Imported Upstream version 1.33.1
[platform/upstream/grpc.git] / test / cpp / naming / cancel_ares_query_test.cc
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 <stdio.h>
20 #include <string.h>
21
22 #include <string>
23
24 #include "absl/strings/str_cat.h"
25 #include "absl/strings/str_format.h"
26
27 #include <gflags/gflags.h>
28 #include <gmock/gmock.h>
29
30 #include <grpc/byte_buffer.h>
31 #include <grpc/grpc.h>
32 #include <grpc/support/alloc.h>
33 #include <grpc/support/log.h>
34 #include <grpc/support/time.h>
35
36 #include "src/core/ext/filters/client_channel/resolver.h"
37 #include "src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h"
38 #include "src/core/ext/filters/client_channel/resolver_registry.h"
39 #include "src/core/lib/channel/channel_args.h"
40 #include "src/core/lib/debug/stats.h"
41 #include "src/core/lib/gpr/string.h"
42 #include "src/core/lib/gprpp/orphanable.h"
43 #include "src/core/lib/gprpp/thd.h"
44 #include "src/core/lib/iomgr/pollset.h"
45 #include "src/core/lib/iomgr/pollset_set.h"
46 #include "src/core/lib/iomgr/work_serializer.h"
47 #include "test/core/end2end/cq_verifier.h"
48 #include "test/core/util/cmdline.h"
49 #include "test/core/util/port.h"
50 #include "test/core/util/test_config.h"
51 #include "test/cpp/naming/dns_test_util.h"
52
53 #ifdef GPR_WINDOWS
54 #include "src/core/lib/iomgr/sockaddr_windows.h"
55 #include "src/core/lib/iomgr/socket_windows.h"
56 #define BAD_SOCKET_RETURN_VAL INVALID_SOCKET
57 #else
58 #include "src/core/lib/iomgr/sockaddr_posix.h"
59 #define BAD_SOCKET_RETURN_VAL -1
60 #endif
61
62 namespace {
63
64 void* Tag(intptr_t t) { return (void*)t; }
65
66 gpr_timespec FiveSecondsFromNow(void) {
67   return grpc_timeout_seconds_to_deadline(5);
68 }
69
70 void DrainCq(grpc_completion_queue* cq) {
71   grpc_event ev;
72   do {
73     ev = grpc_completion_queue_next(cq, FiveSecondsFromNow(), nullptr);
74   } while (ev.type != GRPC_QUEUE_SHUTDOWN);
75 }
76
77 void EndTest(grpc_channel* client, grpc_completion_queue* cq) {
78   grpc_channel_destroy(client);
79   grpc_completion_queue_shutdown(cq);
80   DrainCq(cq);
81   grpc_completion_queue_destroy(cq);
82 }
83
84 struct ArgsStruct {
85   gpr_atm done_atm;
86   gpr_mu* mu;
87   grpc_pollset* pollset;
88   grpc_pollset_set* pollset_set;
89   std::shared_ptr<grpc_core::WorkSerializer> lock;
90   grpc_channel_args* channel_args;
91 };
92
93 void ArgsInit(ArgsStruct* args) {
94   args->pollset = (grpc_pollset*)gpr_zalloc(grpc_pollset_size());
95   grpc_pollset_init(args->pollset, &args->mu);
96   args->pollset_set = grpc_pollset_set_create();
97   grpc_pollset_set_add_pollset(args->pollset_set, args->pollset);
98   args->lock = std::make_shared<grpc_core::WorkSerializer>();
99   gpr_atm_rel_store(&args->done_atm, 0);
100   args->channel_args = nullptr;
101 }
102
103 void DoNothing(void* /*arg*/, grpc_error* /*error*/) {}
104
105 void ArgsFinish(ArgsStruct* args) {
106   grpc_pollset_set_del_pollset(args->pollset_set, args->pollset);
107   grpc_pollset_set_destroy(args->pollset_set);
108   grpc_closure DoNothing_cb;
109   GRPC_CLOSURE_INIT(&DoNothing_cb, DoNothing, nullptr,
110                     grpc_schedule_on_exec_ctx);
111   grpc_pollset_shutdown(args->pollset, &DoNothing_cb);
112   // exec_ctx needs to be flushed before calling grpc_pollset_destroy()
113   grpc_channel_args_destroy(args->channel_args);
114   grpc_core::ExecCtx::Get()->Flush();
115   grpc_pollset_destroy(args->pollset);
116   gpr_free(args->pollset);
117 }
118
119 void PollPollsetUntilRequestDone(ArgsStruct* args) {
120   while (true) {
121     bool done = gpr_atm_acq_load(&args->done_atm) != 0;
122     if (done) {
123       break;
124     }
125     grpc_pollset_worker* worker = nullptr;
126     grpc_core::ExecCtx exec_ctx;
127     gpr_mu_lock(args->mu);
128     GRPC_LOG_IF_ERROR(
129         "pollset_work",
130         grpc_pollset_work(args->pollset, &worker,
131                           grpc_timespec_to_millis_round_up(
132                               gpr_inf_future(GPR_CLOCK_REALTIME))));
133     gpr_mu_unlock(args->mu);
134   }
135 }
136
137 class AssertFailureResultHandler : public grpc_core::Resolver::ResultHandler {
138  public:
139   explicit AssertFailureResultHandler(ArgsStruct* args) : args_(args) {}
140
141   ~AssertFailureResultHandler() override {
142     gpr_atm_rel_store(&args_->done_atm, 1);
143     gpr_mu_lock(args_->mu);
144     GRPC_LOG_IF_ERROR("pollset_kick",
145                       grpc_pollset_kick(args_->pollset, nullptr));
146     gpr_mu_unlock(args_->mu);
147   }
148
149   void ReturnResult(grpc_core::Resolver::Result /*result*/) override {
150     GPR_ASSERT(false);
151   }
152
153   void ReturnError(grpc_error* /*error*/) override { GPR_ASSERT(false); }
154
155  private:
156   ArgsStruct* args_;
157 };
158
159 void TestCancelActiveDNSQuery(ArgsStruct* args) {
160   int fake_dns_port = grpc_pick_unused_port_or_die();
161   grpc::testing::FakeNonResponsiveDNSServer fake_dns_server(fake_dns_port);
162   std::string client_target = absl::StrFormat(
163       "dns://[::1]:%d/dont-care-since-wont-be-resolved.test.com:1234",
164       fake_dns_port);
165   // create resolver and resolve
166   grpc_core::OrphanablePtr<grpc_core::Resolver> resolver =
167       grpc_core::ResolverRegistry::CreateResolver(
168           client_target.c_str(), nullptr, args->pollset_set, args->lock,
169           std::unique_ptr<grpc_core::Resolver::ResultHandler>(
170               new AssertFailureResultHandler(args)));
171   resolver->StartLocked();
172   // Without resetting and causing resolver shutdown, the
173   // PollPollsetUntilRequestDone call should never finish.
174   resolver.reset();
175   grpc_core::ExecCtx::Get()->Flush();
176   PollPollsetUntilRequestDone(args);
177   ArgsFinish(args);
178 }
179
180 class CancelDuringAresQuery : public ::testing::Test {
181  protected:
182   static void SetUpTestCase() {
183     GPR_GLOBAL_CONFIG_SET(grpc_dns_resolver, "ares");
184     // Sanity check the time that it takes to run the test
185     // including the teardown time (the teardown
186     // part of the test involves cancelling the DNS query,
187     // which is the main point of interest for this test).
188     overall_deadline = grpc_timeout_seconds_to_deadline(4);
189     grpc_init();
190   }
191
192   static void TearDownTestCase() {
193     grpc_shutdown();
194     if (gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), overall_deadline) > 0) {
195       gpr_log(GPR_ERROR, "Test took too long");
196       abort();
197     }
198   }
199
200  private:
201   static gpr_timespec overall_deadline;
202 };
203 gpr_timespec CancelDuringAresQuery::overall_deadline;
204
205 TEST_F(CancelDuringAresQuery, TestCancelActiveDNSQuery) {
206   grpc_core::ExecCtx exec_ctx;
207   ArgsStruct args;
208   ArgsInit(&args);
209   TestCancelActiveDNSQuery(&args);
210 }
211
212 #ifdef GPR_WINDOWS
213
214 void MaybePollArbitraryPollsetTwice() {
215   grpc_pollset* pollset = (grpc_pollset*)gpr_zalloc(grpc_pollset_size());
216   gpr_mu* mu;
217   grpc_pollset_init(pollset, &mu);
218   grpc_pollset_worker* worker = nullptr;
219   // Make a zero timeout poll
220   gpr_mu_lock(mu);
221   GRPC_LOG_IF_ERROR(
222       "pollset_work",
223       grpc_pollset_work(pollset, &worker, grpc_core::ExecCtx::Get()->Now()));
224   gpr_mu_unlock(mu);
225   grpc_core::ExecCtx::Get()->Flush();
226   // Make a second zero-timeout poll (in case the first one
227   // short-circuited by picking up a previous "kick")
228   gpr_mu_lock(mu);
229   GRPC_LOG_IF_ERROR(
230       "pollset_work",
231       grpc_pollset_work(pollset, &worker, grpc_core::ExecCtx::Get()->Now()));
232   gpr_mu_unlock(mu);
233   grpc_core::ExecCtx::Get()->Flush();
234   grpc_pollset_destroy(pollset);
235   gpr_free(pollset);
236 }
237
238 #else
239
240 void MaybePollArbitraryPollsetTwice() {}
241
242 #endif
243
244 TEST_F(CancelDuringAresQuery, TestFdsAreDeletedFromPollsetSet) {
245   grpc_core::ExecCtx exec_ctx;
246   ArgsStruct args;
247   ArgsInit(&args);
248   // Add fake_other_pollset_set into the mix to test
249   // that we're explicitly deleting fd's from their pollset.
250   // If we aren't doing so, then the remaining presence of
251   // "fake_other_pollset_set" after the request is done and the resolver
252   // pollset set is destroyed should keep the resolver's fd alive and
253   // fail the test.
254   grpc_pollset_set* fake_other_pollset_set = grpc_pollset_set_create();
255   grpc_pollset_set_add_pollset_set(fake_other_pollset_set, args.pollset_set);
256   // Note that running the cancellation c-ares test is somewhat irrelevant for
257   // this test. This test only cares about what happens to fd's that c-ares
258   // opens.
259   TestCancelActiveDNSQuery(&args);
260   // This test relies on the assumption that cancelling a c-ares query
261   // will flush out all callbacks on the current exec ctx, which is true
262   // on posix platforms but not on Windows, because fd shutdown on Windows
263   // requires a trip through the polling loop to schedule the callback.
264   // So we need to do extra polling work on Windows to free things up.
265   MaybePollArbitraryPollsetTwice();
266   EXPECT_EQ(grpc_iomgr_count_objects_for_testing(), 0u);
267   grpc_pollset_set_destroy(fake_other_pollset_set);
268 }
269
270 // Settings for TestCancelDuringActiveQuery test
271 typedef enum {
272   NONE,
273   SHORT,
274   ZERO,
275 } cancellation_test_query_timeout_setting;
276
277 void TestCancelDuringActiveQuery(
278     cancellation_test_query_timeout_setting query_timeout_setting) {
279   // Start up fake non responsive DNS server
280   int fake_dns_port = grpc_pick_unused_port_or_die();
281   grpc::testing::FakeNonResponsiveDNSServer fake_dns_server(fake_dns_port);
282   // Create a call that will try to use the fake DNS server
283   std::string client_target = absl::StrFormat(
284       "dns://[::1]:%d/dont-care-since-wont-be-resolved.test.com:1234",
285       fake_dns_port);
286   gpr_log(GPR_DEBUG, "TestCancelActiveDNSQuery. query timeout setting: %d",
287           query_timeout_setting);
288   grpc_channel_args* client_args = nullptr;
289   grpc_status_code expected_status_code = GRPC_STATUS_OK;
290   gpr_timespec rpc_deadline;
291   if (query_timeout_setting == NONE) {
292     // The RPC deadline should go off well before the DNS resolution
293     // timeout fires.
294     expected_status_code = GRPC_STATUS_DEADLINE_EXCEEDED;
295     // use default DNS resolution timeout (which is over one minute).
296     client_args = nullptr;
297     rpc_deadline = grpc_timeout_milliseconds_to_deadline(100);
298   } else if (query_timeout_setting == SHORT) {
299     // The DNS resolution timeout should fire well before the
300     // RPC's deadline expires.
301     expected_status_code = GRPC_STATUS_UNAVAILABLE;
302     grpc_arg arg;
303     arg.type = GRPC_ARG_INTEGER;
304     arg.key = const_cast<char*>(GRPC_ARG_DNS_ARES_QUERY_TIMEOUT_MS);
305     arg.value.integer =
306         1;  // Set this shorter than the call deadline so that it goes off.
307     client_args = grpc_channel_args_copy_and_add(nullptr, &arg, 1);
308     // Set the deadline high enough such that if we hit this and get
309     // a deadline exceeded status code, then we are confident that there's
310     // a bug causing cancellation of DNS resolutions to not happen in a timely
311     // manner.
312     rpc_deadline = grpc_timeout_seconds_to_deadline(10);
313   } else if (query_timeout_setting == ZERO) {
314     // The RPC deadline should go off well before the DNS resolution
315     // timeout fires.
316     expected_status_code = GRPC_STATUS_DEADLINE_EXCEEDED;
317     grpc_arg arg;
318     arg.type = GRPC_ARG_INTEGER;
319     arg.key = const_cast<char*>(GRPC_ARG_DNS_ARES_QUERY_TIMEOUT_MS);
320     arg.value.integer = 0;  // Set this to zero to disable query timeouts.
321     client_args = grpc_channel_args_copy_and_add(nullptr, &arg, 1);
322     rpc_deadline = grpc_timeout_milliseconds_to_deadline(100);
323   } else {
324     abort();
325   }
326   grpc_channel* client =
327       grpc_insecure_channel_create(client_target.c_str(), client_args, nullptr);
328   grpc_completion_queue* cq = grpc_completion_queue_create_for_next(nullptr);
329   cq_verifier* cqv = cq_verifier_create(cq);
330   grpc_call* call = grpc_channel_create_call(
331       client, nullptr, GRPC_PROPAGATE_DEFAULTS, cq,
332       grpc_slice_from_static_string("/foo"), nullptr, rpc_deadline, nullptr);
333   GPR_ASSERT(call);
334   grpc_metadata_array initial_metadata_recv;
335   grpc_metadata_array trailing_metadata_recv;
336   grpc_metadata_array request_metadata_recv;
337   grpc_metadata_array_init(&initial_metadata_recv);
338   grpc_metadata_array_init(&trailing_metadata_recv);
339   grpc_metadata_array_init(&request_metadata_recv);
340   grpc_call_details call_details;
341   grpc_call_details_init(&call_details);
342   grpc_status_code status;
343   const char* error_string;
344   grpc_slice details;
345   // Set ops for client the request
346   grpc_op ops_base[6];
347   memset(ops_base, 0, sizeof(ops_base));
348   grpc_op* op = ops_base;
349   op->op = GRPC_OP_SEND_INITIAL_METADATA;
350   op->data.send_initial_metadata.count = 0;
351   op->flags = 0;
352   op->reserved = nullptr;
353   op++;
354   op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT;
355   op->flags = 0;
356   op->reserved = nullptr;
357   op++;
358   op->op = GRPC_OP_RECV_INITIAL_METADATA;
359   op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv;
360   op->flags = 0;
361   op->reserved = nullptr;
362   op++;
363   op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
364   op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv;
365   op->data.recv_status_on_client.status = &status;
366   op->data.recv_status_on_client.status_details = &details;
367   op->data.recv_status_on_client.error_string = &error_string;
368   op->flags = 0;
369   op->reserved = nullptr;
370   op++;
371   // Run the call and sanity check it failed as expected
372   grpc_call_error error = grpc_call_start_batch(
373       call, ops_base, static_cast<size_t>(op - ops_base), Tag(1), nullptr);
374   EXPECT_EQ(GRPC_CALL_OK, error);
375   CQ_EXPECT_COMPLETION(cqv, Tag(1), 1);
376   cq_verify(cqv);
377   EXPECT_EQ(status, expected_status_code);
378   // Teardown
379   grpc_channel_args_destroy(client_args);
380   grpc_slice_unref(details);
381   gpr_free((void*)error_string);
382   grpc_metadata_array_destroy(&initial_metadata_recv);
383   grpc_metadata_array_destroy(&trailing_metadata_recv);
384   grpc_metadata_array_destroy(&request_metadata_recv);
385   grpc_call_details_destroy(&call_details);
386   grpc_call_unref(call);
387   cq_verifier_destroy(cqv);
388   EndTest(client, cq);
389 }
390
391 TEST_F(CancelDuringAresQuery,
392        TestHitDeadlineAndDestroyChannelDuringAresResolutionIsGraceful) {
393   TestCancelDuringActiveQuery(NONE /* don't set query timeouts */);
394 }
395
396 TEST_F(
397     CancelDuringAresQuery,
398     TestHitDeadlineAndDestroyChannelDuringAresResolutionWithQueryTimeoutIsGraceful) {
399   TestCancelDuringActiveQuery(SHORT /* set short query timeout */);
400 }
401
402 TEST_F(
403     CancelDuringAresQuery,
404     TestHitDeadlineAndDestroyChannelDuringAresResolutionWithZeroQueryTimeoutIsGraceful) {
405   TestCancelDuringActiveQuery(ZERO /* disable query timeouts */);
406 }
407
408 }  // namespace
409
410 int main(int argc, char** argv) {
411   grpc::testing::TestEnvironment env(argc, argv);
412   ::testing::InitGoogleTest(&argc, argv);
413   auto result = RUN_ALL_TESTS();
414   return result;
415 }