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