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.
24 #include "absl/strings/str_cat.h"
25 #include "absl/strings/str_format.h"
27 #include <gflags/gflags.h>
28 #include <gmock/gmock.h>
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>
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"
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
58 #include "src/core/lib/iomgr/sockaddr_posix.h"
59 #define BAD_SOCKET_RETURN_VAL -1
64 void* Tag(intptr_t t) { return (void*)t; }
66 gpr_timespec FiveSecondsFromNow(void) {
67 return grpc_timeout_seconds_to_deadline(5);
70 void DrainCq(grpc_completion_queue* cq) {
73 ev = grpc_completion_queue_next(cq, FiveSecondsFromNow(), nullptr);
74 } while (ev.type != GRPC_QUEUE_SHUTDOWN);
77 void EndTest(grpc_channel* client, grpc_completion_queue* cq) {
78 grpc_channel_destroy(client);
79 grpc_completion_queue_shutdown(cq);
81 grpc_completion_queue_destroy(cq);
87 grpc_pollset* pollset;
88 grpc_pollset_set* pollset_set;
89 std::shared_ptr<grpc_core::WorkSerializer> lock;
90 grpc_channel_args* channel_args;
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;
103 void DoNothing(void* /*arg*/, grpc_error* /*error*/) {}
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);
119 void PollPollsetUntilRequestDone(ArgsStruct* args) {
121 bool done = gpr_atm_acq_load(&args->done_atm) != 0;
125 grpc_pollset_worker* worker = nullptr;
126 grpc_core::ExecCtx exec_ctx;
127 gpr_mu_lock(args->mu);
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);
137 class AssertFailureResultHandler : public grpc_core::Resolver::ResultHandler {
139 explicit AssertFailureResultHandler(ArgsStruct* args) : args_(args) {}
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);
149 void ReturnResult(grpc_core::Resolver::Result /*result*/) override {
153 void ReturnError(grpc_error* /*error*/) override { GPR_ASSERT(false); }
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",
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.
175 grpc_core::ExecCtx::Get()->Flush();
176 PollPollsetUntilRequestDone(args);
180 class CancelDuringAresQuery : public ::testing::Test {
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);
192 static void TearDownTestCase() {
194 if (gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), overall_deadline) > 0) {
195 gpr_log(GPR_ERROR, "Test took too long");
201 static gpr_timespec overall_deadline;
203 gpr_timespec CancelDuringAresQuery::overall_deadline;
205 TEST_F(CancelDuringAresQuery, TestCancelActiveDNSQuery) {
206 grpc_core::ExecCtx exec_ctx;
209 TestCancelActiveDNSQuery(&args);
214 void MaybePollArbitraryPollsetTwice() {
215 grpc_pollset* pollset = (grpc_pollset*)gpr_zalloc(grpc_pollset_size());
217 grpc_pollset_init(pollset, &mu);
218 grpc_pollset_worker* worker = nullptr;
219 // Make a zero timeout poll
223 grpc_pollset_work(pollset, &worker, grpc_core::ExecCtx::Get()->Now()));
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")
231 grpc_pollset_work(pollset, &worker, grpc_core::ExecCtx::Get()->Now()));
233 grpc_core::ExecCtx::Get()->Flush();
234 grpc_pollset_destroy(pollset);
240 void MaybePollArbitraryPollsetTwice() {}
244 TEST_F(CancelDuringAresQuery, TestFdsAreDeletedFromPollsetSet) {
245 grpc_core::ExecCtx exec_ctx;
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
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
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);
270 // Settings for TestCancelDuringActiveQuery test
275 } cancellation_test_query_timeout_setting;
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",
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
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;
303 arg.type = GRPC_ARG_INTEGER;
304 arg.key = const_cast<char*>(GRPC_ARG_DNS_ARES_QUERY_TIMEOUT_MS);
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
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
316 expected_status_code = GRPC_STATUS_DEADLINE_EXCEEDED;
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);
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);
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;
345 // Set ops for client the request
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;
352 op->reserved = nullptr;
354 op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT;
356 op->reserved = nullptr;
358 op->op = GRPC_OP_RECV_INITIAL_METADATA;
359 op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv;
361 op->reserved = nullptr;
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;
369 op->reserved = nullptr;
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);
377 EXPECT_EQ(status, expected_status_code);
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);
391 TEST_F(CancelDuringAresQuery,
392 TestHitDeadlineAndDestroyChannelDuringAresResolutionIsGraceful) {
393 TestCancelDuringActiveQuery(NONE /* don't set query timeouts */);
397 CancelDuringAresQuery,
398 TestHitDeadlineAndDestroyChannelDuringAresResolutionWithQueryTimeoutIsGraceful) {
399 TestCancelDuringActiveQuery(SHORT /* set short query timeout */);
403 CancelDuringAresQuery,
404 TestHitDeadlineAndDestroyChannelDuringAresResolutionWithZeroQueryTimeoutIsGraceful) {
405 TestCancelDuringActiveQuery(ZERO /* disable query timeouts */);
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();