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