client_lb_end2end_test.cc 87 KB

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