Debian Codegraph @

test/cpp/end2end/test_service_impl.h

raw
1 /*
2 *
3 * Copyright 2016 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 #ifndef GRPC_TEST_CPP_END2END_TEST_SERVICE_IMPL_H
20 #define GRPC_TEST_CPP_END2END_TEST_SERVICE_IMPL_H
21
22 #include <condition_variable>
23 #include <memory>
24 #include <mutex>
25 #include <string>
26 #include <thread>
27
28 #include <gtest/gtest.h>
29
30 #include <grpc/grpc.h>
31 #include <grpc/support/log.h>
32 #include <grpcpp/alarm.h>
33 #include <grpcpp/security/credentials.h>
34 #include <grpcpp/server_context.h>
35
36 #include "src/proto/grpc/testing/echo.grpc.pb.h"
37 #include "test/core/util/test_config.h"
38 #include "test/cpp/util/string_ref_helper.h"
39
40 namespace grpc {
41 namespace testing {
42
43 const int kServerDefaultResponseStreamsToSend = 3;
44 const char* const kServerResponseStreamsToSend = "server_responses_to_send";
45 const char* const kServerTryCancelRequest = "server_try_cancel";
46 const char* const kClientTryCancelRequest = "client_try_cancel";
47 const char* const kDebugInfoTrailerKey = "debug-info-bin";
48 const char* const kServerFinishAfterNReads = "server_finish_after_n_reads";
49 const char* const kServerUseCoalescingApi = "server_use_coalescing_api";
50 const char* const kCheckClientInitialMetadataKey = "custom_client_metadata";
51 const char* const kCheckClientInitialMetadataVal = "Value for client metadata";
52
53 typedef enum {
54 DO_NOT_CANCEL = 0,
55 CANCEL_BEFORE_PROCESSING,
56 CANCEL_DURING_PROCESSING,
57 CANCEL_AFTER_PROCESSING
58 } ServerTryCancelRequestPhase;
59
60 namespace internal {
61 // When echo_deadline is requested, deadline seen in the ServerContext is set in
62 // the response in seconds.
63 void MaybeEchoDeadline(ServerContextBase* context, const EchoRequest* request,
64 EchoResponse* response);
65
66 void CheckServerAuthContext(const ServerContextBase* context,
67 const std::string& expected_transport_security_type,
68 const std::string& expected_client_identity);
69
70 // Returns the number of pairs in metadata that exactly match the given
71 // key-value pair. Returns -1 if the pair wasn't found.
72 int MetadataMatchCount(
73 const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
74 const std::string& key, const std::string& value);
75
76 int GetIntValueFromMetadataHelper(
77 const char* key,
78 const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
79 int default_value);
80
81 int GetIntValueFromMetadata(
82 const char* key,
83 const std::multimap<grpc::string_ref, grpc::string_ref>& metadata,
84 int default_value);
85
86 void ServerTryCancel(ServerContext* context);
87 } // namespace internal
88
89 class TestServiceSignaller {
90 public:
91 void ClientWaitUntilRpcStarted() {
92 std::unique_lock<std::mutex> lock(mu_);
93 cv_rpc_started_.wait(lock, [this] { return rpc_started_; });
94 }
95 void ServerWaitToContinue() {
96 std::unique_lock<std::mutex> lock(mu_);
97 cv_server_continue_.wait(lock, [this] { return server_should_continue_; });
98 }
99 void SignalClientThatRpcStarted() {
100 std::unique_lock<std::mutex> lock(mu_);
101 rpc_started_ = true;
102 cv_rpc_started_.notify_one();
103 }
104 void SignalServerToContinue() {
105 std::unique_lock<std::mutex> lock(mu_);
106 server_should_continue_ = true;
107 cv_server_continue_.notify_one();
108 }
109
110 private:
111 std::mutex mu_;
112 std::condition_variable cv_rpc_started_;
113 bool rpc_started_ /* GUARDED_BY(mu_) */ = false;
114 std::condition_variable cv_server_continue_;
115 bool server_should_continue_ /* GUARDED_BY(mu_) */ = false;
116 };
117
118 template <typename RpcService>
119 class TestMultipleServiceImpl : public RpcService {
120 public:
121 TestMultipleServiceImpl() : signal_client_(false), host_() {}
122 explicit TestMultipleServiceImpl(const std::string& host)
123 : signal_client_(false), host_(new std::string(host)) {}
124
125 Status Echo(ServerContext* context, const EchoRequest* request,
126 EchoResponse* response) {
127 if (request->has_param() &&
128 request->param().server_notify_client_when_started()) {
129 signaller_.SignalClientThatRpcStarted();
130 signaller_.ServerWaitToContinue();
131 }
132
133 // A bit of sleep to make sure that short deadline tests fail
134 if (request->has_param() && request->param().server_sleep_us() > 0) {
135 gpr_sleep_until(gpr_time_add(
136 gpr_now(GPR_CLOCK_MONOTONIC),
137 gpr_time_from_micros(
138 request->param().server_sleep_us() * grpc_test_slowdown_factor(),
139 GPR_TIMESPAN)));
140 }
141
142 if (request->has_param() && request->param().server_die()) {
143 gpr_log(GPR_ERROR, "The request should not reach application handler.");
144 GPR_ASSERT(0);
145 }
146 if (request->has_param() && request->param().has_expected_error()) {
147 const auto& error = request->param().expected_error();
148 return Status(static_cast<StatusCode>(error.code()),
149 error.error_message(), error.binary_error_details());
150 }
151 int server_try_cancel = internal::GetIntValueFromMetadata(
152 kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
153 if (server_try_cancel > DO_NOT_CANCEL) {
154 // Since this is a unary RPC, by the time this server handler is called,
155 // the 'request' message is already read from the client. So the scenarios
156 // in server_try_cancel don't make much sense. Just cancel the RPC as long
157 // as server_try_cancel is not DO_NOT_CANCEL
158 internal::ServerTryCancel(context);
159 return Status::CANCELLED;
160 }
161
162 response->set_message(request->message());
163 internal::MaybeEchoDeadline(context, request, response);
164 if (host_) {
165 response->mutable_param()->set_host(*host_);
166 } else if (request->has_param() &&
167 request->param().echo_host_from_authority_header()) {
168 auto authority = context->ExperimentalGetAuthority();
169 std::string authority_str(authority.data(), authority.size());
170 response->mutable_param()->set_host(std::move(authority_str));
171 }
172 if (request->has_param() && request->param().client_cancel_after_us()) {
173 {
174 std::unique_lock<std::mutex> lock(mu_);
175 signal_client_ = true;
176 ++rpcs_waiting_for_client_cancel_;
177 }
178 while (!context->IsCancelled()) {
179 gpr_sleep_until(gpr_time_add(
180 gpr_now(GPR_CLOCK_REALTIME),
181 gpr_time_from_micros(request->param().client_cancel_after_us() *
182 grpc_test_slowdown_factor(),
183 GPR_TIMESPAN)));
184 }
185 {
186 std::unique_lock<std::mutex> lock(mu_);
187 --rpcs_waiting_for_client_cancel_;
188 }
189 return Status::CANCELLED;
190 } else if (request->has_param() &&
191 request->param().server_cancel_after_us()) {
192 gpr_sleep_until(gpr_time_add(
193 gpr_now(GPR_CLOCK_REALTIME),
194 gpr_time_from_micros(request->param().server_cancel_after_us() *
195 grpc_test_slowdown_factor(),
196 GPR_TIMESPAN)));
197 return Status::CANCELLED;
198 } else if (!request->has_param() ||
199 !request->param().skip_cancelled_check()) {
200 EXPECT_FALSE(context->IsCancelled());
201 }
202
203 if (request->has_param() && request->param().echo_metadata_initially()) {
204 const std::multimap<grpc::string_ref, grpc::string_ref>& client_metadata =
205 context->client_metadata();
206 for (const auto& metadatum : client_metadata) {
207 context->AddInitialMetadata(ToString(metadatum.first),
208 ToString(metadatum.second));
209 }
210 }
211
212 if (request->has_param() && request->param().echo_metadata()) {
213 const std::multimap<grpc::string_ref, grpc::string_ref>& client_metadata =
214 context->client_metadata();
215 for (const auto& metadatum : client_metadata) {
216 context->AddTrailingMetadata(ToString(metadatum.first),
217 ToString(metadatum.second));
218 }
219 // Terminate rpc with error and debug info in trailer.
220 if (request->param().debug_info().stack_entries_size() ||
221 !request->param().debug_info().detail().empty()) {
222 std::string serialized_debug_info =
223 request->param().debug_info().SerializeAsString();
224 context->AddTrailingMetadata(kDebugInfoTrailerKey,
225 serialized_debug_info);
226 return Status::CANCELLED;
227 }
228 }
229 if (request->has_param() &&
230 (request->param().expected_client_identity().length() > 0 ||
231 request->param().check_auth_context())) {
232 internal::CheckServerAuthContext(
233 context, request->param().expected_transport_security_type(),
234 request->param().expected_client_identity());
235 }
236 if (request->has_param() &&
237 request->param().response_message_length() > 0) {
238 response->set_message(
239 std::string(request->param().response_message_length(), '\0'));
240 }
241 if (request->has_param() && request->param().echo_peer()) {
242 response->mutable_param()->set_peer(context->peer());
243 }
244 return Status::OK;
245 }
246
247 Status Echo1(ServerContext* context, const EchoRequest* request,
248 EchoResponse* response) {
249 return Echo(context, request, response);
250 }
251
252 Status Echo2(ServerContext* context, const EchoRequest* request,
253 EchoResponse* response) {
254 return Echo(context, request, response);
255 }
256
257 Status CheckClientInitialMetadata(ServerContext* context,
258 const SimpleRequest* /*request*/,
259 SimpleResponse* /*response*/) {
260 EXPECT_EQ(internal::MetadataMatchCount(context->client_metadata(),
261 kCheckClientInitialMetadataKey,
262 kCheckClientInitialMetadataVal),
263 1);
264 EXPECT_EQ(1u,
265 context->client_metadata().count(kCheckClientInitialMetadataKey));
266 return Status::OK;
267 }
268
269 // Unimplemented is left unimplemented to test the returned error.
270
271 Status RequestStream(ServerContext* context,
272 ServerReader<EchoRequest>* reader,
273 EchoResponse* response) {
274 // If 'server_try_cancel' is set in the metadata, the RPC is cancelled by
275 // the server by calling ServerContext::TryCancel() depending on the value:
276 // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server reads
277 // any message from the client
278 // CANCEL_DURING_PROCESSING: The RPC is cancelled while the server is
279 // reading messages from the client
280 // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server reads
281 // all the messages from the client
282 int server_try_cancel = internal::GetIntValueFromMetadata(
283 kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
284
285 EchoRequest request;
286 response->set_message("");
287
288 if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
289 internal::ServerTryCancel(context);
290 return Status::CANCELLED;
291 }
292
293 std::thread* server_try_cancel_thd = nullptr;
294 if (server_try_cancel == CANCEL_DURING_PROCESSING) {
295 server_try_cancel_thd =
296 new std::thread([context] { internal::ServerTryCancel(context); });
297 }
298
299 int num_msgs_read = 0;
300 while (reader->Read(&request)) {
301 response->mutable_message()->append(request.message());
302 }
303 gpr_log(GPR_INFO, "Read: %d messages", num_msgs_read);
304
305 if (server_try_cancel_thd != nullptr) {
306 server_try_cancel_thd->join();
307 delete server_try_cancel_thd;
308 return Status::CANCELLED;
309 }
310
311 if (server_try_cancel == CANCEL_AFTER_PROCESSING) {
312 internal::ServerTryCancel(context);
313 return Status::CANCELLED;
314 }
315
316 return Status::OK;
317 }
318
319 // Return 'kNumResponseStreamMsgs' messages.
320 // TODO(yangg) make it generic by adding a parameter into EchoRequest
321 Status ResponseStream(ServerContext* context, const EchoRequest* request,
322 ServerWriter<EchoResponse>* writer) {
323 // If server_try_cancel is set in the metadata, the RPC is cancelled by the
324 // server by calling ServerContext::TryCancel() depending on the value:
325 // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server writes
326 // any messages to the client
327 // CANCEL_DURING_PROCESSING: The RPC is cancelled while the server is
328 // writing messages to the client
329 // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server writes
330 // all the messages to the client
331 int server_try_cancel = internal::GetIntValueFromMetadata(
332 kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
333
334 int server_coalescing_api = internal::GetIntValueFromMetadata(
335 kServerUseCoalescingApi, context->client_metadata(), 0);
336
337 int server_responses_to_send = internal::GetIntValueFromMetadata(
338 kServerResponseStreamsToSend, context->client_metadata(),
339 kServerDefaultResponseStreamsToSend);
340
341 if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
342 internal::ServerTryCancel(context);
343 return Status::CANCELLED;
344 }
345
346 EchoResponse response;
347 std::thread* server_try_cancel_thd = nullptr;
348 if (server_try_cancel == CANCEL_DURING_PROCESSING) {
349 server_try_cancel_thd =
350 new std::thread([context] { internal::ServerTryCancel(context); });
351 }
352
353 for (int i = 0; i < server_responses_to_send; i++) {
354 response.set_message(request->message() + std::to_string(i));
355 if (i == server_responses_to_send - 1 && server_coalescing_api != 0) {
356 writer->WriteLast(response, WriteOptions());
357 } else {
358 writer->Write(response);
359 }
360 }
361
362 if (server_try_cancel_thd != nullptr) {
363 server_try_cancel_thd->join();
364 delete server_try_cancel_thd;
365 return Status::CANCELLED;
366 }
367
368 if (server_try_cancel == CANCEL_AFTER_PROCESSING) {
369 internal::ServerTryCancel(context);
370 return Status::CANCELLED;
371 }
372
373 return Status::OK;
374 }
375
376 Status BidiStream(ServerContext* context,
377 ServerReaderWriter<EchoResponse, EchoRequest>* stream) {
378 // If server_try_cancel is set in the metadata, the RPC is cancelled by the
379 // server by calling ServerContext::TryCancel() depending on the value:
380 // CANCEL_BEFORE_PROCESSING: The RPC is cancelled before the server reads/
381 // writes any messages from/to the client
382 // CANCEL_DURING_PROCESSING: The RPC is cancelled while the server is
383 // reading/writing messages from/to the client
384 // CANCEL_AFTER_PROCESSING: The RPC is cancelled after the server
385 // reads/writes all messages from/to the client
386 int server_try_cancel = internal::GetIntValueFromMetadata(
387 kServerTryCancelRequest, context->client_metadata(), DO_NOT_CANCEL);
388
389 int client_try_cancel = static_cast<bool>(internal::GetIntValueFromMetadata(
390 kClientTryCancelRequest, context->client_metadata(), 0));
391
392 EchoRequest request;
393 EchoResponse response;
394
395 if (server_try_cancel == CANCEL_BEFORE_PROCESSING) {
396 internal::ServerTryCancel(context);
397 return Status::CANCELLED;
398 }
399
400 std::thread* server_try_cancel_thd = nullptr;
401 if (server_try_cancel == CANCEL_DURING_PROCESSING) {
402 server_try_cancel_thd =
403 new std::thread([context] { internal::ServerTryCancel(context); });
404 }
405
406 // kServerFinishAfterNReads suggests after how many reads, the server should
407 // write the last message and send status (coalesced using WriteLast)
408 int server_write_last = internal::GetIntValueFromMetadata(
409 kServerFinishAfterNReads, context->client_metadata(), 0);
410
411 int read_counts = 0;
412 while (stream->Read(&request)) {
413 read_counts++;
414 gpr_log(GPR_INFO, "recv msg %s", request.message().c_str());
415 response.set_message(request.message());
416 if (read_counts == server_write_last) {
417 stream->WriteLast(response, WriteOptions());
418 break;
419 } else {
420 stream->Write(response);
421 }
422 }
423
424 if (client_try_cancel) {
425 EXPECT_TRUE(context->IsCancelled());
426 }
427
428 if (server_try_cancel_thd != nullptr) {
429 server_try_cancel_thd->join();
430 delete server_try_cancel_thd;
431 return Status::CANCELLED;
432 }
433
434 if (server_try_cancel == CANCEL_AFTER_PROCESSING) {
435 internal::ServerTryCancel(context);
436 return Status::CANCELLED;
437 }
438
439 return Status::OK;
440 }
441
442 // Unimplemented is left unimplemented to test the returned error.
443 bool signal_client() {
444 std::unique_lock<std::mutex> lock(mu_);
445 return signal_client_;
446 }
447 void ClientWaitUntilRpcStarted() { signaller_.ClientWaitUntilRpcStarted(); }
448 void SignalServerToContinue() { signaller_.SignalServerToContinue(); }
449 uint64_t RpcsWaitingForClientCancel() {
450 std::unique_lock<std::mutex> lock(mu_);
451 return rpcs_waiting_for_client_cancel_;
452 }
453
454 private:
455 bool signal_client_;
456 std::mutex mu_;
457 TestServiceSignaller signaller_;
458 std::unique_ptr<std::string> host_;
459 uint64_t rpcs_waiting_for_client_cancel_ = 0;
460 };
461
462 class CallbackTestServiceImpl
463 : public grpc::testing::EchoTestService::CallbackService {
464 public:
465 CallbackTestServiceImpl() : signal_client_(false), host_() {}
466 explicit CallbackTestServiceImpl(const std::string& host)
467 : signal_client_(false), host_(new std::string(host)) {}
468
469 ServerUnaryReactor* Echo(CallbackServerContext* context,
470 const EchoRequest* request,
471 EchoResponse* response) override;
472
473 ServerUnaryReactor* CheckClientInitialMetadata(CallbackServerContext* context,
474 const SimpleRequest*,
475 SimpleResponse*) override;
476
477 ServerReadReactor<EchoRequest>* RequestStream(
478 CallbackServerContext* context, EchoResponse* response) override;
479
480 ServerWriteReactor<EchoResponse>* ResponseStream(
481 CallbackServerContext* context, const EchoRequest* request) override;
482
483 ServerBidiReactor<EchoRequest, EchoResponse>* BidiStream(
484 CallbackServerContext* context) override;
485
486 // Unimplemented is left unimplemented to test the returned error.
487 bool signal_client() {
488 std::unique_lock<std::mutex> lock(mu_);
489 return signal_client_;
490 }
491 void ClientWaitUntilRpcStarted() { signaller_.ClientWaitUntilRpcStarted(); }
492 void SignalServerToContinue() { signaller_.SignalServerToContinue(); }
493
494 private:
495 bool signal_client_;
496 std::mutex mu_;
497 TestServiceSignaller signaller_;
498 std::unique_ptr<std::string> host_;
499 };
500
501 using TestServiceImpl =
502 TestMultipleServiceImpl<grpc::testing::EchoTestService::Service>;
503
504 } // namespace testing
505 } // namespace grpc
506
507 #endif // GRPC_TEST_CPP_END2END_TEST_SERVICE_IMPL_H