-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathserver.cc
More file actions
310 lines (276 loc) · 13.7 KB
/
server.cc
File metadata and controls
310 lines (276 loc) · 13.7 KB
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
#include "test/integration/server.h"
#include <memory>
#include <string>
#include "envoy/http/header_map.h"
#include "source/common/common/random_generator.h"
#include "source/common/common/thread.h"
#include "source/common/local_info/local_info_impl.h"
#include "source/common/network/utility.h"
#include "source/common/stats/thread_local_store.h"
#include "source/common/thread_local/thread_local_impl.h"
#include "source/server/hot_restart_nop_impl.h"
#include "source/server/instance_impl.h"
#include "source/server/options_impl_base.h"
#include "source/server/process_context_impl.h"
#include "test/integration/utility.h"
#include "test/mocks/common.h"
#include "test/test_common/environment.h"
#include "absl/strings/str_replace.h"
#include "gtest/gtest.h"
namespace Envoy {
namespace Server {
OptionsImplBase
createTestOptionsImpl(const std::string& config_path, const std::string& config_yaml,
Network::Address::IpVersion ip_version,
FieldValidationConfig validation_config, uint32_t concurrency,
std::chrono::seconds drain_time, Server::DrainStrategy drain_strategy,
bool use_bootstrap_node_metadata,
std::unique_ptr<envoy::config::bootstrap::v3::Bootstrap>&& config_proto) {
// Empty string values mean the Bootstrap node metadata won't be overridden.
const std::string service_cluster = use_bootstrap_node_metadata ? "" : "cluster_name";
const std::string service_node = use_bootstrap_node_metadata ? "" : "node_name";
const std::string service_zone = use_bootstrap_node_metadata ? "" : "zone_name";
OptionsImplBase test_options;
test_options.setServiceClusterName(service_cluster);
test_options.setServiceNodeName(service_node);
test_options.setServiceZone(service_zone);
test_options.setLogLevel(spdlog::level::info);
test_options.setConfigPath(config_path);
test_options.setConfigYaml(config_yaml);
test_options.setLocalAddressIpVersion(ip_version);
test_options.setFileFlushIntervalMsec(std::chrono::milliseconds(50));
test_options.setFileFlushMinSizeKB(128);
test_options.setDrainTime(drain_time);
test_options.setParentShutdownTime(std::chrono::seconds(2));
test_options.setDrainStrategy(drain_strategy);
test_options.setAllowUnknownFields(validation_config.allow_unknown_static_fields);
test_options.setRejectUnknownFieldsDynamic(validation_config.reject_unknown_dynamic_fields);
test_options.setIgnoreUnknownFieldsDynamic(validation_config.ignore_unknown_dynamic_fields);
test_options.setSkipDeprecatedLog(false);
test_options.setConcurrency(concurrency);
test_options.setHotRestartDisabled(true);
if (config_proto) {
test_options.setConfigProto(std::move(config_proto));
}
return test_options;
}
} // namespace Server
IntegrationTestServerPtr IntegrationTestServer::create(
const std::string& config_path, const Network::Address::IpVersion version,
std::function<void(IntegrationTestServer&)> server_ready_function,
std::function<void()> on_server_init_function, absl::optional<uint64_t> deterministic_value,
Event::TestTimeSystem& time_system, Api::Api& api, bool defer_listener_finalization,
ProcessObjectOptRef process_object, Server::FieldValidationConfig validation_config,
uint32_t concurrency, std::chrono::seconds drain_time, Server::DrainStrategy drain_strategy,
Buffer::WatermarkFactorySharedPtr watermark_factory, bool use_real_stats,
bool use_bootstrap_node_metadata,
std::unique_ptr<envoy::config::bootstrap::v3::Bootstrap>&& config_proto,
bool use_admin_server) {
IntegrationTestServerPtr server{std::make_unique<IntegrationTestServerImpl>(
time_system, api, config_path, use_real_stats, std::move(config_proto))};
if (server_ready_function != nullptr) {
server->setOnServerReadyCb(server_ready_function);
}
server->start(version, on_server_init_function, deterministic_value, defer_listener_finalization,
process_object, validation_config, concurrency, drain_time, drain_strategy,
watermark_factory, use_bootstrap_node_metadata, use_admin_server);
return server;
}
void IntegrationTestServer::waitUntilListenersReady() {
Thread::LockGuard guard(listeners_mutex_);
while (pending_listeners_ != 0) {
// If your test is hanging forever here, you may need to create your listener manually,
// after BaseIntegrationTest::initialize() is done. See cds_integration_test.cc for an example.
listeners_cv_.wait(listeners_mutex_); // Safe since CondVar::wait won't throw.
}
ENVOY_LOG(info, "listener wait complete");
}
void IntegrationTestServer::setDynamicContextParam(absl::string_view resource_type_url,
absl::string_view key, absl::string_view value) {
server().dispatcher().post([this, resource_type_url, key, value]() {
ASSERT_TRUE(server()
.localInfo()
.contextProvider()
.setDynamicContextParam(resource_type_url, key, value)
.ok());
});
}
void IntegrationTestServer::unsetDynamicContextParam(absl::string_view resource_type_url,
absl::string_view key) {
server().dispatcher().post([this, resource_type_url, key]() {
ASSERT_TRUE(server()
.localInfo()
.contextProvider()
.unsetDynamicContextParam(resource_type_url, key)
.ok());
});
}
void IntegrationTestServer::setAdsConfigSource(
const envoy::config::core::v3::ApiConfigSource& config_source) {
server().dispatcher().post([this, config_source]() {
absl::Status status = server().xdsManager().setAdsConfigSource(config_source);
});
}
void IntegrationTestServer::start(
const Network::Address::IpVersion version, std::function<void()> on_server_init_function,
absl::optional<uint64_t> deterministic_value, bool defer_listener_finalization,
ProcessObjectOptRef process_object, Server::FieldValidationConfig validator_config,
uint32_t concurrency, std::chrono::seconds drain_time, Server::DrainStrategy drain_strategy,
Buffer::WatermarkFactorySharedPtr watermark_factory, bool use_bootstrap_node_metadata,
bool use_admin_server) {
ENVOY_LOG(info, "starting integration test server");
ASSERT(!thread_);
thread_ = api_.threadFactory().createThread(
[version, deterministic_value, process_object, validator_config, concurrency, drain_time,
drain_strategy, watermark_factory, use_bootstrap_node_metadata, use_admin_server,
this]() -> void {
threadRoutine(version, deterministic_value, process_object, validator_config, concurrency,
drain_time, drain_strategy, watermark_factory, use_bootstrap_node_metadata,
use_admin_server);
});
// If any steps need to be done prior to workers starting, do them now. E.g., xDS pre-init.
// Note that there is no synchronization guaranteeing this happens either
// before workers starting or after server start. Any needed synchronization must occur in the
// routines. These steps are executed at this point in the code to allow server initialization
// to be dependent on them (e.g. control plane peers).
if (on_server_init_function != nullptr) {
on_server_init_function();
}
// Wait for the server to be created and the number of initial listeners to wait for to be set.
server_set_.waitReady();
if (!defer_listener_finalization) {
// Now wait for the initial listeners (if any) to actually be listening on the worker.
// At this point the server is up and ready for testing.
waitUntilListenersReady();
}
// If we are tapping, spin up tcpdump.
const auto tap_path = TestEnvironment::getOptionalEnvVar("TAP_PATH");
if (tap_path) {
std::vector<uint32_t> ports;
for (auto listener : server().listenerManager().listeners()) {
const auto listen_addr = listener.get().listenSocketFactories()[0]->localAddress();
if (listen_addr->type() == Network::Address::Type::Ip) {
ports.push_back(listen_addr->ip()->port());
}
}
// TODO(htuch): Support a different loopback interface as needed.
const ::testing::TestInfo* const test_info =
::testing::UnitTest::GetInstance()->current_test_info();
const std::string test_id =
std::string(test_info->name()) + "_" + std::string(test_info->test_case_name());
const std::string pcap_path =
tap_path.value() + "_" + absl::StrReplaceAll(test_id, {{"/", "_"}}) + "_server.pcap";
tcp_dump_ = std::make_unique<TcpDump>(pcap_path, "lo", ports);
}
}
IntegrationTestServer::~IntegrationTestServer() {
// Derived class must have shutdown server.
thread_->join();
}
void IntegrationTestServer::onWorkerListenerAdded() {
if (on_worker_listener_added_cb_) {
on_worker_listener_added_cb_();
}
Thread::LockGuard guard(listeners_mutex_);
if (pending_listeners_ > 0) {
pending_listeners_--;
listeners_cv_.notifyOne();
}
}
void IntegrationTestServer::onWorkerListenerRemoved() {
if (on_worker_listener_removed_cb_) {
on_worker_listener_removed_cb_();
}
}
void IntegrationTestServer::serverReady() {
pending_listeners_ = server().listenerManager().listeners().size();
if (on_server_ready_cb_ != nullptr) {
on_server_ready_cb_(*this);
}
server_set_.setReady();
}
void IntegrationTestServer::threadRoutine(const Network::Address::IpVersion version,
absl::optional<uint64_t> deterministic_value,
ProcessObjectOptRef process_object,
Server::FieldValidationConfig validation_config,
uint32_t concurrency, std::chrono::seconds drain_time,
Server::DrainStrategy drain_strategy,
Buffer::WatermarkFactorySharedPtr watermark_factory,
bool use_bootstrap_node_metadata, bool use_admin_server) {
OptionsImplBase options(Server::createTestOptionsImpl(
config_path_, "", version, validation_config, concurrency, drain_time, drain_strategy,
use_bootstrap_node_metadata, std::move(config_proto_)));
Thread::MutexBasicLockable lock;
Random::RandomGeneratorPtr random_generator;
if (deterministic_value.has_value()) {
random_generator = std::make_unique<testing::NiceMock<Random::MockRandomGenerator>>(
deterministic_value.value());
} else {
random_generator = std::make_unique<Random::RandomGeneratorImpl>();
}
createAndRunEnvoyServer(options, time_system_, Network::Utility::getLocalAddress(version), *this,
lock, *this, std::move(random_generator), process_object,
watermark_factory, use_admin_server);
}
IntegrationTestServerImpl::IntegrationTestServerImpl(
Event::TestTimeSystem& time_system, Api::Api& api, const std::string& config_path,
bool use_real_stats, std::unique_ptr<envoy::config::bootstrap::v3::Bootstrap>&& config_proto)
: IntegrationTestServer(time_system, api, config_path, std::move(config_proto)) {
stats_allocator_ = (use_real_stats ? std::make_unique<Stats::Allocator>(symbol_table_)
: std::make_unique<Stats::NotifyingAllocator>(symbol_table_));
}
void IntegrationTestServerImpl::createAndRunEnvoyServer(
OptionsImplBase& options, Event::TimeSystem& time_system,
Network::Address::InstanceConstSharedPtr local_address, ListenerHooks& hooks,
Thread::BasicLockable& access_log_lock, Server::ComponentFactory& component_factory,
Random::RandomGeneratorPtr&& random_generator, ProcessObjectOptRef process_object,
Buffer::WatermarkFactorySharedPtr watermark_factory, bool use_admin_server) {
{
Init::ManagerImpl init_manager{"Server"};
Server::HotRestartNopImpl restarter;
ThreadLocal::InstanceImpl tls;
Stats::ThreadLocalStoreImpl stat_store(*stats_allocator_);
std::unique_ptr<ProcessContext> process_context;
if (process_object.has_value()) {
process_context = std::make_unique<ProcessContextImpl>(process_object->get());
}
Server::InstanceImpl server(init_manager, options, time_system, hooks, restarter, stat_store,
access_log_lock, std::move(random_generator), tls,
Thread::threadFactoryForTest(), Filesystem::fileSystemForTest(),
std::move(process_context), watermark_factory);
server.initialize(local_address, component_factory);
// This is technically thread unsafe (assigning to a shared_ptr accessed
// across threads), but because we synchronize below through serverReady(), the only
// consumer on the main test thread in ~IntegrationTestServerImpl will not race.
if (use_admin_server && server.admin()) {
admin_address_ = server.admin()->socket().connectionInfoProvider().localAddress();
}
server_ = &server;
stat_store_ = &stat_store;
serverReady();
server.run();
}
server_gone_.Notify();
}
IntegrationTestServerImpl::~IntegrationTestServerImpl() {
ENVOY_LOG(info, "stopping integration test server");
if (useAdminInterfaceToQuit()) {
Network::Address::InstanceConstSharedPtr admin_address(admin_address_);
if (admin_address != nullptr) {
BufferingStreamDecoderPtr response = IntegrationUtil::makeSingleRequest(
admin_address, "POST", "/quitquitquit", "", Http::CodecType::HTTP1);
EXPECT_TRUE(response->complete());
EXPECT_EQ("200", response->headers().getStatusValue());
server_gone_.WaitForNotification();
}
} else {
if (server_) {
server_->dispatcher().post([this]() { server_->shutdown(); });
server_gone_.WaitForNotification();
}
}
server_ = nullptr;
admin_address_ = nullptr;
stat_store_ = nullptr;
}
} // namespace Envoy