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
|
/**
* Copyright (C) 2021-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.
*/
#pragma once
#include <memory>
#include "mongo/db/process_health/fault_manager.h"
#include "mongo/db/process_health/health_observer_mock.h"
#include "mongo/db/process_health/health_observer_registration.h"
#include "mongo/executor/network_interface_factory.h"
#include "mongo/executor/thread_pool_task_executor_test_fixture.h"
#include "mongo/idl/server_parameter_test_util.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/concurrency/thread_pool.h"
#include "mongo/util/tick_source_mock.h"
namespace mongo {
using executor::TaskExecutor;
using executor::ThreadPoolExecutorTest;
namespace process_health {
namespace test {
static inline std::unique_ptr<FaultManagerConfig> getConfigWithDisabledPeriodicChecks() {
auto config = std::make_unique<FaultManagerConfig>();
config->disablePeriodicChecksForTests();
return config;
}
/**
* Test wrapper class for FaultManager that has access to protected methods
* for testing.
*/
class FaultManagerTestImpl : public FaultManager {
public:
FaultManagerTestImpl(ServiceContext* svcCtx,
std::shared_ptr<executor::TaskExecutor> taskExecutor,
std::unique_ptr<FaultManagerConfig> config)
: FaultManager(svcCtx,
taskExecutor,
[&config]() -> std::unique_ptr<FaultManagerConfig> {
if (config)
return std::move(config);
else
return getConfigWithDisabledPeriodicChecks();
}(),
[](std::string cause) {
// In tests, do not crash.
LOGV2(5936606,
"Fault manager progress monitor triggered the termination",
"cause"_attr = cause);
}) {}
void healthCheckTest(HealthObserver* observer, CancellationToken token) {
healthCheck(observer, token);
}
void schedulePeriodicHealthCheckThreadTest() {
schedulePeriodicHealthCheckThread();
}
std::vector<HealthObserver*> getHealthObserversTest() {
return getHealthObservers();
}
FaultFacetsContainerPtr getOrCreateFaultFacetsContainerTest() {
return getOrCreateFaultFacetsContainer();
}
FaultInternal& getFault() {
FaultFacetsContainerPtr fault = getFaultFacetsContainer();
invariant(fault);
return *(static_cast<FaultInternal*>(fault.get()));
}
void progressMonitorCheckTest(std::function<void(std::string cause)> crashCb) {
progressMonitorCheckForTests(crashCb);
}
FaultManagerConfig getConfigTest() {
return getConfig();
}
FaultState acceptTest(const HealthCheckStatus& message) {
return accept(message);
}
};
/**
* Test suite for fault manager.
*/
class FaultManagerTest : public unittest::Test {
public:
void setUp() override {
HealthObserverRegistration::resetObserverFactoriesForTest();
createServiceContextIfNeeded();
bumpUpLogging();
resetManager();
}
void createServiceContextIfNeeded() {
if (!_svcCtx) {
// Reset only once because the Ldap connection reaper is running asynchronously
// and is using the simulated clock, which should not go out of scope.
_svcCtx = ServiceContext::make();
_svcCtx->setFastClockSource(std::make_unique<ClockSourceMock>());
_svcCtx->setPreciseClockSource(std::make_unique<ClockSourceMock>());
_svcCtx->setTickSource(std::make_unique<TickSourceMock<Milliseconds>>());
advanceTime(Seconds(100));
}
}
void bumpUpLogging() {
logv2::LogManager::global().getGlobalSettings().setMinimumLoggedSeverity(
mongo::logv2::LogComponent::kProcessHealth, logv2::LogSeverity::Debug(3));
logv2::LogManager::global().getGlobalSettings().setMinimumLoggedSeverity(
mongo::logv2::LogComponent::kAccessControl, logv2::LogSeverity::Debug(3));
}
void tearDown() override {
LOGV2(6007905, "Clean up test resources");
// Shutdown the executor before the context is deleted.
resetManager();
}
void constructTaskExecutor() {
if (_executor) {
_executor->shutdown();
_executor->join();
}
auto network = std::shared_ptr<executor::NetworkInterface>(
executor::makeNetworkInterface("FaultManagerTest").release());
ThreadPool::Options options;
auto pool = std::make_unique<ThreadPool>(options);
_executor =
std::make_unique<executor::ThreadPoolTaskExecutor>(std::move(pool), std::move(network));
}
void resetManager(std::unique_ptr<FaultManagerConfig> config = nullptr) {
constructTaskExecutor();
FaultManager::set(
_svcCtx.get(),
std::make_unique<FaultManagerTestImpl>(_svcCtx.get(), _executor, std::move(config)));
}
void registerMockHealthObserver(FaultFacetType mockType,
std::function<double()> getSeverityCallback) {
HealthObserverRegistration::registerObserverFactory(
[mockType, getSeverityCallback](ServiceContext* svcCtx) {
return std::make_unique<HealthObserverMock>(mockType, svcCtx, getSeverityCallback);
});
}
template <typename Observer>
void registerHealthObserver() {
HealthObserverRegistration::registerObserverFactory(
[](ServiceContext* svcCtx) { return std::make_unique<Observer>(svcCtx); });
}
FaultManagerTestImpl& manager() {
return *static_cast<FaultManagerTestImpl*>(FaultManager::get(_svcCtx.get()));
}
ClockSourceMock& clockSource() {
return *static_cast<ClockSourceMock*>(_svcCtx->getFastClockSource());
}
ServiceContext* svcCtx() const {
return _svcCtx.get();
}
TickSourceMock<Milliseconds>& tickSource() {
return *static_cast<TickSourceMock<Milliseconds>*>(_svcCtx->getTickSource());
}
template <typename Observer>
Observer& observer(FaultFacetType type) {
std::vector<HealthObserver*> observers = manager().getHealthObserversTest();
ASSERT_TRUE(!observers.empty());
auto it = std::find_if(observers.begin(), observers.end(), [type](const HealthObserver* o) {
return o->getType() == type;
});
ASSERT_TRUE(it != observers.end());
return *static_cast<Observer*>(*it);
}
HealthObserverBase::PeriodicHealthCheckContext checkContext() {
HealthObserverBase::PeriodicHealthCheckContext ctx{CancellationToken::uncancelable(),
_executor};
return ctx;
}
template <typename Duration>
void advanceTime(Duration d) {
clockSource().advance(d);
static_cast<ClockSourceMock*>(_svcCtx->getPreciseClockSource())->advance(d);
tickSource().advance(d);
}
static inline const Seconds kWaitTimeout{30};
static inline const Milliseconds kSleepTime{1};
void assertSoon(std::function<bool()> predicate, Milliseconds timeout = kWaitTimeout) {
Timer t;
while (t.elapsed() < timeout) {
if (predicate())
return;
sleepFor(kSleepTime);
}
invariant(false);
}
static inline const Milliseconds kCheckTimeIncrement{100};
void assertSoonWithHealthCheck(std::function<bool()> predicate,
Milliseconds timeout = kWaitTimeout) {
auto predicate2 = [=]() {
if (predicate())
return true;
else {
advanceTime(kCheckTimeIncrement);
manager().schedulePeriodicHealthCheckThreadTest();
return false;
}
};
assertSoon(predicate2, timeout);
}
bool hasFault() {
return static_cast<bool>(manager().currentFault());
}
void waitForFaultBeingResolved() {
assertSoon([this]() { return !hasFault(); });
}
void waitForFaultBeingCreated() {
assertSoon([this]() { return hasFault(); });
}
void waitForTransitionIntoState(FaultState state) {
assertSoonWithHealthCheck([=]() { return manager().getFaultState() == state; });
}
private:
ServiceContext::UniqueServiceContext _svcCtx;
std::shared_ptr<executor::ThreadPoolTaskExecutor> _executor;
};
} // namespace test
} // namespace process_health
} // namespace mongo
|