Debian Codegraph @

test/cpp/end2end/cfstream_test.cc

raw
1 /*
2 *
3 * Copyright 2019 The gRPC Authors
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #include <algorithm>
20 #include <memory>
21 #include <mutex>
22 #include <random>
23 #include <thread>
24
25 #include <gtest/gtest.h>
26
27 #include <grpc/grpc.h>
28 #include <grpc/support/alloc.h>
29 #include <grpc/support/atm.h>
30 #include <grpc/support/log.h>
31 #include <grpc/support/string_util.h>
32 #include <grpc/support/time.h>
33 #include <grpcpp/channel.h>
34 #include <grpcpp/client_context.h>
35 #include <grpcpp/create_channel.h>
36 #include <grpcpp/health_check_service_interface.h>
37 #include <grpcpp/server.h>
38 #include <grpcpp/server_builder.h>
39
40 #include "src/core/lib/backoff/backoff.h"
41 #include "src/core/lib/gprpp/env.h"
42 #include "src/core/lib/iomgr/port.h"
43 #include "src/proto/grpc/testing/echo.grpc.pb.h"
44 #include "test/core/util/port.h"
45 #include "test/core/util/test_config.h"
46 #include "test/cpp/end2end/test_service_impl.h"
47 #include "test/cpp/util/test_credentials_provider.h"
48
49 #ifdef GRPC_CFSTREAM
50 using grpc::ClientAsyncResponseReader;
51 using grpc::testing::EchoRequest;
52 using grpc::testing::EchoResponse;
53 using grpc::testing::RequestParams;
54 using std::chrono::system_clock;
55
56 namespace grpc {
57 namespace testing {
58 namespace {
59
60 struct TestScenario {
61 TestScenario(const std::string& creds_type, const std::string& content)
62 : credentials_type(creds_type), message_content(content) {}
63 const std::string credentials_type;
64 const std::string message_content;
65 };
66
67 class CFStreamTest : public ::testing::TestWithParam<TestScenario> {
68 protected:
69 CFStreamTest()
70 : server_host_("grpctest"),
71 interface_("lo0"),
72 ipv4_address_("10.0.0.1") {}
73
74 void DNSUp() {
75 std::ostringstream cmd;
76 // Add DNS entry for server_host_ in /etc/hosts
77 cmd << "echo '" << ipv4_address_ << " " << server_host_
78 << " ' | sudo tee -a /etc/hosts";
79 std::system(cmd.str().c_str());
80 }
81
82 void DNSDown() {
83 std::ostringstream cmd;
84 // Remove DNS entry for server_host_ in /etc/hosts
85 cmd << "sudo sed -i '.bak' '/" << server_host_ << "/d' /etc/hosts";
86 std::system(cmd.str().c_str());
87 }
88
89 void InterfaceUp() {
90 std::ostringstream cmd;
91 cmd << "sudo /sbin/ifconfig " << interface_ << " alias " << ipv4_address_;
92 std::system(cmd.str().c_str());
93 }
94
95 void InterfaceDown() {
96 std::ostringstream cmd;
97 cmd << "sudo /sbin/ifconfig " << interface_ << " -alias " << ipv4_address_;
98 std::system(cmd.str().c_str());
99 }
100
101 void NetworkUp() {
102 gpr_log(GPR_DEBUG, "Bringing network up");
103 InterfaceUp();
104 DNSUp();
105 }
106
107 void NetworkDown() {
108 gpr_log(GPR_DEBUG, "Bringing network down");
109 InterfaceDown();
110 DNSDown();
111 }
112
113 void SetUp() override {
114 NetworkUp();
115 grpc_init();
116 StartServer();
117 }
118
119 void TearDown() override {
120 NetworkDown();
121 StopServer();
122 grpc_shutdown();
123 }
124
125 void StartServer() {
126 port_ = grpc_pick_unused_port_or_die();
127 server_.reset(new ServerData(port_, GetParam().credentials_type));
128 server_->Start(server_host_);
129 }
130 void StopServer() { server_->Shutdown(); }
131
132 std::unique_ptr<grpc::testing::EchoTestService::Stub> BuildStub(
133 const std::shared_ptr<Channel>& channel) {
134 return grpc::testing::EchoTestService::NewStub(channel);
135 }
136
137 std::shared_ptr<Channel> BuildChannel() {
138 std::ostringstream server_address;
139 server_address << server_host_ << ":" << port_;
140 ChannelArguments args;
141 auto channel_creds = GetCredentialsProvider()->GetChannelCredentials(
142 GetParam().credentials_type, &args);
143 return CreateCustomChannel(server_address.str(), channel_creds, args);
144 }
145
146 void SendRpc(
147 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
148 bool expect_success = false) {
149 auto response = std::unique_ptr<EchoResponse>(new EchoResponse());
150 EchoRequest request;
151 auto& msg = GetParam().message_content;
152 request.set_message(msg);
153 ClientContext context;
154 Status status = stub->Echo(&context, request, response.get());
155 if (status.ok()) {
156 gpr_log(GPR_DEBUG, "RPC with succeeded");
157 EXPECT_EQ(msg, response->message());
158 } else {
159 gpr_log(GPR_DEBUG, "RPC failed: %s", status.error_message().c_str());
160 }
161 if (expect_success) {
162 EXPECT_TRUE(status.ok());
163 }
164 }
165 void SendAsyncRpc(
166 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
167 RequestParams param = RequestParams()) {
168 EchoRequest request;
169 request.set_message(GetParam().message_content);
170 *request.mutable_param() = std::move(param);
171 AsyncClientCall* call = new AsyncClientCall;
172
173 call->response_reader =
174 stub->PrepareAsyncEcho(&call->context, request, &cq_);
175
176 call->response_reader->StartCall();
177 call->response_reader->Finish(&call->reply, &call->status, (void*)call);
178 }
179
180 void ShutdownCQ() { cq_.Shutdown(); }
181
182 bool CQNext(void** tag, bool* ok) {
183 auto deadline = std::chrono::system_clock::now() + std::chrono::seconds(10);
184 auto ret = cq_.AsyncNext(tag, ok, deadline);
185 if (ret == grpc::CompletionQueue::GOT_EVENT) {
186 return true;
187 } else if (ret == grpc::CompletionQueue::SHUTDOWN) {
188 return false;
189 } else {
190 GPR_ASSERT(ret == grpc::CompletionQueue::TIMEOUT);
191 // This can happen if we hit the Apple CFStream bug which results in the
192 // read stream freezing. We are ignoring hangs and timeouts, but these
193 // tests are still useful as they can catch memory memory corruptions,
194 // crashes and other bugs that don't result in test freeze/timeout.
195 return false;
196 }
197 }
198
199 bool WaitForChannelNotReady(Channel* channel, int timeout_seconds = 5) {
200 const gpr_timespec deadline =
201 grpc_timeout_seconds_to_deadline(timeout_seconds);
202 grpc_connectivity_state state;
203 while ((state = channel->GetState(false /* try_to_connect */)) ==
204 GRPC_CHANNEL_READY) {
205 if (!channel->WaitForStateChange(state, deadline)) return false;
206 }
207 return true;
208 }
209
210 bool WaitForChannelReady(Channel* channel, int timeout_seconds = 10) {
211 const gpr_timespec deadline =
212 grpc_timeout_seconds_to_deadline(timeout_seconds);
213 grpc_connectivity_state state;
214 while ((state = channel->GetState(true /* try_to_connect */)) !=
215 GRPC_CHANNEL_READY) {
216 if (!channel->WaitForStateChange(state, deadline)) return false;
217 }
218 return true;
219 }
220
221 struct AsyncClientCall {
222 EchoResponse reply;
223 ClientContext context;
224 Status status;
225 std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader;
226 };
227
228 private:
229 struct ServerData {
230 int port_;
231 const std::string creds_;
232 std::unique_ptr<Server> server_;
233 TestServiceImpl service_;
234 std::unique_ptr<std::thread> thread_;
235 bool server_ready_ = false;
236
237 ServerData(int port, const std::string& creds)
238 : port_(port), creds_(creds) {}
239
240 void Start(const std::string& server_host) {
241 gpr_log(GPR_INFO, "starting server on port %d", port_);
242 std::mutex mu;
243 std::unique_lock<std::mutex> lock(mu);
244 std::condition_variable cond;
245 thread_.reset(new std::thread(
246 std::bind(&ServerData::Serve, this, server_host, &mu, &cond)));
247 cond.wait(lock, [this] { return server_ready_; });
248 server_ready_ = false;
249 gpr_log(GPR_INFO, "server startup complete");
250 }
251
252 void Serve(const std::string& server_host, std::mutex* mu,
253 std::condition_variable* cond) {
254 std::ostringstream server_address;
255 server_address << server_host << ":" << port_;
256 ServerBuilder builder;
257 auto server_creds =
258 GetCredentialsProvider()->GetServerCredentials(creds_);
259 builder.AddListeningPort(server_address.str(), server_creds);
260 builder.RegisterService(&service_);
261 server_ = builder.BuildAndStart();
262 std::lock_guard<std::mutex> lock(*mu);
263 server_ready_ = true;
264 cond->notify_one();
265 }
266
267 void Shutdown(bool join = true) {
268 server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
269 if (join) thread_->join();
270 }
271 };
272
273 CompletionQueue cq_;
274 const std::string server_host_;
275 const std::string interface_;
276 const std::string ipv4_address_;
277 std::unique_ptr<ServerData> server_;
278 int port_;
279 };
280
281 std::vector<TestScenario> CreateTestScenarios() {
282 std::vector<TestScenario> scenarios;
283 std::vector<std::string> credentials_types;
284 std::vector<std::string> messages;
285
286 credentials_types.push_back(kInsecureCredentialsType);
287 auto sec_list = GetCredentialsProvider()->GetSecureCredentialsTypeList();
288 for (auto sec = sec_list.begin(); sec != sec_list.end(); sec++) {
289 credentials_types.push_back(*sec);
290 }
291
292 messages.push_back("🖖");
293 for (size_t k = 1; k < GRPC_DEFAULT_MAX_RECV_MESSAGE_LENGTH / 1024; k *= 32) {
294 std::string big_msg;
295 for (size_t i = 0; i < k * 1024; ++i) {
296 char c = 'a' + (i % 26);
297 big_msg += c;
298 }
299 messages.push_back(big_msg);
300 }
301 for (auto cred = credentials_types.begin(); cred != credentials_types.end();
302 ++cred) {
303 for (auto msg = messages.begin(); msg != messages.end(); msg++) {
304 scenarios.emplace_back(*cred, *msg);
305 }
306 }
307
308 return scenarios;
309 }
310
311 INSTANTIATE_TEST_SUITE_P(CFStreamTest, CFStreamTest,
312 ::testing::ValuesIn(CreateTestScenarios()));
313
314 // gRPC should automatically detech network flaps (without enabling keepalives)
315 // when CFStream is enabled
316 TEST_P(CFStreamTest, NetworkTransition) {
317 auto channel = BuildChannel();
318 auto stub = BuildStub(channel);
319 // Channel should be in READY state after we send an RPC
320 SendRpc(stub, /*expect_success=*/true);
321 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
322
323 std::atomic_bool shutdown{false};
324 std::thread sender = std::thread([this, &stub, &shutdown]() {
325 while (true) {
326 if (shutdown.load()) {
327 return;
328 }
329 SendRpc(stub);
330 std::this_thread::sleep_for(std::chrono::milliseconds(1000));
331 }
332 });
333
334 // bring down network
335 NetworkDown();
336
337 // network going down should be detected by cfstream
338 EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
339
340 // bring network interface back up
341 std::this_thread::sleep_for(std::chrono::milliseconds(1000));
342 NetworkUp();
343
344 // channel should reconnect
345 EXPECT_TRUE(WaitForChannelReady(channel.get()));
346 EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
347 shutdown.store(true);
348 sender.join();
349 }
350
351 // Network flaps while RPCs are in flight
352 TEST_P(CFStreamTest, NetworkFlapRpcsInFlight) {
353 auto channel = BuildChannel();
354 auto stub = BuildStub(channel);
355 std::atomic_int rpcs_sent{0};
356
357 // Channel should be in READY state after we send some RPCs
358 for (int i = 0; i < 10; ++i) {
359 RequestParams param;
360 param.set_skip_cancelled_check(true);
361 SendAsyncRpc(stub, param);
362 ++rpcs_sent;
363 }
364 EXPECT_TRUE(WaitForChannelReady(channel.get()));
365
366 // Bring down the network
367 NetworkDown();
368
369 std::thread thd = std::thread([this, &rpcs_sent]() {
370 void* got_tag;
371 bool ok = false;
372 bool network_down = true;
373 int total_completions = 0;
374
375 while (CQNext(&got_tag, &ok)) {
376 ++total_completions;
377 GPR_ASSERT(ok);
378 AsyncClientCall* call = static_cast<AsyncClientCall*>(got_tag);
379 if (!call->status.ok()) {
380 gpr_log(GPR_DEBUG, "RPC failed with error: %s",
381 call->status.error_message().c_str());
382 // Bring network up when RPCs start failing
383 if (network_down) {
384 NetworkUp();
385 network_down = false;
386 }
387 } else {
388 gpr_log(GPR_DEBUG, "RPC succeeded");
389 }
390 delete call;
391 }
392 // Remove line below and uncomment the following line after Apple CFStream
393 // bug has been fixed.
394 (void)rpcs_sent;
395 // EXPECT_EQ(total_completions, rpcs_sent);
396 });
397
398 for (int i = 0; i < 100; ++i) {
399 RequestParams param;
400 param.set_skip_cancelled_check(true);
401 SendAsyncRpc(stub, param);
402 std::this_thread::sleep_for(std::chrono::milliseconds(10));
403 ++rpcs_sent;
404 }
405
406 ShutdownCQ();
407
408 thd.join();
409 }
410
411 // Send a bunch of RPCs, some of which are expected to fail.
412 // We should get back a response for all RPCs
413 TEST_P(CFStreamTest, ConcurrentRpc) {
414 auto channel = BuildChannel();
415 auto stub = BuildStub(channel);
416 std::atomic_int rpcs_sent{0};
417 std::thread thd = std::thread([this, &rpcs_sent]() {
418 void* got_tag;
419 bool ok = false;
420 int total_completions = 0;
421
422 while (CQNext(&got_tag, &ok)) {
423 ++total_completions;
424 GPR_ASSERT(ok);
425 AsyncClientCall* call = static_cast<AsyncClientCall*>(got_tag);
426 if (!call->status.ok()) {
427 gpr_log(GPR_DEBUG, "RPC failed with error: %s",
428 call->status.error_message().c_str());
429 // Bring network up when RPCs start failing
430 } else {
431 gpr_log(GPR_DEBUG, "RPC succeeded");
432 }
433 delete call;
434 }
435 // Remove line below and uncomment the following line after Apple CFStream
436 // bug has been fixed.
437 (void)rpcs_sent;
438 // EXPECT_EQ(total_completions, rpcs_sent);
439 });
440
441 for (int i = 0; i < 10; ++i) {
442 if (i % 3 == 0) {
443 RequestParams param;
444 ErrorStatus* error = param.mutable_expected_error();
445 error->set_code(StatusCode::INTERNAL);
446 error->set_error_message("internal error");
447 SendAsyncRpc(stub, param);
448 } else if (i % 5 == 0) {
449 RequestParams param;
450 param.set_echo_metadata(true);
451 DebugInfo* info = param.mutable_debug_info();
452 info->add_stack_entries("stack_entry1");
453 info->add_stack_entries("stack_entry2");
454 info->set_detail("detailed debug info");
455 SendAsyncRpc(stub, param);
456 } else {
457 SendAsyncRpc(stub);
458 }
459 ++rpcs_sent;
460 }
461
462 ShutdownCQ();
463
464 thd.join();
465 }
466
467 } // namespace
468 } // namespace testing
469 } // namespace grpc
470 #endif // GRPC_CFSTREAM
471
472 int main(int argc, char** argv) {
473 ::testing::InitGoogleTest(&argc, argv);
474 grpc::testing::TestEnvironment env(&argc, argv);
475 grpc_core::SetEnv("grpc_cfstream", "1");
476 const auto result = RUN_ALL_TESTS();
477 return result;
478 }