Debian Codegraph @

test/core/client_channel/resolvers/dns_resolver_cooldown_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 <inttypes.h>
20
21 #include <functional>
22 #include <memory>
23 #include <string>
24 #include <utility>
25 #include <vector>
26
27 #include "absl/status/status.h"
28 #include "absl/status/statusor.h"
29 #include "absl/strings/string_view.h"
30 #include "gtest/gtest.h"
31
32 #include <grpc/event_engine/event_engine.h>
33 #include <grpc/grpc.h>
34 #include <grpc/support/alloc.h>
35 #include <grpc/support/atm.h>
36 #include <grpc/support/log.h>
37 #include <grpc/support/sync.h>
38 #include <grpc/support/time.h>
39
40 #include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
41 #include "src/core/lib/channel/channel_args.h"
42 #include "src/core/lib/config/core_configuration.h"
43 #include "src/core/lib/event_engine/default_event_engine.h"
44 #include "src/core/lib/gprpp/debug_location.h"
45 #include "src/core/lib/gprpp/no_destruct.h"
46 #include "src/core/lib/gprpp/notification.h"
47 #include "src/core/lib/gprpp/orphanable.h"
48 #include "src/core/lib/gprpp/time.h"
49 #include "src/core/lib/gprpp/work_serializer.h"
50 #include "src/core/lib/iomgr/closure.h"
51 #include "src/core/lib/iomgr/error.h"
52 #include "src/core/lib/iomgr/exec_ctx.h"
53 #include "src/core/lib/iomgr/iomgr_fwd.h"
54 #include "src/core/lib/iomgr/pollset.h"
55 #include "src/core/lib/iomgr/pollset_set.h"
56 #include "src/core/lib/iomgr/resolve_address.h"
57 #include "src/core/lib/iomgr/resolved_address.h"
58 #include "src/core/lib/resolver/resolver.h"
59 #include "src/core/lib/resolver/resolver_factory.h"
60 #include "src/core/lib/resolver/resolver_registry.h"
61 #include "src/core/lib/resolver/server_address.h"
62 #include "src/core/lib/uri/uri_parser.h"
63 #include "test/core/util/test_config.h"
64
65 constexpr int kMinResolutionPeriodMs = 1000;
66
67 static std::shared_ptr<grpc_core::WorkSerializer>* g_work_serializer;
68
69 static grpc_ares_request* (*g_default_dns_lookup_ares)(
70 const char* dns_server, const char* name, const char* default_port,
71 grpc_pollset_set* interested_parties, grpc_closure* on_done,
72 std::unique_ptr<grpc_core::ServerAddressList>* addresses,
73 int query_timeout_ms);
74
75 // Counter incremented by TestDNSResolver::LookupHostname indicating the
76 // number of times a system-level resolution has happened.
77 static int g_resolution_count;
78
79 static struct iomgr_args {
80 gpr_event ev;
81 gpr_atm done_atm;
82 gpr_mu* mu;
83 grpc_pollset* pollset;
84 grpc_pollset_set* pollset_set;
85 } g_iomgr_args;
86
87 namespace {
88
89 class TestDNSResolver : public grpc_core::DNSResolver {
90 public:
91 explicit TestDNSResolver(
92 std::shared_ptr<grpc_core::DNSResolver> default_resolver)
93 : default_resolver_(std::move(default_resolver)),
94 engine_(grpc_event_engine::experimental::GetDefaultEventEngine()) {}
95 // Wrapper around default resolve_address in order to count the number of
96 // times we incur in a system-level name resolution.
97 TaskHandle LookupHostname(
98 std::function<void(absl::StatusOr<std::vector<grpc_resolved_address>>)>
99 on_resolved,
100 absl::string_view name, absl::string_view default_port,
101 grpc_core::Duration timeout, grpc_pollset_set* interested_parties,
102 absl::string_view name_server) override {
103 auto result = default_resolver_->LookupHostname(
104 std::move(on_resolved), name, default_port, timeout, interested_parties,
105 name_server);
106 ++g_resolution_count;
107 static grpc_core::Timestamp last_resolution_time =
108 grpc_core::Timestamp::ProcessEpoch();
109 if (last_resolution_time == grpc_core::Timestamp::ProcessEpoch()) {
110 last_resolution_time = grpc_core::Timestamp::FromTimespecRoundUp(
111 gpr_now(GPR_CLOCK_MONOTONIC));
112 } else {
113 auto now = grpc_core::Timestamp::FromTimespecRoundUp(
114 gpr_now(GPR_CLOCK_MONOTONIC));
115 EXPECT_GE(now - last_resolution_time,
116 grpc_core::Duration::Milliseconds(kMinResolutionPeriodMs));
117 last_resolution_time = now;
118 }
119 // For correct time diff comparisons, make sure that any subsequent calls
120 // to grpc_core::Timestamp::Now() on this thread don't return a time
121 // which is earlier than that returned by the call(s) to
122 // gpr_now(GPR_CLOCK_MONOTONIC) within this function. This is important
123 // because the resolver's last_resolution_timestamp_ will be taken from
124 // grpc_core::Timestamp::Now() right after this returns.
125 grpc_core::ExecCtx::Get()->InvalidateNow();
126 return result;
127 }
128
129 absl::StatusOr<std::vector<grpc_resolved_address>> LookupHostnameBlocking(
130 absl::string_view name, absl::string_view default_port) override {
131 return default_resolver_->LookupHostnameBlocking(name, default_port);
132 }
133
134 TaskHandle LookupSRV(
135 std::function<void(absl::StatusOr<std::vector<grpc_resolved_address>>)>
136 on_resolved,
137 absl::string_view /* name */, grpc_core::Duration /* timeout */,
138 grpc_pollset_set* /* interested_parties */,
139 absl::string_view /* name_server */) override {
140 engine_->Run([on_resolved] {
141 grpc_core::ApplicationCallbackExecCtx app_exec_ctx;
142 grpc_core::ExecCtx exec_ctx;
143 on_resolved(absl::UnimplementedError(
144 "The Testing DNS resolver does not support looking up SRV records"));
145 });
146 return {-1, -1};
147 };
148
149 TaskHandle LookupTXT(
150 std::function<void(absl::StatusOr<std::string>)> on_resolved,
151 absl::string_view /* name */, grpc_core::Duration /* timeout */,
152 grpc_pollset_set* /* interested_parties */,
153 absl::string_view /* name_server */) override {
154 // Not supported
155 engine_->Run([on_resolved] {
156 grpc_core::ApplicationCallbackExecCtx app_exec_ctx;
157 grpc_core::ExecCtx exec_ctx;
158 on_resolved(absl::UnimplementedError(
159 "The Testing DNS resolver does not support looking up TXT records"));
160 });
161 return {-1, -1};
162 };
163
164 // Not cancellable
165 bool Cancel(TaskHandle /*handle*/) override { return false; }
166
167 private:
168 std::shared_ptr<grpc_core::DNSResolver> default_resolver_;
169 std::shared_ptr<grpc_event_engine::experimental::EventEngine> engine_;
170 };
171
172 } // namespace
173
174 static grpc_ares_request* test_dns_lookup_ares(
175 const char* dns_server, const char* name, const char* default_port,
176 grpc_pollset_set* /*interested_parties*/, grpc_closure* on_done,
177 std::unique_ptr<grpc_core::ServerAddressList>* addresses,
178 int query_timeout_ms) {
179 // A records should suffice
180 grpc_ares_request* result = g_default_dns_lookup_ares(
181 dns_server, name, default_port, g_iomgr_args.pollset_set, on_done,
182 addresses, query_timeout_ms);
183 ++g_resolution_count;
184 static auto last_resolution_time = grpc_core::Timestamp::ProcessEpoch();
185 auto now =
186 grpc_core::Timestamp::FromTimespecRoundUp(gpr_now(GPR_CLOCK_MONOTONIC));
187 gpr_log(GPR_DEBUG,
188 "last_resolution_time:%" PRId64 " now:%" PRId64
189 " min_time_between:%d",
190 last_resolution_time.milliseconds_after_process_epoch(),
191 now.milliseconds_after_process_epoch(), kMinResolutionPeriodMs);
192 if (last_resolution_time != grpc_core::Timestamp::ProcessEpoch()) {
193 EXPECT_GE(now - last_resolution_time,
194 grpc_core::Duration::Milliseconds(kMinResolutionPeriodMs));
195 }
196 last_resolution_time = now;
197 // For correct time diff comparisons, make sure that any subsequent calls
198 // to grpc_core::Timestamp::Now() on this thread don't return a time
199 // which is earlier than that returned by the call(s) to
200 // gpr_now(GPR_CLOCK_MONOTONIC) within this function. This is important
201 // because the resolver's last_resolution_timestamp_ will be taken from
202 // grpc_core::Timestamp::Now() right after this returns.
203 grpc_core::ExecCtx::Get()->InvalidateNow();
204 return result;
205 }
206
207 static gpr_timespec test_deadline(void) {
208 return grpc_timeout_seconds_to_deadline(100);
209 }
210
211 static void do_nothing(void* /*arg*/, grpc_error_handle /*error*/) {}
212
213 static void iomgr_args_init(iomgr_args* args) {
214 gpr_event_init(&args->ev);
215 args->pollset = static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
216 grpc_pollset_init(args->pollset, &args->mu);
217 args->pollset_set = grpc_pollset_set_create();
218 grpc_pollset_set_add_pollset(args->pollset_set, args->pollset);
219 gpr_atm_rel_store(&args->done_atm, 0);
220 }
221
222 static void iomgr_args_finish(iomgr_args* args) {
223 ASSERT_TRUE(gpr_event_wait(&args->ev, test_deadline()));
224 grpc_pollset_set_del_pollset(args->pollset_set, args->pollset);
225 grpc_pollset_set_destroy(args->pollset_set);
226 grpc_closure do_nothing_cb;
227 GRPC_CLOSURE_INIT(&do_nothing_cb, do_nothing, nullptr,
228 grpc_schedule_on_exec_ctx);
229 gpr_mu_lock(args->mu);
230 grpc_pollset_shutdown(args->pollset, &do_nothing_cb);
231 gpr_mu_unlock(args->mu);
232 // exec_ctx needs to be flushed before calling grpc_pollset_destroy()
233 grpc_core::ExecCtx::Get()->Flush();
234 grpc_pollset_destroy(args->pollset);
235 gpr_free(args->pollset);
236 }
237
238 static grpc_core::Timestamp n_sec_deadline(int seconds) {
239 return grpc_core::Timestamp::FromTimespecRoundUp(
240 grpc_timeout_seconds_to_deadline(seconds));
241 }
242
243 static void poll_pollset_until_request_done(iomgr_args* args) {
244 grpc_core::ExecCtx exec_ctx;
245 grpc_core::Timestamp deadline = n_sec_deadline(10);
246 while (true) {
247 bool done = gpr_atm_acq_load(&args->done_atm) != 0;
248 if (done) {
249 break;
250 }
251 grpc_core::Duration time_left = deadline - grpc_core::Timestamp::Now();
252 gpr_log(GPR_DEBUG, "done=%d, time_left=%" PRId64, done, time_left.millis());
253 ASSERT_GE(time_left, grpc_core::Duration::Zero());
254 grpc_pollset_worker* worker = nullptr;
255 gpr_mu_lock(args->mu);
256 GRPC_LOG_IF_ERROR("pollset_work", grpc_pollset_work(args->pollset, &worker,
257 n_sec_deadline(1)));
258 gpr_mu_unlock(args->mu);
259 grpc_core::ExecCtx::Get()->Flush();
260 }
261 gpr_event_set(&args->ev, reinterpret_cast<void*>(1));
262 }
263
264 struct OnResolutionCallbackArg;
265
266 class ResultHandler : public grpc_core::Resolver::ResultHandler {
267 public:
268 using ResultCallback = void (*)(OnResolutionCallbackArg* state);
269
270 void SetCallback(ResultCallback result_cb, OnResolutionCallbackArg* state) {
271 ASSERT_EQ(result_cb_, nullptr);
272 result_cb_ = result_cb;
273 ASSERT_EQ(state_, nullptr);
274 state_ = state;
275 }
276
277 void ReportResult(grpc_core::Resolver::Result result) override {
278 if (result.result_health_callback != nullptr) {
279 result.result_health_callback(absl::OkStatus());
280 }
281 ASSERT_NE(result_cb_, nullptr);
282 ASSERT_NE(state_, nullptr);
283 ResultCallback cb = result_cb_;
284 OnResolutionCallbackArg* state = state_;
285 result_cb_ = nullptr;
286 state_ = nullptr;
287 cb(state);
288 }
289
290 private:
291 ResultCallback result_cb_ = nullptr;
292 OnResolutionCallbackArg* state_ = nullptr;
293 };
294
295 struct OnResolutionCallbackArg {
296 const char* uri_str = nullptr;
297 grpc_core::OrphanablePtr<grpc_core::Resolver> resolver;
298 ResultHandler* result_handler;
299 };
300
301 // Set to true by the last callback in the resolution chain.
302 static grpc_core::NoDestruct<grpc_core::Notification> g_all_callbacks_invoked;
303
304 // It's interesting to run a few rounds of this test because as
305 // we run more rounds, the base starting time
306 // (i.e. ExecCtx g_start_time) gets further and further away
307 // from "Now()". Thus the more rounds ran, the more highlighted the
308 // difference is between absolute and relative times values.
309 static void on_fourth_resolution(OnResolutionCallbackArg* cb_arg) {
310 gpr_log(GPR_INFO, "4th: g_resolution_count: %d", g_resolution_count);
311 ASSERT_EQ(g_resolution_count, 4);
312 cb_arg->resolver.reset();
313 gpr_atm_rel_store(&g_iomgr_args.done_atm, 1);
314 gpr_mu_lock(g_iomgr_args.mu);
315 GRPC_LOG_IF_ERROR("pollset_kick",
316 grpc_pollset_kick(g_iomgr_args.pollset, nullptr));
317 gpr_mu_unlock(g_iomgr_args.mu);
318 delete cb_arg;
319 g_all_callbacks_invoked->Notify();
320 }
321
322 static void on_third_resolution(OnResolutionCallbackArg* cb_arg) {
323 gpr_log(GPR_INFO, "3rd: g_resolution_count: %d", g_resolution_count);
324 ASSERT_EQ(g_resolution_count, 3);
325 cb_arg->result_handler->SetCallback(on_fourth_resolution, cb_arg);
326 cb_arg->resolver->RequestReresolutionLocked();
327 gpr_mu_lock(g_iomgr_args.mu);
328 GRPC_LOG_IF_ERROR("pollset_kick",
329 grpc_pollset_kick(g_iomgr_args.pollset, nullptr));
330 gpr_mu_unlock(g_iomgr_args.mu);
331 }
332
333 static void on_second_resolution(OnResolutionCallbackArg* cb_arg) {
334 gpr_log(GPR_INFO, "2nd: g_resolution_count: %d", g_resolution_count);
335 // The resolution callback was not invoked until new data was
336 // available, which was delayed until after the cooldown period.
337 ASSERT_EQ(g_resolution_count, 2);
338 cb_arg->result_handler->SetCallback(on_third_resolution, cb_arg);
339 cb_arg->resolver->RequestReresolutionLocked();
340 gpr_mu_lock(g_iomgr_args.mu);
341 GRPC_LOG_IF_ERROR("pollset_kick",
342 grpc_pollset_kick(g_iomgr_args.pollset, nullptr));
343 gpr_mu_unlock(g_iomgr_args.mu);
344 }
345
346 static void on_first_resolution(OnResolutionCallbackArg* cb_arg) {
347 gpr_log(GPR_INFO, "1st: g_resolution_count: %d", g_resolution_count);
348 // There's one initial system-level resolution and one invocation of a
349 // notification callback (the current function).
350 ASSERT_EQ(g_resolution_count, 1);
351 cb_arg->result_handler->SetCallback(on_second_resolution, cb_arg);
352 cb_arg->resolver->RequestReresolutionLocked();
353 gpr_mu_lock(g_iomgr_args.mu);
354 GRPC_LOG_IF_ERROR("pollset_kick",
355 grpc_pollset_kick(g_iomgr_args.pollset, nullptr));
356 gpr_mu_unlock(g_iomgr_args.mu);
357 }
358
359 static void start_test_under_work_serializer(void* arg) {
360 OnResolutionCallbackArg* res_cb_arg =
361 static_cast<OnResolutionCallbackArg*>(arg);
362 res_cb_arg->result_handler = new ResultHandler();
363 grpc_core::ResolverFactory* factory = grpc_core::CoreConfiguration::Get()
364 .resolver_registry()
365 .LookupResolverFactory("dns");
366 absl::StatusOr<grpc_core::URI> uri =
367 grpc_core::URI::Parse(res_cb_arg->uri_str);
368 gpr_log(GPR_DEBUG, "test: '%s' should be valid for '%s'", res_cb_arg->uri_str,
369 std::string(factory->scheme()).c_str());
370 if (!uri.ok()) {
371 gpr_log(GPR_ERROR, "%s", uri.status().ToString().c_str());
372 ASSERT_TRUE(uri.ok());
373 }
374 grpc_core::ResolverArgs args;
375 args.uri = std::move(*uri);
376 args.work_serializer = *g_work_serializer;
377 args.result_handler = std::unique_ptr<grpc_core::Resolver::ResultHandler>(
378 res_cb_arg->result_handler);
379 g_resolution_count = 0;
380
381 grpc_arg cooldown_arg = grpc_channel_arg_integer_create(
382 const_cast<char*>(GRPC_ARG_DNS_MIN_TIME_BETWEEN_RESOLUTIONS_MS),
383 kMinResolutionPeriodMs);
384 grpc_channel_args cooldown_args = {1, &cooldown_arg};
385 args.args = grpc_core::ChannelArgs::FromC(&cooldown_args);
386 res_cb_arg->resolver = factory->CreateResolver(std::move(args));
387 ASSERT_NE(res_cb_arg->resolver, nullptr);
388 // First resolution, would incur in system-level resolution.
389 res_cb_arg->result_handler->SetCallback(on_first_resolution, res_cb_arg);
390 res_cb_arg->resolver->StartLocked();
391 }
392
393 static void test_cooldown() {
394 grpc_core::ExecCtx exec_ctx;
395 iomgr_args_init(&g_iomgr_args);
396 OnResolutionCallbackArg* res_cb_arg = new OnResolutionCallbackArg();
397 res_cb_arg->uri_str = "dns:127.0.0.1";
398
399 (*g_work_serializer)
400 ->Run([res_cb_arg]() { start_test_under_work_serializer(res_cb_arg); },
401 DEBUG_LOCATION);
402 grpc_core::ExecCtx::Get()->Flush();
403 poll_pollset_until_request_done(&g_iomgr_args);
404 iomgr_args_finish(&g_iomgr_args);
405 }
406
407 TEST(DnsResolverCooldownTest, MainTest) {
408 grpc_init();
409
410 auto work_serializer = std::make_shared<grpc_core::WorkSerializer>();
411 g_work_serializer = &work_serializer;
412
413 g_default_dns_lookup_ares = grpc_dns_lookup_hostname_ares;
414 grpc_dns_lookup_hostname_ares = test_dns_lookup_ares;
415 grpc_core::ResetDNSResolver(
416 std::make_unique<TestDNSResolver>(grpc_core::GetDNSResolver()));
417
418 test_cooldown();
419
420 grpc_shutdown();
421 g_all_callbacks_invoked->WaitForNotification();
422 }
423
424 int main(int argc, char** argv) {
425 grpc::testing::TestEnvironment env(&argc, argv);
426 ::testing::InitGoogleTest(&argc, argv);
427 return RUN_ALL_TESTS();
428 }