Debian Codegraph @

test/cpp/naming/cancel_ares_query_test.cc

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