ad67402e3df890a4c436ffe4ba7326bed8bff489
[platform/upstream/grpc.git] / test / cpp / end2end / filter_end2end_test.cc
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 #include <memory>
20 #include <mutex>
21
22 #include <grpc/grpc.h>
23 #include <grpc/support/time.h>
24 #include <grpcpp/channel.h>
25 #include <grpcpp/client_context.h>
26 #include <grpcpp/create_channel.h>
27 #include <grpcpp/generic/async_generic_service.h>
28 #include <grpcpp/generic/generic_stub.h>
29 #include <grpcpp/impl/codegen/proto_utils.h>
30 #include <grpcpp/server.h>
31 #include <grpcpp/server_builder.h>
32 #include <grpcpp/server_context.h>
33 #include <grpcpp/support/config.h>
34 #include <grpcpp/support/slice.h>
35
36 #include "src/cpp/common/channel_filter.h"
37 #include "src/proto/grpc/testing/echo.grpc.pb.h"
38 #include "test/core/util/port.h"
39 #include "test/core/util/test_config.h"
40 #include "test/cpp/util/byte_buffer_proto_helper.h"
41
42 #include <gtest/gtest.h>
43
44 using grpc::testing::EchoRequest;
45 using grpc::testing::EchoResponse;
46 using std::chrono::system_clock;
47
48 namespace grpc {
49 namespace testing {
50 namespace {
51
52 void* tag(int i) { return (void*)static_cast<intptr_t>(i); }
53
54 void verify_ok(CompletionQueue* cq, int i, bool expect_ok) {
55   bool ok;
56   void* got_tag;
57   EXPECT_TRUE(cq->Next(&got_tag, &ok));
58   EXPECT_EQ(expect_ok, ok);
59   EXPECT_EQ(tag(i), got_tag);
60 }
61
62 namespace {
63
64 int global_num_connections = 0;
65 int global_num_calls = 0;
66 std::mutex global_mu;
67
68 void IncrementConnectionCounter() {
69   std::unique_lock<std::mutex> lock(global_mu);
70   ++global_num_connections;
71 }
72
73 void ResetConnectionCounter() {
74   std::unique_lock<std::mutex> lock(global_mu);
75   global_num_connections = 0;
76 }
77
78 int GetConnectionCounterValue() {
79   std::unique_lock<std::mutex> lock(global_mu);
80   return global_num_connections;
81 }
82
83 void IncrementCallCounter() {
84   std::unique_lock<std::mutex> lock(global_mu);
85   ++global_num_calls;
86 }
87
88 void ResetCallCounter() {
89   std::unique_lock<std::mutex> lock(global_mu);
90   global_num_calls = 0;
91 }
92
93 int GetCallCounterValue() {
94   std::unique_lock<std::mutex> lock(global_mu);
95   return global_num_calls;
96 }
97
98 }  // namespace
99
100 class ChannelDataImpl : public ChannelData {
101  public:
102   grpc_error* Init(grpc_channel_element* elem,
103                    grpc_channel_element_args* args) {
104     IncrementConnectionCounter();
105     return GRPC_ERROR_NONE;
106   }
107 };
108
109 class CallDataImpl : public CallData {
110  public:
111   void StartTransportStreamOpBatch(grpc_call_element* elem,
112                                    TransportStreamOpBatch* op) override {
113     // Incrementing the counter could be done from Init(), but we want
114     // to test that the individual methods are actually called correctly.
115     if (op->recv_initial_metadata() != nullptr) IncrementCallCounter();
116     grpc_call_next_op(elem, op->op());
117   }
118 };
119
120 class FilterEnd2endTest : public ::testing::Test {
121  protected:
122   FilterEnd2endTest() : server_host_("localhost") {}
123
124   void SetUp() override {
125     int port = grpc_pick_unused_port_or_die();
126     server_address_ << server_host_ << ":" << port;
127     // Setup server
128     ServerBuilder builder;
129     builder.AddListeningPort(server_address_.str(),
130                              InsecureServerCredentials());
131     builder.RegisterAsyncGenericService(&generic_service_);
132     srv_cq_ = builder.AddCompletionQueue();
133     server_ = builder.BuildAndStart();
134   }
135
136   void TearDown() override {
137     server_->Shutdown();
138     void* ignored_tag;
139     bool ignored_ok;
140     cli_cq_.Shutdown();
141     srv_cq_->Shutdown();
142     while (cli_cq_.Next(&ignored_tag, &ignored_ok))
143       ;
144     while (srv_cq_->Next(&ignored_tag, &ignored_ok))
145       ;
146   }
147
148   void ResetStub() {
149     std::shared_ptr<Channel> channel =
150         CreateChannel(server_address_.str(), InsecureChannelCredentials());
151     generic_stub_.reset(new GenericStub(channel));
152     ResetConnectionCounter();
153     ResetCallCounter();
154   }
155
156   void server_ok(int i) { verify_ok(srv_cq_.get(), i, true); }
157   void client_ok(int i) { verify_ok(&cli_cq_, i, true); }
158   void server_fail(int i) { verify_ok(srv_cq_.get(), i, false); }
159   void client_fail(int i) { verify_ok(&cli_cq_, i, false); }
160
161   void SendRpc(int num_rpcs) {
162     const grpc::string kMethodName("/grpc.cpp.test.util.EchoTestService/Echo");
163     for (int i = 0; i < num_rpcs; i++) {
164       EchoRequest send_request;
165       EchoRequest recv_request;
166       EchoResponse send_response;
167       EchoResponse recv_response;
168       Status recv_status;
169
170       ClientContext cli_ctx;
171       GenericServerContext srv_ctx;
172       GenericServerAsyncReaderWriter stream(&srv_ctx);
173
174       // The string needs to be long enough to test heap-based slice.
175       send_request.set_message("Hello world. Hello world. Hello world.");
176       std::unique_ptr<GenericClientAsyncReaderWriter> call =
177           generic_stub_->PrepareCall(&cli_ctx, kMethodName, &cli_cq_);
178       call->StartCall(tag(1));
179       client_ok(1);
180       std::unique_ptr<ByteBuffer> send_buffer =
181           SerializeToByteBuffer(&send_request);
182       call->Write(*send_buffer, tag(2));
183       // Send ByteBuffer can be destroyed after calling Write.
184       send_buffer.reset();
185       client_ok(2);
186       call->WritesDone(tag(3));
187       client_ok(3);
188
189       generic_service_.RequestCall(&srv_ctx, &stream, srv_cq_.get(),
190                                    srv_cq_.get(), tag(4));
191
192       verify_ok(srv_cq_.get(), 4, true);
193       EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
194       EXPECT_EQ(kMethodName, srv_ctx.method());
195       ByteBuffer recv_buffer;
196       stream.Read(&recv_buffer, tag(5));
197       server_ok(5);
198       EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
199       EXPECT_EQ(send_request.message(), recv_request.message());
200
201       send_response.set_message(recv_request.message());
202       send_buffer = SerializeToByteBuffer(&send_response);
203       stream.Write(*send_buffer, tag(6));
204       send_buffer.reset();
205       server_ok(6);
206
207       stream.Finish(Status::OK, tag(7));
208       server_ok(7);
209
210       recv_buffer.Clear();
211       call->Read(&recv_buffer, tag(8));
212       client_ok(8);
213       EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
214
215       call->Finish(&recv_status, tag(9));
216       client_ok(9);
217
218       EXPECT_EQ(send_response.message(), recv_response.message());
219       EXPECT_TRUE(recv_status.ok());
220     }
221   }
222
223   CompletionQueue cli_cq_;
224   std::unique_ptr<ServerCompletionQueue> srv_cq_;
225   std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
226   std::unique_ptr<grpc::GenericStub> generic_stub_;
227   std::unique_ptr<Server> server_;
228   AsyncGenericService generic_service_;
229   const grpc::string server_host_;
230   std::ostringstream server_address_;
231 };
232
233 TEST_F(FilterEnd2endTest, SimpleRpc) {
234   ResetStub();
235   EXPECT_EQ(0, GetConnectionCounterValue());
236   EXPECT_EQ(0, GetCallCounterValue());
237   SendRpc(1);
238   EXPECT_EQ(1, GetConnectionCounterValue());
239   EXPECT_EQ(1, GetCallCounterValue());
240 }
241
242 TEST_F(FilterEnd2endTest, SequentialRpcs) {
243   ResetStub();
244   EXPECT_EQ(0, GetConnectionCounterValue());
245   EXPECT_EQ(0, GetCallCounterValue());
246   SendRpc(10);
247   EXPECT_EQ(1, GetConnectionCounterValue());
248   EXPECT_EQ(10, GetCallCounterValue());
249 }
250
251 // One ping, one pong.
252 TEST_F(FilterEnd2endTest, SimpleBidiStreaming) {
253   ResetStub();
254   EXPECT_EQ(0, GetConnectionCounterValue());
255   EXPECT_EQ(0, GetCallCounterValue());
256
257   const grpc::string kMethodName(
258       "/grpc.cpp.test.util.EchoTestService/BidiStream");
259   EchoRequest send_request;
260   EchoRequest recv_request;
261   EchoResponse send_response;
262   EchoResponse recv_response;
263   Status recv_status;
264   ClientContext cli_ctx;
265   GenericServerContext srv_ctx;
266   GenericServerAsyncReaderWriter srv_stream(&srv_ctx);
267
268   cli_ctx.set_compression_algorithm(GRPC_COMPRESS_GZIP);
269   send_request.set_message("Hello");
270   std::unique_ptr<GenericClientAsyncReaderWriter> cli_stream =
271       generic_stub_->PrepareCall(&cli_ctx, kMethodName, &cli_cq_);
272   cli_stream->StartCall(tag(1));
273   client_ok(1);
274
275   generic_service_.RequestCall(&srv_ctx, &srv_stream, srv_cq_.get(),
276                                srv_cq_.get(), tag(2));
277
278   verify_ok(srv_cq_.get(), 2, true);
279   EXPECT_EQ(server_host_, srv_ctx.host().substr(0, server_host_.length()));
280   EXPECT_EQ(kMethodName, srv_ctx.method());
281
282   std::unique_ptr<ByteBuffer> send_buffer =
283       SerializeToByteBuffer(&send_request);
284   cli_stream->Write(*send_buffer, tag(3));
285   send_buffer.reset();
286   client_ok(3);
287
288   ByteBuffer recv_buffer;
289   srv_stream.Read(&recv_buffer, tag(4));
290   server_ok(4);
291   EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_request));
292   EXPECT_EQ(send_request.message(), recv_request.message());
293
294   send_response.set_message(recv_request.message());
295   send_buffer = SerializeToByteBuffer(&send_response);
296   srv_stream.Write(*send_buffer, tag(5));
297   send_buffer.reset();
298   server_ok(5);
299
300   cli_stream->Read(&recv_buffer, tag(6));
301   client_ok(6);
302   EXPECT_TRUE(ParseFromByteBuffer(&recv_buffer, &recv_response));
303   EXPECT_EQ(send_response.message(), recv_response.message());
304
305   cli_stream->WritesDone(tag(7));
306   client_ok(7);
307
308   srv_stream.Read(&recv_buffer, tag(8));
309   server_fail(8);
310
311   srv_stream.Finish(Status::OK, tag(9));
312   server_ok(9);
313
314   cli_stream->Finish(&recv_status, tag(10));
315   client_ok(10);
316
317   EXPECT_EQ(send_response.message(), recv_response.message());
318   EXPECT_TRUE(recv_status.ok());
319
320   EXPECT_EQ(1, GetCallCounterValue());
321   EXPECT_EQ(1, GetConnectionCounterValue());
322 }
323
324 void RegisterFilter() {
325   grpc::RegisterChannelFilter<ChannelDataImpl, CallDataImpl>(
326       "test-filter", GRPC_SERVER_CHANNEL, INT_MAX, nullptr);
327 }
328
329 }  // namespace
330 }  // namespace testing
331 }  // namespace grpc
332
333 int main(int argc, char** argv) {
334   grpc::testing::TestEnvironment env(argc, argv);
335   ::testing::InitGoogleTest(&argc, argv);
336   grpc::testing::RegisterFilter();
337   return RUN_ALL_TESTS();
338 }