Imported Upstream version 1.34.0
[platform/upstream/grpc.git] / test / core / transport / chttp2 / too_many_pings_test.cc
1 /*
2  *
3  * Copyright 2020 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 <grpc/support/port_platform.h>
20
21 #include <gmock/gmock.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <functional>
25 #include <set>
26 #include <thread>
27
28 #include "absl/strings/str_cat.h"
29
30 #include <grpc/grpc.h>
31 #include <grpc/grpc_security.h>
32 #include <grpc/impl/codegen/grpc_types.h>
33 #include <grpc/slice.h>
34 #include <grpc/support/alloc.h>
35 #include <grpc/support/log.h>
36 #include <grpc/support/string_util.h>
37 #include <grpc/support/time.h>
38
39 #include <grpcpp/impl/codegen/service_type.h>
40 #include <grpcpp/server_builder.h>
41
42 #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
43 #include "src/core/lib/gpr/useful.h"
44 #include "src/core/lib/gprpp/host_port.h"
45 #include "src/core/lib/gprpp/thd.h"
46 #include "src/core/lib/iomgr/error.h"
47 #include "src/core/lib/iomgr/parse_address.h"
48 #include "src/core/lib/security/credentials/alts/alts_credentials.h"
49 #include "src/core/lib/security/credentials/credentials.h"
50 #include "src/core/lib/security/security_connector/alts/alts_security_connector.h"
51 #include "src/core/lib/slice/slice_string_helpers.h"
52 #include "src/core/lib/surface/channel.h"
53
54 #include "test/core/util/memory_counters.h"
55 #include "test/core/util/port.h"
56 #include "test/core/util/test_config.h"
57
58 #include "test/core/end2end/cq_verifier.h"
59
60 namespace {
61
62 void* tag(int i) { return (void*)static_cast<intptr_t>(i); }
63
64 // Perform a simple RPC where the server cancels the request with
65 // grpc_call_cancel_with_status
66 grpc_status_code PerformCall(grpc_channel* channel, grpc_server* server,
67                              grpc_completion_queue* cq) {
68   grpc_call* c;
69   grpc_call* s;
70   cq_verifier* cqv = cq_verifier_create(cq);
71   grpc_op ops[6];
72   grpc_op* op;
73   grpc_metadata_array trailing_metadata_recv;
74   grpc_metadata_array request_metadata_recv;
75   grpc_call_details call_details;
76   grpc_status_code status;
77   grpc_call_error error;
78   grpc_slice details;
79   gpr_timespec deadline = grpc_timeout_seconds_to_deadline(5);
80   // Start a call
81   c = grpc_channel_create_call(channel, nullptr, GRPC_PROPAGATE_DEFAULTS, cq,
82                                grpc_slice_from_static_string("/foo"), nullptr,
83                                deadline, nullptr);
84   GPR_ASSERT(c);
85   grpc_metadata_array_init(&trailing_metadata_recv);
86   grpc_metadata_array_init(&request_metadata_recv);
87   grpc_call_details_init(&call_details);
88   memset(ops, 0, sizeof(ops));
89   op = ops;
90   op->op = GRPC_OP_SEND_INITIAL_METADATA;
91   op->data.send_initial_metadata.count = 0;
92   op->flags = 0;
93   op->reserved = nullptr;
94   op++;
95   op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
96   op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;
97   op->data.recv_status_on_client.status = &status;
98   op->data.recv_status_on_client.status_details = &details;
99   op->flags = 0;
100   op->reserved = nullptr;
101   op++;
102   error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(1),
103                                 nullptr);
104   GPR_ASSERT(GRPC_CALL_OK == error);
105   // Request a call on the server
106   error = grpc_server_request_call(server, &s, &call_details,
107                                    &request_metadata_recv, cq, cq, tag(101));
108   GPR_ASSERT(GRPC_CALL_OK == error);
109   CQ_EXPECT_COMPLETION(cqv, tag(101), 1);
110   cq_verify(cqv);
111   grpc_call_cancel_with_status(s, GRPC_STATUS_PERMISSION_DENIED, "test status",
112                                nullptr);
113   CQ_EXPECT_COMPLETION(cqv, tag(1), 1);
114   cq_verify(cqv);
115   // cleanup
116   grpc_slice_unref(details);
117   grpc_metadata_array_destroy(&trailing_metadata_recv);
118   grpc_metadata_array_destroy(&request_metadata_recv);
119   grpc_call_details_destroy(&call_details);
120   grpc_call_unref(c);
121   grpc_call_unref(s);
122   cq_verifier_destroy(cqv);
123   return status;
124 }
125
126 // Test that sending a lot of RPCs that are cancelled by the server doesn't
127 // result in too many pings due to the pings sent by BDP.
128 TEST(TooManyPings, TestLotsOfServerCancelledRpcsDoesntGiveTooManyPings) {
129   grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
130   // create the server
131   grpc_server* server = grpc_server_create(nullptr, nullptr);
132   std::string server_address =
133       grpc_core::JoinHostPort("localhost", grpc_pick_unused_port_or_die());
134   grpc_server_register_completion_queue(server, cq, nullptr);
135   GPR_ASSERT(
136       grpc_server_add_insecure_http2_port(server, server_address.c_str()));
137   grpc_server_start(server);
138   // create the channel (bdp pings are enabled by default)
139   grpc_channel* channel = grpc_insecure_channel_create(
140       server_address.c_str(), nullptr /* channel args */, nullptr);
141   std::map<grpc_status_code, int> statuses_and_counts;
142   const int kNumTotalRpcs = 1e5;
143   // perform an RPC
144   gpr_log(GPR_INFO,
145           "Performing %d total RPCs and expecting them all to receive status "
146           "PERMISSION_DENIED (%d)",
147           kNumTotalRpcs, GRPC_STATUS_PERMISSION_DENIED);
148   for (int i = 0; i < kNumTotalRpcs; i++) {
149     grpc_status_code status = PerformCall(channel, server, cq);
150     statuses_and_counts[status] += 1;
151   }
152   int num_not_cancelled = 0;
153   for (auto itr = statuses_and_counts.begin(); itr != statuses_and_counts.end();
154        itr++) {
155     if (itr->first != GRPC_STATUS_PERMISSION_DENIED) {
156       num_not_cancelled += itr->second;
157     }
158     gpr_log(GPR_INFO, "%d / %d RPCs received status code: %d", itr->second,
159             kNumTotalRpcs, itr->first);
160   }
161   if (num_not_cancelled > 0) {
162     gpr_log(GPR_ERROR,
163             "Expected all RPCs to receive status PERMISSION_DENIED (%d) but %d "
164             "received other status codes",
165             GRPC_STATUS_PERMISSION_DENIED, num_not_cancelled);
166     FAIL();
167   }
168   // shutdown and destroy the client and server
169   grpc_channel_destroy(channel);
170   grpc_server_shutdown_and_notify(server, cq, nullptr);
171   grpc_completion_queue_shutdown(cq);
172   while (grpc_completion_queue_next(cq, gpr_inf_future(GPR_CLOCK_REALTIME),
173                                     nullptr)
174              .type != GRPC_QUEUE_SHUTDOWN) {
175   }
176   grpc_server_destroy(server);
177   grpc_completion_queue_destroy(cq);
178 }
179
180 // Perform a simple RPC where the client makes a request, and both the client
181 // and server continue reading so that gRPC can send and receive keepalive
182 // pings.
183 grpc_status_code PerformWaitingCall(grpc_channel* channel, grpc_server* server,
184                                     grpc_completion_queue* cq) {
185   grpc_call* c;
186   grpc_call* s;
187   cq_verifier* cqv = cq_verifier_create(cq);
188   grpc_op ops[6];
189   grpc_op* op;
190   grpc_metadata_array trailing_metadata_recv;
191   grpc_metadata_array request_metadata_recv;
192   grpc_call_details call_details;
193   grpc_status_code status;
194   grpc_call_error error;
195   grpc_slice details;
196   gpr_timespec deadline = grpc_timeout_seconds_to_deadline(15);
197   // Start a call
198   c = grpc_channel_create_call(channel, nullptr, GRPC_PROPAGATE_DEFAULTS, cq,
199                                grpc_slice_from_static_string("/foo"), nullptr,
200                                deadline, nullptr);
201   GPR_ASSERT(c);
202   grpc_metadata_array_init(&trailing_metadata_recv);
203   grpc_metadata_array_init(&request_metadata_recv);
204   grpc_call_details_init(&call_details);
205   memset(ops, 0, sizeof(ops));
206   op = ops;
207   op->op = GRPC_OP_SEND_INITIAL_METADATA;
208   op->data.send_initial_metadata.count = 0;
209   op->flags = 0;
210   op->reserved = nullptr;
211   op++;
212   op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
213   op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;
214   op->data.recv_status_on_client.status = &status;
215   op->data.recv_status_on_client.status_details = &details;
216   op->flags = 0;
217   op->reserved = nullptr;
218   op++;
219   error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(1),
220                                 nullptr);
221   GPR_ASSERT(GRPC_CALL_OK == error);
222   // Request a call on the server
223   error = grpc_server_request_call(server, &s, &call_details,
224                                    &request_metadata_recv, cq, cq, tag(101));
225   GPR_ASSERT(GRPC_CALL_OK == error);
226   CQ_EXPECT_COMPLETION(cqv, tag(101), 1);
227   cq_verify(cqv);
228   // Since the server is configured to allow only a single ping strike, it would
229   // take 3 pings to trigger the GOAWAY frame with "too_many_pings" from the
230   // server. (The second ping from the client would be the first bad ping sent
231   // too quickly leading to a ping strike and the third ping would lead to the
232   // GOAWAY.) If the client settings match with the server's settings, there
233   // won't be a bad ping, and the call will end due to the deadline expiring
234   // instead.
235   CQ_EXPECT_COMPLETION(cqv, tag(1), 1);
236   // The call will end after this
237   cq_verify(cqv, 60);
238   // cleanup
239   grpc_slice_unref(details);
240   grpc_metadata_array_destroy(&trailing_metadata_recv);
241   grpc_metadata_array_destroy(&request_metadata_recv);
242   grpc_call_details_destroy(&call_details);
243   grpc_call_unref(c);
244   grpc_call_unref(s);
245   cq_verifier_destroy(cqv);
246   return status;
247 }
248
249 // Shuts down and destroys the server.
250 void ServerShutdownAndDestroy(grpc_server* server, grpc_completion_queue* cq) {
251   // Shutdown and destroy server
252   grpc_server_shutdown_and_notify(server, cq, (void*)(1000));
253   while (grpc_completion_queue_next(cq, gpr_inf_future(GPR_CLOCK_REALTIME),
254                                     nullptr)
255              .tag != (void*)(1000)) {
256   }
257   grpc_server_destroy(server);
258 }
259
260 void VerifyChannelReady(grpc_channel* channel, grpc_completion_queue* cq) {
261   grpc_connectivity_state state =
262       grpc_channel_check_connectivity_state(channel, 1 /* try_to_connect */);
263   while (state != GRPC_CHANNEL_READY) {
264     grpc_channel_watch_connectivity_state(
265         channel, state, grpc_timeout_seconds_to_deadline(5), cq, nullptr);
266     grpc_completion_queue_next(cq, grpc_timeout_seconds_to_deadline(5),
267                                nullptr);
268     state = grpc_channel_check_connectivity_state(channel, 0);
269   }
270 }
271
272 void VerifyChannelDisconnected(grpc_channel* channel,
273                                grpc_completion_queue* cq) {
274   // Verify channel gets disconnected. Use a ping to make sure that clients
275   // tries sending/receiving bytes if the channel is connected.
276   grpc_channel_ping(channel, cq, (void*)(2000), nullptr);
277   grpc_event ev = grpc_completion_queue_next(
278       cq, grpc_timeout_seconds_to_deadline(5), nullptr);
279   GPR_ASSERT(ev.type == GRPC_OP_COMPLETE);
280   GPR_ASSERT(ev.tag == (void*)(2000));
281   GPR_ASSERT(ev.success == 0);
282   GPR_ASSERT(grpc_channel_check_connectivity_state(channel, 0) !=
283              GRPC_CHANNEL_READY);
284 }
285
286 class KeepaliveThrottlingTest : public ::testing::Test {
287  protected:
288   // Starts the server and makes sure that the channel is able to get connected.
289   grpc_server* ServerStart(const char* addr, grpc_completion_queue* cq) {
290     // Set up server channel args to expect pings at an interval of 5 seconds
291     // and use a single ping strike
292     grpc_arg server_args[] = {
293         grpc_channel_arg_integer_create(
294             const_cast<char*>(
295                 GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS),
296             5 * 1000),
297         grpc_channel_arg_integer_create(
298             const_cast<char*>(GRPC_ARG_HTTP2_MAX_PING_STRIKES), 1)};
299     grpc_channel_args server_channel_args = {GPR_ARRAY_SIZE(server_args),
300                                              server_args};
301     // Create server
302     grpc_server* server = grpc_server_create(&server_channel_args, nullptr);
303     grpc_server_register_completion_queue(server, cq, nullptr);
304     GPR_ASSERT(grpc_server_add_insecure_http2_port(server, addr));
305     grpc_server_start(server);
306     return server;
307   }
308 };
309
310 TEST_F(KeepaliveThrottlingTest, KeepaliveThrottlingMultipleChannels) {
311   grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
312   std::string server_address =
313       grpc_core::JoinHostPort("127.0.0.1", grpc_pick_unused_port_or_die());
314   grpc_server* server = ServerStart(server_address.c_str(), cq);
315   // create two channel with a keepalive ping interval of 1 second.
316   grpc_arg client_args[] = {
317       grpc_channel_arg_integer_create(
318           const_cast<char*>(GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA), 0),
319       grpc_channel_arg_integer_create(
320           const_cast<char*>(GRPC_ARG_KEEPALIVE_TIME_MS), 1 * 1000),
321       grpc_channel_arg_integer_create(
322           const_cast<char*>(GRPC_ARG_HTTP2_BDP_PROBE), 0)};
323   grpc_channel_args client_channel_args = {GPR_ARRAY_SIZE(client_args),
324                                            client_args};
325   grpc_channel* channel = grpc_insecure_channel_create(
326       server_address.c_str(), &client_channel_args, nullptr);
327   grpc_channel* channel_dup = grpc_insecure_channel_create(
328       server_address.c_str(), &client_channel_args, nullptr);
329   int expected_keepalive_time_sec = 1;
330   // We need 3 GOAWAY frames to throttle the keepalive time from 1 second to 8
331   // seconds (> 5sec).
332   for (int i = 0; i < 3; i++) {
333     gpr_log(GPR_INFO, "Expected keepalive time : %d",
334             expected_keepalive_time_sec);
335     EXPECT_EQ(PerformWaitingCall(channel, server, cq), GRPC_STATUS_UNAVAILABLE);
336     expected_keepalive_time_sec *= 2;
337   }
338   gpr_log(
339       GPR_INFO,
340       "Client keepalive time %d should now be in sync with the server settings",
341       expected_keepalive_time_sec);
342   EXPECT_EQ(PerformWaitingCall(channel, server, cq),
343             GRPC_STATUS_DEADLINE_EXCEEDED);
344   // Since the subchannel is shared, the second channel should also have
345   // keepalive settings in sync with the server.
346   gpr_log(GPR_INFO, "Now testing second channel sharing the same subchannel");
347   EXPECT_EQ(PerformWaitingCall(channel_dup, server, cq),
348             GRPC_STATUS_DEADLINE_EXCEEDED);
349   // shutdown and destroy the client and server
350   grpc_channel_destroy(channel);
351   grpc_channel_destroy(channel_dup);
352   ServerShutdownAndDestroy(server, cq);
353   grpc_completion_queue_shutdown(cq);
354   while (grpc_completion_queue_next(cq, gpr_inf_future(GPR_CLOCK_REALTIME),
355                                     nullptr)
356              .type != GRPC_QUEUE_SHUTDOWN) {
357   }
358   grpc_completion_queue_destroy(cq);
359 }
360
361 grpc_core::Resolver::Result BuildResolverResult(
362     const std::vector<std::string>& addresses) {
363   grpc_core::Resolver::Result result;
364   for (const auto& address_str : addresses) {
365     grpc_uri* uri = grpc_uri_parse(address_str.c_str(), true);
366     if (uri == nullptr) {
367       gpr_log(GPR_ERROR, "Failed to parse uri:%s", address_str.c_str());
368       GPR_ASSERT(0);
369     }
370     grpc_resolved_address address;
371     GPR_ASSERT(grpc_parse_uri(uri, &address));
372     result.addresses.emplace_back(address.addr, address.len, nullptr);
373     grpc_uri_destroy(uri);
374   }
375   return result;
376 }
377
378 // Tests that when new subchannels are created due to a change in resolved
379 // addresses, the new subchannels use the updated keepalive time.
380 TEST_F(KeepaliveThrottlingTest, NewSubchannelsUseUpdatedKeepaliveTime) {
381   grpc_core::ExecCtx exec_ctx;
382   grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
383   std::string server_address1 =
384       grpc_core::JoinHostPort("127.0.0.1", grpc_pick_unused_port_or_die());
385   std::string server_address2 =
386       grpc_core::JoinHostPort("127.0.0.1", grpc_pick_unused_port_or_die());
387   grpc_server* server1 = ServerStart(server_address1.c_str(), cq);
388   grpc_server* server2 = ServerStart(server_address2.c_str(), cq);
389   // create a single channel with multiple subchannels with a keepalive ping
390   // interval of 1 second. To get finer control on subchannel connection times,
391   // we are using pick_first instead of round_robin and using the fake resolver
392   // response generator to switch between the two.
393   auto response_generator =
394       grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
395   grpc_arg client_args[] = {
396       grpc_channel_arg_integer_create(
397           const_cast<char*>(GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA), 0),
398       grpc_channel_arg_integer_create(
399           const_cast<char*>(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS), 0),
400       grpc_channel_arg_integer_create(
401           const_cast<char*>(GRPC_ARG_KEEPALIVE_TIME_MS), 1 * 1000),
402       grpc_channel_arg_integer_create(
403           const_cast<char*>(GRPC_ARG_HTTP2_BDP_PROBE), 0),
404       grpc_core::FakeResolverResponseGenerator::MakeChannelArg(
405           response_generator.get())};
406   grpc_channel_args client_channel_args = {GPR_ARRAY_SIZE(client_args),
407                                            client_args};
408   grpc_channel* channel =
409       grpc_insecure_channel_create("fake:///", &client_channel_args, nullptr);
410   // For a single subchannel 3 GOAWAYs would be sufficient to increase the
411   // keepalive time from 1 second to beyond 5 seconds. Even though we are
412   // alternating between two subchannels, 3 GOAWAYs should still be enough since
413   // the channel should start all new transports with the new keepalive value
414   // (even those from a different subchannel).
415   int expected_keepalive_time_sec = 1;
416   for (int i = 0; i < 3; i++) {
417     gpr_log(GPR_INFO, "Expected keepalive time : %d",
418             expected_keepalive_time_sec);
419     response_generator->SetResponse(BuildResolverResult({absl::StrCat(
420         "ipv4:", i % 2 == 0 ? server_address1 : server_address2)}));
421     // ExecCtx::Flush() might not be enough to make sure that the resolver
422     // result has been propagated, so sleep for a bit.
423     grpc_core::ExecCtx::Get()->Flush();
424     gpr_sleep_until(grpc_timeout_seconds_to_deadline(1));
425     EXPECT_EQ(PerformWaitingCall(channel, i % 2 == 0 ? server1 : server2, cq),
426               GRPC_STATUS_UNAVAILABLE);
427     expected_keepalive_time_sec *= 2;
428   }
429   gpr_log(
430       GPR_INFO,
431       "Client keepalive time %d should now be in sync with the server settings",
432       expected_keepalive_time_sec);
433   response_generator->SetResponse(
434       BuildResolverResult({absl::StrCat("ipv4:", server_address2)}));
435   grpc_core::ExecCtx::Get()->Flush();
436   gpr_sleep_until(grpc_timeout_seconds_to_deadline(1));
437   EXPECT_EQ(PerformWaitingCall(channel, server2, cq),
438             GRPC_STATUS_DEADLINE_EXCEEDED);
439   // shutdown and destroy the client and server
440   grpc_channel_destroy(channel);
441   ServerShutdownAndDestroy(server1, cq);
442   ServerShutdownAndDestroy(server2, cq);
443   grpc_completion_queue_shutdown(cq);
444   while (grpc_completion_queue_next(cq, gpr_inf_future(GPR_CLOCK_REALTIME),
445                                     nullptr)
446              .type != GRPC_QUEUE_SHUTDOWN) {
447   }
448   grpc_completion_queue_destroy(cq);
449 }
450
451 // Tests that when a channel has multiple subchannels and receives a GOAWAY with
452 // "too_many_pings" on one of them, all subchannels start any new transports
453 // with an updated keepalive time.
454 TEST_F(KeepaliveThrottlingTest,
455        ExistingSubchannelsUseNewKeepaliveTimeWhenReconnecting) {
456   grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
457   std::string server_address1 =
458       grpc_core::JoinHostPort("127.0.0.1", grpc_pick_unused_port_or_die());
459   std::string server_address2 =
460       grpc_core::JoinHostPort("127.0.0.1", grpc_pick_unused_port_or_die());
461   // create a single channel with round robin load balancing policy.
462   auto response_generator =
463       grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
464   grpc_arg client_args[] = {
465       grpc_channel_arg_integer_create(
466           const_cast<char*>(GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA), 0),
467       grpc_channel_arg_integer_create(
468           const_cast<char*>(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS), 0),
469       grpc_channel_arg_integer_create(
470           const_cast<char*>(GRPC_ARG_KEEPALIVE_TIME_MS), 1 * 1000),
471       grpc_channel_arg_integer_create(
472           const_cast<char*>(GRPC_ARG_HTTP2_BDP_PROBE), 0),
473       grpc_core::FakeResolverResponseGenerator::MakeChannelArg(
474           response_generator.get())};
475   grpc_channel_args client_channel_args = {GPR_ARRAY_SIZE(client_args),
476                                            client_args};
477   grpc_channel* channel =
478       grpc_insecure_channel_create("fake:///", &client_channel_args, nullptr);
479   response_generator->SetResponse(
480       BuildResolverResult({absl::StrCat("ipv4:", server_address1),
481                            absl::StrCat("ipv4:", server_address2)}));
482   // For a single subchannel 3 GOAWAYs would be sufficient to increase the
483   // keepalive time from 1 second to beyond 5 seconds. Even though we are
484   // alternating between two subchannels, 3 GOAWAYs should still be enough since
485   // the channel should start all new transports with the new keepalive value
486   // (even those from a different subchannel).
487   int expected_keepalive_time_sec = 1;
488   for (int i = 0; i < 3; i++) {
489     gpr_log(GPR_ERROR, "Expected keepalive time : %d",
490             expected_keepalive_time_sec);
491     grpc_server* server = ServerStart(
492         i % 2 == 0 ? server_address1.c_str() : server_address2.c_str(), cq);
493     VerifyChannelReady(channel, cq);
494     EXPECT_EQ(PerformWaitingCall(channel, server, cq), GRPC_STATUS_UNAVAILABLE);
495     ServerShutdownAndDestroy(server, cq);
496     VerifyChannelDisconnected(channel, cq);
497     expected_keepalive_time_sec *= 2;
498   }
499   gpr_log(
500       GPR_INFO,
501       "Client keepalive time %d should now be in sync with the server settings",
502       expected_keepalive_time_sec);
503   grpc_server* server = ServerStart(server_address1.c_str(), cq);
504   VerifyChannelReady(channel, cq);
505   EXPECT_EQ(PerformWaitingCall(channel, server, cq),
506             GRPC_STATUS_DEADLINE_EXCEEDED);
507   ServerShutdownAndDestroy(server, cq);
508   // shutdown and destroy the client
509   grpc_channel_destroy(channel);
510   grpc_completion_queue_shutdown(cq);
511   while (grpc_completion_queue_next(cq, gpr_inf_future(GPR_CLOCK_REALTIME),
512                                     nullptr)
513              .type != GRPC_QUEUE_SHUTDOWN) {
514   }
515   grpc_completion_queue_destroy(cq);
516 }
517
518 // Perform a simple RPC where the client makes a request expecting a response
519 // with payload.
520 void PerformCallWithResponsePayload(grpc_channel* channel, grpc_server* server,
521                                     grpc_completion_queue* cq) {
522   grpc_slice response_payload_slice = grpc_slice_from_static_string("hello");
523
524   grpc_call* c;
525   grpc_call* s;
526   grpc_byte_buffer* response_payload =
527       grpc_raw_byte_buffer_create(&response_payload_slice, 1);
528   cq_verifier* cqv = cq_verifier_create(cq);
529   grpc_op ops[6];
530   grpc_op* op;
531   grpc_metadata_array initial_metadata_recv;
532   grpc_metadata_array trailing_metadata_recv;
533   grpc_metadata_array request_metadata_recv;
534   grpc_byte_buffer* response_payload_recv = nullptr;
535   grpc_call_details call_details;
536   grpc_status_code status;
537   grpc_call_error error;
538   grpc_slice details;
539   int was_cancelled = 2;
540
541   gpr_timespec deadline = grpc_timeout_seconds_to_deadline(60);
542   c = grpc_channel_create_call(channel, nullptr, GRPC_PROPAGATE_DEFAULTS, cq,
543                                grpc_slice_from_static_string("/foo"), nullptr,
544                                deadline, nullptr);
545   GPR_ASSERT(c);
546
547   grpc_metadata_array_init(&initial_metadata_recv);
548   grpc_metadata_array_init(&trailing_metadata_recv);
549   grpc_metadata_array_init(&request_metadata_recv);
550   grpc_call_details_init(&call_details);
551
552   memset(ops, 0, sizeof(ops));
553   op = ops;
554   op->op = GRPC_OP_SEND_INITIAL_METADATA;
555   op->data.send_initial_metadata.count = 0;
556   op->flags = 0;
557   op->reserved = nullptr;
558   op++;
559   op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT;
560   op->flags = 0;
561   op->reserved = nullptr;
562   op++;
563   op->op = GRPC_OP_RECV_INITIAL_METADATA;
564   op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv;
565   op->flags = 0;
566   op->reserved = nullptr;
567   op++;
568   op->op = GRPC_OP_RECV_MESSAGE;
569   op->data.recv_message.recv_message = &response_payload_recv;
570   op->flags = 0;
571   op->reserved = nullptr;
572   op++;
573   op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
574   op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;
575   op->data.recv_status_on_client.status = &status;
576   op->data.recv_status_on_client.status_details = &details;
577   op->flags = 0;
578   op->reserved = nullptr;
579   op++;
580   error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(1),
581                                 nullptr);
582   GPR_ASSERT(GRPC_CALL_OK == error);
583
584   error = grpc_server_request_call(server, &s, &call_details,
585                                    &request_metadata_recv, cq, cq, tag(101));
586   GPR_ASSERT(GRPC_CALL_OK == error);
587   CQ_EXPECT_COMPLETION(cqv, tag(101), 1);
588   cq_verify(cqv);
589
590   memset(ops, 0, sizeof(ops));
591   op = ops;
592   op->op = GRPC_OP_SEND_INITIAL_METADATA;
593   op->data.send_initial_metadata.count = 0;
594   op->flags = 0;
595   op->reserved = nullptr;
596   op++;
597   error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), tag(102),
598                                 nullptr);
599   GPR_ASSERT(GRPC_CALL_OK == error);
600
601   CQ_EXPECT_COMPLETION(cqv, tag(102), 1);
602   cq_verify(cqv);
603
604   memset(ops, 0, sizeof(ops));
605   op = ops;
606   op->op = GRPC_OP_RECV_CLOSE_ON_SERVER;
607   op->data.recv_close_on_server.cancelled = &was_cancelled;
608   op->flags = 0;
609   op->reserved = nullptr;
610   op++;
611   op->op = GRPC_OP_SEND_MESSAGE;
612   op->data.send_message.send_message = response_payload;
613   op->flags = 0;
614   op->reserved = nullptr;
615   op++;
616   op->op = GRPC_OP_SEND_STATUS_FROM_SERVER;
617   op->data.send_status_from_server.trailing_metadata_count = 0;
618   op->data.send_status_from_server.status = GRPC_STATUS_OK;
619   grpc_slice status_details = grpc_slice_from_static_string("xyz");
620   op->data.send_status_from_server.status_details = &status_details;
621   op->flags = 0;
622   op->reserved = nullptr;
623   op++;
624   error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), tag(103),
625                                 nullptr);
626   GPR_ASSERT(GRPC_CALL_OK == error);
627
628   CQ_EXPECT_COMPLETION(cqv, tag(103), 1);
629   CQ_EXPECT_COMPLETION(cqv, tag(1), 1);
630   cq_verify(cqv);
631
632   GPR_ASSERT(status == GRPC_STATUS_OK);
633   GPR_ASSERT(0 == grpc_slice_str_cmp(details, "xyz"));
634   GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, "/foo"));
635   GPR_ASSERT(was_cancelled == 0);
636   GPR_ASSERT(
637       byte_buffer_eq_slice(response_payload_recv, response_payload_slice));
638
639   grpc_slice_unref(details);
640   grpc_metadata_array_destroy(&initial_metadata_recv);
641   grpc_metadata_array_destroy(&trailing_metadata_recv);
642   grpc_metadata_array_destroy(&request_metadata_recv);
643   grpc_call_details_destroy(&call_details);
644
645   grpc_call_unref(c);
646   grpc_call_unref(s);
647
648   cq_verifier_destroy(cqv);
649
650   grpc_byte_buffer_destroy(response_payload);
651   grpc_byte_buffer_destroy(response_payload_recv);
652 }
653
654 TEST(TooManyPings, BdpPingNotSentWithoutReceiveSideActivity) {
655   grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
656   // create the server
657   std::string server_address =
658       grpc_core::JoinHostPort("localhost", grpc_pick_unused_port_or_die());
659   grpc_arg server_args[] = {
660       grpc_channel_arg_integer_create(
661           const_cast<char*>(
662               GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS),
663           60 * 1000),
664       grpc_channel_arg_integer_create(
665           const_cast<char*>(GRPC_ARG_HTTP2_MAX_PING_STRIKES), 1)};
666   grpc_channel_args server_channel_args = {GPR_ARRAY_SIZE(server_args),
667                                            server_args};
668   grpc_server* server = grpc_server_create(&server_channel_args, nullptr);
669   grpc_server_register_completion_queue(server, cq, nullptr);
670   GPR_ASSERT(
671       grpc_server_add_insecure_http2_port(server, server_address.c_str()));
672   grpc_server_start(server);
673   // create the channel (bdp pings are enabled by default)
674   grpc_arg client_args[] = {
675       grpc_channel_arg_integer_create(
676           const_cast<char*>(GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA), 0),
677       grpc_channel_arg_integer_create(
678           const_cast<char*>(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS), 1)};
679   grpc_channel_args client_channel_args = {GPR_ARRAY_SIZE(client_args),
680                                            client_args};
681   grpc_channel* channel = grpc_insecure_channel_create(
682       server_address.c_str(), &client_channel_args, nullptr);
683   VerifyChannelReady(channel, cq);
684   cq_verifier* cqv = cq_verifier_create(cq);
685   cq_verify_empty_timeout(cqv, 1);
686   // Channel should be able to send two pings without disconnect if there was no
687   // BDP sent.
688   grpc_channel_ping(channel, cq, tag(1), nullptr);
689   CQ_EXPECT_COMPLETION(cqv, tag(1), 1);
690   cq_verify(cqv, 5);
691   // Second ping
692   grpc_channel_ping(channel, cq, tag(2), nullptr);
693   CQ_EXPECT_COMPLETION(cqv, tag(2), 1);
694   cq_verify(cqv, 5);
695   ASSERT_EQ(grpc_channel_check_connectivity_state(channel, 0),
696             GRPC_CHANNEL_READY);
697   PerformCallWithResponsePayload(channel, server, cq);
698   // Wait a bit to make sure that the BDP ping goes out.
699   cq_verify_empty_timeout(cqv, 1);
700   // The call with a response payload should have triggered a BDP ping.
701   // Send two more pings to verify. The second ping should cause a disconnect.
702   // If BDP was not sent, the second ping would not cause a disconnect.
703   grpc_channel_ping(channel, cq, tag(3), nullptr);
704   CQ_EXPECT_COMPLETION(cqv, tag(3), 1);
705   cq_verify(cqv, 5);
706   // Second ping
707   grpc_channel_ping(channel, cq, tag(4), nullptr);
708   CQ_EXPECT_COMPLETION(cqv, tag(4), 1);
709   cq_verify(cqv, 5);
710   cq_verify_empty_timeout(cqv, 1);
711   ASSERT_NE(grpc_channel_check_connectivity_state(channel, 0),
712             GRPC_CHANNEL_READY);
713   cq_verifier_destroy(cqv);
714   // shutdown and destroy the client and server
715   ServerShutdownAndDestroy(server, cq);
716   grpc_channel_destroy(channel);
717   grpc_completion_queue_shutdown(cq);
718   while (grpc_completion_queue_next(cq, gpr_inf_future(GPR_CLOCK_REALTIME),
719                                     nullptr)
720              .type != GRPC_QUEUE_SHUTDOWN) {
721   }
722   grpc_completion_queue_destroy(cq);
723 }
724
725 }  // namespace
726
727 int main(int argc, char** argv) {
728   ::testing::InitGoogleTest(&argc, argv);
729   grpc::testing::TestEnvironment env(argc, argv);
730   grpc_init();
731   auto result = RUN_ALL_TESTS();
732   grpc_shutdown();
733   return result;
734 }