xref: /aosp_15_r20/external/grpc-grpc/test/cpp/naming/resolver_component_test.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 //
2 //
3 // Copyright 2017 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 <errno.h>
20 #include <fcntl.h>
21 #include <string.h>
22 
23 #include <string>
24 #include <thread>
25 #include <vector>
26 
27 #include <gmock/gmock.h>
28 
29 #include "absl/flags/flag.h"
30 #include "absl/memory/memory.h"
31 #include "absl/strings/str_cat.h"
32 #include "absl/strings/str_format.h"
33 
34 #include <grpc/grpc.h>
35 #include <grpc/impl/grpc_types.h>
36 #include <grpc/support/alloc.h>
37 #include <grpc/support/log.h>
38 #include <grpc/support/port_platform.h>
39 #include <grpc/support/sync.h>
40 #include <grpc/support/time.h>
41 
42 #include "src/core/client_channel/client_channel_filter.h"
43 #include "src/core/lib/address_utils/parse_address.h"
44 #include "src/core/lib/address_utils/sockaddr_utils.h"
45 #include "src/core/lib/channel/channel_args.h"
46 #include "src/core/lib/config/core_configuration.h"
47 #include "src/core/lib/event_engine/ares_resolver.h"
48 #include "src/core/lib/event_engine/default_event_engine.h"
49 #include "src/core/lib/experiments/experiments.h"
50 #include "src/core/lib/gpr/string.h"
51 #include "src/core/lib/gprpp/crash.h"
52 #include "src/core/lib/gprpp/host_port.h"
53 #include "src/core/lib/gprpp/orphanable.h"
54 #include "src/core/lib/gprpp/work_serializer.h"
55 #include "src/core/lib/iomgr/executor.h"
56 #include "src/core/lib/iomgr/iomgr.h"
57 #include "src/core/lib/iomgr/resolve_address.h"
58 #include "src/core/lib/iomgr/socket_utils.h"
59 #include "src/core/load_balancing/grpclb/grpclb_balancer_addresses.h"
60 #include "src/core/resolver/dns/c_ares/grpc_ares_wrapper.h"
61 #include "src/core/resolver/endpoint_addresses.h"
62 #include "src/core/resolver/resolver.h"
63 #include "src/core/resolver/resolver_registry.h"
64 #include "test/core/util/fake_udp_and_tcp_server.h"
65 #include "test/core/util/port.h"
66 #include "test/core/util/socket_use_after_close_detector.h"
67 #include "test/core/util/test_config.h"
68 #include "test/cpp/util/subprocess.h"
69 #include "test/cpp/util/test_config.h"
70 
71 using ::grpc_event_engine::experimental::GetDefaultEventEngine;
72 using std::vector;
73 using testing::UnorderedElementsAreArray;
74 
75 ABSL_FLAG(std::string, target_name, "", "Target name to resolve.");
76 ABSL_FLAG(std::string, do_ordered_address_comparison, "",
77           "Whether or not to compare resolved addresses to expected "
78           "addresses using an ordered comparison. This is useful for "
79           "testing certain behaviors that involve sorting of resolved "
80           "addresses. Note it would be better if this argument was a "
81           "bool flag, but it's a string for ease of invocation from "
82           "the generated python test runner.");
83 ABSL_FLAG(std::string, expected_addrs, "",
84           "List of expected backend or balancer addresses in the form "
85           "'<ip0:port0>,<is_balancer0>;<ip1:port1>,<is_balancer1>;...'. "
86           "'is_balancer' should be bool, i.e. true or false.");
87 ABSL_FLAG(std::string, expected_chosen_service_config, "",
88           "Expected service config json string that gets chosen (no "
89           "whitespace). Empty for none.");
90 ABSL_FLAG(std::string, expected_service_config_error, "",
91           "Expected service config error. Empty for none.");
92 ABSL_FLAG(std::string, local_dns_server_address, "",
93           "Optional. This address is placed as the uri authority if present.");
94 // TODO(Capstan): Is this worth making `bool` now with Abseil flags?
95 ABSL_FLAG(
96     std::string, enable_srv_queries, "",
97     "Whether or not to enable SRV queries for the ares resolver instance."
98     "It would be better if this arg could be bool, but the way that we "
99     "generate "
100     "the python script runner doesn't allow us to pass a gflags bool to this "
101     "binary.");
102 // TODO(Capstan): Is this worth making `bool` now with Abseil flags?
103 ABSL_FLAG(
104     std::string, enable_txt_queries, "",
105     "Whether or not to enable TXT queries for the ares resolver instance."
106     "It would be better if this arg could be bool, but the way that we "
107     "generate "
108     "the python script runner doesn't allow us to pass a gflags bool to this "
109     "binary.");
110 // TODO(Capstan): Is this worth making `bool` now with Abseil flags?
111 ABSL_FLAG(
112     std::string, inject_broken_nameserver_list, "",
113     "Whether or not to configure c-ares to use a broken nameserver list, in "
114     "which "
115     "the first nameserver in the list is non-responsive, but the second one "
116     "works, i.e "
117     "serves the expected DNS records; using for testing such a real scenario."
118     "It would be better if this arg could be bool, but the way that we "
119     "generate "
120     "the python script runner doesn't allow us to pass a gflags bool to this "
121     "binary.");
122 ABSL_FLAG(std::string, expected_lb_policy, "",
123           "Expected lb policy name that appears in resolver result channel "
124           "arg. Empty for none.");
125 
126 namespace {
127 
128 class GrpcLBAddress final {
129  public:
GrpcLBAddress(std::string address,bool is_balancer)130   GrpcLBAddress(std::string address, bool is_balancer)
131       : is_balancer(is_balancer), address(std::move(address)) {}
132 
operator ==(const GrpcLBAddress & other) const133   bool operator==(const GrpcLBAddress& other) const {
134     return this->is_balancer == other.is_balancer &&
135            this->address == other.address;
136   }
137 
operator !=(const GrpcLBAddress & other) const138   bool operator!=(const GrpcLBAddress& other) const {
139     return !(*this == other);
140   }
141 
142   bool is_balancer;
143   std::string address;
144 };
145 
ParseExpectedAddrs(std::string expected_addrs)146 vector<GrpcLBAddress> ParseExpectedAddrs(std::string expected_addrs) {
147   std::vector<GrpcLBAddress> out;
148   while (!expected_addrs.empty()) {
149     // get the next <ip>,<port> (v4 or v6)
150     size_t next_comma = expected_addrs.find(',');
151     if (next_comma == std::string::npos) {
152       grpc_core::Crash(absl::StrFormat(
153           "Missing ','. Expected_addrs arg should be a semicolon-separated "
154           "list of <ip-port>,<bool> pairs. Left-to-be-parsed arg is |%s|",
155           expected_addrs.c_str()));
156     }
157     std::string next_addr = expected_addrs.substr(0, next_comma);
158     expected_addrs = expected_addrs.substr(next_comma + 1, std::string::npos);
159     // get the next is_balancer 'bool' associated with this address
160     size_t next_semicolon = expected_addrs.find(';');
161     bool is_balancer = false;
162     gpr_parse_bool_value(expected_addrs.substr(0, next_semicolon).c_str(),
163                          &is_balancer);
164     out.emplace_back(GrpcLBAddress(next_addr, is_balancer));
165     if (next_semicolon == std::string::npos) {
166       break;
167     }
168     expected_addrs =
169         expected_addrs.substr(next_semicolon + 1, std::string::npos);
170   }
171   if (out.empty()) {
172     grpc_core::Crash(
173         "expected_addrs arg should be a semicolon-separated list of "
174         "<ip-port>,<bool> pairs");
175   }
176   return out;
177 }
178 
TestDeadline(void)179 gpr_timespec TestDeadline(void) {
180   return grpc_timeout_seconds_to_deadline(100);
181 }
182 
183 struct ArgsStruct {
184   gpr_event ev;
185   gpr_mu* mu;
186   bool done;              // guarded by mu
187   grpc_pollset* pollset;  // guarded by mu
188   grpc_pollset_set* pollset_set;
189   std::shared_ptr<grpc_core::WorkSerializer> lock;
190   grpc_channel_args* channel_args;
191   vector<GrpcLBAddress> expected_addrs;
192   std::string expected_service_config_string;
193   std::string expected_service_config_error;
194   std::string expected_lb_policy;
195 };
196 
ArgsInit(ArgsStruct * args)197 void ArgsInit(ArgsStruct* args) {
198   gpr_event_init(&args->ev);
199   args->pollset = static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
200   grpc_pollset_init(args->pollset, &args->mu);
201   args->pollset_set = grpc_pollset_set_create();
202   grpc_pollset_set_add_pollset(args->pollset_set, args->pollset);
203   args->lock = std::make_shared<grpc_core::WorkSerializer>(
204       grpc_event_engine::experimental::GetDefaultEventEngine());
205   args->done = false;
206   args->channel_args = nullptr;
207 }
208 
DoNothing(void *,grpc_error_handle)209 void DoNothing(void* /*arg*/, grpc_error_handle /*error*/) {}
210 
ArgsFinish(ArgsStruct * args)211 void ArgsFinish(ArgsStruct* args) {
212   GPR_ASSERT(gpr_event_wait(&args->ev, TestDeadline()));
213   grpc_pollset_set_del_pollset(args->pollset_set, args->pollset);
214   grpc_pollset_set_destroy(args->pollset_set);
215   grpc_closure DoNothing_cb;
216   GRPC_CLOSURE_INIT(&DoNothing_cb, DoNothing, nullptr,
217                     grpc_schedule_on_exec_ctx);
218   grpc_pollset_shutdown(args->pollset, &DoNothing_cb);
219   // exec_ctx needs to be flushed before calling grpc_pollset_destroy()
220   grpc_channel_args_destroy(args->channel_args);
221   grpc_core::ExecCtx::Get()->Flush();
222   grpc_pollset_destroy(args->pollset);
223   gpr_free(args->pollset);
224 }
225 
NSecondDeadline(int seconds)226 gpr_timespec NSecondDeadline(int seconds) {
227   return gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
228                       gpr_time_from_seconds(seconds, GPR_TIMESPAN));
229 }
230 
PollPollsetUntilRequestDone(ArgsStruct * args)231 void PollPollsetUntilRequestDone(ArgsStruct* args) {
232   // Use a 20-second timeout to give room for the tests that involve
233   // a non-responsive name server (c-ares uses a ~5 second query timeout
234   // for that server before succeeding with the healthy one).
235   gpr_timespec deadline = NSecondDeadline(20);
236   while (true) {
237     grpc_core::MutexLockForGprMu lock(args->mu);
238     if (args->done) {
239       break;
240     }
241     gpr_timespec time_left =
242         gpr_time_sub(deadline, gpr_now(GPR_CLOCK_REALTIME));
243     gpr_log(GPR_DEBUG, "done=%d, time_left=%" PRId64 ".%09d", args->done,
244             time_left.tv_sec, time_left.tv_nsec);
245     GPR_ASSERT(gpr_time_cmp(time_left, gpr_time_0(GPR_TIMESPAN)) >= 0);
246     grpc_pollset_worker* worker = nullptr;
247     grpc_core::ExecCtx exec_ctx;
248     if (grpc_core::IsEventEngineDnsEnabled()) {
249       // This essentially becomes a condition variable.
250       GRPC_LOG_IF_ERROR(
251           "pollset_work",
252           grpc_pollset_work(
253               args->pollset, &worker,
254               grpc_core::Timestamp::FromTimespecRoundUp(deadline)));
255     } else {
256       GRPC_LOG_IF_ERROR(
257           "pollset_work",
258           grpc_pollset_work(
259               args->pollset, &worker,
260               grpc_core::Timestamp::FromTimespecRoundUp(NSecondDeadline(1))));
261     }
262   }
263   gpr_event_set(&args->ev, reinterpret_cast<void*>(1));
264 }
265 
CheckServiceConfigResultLocked(const char * service_config_json,absl::Status service_config_error,ArgsStruct * args)266 void CheckServiceConfigResultLocked(const char* service_config_json,
267                                     absl::Status service_config_error,
268                                     ArgsStruct* args) {
269   if (!args->expected_service_config_string.empty()) {
270     ASSERT_NE(service_config_json, nullptr);
271     EXPECT_EQ(service_config_json, args->expected_service_config_string);
272   }
273   if (args->expected_service_config_error.empty()) {
274     EXPECT_TRUE(service_config_error.ok())
275         << "Actual error: " << service_config_error.ToString();
276   } else {
277     EXPECT_THAT(service_config_error.ToString(),
278                 testing::HasSubstr(args->expected_service_config_error));
279   }
280 }
281 
CheckLBPolicyResultLocked(const grpc_core::ChannelArgs channel_args,ArgsStruct * args)282 void CheckLBPolicyResultLocked(const grpc_core::ChannelArgs channel_args,
283                                ArgsStruct* args) {
284   absl::optional<absl::string_view> lb_policy_arg =
285       channel_args.GetString(GRPC_ARG_LB_POLICY_NAME);
286   if (!args->expected_lb_policy.empty()) {
287     EXPECT_TRUE(lb_policy_arg.has_value());
288     EXPECT_EQ(*lb_policy_arg, args->expected_lb_policy);
289   } else {
290     EXPECT_FALSE(lb_policy_arg.has_value());
291   }
292 }
293 
294 class ResultHandler : public grpc_core::Resolver::ResultHandler {
295  public:
Create(ArgsStruct * args)296   static std::unique_ptr<grpc_core::Resolver::ResultHandler> Create(
297       ArgsStruct* args) {
298     return std::unique_ptr<grpc_core::Resolver::ResultHandler>(
299         new ResultHandler(args));
300   }
301 
ResultHandler(ArgsStruct * args)302   explicit ResultHandler(ArgsStruct* args) : args_(args) {}
303 
ReportResult(grpc_core::Resolver::Result result)304   void ReportResult(grpc_core::Resolver::Result result) override {
305     CheckResult(result);
306     grpc_core::MutexLockForGprMu lock(args_->mu);
307     GPR_ASSERT(!args_->done);
308     args_->done = true;
309     GRPC_LOG_IF_ERROR("pollset_kick",
310                       grpc_pollset_kick(args_->pollset, nullptr));
311   }
312 
CheckResult(const grpc_core::Resolver::Result &)313   virtual void CheckResult(const grpc_core::Resolver::Result& /*result*/) {}
314 
315  protected:
args_struct() const316   ArgsStruct* args_struct() const { return args_; }
317 
318  private:
319   ArgsStruct* args_;
320 };
321 
322 class CheckingResultHandler : public ResultHandler {
323  public:
Create(ArgsStruct * args)324   static std::unique_ptr<grpc_core::Resolver::ResultHandler> Create(
325       ArgsStruct* args) {
326     return std::unique_ptr<grpc_core::Resolver::ResultHandler>(
327         new CheckingResultHandler(args));
328   }
329 
CheckingResultHandler(ArgsStruct * args)330   explicit CheckingResultHandler(ArgsStruct* args) : ResultHandler(args) {}
331 
CheckResult(const grpc_core::Resolver::Result & result)332   void CheckResult(const grpc_core::Resolver::Result& result) override {
333     ASSERT_TRUE(result.addresses.ok()) << result.addresses.status().ToString();
334     ArgsStruct* args = args_struct();
335     std::vector<GrpcLBAddress> found_lb_addrs;
336     AddActualAddresses(*result.addresses, /*is_balancer=*/false,
337                        &found_lb_addrs);
338     const grpc_core::EndpointAddressesList* balancer_addresses =
339         grpc_core::FindGrpclbBalancerAddressesInChannelArgs(result.args);
340     if (balancer_addresses != nullptr) {
341       AddActualAddresses(*balancer_addresses, /*is_balancer=*/true,
342                          &found_lb_addrs);
343     }
344     gpr_log(GPR_INFO,
345             "found %" PRIdPTR " backend addresses and %" PRIdPTR
346             " balancer addresses",
347             result.addresses->size(),
348             balancer_addresses == nullptr ? 0L : balancer_addresses->size());
349     if (args->expected_addrs.size() != found_lb_addrs.size()) {
350       grpc_core::Crash(absl::StrFormat("found lb addrs size is: %" PRIdPTR
351                                        ". expected addrs size is %" PRIdPTR,
352                                        found_lb_addrs.size(),
353                                        args->expected_addrs.size()));
354     }
355     if (absl::GetFlag(FLAGS_do_ordered_address_comparison) == "True") {
356       EXPECT_EQ(args->expected_addrs, found_lb_addrs);
357     } else if (absl::GetFlag(FLAGS_do_ordered_address_comparison) == "False") {
358       EXPECT_THAT(args->expected_addrs,
359                   UnorderedElementsAreArray(found_lb_addrs));
360     } else {
361       gpr_log(GPR_ERROR,
362               "Invalid for setting for --do_ordered_address_comparison. "
363               "Have %s, want True or False",
364               absl::GetFlag(FLAGS_do_ordered_address_comparison).c_str());
365       GPR_ASSERT(0);
366     }
367     if (!result.service_config.ok()) {
368       CheckServiceConfigResultLocked(nullptr, result.service_config.status(),
369                                      args);
370     } else if (*result.service_config == nullptr) {
371       CheckServiceConfigResultLocked(nullptr, absl::OkStatus(), args);
372     } else {
373       CheckServiceConfigResultLocked(
374           std::string((*result.service_config)->json_string()).c_str(),
375           absl::OkStatus(), args);
376     }
377     if (args->expected_service_config_string.empty()) {
378       CheckLBPolicyResultLocked(result.args, args);
379     }
380   }
381 
382  private:
AddActualAddresses(const grpc_core::EndpointAddressesList & addresses,bool is_balancer,std::vector<GrpcLBAddress> * out)383   static void AddActualAddresses(
384       const grpc_core::EndpointAddressesList& addresses, bool is_balancer,
385       std::vector<GrpcLBAddress>* out) {
386     for (size_t i = 0; i < addresses.size(); i++) {
387       const grpc_core::EndpointAddresses& addr = addresses[i];
388       std::string str =
389           grpc_sockaddr_to_string(&addr.address(), true /* normalize */)
390               .value();
391       gpr_log(GPR_INFO, "%s", str.c_str());
392       out->emplace_back(GrpcLBAddress(std::move(str), is_balancer));
393     }
394   }
395 };
396 
397 int g_fake_non_responsive_dns_server_port = -1;
398 
399 // This function will configure any ares_channel created by the c-ares based
400 // resolver. This is useful to effectively mock /etc/resolv.conf settings
401 // (and equivalent on Windows), which unit tests don't have write permissions.
402 //
InjectBrokenNameServerList(ares_channel * channel)403 void InjectBrokenNameServerList(ares_channel* channel) {
404   struct ares_addr_port_node dns_server_addrs[2];
405   memset(dns_server_addrs, 0, sizeof(dns_server_addrs));
406   std::string unused_host;
407   std::string local_dns_server_port;
408   GPR_ASSERT(grpc_core::SplitHostPort(
409       absl::GetFlag(FLAGS_local_dns_server_address).c_str(), &unused_host,
410       &local_dns_server_port));
411   gpr_log(GPR_DEBUG,
412           "Injecting broken nameserver list. Bad server address:|[::1]:%d|. "
413           "Good server address:%s",
414           g_fake_non_responsive_dns_server_port,
415           absl::GetFlag(FLAGS_local_dns_server_address).c_str());
416   // Put the non-responsive DNS server at the front of c-ares's nameserver list.
417   dns_server_addrs[0].family = AF_INET6;
418   (reinterpret_cast<char*>(&dns_server_addrs[0].addr.addr6))[15] = 0x1;
419   dns_server_addrs[0].tcp_port = g_fake_non_responsive_dns_server_port;
420   dns_server_addrs[0].udp_port = g_fake_non_responsive_dns_server_port;
421   dns_server_addrs[0].next = &dns_server_addrs[1];
422   // Put the actual healthy DNS server after the first one. The expectation is
423   // that the resolver will timeout the query to the non-responsive DNS server
424   // and will skip over to this healthy DNS server, without causing any DNS
425   // resolution errors.
426   dns_server_addrs[1].family = AF_INET;
427   (reinterpret_cast<char*>(&dns_server_addrs[1].addr.addr4))[0] = 0x7f;
428   (reinterpret_cast<char*>(&dns_server_addrs[1].addr.addr4))[3] = 0x1;
429   dns_server_addrs[1].tcp_port = atoi(local_dns_server_port.c_str());
430   dns_server_addrs[1].udp_port = atoi(local_dns_server_port.c_str());
431   dns_server_addrs[1].next = nullptr;
432   GPR_ASSERT(ares_set_servers_ports(*channel, dns_server_addrs) ==
433              ARES_SUCCESS);
434 }
435 
StartResolvingLocked(grpc_core::Resolver * r)436 void StartResolvingLocked(grpc_core::Resolver* r) { r->StartLocked(); }
437 
RunResolvesRelevantRecordsTest(std::unique_ptr<grpc_core::Resolver::ResultHandler> (* CreateResultHandler)(ArgsStruct * args),grpc_core::ChannelArgs resolver_args)438 void RunResolvesRelevantRecordsTest(
439     std::unique_ptr<grpc_core::Resolver::ResultHandler> (*CreateResultHandler)(
440         ArgsStruct* args),
441     grpc_core::ChannelArgs resolver_args) {
442   grpc_core::ExecCtx exec_ctx;
443   ArgsStruct args;
444   ArgsInit(&args);
445   args.expected_addrs = ParseExpectedAddrs(absl::GetFlag(FLAGS_expected_addrs));
446   args.expected_service_config_string =
447       absl::GetFlag(FLAGS_expected_chosen_service_config);
448   args.expected_service_config_error =
449       absl::GetFlag(FLAGS_expected_service_config_error);
450   args.expected_lb_policy = absl::GetFlag(FLAGS_expected_lb_policy);
451   // maybe build the address with an authority
452   std::string whole_uri;
453   gpr_log(GPR_DEBUG,
454           "resolver_component_test: --inject_broken_nameserver_list: %s",
455           absl::GetFlag(FLAGS_inject_broken_nameserver_list).c_str());
456   std::unique_ptr<grpc_core::testing::FakeUdpAndTcpServer>
457       fake_non_responsive_dns_server;
458   if (absl::GetFlag(FLAGS_inject_broken_nameserver_list) == "True") {
459     fake_non_responsive_dns_server = std::make_unique<
460         grpc_core::testing::FakeUdpAndTcpServer>(
461         grpc_core::testing::FakeUdpAndTcpServer::AcceptMode::
462             kWaitForClientToSendFirstBytes,
463         grpc_core::testing::FakeUdpAndTcpServer::CloseSocketUponCloseFromPeer);
464     g_fake_non_responsive_dns_server_port =
465         fake_non_responsive_dns_server->port();
466     if (grpc_core::IsEventEngineDnsEnabled()) {
467       event_engine_grpc_ares_test_only_inject_config =
468           InjectBrokenNameServerList;
469     } else {
470       grpc_ares_test_only_inject_config = InjectBrokenNameServerList;
471     }
472     whole_uri = absl::StrCat("dns:///", absl::GetFlag(FLAGS_target_name));
473   } else if (absl::GetFlag(FLAGS_inject_broken_nameserver_list) == "False") {
474     gpr_log(GPR_INFO, "Specifying authority in uris to: %s",
475             absl::GetFlag(FLAGS_local_dns_server_address).c_str());
476     whole_uri = absl::StrFormat("dns://%s/%s",
477                                 absl::GetFlag(FLAGS_local_dns_server_address),
478                                 absl::GetFlag(FLAGS_target_name));
479   } else {
480     grpc_core::Crash("Invalid value for --inject_broken_nameserver_list.");
481   }
482   gpr_log(GPR_DEBUG, "resolver_component_test: --enable_srv_queries: %s",
483           absl::GetFlag(FLAGS_enable_srv_queries).c_str());
484   // By default, SRV queries are disabled, so tests that expect no SRV query
485   // should avoid setting any channel arg. Test cases that do rely on the SRV
486   // query must explicitly enable SRV though.
487   if (absl::GetFlag(FLAGS_enable_srv_queries) == "True") {
488     resolver_args = resolver_args.Set(GRPC_ARG_DNS_ENABLE_SRV_QUERIES, true);
489   } else if (absl::GetFlag(FLAGS_enable_srv_queries) != "False") {
490     grpc_core::Crash("Invalid value for --enable_srv_queries.");
491   }
492   gpr_log(GPR_DEBUG, "resolver_component_test: --enable_txt_queries: %s",
493           absl::GetFlag(FLAGS_enable_txt_queries).c_str());
494   // By default, TXT queries are disabled, so tests that expect no TXT query
495   // should avoid setting any channel arg. Test cases that do rely on the TXT
496   // query must explicitly enable TXT though.
497   if (absl::GetFlag(FLAGS_enable_txt_queries) == "True") {
498     // Unlike SRV queries, there isn't a channel arg specific to TXT records.
499     // Rather, we use the resolver-agnostic "service config" resolution option,
500     // for which c-ares has its own specific default value, which isn't
501     // necessarily shared by other resolvers.
502     resolver_args =
503         resolver_args.Set(GRPC_ARG_SERVICE_CONFIG_DISABLE_RESOLUTION, false);
504   } else if (absl::GetFlag(FLAGS_enable_txt_queries) != "False") {
505     grpc_core::Crash("Invalid value for --enable_txt_queries.");
506   }
507   resolver_args = resolver_args.SetObject(GetDefaultEventEngine());
508   // create resolver and resolve
509   grpc_core::OrphanablePtr<grpc_core::Resolver> resolver =
510       grpc_core::CoreConfiguration::Get().resolver_registry().CreateResolver(
511           whole_uri.c_str(), resolver_args, args.pollset_set, args.lock,
512           CreateResultHandler(&args));
513   auto* resolver_ptr = resolver.get();
514   args.lock->Run([resolver_ptr]() { StartResolvingLocked(resolver_ptr); },
515                  DEBUG_LOCATION);
516   grpc_core::ExecCtx::Get()->Flush();
517   PollPollsetUntilRequestDone(&args);
518   ArgsFinish(&args);
519 }
520 
TEST(ResolverComponentTest,TestResolvesRelevantRecords)521 TEST(ResolverComponentTest, TestResolvesRelevantRecords) {
522   RunResolvesRelevantRecordsTest(CheckingResultHandler::Create,
523                                  grpc_core::ChannelArgs());
524 }
525 
TEST(ResolverComponentTest,TestResolvesRelevantRecordsWithConcurrentFdStress)526 TEST(ResolverComponentTest, TestResolvesRelevantRecordsWithConcurrentFdStress) {
527   grpc_core::testing::SocketUseAfterCloseDetector
528       socket_use_after_close_detector;
529   // Run the resolver test
530   RunResolvesRelevantRecordsTest(ResultHandler::Create,
531                                  grpc_core::ChannelArgs());
532 }
533 
TEST(ResolverComponentTest,TestDoesntCrashOrHangWith1MsTimeout)534 TEST(ResolverComponentTest, TestDoesntCrashOrHangWith1MsTimeout) {
535   // Queries in this test could either complete successfully or time out
536   // and show cancellation. This test doesn't care - we just care that the
537   // query completes and doesn't crash, get stuck, leak, etc.
538   RunResolvesRelevantRecordsTest(
539       ResultHandler::Create,
540       grpc_core::ChannelArgs().Set(GRPC_ARG_DNS_ARES_QUERY_TIMEOUT_MS, 1));
541 }
542 
543 }  // namespace
544 
main(int argc,char ** argv)545 int main(int argc, char** argv) {
546   ::testing::InitGoogleTest(&argc, argv);
547   // Need before TestEnvironment construct for --grpc_experiments flag at
548   // least.
549   grpc::testing::InitTest(&argc, &argv, true);
550   grpc::testing::TestEnvironment env(&argc, argv);
551   if (absl::GetFlag(FLAGS_target_name).empty()) {
552     grpc_core::Crash("Missing target_name param.");
553   }
554   grpc_init();
555   auto result = RUN_ALL_TESTS();
556   grpc_shutdown();
557   return result;
558 }
559