Debian Codegraph @

test/cpp/end2end/thread_stress_test.cc

raw
1 /*
2 *
3 * Copyright 2015 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 <cinttypes>
20 #include <mutex>
21 #include <thread>
22
23 #include <gtest/gtest.h>
24
25 #include <grpc/grpc.h>
26 #include <grpc/support/time.h>
27 #include <grpcpp/channel.h>
28 #include <grpcpp/client_context.h>
29 #include <grpcpp/create_channel.h>
30 #include <grpcpp/impl/codegen/sync.h>
31 #include <grpcpp/resource_quota.h>
32 #include <grpcpp/server.h>
33 #include <grpcpp/server_builder.h>
34 #include <grpcpp/server_context.h>
35
36 #include "src/core/lib/gprpp/env.h"
37 #include "src/core/lib/surface/api_trace.h"
38 #include "src/proto/grpc/testing/duplicate/echo_duplicate.grpc.pb.h"
39 #include "src/proto/grpc/testing/echo.grpc.pb.h"
40 #include "test/core/util/port.h"
41 #include "test/core/util/test_config.h"
42
43 #if defined(__APPLE__)
44 // Use less # of threads on Mac because its test machines are less powerful
45 // to finish the test on time. (context: b/185231823)
46 const int kNumThreads = 100; // Number of threads
47 #else
48 const int kNumThreads = 300; // Number of threads
49 #endif
50 const int kNumAsyncSendThreads = 2;
51 const int kNumAsyncReceiveThreads = 50;
52 const int kNumAsyncServerThreads = 50;
53 const int kNumRpcs = 1000; // Number of RPCs per thread
54
55 namespace grpc {
56 namespace testing {
57
58 class TestServiceImpl : public grpc::testing::EchoTestService::Service {
59 public:
60 TestServiceImpl() {}
61
62 Status Echo(ServerContext* /*context*/, const EchoRequest* request,
63 EchoResponse* response) override {
64 response->set_message(request->message());
65 return Status::OK;
66 }
67 };
68
69 template <class Service>
70 class CommonStressTest {
71 public:
72 CommonStressTest() : kMaxMessageSize_(8192) {
73 #if TARGET_OS_IPHONE
74 // Workaround Apple CFStream bug
75 grpc_core::SetEnv("grpc_cfstream", "0");
76 #endif
77 }
78 virtual ~CommonStressTest() {}
79 virtual void SetUp() = 0;
80 virtual void TearDown() = 0;
81 virtual void ResetStub() = 0;
82 virtual bool AllowExhaustion() = 0;
83 grpc::testing::EchoTestService::Stub* GetStub() { return stub_.get(); }
84
85 protected:
86 std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
87 std::unique_ptr<Server> server_;
88
89 virtual void SetUpStart(ServerBuilder* builder, Service* service) = 0;
90 void SetUpStartCommon(ServerBuilder* builder, Service* service) {
91 builder->RegisterService(service);
92 builder->SetMaxMessageSize(
93 kMaxMessageSize_); // For testing max message size.
94 }
95 void SetUpEnd(ServerBuilder* builder) { server_ = builder->BuildAndStart(); }
96 void TearDownStart() { server_->Shutdown(); }
97 void TearDownEnd() {}
98
99 private:
100 const int kMaxMessageSize_;
101 };
102
103 template <class Service>
104 class CommonStressTestInsecure : public CommonStressTest<Service> {
105 public:
106 void ResetStub() override {
107 std::shared_ptr<Channel> channel = grpc::CreateChannel(
108 server_address_.str(), InsecureChannelCredentials());
109 this->stub_ = grpc::testing::EchoTestService::NewStub(channel);
110 }
111 bool AllowExhaustion() override { return false; }
112
113 protected:
114 void SetUpStart(ServerBuilder* builder, Service* service) override {
115 int port = grpc_pick_unused_port_or_die();
116 this->server_address_ << "localhost:" << port;
117 // Setup server
118 builder->AddListeningPort(server_address_.str(),
119 InsecureServerCredentials());
120 this->SetUpStartCommon(builder, service);
121 }
122
123 private:
124 std::ostringstream server_address_;
125 };
126
127 template <class Service, bool allow_resource_exhaustion>
128 class CommonStressTestInproc : public CommonStressTest<Service> {
129 public:
130 void ResetStub() override {
131 ChannelArguments args;
132 std::shared_ptr<Channel> channel = this->server_->InProcessChannel(args);
133 this->stub_ = grpc::testing::EchoTestService::NewStub(channel);
134 }
135 bool AllowExhaustion() override { return allow_resource_exhaustion; }
136
137 protected:
138 void SetUpStart(ServerBuilder* builder, Service* service) override {
139 this->SetUpStartCommon(builder, service);
140 }
141 };
142
143 template <class BaseClass>
144 class CommonStressTestSyncServer : public BaseClass {
145 public:
146 void SetUp() override {
147 ServerBuilder builder;
148 this->SetUpStart(&builder, &service_);
149 this->SetUpEnd(&builder);
150 }
151 void TearDown() override {
152 this->TearDownStart();
153 this->TearDownEnd();
154 }
155
156 private:
157 TestServiceImpl service_;
158 };
159
160 template <class BaseClass>
161 class CommonStressTestSyncServerLowThreadCount : public BaseClass {
162 public:
163 void SetUp() override {
164 ServerBuilder builder;
165 ResourceQuota quota;
166 this->SetUpStart(&builder, &service_);
167 quota.SetMaxThreads(4);
168 builder.SetResourceQuota(quota);
169 this->SetUpEnd(&builder);
170 }
171 void TearDown() override {
172 this->TearDownStart();
173 this->TearDownEnd();
174 }
175
176 private:
177 TestServiceImpl service_;
178 };
179
180 template <class BaseClass>
181 class CommonStressTestAsyncServer : public BaseClass {
182 public:
183 CommonStressTestAsyncServer() : contexts_(kNumAsyncServerThreads * 100) {}
184 void SetUp() override {
185 shutting_down_ = false;
186 ServerBuilder builder;
187 this->SetUpStart(&builder, &service_);
188 cq_ = builder.AddCompletionQueue();
189 this->SetUpEnd(&builder);
190 for (int i = 0; i < kNumAsyncServerThreads * 100; i++) {
191 RefreshContext(i);
192 }
193 for (int i = 0; i < kNumAsyncServerThreads; i++) {
194 server_threads_.emplace_back(&CommonStressTestAsyncServer::ProcessRpcs,
195 this);
196 }
197 }
198 void TearDown() override {
199 {
200 grpc::internal::MutexLock l(&mu_);
201 this->TearDownStart();
202 shutting_down_ = true;
203 cq_->Shutdown();
204 }
205
206 for (int i = 0; i < kNumAsyncServerThreads; i++) {
207 server_threads_[i].join();
208 }
209
210 void* ignored_tag;
211 bool ignored_ok;
212 while (cq_->Next(&ignored_tag, &ignored_ok)) {
213 }
214 this->TearDownEnd();
215 }
216
217 private:
218 void ProcessRpcs() {
219 void* tag;
220 bool ok;
221 while (cq_->Next(&tag, &ok)) {
222 if (ok) {
223 int i = static_cast<int>(reinterpret_cast<intptr_t>(tag));
224 switch (contexts_[i].state) {
225 case Context::READY: {
226 contexts_[i].state = Context::DONE;
227 EchoResponse send_response;
228 send_response.set_message(contexts_[i].recv_request.message());
229 contexts_[i].response_writer->Finish(send_response, Status::OK,
230 tag);
231 break;
232 }
233 case Context::DONE:
234 RefreshContext(i);
235 break;
236 }
237 }
238 }
239 }
240 void RefreshContext(int i) {
241 grpc::internal::MutexLock l(&mu_);
242 if (!shutting_down_) {
243 contexts_[i].state = Context::READY;
244 contexts_[i].srv_ctx.reset(new ServerContext);
245 contexts_[i].response_writer.reset(
246 new grpc::ServerAsyncResponseWriter<EchoResponse>(
247 contexts_[i].srv_ctx.get()));
248 service_.RequestEcho(contexts_[i].srv_ctx.get(),
249 &contexts_[i].recv_request,
250 contexts_[i].response_writer.get(), cq_.get(),
251 cq_.get(), reinterpret_cast<void*>(i));
252 }
253 }
254 struct Context {
255 std::unique_ptr<ServerContext> srv_ctx;
256 std::unique_ptr<grpc::ServerAsyncResponseWriter<EchoResponse>>
257 response_writer;
258 EchoRequest recv_request;
259 enum { READY, DONE } state;
260 };
261 std::vector<Context> contexts_;
262 grpc::testing::EchoTestService::AsyncService service_;
263 std::unique_ptr<ServerCompletionQueue> cq_;
264 bool shutting_down_;
265 grpc::internal::Mutex mu_;
266 std::vector<std::thread> server_threads_;
267 };
268
269 template <class Common>
270 class End2endTest : public ::testing::Test {
271 protected:
272 End2endTest() {}
273 void SetUp() override { common_.SetUp(); }
274 void TearDown() override { common_.TearDown(); }
275 void ResetStub() { common_.ResetStub(); }
276
277 Common common_;
278 };
279
280 static void SendRpc(grpc::testing::EchoTestService::Stub* stub, int num_rpcs,
281 bool allow_exhaustion, gpr_atm* errors) {
282 EchoRequest request;
283 EchoResponse response;
284 request.set_message("Hello");
285
286 for (int i = 0; i < num_rpcs; ++i) {
287 ClientContext context;
288 Status s = stub->Echo(&context, request, &response);
289 EXPECT_TRUE(s.ok() || (allow_exhaustion &&
290 s.error_code() == StatusCode::RESOURCE_EXHAUSTED));
291 if (!s.ok()) {
292 if (!(allow_exhaustion &&
293 s.error_code() == StatusCode::RESOURCE_EXHAUSTED)) {
294 gpr_log(GPR_ERROR, "RPC error: %d: %s", s.error_code(),
295 s.error_message().c_str());
296 }
297 gpr_atm_no_barrier_fetch_add(errors, static_cast<gpr_atm>(1));
298 } else {
299 EXPECT_EQ(response.message(), request.message());
300 }
301 }
302 }
303
304 typedef ::testing::Types<
305 CommonStressTestSyncServer<CommonStressTestInsecure<TestServiceImpl>>,
306 CommonStressTestSyncServer<CommonStressTestInproc<TestServiceImpl, false>>,
307 CommonStressTestSyncServerLowThreadCount<
308 CommonStressTestInproc<TestServiceImpl, true>>,
309 CommonStressTestAsyncServer<
310 CommonStressTestInsecure<grpc::testing::EchoTestService::AsyncService>>,
311 CommonStressTestAsyncServer<CommonStressTestInproc<
312 grpc::testing::EchoTestService::AsyncService, false>>>
313 CommonTypes;
314 TYPED_TEST_SUITE(End2endTest, CommonTypes);
315 TYPED_TEST(End2endTest, ThreadStress) {
316 this->common_.ResetStub();
317 std::vector<std::thread> threads;
318 gpr_atm errors;
319 gpr_atm_rel_store(&errors, static_cast<gpr_atm>(0));
320 int num_threads = kNumThreads / grpc_test_slowdown_factor();
321 // The number of threads should be > 10 to be able to catch errors
322 ASSERT_GT(num_threads, 10);
323 threads.reserve(num_threads);
324 for (int i = 0; i < num_threads; ++i) {
325 threads.emplace_back(SendRpc, this->common_.GetStub(), kNumRpcs,
326 this->common_.AllowExhaustion(), &errors);
327 }
328 for (int i = 0; i < num_threads; ++i) {
329 threads[i].join();
330 }
331 uint64_t error_cnt = static_cast<uint64_t>(gpr_atm_no_barrier_load(&errors));
332 if (error_cnt != 0) {
333 gpr_log(GPR_INFO, "RPC error count: %" PRIu64, error_cnt);
334 }
335 // If this test allows resource exhaustion, expect that it actually sees some
336 if (this->common_.AllowExhaustion()) {
337 EXPECT_GT(error_cnt, static_cast<uint64_t>(0));
338 }
339 }
340
341 template <class Common>
342 class AsyncClientEnd2endTest : public ::testing::Test {
343 protected:
344 AsyncClientEnd2endTest() : rpcs_outstanding_(0) {}
345
346 void SetUp() override { common_.SetUp(); }
347 void TearDown() override {
348 void* ignored_tag;
349 bool ignored_ok;
350 while (cq_.Next(&ignored_tag, &ignored_ok)) {
351 }
352 common_.TearDown();
353 }
354
355 void Wait() {
356 grpc::internal::MutexLock l(&mu_);
357 while (rpcs_outstanding_ != 0) {
358 cv_.Wait(&mu_);
359 }
360
361 cq_.Shutdown();
362 }
363
364 struct AsyncClientCall {
365 EchoResponse response;
366 ClientContext context;
367 Status status;
368 std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader;
369 };
370
371 void AsyncSendRpc(int num_rpcs) {
372 for (int i = 0; i < num_rpcs; ++i) {
373 AsyncClientCall* call = new AsyncClientCall;
374 EchoRequest request;
375 request.set_message("Hello: " + std::to_string(i));
376 call->response_reader =
377 common_.GetStub()->AsyncEcho(&call->context, request, &cq_);
378 call->response_reader->Finish(&call->response, &call->status, call);
379
380 grpc::internal::MutexLock l(&mu_);
381 rpcs_outstanding_++;
382 }
383 }
384
385 void AsyncCompleteRpc() {
386 while (true) {
387 void* got_tag;
388 bool ok = false;
389 if (!cq_.Next(&got_tag, &ok)) break;
390 AsyncClientCall* call = static_cast<AsyncClientCall*>(got_tag);
391 if (!ok) {
392 gpr_log(GPR_DEBUG, "Error: %d", call->status.error_code());
393 }
394 delete call;
395
396 bool notify;
397 {
398 grpc::internal::MutexLock l(&mu_);
399 rpcs_outstanding_--;
400 notify = (rpcs_outstanding_ == 0);
401 }
402 if (notify) {
403 cv_.Signal();
404 }
405 }
406 }
407
408 Common common_;
409 CompletionQueue cq_;
410 grpc::internal::Mutex mu_;
411 grpc::internal::CondVar cv_;
412 int rpcs_outstanding_;
413 };
414
415 TYPED_TEST_SUITE(AsyncClientEnd2endTest, CommonTypes);
416 TYPED_TEST(AsyncClientEnd2endTest, ThreadStress) {
417 this->common_.ResetStub();
418 std::vector<std::thread> send_threads, completion_threads;
419 for (int i = 0; i < kNumAsyncReceiveThreads; ++i) {
420 completion_threads.emplace_back(
421 &AsyncClientEnd2endTest_ThreadStress_Test<TypeParam>::AsyncCompleteRpc,
422 this);
423 }
424 for (int i = 0; i < kNumAsyncSendThreads; ++i) {
425 send_threads.emplace_back(
426 &AsyncClientEnd2endTest_ThreadStress_Test<TypeParam>::AsyncSendRpc,
427 this, kNumRpcs);
428 }
429 for (int i = 0; i < kNumAsyncSendThreads; ++i) {
430 send_threads[i].join();
431 }
432
433 this->Wait();
434 for (int i = 0; i < kNumAsyncReceiveThreads; ++i) {
435 completion_threads[i].join();
436 }
437 }
438
439 } // namespace testing
440 } // namespace grpc
441
442 int main(int argc, char** argv) {
443 grpc::testing::TestEnvironment env(&argc, argv);
444 ::testing::InitGoogleTest(&argc, argv);
445 return RUN_ALL_TESTS();
446 }