3 * Copyright 2015 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
22 #include <gflags/gflags.h>
23 #include <gmock/gmock.h>
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"
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
53 #include "src/core/lib/iomgr/sockaddr_posix.h"
54 #define BAD_SOCKET_RETURN_VAL -1
59 void* Tag(intptr_t t) { return (void*)t; }
61 gpr_timespec FiveSecondsFromNow(void) {
62 return grpc_timeout_seconds_to_deadline(5);
65 void DrainCq(grpc_completion_queue* cq) {
68 ev = grpc_completion_queue_next(cq, FiveSecondsFromNow(), nullptr);
69 } while (ev.type != GRPC_QUEUE_SHUTDOWN);
72 void EndTest(grpc_channel* client, grpc_completion_queue* cq) {
73 grpc_channel_destroy(client);
74 grpc_completion_queue_shutdown(cq);
76 grpc_completion_queue_destroy(cq);
79 class FakeNonResponsiveDNSServer {
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");
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);
97 ~FakeNonResponsiveDNSServer() {
112 grpc_pollset* pollset;
113 grpc_pollset_set* pollset_set;
115 grpc_channel_args* channel_args;
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;
128 void DoNothing(void* arg, grpc_error* error) {}
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);
145 void PollPollsetUntilRequestDone(ArgsStruct* args) {
147 bool done = gpr_atm_acq_load(&args->done_atm) != 0;
151 grpc_pollset_worker* worker = nullptr;
152 grpc_core::ExecCtx exec_ctx;
153 gpr_mu_lock(args->mu);
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);
163 class AssertFailureResultHandler : public grpc_core::Resolver::ResultHandler {
165 explicit AssertFailureResultHandler(ArgsStruct* args) : args_(args) {}
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);
175 void ReturnResult(grpc_core::Resolver::Result result) override {
179 void ReturnError(grpc_error* error) override { GPR_ASSERT(false); }
185 void TestCancelActiveDNSQuery(ArgsStruct* args) {
186 int fake_dns_port = grpc_pick_unused_port_or_die();
187 FakeNonResponsiveDNSServer fake_dns_server(fake_dns_port);
189 GPR_ASSERT(gpr_asprintf(
191 "dns://[::1]:%d/dont-care-since-wont-be-resolved.test.com:1234",
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.
204 grpc_core::ExecCtx::Get()->Flush();
205 PollPollsetUntilRequestDone(args);
209 TEST(CancelDuringAresQuery, TestCancelActiveDNSQuery) {
210 grpc_core::ExecCtx exec_ctx;
213 TestCancelActiveDNSQuery(&args);
218 void MaybePollArbitraryPollsetTwice() {
219 grpc_pollset* pollset = (grpc_pollset*)gpr_zalloc(grpc_pollset_size());
221 grpc_pollset_init(pollset, &mu);
222 grpc_pollset_worker* worker = nullptr;
223 // Make a zero timeout poll
227 grpc_pollset_work(pollset, &worker, grpc_core::ExecCtx::Get()->Now()));
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")
235 grpc_pollset_work(pollset, &worker, grpc_core::ExecCtx::Get()->Now()));
237 grpc_core::ExecCtx::Get()->Flush();
238 grpc_pollset_destroy(pollset);
244 void MaybePollArbitraryPollsetTwice() {}
248 TEST(CancelDuringAresQuery, TestFdsAreDeletedFromPollsetSet) {
249 grpc_core::ExecCtx exec_ctx;
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
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
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);
274 // Settings for TestCancelDuringActiveQuery test
279 } cancellation_test_query_timeout_setting;
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(
290 "dns://[::1]:%d/dont-care-since-wont-be-resolved.test.com:1234",
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;
302 arg.type = GRPC_ARG_INTEGER;
303 arg.key = const_cast<char*>(GRPC_ARG_DNS_ARES_QUERY_TIMEOUT_MS);
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;
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);
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);
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;
338 // Set ops for client the request
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;
345 op->reserved = nullptr;
347 op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT;
349 op->reserved = nullptr;
351 op->op = GRPC_OP_RECV_INITIAL_METADATA;
352 op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv;
354 op->reserved = nullptr;
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;
362 op->reserved = nullptr;
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);
370 EXPECT_EQ(status, expected_status_code);
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);
384 TEST(CancelDuringAresQuery,
385 TestHitDeadlineAndDestroyChannelDuringAresResolutionIsGraceful) {
386 TestCancelDuringActiveQuery(NONE /* don't set query timeouts */);
390 CancelDuringAresQuery,
391 TestHitDeadlineAndDestroyChannelDuringAresResolutionWithQueryTimeoutIsGraceful) {
392 TestCancelDuringActiveQuery(SHORT /* set short query timeout */);
396 CancelDuringAresQuery,
397 TestHitDeadlineAndDestroyChannelDuringAresResolutionWithZeroQueryTimeoutIsGraceful) {
398 TestCancelDuringActiveQuery(ZERO /* disable query timeouts */);
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);
413 auto result = RUN_ALL_TESTS();
415 if (gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), overall_deadline) > 0) {
416 gpr_log(GPR_ERROR, "Test took too long");