client_lb_end2end_test.cc 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811
  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 <set>
  23. #include <string>
  24. #include <thread>
  25. #include "absl/strings/str_cat.h"
  26. #include <grpc/grpc.h>
  27. #include <grpc/support/alloc.h>
  28. #include <grpc/support/atm.h>
  29. #include <grpc/support/log.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/health_check_service_interface.h>
  35. #include <grpcpp/impl/codegen/sync.h>
  36. #include <grpcpp/server.h>
  37. #include <grpcpp/server_builder.h>
  38. #include "src/core/ext/filters/client_channel/backup_poller.h"
  39. #include "src/core/ext/filters/client_channel/global_subchannel_pool.h"
  40. #include "src/core/ext/filters/client_channel/parse_address.h"
  41. #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
  42. #include "src/core/ext/filters/client_channel/server_address.h"
  43. #include "src/core/ext/filters/client_channel/service_config.h"
  44. #include "src/core/lib/backoff/backoff.h"
  45. #include "src/core/lib/channel/channel_args.h"
  46. #include "src/core/lib/gpr/env.h"
  47. #include "src/core/lib/gprpp/debug_location.h"
  48. #include "src/core/lib/gprpp/ref_counted_ptr.h"
  49. #include "src/core/lib/iomgr/tcp_client.h"
  50. #include "src/core/lib/security/credentials/fake/fake_credentials.h"
  51. #include "src/cpp/client/secure_credentials.h"
  52. #include "src/cpp/server/secure_server_credentials.h"
  53. #include "src/proto/grpc/testing/echo.grpc.pb.h"
  54. #include "src/proto/grpc/testing/xds/orca_load_report_for_test.pb.h"
  55. #include "test/core/util/port.h"
  56. #include "test/core/util/test_config.h"
  57. #include "test/core/util/test_lb_policies.h"
  58. #include "test/cpp/end2end/test_service_impl.h"
  59. #include <gmock/gmock.h>
  60. #include <gtest/gtest.h>
  61. using grpc::testing::EchoRequest;
  62. using grpc::testing::EchoResponse;
  63. using std::chrono::system_clock;
  64. // defined in tcp_client.cc
  65. extern grpc_tcp_client_vtable* grpc_tcp_client_impl;
  66. static grpc_tcp_client_vtable* default_client_impl;
  67. namespace grpc {
  68. namespace testing {
  69. namespace {
  70. gpr_atm g_connection_delay_ms;
  71. void tcp_client_connect_with_delay(grpc_closure* closure, grpc_endpoint** ep,
  72. grpc_pollset_set* interested_parties,
  73. const grpc_channel_args* channel_args,
  74. const grpc_resolved_address* addr,
  75. grpc_millis deadline) {
  76. const int delay_ms = gpr_atm_acq_load(&g_connection_delay_ms);
  77. if (delay_ms > 0) {
  78. gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(delay_ms));
  79. }
  80. default_client_impl->connect(closure, ep, interested_parties, channel_args,
  81. addr, deadline + delay_ms);
  82. }
  83. grpc_tcp_client_vtable delayed_connect = {tcp_client_connect_with_delay};
  84. // Subclass of TestServiceImpl that increments a request counter for
  85. // every call to the Echo RPC.
  86. class MyTestServiceImpl : public TestServiceImpl {
  87. public:
  88. Status Echo(ServerContext* context, const EchoRequest* request,
  89. EchoResponse* response) override {
  90. const udpa::data::orca::v1::OrcaLoadReport* load_report = nullptr;
  91. {
  92. grpc::internal::MutexLock lock(&mu_);
  93. ++request_count_;
  94. load_report = load_report_;
  95. }
  96. AddClient(context->peer());
  97. if (load_report != nullptr) {
  98. // TODO(roth): Once we provide a more standard server-side API for
  99. // populating this data, use that API here.
  100. context->AddTrailingMetadata("x-endpoint-load-metrics-bin",
  101. load_report->SerializeAsString());
  102. }
  103. return TestServiceImpl::Echo(context, request, response);
  104. }
  105. int request_count() {
  106. grpc::internal::MutexLock lock(&mu_);
  107. return request_count_;
  108. }
  109. void ResetCounters() {
  110. grpc::internal::MutexLock lock(&mu_);
  111. request_count_ = 0;
  112. }
  113. std::set<std::string> clients() {
  114. grpc::internal::MutexLock lock(&clients_mu_);
  115. return clients_;
  116. }
  117. void set_load_report(udpa::data::orca::v1::OrcaLoadReport* load_report) {
  118. grpc::internal::MutexLock lock(&mu_);
  119. load_report_ = load_report;
  120. }
  121. private:
  122. void AddClient(const std::string& client) {
  123. grpc::internal::MutexLock lock(&clients_mu_);
  124. clients_.insert(client);
  125. }
  126. grpc::internal::Mutex mu_;
  127. int request_count_ = 0;
  128. const udpa::data::orca::v1::OrcaLoadReport* load_report_ = nullptr;
  129. grpc::internal::Mutex clients_mu_;
  130. std::set<std::string> clients_;
  131. };
  132. class FakeResolverResponseGeneratorWrapper {
  133. public:
  134. FakeResolverResponseGeneratorWrapper()
  135. : response_generator_(grpc_core::MakeRefCounted<
  136. grpc_core::FakeResolverResponseGenerator>()) {}
  137. FakeResolverResponseGeneratorWrapper(
  138. FakeResolverResponseGeneratorWrapper&& other) noexcept {
  139. response_generator_ = std::move(other.response_generator_);
  140. }
  141. void SetNextResolution(const std::vector<int>& ports,
  142. const char* service_config_json = nullptr) {
  143. grpc_core::ExecCtx exec_ctx;
  144. response_generator_->SetResponse(
  145. BuildFakeResults(ports, service_config_json));
  146. }
  147. void SetNextResolutionUponError(const std::vector<int>& ports) {
  148. grpc_core::ExecCtx exec_ctx;
  149. response_generator_->SetReresolutionResponse(BuildFakeResults(ports));
  150. }
  151. void SetFailureOnReresolution() {
  152. grpc_core::ExecCtx exec_ctx;
  153. response_generator_->SetFailureOnReresolution();
  154. }
  155. grpc_core::FakeResolverResponseGenerator* Get() const {
  156. return response_generator_.get();
  157. }
  158. private:
  159. static grpc_core::Resolver::Result BuildFakeResults(
  160. const std::vector<int>& ports,
  161. const char* service_config_json = nullptr) {
  162. grpc_core::Resolver::Result result;
  163. for (const int& port : ports) {
  164. std::string lb_uri_str = absl::StrCat("ipv4:127.0.0.1:", port);
  165. grpc_uri* lb_uri = grpc_uri_parse(lb_uri_str.c_str(), true);
  166. GPR_ASSERT(lb_uri != nullptr);
  167. grpc_resolved_address address;
  168. GPR_ASSERT(grpc_parse_uri(lb_uri, &address));
  169. result.addresses.emplace_back(address.addr, address.len,
  170. nullptr /* args */);
  171. grpc_uri_destroy(lb_uri);
  172. }
  173. if (service_config_json != nullptr) {
  174. result.service_config = grpc_core::ServiceConfig::Create(
  175. service_config_json, &result.service_config_error);
  176. GPR_ASSERT(result.service_config != nullptr);
  177. }
  178. return result;
  179. }
  180. grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
  181. response_generator_;
  182. };
  183. class ClientLbEnd2endTest : public ::testing::Test {
  184. protected:
  185. ClientLbEnd2endTest()
  186. : server_host_("localhost"),
  187. kRequestMessage_("Live long and prosper."),
  188. creds_(new SecureChannelCredentials(
  189. grpc_fake_transport_security_credentials_create())) {}
  190. static void SetUpTestCase() {
  191. // Make the backup poller poll very frequently in order to pick up
  192. // updates from all the subchannels's FDs.
  193. GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
  194. #if TARGET_OS_IPHONE
  195. // Workaround Apple CFStream bug
  196. gpr_setenv("grpc_cfstream", "0");
  197. #endif
  198. }
  199. void SetUp() override { grpc_init(); }
  200. void TearDown() override {
  201. for (size_t i = 0; i < servers_.size(); ++i) {
  202. servers_[i]->Shutdown();
  203. }
  204. servers_.clear();
  205. creds_.reset();
  206. grpc_shutdown_blocking();
  207. }
  208. void CreateServers(size_t num_servers,
  209. std::vector<int> ports = std::vector<int>()) {
  210. servers_.clear();
  211. for (size_t i = 0; i < num_servers; ++i) {
  212. int port = 0;
  213. if (ports.size() == num_servers) port = ports[i];
  214. servers_.emplace_back(new ServerData(port));
  215. }
  216. }
  217. void StartServer(size_t index) { servers_[index]->Start(server_host_); }
  218. void StartServers(size_t num_servers,
  219. std::vector<int> ports = std::vector<int>()) {
  220. CreateServers(num_servers, std::move(ports));
  221. for (size_t i = 0; i < num_servers; ++i) {
  222. StartServer(i);
  223. }
  224. }
  225. std::vector<int> GetServersPorts(size_t start_index = 0) {
  226. std::vector<int> ports;
  227. for (size_t i = start_index; i < servers_.size(); ++i) {
  228. ports.push_back(servers_[i]->port_);
  229. }
  230. return ports;
  231. }
  232. FakeResolverResponseGeneratorWrapper BuildResolverResponseGenerator() {
  233. return FakeResolverResponseGeneratorWrapper();
  234. }
  235. std::unique_ptr<grpc::testing::EchoTestService::Stub> BuildStub(
  236. const std::shared_ptr<Channel>& channel) {
  237. return grpc::testing::EchoTestService::NewStub(channel);
  238. }
  239. std::shared_ptr<Channel> BuildChannel(
  240. const std::string& lb_policy_name,
  241. const FakeResolverResponseGeneratorWrapper& response_generator,
  242. ChannelArguments args = ChannelArguments()) {
  243. if (lb_policy_name.size() > 0) {
  244. args.SetLoadBalancingPolicyName(lb_policy_name);
  245. } // else, default to pick first
  246. args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
  247. response_generator.Get());
  248. return ::grpc::CreateCustomChannel("fake:///", creds_, args);
  249. }
  250. bool SendRpc(
  251. const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
  252. EchoResponse* response = nullptr, int timeout_ms = 1000,
  253. Status* result = nullptr, bool wait_for_ready = false) {
  254. const bool local_response = (response == nullptr);
  255. if (local_response) response = new EchoResponse;
  256. EchoRequest request;
  257. request.set_message(kRequestMessage_);
  258. ClientContext context;
  259. context.set_deadline(grpc_timeout_milliseconds_to_deadline(timeout_ms));
  260. if (wait_for_ready) context.set_wait_for_ready(true);
  261. Status status = stub->Echo(&context, request, response);
  262. if (result != nullptr) *result = status;
  263. if (local_response) delete response;
  264. return status.ok();
  265. }
  266. void CheckRpcSendOk(
  267. const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
  268. const grpc_core::DebugLocation& location, bool wait_for_ready = false) {
  269. EchoResponse response;
  270. Status status;
  271. const bool success =
  272. SendRpc(stub, &response, 2000, &status, wait_for_ready);
  273. ASSERT_TRUE(success) << "From " << location.file() << ":" << location.line()
  274. << "\n"
  275. << "Error: " << status.error_message() << " "
  276. << status.error_details();
  277. ASSERT_EQ(response.message(), kRequestMessage_)
  278. << "From " << location.file() << ":" << location.line();
  279. if (!success) abort();
  280. }
  281. void CheckRpcSendFailure(
  282. const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub) {
  283. const bool success = SendRpc(stub);
  284. EXPECT_FALSE(success);
  285. }
  286. struct ServerData {
  287. int port_;
  288. std::unique_ptr<Server> server_;
  289. MyTestServiceImpl service_;
  290. std::unique_ptr<std::thread> thread_;
  291. bool server_ready_ = false;
  292. bool started_ = false;
  293. explicit ServerData(int port = 0) {
  294. port_ = port > 0 ? port : grpc_pick_unused_port_or_die();
  295. }
  296. void Start(const std::string& server_host) {
  297. gpr_log(GPR_INFO, "starting server on port %d", port_);
  298. started_ = true;
  299. grpc::internal::Mutex mu;
  300. grpc::internal::MutexLock lock(&mu);
  301. grpc::internal::CondVar cond;
  302. thread_.reset(new std::thread(
  303. std::bind(&ServerData::Serve, this, server_host, &mu, &cond)));
  304. cond.WaitUntil(&mu, [this] { return server_ready_; });
  305. server_ready_ = false;
  306. gpr_log(GPR_INFO, "server startup complete");
  307. }
  308. void Serve(const std::string& server_host, grpc::internal::Mutex* mu,
  309. grpc::internal::CondVar* cond) {
  310. std::ostringstream server_address;
  311. server_address << server_host << ":" << port_;
  312. ServerBuilder builder;
  313. std::shared_ptr<ServerCredentials> creds(new SecureServerCredentials(
  314. grpc_fake_transport_security_server_credentials_create()));
  315. builder.AddListeningPort(server_address.str(), std::move(creds));
  316. builder.RegisterService(&service_);
  317. server_ = builder.BuildAndStart();
  318. grpc::internal::MutexLock lock(mu);
  319. server_ready_ = true;
  320. cond->Signal();
  321. }
  322. void Shutdown() {
  323. if (!started_) return;
  324. server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
  325. thread_->join();
  326. started_ = false;
  327. }
  328. void SetServingStatus(const std::string& service, bool serving) {
  329. server_->GetHealthCheckService()->SetServingStatus(service, serving);
  330. }
  331. };
  332. void ResetCounters() {
  333. for (const auto& server : servers_) server->service_.ResetCounters();
  334. }
  335. void WaitForServer(
  336. const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
  337. size_t server_idx, const grpc_core::DebugLocation& location,
  338. bool ignore_failure = false) {
  339. do {
  340. if (ignore_failure) {
  341. SendRpc(stub);
  342. } else {
  343. CheckRpcSendOk(stub, location, true);
  344. }
  345. } while (servers_[server_idx]->service_.request_count() == 0);
  346. ResetCounters();
  347. }
  348. bool WaitForChannelState(
  349. Channel* channel, std::function<bool(grpc_connectivity_state)> predicate,
  350. bool try_to_connect = false, int timeout_seconds = 5) {
  351. const gpr_timespec deadline =
  352. grpc_timeout_seconds_to_deadline(timeout_seconds);
  353. while (true) {
  354. grpc_connectivity_state state = channel->GetState(try_to_connect);
  355. if (predicate(state)) break;
  356. if (!channel->WaitForStateChange(state, deadline)) return false;
  357. }
  358. return true;
  359. }
  360. bool WaitForChannelNotReady(Channel* channel, int timeout_seconds = 5) {
  361. auto predicate = [](grpc_connectivity_state state) {
  362. return state != GRPC_CHANNEL_READY;
  363. };
  364. return WaitForChannelState(channel, predicate, false, timeout_seconds);
  365. }
  366. bool WaitForChannelReady(Channel* channel, int timeout_seconds = 5) {
  367. auto predicate = [](grpc_connectivity_state state) {
  368. return state == GRPC_CHANNEL_READY;
  369. };
  370. return WaitForChannelState(channel, predicate, true, timeout_seconds);
  371. }
  372. bool SeenAllServers() {
  373. for (const auto& server : servers_) {
  374. if (server->service_.request_count() == 0) return false;
  375. }
  376. return true;
  377. }
  378. // Updates \a connection_order by appending to it the index of the newly
  379. // connected server. Must be called after every single RPC.
  380. void UpdateConnectionOrder(
  381. const std::vector<std::unique_ptr<ServerData>>& servers,
  382. std::vector<int>* connection_order) {
  383. for (size_t i = 0; i < servers.size(); ++i) {
  384. if (servers[i]->service_.request_count() == 1) {
  385. // Was the server index known? If not, update connection_order.
  386. const auto it =
  387. std::find(connection_order->begin(), connection_order->end(), i);
  388. if (it == connection_order->end()) {
  389. connection_order->push_back(i);
  390. return;
  391. }
  392. }
  393. }
  394. }
  395. const std::string server_host_;
  396. std::vector<std::unique_ptr<ServerData>> servers_;
  397. const std::string kRequestMessage_;
  398. std::shared_ptr<ChannelCredentials> creds_;
  399. };
  400. TEST_F(ClientLbEnd2endTest, ChannelStateConnectingWhenResolving) {
  401. const int kNumServers = 3;
  402. StartServers(kNumServers);
  403. auto response_generator = BuildResolverResponseGenerator();
  404. auto channel = BuildChannel("", response_generator);
  405. auto stub = BuildStub(channel);
  406. // Initial state should be IDLE.
  407. EXPECT_EQ(channel->GetState(false /* try_to_connect */), GRPC_CHANNEL_IDLE);
  408. // Tell the channel to try to connect.
  409. // Note that this call also returns IDLE, since the state change has
  410. // not yet occurred; it just gets triggered by this call.
  411. EXPECT_EQ(channel->GetState(true /* try_to_connect */), GRPC_CHANNEL_IDLE);
  412. // Now that the channel is trying to connect, we should be in state
  413. // CONNECTING.
  414. EXPECT_EQ(channel->GetState(false /* try_to_connect */),
  415. GRPC_CHANNEL_CONNECTING);
  416. // Return a resolver result, which allows the connection attempt to proceed.
  417. response_generator.SetNextResolution(GetServersPorts());
  418. // We should eventually transition into state READY.
  419. EXPECT_TRUE(WaitForChannelReady(channel.get()));
  420. }
  421. TEST_F(ClientLbEnd2endTest, PickFirst) {
  422. // Start servers and send one RPC per server.
  423. const int kNumServers = 3;
  424. StartServers(kNumServers);
  425. auto response_generator = BuildResolverResponseGenerator();
  426. auto channel = BuildChannel(
  427. "", response_generator); // test that pick first is the default.
  428. auto stub = BuildStub(channel);
  429. response_generator.SetNextResolution(GetServersPorts());
  430. for (size_t i = 0; i < servers_.size(); ++i) {
  431. CheckRpcSendOk(stub, DEBUG_LOCATION);
  432. }
  433. // All requests should have gone to a single server.
  434. bool found = false;
  435. for (size_t i = 0; i < servers_.size(); ++i) {
  436. const int request_count = servers_[i]->service_.request_count();
  437. if (request_count == kNumServers) {
  438. found = true;
  439. } else {
  440. EXPECT_EQ(0, request_count);
  441. }
  442. }
  443. EXPECT_TRUE(found);
  444. // Check LB policy name for the channel.
  445. EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
  446. }
  447. TEST_F(ClientLbEnd2endTest, PickFirstProcessPending) {
  448. StartServers(1); // Single server
  449. auto response_generator = BuildResolverResponseGenerator();
  450. auto channel = BuildChannel(
  451. "", response_generator); // test that pick first is the default.
  452. auto stub = BuildStub(channel);
  453. response_generator.SetNextResolution({servers_[0]->port_});
  454. WaitForServer(stub, 0, DEBUG_LOCATION);
  455. // Create a new channel and its corresponding PF LB policy, which will pick
  456. // the subchannels in READY state from the previous RPC against the same
  457. // target (even if it happened over a different channel, because subchannels
  458. // are globally reused). Progress should happen without any transition from
  459. // this READY state.
  460. auto second_response_generator = BuildResolverResponseGenerator();
  461. auto second_channel = BuildChannel("", second_response_generator);
  462. auto second_stub = BuildStub(second_channel);
  463. second_response_generator.SetNextResolution({servers_[0]->port_});
  464. CheckRpcSendOk(second_stub, DEBUG_LOCATION);
  465. }
  466. TEST_F(ClientLbEnd2endTest, PickFirstSelectsReadyAtStartup) {
  467. ChannelArguments args;
  468. constexpr int kInitialBackOffMs = 5000;
  469. args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
  470. // Create 2 servers, but start only the second one.
  471. std::vector<int> ports = {grpc_pick_unused_port_or_die(),
  472. grpc_pick_unused_port_or_die()};
  473. CreateServers(2, ports);
  474. StartServer(1);
  475. auto response_generator1 = BuildResolverResponseGenerator();
  476. auto channel1 = BuildChannel("pick_first", response_generator1, args);
  477. auto stub1 = BuildStub(channel1);
  478. response_generator1.SetNextResolution(ports);
  479. // Wait for second server to be ready.
  480. WaitForServer(stub1, 1, DEBUG_LOCATION);
  481. // Create a second channel with the same addresses. Its PF instance
  482. // should immediately pick the second subchannel, since it's already
  483. // in READY state.
  484. auto response_generator2 = BuildResolverResponseGenerator();
  485. auto channel2 = BuildChannel("pick_first", response_generator2, args);
  486. response_generator2.SetNextResolution(ports);
  487. // Check that the channel reports READY without waiting for the
  488. // initial backoff.
  489. EXPECT_TRUE(WaitForChannelReady(channel2.get(), 1 /* timeout_seconds */));
  490. }
  491. TEST_F(ClientLbEnd2endTest, PickFirstBackOffInitialReconnect) {
  492. ChannelArguments args;
  493. constexpr int kInitialBackOffMs = 100;
  494. args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
  495. const std::vector<int> ports = {grpc_pick_unused_port_or_die()};
  496. const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
  497. auto response_generator = BuildResolverResponseGenerator();
  498. auto channel = BuildChannel("pick_first", response_generator, args);
  499. auto stub = BuildStub(channel);
  500. response_generator.SetNextResolution(ports);
  501. // The channel won't become connected (there's no server).
  502. ASSERT_FALSE(channel->WaitForConnected(
  503. grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 2)));
  504. // Bring up a server on the chosen port.
  505. StartServers(1, ports);
  506. // Now it will.
  507. ASSERT_TRUE(channel->WaitForConnected(
  508. grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 2)));
  509. const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
  510. const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
  511. gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited_ms);
  512. // We should have waited at least kInitialBackOffMs. We substract one to
  513. // account for test and precision accuracy drift.
  514. EXPECT_GE(waited_ms, kInitialBackOffMs - 1);
  515. // But not much more.
  516. EXPECT_GT(
  517. gpr_time_cmp(
  518. grpc_timeout_milliseconds_to_deadline(kInitialBackOffMs * 1.10), t1),
  519. 0);
  520. }
  521. TEST_F(ClientLbEnd2endTest, PickFirstBackOffMinReconnect) {
  522. ChannelArguments args;
  523. constexpr int kMinReconnectBackOffMs = 1000;
  524. args.SetInt(GRPC_ARG_MIN_RECONNECT_BACKOFF_MS, kMinReconnectBackOffMs);
  525. const std::vector<int> ports = {grpc_pick_unused_port_or_die()};
  526. auto response_generator = BuildResolverResponseGenerator();
  527. auto channel = BuildChannel("pick_first", response_generator, args);
  528. auto stub = BuildStub(channel);
  529. response_generator.SetNextResolution(ports);
  530. // Make connection delay a 10% longer than it's willing to in order to make
  531. // sure we are hitting the codepath that waits for the min reconnect backoff.
  532. gpr_atm_rel_store(&g_connection_delay_ms, kMinReconnectBackOffMs * 1.10);
  533. default_client_impl = grpc_tcp_client_impl;
  534. grpc_set_tcp_client_impl(&delayed_connect);
  535. const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
  536. channel->WaitForConnected(
  537. grpc_timeout_milliseconds_to_deadline(kMinReconnectBackOffMs * 2));
  538. const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
  539. const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
  540. gpr_log(GPR_DEBUG, "Waited %" PRId64 " ms", waited_ms);
  541. // We should have waited at least kMinReconnectBackOffMs. We substract one to
  542. // account for test and precision accuracy drift.
  543. EXPECT_GE(waited_ms, kMinReconnectBackOffMs - 1);
  544. gpr_atm_rel_store(&g_connection_delay_ms, 0);
  545. }
  546. TEST_F(ClientLbEnd2endTest, PickFirstResetConnectionBackoff) {
  547. ChannelArguments args;
  548. constexpr int kInitialBackOffMs = 1000;
  549. args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
  550. const std::vector<int> ports = {grpc_pick_unused_port_or_die()};
  551. auto response_generator = BuildResolverResponseGenerator();
  552. auto channel = BuildChannel("pick_first", response_generator, args);
  553. auto stub = BuildStub(channel);
  554. response_generator.SetNextResolution(ports);
  555. // The channel won't become connected (there's no server).
  556. EXPECT_FALSE(
  557. channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
  558. // Bring up a server on the chosen port.
  559. StartServers(1, ports);
  560. const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
  561. // Wait for connect, but not long enough. This proves that we're
  562. // being throttled by initial backoff.
  563. EXPECT_FALSE(
  564. channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
  565. // Reset connection backoff.
  566. experimental::ChannelResetConnectionBackoff(channel.get());
  567. // Wait for connect. Should happen as soon as the client connects to
  568. // the newly started server, which should be before the initial
  569. // backoff timeout elapses.
  570. EXPECT_TRUE(
  571. channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(20)));
  572. const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
  573. const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
  574. gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited_ms);
  575. // We should have waited less than kInitialBackOffMs.
  576. EXPECT_LT(waited_ms, kInitialBackOffMs);
  577. }
  578. TEST_F(ClientLbEnd2endTest,
  579. PickFirstResetConnectionBackoffNextAttemptStartsImmediately) {
  580. ChannelArguments args;
  581. constexpr int kInitialBackOffMs = 1000;
  582. args.SetInt(GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS, kInitialBackOffMs);
  583. const std::vector<int> ports = {grpc_pick_unused_port_or_die()};
  584. auto response_generator = BuildResolverResponseGenerator();
  585. auto channel = BuildChannel("pick_first", response_generator, args);
  586. auto stub = BuildStub(channel);
  587. response_generator.SetNextResolution(ports);
  588. // Wait for connect, which should fail ~immediately, because the server
  589. // is not up.
  590. gpr_log(GPR_INFO, "=== INITIAL CONNECTION ATTEMPT");
  591. EXPECT_FALSE(
  592. channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
  593. // Reset connection backoff.
  594. // Note that the time at which the third attempt will be started is
  595. // actually computed at this point, so we record the start time here.
  596. gpr_log(GPR_INFO, "=== RESETTING BACKOFF");
  597. const gpr_timespec t0 = gpr_now(GPR_CLOCK_MONOTONIC);
  598. experimental::ChannelResetConnectionBackoff(channel.get());
  599. // Trigger a second connection attempt. This should also fail
  600. // ~immediately, but the retry should be scheduled for
  601. // kInitialBackOffMs instead of applying the multiplier.
  602. gpr_log(GPR_INFO, "=== POLLING FOR SECOND CONNECTION ATTEMPT");
  603. EXPECT_FALSE(
  604. channel->WaitForConnected(grpc_timeout_milliseconds_to_deadline(10)));
  605. // Bring up a server on the chosen port.
  606. gpr_log(GPR_INFO, "=== STARTING BACKEND");
  607. StartServers(1, ports);
  608. // Wait for connect. Should happen within kInitialBackOffMs.
  609. // Give an extra 100ms to account for the time spent in the second and
  610. // third connection attempts themselves (since what we really want to
  611. // measure is the time between the two). As long as this is less than
  612. // the 1.6x increase we would see if the backoff state was not reset
  613. // properly, the test is still proving that the backoff was reset.
  614. constexpr int kWaitMs = kInitialBackOffMs + 100;
  615. gpr_log(GPR_INFO, "=== POLLING FOR THIRD CONNECTION ATTEMPT");
  616. EXPECT_TRUE(channel->WaitForConnected(
  617. grpc_timeout_milliseconds_to_deadline(kWaitMs)));
  618. const gpr_timespec t1 = gpr_now(GPR_CLOCK_MONOTONIC);
  619. const grpc_millis waited_ms = gpr_time_to_millis(gpr_time_sub(t1, t0));
  620. gpr_log(GPR_DEBUG, "Waited %" PRId64 " milliseconds", waited_ms);
  621. EXPECT_LT(waited_ms, kWaitMs);
  622. }
  623. TEST_F(ClientLbEnd2endTest, PickFirstUpdates) {
  624. // Start servers and send one RPC per server.
  625. const int kNumServers = 3;
  626. StartServers(kNumServers);
  627. auto response_generator = BuildResolverResponseGenerator();
  628. auto channel = BuildChannel("pick_first", response_generator);
  629. auto stub = BuildStub(channel);
  630. std::vector<int> ports;
  631. // Perform one RPC against the first server.
  632. ports.emplace_back(servers_[0]->port_);
  633. response_generator.SetNextResolution(ports);
  634. gpr_log(GPR_INFO, "****** SET [0] *******");
  635. CheckRpcSendOk(stub, DEBUG_LOCATION);
  636. EXPECT_EQ(servers_[0]->service_.request_count(), 1);
  637. // An empty update will result in the channel going into TRANSIENT_FAILURE.
  638. ports.clear();
  639. response_generator.SetNextResolution(ports);
  640. gpr_log(GPR_INFO, "****** SET none *******");
  641. grpc_connectivity_state channel_state;
  642. do {
  643. channel_state = channel->GetState(true /* try to connect */);
  644. } while (channel_state == GRPC_CHANNEL_READY);
  645. ASSERT_NE(channel_state, GRPC_CHANNEL_READY);
  646. servers_[0]->service_.ResetCounters();
  647. // Next update introduces servers_[1], making the channel recover.
  648. ports.clear();
  649. ports.emplace_back(servers_[1]->port_);
  650. response_generator.SetNextResolution(ports);
  651. gpr_log(GPR_INFO, "****** SET [1] *******");
  652. WaitForServer(stub, 1, DEBUG_LOCATION);
  653. EXPECT_EQ(servers_[0]->service_.request_count(), 0);
  654. // And again for servers_[2]
  655. ports.clear();
  656. ports.emplace_back(servers_[2]->port_);
  657. response_generator.SetNextResolution(ports);
  658. gpr_log(GPR_INFO, "****** SET [2] *******");
  659. WaitForServer(stub, 2, DEBUG_LOCATION);
  660. EXPECT_EQ(servers_[0]->service_.request_count(), 0);
  661. EXPECT_EQ(servers_[1]->service_.request_count(), 0);
  662. // Check LB policy name for the channel.
  663. EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
  664. }
  665. TEST_F(ClientLbEnd2endTest, PickFirstUpdateSuperset) {
  666. // Start servers and send one RPC per server.
  667. const int kNumServers = 3;
  668. StartServers(kNumServers);
  669. auto response_generator = BuildResolverResponseGenerator();
  670. auto channel = BuildChannel("pick_first", response_generator);
  671. auto stub = BuildStub(channel);
  672. std::vector<int> ports;
  673. // Perform one RPC against the first server.
  674. ports.emplace_back(servers_[0]->port_);
  675. response_generator.SetNextResolution(ports);
  676. gpr_log(GPR_INFO, "****** SET [0] *******");
  677. CheckRpcSendOk(stub, DEBUG_LOCATION);
  678. EXPECT_EQ(servers_[0]->service_.request_count(), 1);
  679. servers_[0]->service_.ResetCounters();
  680. // Send and superset update
  681. ports.clear();
  682. ports.emplace_back(servers_[1]->port_);
  683. ports.emplace_back(servers_[0]->port_);
  684. response_generator.SetNextResolution(ports);
  685. gpr_log(GPR_INFO, "****** SET superset *******");
  686. CheckRpcSendOk(stub, DEBUG_LOCATION);
  687. // We stick to the previously connected server.
  688. WaitForServer(stub, 0, DEBUG_LOCATION);
  689. EXPECT_EQ(0, servers_[1]->service_.request_count());
  690. // Check LB policy name for the channel.
  691. EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
  692. }
  693. TEST_F(ClientLbEnd2endTest, PickFirstGlobalSubchannelPool) {
  694. // Start one server.
  695. const int kNumServers = 1;
  696. StartServers(kNumServers);
  697. std::vector<int> ports = GetServersPorts();
  698. // Create two channels that (by default) use the global subchannel pool.
  699. auto response_generator1 = BuildResolverResponseGenerator();
  700. auto channel1 = BuildChannel("pick_first", response_generator1);
  701. auto stub1 = BuildStub(channel1);
  702. response_generator1.SetNextResolution(ports);
  703. auto response_generator2 = BuildResolverResponseGenerator();
  704. auto channel2 = BuildChannel("pick_first", response_generator2);
  705. auto stub2 = BuildStub(channel2);
  706. response_generator2.SetNextResolution(ports);
  707. WaitForServer(stub1, 0, DEBUG_LOCATION);
  708. // Send one RPC on each channel.
  709. CheckRpcSendOk(stub1, DEBUG_LOCATION);
  710. CheckRpcSendOk(stub2, DEBUG_LOCATION);
  711. // The server receives two requests.
  712. EXPECT_EQ(2, servers_[0]->service_.request_count());
  713. // The two requests are from the same client port, because the two channels
  714. // share subchannels via the global subchannel pool.
  715. EXPECT_EQ(1UL, servers_[0]->service_.clients().size());
  716. }
  717. TEST_F(ClientLbEnd2endTest, PickFirstLocalSubchannelPool) {
  718. // Start one server.
  719. const int kNumServers = 1;
  720. StartServers(kNumServers);
  721. std::vector<int> ports = GetServersPorts();
  722. // Create two channels that use local subchannel pool.
  723. ChannelArguments args;
  724. args.SetInt(GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL, 1);
  725. auto response_generator1 = BuildResolverResponseGenerator();
  726. auto channel1 = BuildChannel("pick_first", response_generator1, args);
  727. auto stub1 = BuildStub(channel1);
  728. response_generator1.SetNextResolution(ports);
  729. auto response_generator2 = BuildResolverResponseGenerator();
  730. auto channel2 = BuildChannel("pick_first", response_generator2, args);
  731. auto stub2 = BuildStub(channel2);
  732. response_generator2.SetNextResolution(ports);
  733. WaitForServer(stub1, 0, DEBUG_LOCATION);
  734. // Send one RPC on each channel.
  735. CheckRpcSendOk(stub1, DEBUG_LOCATION);
  736. CheckRpcSendOk(stub2, DEBUG_LOCATION);
  737. // The server receives two requests.
  738. EXPECT_EQ(2, servers_[0]->service_.request_count());
  739. // The two requests are from two client ports, because the two channels didn't
  740. // share subchannels with each other.
  741. EXPECT_EQ(2UL, servers_[0]->service_.clients().size());
  742. }
  743. TEST_F(ClientLbEnd2endTest, PickFirstManyUpdates) {
  744. const int kNumUpdates = 1000;
  745. const int kNumServers = 3;
  746. StartServers(kNumServers);
  747. auto response_generator = BuildResolverResponseGenerator();
  748. auto channel = BuildChannel("pick_first", response_generator);
  749. auto stub = BuildStub(channel);
  750. std::vector<int> ports = GetServersPorts();
  751. for (size_t i = 0; i < kNumUpdates; ++i) {
  752. std::shuffle(ports.begin(), ports.end(),
  753. std::mt19937(std::random_device()()));
  754. response_generator.SetNextResolution(ports);
  755. // We should re-enter core at the end of the loop to give the resolution
  756. // setting closure a chance to run.
  757. if ((i + 1) % 10 == 0) CheckRpcSendOk(stub, DEBUG_LOCATION);
  758. }
  759. // Check LB policy name for the channel.
  760. EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
  761. }
  762. TEST_F(ClientLbEnd2endTest, PickFirstReresolutionNoSelected) {
  763. // Prepare the ports for up servers and down servers.
  764. const int kNumServers = 3;
  765. const int kNumAliveServers = 1;
  766. StartServers(kNumAliveServers);
  767. std::vector<int> alive_ports, dead_ports;
  768. for (size_t i = 0; i < kNumServers; ++i) {
  769. if (i < kNumAliveServers) {
  770. alive_ports.emplace_back(servers_[i]->port_);
  771. } else {
  772. dead_ports.emplace_back(grpc_pick_unused_port_or_die());
  773. }
  774. }
  775. auto response_generator = BuildResolverResponseGenerator();
  776. auto channel = BuildChannel("pick_first", response_generator);
  777. auto stub = BuildStub(channel);
  778. // The initial resolution only contains dead ports. There won't be any
  779. // selected subchannel. Re-resolution will return the same result.
  780. response_generator.SetNextResolution(dead_ports);
  781. gpr_log(GPR_INFO, "****** INITIAL RESOLUTION SET *******");
  782. for (size_t i = 0; i < 10; ++i) CheckRpcSendFailure(stub);
  783. // Set a re-resolution result that contains reachable ports, so that the
  784. // pick_first LB policy can recover soon.
  785. response_generator.SetNextResolutionUponError(alive_ports);
  786. gpr_log(GPR_INFO, "****** RE-RESOLUTION SET *******");
  787. WaitForServer(stub, 0, DEBUG_LOCATION, true /* ignore_failure */);
  788. CheckRpcSendOk(stub, DEBUG_LOCATION);
  789. EXPECT_EQ(servers_[0]->service_.request_count(), 1);
  790. // Check LB policy name for the channel.
  791. EXPECT_EQ("pick_first", channel->GetLoadBalancingPolicyName());
  792. }
  793. TEST_F(ClientLbEnd2endTest, PickFirstReconnectWithoutNewResolverResult) {
  794. std::vector<int> ports = {grpc_pick_unused_port_or_die()};
  795. StartServers(1, ports);
  796. auto response_generator = BuildResolverResponseGenerator();
  797. auto channel = BuildChannel("pick_first", response_generator);
  798. auto stub = BuildStub(channel);
  799. response_generator.SetNextResolution(ports);
  800. gpr_log(GPR_INFO, "****** INITIAL CONNECTION *******");
  801. WaitForServer(stub, 0, DEBUG_LOCATION);
  802. gpr_log(GPR_INFO, "****** STOPPING SERVER ******");
  803. servers_[0]->Shutdown();
  804. EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
  805. gpr_log(GPR_INFO, "****** RESTARTING SERVER ******");
  806. StartServers(1, ports);
  807. WaitForServer(stub, 0, DEBUG_LOCATION);
  808. }
  809. TEST_F(ClientLbEnd2endTest,
  810. PickFirstReconnectWithoutNewResolverResultStartsFromTopOfList) {
  811. std::vector<int> ports = {grpc_pick_unused_port_or_die(),
  812. grpc_pick_unused_port_or_die()};
  813. CreateServers(2, ports);
  814. StartServer(1);
  815. auto response_generator = BuildResolverResponseGenerator();
  816. auto channel = BuildChannel("pick_first", response_generator);
  817. auto stub = BuildStub(channel);
  818. response_generator.SetNextResolution(ports);
  819. gpr_log(GPR_INFO, "****** INITIAL CONNECTION *******");
  820. WaitForServer(stub, 1, DEBUG_LOCATION);
  821. gpr_log(GPR_INFO, "****** STOPPING SERVER ******");
  822. servers_[1]->Shutdown();
  823. EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
  824. gpr_log(GPR_INFO, "****** STARTING BOTH SERVERS ******");
  825. StartServers(2, ports);
  826. WaitForServer(stub, 0, DEBUG_LOCATION);
  827. }
  828. TEST_F(ClientLbEnd2endTest, PickFirstCheckStateBeforeStartWatch) {
  829. std::vector<int> ports = {grpc_pick_unused_port_or_die()};
  830. StartServers(1, ports);
  831. auto response_generator = BuildResolverResponseGenerator();
  832. auto channel_1 = BuildChannel("pick_first", response_generator);
  833. auto stub_1 = BuildStub(channel_1);
  834. response_generator.SetNextResolution(ports);
  835. gpr_log(GPR_INFO, "****** RESOLUTION SET FOR CHANNEL 1 *******");
  836. WaitForServer(stub_1, 0, DEBUG_LOCATION);
  837. gpr_log(GPR_INFO, "****** CHANNEL 1 CONNECTED *******");
  838. servers_[0]->Shutdown();
  839. // Channel 1 will receive a re-resolution containing the same server. It will
  840. // create a new subchannel and hold a ref to it.
  841. StartServers(1, ports);
  842. gpr_log(GPR_INFO, "****** SERVER RESTARTED *******");
  843. auto response_generator_2 = BuildResolverResponseGenerator();
  844. auto channel_2 = BuildChannel("pick_first", response_generator_2);
  845. auto stub_2 = BuildStub(channel_2);
  846. response_generator_2.SetNextResolution(ports);
  847. gpr_log(GPR_INFO, "****** RESOLUTION SET FOR CHANNEL 2 *******");
  848. WaitForServer(stub_2, 0, DEBUG_LOCATION, true);
  849. gpr_log(GPR_INFO, "****** CHANNEL 2 CONNECTED *******");
  850. servers_[0]->Shutdown();
  851. // Wait until the disconnection has triggered the connectivity notification.
  852. // Otherwise, the subchannel may be picked for next call but will fail soon.
  853. EXPECT_TRUE(WaitForChannelNotReady(channel_2.get()));
  854. // Channel 2 will also receive a re-resolution containing the same server.
  855. // Both channels will ref the same subchannel that failed.
  856. StartServers(1, ports);
  857. gpr_log(GPR_INFO, "****** SERVER RESTARTED AGAIN *******");
  858. gpr_log(GPR_INFO, "****** CHANNEL 2 STARTING A CALL *******");
  859. // The first call after the server restart will succeed.
  860. CheckRpcSendOk(stub_2, DEBUG_LOCATION);
  861. gpr_log(GPR_INFO, "****** CHANNEL 2 FINISHED A CALL *******");
  862. // Check LB policy name for the channel.
  863. EXPECT_EQ("pick_first", channel_1->GetLoadBalancingPolicyName());
  864. // Check LB policy name for the channel.
  865. EXPECT_EQ("pick_first", channel_2->GetLoadBalancingPolicyName());
  866. }
  867. TEST_F(ClientLbEnd2endTest, PickFirstIdleOnDisconnect) {
  868. // Start server, send RPC, and make sure channel is READY.
  869. const int kNumServers = 1;
  870. StartServers(kNumServers);
  871. auto response_generator = BuildResolverResponseGenerator();
  872. auto channel =
  873. BuildChannel("", response_generator); // pick_first is the default.
  874. auto stub = BuildStub(channel);
  875. response_generator.SetNextResolution(GetServersPorts());
  876. CheckRpcSendOk(stub, DEBUG_LOCATION);
  877. EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
  878. // Stop server. Channel should go into state IDLE.
  879. response_generator.SetFailureOnReresolution();
  880. servers_[0]->Shutdown();
  881. EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
  882. EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
  883. servers_.clear();
  884. }
  885. TEST_F(ClientLbEnd2endTest, PickFirstPendingUpdateAndSelectedSubchannelFails) {
  886. auto response_generator = BuildResolverResponseGenerator();
  887. auto channel =
  888. BuildChannel("", response_generator); // pick_first is the default.
  889. auto stub = BuildStub(channel);
  890. // Create a number of servers, but only start 1 of them.
  891. CreateServers(10);
  892. StartServer(0);
  893. // Initially resolve to first server and make sure it connects.
  894. gpr_log(GPR_INFO, "Phase 1: Connect to first server.");
  895. response_generator.SetNextResolution({servers_[0]->port_});
  896. CheckRpcSendOk(stub, DEBUG_LOCATION, true /* wait_for_ready */);
  897. EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
  898. // Send a resolution update with the remaining servers, none of which are
  899. // running yet, so the update will stay pending. Note that it's important
  900. // to have multiple servers here, or else the test will be flaky; with only
  901. // one server, the pending subchannel list has already gone into
  902. // TRANSIENT_FAILURE due to hitting the end of the list by the time we
  903. // check the state.
  904. gpr_log(GPR_INFO,
  905. "Phase 2: Resolver update pointing to remaining "
  906. "(not started) servers.");
  907. response_generator.SetNextResolution(GetServersPorts(1 /* start_index */));
  908. // RPCs will continue to be sent to the first server.
  909. CheckRpcSendOk(stub, DEBUG_LOCATION);
  910. // Now stop the first server, so that the current subchannel list
  911. // fails. This should cause us to immediately swap over to the
  912. // pending list, even though it's not yet connected. The state should
  913. // be set to CONNECTING, since that's what the pending subchannel list
  914. // was doing when we swapped over.
  915. gpr_log(GPR_INFO, "Phase 3: Stopping first server.");
  916. servers_[0]->Shutdown();
  917. WaitForChannelNotReady(channel.get());
  918. // TODO(roth): This should always return CONNECTING, but it's flaky
  919. // between that and TRANSIENT_FAILURE. I suspect that this problem
  920. // will go away once we move the backoff code out of the subchannel
  921. // and into the LB policies.
  922. EXPECT_THAT(channel->GetState(false),
  923. ::testing::AnyOf(GRPC_CHANNEL_CONNECTING,
  924. GRPC_CHANNEL_TRANSIENT_FAILURE));
  925. // Now start the second server.
  926. gpr_log(GPR_INFO, "Phase 4: Starting second server.");
  927. StartServer(1);
  928. // The channel should go to READY state and RPCs should go to the
  929. // second server.
  930. WaitForChannelReady(channel.get());
  931. WaitForServer(stub, 1, DEBUG_LOCATION, true /* ignore_failure */);
  932. }
  933. TEST_F(ClientLbEnd2endTest, PickFirstStaysIdleUponEmptyUpdate) {
  934. // Start server, send RPC, and make sure channel is READY.
  935. const int kNumServers = 1;
  936. StartServers(kNumServers);
  937. auto response_generator = BuildResolverResponseGenerator();
  938. auto channel =
  939. BuildChannel("", response_generator); // pick_first is the default.
  940. auto stub = BuildStub(channel);
  941. response_generator.SetNextResolution(GetServersPorts());
  942. CheckRpcSendOk(stub, DEBUG_LOCATION);
  943. EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
  944. // Stop server. Channel should go into state IDLE.
  945. servers_[0]->Shutdown();
  946. EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
  947. EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
  948. // Now send resolver update that includes no addresses. Channel
  949. // should stay in state IDLE.
  950. response_generator.SetNextResolution({});
  951. EXPECT_FALSE(channel->WaitForStateChange(
  952. GRPC_CHANNEL_IDLE, grpc_timeout_seconds_to_deadline(3)));
  953. // Now bring the backend back up and send a non-empty resolver update,
  954. // and then try to send an RPC. Channel should go back into state READY.
  955. StartServer(0);
  956. response_generator.SetNextResolution(GetServersPorts());
  957. CheckRpcSendOk(stub, DEBUG_LOCATION);
  958. EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
  959. }
  960. TEST_F(ClientLbEnd2endTest, RoundRobin) {
  961. // Start servers and send one RPC per server.
  962. const int kNumServers = 3;
  963. StartServers(kNumServers);
  964. auto response_generator = BuildResolverResponseGenerator();
  965. auto channel = BuildChannel("round_robin", response_generator);
  966. auto stub = BuildStub(channel);
  967. response_generator.SetNextResolution(GetServersPorts());
  968. // Wait until all backends are ready.
  969. do {
  970. CheckRpcSendOk(stub, DEBUG_LOCATION);
  971. } while (!SeenAllServers());
  972. ResetCounters();
  973. // "Sync" to the end of the list. Next sequence of picks will start at the
  974. // first server (index 0).
  975. WaitForServer(stub, servers_.size() - 1, DEBUG_LOCATION);
  976. std::vector<int> connection_order;
  977. for (size_t i = 0; i < servers_.size(); ++i) {
  978. CheckRpcSendOk(stub, DEBUG_LOCATION);
  979. UpdateConnectionOrder(servers_, &connection_order);
  980. }
  981. // Backends should be iterated over in the order in which the addresses were
  982. // given.
  983. const auto expected = std::vector<int>{0, 1, 2};
  984. EXPECT_EQ(expected, connection_order);
  985. // Check LB policy name for the channel.
  986. EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
  987. }
  988. TEST_F(ClientLbEnd2endTest, RoundRobinProcessPending) {
  989. StartServers(1); // Single server
  990. auto response_generator = BuildResolverResponseGenerator();
  991. auto channel = BuildChannel("round_robin", response_generator);
  992. auto stub = BuildStub(channel);
  993. response_generator.SetNextResolution({servers_[0]->port_});
  994. WaitForServer(stub, 0, DEBUG_LOCATION);
  995. // Create a new channel and its corresponding RR LB policy, which will pick
  996. // the subchannels in READY state from the previous RPC against the same
  997. // target (even if it happened over a different channel, because subchannels
  998. // are globally reused). Progress should happen without any transition from
  999. // this READY state.
  1000. auto second_response_generator = BuildResolverResponseGenerator();
  1001. auto second_channel = BuildChannel("round_robin", second_response_generator);
  1002. auto second_stub = BuildStub(second_channel);
  1003. second_response_generator.SetNextResolution({servers_[0]->port_});
  1004. CheckRpcSendOk(second_stub, DEBUG_LOCATION);
  1005. }
  1006. TEST_F(ClientLbEnd2endTest, RoundRobinUpdates) {
  1007. // Start servers and send one RPC per server.
  1008. const int kNumServers = 3;
  1009. StartServers(kNumServers);
  1010. auto response_generator = BuildResolverResponseGenerator();
  1011. auto channel = BuildChannel("round_robin", response_generator);
  1012. auto stub = BuildStub(channel);
  1013. std::vector<int> ports;
  1014. // Start with a single server.
  1015. gpr_log(GPR_INFO, "*** FIRST BACKEND ***");
  1016. ports.emplace_back(servers_[0]->port_);
  1017. response_generator.SetNextResolution(ports);
  1018. WaitForServer(stub, 0, DEBUG_LOCATION);
  1019. // Send RPCs. They should all go servers_[0]
  1020. for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
  1021. EXPECT_EQ(10, servers_[0]->service_.request_count());
  1022. EXPECT_EQ(0, servers_[1]->service_.request_count());
  1023. EXPECT_EQ(0, servers_[2]->service_.request_count());
  1024. servers_[0]->service_.ResetCounters();
  1025. // And now for the second server.
  1026. gpr_log(GPR_INFO, "*** SECOND BACKEND ***");
  1027. ports.clear();
  1028. ports.emplace_back(servers_[1]->port_);
  1029. response_generator.SetNextResolution(ports);
  1030. // Wait until update has been processed, as signaled by the second backend
  1031. // receiving a request.
  1032. EXPECT_EQ(0, servers_[1]->service_.request_count());
  1033. WaitForServer(stub, 1, DEBUG_LOCATION);
  1034. for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
  1035. EXPECT_EQ(0, servers_[0]->service_.request_count());
  1036. EXPECT_EQ(10, servers_[1]->service_.request_count());
  1037. EXPECT_EQ(0, servers_[2]->service_.request_count());
  1038. servers_[1]->service_.ResetCounters();
  1039. // ... and for the last server.
  1040. gpr_log(GPR_INFO, "*** THIRD BACKEND ***");
  1041. ports.clear();
  1042. ports.emplace_back(servers_[2]->port_);
  1043. response_generator.SetNextResolution(ports);
  1044. WaitForServer(stub, 2, DEBUG_LOCATION);
  1045. for (size_t i = 0; i < 10; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
  1046. EXPECT_EQ(0, servers_[0]->service_.request_count());
  1047. EXPECT_EQ(0, servers_[1]->service_.request_count());
  1048. EXPECT_EQ(10, servers_[2]->service_.request_count());
  1049. servers_[2]->service_.ResetCounters();
  1050. // Back to all servers.
  1051. gpr_log(GPR_INFO, "*** ALL BACKENDS ***");
  1052. ports.clear();
  1053. ports.emplace_back(servers_[0]->port_);
  1054. ports.emplace_back(servers_[1]->port_);
  1055. ports.emplace_back(servers_[2]->port_);
  1056. response_generator.SetNextResolution(ports);
  1057. WaitForServer(stub, 0, DEBUG_LOCATION);
  1058. WaitForServer(stub, 1, DEBUG_LOCATION);
  1059. WaitForServer(stub, 2, DEBUG_LOCATION);
  1060. // Send three RPCs, one per server.
  1061. for (size_t i = 0; i < 3; ++i) CheckRpcSendOk(stub, DEBUG_LOCATION);
  1062. EXPECT_EQ(1, servers_[0]->service_.request_count());
  1063. EXPECT_EQ(1, servers_[1]->service_.request_count());
  1064. EXPECT_EQ(1, servers_[2]->service_.request_count());
  1065. // An empty update will result in the channel going into TRANSIENT_FAILURE.
  1066. gpr_log(GPR_INFO, "*** NO BACKENDS ***");
  1067. ports.clear();
  1068. response_generator.SetNextResolution(ports);
  1069. grpc_connectivity_state channel_state;
  1070. do {
  1071. channel_state = channel->GetState(true /* try to connect */);
  1072. } while (channel_state == GRPC_CHANNEL_READY);
  1073. ASSERT_NE(channel_state, GRPC_CHANNEL_READY);
  1074. servers_[0]->service_.ResetCounters();
  1075. // Next update introduces servers_[1], making the channel recover.
  1076. gpr_log(GPR_INFO, "*** BACK TO SECOND BACKEND ***");
  1077. ports.clear();
  1078. ports.emplace_back(servers_[1]->port_);
  1079. response_generator.SetNextResolution(ports);
  1080. WaitForServer(stub, 1, DEBUG_LOCATION);
  1081. channel_state = channel->GetState(false /* try to connect */);
  1082. ASSERT_EQ(channel_state, GRPC_CHANNEL_READY);
  1083. // Check LB policy name for the channel.
  1084. EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
  1085. }
  1086. TEST_F(ClientLbEnd2endTest, RoundRobinUpdateInError) {
  1087. const int kNumServers = 3;
  1088. StartServers(kNumServers);
  1089. auto response_generator = BuildResolverResponseGenerator();
  1090. auto channel = BuildChannel("round_robin", response_generator);
  1091. auto stub = BuildStub(channel);
  1092. std::vector<int> ports;
  1093. // Start with a single server.
  1094. ports.emplace_back(servers_[0]->port_);
  1095. response_generator.SetNextResolution(ports);
  1096. WaitForServer(stub, 0, DEBUG_LOCATION);
  1097. // Send RPCs. They should all go to servers_[0]
  1098. for (size_t i = 0; i < 10; ++i) SendRpc(stub);
  1099. EXPECT_EQ(10, servers_[0]->service_.request_count());
  1100. EXPECT_EQ(0, servers_[1]->service_.request_count());
  1101. EXPECT_EQ(0, servers_[2]->service_.request_count());
  1102. servers_[0]->service_.ResetCounters();
  1103. // Shutdown one of the servers to be sent in the update.
  1104. servers_[1]->Shutdown();
  1105. ports.emplace_back(servers_[1]->port_);
  1106. ports.emplace_back(servers_[2]->port_);
  1107. response_generator.SetNextResolution(ports);
  1108. WaitForServer(stub, 0, DEBUG_LOCATION);
  1109. WaitForServer(stub, 2, DEBUG_LOCATION);
  1110. // Send three RPCs, one per server.
  1111. for (size_t i = 0; i < kNumServers; ++i) SendRpc(stub);
  1112. // The server in shutdown shouldn't receive any.
  1113. EXPECT_EQ(0, servers_[1]->service_.request_count());
  1114. }
  1115. TEST_F(ClientLbEnd2endTest, RoundRobinManyUpdates) {
  1116. // Start servers and send one RPC per server.
  1117. const int kNumServers = 3;
  1118. StartServers(kNumServers);
  1119. auto response_generator = BuildResolverResponseGenerator();
  1120. auto channel = BuildChannel("round_robin", response_generator);
  1121. auto stub = BuildStub(channel);
  1122. std::vector<int> ports = GetServersPorts();
  1123. for (size_t i = 0; i < 1000; ++i) {
  1124. std::shuffle(ports.begin(), ports.end(),
  1125. std::mt19937(std::random_device()()));
  1126. response_generator.SetNextResolution(ports);
  1127. if (i % 10 == 0) CheckRpcSendOk(stub, DEBUG_LOCATION);
  1128. }
  1129. // Check LB policy name for the channel.
  1130. EXPECT_EQ("round_robin", channel->GetLoadBalancingPolicyName());
  1131. }
  1132. TEST_F(ClientLbEnd2endTest, RoundRobinConcurrentUpdates) {
  1133. // TODO(dgq): replicate the way internal testing exercises the concurrent
  1134. // update provisions of RR.
  1135. }
  1136. TEST_F(ClientLbEnd2endTest, RoundRobinReresolve) {
  1137. // Start servers and send one RPC per server.
  1138. const int kNumServers = 3;
  1139. std::vector<int> first_ports;
  1140. std::vector<int> second_ports;
  1141. first_ports.reserve(kNumServers);
  1142. for (int i = 0; i < kNumServers; ++i) {
  1143. first_ports.push_back(grpc_pick_unused_port_or_die());
  1144. }
  1145. second_ports.reserve(kNumServers);
  1146. for (int i = 0; i < kNumServers; ++i) {
  1147. second_ports.push_back(grpc_pick_unused_port_or_die());
  1148. }
  1149. StartServers(kNumServers, first_ports);
  1150. auto response_generator = BuildResolverResponseGenerator();
  1151. auto channel = BuildChannel("round_robin", response_generator);
  1152. auto stub = BuildStub(channel);
  1153. response_generator.SetNextResolution(first_ports);
  1154. // Send a number of RPCs, which succeed.
  1155. for (size_t i = 0; i < 100; ++i) {
  1156. CheckRpcSendOk(stub, DEBUG_LOCATION);
  1157. }
  1158. // Kill all servers
  1159. gpr_log(GPR_INFO, "****** ABOUT TO KILL SERVERS *******");
  1160. for (size_t i = 0; i < servers_.size(); ++i) {
  1161. servers_[i]->Shutdown();
  1162. }
  1163. gpr_log(GPR_INFO, "****** SERVERS KILLED *******");
  1164. gpr_log(GPR_INFO, "****** SENDING DOOMED REQUESTS *******");
  1165. // Client requests should fail. Send enough to tickle all subchannels.
  1166. for (size_t i = 0; i < servers_.size(); ++i) CheckRpcSendFailure(stub);
  1167. gpr_log(GPR_INFO, "****** DOOMED REQUESTS SENT *******");
  1168. // Bring servers back up on a different set of ports. We need to do this to be
  1169. // sure that the eventual success is *not* due to subchannel reconnection
  1170. // attempts and that an actual re-resolution has happened as a result of the
  1171. // RR policy going into transient failure when all its subchannels become
  1172. // unavailable (in transient failure as well).
  1173. gpr_log(GPR_INFO, "****** RESTARTING SERVERS *******");
  1174. StartServers(kNumServers, second_ports);
  1175. // Don't notify of the update. Wait for the LB policy's re-resolution to
  1176. // "pull" the new ports.
  1177. response_generator.SetNextResolutionUponError(second_ports);
  1178. gpr_log(GPR_INFO, "****** SERVERS RESTARTED *******");
  1179. gpr_log(GPR_INFO, "****** SENDING REQUEST TO SUCCEED *******");
  1180. // Client request should eventually (but still fairly soon) succeed.
  1181. const gpr_timespec deadline = grpc_timeout_seconds_to_deadline(5);
  1182. gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
  1183. while (gpr_time_cmp(deadline, now) > 0) {
  1184. if (SendRpc(stub)) break;
  1185. now = gpr_now(GPR_CLOCK_MONOTONIC);
  1186. }
  1187. ASSERT_GT(gpr_time_cmp(deadline, now), 0);
  1188. }
  1189. TEST_F(ClientLbEnd2endTest, RoundRobinTransientFailure) {
  1190. // Start servers and create channel. Channel should go to READY state.
  1191. const int kNumServers = 3;
  1192. StartServers(kNumServers);
  1193. auto response_generator = BuildResolverResponseGenerator();
  1194. auto channel = BuildChannel("round_robin", response_generator);
  1195. auto stub = BuildStub(channel);
  1196. response_generator.SetNextResolution(GetServersPorts());
  1197. EXPECT_TRUE(WaitForChannelReady(channel.get()));
  1198. // Now kill the servers. The channel should transition to TRANSIENT_FAILURE.
  1199. // TODO(roth): This test should ideally check that even when the
  1200. // subchannels are in state CONNECTING for an extended period of time,
  1201. // we will still report TRANSIENT_FAILURE. Unfortunately, we don't
  1202. // currently have a good way to get a subchannel to report CONNECTING
  1203. // for a long period of time, since the servers in this test framework
  1204. // are on the loopback interface, which will immediately return a
  1205. // "Connection refused" error, so the subchannels will only be in
  1206. // CONNECTING state very briefly. When we have time, see if we can
  1207. // find a way to fix this.
  1208. for (size_t i = 0; i < servers_.size(); ++i) {
  1209. servers_[i]->Shutdown();
  1210. }
  1211. auto predicate = [](grpc_connectivity_state state) {
  1212. return state == GRPC_CHANNEL_TRANSIENT_FAILURE;
  1213. };
  1214. EXPECT_TRUE(WaitForChannelState(channel.get(), predicate));
  1215. }
  1216. TEST_F(ClientLbEnd2endTest, RoundRobinTransientFailureAtStartup) {
  1217. // Create channel and return servers that don't exist. Channel should
  1218. // quickly transition into TRANSIENT_FAILURE.
  1219. // TODO(roth): This test should ideally check that even when the
  1220. // subchannels are in state CONNECTING for an extended period of time,
  1221. // we will still report TRANSIENT_FAILURE. Unfortunately, we don't
  1222. // currently have a good way to get a subchannel to report CONNECTING
  1223. // for a long period of time, since the servers in this test framework
  1224. // are on the loopback interface, which will immediately return a
  1225. // "Connection refused" error, so the subchannels will only be in
  1226. // CONNECTING state very briefly. When we have time, see if we can
  1227. // find a way to fix this.
  1228. auto response_generator = BuildResolverResponseGenerator();
  1229. auto channel = BuildChannel("round_robin", response_generator);
  1230. auto stub = BuildStub(channel);
  1231. response_generator.SetNextResolution({
  1232. grpc_pick_unused_port_or_die(),
  1233. grpc_pick_unused_port_or_die(),
  1234. grpc_pick_unused_port_or_die(),
  1235. });
  1236. for (size_t i = 0; i < servers_.size(); ++i) {
  1237. servers_[i]->Shutdown();
  1238. }
  1239. auto predicate = [](grpc_connectivity_state state) {
  1240. return state == GRPC_CHANNEL_TRANSIENT_FAILURE;
  1241. };
  1242. EXPECT_TRUE(WaitForChannelState(channel.get(), predicate, true));
  1243. }
  1244. TEST_F(ClientLbEnd2endTest, RoundRobinSingleReconnect) {
  1245. const int kNumServers = 3;
  1246. StartServers(kNumServers);
  1247. const auto ports = GetServersPorts();
  1248. auto response_generator = BuildResolverResponseGenerator();
  1249. auto channel = BuildChannel("round_robin", response_generator);
  1250. auto stub = BuildStub(channel);
  1251. response_generator.SetNextResolution(ports);
  1252. for (size_t i = 0; i < kNumServers; ++i) {
  1253. WaitForServer(stub, i, DEBUG_LOCATION);
  1254. }
  1255. for (size_t i = 0; i < servers_.size(); ++i) {
  1256. CheckRpcSendOk(stub, DEBUG_LOCATION);
  1257. EXPECT_EQ(1, servers_[i]->service_.request_count()) << "for backend #" << i;
  1258. }
  1259. // One request should have gone to each server.
  1260. for (size_t i = 0; i < servers_.size(); ++i) {
  1261. EXPECT_EQ(1, servers_[i]->service_.request_count());
  1262. }
  1263. const auto pre_death = servers_[0]->service_.request_count();
  1264. // Kill the first server.
  1265. servers_[0]->Shutdown();
  1266. // Client request still succeed. May need retrying if RR had returned a pick
  1267. // before noticing the change in the server's connectivity.
  1268. while (!SendRpc(stub)) {
  1269. } // Retry until success.
  1270. // Send a bunch of RPCs that should succeed.
  1271. for (int i = 0; i < 10 * kNumServers; ++i) {
  1272. CheckRpcSendOk(stub, DEBUG_LOCATION);
  1273. }
  1274. const auto post_death = servers_[0]->service_.request_count();
  1275. // No requests have gone to the deceased server.
  1276. EXPECT_EQ(pre_death, post_death);
  1277. // Bring the first server back up.
  1278. StartServer(0);
  1279. // Requests should start arriving at the first server either right away (if
  1280. // the server managed to start before the RR policy retried the subchannel) or
  1281. // after the subchannel retry delay otherwise (RR's subchannel retried before
  1282. // the server was fully back up).
  1283. WaitForServer(stub, 0, DEBUG_LOCATION);
  1284. }
  1285. // If health checking is required by client but health checking service
  1286. // is not running on the server, the channel should be treated as healthy.
  1287. TEST_F(ClientLbEnd2endTest,
  1288. RoundRobinServersHealthCheckingUnimplementedTreatedAsHealthy) {
  1289. StartServers(1); // Single server
  1290. ChannelArguments args;
  1291. args.SetServiceConfigJSON(
  1292. "{\"healthCheckConfig\": "
  1293. "{\"serviceName\": \"health_check_service_name\"}}");
  1294. auto response_generator = BuildResolverResponseGenerator();
  1295. auto channel = BuildChannel("round_robin", response_generator, args);
  1296. auto stub = BuildStub(channel);
  1297. response_generator.SetNextResolution({servers_[0]->port_});
  1298. EXPECT_TRUE(WaitForChannelReady(channel.get()));
  1299. CheckRpcSendOk(stub, DEBUG_LOCATION);
  1300. }
  1301. TEST_F(ClientLbEnd2endTest, RoundRobinWithHealthChecking) {
  1302. EnableDefaultHealthCheckService(true);
  1303. // Start servers.
  1304. const int kNumServers = 3;
  1305. StartServers(kNumServers);
  1306. ChannelArguments args;
  1307. args.SetServiceConfigJSON(
  1308. "{\"healthCheckConfig\": "
  1309. "{\"serviceName\": \"health_check_service_name\"}}");
  1310. auto response_generator = BuildResolverResponseGenerator();
  1311. auto channel = BuildChannel("round_robin", response_generator, args);
  1312. auto stub = BuildStub(channel);
  1313. response_generator.SetNextResolution(GetServersPorts());
  1314. // Channel should not become READY, because health checks should be failing.
  1315. gpr_log(GPR_INFO,
  1316. "*** initial state: unknown health check service name for "
  1317. "all servers");
  1318. EXPECT_FALSE(WaitForChannelReady(channel.get(), 1));
  1319. // Now set one of the servers to be healthy.
  1320. // The channel should become healthy and all requests should go to
  1321. // the healthy server.
  1322. gpr_log(GPR_INFO, "*** server 0 healthy");
  1323. servers_[0]->SetServingStatus("health_check_service_name", true);
  1324. EXPECT_TRUE(WaitForChannelReady(channel.get()));
  1325. for (int i = 0; i < 10; ++i) {
  1326. CheckRpcSendOk(stub, DEBUG_LOCATION);
  1327. }
  1328. EXPECT_EQ(10, servers_[0]->service_.request_count());
  1329. EXPECT_EQ(0, servers_[1]->service_.request_count());
  1330. EXPECT_EQ(0, servers_[2]->service_.request_count());
  1331. // Now set a second server to be healthy.
  1332. gpr_log(GPR_INFO, "*** server 2 healthy");
  1333. servers_[2]->SetServingStatus("health_check_service_name", true);
  1334. WaitForServer(stub, 2, DEBUG_LOCATION);
  1335. for (int i = 0; i < 10; ++i) {
  1336. CheckRpcSendOk(stub, DEBUG_LOCATION);
  1337. }
  1338. EXPECT_EQ(5, servers_[0]->service_.request_count());
  1339. EXPECT_EQ(0, servers_[1]->service_.request_count());
  1340. EXPECT_EQ(5, servers_[2]->service_.request_count());
  1341. // Now set the remaining server to be healthy.
  1342. gpr_log(GPR_INFO, "*** server 1 healthy");
  1343. servers_[1]->SetServingStatus("health_check_service_name", true);
  1344. WaitForServer(stub, 1, DEBUG_LOCATION);
  1345. for (int i = 0; i < 9; ++i) {
  1346. CheckRpcSendOk(stub, DEBUG_LOCATION);
  1347. }
  1348. EXPECT_EQ(3, servers_[0]->service_.request_count());
  1349. EXPECT_EQ(3, servers_[1]->service_.request_count());
  1350. EXPECT_EQ(3, servers_[2]->service_.request_count());
  1351. // Now set one server to be unhealthy again. Then wait until the
  1352. // unhealthiness has hit the client. We know that the client will see
  1353. // this when we send kNumServers requests and one of the remaining servers
  1354. // sees two of the requests.
  1355. gpr_log(GPR_INFO, "*** server 0 unhealthy");
  1356. servers_[0]->SetServingStatus("health_check_service_name", false);
  1357. do {
  1358. ResetCounters();
  1359. for (int i = 0; i < kNumServers; ++i) {
  1360. CheckRpcSendOk(stub, DEBUG_LOCATION);
  1361. }
  1362. } while (servers_[1]->service_.request_count() != 2 &&
  1363. servers_[2]->service_.request_count() != 2);
  1364. // Now set the remaining two servers to be unhealthy. Make sure the
  1365. // channel leaves READY state and that RPCs fail.
  1366. gpr_log(GPR_INFO, "*** all servers unhealthy");
  1367. servers_[1]->SetServingStatus("health_check_service_name", false);
  1368. servers_[2]->SetServingStatus("health_check_service_name", false);
  1369. EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
  1370. CheckRpcSendFailure(stub);
  1371. // Clean up.
  1372. EnableDefaultHealthCheckService(false);
  1373. }
  1374. TEST_F(ClientLbEnd2endTest,
  1375. RoundRobinWithHealthCheckingHandlesSubchannelFailure) {
  1376. EnableDefaultHealthCheckService(true);
  1377. // Start servers.
  1378. const int kNumServers = 3;
  1379. StartServers(kNumServers);
  1380. servers_[0]->SetServingStatus("health_check_service_name", true);
  1381. servers_[1]->SetServingStatus("health_check_service_name", true);
  1382. servers_[2]->SetServingStatus("health_check_service_name", true);
  1383. ChannelArguments args;
  1384. args.SetServiceConfigJSON(
  1385. "{\"healthCheckConfig\": "
  1386. "{\"serviceName\": \"health_check_service_name\"}}");
  1387. auto response_generator = BuildResolverResponseGenerator();
  1388. auto channel = BuildChannel("round_robin", response_generator, args);
  1389. auto stub = BuildStub(channel);
  1390. response_generator.SetNextResolution(GetServersPorts());
  1391. WaitForServer(stub, 0, DEBUG_LOCATION);
  1392. // Stop server 0 and send a new resolver result to ensure that RR
  1393. // checks each subchannel's state.
  1394. servers_[0]->Shutdown();
  1395. response_generator.SetNextResolution(GetServersPorts());
  1396. // Send a bunch more RPCs.
  1397. for (size_t i = 0; i < 100; i++) {
  1398. SendRpc(stub);
  1399. }
  1400. }
  1401. TEST_F(ClientLbEnd2endTest, RoundRobinWithHealthCheckingInhibitPerChannel) {
  1402. EnableDefaultHealthCheckService(true);
  1403. // Start server.
  1404. const int kNumServers = 1;
  1405. StartServers(kNumServers);
  1406. // Create a channel with health-checking enabled.
  1407. ChannelArguments args;
  1408. args.SetServiceConfigJSON(
  1409. "{\"healthCheckConfig\": "
  1410. "{\"serviceName\": \"health_check_service_name\"}}");
  1411. auto response_generator1 = BuildResolverResponseGenerator();
  1412. auto channel1 = BuildChannel("round_robin", response_generator1, args);
  1413. auto stub1 = BuildStub(channel1);
  1414. std::vector<int> ports = GetServersPorts();
  1415. response_generator1.SetNextResolution(ports);
  1416. // Create a channel with health checking enabled but inhibited.
  1417. args.SetInt(GRPC_ARG_INHIBIT_HEALTH_CHECKING, 1);
  1418. auto response_generator2 = BuildResolverResponseGenerator();
  1419. auto channel2 = BuildChannel("round_robin", response_generator2, args);
  1420. auto stub2 = BuildStub(channel2);
  1421. response_generator2.SetNextResolution(ports);
  1422. // First channel should not become READY, because health checks should be
  1423. // failing.
  1424. EXPECT_FALSE(WaitForChannelReady(channel1.get(), 1));
  1425. CheckRpcSendFailure(stub1);
  1426. // Second channel should be READY.
  1427. EXPECT_TRUE(WaitForChannelReady(channel2.get(), 1));
  1428. CheckRpcSendOk(stub2, DEBUG_LOCATION);
  1429. // Enable health checks on the backend and wait for channel 1 to succeed.
  1430. servers_[0]->SetServingStatus("health_check_service_name", true);
  1431. CheckRpcSendOk(stub1, DEBUG_LOCATION, true /* wait_for_ready */);
  1432. // Check that we created only one subchannel to the backend.
  1433. EXPECT_EQ(1UL, servers_[0]->service_.clients().size());
  1434. // Clean up.
  1435. EnableDefaultHealthCheckService(false);
  1436. }
  1437. TEST_F(ClientLbEnd2endTest, RoundRobinWithHealthCheckingServiceNamePerChannel) {
  1438. EnableDefaultHealthCheckService(true);
  1439. // Start server.
  1440. const int kNumServers = 1;
  1441. StartServers(kNumServers);
  1442. // Create a channel with health-checking enabled.
  1443. ChannelArguments args;
  1444. args.SetServiceConfigJSON(
  1445. "{\"healthCheckConfig\": "
  1446. "{\"serviceName\": \"health_check_service_name\"}}");
  1447. auto response_generator1 = BuildResolverResponseGenerator();
  1448. auto channel1 = BuildChannel("round_robin", response_generator1, args);
  1449. auto stub1 = BuildStub(channel1);
  1450. std::vector<int> ports = GetServersPorts();
  1451. response_generator1.SetNextResolution(ports);
  1452. // Create a channel with health-checking enabled with a different
  1453. // service name.
  1454. ChannelArguments args2;
  1455. args2.SetServiceConfigJSON(
  1456. "{\"healthCheckConfig\": "
  1457. "{\"serviceName\": \"health_check_service_name2\"}}");
  1458. auto response_generator2 = BuildResolverResponseGenerator();
  1459. auto channel2 = BuildChannel("round_robin", response_generator2, args2);
  1460. auto stub2 = BuildStub(channel2);
  1461. response_generator2.SetNextResolution(ports);
  1462. // Allow health checks from channel 2 to succeed.
  1463. servers_[0]->SetServingStatus("health_check_service_name2", true);
  1464. // First channel should not become READY, because health checks should be
  1465. // failing.
  1466. EXPECT_FALSE(WaitForChannelReady(channel1.get(), 1));
  1467. CheckRpcSendFailure(stub1);
  1468. // Second channel should be READY.
  1469. EXPECT_TRUE(WaitForChannelReady(channel2.get(), 1));
  1470. CheckRpcSendOk(stub2, DEBUG_LOCATION);
  1471. // Enable health checks for channel 1 and wait for it to succeed.
  1472. servers_[0]->SetServingStatus("health_check_service_name", true);
  1473. CheckRpcSendOk(stub1, DEBUG_LOCATION, true /* wait_for_ready */);
  1474. // Check that we created only one subchannel to the backend.
  1475. EXPECT_EQ(1UL, servers_[0]->service_.clients().size());
  1476. // Clean up.
  1477. EnableDefaultHealthCheckService(false);
  1478. }
  1479. TEST_F(ClientLbEnd2endTest,
  1480. RoundRobinWithHealthCheckingServiceNameChangesAfterSubchannelsCreated) {
  1481. EnableDefaultHealthCheckService(true);
  1482. // Start server.
  1483. const int kNumServers = 1;
  1484. StartServers(kNumServers);
  1485. // Create a channel with health-checking enabled.
  1486. const char* kServiceConfigJson =
  1487. "{\"healthCheckConfig\": "
  1488. "{\"serviceName\": \"health_check_service_name\"}}";
  1489. auto response_generator = BuildResolverResponseGenerator();
  1490. auto channel = BuildChannel("round_robin", response_generator);
  1491. auto stub = BuildStub(channel);
  1492. std::vector<int> ports = GetServersPorts();
  1493. response_generator.SetNextResolution(ports, kServiceConfigJson);
  1494. servers_[0]->SetServingStatus("health_check_service_name", true);
  1495. EXPECT_TRUE(WaitForChannelReady(channel.get(), 1 /* timeout_seconds */));
  1496. // Send an update on the channel to change it to use a health checking
  1497. // service name that is not being reported as healthy.
  1498. const char* kServiceConfigJson2 =
  1499. "{\"healthCheckConfig\": "
  1500. "{\"serviceName\": \"health_check_service_name2\"}}";
  1501. response_generator.SetNextResolution(ports, kServiceConfigJson2);
  1502. EXPECT_TRUE(WaitForChannelNotReady(channel.get()));
  1503. // Clean up.
  1504. EnableDefaultHealthCheckService(false);
  1505. }
  1506. TEST_F(ClientLbEnd2endTest, ChannelIdleness) {
  1507. // Start server.
  1508. const int kNumServers = 1;
  1509. StartServers(kNumServers);
  1510. // Set max idle time and build the channel.
  1511. ChannelArguments args;
  1512. args.SetInt(GRPC_ARG_CLIENT_IDLE_TIMEOUT_MS, 1000);
  1513. auto response_generator = BuildResolverResponseGenerator();
  1514. auto channel = BuildChannel("", response_generator, args);
  1515. auto stub = BuildStub(channel);
  1516. // The initial channel state should be IDLE.
  1517. EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
  1518. // After sending RPC, channel state should be READY.
  1519. response_generator.SetNextResolution(GetServersPorts());
  1520. CheckRpcSendOk(stub, DEBUG_LOCATION);
  1521. EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
  1522. // After a period time not using the channel, the channel state should switch
  1523. // to IDLE.
  1524. gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(1200));
  1525. EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_IDLE);
  1526. // Sending a new RPC should awake the IDLE channel.
  1527. response_generator.SetNextResolution(GetServersPorts());
  1528. CheckRpcSendOk(stub, DEBUG_LOCATION);
  1529. EXPECT_EQ(channel->GetState(false), GRPC_CHANNEL_READY);
  1530. }
  1531. class ClientLbInterceptTrailingMetadataTest : public ClientLbEnd2endTest {
  1532. protected:
  1533. void SetUp() override {
  1534. ClientLbEnd2endTest::SetUp();
  1535. current_test_instance_ = this;
  1536. }
  1537. void TearDown() override { ClientLbEnd2endTest::TearDown(); }
  1538. static void SetUpTestCase() {
  1539. grpc_init();
  1540. grpc_core::RegisterInterceptRecvTrailingMetadataLoadBalancingPolicy(
  1541. ReportTrailerIntercepted, nullptr);
  1542. }
  1543. static void TearDownTestCase() { grpc_shutdown_blocking(); }
  1544. int trailers_intercepted() {
  1545. grpc::internal::MutexLock lock(&mu_);
  1546. return trailers_intercepted_;
  1547. }
  1548. const udpa::data::orca::v1::OrcaLoadReport* backend_load_report() {
  1549. grpc::internal::MutexLock lock(&mu_);
  1550. return load_report_.get();
  1551. }
  1552. private:
  1553. static void ReportTrailerIntercepted(
  1554. void* arg, const grpc_core::LoadBalancingPolicy::BackendMetricData*
  1555. backend_metric_data) {
  1556. ClientLbInterceptTrailingMetadataTest* self = current_test_instance_;
  1557. grpc::internal::MutexLock lock(&self->mu_);
  1558. self->trailers_intercepted_++;
  1559. if (backend_metric_data != nullptr) {
  1560. self->load_report_.reset(new udpa::data::orca::v1::OrcaLoadReport);
  1561. self->load_report_->set_cpu_utilization(
  1562. backend_metric_data->cpu_utilization);
  1563. self->load_report_->set_mem_utilization(
  1564. backend_metric_data->mem_utilization);
  1565. self->load_report_->set_rps(backend_metric_data->requests_per_second);
  1566. for (const auto& p : backend_metric_data->request_cost) {
  1567. std::string name = std::string(p.first);
  1568. (*self->load_report_->mutable_request_cost())[std::move(name)] =
  1569. p.second;
  1570. }
  1571. for (const auto& p : backend_metric_data->utilization) {
  1572. std::string name = std::string(p.first);
  1573. (*self->load_report_->mutable_utilization())[std::move(name)] =
  1574. p.second;
  1575. }
  1576. }
  1577. }
  1578. static ClientLbInterceptTrailingMetadataTest* current_test_instance_;
  1579. grpc::internal::Mutex mu_;
  1580. int trailers_intercepted_ = 0;
  1581. std::unique_ptr<udpa::data::orca::v1::OrcaLoadReport> load_report_;
  1582. };
  1583. ClientLbInterceptTrailingMetadataTest*
  1584. ClientLbInterceptTrailingMetadataTest::current_test_instance_ = nullptr;
  1585. TEST_F(ClientLbInterceptTrailingMetadataTest, InterceptsRetriesDisabled) {
  1586. const int kNumServers = 1;
  1587. const int kNumRpcs = 10;
  1588. StartServers(kNumServers);
  1589. auto response_generator = BuildResolverResponseGenerator();
  1590. auto channel =
  1591. BuildChannel("intercept_trailing_metadata_lb", response_generator);
  1592. auto stub = BuildStub(channel);
  1593. response_generator.SetNextResolution(GetServersPorts());
  1594. for (size_t i = 0; i < kNumRpcs; ++i) {
  1595. CheckRpcSendOk(stub, DEBUG_LOCATION);
  1596. }
  1597. // Check LB policy name for the channel.
  1598. EXPECT_EQ("intercept_trailing_metadata_lb",
  1599. channel->GetLoadBalancingPolicyName());
  1600. EXPECT_EQ(kNumRpcs, trailers_intercepted());
  1601. EXPECT_EQ(nullptr, backend_load_report());
  1602. }
  1603. TEST_F(ClientLbInterceptTrailingMetadataTest, InterceptsRetriesEnabled) {
  1604. const int kNumServers = 1;
  1605. const int kNumRpcs = 10;
  1606. StartServers(kNumServers);
  1607. ChannelArguments args;
  1608. args.SetServiceConfigJSON(
  1609. "{\n"
  1610. " \"methodConfig\": [ {\n"
  1611. " \"name\": [\n"
  1612. " { \"service\": \"grpc.testing.EchoTestService\" }\n"
  1613. " ],\n"
  1614. " \"retryPolicy\": {\n"
  1615. " \"maxAttempts\": 3,\n"
  1616. " \"initialBackoff\": \"1s\",\n"
  1617. " \"maxBackoff\": \"120s\",\n"
  1618. " \"backoffMultiplier\": 1.6,\n"
  1619. " \"retryableStatusCodes\": [ \"ABORTED\" ]\n"
  1620. " }\n"
  1621. " } ]\n"
  1622. "}");
  1623. auto response_generator = BuildResolverResponseGenerator();
  1624. auto channel =
  1625. BuildChannel("intercept_trailing_metadata_lb", response_generator, args);
  1626. auto stub = BuildStub(channel);
  1627. response_generator.SetNextResolution(GetServersPorts());
  1628. for (size_t i = 0; i < kNumRpcs; ++i) {
  1629. CheckRpcSendOk(stub, DEBUG_LOCATION);
  1630. }
  1631. // Check LB policy name for the channel.
  1632. EXPECT_EQ("intercept_trailing_metadata_lb",
  1633. channel->GetLoadBalancingPolicyName());
  1634. EXPECT_EQ(kNumRpcs, trailers_intercepted());
  1635. EXPECT_EQ(nullptr, backend_load_report());
  1636. }
  1637. TEST_F(ClientLbInterceptTrailingMetadataTest, BackendMetricData) {
  1638. const int kNumServers = 1;
  1639. const int kNumRpcs = 10;
  1640. StartServers(kNumServers);
  1641. udpa::data::orca::v1::OrcaLoadReport load_report;
  1642. load_report.set_cpu_utilization(0.5);
  1643. load_report.set_mem_utilization(0.75);
  1644. load_report.set_rps(25);
  1645. auto* request_cost = load_report.mutable_request_cost();
  1646. (*request_cost)["foo"] = 0.8;
  1647. (*request_cost)["bar"] = 1.4;
  1648. auto* utilization = load_report.mutable_utilization();
  1649. (*utilization)["baz"] = 1.1;
  1650. (*utilization)["quux"] = 0.9;
  1651. for (const auto& server : servers_) {
  1652. server->service_.set_load_report(&load_report);
  1653. }
  1654. auto response_generator = BuildResolverResponseGenerator();
  1655. auto channel =
  1656. BuildChannel("intercept_trailing_metadata_lb", response_generator);
  1657. auto stub = BuildStub(channel);
  1658. response_generator.SetNextResolution(GetServersPorts());
  1659. for (size_t i = 0; i < kNumRpcs; ++i) {
  1660. CheckRpcSendOk(stub, DEBUG_LOCATION);
  1661. auto* actual = backend_load_report();
  1662. ASSERT_NE(actual, nullptr);
  1663. // TODO(roth): Change this to use EqualsProto() once that becomes
  1664. // available in OSS.
  1665. EXPECT_EQ(actual->cpu_utilization(), load_report.cpu_utilization());
  1666. EXPECT_EQ(actual->mem_utilization(), load_report.mem_utilization());
  1667. EXPECT_EQ(actual->rps(), load_report.rps());
  1668. EXPECT_EQ(actual->request_cost().size(), load_report.request_cost().size());
  1669. for (const auto& p : actual->request_cost()) {
  1670. auto it = load_report.request_cost().find(p.first);
  1671. ASSERT_NE(it, load_report.request_cost().end());
  1672. EXPECT_EQ(it->second, p.second);
  1673. }
  1674. EXPECT_EQ(actual->utilization().size(), load_report.utilization().size());
  1675. for (const auto& p : actual->utilization()) {
  1676. auto it = load_report.utilization().find(p.first);
  1677. ASSERT_NE(it, load_report.utilization().end());
  1678. EXPECT_EQ(it->second, p.second);
  1679. }
  1680. }
  1681. // Check LB policy name for the channel.
  1682. EXPECT_EQ("intercept_trailing_metadata_lb",
  1683. channel->GetLoadBalancingPolicyName());
  1684. EXPECT_EQ(kNumRpcs, trailers_intercepted());
  1685. }
  1686. } // namespace
  1687. } // namespace testing
  1688. } // namespace grpc
  1689. int main(int argc, char** argv) {
  1690. ::testing::InitGoogleTest(&argc, argv);
  1691. grpc::testing::TestEnvironment env(argc, argv);
  1692. const auto result = RUN_ALL_TESTS();
  1693. return result;
  1694. }