3 * Copyright 2016 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
26 #include <grpc/grpc.h>
27 #include <grpc/support/alloc.h>
28 #include <grpc/support/atm.h>
29 #include <grpc/support/log.h>
30 #include <grpc/support/string_util.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 <grpcpp/support/validate_service_config.h>
41 #include "src/core/ext/filters/client_channel/backup_poller.h"
42 #include "src/core/ext/filters/client_channel/global_subchannel_pool.h"
43 #include "src/core/ext/filters/client_channel/parse_address.h"
44 #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
45 #include "src/core/ext/filters/client_channel/server_address.h"
46 #include "src/core/lib/backoff/backoff.h"
47 #include "src/core/lib/channel/channel_args.h"
48 #include "src/core/lib/gprpp/debug_location.h"
49 #include "src/core/lib/gprpp/ref_counted_ptr.h"
50 #include "src/core/lib/iomgr/tcp_client.h"
51 #include "src/core/lib/security/credentials/fake/fake_credentials.h"
52 #include "src/cpp/client/secure_credentials.h"
53 #include "src/cpp/server/secure_server_credentials.h"
55 #include "src/proto/grpc/testing/echo.grpc.pb.h"
56 #include "test/core/util/port.h"
57 #include "test/core/util/test_config.h"
58 #include "test/cpp/end2end/test_service_impl.h"
60 #include <gmock/gmock.h>
61 #include <gtest/gtest.h>
63 using grpc::testing::EchoRequest;
64 using grpc::testing::EchoResponse;
65 using std::chrono::system_clock;
71 // Subclass of TestServiceImpl that increments a request counter for
72 // every call to the Echo RPC.
73 class MyTestServiceImpl : public TestServiceImpl {
75 MyTestServiceImpl() : request_count_(0) {}
77 Status Echo(ServerContext* context, const EchoRequest* request,
78 EchoResponse* response) override {
80 grpc::internal::MutexLock lock(&mu_);
83 AddClient(context->peer());
84 return TestServiceImpl::Echo(context, request, response);
88 grpc::internal::MutexLock lock(&mu_);
89 return request_count_;
92 void ResetCounters() {
93 grpc::internal::MutexLock lock(&mu_);
97 std::set<grpc::string> clients() {
98 grpc::internal::MutexLock lock(&clients_mu_);
103 void AddClient(const grpc::string& client) {
104 grpc::internal::MutexLock lock(&clients_mu_);
105 clients_.insert(client);
108 grpc::internal::Mutex mu_;
110 grpc::internal::Mutex clients_mu_;
111 std::set<grpc::string> clients_;
114 class ServiceConfigEnd2endTest : public ::testing::Test {
116 ServiceConfigEnd2endTest()
117 : server_host_("localhost"),
118 kRequestMessage_("Live long and prosper."),
119 creds_(new SecureChannelCredentials(
120 grpc_fake_transport_security_credentials_create())) {}
122 static void SetUpTestCase() {
123 // Make the backup poller poll very frequently in order to pick up
124 // updates from all the subchannels's FDs.
125 GPR_GLOBAL_CONFIG_SET(grpc_client_channel_backup_poll_interval_ms, 1);
128 void SetUp() override {
130 response_generator_ =
131 grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
134 void TearDown() override {
135 for (size_t i = 0; i < servers_.size(); ++i) {
136 servers_[i]->Shutdown();
138 // Explicitly destroy all the members so that we can make sure grpc_shutdown
139 // has finished by the end of this function, and thus all the registered
140 // LB policy factories are removed.
144 grpc_shutdown_blocking();
147 void CreateServers(size_t num_servers,
148 std::vector<int> ports = std::vector<int>()) {
150 for (size_t i = 0; i < num_servers; ++i) {
152 if (ports.size() == num_servers) port = ports[i];
153 servers_.emplace_back(new ServerData(port));
157 void StartServer(size_t index) { servers_[index]->Start(server_host_); }
159 void StartServers(size_t num_servers,
160 std::vector<int> ports = std::vector<int>()) {
161 CreateServers(num_servers, std::move(ports));
162 for (size_t i = 0; i < num_servers; ++i) {
167 grpc_core::Resolver::Result BuildFakeResults(const std::vector<int>& ports) {
168 grpc_core::Resolver::Result result;
169 for (const int& port : ports) {
171 gpr_asprintf(&lb_uri_str, "ipv4:127.0.0.1:%d", port);
172 grpc_uri* lb_uri = grpc_uri_parse(lb_uri_str, true);
173 GPR_ASSERT(lb_uri != nullptr);
174 grpc_resolved_address address;
175 GPR_ASSERT(grpc_parse_uri(lb_uri, &address));
176 result.addresses.emplace_back(address.addr, address.len,
178 grpc_uri_destroy(lb_uri);
179 gpr_free(lb_uri_str);
184 void SetNextResolutionNoServiceConfig(const std::vector<int>& ports) {
185 grpc_core::ExecCtx exec_ctx;
186 grpc_core::Resolver::Result result = BuildFakeResults(ports);
187 response_generator_->SetResponse(result);
190 void SetNextResolutionValidServiceConfig(const std::vector<int>& ports) {
191 grpc_core::ExecCtx exec_ctx;
192 grpc_core::Resolver::Result result = BuildFakeResults(ports);
193 result.service_config =
194 grpc_core::ServiceConfig::Create("{}", &result.service_config_error);
195 response_generator_->SetResponse(result);
198 void SetNextResolutionInvalidServiceConfig(const std::vector<int>& ports) {
199 grpc_core::ExecCtx exec_ctx;
200 grpc_core::Resolver::Result result = BuildFakeResults(ports);
201 result.service_config =
202 grpc_core::ServiceConfig::Create("{", &result.service_config_error);
203 response_generator_->SetResponse(result);
206 void SetNextResolutionWithServiceConfig(const std::vector<int>& ports,
207 const char* svc_cfg) {
208 grpc_core::ExecCtx exec_ctx;
209 grpc_core::Resolver::Result result = BuildFakeResults(ports);
210 result.service_config =
211 grpc_core::ServiceConfig::Create(svc_cfg, &result.service_config_error);
212 response_generator_->SetResponse(result);
215 std::vector<int> GetServersPorts(size_t start_index = 0) {
216 std::vector<int> ports;
217 for (size_t i = start_index; i < servers_.size(); ++i) {
218 ports.push_back(servers_[i]->port_);
223 std::unique_ptr<grpc::testing::EchoTestService::Stub> BuildStub(
224 const std::shared_ptr<Channel>& channel) {
225 return grpc::testing::EchoTestService::NewStub(channel);
228 std::shared_ptr<Channel> BuildChannel() {
229 ChannelArguments args;
230 args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
231 response_generator_.get());
232 return ::grpc::CreateCustomChannel("fake:///", creds_, args);
235 std::shared_ptr<Channel> BuildChannelWithDefaultServiceConfig() {
236 ChannelArguments args;
237 EXPECT_THAT(grpc::experimental::ValidateServiceConfigJSON(
238 ValidDefaultServiceConfig()),
239 ::testing::StrEq(""));
240 args.SetServiceConfigJSON(ValidDefaultServiceConfig());
241 args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
242 response_generator_.get());
243 return ::grpc::CreateCustomChannel("fake:///", creds_, args);
246 std::shared_ptr<Channel> BuildChannelWithInvalidDefaultServiceConfig() {
247 ChannelArguments args;
249 grpc::experimental::ValidateServiceConfigJSON(
250 InvalidDefaultServiceConfig()),
251 ::testing::HasSubstr("failed to parse JSON for service config"));
252 args.SetServiceConfigJSON(InvalidDefaultServiceConfig());
253 args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
254 response_generator_.get());
255 return ::grpc::CreateCustomChannel("fake:///", creds_, args);
259 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
260 EchoResponse* response = nullptr, int timeout_ms = 1000,
261 Status* result = nullptr, bool wait_for_ready = false) {
262 const bool local_response = (response == nullptr);
263 if (local_response) response = new EchoResponse;
265 request.set_message(kRequestMessage_);
266 ClientContext context;
267 context.set_deadline(grpc_timeout_milliseconds_to_deadline(timeout_ms));
268 if (wait_for_ready) context.set_wait_for_ready(true);
269 Status status = stub->Echo(&context, request, response);
270 if (result != nullptr) *result = status;
271 if (local_response) delete response;
276 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
277 const grpc_core::DebugLocation& location, bool wait_for_ready = false) {
278 EchoResponse response;
281 SendRpc(stub, &response, 2000, &status, wait_for_ready);
282 ASSERT_TRUE(success) << "From " << location.file() << ":" << location.line()
284 << "Error: " << status.error_message() << " "
285 << status.error_details();
286 ASSERT_EQ(response.message(), kRequestMessage_)
287 << "From " << location.file() << ":" << location.line();
288 if (!success) abort();
291 void CheckRpcSendFailure(
292 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub) {
293 const bool success = SendRpc(stub);
294 EXPECT_FALSE(success);
299 std::unique_ptr<Server> server_;
300 MyTestServiceImpl service_;
301 std::unique_ptr<std::thread> thread_;
302 bool server_ready_ = false;
303 bool started_ = false;
305 explicit ServerData(int port = 0) {
306 port_ = port > 0 ? port : grpc_pick_unused_port_or_die();
309 void Start(const grpc::string& server_host) {
310 gpr_log(GPR_INFO, "starting server on port %d", port_);
312 grpc::internal::Mutex mu;
313 grpc::internal::MutexLock lock(&mu);
314 grpc::internal::CondVar cond;
315 thread_.reset(new std::thread(
316 std::bind(&ServerData::Serve, this, server_host, &mu, &cond)));
317 cond.WaitUntil(&mu, [this] { return server_ready_; });
318 server_ready_ = false;
319 gpr_log(GPR_INFO, "server startup complete");
322 void Serve(const grpc::string& server_host, grpc::internal::Mutex* mu,
323 grpc::internal::CondVar* cond) {
324 std::ostringstream server_address;
325 server_address << server_host << ":" << port_;
326 ServerBuilder builder;
327 std::shared_ptr<ServerCredentials> creds(new SecureServerCredentials(
328 grpc_fake_transport_security_server_credentials_create()));
329 builder.AddListeningPort(server_address.str(), std::move(creds));
330 builder.RegisterService(&service_);
331 server_ = builder.BuildAndStart();
332 grpc::internal::MutexLock lock(mu);
333 server_ready_ = true;
338 if (!started_) return;
339 server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
344 void SetServingStatus(const grpc::string& service, bool serving) {
345 server_->GetHealthCheckService()->SetServingStatus(service, serving);
349 void ResetCounters() {
350 for (const auto& server : servers_) server->service_.ResetCounters();
354 const std::unique_ptr<grpc::testing::EchoTestService::Stub>& stub,
355 size_t server_idx, const grpc_core::DebugLocation& location,
356 bool ignore_failure = false) {
358 if (ignore_failure) {
361 CheckRpcSendOk(stub, location, true);
363 } while (servers_[server_idx]->service_.request_count() == 0);
367 bool WaitForChannelNotReady(Channel* channel, int timeout_seconds = 5) {
368 const gpr_timespec deadline =
369 grpc_timeout_seconds_to_deadline(timeout_seconds);
370 grpc_connectivity_state state;
371 while ((state = channel->GetState(false /* try_to_connect */)) ==
372 GRPC_CHANNEL_READY) {
373 if (!channel->WaitForStateChange(state, deadline)) return false;
378 bool WaitForChannelReady(Channel* channel, int timeout_seconds = 5) {
379 const gpr_timespec deadline =
380 grpc_timeout_seconds_to_deadline(timeout_seconds);
381 grpc_connectivity_state state;
382 while ((state = channel->GetState(true /* try_to_connect */)) !=
383 GRPC_CHANNEL_READY) {
384 if (!channel->WaitForStateChange(state, deadline)) return false;
389 bool SeenAllServers() {
390 for (const auto& server : servers_) {
391 if (server->service_.request_count() == 0) return false;
396 // Updates \a connection_order by appending to it the index of the newly
397 // connected server. Must be called after every single RPC.
398 void UpdateConnectionOrder(
399 const std::vector<std::unique_ptr<ServerData>>& servers,
400 std::vector<int>* connection_order) {
401 for (size_t i = 0; i < servers.size(); ++i) {
402 if (servers[i]->service_.request_count() == 1) {
403 // Was the server index known? If not, update connection_order.
405 std::find(connection_order->begin(), connection_order->end(), i);
406 if (it == connection_order->end()) {
407 connection_order->push_back(i);
414 const char* ValidServiceConfigV1() { return "{\"version\": \"1\"}"; }
416 const char* ValidServiceConfigV2() { return "{\"version\": \"2\"}"; }
418 const char* ValidDefaultServiceConfig() {
419 return "{\"version\": \"valid_default\"}";
422 const char* InvalidDefaultServiceConfig() {
423 return "{\"version\": \"invalid_default\"";
426 const grpc::string server_host_;
427 std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
428 std::vector<std::unique_ptr<ServerData>> servers_;
429 grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
431 const grpc::string kRequestMessage_;
432 std::shared_ptr<ChannelCredentials> creds_;
435 TEST_F(ServiceConfigEnd2endTest, NoServiceConfigTest) {
437 auto channel = BuildChannel();
438 auto stub = BuildStub(channel);
439 SetNextResolutionNoServiceConfig(GetServersPorts());
440 CheckRpcSendOk(stub, DEBUG_LOCATION);
441 EXPECT_STREQ("", channel->GetServiceConfigJSON().c_str());
444 TEST_F(ServiceConfigEnd2endTest, NoServiceConfigWithDefaultConfigTest) {
446 auto channel = BuildChannelWithDefaultServiceConfig();
447 auto stub = BuildStub(channel);
448 SetNextResolutionNoServiceConfig(GetServersPorts());
449 CheckRpcSendOk(stub, DEBUG_LOCATION);
450 EXPECT_STREQ(ValidDefaultServiceConfig(),
451 channel->GetServiceConfigJSON().c_str());
454 TEST_F(ServiceConfigEnd2endTest, InvalidServiceConfigTest) {
456 auto channel = BuildChannel();
457 auto stub = BuildStub(channel);
458 SetNextResolutionInvalidServiceConfig(GetServersPorts());
459 CheckRpcSendFailure(stub);
462 TEST_F(ServiceConfigEnd2endTest, InvalidServiceConfigWithDefaultConfigTest) {
464 auto channel = BuildChannelWithDefaultServiceConfig();
465 auto stub = BuildStub(channel);
466 SetNextResolutionInvalidServiceConfig(GetServersPorts());
467 CheckRpcSendOk(stub, DEBUG_LOCATION);
468 EXPECT_STREQ(ValidDefaultServiceConfig(),
469 channel->GetServiceConfigJSON().c_str());
472 TEST_F(ServiceConfigEnd2endTest, ValidServiceConfigUpdatesTest) {
474 auto channel = BuildChannel();
475 auto stub = BuildStub(channel);
476 SetNextResolutionWithServiceConfig(GetServersPorts(), ValidServiceConfigV1());
477 CheckRpcSendOk(stub, DEBUG_LOCATION);
478 EXPECT_STREQ(ValidServiceConfigV1(), channel->GetServiceConfigJSON().c_str());
479 SetNextResolutionWithServiceConfig(GetServersPorts(), ValidServiceConfigV2());
480 CheckRpcSendOk(stub, DEBUG_LOCATION);
481 EXPECT_STREQ(ValidServiceConfigV2(), channel->GetServiceConfigJSON().c_str());
484 TEST_F(ServiceConfigEnd2endTest,
485 NoServiceConfigUpdateAfterValidServiceConfigTest) {
487 auto channel = BuildChannel();
488 auto stub = BuildStub(channel);
489 SetNextResolutionWithServiceConfig(GetServersPorts(), ValidServiceConfigV1());
490 CheckRpcSendOk(stub, DEBUG_LOCATION);
491 EXPECT_STREQ(ValidServiceConfigV1(), channel->GetServiceConfigJSON().c_str());
492 SetNextResolutionNoServiceConfig(GetServersPorts());
493 CheckRpcSendOk(stub, DEBUG_LOCATION);
494 EXPECT_STREQ("", channel->GetServiceConfigJSON().c_str());
497 TEST_F(ServiceConfigEnd2endTest,
498 NoServiceConfigUpdateAfterValidServiceConfigWithDefaultConfigTest) {
500 auto channel = BuildChannelWithDefaultServiceConfig();
501 auto stub = BuildStub(channel);
502 SetNextResolutionWithServiceConfig(GetServersPorts(), ValidServiceConfigV1());
503 CheckRpcSendOk(stub, DEBUG_LOCATION);
504 EXPECT_STREQ(ValidServiceConfigV1(), channel->GetServiceConfigJSON().c_str());
505 SetNextResolutionNoServiceConfig(GetServersPorts());
506 CheckRpcSendOk(stub, DEBUG_LOCATION);
507 EXPECT_STREQ(ValidDefaultServiceConfig(),
508 channel->GetServiceConfigJSON().c_str());
511 TEST_F(ServiceConfigEnd2endTest,
512 InvalidServiceConfigUpdateAfterValidServiceConfigTest) {
514 auto channel = BuildChannel();
515 auto stub = BuildStub(channel);
516 SetNextResolutionWithServiceConfig(GetServersPorts(), ValidServiceConfigV1());
517 CheckRpcSendOk(stub, DEBUG_LOCATION);
518 EXPECT_STREQ(ValidServiceConfigV1(), channel->GetServiceConfigJSON().c_str());
519 SetNextResolutionInvalidServiceConfig(GetServersPorts());
520 CheckRpcSendOk(stub, DEBUG_LOCATION);
521 EXPECT_STREQ(ValidServiceConfigV1(), channel->GetServiceConfigJSON().c_str());
524 TEST_F(ServiceConfigEnd2endTest,
525 InvalidServiceConfigUpdateAfterValidServiceConfigWithDefaultConfigTest) {
527 auto channel = BuildChannelWithDefaultServiceConfig();
528 auto stub = BuildStub(channel);
529 SetNextResolutionWithServiceConfig(GetServersPorts(), ValidServiceConfigV1());
530 CheckRpcSendOk(stub, DEBUG_LOCATION);
531 EXPECT_STREQ(ValidServiceConfigV1(), channel->GetServiceConfigJSON().c_str());
532 SetNextResolutionInvalidServiceConfig(GetServersPorts());
533 CheckRpcSendOk(stub, DEBUG_LOCATION);
534 EXPECT_STREQ(ValidServiceConfigV1(), channel->GetServiceConfigJSON().c_str());
537 TEST_F(ServiceConfigEnd2endTest,
538 ValidServiceConfigAfterInvalidServiceConfigTest) {
540 auto channel = BuildChannel();
541 auto stub = BuildStub(channel);
542 SetNextResolutionInvalidServiceConfig(GetServersPorts());
543 CheckRpcSendFailure(stub);
544 SetNextResolutionValidServiceConfig(GetServersPorts());
545 CheckRpcSendOk(stub, DEBUG_LOCATION);
548 TEST_F(ServiceConfigEnd2endTest, NoServiceConfigAfterInvalidServiceConfigTest) {
550 auto channel = BuildChannel();
551 auto stub = BuildStub(channel);
552 SetNextResolutionInvalidServiceConfig(GetServersPorts());
553 CheckRpcSendFailure(stub);
554 SetNextResolutionNoServiceConfig(GetServersPorts());
555 CheckRpcSendOk(stub, DEBUG_LOCATION);
556 EXPECT_STREQ("", channel->GetServiceConfigJSON().c_str());
559 TEST_F(ServiceConfigEnd2endTest,
560 AnotherInvalidServiceConfigAfterInvalidServiceConfigTest) {
562 auto channel = BuildChannel();
563 auto stub = BuildStub(channel);
564 SetNextResolutionInvalidServiceConfig(GetServersPorts());
565 CheckRpcSendFailure(stub);
566 SetNextResolutionInvalidServiceConfig(GetServersPorts());
567 CheckRpcSendFailure(stub);
570 TEST_F(ServiceConfigEnd2endTest, InvalidDefaultServiceConfigTest) {
572 auto channel = BuildChannelWithInvalidDefaultServiceConfig();
573 auto stub = BuildStub(channel);
574 // An invalid default service config results in a lame channel which fails all
576 CheckRpcSendFailure(stub);
579 TEST_F(ServiceConfigEnd2endTest,
580 InvalidDefaultServiceConfigTestWithValidServiceConfig) {
582 auto channel = BuildChannelWithInvalidDefaultServiceConfig();
583 auto stub = BuildStub(channel);
584 CheckRpcSendFailure(stub);
585 // An invalid default service config results in a lame channel which fails all
587 SetNextResolutionValidServiceConfig(GetServersPorts());
588 CheckRpcSendFailure(stub);
591 TEST_F(ServiceConfigEnd2endTest,
592 InvalidDefaultServiceConfigTestWithInvalidServiceConfig) {
594 auto channel = BuildChannelWithInvalidDefaultServiceConfig();
595 auto stub = BuildStub(channel);
596 CheckRpcSendFailure(stub);
597 // An invalid default service config results in a lame channel which fails all
599 SetNextResolutionInvalidServiceConfig(GetServersPorts());
600 CheckRpcSendFailure(stub);
603 TEST_F(ServiceConfigEnd2endTest,
604 InvalidDefaultServiceConfigTestWithNoServiceConfig) {
606 auto channel = BuildChannelWithInvalidDefaultServiceConfig();
607 auto stub = BuildStub(channel);
608 CheckRpcSendFailure(stub);
609 // An invalid default service config results in a lame channel which fails all
611 SetNextResolutionNoServiceConfig(GetServersPorts());
612 CheckRpcSendFailure(stub);
616 } // namespace testing
619 int main(int argc, char** argv) {
620 ::testing::InitGoogleTest(&argc, argv);
621 grpc::testing::TestEnvironment env(argc, argv);
622 const auto result = RUN_ALL_TESTS();