test_service_impl.h 18 KB

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