1 /*
2 *
3 * Copyright 2016 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 <algorithm>
20 #include <memory>
21 #include <mutex>
22 #include <random>
23 #include <thread>
24
25 #include <grpc/grpc.h>
26 #include <grpc/support/alloc.h>
27 #include <grpc/support/atm.h>
28 #include <grpc/support/log.h>
29 #include <grpc/support/string_util.h>
30 #include <grpc/support/time.h>
31 #include <grpcpp/channel.h>
32 #include <grpcpp/client_context.h>
33 #include <grpcpp/create_channel.h>
34 #include <grpcpp/server.h>
35 #include <grpcpp/server_builder.h>
36
37 #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
38 #include "src/core/ext/filters/client_channel/subchannel_index.h"
39 #include "src/core/lib/backoff/backoff.h"
40 #include "src/core/lib/gpr/env.h"
41 #include "src/core/lib/gprpp/debug_location.h"
42 #include "src/core/lib/gprpp/ref_counted_ptr.h"
43 #include "src/core/lib/iomgr/tcp_client.h"
44
45 #include "src/proto/grpc/testing/echo.grpc.pb.h"
46 #include "test/core/util/port.h"
47 #include "test/core/util/test_config.h"
48 #include "test/cpp/end2end/test_service_impl.h"
49
50 #include <gtest/gtest.h>
51
52 using grpc::testing::EchoRequest;
53 using grpc::testing::EchoResponse;
54 using std::chrono::system_clock;
55
56 // defined in tcp_client.cc
57 extern grpc_tcp_client_vtable* grpc_tcp_client_impl;
58
59 static grpc_tcp_client_vtable* default_client_impl;
60
61 namespace grpc {
62 namespace testing {
63 namespace {
64
65 gpr_atm g_connection_delay_ms;
66
tcp_client_connect_with_delay(grpc_closure * closure,grpc_endpoint ** ep,grpc_pollset_set * interested_parties,const grpc_channel_args * channel_args,const grpc_resolved_address * addr,grpc_millis deadline)67 void tcp_client_connect_with_delay(grpc_closure* closure, grpc_endpoint** ep,
68 grpc_pollset_set* interested_parties,
69 const grpc_channel_args* channel_args,
70 const grpc_resolved_address* addr,
71 grpc_millis deadline) {
72 const int delay_ms = gpr_atm_acq_load(&g_connection_delay_ms);
73 if (delay_ms > 0) {
74 gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms));
75 }
76 default_client_impl->connect(closure, ep, interested_parties, channel_args,
77 addr, deadline + delay_ms);
78 }
79
80 grpc_tcp_client_vtable delayed_connect = {tcp_client_connect_with_delay};
81
82 // Subclass of TestServiceImpl that increments a request counter for
83 // every call to the Echo RPC.
84 class MyTestServiceImpl : public TestServiceImpl {
85 public:
MyTestServiceImpl()86 MyTestServiceImpl() : request_count_(0) {}
87
Echo(ServerContext * context,const EchoRequest * request,EchoResponse * response)88 Status Echo(ServerContext* context, const EchoRequest* request,
89 EchoResponse* response) override {
90 {
91 std::unique_lock<std::mutex> lock(mu_);
92 ++request_count_;
93 }
94 return TestServiceImpl::Echo(context, request, response);
95 }
96
request_count()97 int request_count() {
98 std::unique_lock<std::mutex> lock(mu_);
99 return request_count_;
100 }
101
ResetCounters()102 void ResetCounters() {
103 std::unique_lock<std::mutex> lock(mu_);
104 request_count_ = 0;
105 }
106
107 private:
108 std::mutex mu_;
109 int request_count_;
110 };
111
112 class ClientLbEnd2endTest : public ::testing::Test {
113 protected:
ClientLbEnd2endTest()114 ClientLbEnd2endTest()
115 : server_host_("localhost"), kRequestMessage_("Live long and prosper.") {
116 // Make the backup poller poll very frequently in order to pick up
117 // updates from all the subchannels's FDs.
118 gpr_setenv("GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS", "1");
119 }
120
SetUp()121 void SetUp() override {
122 grpc_init();
123 response_generator_ =
124 grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
125 }
126
TearDown()127 void TearDown() override {
128 for (size_t i = 0; i < servers_.size(); ++i) {
129 servers_[i]->Shutdown();
130 }
131 grpc_shutdown();
132 }
133
CreateServers(size_t num_servers,std::vector<int> ports=std::vector<int> ())134 void CreateServers(size_t num_servers,
135 std::vector<int> ports = std::vector<int>()) {
136 servers_.clear();
137 for (size_t i = 0; i < num_servers; ++i) {
138 int port = 0;
139 if (ports.size() == num_servers) port = ports[i];
140 servers_.emplace_back(new ServerData(port));
141 }
142 }
143
StartServer(size_t index)144 void StartServer(size_t index) { servers_[index]->Start(server_host_); }
145
StartServers(size_t num_servers,std::vector<int> ports=std::vector<int> ())146 void StartServers(size_t num_servers,
147 std::vector<int> ports = std::vector<int>()) {
148 CreateServers(num_servers, ports);
149 for (size_t i = 0; i < num_servers; ++i) {
150 StartServer(i);
151 }
152 }
153
BuildFakeResults(const std::vector<int> & ports)154 grpc_channel_args* BuildFakeResults(const std::vector<int>& ports) {
155 grpc_lb_addresses* addresses =
156 grpc_lb_addresses_create(ports.size(), nullptr);
157 for (size_t i = 0; i < ports.size(); ++i) {
158 char* lb_uri_str;
159 gpr_asprintf(&lb_uri_str, "ipv4:127.0.0.1:%d", ports[i]);
160 grpc_uri* lb_uri = grpc_uri_parse(lb_uri_str, true);
161 GPR_ASSERT(lb_uri != nullptr);
162 grpc_lb_addresses_set_address_from_uri(addresses, i, lb_uri,
163 false /* is balancer */,
164 "" /* balancer name */, nullptr);
165 grpc_uri_destroy(lb_uri);
166 gpr_free(lb_uri_str);
167 }
168 const grpc_arg fake_addresses =
169 grpc_lb_addresses_create_channel_arg(addresses);
170 grpc_channel_args* fake_results =
171 grpc_channel_args_copy_and_add(nullptr, &fake_addresses, 1);
172 grpc_lb_addresses_destroy(addresses);
173 return fake_results;
174 }
175
SetNextResolution(const std::vector<int> & ports)176 void SetNextResolution(const std::vector<int>& ports) {
177 grpc_core::ExecCtx exec_ctx;
178 grpc_channel_args* fake_results = BuildFakeResults(ports);
179 response_generator_->SetResponse(fake_results);
180 grpc_channel_args_destroy(fake_results);
181 }
182
SetNextResolutionUponError(const std::vector<int> & ports)183 void SetNextResolutionUponError(const std::vector<int>& ports) {
184 grpc_core::ExecCtx exec_ctx;
185 grpc_channel_args* fake_results = BuildFakeResults(ports);
186 response_generator_->SetReresolutionResponse(fake_results);
187 grpc_channel_args_destroy(fake_results);
188 }
189
GetServersPorts()190 std::vector<int> GetServersPorts() {
191 std::vector<int> ports;
192 for (const auto& server : servers_) ports.push_back(server->port_);
193 return ports;
194 }
195
BuildStub(const std::shared_ptr<Channel> & channel)196 std::unique_ptr<grpc::testing::EchoTestService::Stub> BuildStub(
197 const std::shared_ptr<Channel>& channel) {
198 return grpc::testing::EchoTestService::NewStub(channel);
199 }
200
BuildChannel(const grpc::string & lb_policy_name,ChannelArguments args=ChannelArguments ())201 std::shared_ptr<Channel> BuildChannel(
202 const grpc::string& lb_policy_name,
203 ChannelArguments args = ChannelArguments()) {
204 if (lb_policy_name.size() > 0) {
205 args.SetLoadBalancingPolicyName(lb_policy_name);
206 } // else, default to pick first
207 args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
208 response_generator_.get());
209 return CreateCustomChannel("fake:///", InsecureChannelCredentials(), args);
210 }
211
SendRpc(const std::unique_ptr<grpc::testing::EchoTestService::Stub> & stub,EchoResponse * response=nullptr,int timeout_ms=1000,Status * result=nullptr)212 bool SendRpc(
213 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
214 EchoResponse* response = nullptr, int timeout_ms = 1000,
215 Status* result = nullptr) {
216 const bool local_response = (response == nullptr);
217 if (local_response) response = new EchoResponse;
218 EchoRequest request;
219 request.set_message(kRequestMessage_);
220 ClientContext context;
221 context.set_deadline(grpc_timeout_milliseconds_to_deadline(timeout_ms));
222 Status status = stub->Echo(&context, request, response);
223 if (result != nullptr) *result = status;
224 if (local_response) delete response;
225 return status.ok();
226 }
227
CheckRpcSendOk(const std::unique_ptr<grpc::testing::EchoTestService::Stub> & stub,const grpc_core::DebugLocation & location)228 void CheckRpcSendOk(
229 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
230 const grpc_core::DebugLocation& location) {
231 EchoResponse response;
232 Status status;
233 const bool success = SendRpc(stub, &response, 2000, &status);
234 ASSERT_TRUE(success) << "From " << location.file() << ":" << location.line()
235 << "\n"
236 << "Error: " << status.error_message() << " "
237 << status.error_details();
238 ASSERT_EQ(response.message(), kRequestMessage_)
239 << "From " << location.file() << ":" << location.line();
240 if (!success) abort();
241 }
242
CheckRpcSendFailure(const std::unique_ptr<grpc::testing::EchoTestService::Stub> & stub)243 void CheckRpcSendFailure(
244 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub) {
245 const bool success = SendRpc(stub);
246 EXPECT_FALSE(success);
247 }
248
249 struct ServerData {
250 int port_;
251 std::unique_ptr<Server> server_;
252 MyTestServiceImpl service_;
253 std::unique_ptr<std::thread> thread_;
254 bool server_ready_ = false;
255
ServerDatagrpc::testing::__anon6844b3ba0111::ClientLbEnd2endTest::ServerData256 explicit ServerData(int port = 0) {
257 port_ = port > 0 ? port : grpc_pick_unused_port_or_die();
258 }
259
Startgrpc::testing::__anon6844b3ba0111::ClientLbEnd2endTest::ServerData260 void Start(const grpc::string& server_host) {
261 gpr_log(GPR_INFO, "starting server on port %d", port_);
262 std::mutex mu;
263 std::unique_lock<std::mutex> lock(mu);
264 std::condition_variable cond;
265 thread_.reset(new std::thread(
266 std::bind(&ServerData::Serve, this, server_host, &mu, &cond)));
267 cond.wait(lock, [this] { return server_ready_; });
268 server_ready_ = false;
269 gpr_log(GPR_INFO, "server startup complete");
270 }
271
Servegrpc::testing::__anon6844b3ba0111::ClientLbEnd2endTest::ServerData272 void Serve(const grpc::string& server_host, std::mutex* mu,
273 std::condition_variable* cond) {
274 std::ostringstream server_address;
275 server_address << server_host << ":" << port_;
276 ServerBuilder builder;
277 builder.AddListeningPort(server_address.str(),
278 InsecureServerCredentials());
279 builder.RegisterService(&service_);
280 server_ = builder.BuildAndStart();
281 std::lock_guard<std::mutex> lock(*mu);
282 server_ready_ = true;
283 cond->notify_one();
284 }
285
Shutdowngrpc::testing::__anon6844b3ba0111::ClientLbEnd2endTest::ServerData286 void Shutdown(bool join = true) {
287 server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
288 if (join) thread_->join();
289 }
290 };
291
ResetCounters()292 void ResetCounters() {
293 for (const auto& server : servers_) server->service_.ResetCounters();
294 }
295
WaitForServer(const std::unique_ptr<grpc::testing::EchoTestService::Stub> & stub,size_t server_idx,const grpc_core::DebugLocation & location,bool ignore_failure=false)296 void WaitForServer(
297 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
298 size_t server_idx, const grpc_core::DebugLocation& location,
299 bool ignore_failure = false) {
300 do {
301 if (ignore_failure) {
302 SendRpc(stub);
303 } else {
304 CheckRpcSendOk(stub, location);
305 }
306 } while (servers_[server_idx]->service_.request_count() == 0);
307 ResetCounters();
308 }
309
WaitForChannelNotReady(Channel * channel,int timeout_seconds=5)310 bool WaitForChannelNotReady(Channel* channel, int timeout_seconds = 5) {
311 const gpr_timespec deadline =
312 grpc_timeout_seconds_to_deadline(timeout_seconds);
313 grpc_connectivity_state state;
314 while ((state = channel->GetState(false /* try_to_connect */)) ==
315 GRPC_CHANNEL_READY) {
316 if (!channel->WaitForStateChange(state, deadline)) return false;
317 }
318 return true;
319 }
320
SeenAllServers()321 bool SeenAllServers() {
322 for (const auto& server : servers_) {
323 if (server->service_.request_count() == 0) return false;
324 }
325 return true;
326 }
327
328 // Updates \a connection_order by appending to it the index of the newly
329 // connected server. Must be called after every single RPC.
UpdateConnectionOrder(const std::vector<std::unique_ptr<ServerData>> & servers,std::vector<int> * connection_order)330 void UpdateConnectionOrder(
331 const std::vector<std::unique_ptr<ServerData>>& servers,
332 std::vector<int>* connection_order) {
333 for (size_t i = 0; i < servers.size(); ++i) {
334 if (servers[i]->service_.request_count() == 1) {
335 // Was the server index known? If not, update connection_order.
336 const auto it =
337 std::find(connection_order->begin(), connection_order->end(), i);
338 if (it == connection_order->end()) {
339 connection_order->push_back(i);
340 return;
341 }
342 }
343 }
344 }
345
346 const grpc::string server_host_;
347 std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
348 std::vector<std::unique_ptr<ServerData>> servers_;
349 grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
350 response_generator_;
351 const grpc::string kRequestMessage_;
352 };
353
TEST_F(ClientLbEnd2endTest,PickFirst)354 TEST_F(ClientLbEnd2endTest, PickFirst) {
355 // Start servers and send one RPC per server.
356 const int kNumServers = 3;
357 StartServers(kNumServers);
358 auto channel = BuildChannel(""); // test that pick first is the default.
359 auto stub = BuildStub(channel);
360 std::vector<int> ports;
361 for (size_t i = 0; i < servers_.size(); ++i) {
362 ports.emplace_back(servers_[i]->port_);
363 }
364 SetNextResolution(ports);
365 for (size_t i = 0; i < servers_.size(); ++i) {
366 CheckRpcSendOk(stub, DEBUG_LOCATION);
367 }
368 // All requests should have gone to a single server.
369 bool found = false;
370 for (size_t i = 0; i < servers_.size(); ++i) {
371 const int request_count = servers_[i]->service_.request_count();
372 if (request_count == kNumServers) {
373 found = true;
374 } else {
375 EXPECT_EQ(0, request_count);
376 }
377 }
378 EXPECT_TRUE(found);
379 // Check LB policy name for the channel.
380 EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
381 }
382
TEST_F(ClientLbEnd2endTest,PickFirstProcessPending)383 TEST_F(ClientLbEnd2endTest, PickFirstProcessPending) {
384 StartServers(1); // Single server
385 auto channel = BuildChannel(""); // test that pick first is the default.
386 auto stub = BuildStub(channel);
387 SetNextResolution({servers_[0]->port_});
388 WaitForServer(stub, 0, DEBUG_LOCATION);
389 // Create a new channel and its corresponding PF LB policy, which will pick
390 // the subchannels in READY state from the previous RPC against the same
391 // target (even if it happened over a different channel, because subchannels
392 // are globally reused). Progress should happen without any transition from
393 // this READY state.
394 auto second_channel = BuildChannel("");
395 auto second_stub = BuildStub(second_channel);
396 SetNextResolution({servers_[0]->port_});
397 CheckRpcSendOk(second_stub, DEBUG_LOCATION);
398 }
399
TEST_F(ClientLbEnd2endTest,PickFirstBackOffInitialReconnect)400 TEST_F(ClientLbEnd2endTest, PickFirstBackOffInitialReconnect) {
401 ChannelArguments args;
402 constexpr int kInitialBackOffMs = 100;
403 args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
404 const std::vector<int> ports = {grpc_pick_unused_port_or_die()};
405 const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
406 auto channel = BuildChannel("pick_first", args);
407 auto stub = BuildStub(channel);
408 SetNextResolution(ports);
409 // The channel won't become connected (there's no server).
410 ASSERT_FALSE(channel->WaitForConnected(
411 grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 2)));
412 // Bring up a server on the chosen port.
413 StartServers(1, ports);
414 // Now it will.
415 ASSERT_TRUE(channel->WaitForConnected(
416 grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 2)));
417 const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
418 const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
419 gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited_ms);
420 // We should have waited at least kInitialBackOffMs. We substract one to
421 // account for test and precision accuracy drift.
422 EXPECT_GE(waited_ms, kInitialBackOffMs - 1);
423 // But not much more.
424 EXPECT_GT(
425 gpr_time_cmp(
426 grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 1.10), t1),
427 0);
428 }
429
TEST_F(ClientLbEnd2endTest,PickFirstBackOffMinReconnect)430 TEST_F(ClientLbEnd2endTest, PickFirstBackOffMinReconnect) {
431 ChannelArguments args;
432 constexpr int kMinReconnectBackOffMs = 1000;
433 args.SetInt(GRPC_ARG_MIN_RECONNECT_BACKOFF_MS, kMinReconnectBackOffMs);
434 const std::vector<int> ports = {grpc_pick_unused_port_or_die()};
435 auto channel = BuildChannel("pick_first", args);
436 auto stub = BuildStub(channel);
437 SetNextResolution(ports);
438 // Make connection delay a 10% longer than it's willing to in order to make
439 // sure we are hitting the codepath that waits for the min reconnect backoff.
440 gpr_atm_rel_store(&g_connection_delay_ms, kMinReconnectBackOffMs * 1.10);
441 default_client_impl = grpc_tcp_client_impl;
442 grpc_set_tcp_client_impl(&delayed_connect);
443 const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
444 channel->WaitForConnected(
445 grpc_timeout_milliseconds_to_deadline(kMinReconnectBackOffMs * 2));
446 const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
447 const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
448 gpr_log(GPR_DEBUG, "Waited %" PRId64 " ms", waited_ms);
449 // We should have waited at least kMinReconnectBackOffMs. We substract one to
450 // account for test and precision accuracy drift.
451 EXPECT_GE(waited_ms, kMinReconnectBackOffMs - 1);
452 gpr_atm_rel_store(&g_connection_delay_ms, 0);
453 }
454
TEST_F(ClientLbEnd2endTest,PickFirstResetConnectionBackoff)455 TEST_F(ClientLbEnd2endTest, PickFirstResetConnectionBackoff) {
456 ChannelArguments args;
457 constexpr int kInitialBackOffMs = 1000;
458 args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
459 const std::vector<int> ports = {grpc_pick_unused_port_or_die()};
460 auto channel = BuildChannel("pick_first", args);
461 auto stub = BuildStub(channel);
462 SetNextResolution(ports);
463 // The channel won't become connected (there's no server).
464 EXPECT_FALSE(
465 channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
466 // Bring up a server on the chosen port.
467 StartServers(1, ports);
468 const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
469 // Wait for connect, but not long enough. This proves that we're
470 // being throttled by initial backoff.
471 EXPECT_FALSE(
472 channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
473 // Reset connection backoff.
474 experimental::ChannelResetConnectionBackoff(channel.get());
475 // Wait for connect. Should happen ~immediately.
476 EXPECT_TRUE(
477 channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
478 const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
479 const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
480 gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited_ms);
481 // We should have waited less than kInitialBackOffMs.
482 EXPECT_LT(waited_ms, kInitialBackOffMs);
483 }
484
TEST_F(ClientLbEnd2endTest,PickFirstUpdates)485 TEST_F(ClientLbEnd2endTest, PickFirstUpdates) {
486 // Start servers and send one RPC per server.
487 const int kNumServers = 3;
488 StartServers(kNumServers);
489 auto channel = BuildChannel("pick_first");
490 auto stub = BuildStub(channel);
491
492 std::vector<int> ports;
493
494 // Perform one RPC against the first server.
495 ports.emplace_back(servers_[0]->port_);
496 SetNextResolution(ports);
497 gpr_log(GPR_INFO, "****** SET [0] *******");
498 CheckRpcSendOk(stub, DEBUG_LOCATION);
499 EXPECT_EQ(servers_[0]->service_.request_count(), 1);
500
501 // An empty update will result in the channel going into TRANSIENT_FAILURE.
502 ports.clear();
503 SetNextResolution(ports);
504 gpr_log(GPR_INFO, "****** SET none *******");
505 grpc_connectivity_state channel_state;
506 do {
507 channel_state = channel->GetState(true /* try to connect */);
508 } while (channel_state == GRPC_CHANNEL_READY);
509 GPR_ASSERT(channel_state != GRPC_CHANNEL_READY);
510 servers_[0]->service_.ResetCounters();
511
512 // Next update introduces servers_[1], making the channel recover.
513 ports.clear();
514 ports.emplace_back(servers_[1]->port_);
515 SetNextResolution(ports);
516 gpr_log(GPR_INFO, "****** SET [1] *******");
517 WaitForServer(stub, 1, DEBUG_LOCATION);
518 EXPECT_EQ(servers_[0]->service_.request_count(), 0);
519
520 // And again for servers_[2]
521 ports.clear();
522 ports.emplace_back(servers_[2]->port_);
523 SetNextResolution(ports);
524 gpr_log(GPR_INFO, "****** SET [2] *******");
525 WaitForServer(stub, 2, DEBUG_LOCATION);
526 EXPECT_EQ(servers_[0]->service_.request_count(), 0);
527 EXPECT_EQ(servers_[1]->service_.request_count(), 0);
528
529 // Check LB policy name for the channel.
530 EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
531 }
532
TEST_F(ClientLbEnd2endTest,PickFirstUpdateSuperset)533 TEST_F(ClientLbEnd2endTest, PickFirstUpdateSuperset) {
534 // Start servers and send one RPC per server.
535 const int kNumServers = 3;
536 StartServers(kNumServers);
537 auto channel = BuildChannel("pick_first");
538 auto stub = BuildStub(channel);
539
540 std::vector<int> ports;
541
542 // Perform one RPC against the first server.
543 ports.emplace_back(servers_[0]->port_);
544 SetNextResolution(ports);
545 gpr_log(GPR_INFO, "****** SET [0] *******");
546 CheckRpcSendOk(stub, DEBUG_LOCATION);
547 EXPECT_EQ(servers_[0]->service_.request_count(), 1);
548 servers_[0]->service_.ResetCounters();
549
550 // Send and superset update
551 ports.clear();
552 ports.emplace_back(servers_[1]->port_);
553 ports.emplace_back(servers_[0]->port_);
554 SetNextResolution(ports);
555 gpr_log(GPR_INFO, "****** SET superset *******");
556 CheckRpcSendOk(stub, DEBUG_LOCATION);
557 // We stick to the previously connected server.
558 WaitForServer(stub, 0, DEBUG_LOCATION);
559 EXPECT_EQ(0, servers_[1]->service_.request_count());
560
561 // Check LB policy name for the channel.
562 EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
563 }
564
565 class ClientLbEnd2endWithParamTest
566 : public ClientLbEnd2endTest,
567 public ::testing::WithParamInterface<bool> {
568 protected:
SetUp()569 void SetUp() override {
570 grpc_subchannel_index_test_only_set_force_creation(GetParam());
571 ClientLbEnd2endTest::SetUp();
572 }
573
TearDown()574 void TearDown() override {
575 ClientLbEnd2endTest::TearDown();
576 grpc_subchannel_index_test_only_set_force_creation(false);
577 }
578 };
579
TEST_P(ClientLbEnd2endWithParamTest,PickFirstManyUpdates)580 TEST_P(ClientLbEnd2endWithParamTest, PickFirstManyUpdates) {
581 gpr_log(GPR_INFO, "subchannel force creation: %d", GetParam());
582 // Start servers and send one RPC per server.
583 const int kNumServers = 3;
584 StartServers(kNumServers);
585 auto channel = BuildChannel("pick_first");
586 auto stub = BuildStub(channel);
587 std::vector<int> ports;
588 for (size_t i = 0; i < servers_.size(); ++i) {
589 ports.emplace_back(servers_[i]->port_);
590 }
591 for (size_t i = 0; i < 1000; ++i) {
592 std::shuffle(ports.begin(), ports.end(),
593 std::mt19937(std::random_device()()));
594 SetNextResolution(ports);
595 // We should re-enter core at the end of the loop to give the resolution
596 // setting closure a chance to run.
597 if ((i + 1) % 10 == 0) CheckRpcSendOk(stub, DEBUG_LOCATION);
598 }
599 // Check LB policy name for the channel.
600 EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
601 }
602
603 INSTANTIATE_TEST_CASE_P(SubchannelForceCreation, ClientLbEnd2endWithParamTest,
604 ::testing::Bool());
605
TEST_F(ClientLbEnd2endTest,PickFirstReresolutionNoSelected)606 TEST_F(ClientLbEnd2endTest, PickFirstReresolutionNoSelected) {
607 // Prepare the ports for up servers and down servers.
608 const int kNumServers = 3;
609 const int kNumAliveServers = 1;
610 StartServers(kNumAliveServers);
611 std::vector<int> alive_ports, dead_ports;
612 for (size_t i = 0; i < kNumServers; ++i) {
613 if (i < kNumAliveServers) {
614 alive_ports.emplace_back(servers_[i]->port_);
615 } else {
616 dead_ports.emplace_back(grpc_pick_unused_port_or_die());
617 }
618 }
619 auto channel = BuildChannel("pick_first");
620 auto stub = BuildStub(channel);
621 // The initial resolution only contains dead ports. There won't be any
622 // selected subchannel. Re-resolution will return the same result.
623 SetNextResolution(dead_ports);
624 gpr_log(GPR_INFO, "****** INITIAL RESOLUTION SET *******");
625 for (size_t i = 0; i < 10; ++i) CheckRpcSendFailure(stub);
626 // Set a re-resolution result that contains reachable ports, so that the
627 // pick_first LB policy can recover soon.
628 SetNextResolutionUponError(alive_ports);
629 gpr_log(GPR_INFO, "****** RE-RESOLUTION SET *******");
630 WaitForServer(stub, 0, DEBUG_LOCATION, true /* ignore_failure */);
631 CheckRpcSendOk(stub, DEBUG_LOCATION);
632 EXPECT_EQ(servers_[0]->service_.request_count(), 1);
633 // Check LB policy name for the channel.
634 EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
635 }
636
TEST_F(ClientLbEnd2endTest,PickFirstReconnectWithoutNewResolverResult)637 TEST_F(ClientLbEnd2endTest, PickFirstReconnectWithoutNewResolverResult) {
638 std::vector<int> ports = {grpc_pick_unused_port_or_die()};
639 StartServers(1, ports);
640 auto channel = BuildChannel("pick_first");
641 auto stub = BuildStub(channel);
642 SetNextResolution(ports);
643 gpr_log(GPR_INFO, "****** INITIAL CONNECTION *******");
644 WaitForServer(stub, 0, DEBUG_LOCATION);
645 gpr_log(GPR_INFO, "****** STOPPING SERVER ******");
646 servers_[0]->Shutdown();
647 EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
648 gpr_log(GPR_INFO, "****** RESTARTING SERVER ******");
649 StartServers(1, ports);
650 WaitForServer(stub, 0, DEBUG_LOCATION);
651 }
652
TEST_F(ClientLbEnd2endTest,PickFirstReconnectWithoutNewResolverResultStartsFromTopOfList)653 TEST_F(ClientLbEnd2endTest,
654 PickFirstReconnectWithoutNewResolverResultStartsFromTopOfList) {
655 std::vector<int> ports = {grpc_pick_unused_port_or_die(),
656 grpc_pick_unused_port_or_die()};
657 CreateServers(2, ports);
658 StartServer(1);
659 auto channel = BuildChannel("pick_first");
660 auto stub = BuildStub(channel);
661 SetNextResolution(ports);
662 gpr_log(GPR_INFO, "****** INITIAL CONNECTION *******");
663 WaitForServer(stub, 1, DEBUG_LOCATION);
664 gpr_log(GPR_INFO, "****** STOPPING SERVER ******");
665 servers_[1]->Shutdown();
666 EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
667 gpr_log(GPR_INFO, "****** STARTING BOTH SERVERS ******");
668 StartServers(2, ports);
669 WaitForServer(stub, 0, DEBUG_LOCATION);
670 }
671
TEST_F(ClientLbEnd2endTest,PickFirstCheckStateBeforeStartWatch)672 TEST_F(ClientLbEnd2endTest, PickFirstCheckStateBeforeStartWatch) {
673 std::vector<int> ports = {grpc_pick_unused_port_or_die()};
674 StartServers(1, ports);
675 auto channel_1 = BuildChannel("pick_first");
676 auto stub_1 = BuildStub(channel_1);
677 SetNextResolution(ports);
678 gpr_log(GPR_INFO, "****** RESOLUTION SET FOR CHANNEL 1 *******");
679 WaitForServer(stub_1, 0, DEBUG_LOCATION);
680 gpr_log(GPR_INFO, "****** CHANNEL 1 CONNECTED *******");
681 servers_[0]->Shutdown();
682 // Channel 1 will receive a re-resolution containing the same server. It will
683 // create a new subchannel and hold a ref to it.
684 StartServers(1, ports);
685 gpr_log(GPR_INFO, "****** SERVER RESTARTED *******");
686 auto channel_2 = BuildChannel("pick_first");
687 auto stub_2 = BuildStub(channel_2);
688 // TODO(juanlishen): This resolution result will only be visible to channel 2
689 // since the response generator is only associated with channel 2 now. We
690 // should change the response generator to be able to deliver updates to
691 // multiple channels at once.
692 SetNextResolution(ports);
693 gpr_log(GPR_INFO, "****** RESOLUTION SET FOR CHANNEL 2 *******");
694 WaitForServer(stub_2, 0, DEBUG_LOCATION, true);
695 gpr_log(GPR_INFO, "****** CHANNEL 2 CONNECTED *******");
696 servers_[0]->Shutdown();
697 // Wait until the disconnection has triggered the connectivity notification.
698 // Otherwise, the subchannel may be picked for next call but will fail soon.
699 EXPECT_TRUE(WaitForChannelNotReady(channel_2.get()));
700 // Channel 2 will also receive a re-resolution containing the same server.
701 // Both channels will ref the same subchannel that failed.
702 StartServers(1, ports);
703 gpr_log(GPR_INFO, "****** SERVER RESTARTED AGAIN *******");
704 gpr_log(GPR_INFO, "****** CHANNEL 2 STARTING A CALL *******");
705 // The first call after the server restart will succeed.
706 CheckRpcSendOk(stub_2, DEBUG_LOCATION);
707 gpr_log(GPR_INFO, "****** CHANNEL 2 FINISHED A CALL *******");
708 // Check LB policy name for the channel.
709 EXPECT_EQ("pick_first", channel_1->GetLoadBalancingPolicyName());
710 // Check LB policy name for the channel.
711 EXPECT_EQ("pick_first", channel_2->GetLoadBalancingPolicyName());
712 }
713
TEST_F(ClientLbEnd2endTest,RoundRobin)714 TEST_F(ClientLbEnd2endTest, RoundRobin) {
715 // Start servers and send one RPC per server.
716 const int kNumServers = 3;
717 StartServers(kNumServers);
718 auto channel = BuildChannel("round_robin");
719 auto stub = BuildStub(channel);
720 std::vector<int> ports;
721 for (const auto& server : servers_) {
722 ports.emplace_back(server->port_);
723 }
724 SetNextResolution(ports);
725 // Wait until all backends are ready.
726 do {
727 CheckRpcSendOk(stub, DEBUG_LOCATION);
728 } while (!SeenAllServers());
729 ResetCounters();
730 // "Sync" to the end of the list. Next sequence of picks will start at the
731 // first server (index 0).
732 WaitForServer(stub, servers_.size() - 1, DEBUG_LOCATION);
733 std::vector<int> connection_order;
734 for (size_t i = 0; i < servers_.size(); ++i) {
735 CheckRpcSendOk(stub, DEBUG_LOCATION);
736 UpdateConnectionOrder(servers_, &connection_order);
737 }
738 // Backends should be iterated over in the order in which the addresses were
739 // given.
740 const auto expected = std::vector<int>{0, 1, 2};
741 EXPECT_EQ(expected, connection_order);
742 // Check LB policy name for the channel.
743 EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
744 }
745
TEST_F(ClientLbEnd2endTest,RoundRobinProcessPending)746 TEST_F(ClientLbEnd2endTest, RoundRobinProcessPending) {
747 StartServers(1); // Single server
748 auto channel = BuildChannel("round_robin");
749 auto stub = BuildStub(channel);
750 SetNextResolution({servers_[0]->port_});
751 WaitForServer(stub, 0, DEBUG_LOCATION);
752 // Create a new channel and its corresponding RR LB policy, which will pick
753 // the subchannels in READY state from the previous RPC against the same
754 // target (even if it happened over a different channel, because subchannels
755 // are globally reused). Progress should happen without any transition from
756 // this READY state.
757 auto second_channel = BuildChannel("round_robin");
758 auto second_stub = BuildStub(second_channel);
759 SetNextResolution({servers_[0]->port_});
760 CheckRpcSendOk(second_stub, DEBUG_LOCATION);
761 }
762
TEST_F(ClientLbEnd2endTest,RoundRobinUpdates)763 TEST_F(ClientLbEnd2endTest, RoundRobinUpdates) {
764 // Start servers and send one RPC per server.
765 const int kNumServers = 3;
766 StartServers(kNumServers);
767 auto channel = BuildChannel("round_robin");
768 auto stub = BuildStub(channel);
769 std::vector<int> ports;
770
771 // Start with a single server.
772 ports.emplace_back(servers_[0]->port_);
773 SetNextResolution(ports);
774 WaitForServer(stub, 0, DEBUG_LOCATION);
775 // Send RPCs. They should all go servers_[0]
776 for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
777 EXPECT_EQ(10, servers_[0]->service_.request_count());
778 EXPECT_EQ(0, servers_[1]->service_.request_count());
779 EXPECT_EQ(0, servers_[2]->service_.request_count());
780 servers_[0]->service_.ResetCounters();
781
782 // And now for the second server.
783 ports.clear();
784 ports.emplace_back(servers_[1]->port_);
785 SetNextResolution(ports);
786
787 // Wait until update has been processed, as signaled by the second backend
788 // receiving a request.
789 EXPECT_EQ(0, servers_[1]->service_.request_count());
790 WaitForServer(stub, 1, DEBUG_LOCATION);
791
792 for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
793 EXPECT_EQ(0, servers_[0]->service_.request_count());
794 EXPECT_EQ(10, servers_[1]->service_.request_count());
795 EXPECT_EQ(0, servers_[2]->service_.request_count());
796 servers_[1]->service_.ResetCounters();
797
798 // ... and for the last server.
799 ports.clear();
800 ports.emplace_back(servers_[2]->port_);
801 SetNextResolution(ports);
802 WaitForServer(stub, 2, DEBUG_LOCATION);
803
804 for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
805 EXPECT_EQ(0, servers_[0]->service_.request_count());
806 EXPECT_EQ(0, servers_[1]->service_.request_count());
807 EXPECT_EQ(10, servers_[2]->service_.request_count());
808 servers_[2]->service_.ResetCounters();
809
810 // Back to all servers.
811 ports.clear();
812 ports.emplace_back(servers_[0]->port_);
813 ports.emplace_back(servers_[1]->port_);
814 ports.emplace_back(servers_[2]->port_);
815 SetNextResolution(ports);
816 WaitForServer(stub, 0, DEBUG_LOCATION);
817 WaitForServer(stub, 1, DEBUG_LOCATION);
818 WaitForServer(stub, 2, DEBUG_LOCATION);
819
820 // Send three RPCs, one per server.
821 for (size_t i = 0; i < 3; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
822 EXPECT_EQ(1, servers_[0]->service_.request_count());
823 EXPECT_EQ(1, servers_[1]->service_.request_count());
824 EXPECT_EQ(1, servers_[2]->service_.request_count());
825
826 // An empty update will result in the channel going into TRANSIENT_FAILURE.
827 ports.clear();
828 SetNextResolution(ports);
829 grpc_connectivity_state channel_state;
830 do {
831 channel_state = channel->GetState(true /* try to connect */);
832 } while (channel_state == GRPC_CHANNEL_READY);
833 GPR_ASSERT(channel_state != GRPC_CHANNEL_READY);
834 servers_[0]->service_.ResetCounters();
835
836 // Next update introduces servers_[1], making the channel recover.
837 ports.clear();
838 ports.emplace_back(servers_[1]->port_);
839 SetNextResolution(ports);
840 WaitForServer(stub, 1, DEBUG_LOCATION);
841 channel_state = channel->GetState(false /* try to connect */);
842 GPR_ASSERT(channel_state == GRPC_CHANNEL_READY);
843
844 // Check LB policy name for the channel.
845 EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
846 }
847
TEST_F(ClientLbEnd2endTest,RoundRobinUpdateInError)848 TEST_F(ClientLbEnd2endTest, RoundRobinUpdateInError) {
849 const int kNumServers = 3;
850 StartServers(kNumServers);
851 auto channel = BuildChannel("round_robin");
852 auto stub = BuildStub(channel);
853 std::vector<int> ports;
854
855 // Start with a single server.
856 ports.emplace_back(servers_[0]->port_);
857 SetNextResolution(ports);
858 WaitForServer(stub, 0, DEBUG_LOCATION);
859 // Send RPCs. They should all go to servers_[0]
860 for (size_t i = 0; i < 10; ++i) SendRpc(stub);
861 EXPECT_EQ(10, servers_[0]->service_.request_count());
862 EXPECT_EQ(0, servers_[1]->service_.request_count());
863 EXPECT_EQ(0, servers_[2]->service_.request_count());
864 servers_[0]->service_.ResetCounters();
865
866 // Shutdown one of the servers to be sent in the update.
867 servers_[1]->Shutdown(false);
868 ports.emplace_back(servers_[1]->port_);
869 ports.emplace_back(servers_[2]->port_);
870 SetNextResolution(ports);
871 WaitForServer(stub, 0, DEBUG_LOCATION);
872 WaitForServer(stub, 2, DEBUG_LOCATION);
873
874 // Send three RPCs, one per server.
875 for (size_t i = 0; i < kNumServers; ++i) SendRpc(stub);
876 // The server in shutdown shouldn't receive any.
877 EXPECT_EQ(0, servers_[1]->service_.request_count());
878 }
879
TEST_F(ClientLbEnd2endTest,RoundRobinManyUpdates)880 TEST_F(ClientLbEnd2endTest, RoundRobinManyUpdates) {
881 // Start servers and send one RPC per server.
882 const int kNumServers = 3;
883 StartServers(kNumServers);
884 auto channel = BuildChannel("round_robin");
885 auto stub = BuildStub(channel);
886 std::vector<int> ports;
887 for (size_t i = 0; i < servers_.size(); ++i) {
888 ports.emplace_back(servers_[i]->port_);
889 }
890 for (size_t i = 0; i < 1000; ++i) {
891 std::shuffle(ports.begin(), ports.end(),
892 std::mt19937(std::random_device()()));
893 SetNextResolution(ports);
894 if (i % 10 == 0) CheckRpcSendOk(stub, DEBUG_LOCATION);
895 }
896 // Check LB policy name for the channel.
897 EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
898 }
899
TEST_F(ClientLbEnd2endTest,RoundRobinConcurrentUpdates)900 TEST_F(ClientLbEnd2endTest, RoundRobinConcurrentUpdates) {
901 // TODO(dgq): replicate the way internal testing exercises the concurrent
902 // update provisions of RR.
903 }
904
TEST_F(ClientLbEnd2endTest,RoundRobinReresolve)905 TEST_F(ClientLbEnd2endTest, RoundRobinReresolve) {
906 // Start servers and send one RPC per server.
907 const int kNumServers = 3;
908 std::vector<int> first_ports;
909 std::vector<int> second_ports;
910 first_ports.reserve(kNumServers);
911 for (int i = 0; i < kNumServers; ++i) {
912 first_ports.push_back(grpc_pick_unused_port_or_die());
913 }
914 second_ports.reserve(kNumServers);
915 for (int i = 0; i < kNumServers; ++i) {
916 second_ports.push_back(grpc_pick_unused_port_or_die());
917 }
918 StartServers(kNumServers, first_ports);
919 auto channel = BuildChannel("round_robin");
920 auto stub = BuildStub(channel);
921 SetNextResolution(first_ports);
922 // Send a number of RPCs, which succeed.
923 for (size_t i = 0; i < 100; ++i) {
924 CheckRpcSendOk(stub, DEBUG_LOCATION);
925 }
926 // Kill all servers
927 gpr_log(GPR_INFO, "****** ABOUT TO KILL SERVERS *******");
928 for (size_t i = 0; i < servers_.size(); ++i) {
929 servers_[i]->Shutdown(true);
930 }
931 gpr_log(GPR_INFO, "****** SERVERS KILLED *******");
932 gpr_log(GPR_INFO, "****** SENDING DOOMED REQUESTS *******");
933 // Client requests should fail. Send enough to tickle all subchannels.
934 for (size_t i = 0; i < servers_.size(); ++i) CheckRpcSendFailure(stub);
935 gpr_log(GPR_INFO, "****** DOOMED REQUESTS SENT *******");
936 // Bring servers back up on a different set of ports. We need to do this to be
937 // sure that the eventual success is *not* due to subchannel reconnection
938 // attempts and that an actual re-resolution has happened as a result of the
939 // RR policy going into transient failure when all its subchannels become
940 // unavailable (in transient failure as well).
941 gpr_log(GPR_INFO, "****** RESTARTING SERVERS *******");
942 StartServers(kNumServers, second_ports);
943 // Don't notify of the update. Wait for the LB policy's re-resolution to
944 // "pull" the new ports.
945 SetNextResolutionUponError(second_ports);
946 gpr_log(GPR_INFO, "****** SERVERS RESTARTED *******");
947 gpr_log(GPR_INFO, "****** SENDING REQUEST TO SUCCEED *******");
948 // Client request should eventually (but still fairly soon) succeed.
949 const gpr_timespec deadline = grpc_timeout_seconds_to_deadline(5);
950 gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
951 while (gpr_time_cmp(deadline, now) > 0) {
952 if (SendRpc(stub)) break;
953 now = gpr_now(GPR_CLOCK_MONOTONIC);
954 }
955 GPR_ASSERT(gpr_time_cmp(deadline, now) > 0);
956 }
957
TEST_F(ClientLbEnd2endTest,RoundRobinSingleReconnect)958 TEST_F(ClientLbEnd2endTest, RoundRobinSingleReconnect) {
959 const int kNumServers = 3;
960 StartServers(kNumServers);
961 const auto ports = GetServersPorts();
962 auto channel = BuildChannel("round_robin");
963 auto stub = BuildStub(channel);
964 SetNextResolution(ports);
965 for (size_t i = 0; i < kNumServers; ++i)
966 WaitForServer(stub, i, DEBUG_LOCATION);
967 for (size_t i = 0; i < servers_.size(); ++i) {
968 CheckRpcSendOk(stub, DEBUG_LOCATION);
969 EXPECT_EQ(1, servers_[i]->service_.request_count()) << "for backend #" << i;
970 }
971 // One request should have gone to each server.
972 for (size_t i = 0; i < servers_.size(); ++i) {
973 EXPECT_EQ(1, servers_[i]->service_.request_count());
974 }
975 const auto pre_death = servers_[0]->service_.request_count();
976 // Kill the first server.
977 servers_[0]->Shutdown(true);
978 // Client request still succeed. May need retrying if RR had returned a pick
979 // before noticing the change in the server's connectivity.
980 while (!SendRpc(stub)) {
981 } // Retry until success.
982 // Send a bunch of RPCs that should succeed.
983 for (int i = 0; i < 10 * kNumServers; ++i) {
984 CheckRpcSendOk(stub, DEBUG_LOCATION);
985 }
986 const auto post_death = servers_[0]->service_.request_count();
987 // No requests have gone to the deceased server.
988 EXPECT_EQ(pre_death, post_death);
989 // Bring the first server back up.
990 servers_[0].reset(new ServerData(ports[0]));
991 StartServer(0);
992 // Requests should start arriving at the first server either right away (if
993 // the server managed to start before the RR policy retried the subchannel) or
994 // after the subchannel retry delay otherwise (RR's subchannel retried before
995 // the server was fully back up).
996 WaitForServer(stub, 0, DEBUG_LOCATION);
997 }
998
999 } // namespace
1000 } // namespace testing
1001 } // namespace grpc
1002
main(int argc,char ** argv)1003 int main(int argc, char** argv) {
1004 ::testing::InitGoogleTest(&argc, argv);
1005 grpc_test_init(argc, argv);
1006 const auto result = RUN_ALL_TESTS();
1007 return result;
1008 }
1009