client_lb_end2end_test.cc 44 KB

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