resolver_component_test.cc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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. #include <grpc/support/port_platform.h>
  19. #include <errno.h>
  20. #include <fcntl.h>
  21. #include <string.h>
  22. #include <string>
  23. #include <thread>
  24. #include <vector>
  25. #include <gmock/gmock.h>
  26. #include "absl/flags/flag.h"
  27. #include "absl/memory/memory.h"
  28. #include "absl/strings/str_cat.h"
  29. #include "absl/strings/str_format.h"
  30. #include <grpc/grpc.h>
  31. #include <grpc/impl/codegen/grpc_types.h>
  32. #include <grpc/support/alloc.h>
  33. #include <grpc/support/log.h>
  34. #include <grpc/support/sync.h>
  35. #include <grpc/support/time.h>
  36. #include "src/core/ext/filters/client_channel/client_channel.h"
  37. #include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_balancer_addresses.h"
  38. #include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
  39. #include "src/core/lib/address_utils/parse_address.h"
  40. #include "src/core/lib/address_utils/sockaddr_utils.h"
  41. #include "src/core/lib/channel/channel_args.h"
  42. #include "src/core/lib/config/core_configuration.h"
  43. #include "src/core/lib/gpr/string.h"
  44. #include "src/core/lib/gprpp/host_port.h"
  45. #include "src/core/lib/gprpp/orphanable.h"
  46. #include "src/core/lib/iomgr/executor.h"
  47. #include "src/core/lib/iomgr/iomgr.h"
  48. #include "src/core/lib/iomgr/resolve_address.h"
  49. #include "src/core/lib/iomgr/socket_utils.h"
  50. #include "src/core/lib/iomgr/work_serializer.h"
  51. #include "src/core/lib/resolver/resolver.h"
  52. #include "src/core/lib/resolver/resolver_registry.h"
  53. #include "src/core/lib/resolver/server_address.h"
  54. #include "test/core/util/fake_udp_and_tcp_server.h"
  55. #include "test/core/util/port.h"
  56. #include "test/core/util/test_config.h"
  57. #include "test/cpp/util/subprocess.h"
  58. #include "test/cpp/util/test_config.h"
  59. // TODO(unknown): pull in different headers when enabling this
  60. // test on windows. Also set BAD_SOCKET_RETURN_VAL
  61. // to INVALID_SOCKET on windows.
  62. #ifdef GPR_WINDOWS
  63. #include "src/core/lib/iomgr/sockaddr_windows.h"
  64. #include "src/core/lib/iomgr/socket_windows.h"
  65. #include "src/core/lib/iomgr/tcp_windows.h"
  66. #define BAD_SOCKET_RETURN_VAL INVALID_SOCKET
  67. #else
  68. #include "src/core/lib/iomgr/sockaddr_posix.h"
  69. #define BAD_SOCKET_RETURN_VAL (-1)
  70. #endif
  71. using std::vector;
  72. using testing::UnorderedElementsAreArray;
  73. ABSL_FLAG(std::string, target_name, "", "Target name to resolve.");
  74. ABSL_FLAG(std::string, do_ordered_address_comparison, "",
  75. "Whether or not to compare resolved addresses to expected "
  76. "addresses using an ordered comparison. This is useful for "
  77. "testing certain behaviors that involve sorting of resolved "
  78. "addresses. Note it would be better if this argument was a "
  79. "bool flag, but it's a string for ease of invocation from "
  80. "the generated python test runner.");
  81. ABSL_FLAG(std::string, expected_addrs, "",
  82. "List of expected backend or balancer addresses in the form "
  83. "'<ip0:port0>,<is_balancer0>;<ip1:port1>,<is_balancer1>;...'. "
  84. "'is_balancer' should be bool, i.e. true or false.");
  85. ABSL_FLAG(std::string, expected_chosen_service_config, "",
  86. "Expected service config json string that gets chosen (no "
  87. "whitespace). Empty for none.");
  88. ABSL_FLAG(std::string, expected_service_config_error, "",
  89. "Expected service config error. Empty for none.");
  90. ABSL_FLAG(std::string, local_dns_server_address, "",
  91. "Optional. This address is placed as the uri authority if present.");
  92. // TODO(Capstan): Is this worth making `bool` now with Abseil flags?
  93. ABSL_FLAG(
  94. std::string, enable_srv_queries, "",
  95. "Whether or not to enable SRV queries for the ares resolver instance."
  96. "It would be better if this arg could be bool, but the way that we "
  97. "generate "
  98. "the python script runner doesn't allow us to pass a gflags bool to this "
  99. "binary.");
  100. // TODO(Capstan): Is this worth making `bool` now with Abseil flags?
  101. ABSL_FLAG(
  102. std::string, enable_txt_queries, "",
  103. "Whether or not to enable TXT queries for the ares resolver instance."
  104. "It would be better if this arg could be bool, but the way that we "
  105. "generate "
  106. "the python script runner doesn't allow us to pass a gflags bool to this "
  107. "binary.");
  108. // TODO(Capstan): Is this worth making `bool` now with Abseil flags?
  109. ABSL_FLAG(
  110. std::string, inject_broken_nameserver_list, "",
  111. "Whether or not to configure c-ares to use a broken nameserver list, in "
  112. "which "
  113. "the first nameserver in the list is non-responsive, but the second one "
  114. "works, i.e "
  115. "serves the expected DNS records; using for testing such a real scenario."
  116. "It would be better if this arg could be bool, but the way that we "
  117. "generate "
  118. "the python script runner doesn't allow us to pass a gflags bool to this "
  119. "binary.");
  120. ABSL_FLAG(std::string, expected_lb_policy, "",
  121. "Expected lb policy name that appears in resolver result channel "
  122. "arg. Empty for none.");
  123. namespace {
  124. class GrpcLBAddress final {
  125. public:
  126. GrpcLBAddress(std::string address, bool is_balancer)
  127. : is_balancer(is_balancer), address(std::move(address)) {}
  128. bool operator==(const GrpcLBAddress& other) const {
  129. return this->is_balancer == other.is_balancer &&
  130. this->address == other.address;
  131. }
  132. bool operator!=(const GrpcLBAddress& other) const {
  133. return !(*this == other);
  134. }
  135. bool is_balancer;
  136. std::string address;
  137. };
  138. vector<GrpcLBAddress> ParseExpectedAddrs(std::string expected_addrs) {
  139. std::vector<GrpcLBAddress> out;
  140. while (!expected_addrs.empty()) {
  141. // get the next <ip>,<port> (v4 or v6)
  142. size_t next_comma = expected_addrs.find(',');
  143. if (next_comma == std::string::npos) {
  144. gpr_log(GPR_ERROR,
  145. "Missing ','. Expected_addrs arg should be a semicolon-separated "
  146. "list of <ip-port>,<bool> pairs. Left-to-be-parsed arg is |%s|",
  147. expected_addrs.c_str());
  148. abort();
  149. }
  150. std::string next_addr = expected_addrs.substr(0, next_comma);
  151. expected_addrs = expected_addrs.substr(next_comma + 1, std::string::npos);
  152. // get the next is_balancer 'bool' associated with this address
  153. size_t next_semicolon = expected_addrs.find(';');
  154. bool is_balancer = false;
  155. gpr_parse_bool_value(expected_addrs.substr(0, next_semicolon).c_str(),
  156. &is_balancer);
  157. out.emplace_back(GrpcLBAddress(next_addr, is_balancer));
  158. if (next_semicolon == std::string::npos) {
  159. break;
  160. }
  161. expected_addrs =
  162. expected_addrs.substr(next_semicolon + 1, std::string::npos);
  163. }
  164. if (out.empty()) {
  165. gpr_log(GPR_ERROR,
  166. "expected_addrs arg should be a semicolon-separated list of "
  167. "<ip-port>,<bool> pairs");
  168. abort();
  169. }
  170. return out;
  171. }
  172. gpr_timespec TestDeadline(void) {
  173. return grpc_timeout_seconds_to_deadline(100);
  174. }
  175. struct ArgsStruct {
  176. gpr_event ev;
  177. gpr_atm done_atm;
  178. gpr_mu* mu;
  179. grpc_pollset* pollset;
  180. grpc_pollset_set* pollset_set;
  181. std::shared_ptr<grpc_core::WorkSerializer> lock;
  182. grpc_channel_args* channel_args;
  183. vector<GrpcLBAddress> expected_addrs;
  184. std::string expected_service_config_string;
  185. std::string expected_service_config_error;
  186. std::string expected_lb_policy;
  187. };
  188. void ArgsInit(ArgsStruct* args) {
  189. gpr_event_init(&args->ev);
  190. args->pollset = static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
  191. grpc_pollset_init(args->pollset, &args->mu);
  192. args->pollset_set = grpc_pollset_set_create();
  193. grpc_pollset_set_add_pollset(args->pollset_set, args->pollset);
  194. args->lock = std::make_shared<grpc_core::WorkSerializer>();
  195. gpr_atm_rel_store(&args->done_atm, 0);
  196. args->channel_args = nullptr;
  197. }
  198. void DoNothing(void* /*arg*/, grpc_error_handle /*error*/) {}
  199. void ArgsFinish(ArgsStruct* args) {
  200. GPR_ASSERT(gpr_event_wait(&args->ev, TestDeadline()));
  201. grpc_pollset_set_del_pollset(args->pollset_set, args->pollset);
  202. grpc_pollset_set_destroy(args->pollset_set);
  203. grpc_closure DoNothing_cb;
  204. GRPC_CLOSURE_INIT(&DoNothing_cb, DoNothing, nullptr,
  205. grpc_schedule_on_exec_ctx);
  206. grpc_pollset_shutdown(args->pollset, &DoNothing_cb);
  207. // exec_ctx needs to be flushed before calling grpc_pollset_destroy()
  208. grpc_channel_args_destroy(args->channel_args);
  209. grpc_core::ExecCtx::Get()->Flush();
  210. grpc_pollset_destroy(args->pollset);
  211. gpr_free(args->pollset);
  212. }
  213. gpr_timespec NSecondDeadline(int seconds) {
  214. return gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  215. gpr_time_from_seconds(seconds, GPR_TIMESPAN));
  216. }
  217. void PollPollsetUntilRequestDone(ArgsStruct* args) {
  218. // Use a 20-second timeout to give room for the tests that involve
  219. // a non-responsive name server (c-ares uses a ~5 second query timeout
  220. // for that server before succeeding with the healthy one).
  221. gpr_timespec deadline = NSecondDeadline(20);
  222. while (true) {
  223. bool done = gpr_atm_acq_load(&args->done_atm) != 0;
  224. if (done) {
  225. break;
  226. }
  227. gpr_timespec time_left =
  228. gpr_time_sub(deadline, gpr_now(GPR_CLOCK_REALTIME));
  229. gpr_log(GPR_DEBUG, "done=%d, time_left=%" PRId64 ".%09d", done,
  230. time_left.tv_sec, time_left.tv_nsec);
  231. GPR_ASSERT(gpr_time_cmp(time_left, gpr_time_0(GPR_TIMESPAN)) >= 0);
  232. grpc_pollset_worker* worker = nullptr;
  233. grpc_core::ExecCtx exec_ctx;
  234. gpr_mu_lock(args->mu);
  235. GRPC_LOG_IF_ERROR(
  236. "pollset_work",
  237. grpc_pollset_work(
  238. args->pollset, &worker,
  239. grpc_core::Timestamp::FromTimespecRoundUp(NSecondDeadline(1))));
  240. gpr_mu_unlock(args->mu);
  241. }
  242. gpr_event_set(&args->ev, reinterpret_cast<void*>(1));
  243. }
  244. void CheckServiceConfigResultLocked(const char* service_config_json,
  245. absl::Status service_config_error,
  246. ArgsStruct* args) {
  247. if (!args->expected_service_config_string.empty()) {
  248. ASSERT_NE(service_config_json, nullptr);
  249. EXPECT_EQ(service_config_json, args->expected_service_config_string);
  250. }
  251. if (args->expected_service_config_error.empty()) {
  252. EXPECT_TRUE(service_config_error.ok());
  253. } else {
  254. EXPECT_THAT(service_config_error.ToString(),
  255. testing::HasSubstr(args->expected_service_config_error));
  256. }
  257. }
  258. void CheckLBPolicyResultLocked(const grpc_channel_args* channel_args,
  259. ArgsStruct* args) {
  260. const grpc_arg* lb_policy_arg =
  261. grpc_channel_args_find(channel_args, GRPC_ARG_LB_POLICY_NAME);
  262. if (!args->expected_lb_policy.empty()) {
  263. GPR_ASSERT(lb_policy_arg != nullptr);
  264. GPR_ASSERT(lb_policy_arg->type == GRPC_ARG_STRING);
  265. EXPECT_EQ(lb_policy_arg->value.string, args->expected_lb_policy);
  266. } else {
  267. GPR_ASSERT(lb_policy_arg == nullptr);
  268. }
  269. }
  270. #ifdef GPR_WINDOWS
  271. void OpenAndCloseSocketsStressLoop(int phony_port, gpr_event* done_ev) {
  272. sockaddr_in6 addr;
  273. memset(&addr, 0, sizeof(addr));
  274. addr.sin6_family = AF_INET6;
  275. addr.sin6_port = htons(phony_port);
  276. ((char*)&addr.sin6_addr)[15] = 1;
  277. for (;;) {
  278. if (gpr_event_get(done_ev)) {
  279. return;
  280. }
  281. std::vector<int> sockets;
  282. for (size_t i = 0; i < 50; i++) {
  283. SOCKET s = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, nullptr, 0,
  284. WSA_FLAG_OVERLAPPED);
  285. ASSERT_TRUE(s != BAD_SOCKET_RETURN_VAL)
  286. << "Failed to create TCP ipv6 socket";
  287. gpr_log(GPR_DEBUG, "Opened socket: %d", s);
  288. char val = 1;
  289. ASSERT_TRUE(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) !=
  290. SOCKET_ERROR)
  291. << "Failed to set socketopt reuseaddr. WSA error: " +
  292. std::to_string(WSAGetLastError());
  293. ASSERT_TRUE(grpc_tcp_set_non_block(s) == GRPC_ERROR_NONE)
  294. << "Failed to set socket non-blocking";
  295. ASSERT_TRUE(bind(s, (const sockaddr*)&addr, sizeof(addr)) != SOCKET_ERROR)
  296. << "Failed to bind socket " + std::to_string(s) +
  297. " to [::1]:" + std::to_string(phony_port) +
  298. ". WSA error: " + std::to_string(WSAGetLastError());
  299. ASSERT_TRUE(listen(s, 1) != SOCKET_ERROR)
  300. << "Failed to listen on socket " + std::to_string(s) +
  301. ". WSA error: " + std::to_string(WSAGetLastError());
  302. sockets.push_back(s);
  303. }
  304. // Do a non-blocking accept followed by a close on all of those sockets.
  305. // Do this in a separate loop to try to induce a time window to hit races.
  306. for (size_t i = 0; i < sockets.size(); i++) {
  307. gpr_log(GPR_DEBUG, "non-blocking accept then close on %d", sockets[i]);
  308. ASSERT_TRUE(accept(sockets[i], nullptr, nullptr) == INVALID_SOCKET)
  309. << "Accept on phony socket unexpectedly accepted actual connection.";
  310. ASSERT_TRUE(WSAGetLastError() == WSAEWOULDBLOCK)
  311. << "OpenAndCloseSocketsStressLoop accept on socket " +
  312. std::to_string(sockets[i]) +
  313. " failed in "
  314. "an unexpected way. "
  315. "WSA error: " +
  316. std::to_string(WSAGetLastError()) +
  317. ". Socket use-after-close bugs are likely.";
  318. ASSERT_TRUE(closesocket(sockets[i]) != SOCKET_ERROR)
  319. << "Failed to close socket: " + std::to_string(sockets[i]) +
  320. ". WSA error: " + std::to_string(WSAGetLastError());
  321. }
  322. }
  323. return;
  324. }
  325. #else
  326. void OpenAndCloseSocketsStressLoop(int phony_port, gpr_event* done_ev) {
  327. // The goal of this loop is to catch socket
  328. // "use after close" bugs within the c-ares resolver by acting
  329. // like some separate thread doing I/O.
  330. // It's goal is to try to hit race conditions whereby:
  331. // 1) The c-ares resolver closes a socket.
  332. // 2) This loop opens a socket with (coincidentally) the same handle.
  333. // 3) the c-ares resolver mistakenly uses that same socket without
  334. // realizing that its closed.
  335. // 4) This loop performs an operation on that socket that should
  336. // succeed but instead fails because of what the c-ares
  337. // resolver did in the meantime.
  338. sockaddr_in6 addr;
  339. memset(&addr, 0, sizeof(addr));
  340. addr.sin6_family = AF_INET6;
  341. addr.sin6_port = htons(phony_port);
  342. (reinterpret_cast<char*>(&addr.sin6_addr))[15] = 1;
  343. for (;;) {
  344. if (gpr_event_get(done_ev)) {
  345. return;
  346. }
  347. std::vector<int> sockets;
  348. // First open a bunch of sockets, bind and listen
  349. // '50' is an arbitrary number that, experimentally,
  350. // has a good chance of catching bugs.
  351. for (size_t i = 0; i < 50; i++) {
  352. int s = socket(AF_INET6, SOCK_STREAM, 0);
  353. int val = 1;
  354. ASSERT_TRUE(setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &val, sizeof(val)) ==
  355. 0)
  356. << "Failed to set socketopt reuseport";
  357. ASSERT_TRUE(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) ==
  358. 0)
  359. << "Failed to set socket reuseaddr";
  360. ASSERT_TRUE(fcntl(s, F_SETFL, O_NONBLOCK) == 0)
  361. << "Failed to set socket non-blocking";
  362. ASSERT_TRUE(s != BAD_SOCKET_RETURN_VAL)
  363. << "Failed to create TCP ipv6 socket";
  364. gpr_log(GPR_DEBUG, "Opened fd: %d", s);
  365. ASSERT_TRUE(bind(s, (const sockaddr*)&addr, sizeof(addr)) == 0)
  366. << "Failed to bind socket " + std::to_string(s) +
  367. " to [::1]:" + std::to_string(phony_port) +
  368. ". errno: " + std::to_string(errno);
  369. ASSERT_TRUE(listen(s, 1) == 0) << "Failed to listen on socket " +
  370. std::to_string(s) +
  371. ". errno: " + std::to_string(errno);
  372. sockets.push_back(s);
  373. }
  374. // Do a non-blocking accept followed by a close on all of those sockets.
  375. // Do this in a separate loop to try to induce a time window to hit races.
  376. for (size_t i = 0; i < sockets.size(); i++) {
  377. gpr_log(GPR_DEBUG, "non-blocking accept then close on %d", sockets[i]);
  378. if (accept(sockets[i], nullptr, nullptr)) {
  379. // If e.g. a "shutdown" was called on this fd from another thread,
  380. // then this accept call should fail with an unexpected error.
  381. ASSERT_TRUE(errno == EAGAIN || errno == EWOULDBLOCK)
  382. << "OpenAndCloseSocketsStressLoop accept on socket " +
  383. std::to_string(sockets[i]) +
  384. " failed in "
  385. "an unexpected way. "
  386. "errno: " +
  387. std::to_string(errno) +
  388. ". Socket use-after-close bugs are likely.";
  389. }
  390. ASSERT_TRUE(close(sockets[i]) == 0)
  391. << "Failed to close socket: " + std::to_string(sockets[i]) +
  392. ". errno: " + std::to_string(errno);
  393. }
  394. }
  395. }
  396. #endif
  397. class ResultHandler : public grpc_core::Resolver::ResultHandler {
  398. public:
  399. static std::unique_ptr<grpc_core::Resolver::ResultHandler> Create(
  400. ArgsStruct* args) {
  401. return std::unique_ptr<grpc_core::Resolver::ResultHandler>(
  402. new ResultHandler(args));
  403. }
  404. explicit ResultHandler(ArgsStruct* args) : args_(args) {}
  405. void ReportResult(grpc_core::Resolver::Result result) override {
  406. CheckResult(result);
  407. gpr_atm_rel_store(&args_->done_atm, 1);
  408. gpr_mu_lock(args_->mu);
  409. GRPC_LOG_IF_ERROR("pollset_kick",
  410. grpc_pollset_kick(args_->pollset, nullptr));
  411. gpr_mu_unlock(args_->mu);
  412. }
  413. virtual void CheckResult(const grpc_core::Resolver::Result& /*result*/) {}
  414. protected:
  415. ArgsStruct* args_struct() const { return args_; }
  416. private:
  417. ArgsStruct* args_;
  418. };
  419. class CheckingResultHandler : public ResultHandler {
  420. public:
  421. static std::unique_ptr<grpc_core::Resolver::ResultHandler> Create(
  422. ArgsStruct* args) {
  423. return std::unique_ptr<grpc_core::Resolver::ResultHandler>(
  424. new CheckingResultHandler(args));
  425. }
  426. explicit CheckingResultHandler(ArgsStruct* args) : ResultHandler(args) {}
  427. void CheckResult(const grpc_core::Resolver::Result& result) override {
  428. ASSERT_TRUE(result.addresses.ok()) << result.addresses.status().ToString();
  429. ArgsStruct* args = args_struct();
  430. std::vector<GrpcLBAddress> found_lb_addrs;
  431. AddActualAddresses(*result.addresses, /*is_balancer=*/false,
  432. &found_lb_addrs);
  433. const grpc_core::ServerAddressList* balancer_addresses =
  434. grpc_core::FindGrpclbBalancerAddressesInChannelArgs(*result.args);
  435. if (balancer_addresses != nullptr) {
  436. AddActualAddresses(*balancer_addresses, /*is_balancer=*/true,
  437. &found_lb_addrs);
  438. }
  439. gpr_log(GPR_INFO,
  440. "found %" PRIdPTR " backend addresses and %" PRIdPTR
  441. " balancer addresses",
  442. result.addresses->size(),
  443. balancer_addresses == nullptr ? 0L : balancer_addresses->size());
  444. if (args->expected_addrs.size() != found_lb_addrs.size()) {
  445. gpr_log(GPR_DEBUG,
  446. "found lb addrs size is: %" PRIdPTR
  447. ". expected addrs size is %" PRIdPTR,
  448. found_lb_addrs.size(), args->expected_addrs.size());
  449. abort();
  450. }
  451. if (absl::GetFlag(FLAGS_do_ordered_address_comparison) == "True") {
  452. EXPECT_EQ(args->expected_addrs, found_lb_addrs);
  453. } else if (absl::GetFlag(FLAGS_do_ordered_address_comparison) == "False") {
  454. EXPECT_THAT(args->expected_addrs,
  455. UnorderedElementsAreArray(found_lb_addrs));
  456. } else {
  457. gpr_log(GPR_ERROR,
  458. "Invalid for setting for --do_ordered_address_comparison. "
  459. "Have %s, want True or False",
  460. absl::GetFlag(FLAGS_do_ordered_address_comparison).c_str());
  461. GPR_ASSERT(0);
  462. }
  463. if (!result.service_config.ok()) {
  464. CheckServiceConfigResultLocked(nullptr, result.service_config.status(),
  465. args);
  466. } else if (*result.service_config == nullptr) {
  467. CheckServiceConfigResultLocked(nullptr, absl::OkStatus(), args);
  468. } else {
  469. CheckServiceConfigResultLocked(
  470. std::string((*result.service_config)->json_string()).c_str(),
  471. absl::OkStatus(), args);
  472. }
  473. if (args->expected_service_config_string.empty()) {
  474. CheckLBPolicyResultLocked(result.args, args);
  475. }
  476. }
  477. private:
  478. static void AddActualAddresses(const grpc_core::ServerAddressList& addresses,
  479. bool is_balancer,
  480. std::vector<GrpcLBAddress>* out) {
  481. for (size_t i = 0; i < addresses.size(); i++) {
  482. const grpc_core::ServerAddress& addr = addresses[i];
  483. std::string str =
  484. grpc_sockaddr_to_string(&addr.address(), true /* normalize */);
  485. gpr_log(GPR_INFO, "%s", str.c_str());
  486. out->emplace_back(GrpcLBAddress(std::move(str), is_balancer));
  487. }
  488. }
  489. };
  490. int g_fake_non_responsive_dns_server_port = -1;
  491. /* This function will configure any ares_channel created by the c-ares based
  492. * resolver. This is useful to effectively mock /etc/resolv.conf settings
  493. * (and equivalent on Windows), which unit tests don't have write permissions.
  494. */
  495. void InjectBrokenNameServerList(ares_channel channel) {
  496. struct ares_addr_port_node dns_server_addrs[2];
  497. memset(dns_server_addrs, 0, sizeof(dns_server_addrs));
  498. std::string unused_host;
  499. std::string local_dns_server_port;
  500. GPR_ASSERT(grpc_core::SplitHostPort(
  501. absl::GetFlag(FLAGS_local_dns_server_address).c_str(), &unused_host,
  502. &local_dns_server_port));
  503. gpr_log(GPR_DEBUG,
  504. "Injecting broken nameserver list. Bad server address:|[::1]:%d|. "
  505. "Good server address:%s",
  506. g_fake_non_responsive_dns_server_port,
  507. absl::GetFlag(FLAGS_local_dns_server_address).c_str());
  508. // Put the non-responsive DNS server at the front of c-ares's nameserver list.
  509. dns_server_addrs[0].family = AF_INET6;
  510. (reinterpret_cast<char*>(&dns_server_addrs[0].addr.addr6))[15] = 0x1;
  511. dns_server_addrs[0].tcp_port = g_fake_non_responsive_dns_server_port;
  512. dns_server_addrs[0].udp_port = g_fake_non_responsive_dns_server_port;
  513. dns_server_addrs[0].next = &dns_server_addrs[1];
  514. // Put the actual healthy DNS server after the first one. The expectation is
  515. // that the resolver will timeout the query to the non-responsive DNS server
  516. // and will skip over to this healthy DNS server, without causing any DNS
  517. // resolution errors.
  518. dns_server_addrs[1].family = AF_INET;
  519. (reinterpret_cast<char*>(&dns_server_addrs[1].addr.addr4))[0] = 0x7f;
  520. (reinterpret_cast<char*>(&dns_server_addrs[1].addr.addr4))[3] = 0x1;
  521. dns_server_addrs[1].tcp_port = atoi(local_dns_server_port.c_str());
  522. dns_server_addrs[1].udp_port = atoi(local_dns_server_port.c_str());
  523. dns_server_addrs[1].next = nullptr;
  524. GPR_ASSERT(ares_set_servers_ports(channel, dns_server_addrs) == ARES_SUCCESS);
  525. }
  526. void StartResolvingLocked(grpc_core::Resolver* r) { r->StartLocked(); }
  527. void RunResolvesRelevantRecordsTest(
  528. std::unique_ptr<grpc_core::Resolver::ResultHandler> (*CreateResultHandler)(
  529. ArgsStruct* args)) {
  530. grpc_core::ExecCtx exec_ctx;
  531. ArgsStruct args;
  532. ArgsInit(&args);
  533. args.expected_addrs = ParseExpectedAddrs(absl::GetFlag(FLAGS_expected_addrs));
  534. args.expected_service_config_string =
  535. absl::GetFlag(FLAGS_expected_chosen_service_config);
  536. args.expected_service_config_error =
  537. absl::GetFlag(FLAGS_expected_service_config_error);
  538. args.expected_lb_policy = absl::GetFlag(FLAGS_expected_lb_policy);
  539. // maybe build the address with an authority
  540. std::string whole_uri;
  541. gpr_log(GPR_DEBUG,
  542. "resolver_component_test: --inject_broken_nameserver_list: %s",
  543. absl::GetFlag(FLAGS_inject_broken_nameserver_list).c_str());
  544. std::unique_ptr<grpc_core::testing::FakeUdpAndTcpServer>
  545. fake_non_responsive_dns_server;
  546. if (absl::GetFlag(FLAGS_inject_broken_nameserver_list) == "True") {
  547. fake_non_responsive_dns_server = absl::make_unique<
  548. grpc_core::testing::FakeUdpAndTcpServer>(
  549. grpc_core::testing::FakeUdpAndTcpServer::AcceptMode::
  550. kWaitForClientToSendFirstBytes,
  551. grpc_core::testing::FakeUdpAndTcpServer::CloseSocketUponCloseFromPeer);
  552. g_fake_non_responsive_dns_server_port =
  553. fake_non_responsive_dns_server->port();
  554. grpc_ares_test_only_inject_config = InjectBrokenNameServerList;
  555. whole_uri = absl::StrCat("dns:///", absl::GetFlag(FLAGS_target_name));
  556. } else if (absl::GetFlag(FLAGS_inject_broken_nameserver_list) == "False") {
  557. gpr_log(GPR_INFO, "Specifying authority in uris to: %s",
  558. absl::GetFlag(FLAGS_local_dns_server_address).c_str());
  559. whole_uri = absl::StrFormat("dns://%s/%s",
  560. absl::GetFlag(FLAGS_local_dns_server_address),
  561. absl::GetFlag(FLAGS_target_name));
  562. } else {
  563. gpr_log(GPR_DEBUG, "Invalid value for --inject_broken_nameserver_list.");
  564. abort();
  565. }
  566. gpr_log(GPR_DEBUG, "resolver_component_test: --enable_srv_queries: %s",
  567. absl::GetFlag(FLAGS_enable_srv_queries).c_str());
  568. grpc_channel_args* resolver_args = nullptr;
  569. // By default, SRV queries are disabled, so tests that expect no SRV query
  570. // should avoid setting any channel arg. Test cases that do rely on the SRV
  571. // query must explicitly enable SRV though.
  572. if (absl::GetFlag(FLAGS_enable_srv_queries) == "True") {
  573. grpc_arg srv_queries_arg = grpc_channel_arg_integer_create(
  574. const_cast<char*>(GRPC_ARG_DNS_ENABLE_SRV_QUERIES), true);
  575. resolver_args =
  576. grpc_channel_args_copy_and_add(nullptr, &srv_queries_arg, 1);
  577. } else if (absl::GetFlag(FLAGS_enable_srv_queries) != "False") {
  578. gpr_log(GPR_DEBUG, "Invalid value for --enable_srv_queries.");
  579. abort();
  580. }
  581. gpr_log(GPR_DEBUG, "resolver_component_test: --enable_txt_queries: %s",
  582. absl::GetFlag(FLAGS_enable_txt_queries).c_str());
  583. // By default, TXT queries are disabled, so tests that expect no TXT query
  584. // should avoid setting any channel arg. Test cases that do rely on the TXT
  585. // query must explicitly enable TXT though.
  586. if (absl::GetFlag(FLAGS_enable_txt_queries) == "True") {
  587. // Unlike SRV queries, there isn't a channel arg specific to TXT records.
  588. // Rather, we use the resolver-agnostic "service config" resolution option,
  589. // for which c-ares has its own specific default value, which isn't
  590. // necessarily shared by other resolvers.
  591. grpc_arg txt_queries_arg = grpc_channel_arg_integer_create(
  592. const_cast<char*>(GRPC_ARG_SERVICE_CONFIG_DISABLE_RESOLUTION), false);
  593. grpc_channel_args* tmp_args =
  594. grpc_channel_args_copy_and_add(resolver_args, &txt_queries_arg, 1);
  595. grpc_channel_args_destroy(resolver_args);
  596. resolver_args = tmp_args;
  597. } else if (absl::GetFlag(FLAGS_enable_txt_queries) != "False") {
  598. gpr_log(GPR_DEBUG, "Invalid value for --enable_txt_queries.");
  599. abort();
  600. }
  601. // create resolver and resolve
  602. grpc_core::OrphanablePtr<grpc_core::Resolver> resolver =
  603. grpc_core::CoreConfiguration::Get().resolver_registry().CreateResolver(
  604. whole_uri.c_str(), resolver_args, args.pollset_set, args.lock,
  605. CreateResultHandler(&args));
  606. grpc_channel_args_destroy(resolver_args);
  607. auto* resolver_ptr = resolver.get();
  608. args.lock->Run([resolver_ptr]() { StartResolvingLocked(resolver_ptr); },
  609. DEBUG_LOCATION);
  610. grpc_core::ExecCtx::Get()->Flush();
  611. PollPollsetUntilRequestDone(&args);
  612. ArgsFinish(&args);
  613. }
  614. TEST(ResolverComponentTest, TestResolvesRelevantRecords) {
  615. RunResolvesRelevantRecordsTest(CheckingResultHandler::Create);
  616. }
  617. TEST(ResolverComponentTest, TestResolvesRelevantRecordsWithConcurrentFdStress) {
  618. // Start up background stress thread
  619. int phony_port = grpc_pick_unused_port_or_die();
  620. gpr_event done_ev;
  621. gpr_event_init(&done_ev);
  622. std::thread socket_stress_thread(OpenAndCloseSocketsStressLoop, phony_port,
  623. &done_ev);
  624. // Run the resolver test
  625. RunResolvesRelevantRecordsTest(ResultHandler::Create);
  626. // Shutdown and join stress thread
  627. gpr_event_set(&done_ev, reinterpret_cast<void*>(1));
  628. socket_stress_thread.join();
  629. }
  630. } // namespace
  631. int main(int argc, char** argv) {
  632. grpc_init();
  633. grpc::testing::TestEnvironment env(argc, argv);
  634. ::testing::InitGoogleTest(&argc, argv);
  635. grpc::testing::InitTest(&argc, &argv, true);
  636. if (absl::GetFlag(FLAGS_target_name).empty()) {
  637. gpr_log(GPR_ERROR, "Missing target_name param.");
  638. abort();
  639. }
  640. auto result = RUN_ALL_TESTS();
  641. grpc_shutdown();
  642. return result;
  643. }