grpclb_fallback_test.cc
Go to the documentation of this file.
1 /*
2  *
3  * Copyright 2019 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
20 
21 #include <arpa/inet.h>
22 #include <fcntl.h>
23 #include <inttypes.h>
24 #include <netinet/in.h>
25 #include <netinet/tcp.h>
26 #include <sys/wait.h>
27 #include <unistd.h>
28 
29 #include <chrono>
30 #include <cstdlib>
31 #include <memory>
32 #include <string>
33 #include <thread>
34 
35 #include "absl/flags/flag.h"
36 #include "absl/time/time.h"
37 
38 #include <grpc/support/alloc.h>
39 #include <grpc/support/log.h>
40 #include <grpcpp/channel.h>
41 #include <grpcpp/client_context.h>
42 #include <grpcpp/grpcpp.h>
44 
48 #include "src/proto/grpc/testing/empty.pb.h"
49 #include "src/proto/grpc/testing/messages.pb.h"
50 #include "src/proto/grpc/testing/test.grpc.pb.h"
51 #include "src/proto/grpc/testing/test.pb.h"
54 
56  "User provided credentials type.");
57 ABSL_FLAG(std::string, server_uri, "localhost:1000", "Server URI target");
58 ABSL_FLAG(std::string, induce_fallback_cmd, "exit 1",
59  "Shell command to induce fallback, e.g. by unrouting addresses");
60 ABSL_FLAG(int, fallback_deadline_seconds, 1,
61  "Number of seconds to wait for fallback to occur after inducing it");
62 ABSL_FLAG(std::string, test_case, "",
63  "Test case to run. Valid options are:\n\n"
64  "fallback_before_startup : fallback before making RPCs to backends"
65  "fallback_after_startup : fallback after making RPCs to backends");
66 
67 #ifdef LINUX_VERSION_CODE
68 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 37)
69 #define SOCKET_SUPPORTS_TCP_USER_TIMEOUT
70 #endif
71 #endif
72 
73 #ifdef SOCKET_SUPPORTS_TCP_USER_TIMEOUT
74 using grpc::testing::GrpclbRouteType;
77 using grpc::testing::TestService;
78 
79 namespace {
80 
81 enum RpcMode {
82  FailFast,
83  WaitForReady,
84 };
85 
86 GrpclbRouteType DoRPCAndGetPath(TestService::Stub* stub, int deadline_seconds,
87  RpcMode rpc_mode) {
88  gpr_log(GPR_INFO, "DoRPCAndGetPath deadline_seconds:%d rpc_mode:%d",
89  deadline_seconds, rpc_mode);
93  if (rpc_mode == WaitForReady) {
95  }
96  request.set_fill_grpclb_route_type(true);
99  context.set_deadline(deadline);
100  grpc::Status s = stub->UnaryCall(&context, request, &response);
101  if (!s.ok()) {
102  gpr_log(GPR_INFO, "DoRPCAndGetPath failed. status-message: %s",
103  s.error_message().c_str());
104  return GrpclbRouteType::GRPCLB_ROUTE_TYPE_UNKNOWN;
105  }
106  GPR_ASSERT(response.grpclb_route_type() ==
107  GrpclbRouteType::GRPCLB_ROUTE_TYPE_BACKEND ||
108  response.grpclb_route_type() ==
109  GrpclbRouteType::GRPCLB_ROUTE_TYPE_FALLBACK);
110  gpr_log(GPR_INFO, "DoRPCAndGetPath done. grpclb_route_type:%d",
111  response.grpclb_route_type());
112  return response.grpclb_route_type();
113 }
114 
115 GrpclbRouteType DoRPCAndGetPath(TestService::Stub* stub, int deadline_seconds) {
116  return DoRPCAndGetPath(stub, deadline_seconds, FailFast);
117 }
118 
119 GrpclbRouteType DoWaitForReadyRPCAndGetPath(TestService::Stub* stub,
120  int deadline_seconds) {
121  return DoRPCAndGetPath(stub, deadline_seconds, WaitForReady);
122 }
123 
124 bool TcpUserTimeoutMutateFd(int fd, grpc_socket_mutator* /*mutator*/) {
125  int timeout = 20000; // 20 seconds
126  gpr_log(GPR_INFO, "Setting socket option TCP_USER_TIMEOUT on fd: %d", fd);
127  if (0 != setsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT, &timeout,
128  sizeof(timeout))) {
129  gpr_log(GPR_ERROR, "Failed to set socket option TCP_USER_TIMEOUT");
130  abort();
131  }
132  int newval;
133  socklen_t len = sizeof(newval);
134  if (0 != getsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT, &newval, &len) ||
135  newval != timeout) {
136  gpr_log(GPR_ERROR, "Failed to get expected socket option TCP_USER_TIMEOUT");
137  abort();
138  }
139  return true;
140 }
141 
142 int TcpUserTimeoutCompare(grpc_socket_mutator* /*a*/,
143  grpc_socket_mutator* /*b*/) {
144  return 0;
145 }
146 
147 void TcpUserTimeoutDestroy(grpc_socket_mutator* mutator) { delete mutator; }
148 
149 const grpc_socket_mutator_vtable kTcpUserTimeoutMutatorVtable =
150  grpc_socket_mutator_vtable{TcpUserTimeoutMutateFd, TcpUserTimeoutCompare,
151  TcpUserTimeoutDestroy, nullptr};
152 
153 std::unique_ptr<TestService::Stub> CreateFallbackTestStub() {
154  grpc::ChannelArguments channel_args;
155  grpc_socket_mutator* tcp_user_timeout_mutator = new grpc_socket_mutator();
156  grpc_socket_mutator_init(tcp_user_timeout_mutator,
157  &kTcpUserTimeoutMutatorVtable);
158  channel_args.SetSocketMutator(tcp_user_timeout_mutator);
159  // Allow LB policy to be configured by service config
161  std::shared_ptr<grpc::ChannelCredentials> channel_creds =
163  absl::GetFlag(FLAGS_custom_credentials_type), &channel_args);
164  return TestService::NewStub(grpc::CreateCustomChannel(
165  absl::GetFlag(FLAGS_server_uri), channel_creds, channel_args));
166 }
167 
168 void RunCommand(const std::string& command) {
169  gpr_log(GPR_INFO, "RunCommand: |%s|", command.c_str());
170  int out = std::system(command.c_str());
171  if (WIFEXITED(out)) {
172  int code = WEXITSTATUS(out);
173  if (code != 0) {
174  gpr_log(GPR_ERROR, "RunCommand failed exit code:%d command:|%s|", code,
175  command.c_str());
176  abort();
177  }
178  } else {
179  gpr_log(GPR_ERROR, "RunCommand failed command:|%s|", command.c_str());
180  abort();
181  }
182 }
183 
184 void WaitForFallbackAndDoRPCs(TestService::Stub* stub) {
185  int fallback_retry_count = 0;
186  bool fallback = false;
187  absl::Time fallback_deadline =
188  absl::Now() +
189  absl::Seconds(absl::GetFlag(FLAGS_fallback_deadline_seconds));
190  while (absl::Now() < fallback_deadline) {
191  GrpclbRouteType grpclb_route_type = DoRPCAndGetPath(stub, 1);
192  if (grpclb_route_type == GrpclbRouteType::GRPCLB_ROUTE_TYPE_BACKEND) {
194  "Got grpclb route type backend. Backends are "
195  "supposed to be unreachable, so this test is broken");
196  GPR_ASSERT(0);
197  }
198  if (grpclb_route_type == GrpclbRouteType::GRPCLB_ROUTE_TYPE_FALLBACK) {
200  "Made one successful RPC to a fallback. Now expect the same for "
201  "the rest.");
202  fallback = true;
203  break;
204  } else {
205  gpr_log(GPR_ERROR, "Retryable RPC failure on iteration: %d",
206  fallback_retry_count);
207  }
208  fallback_retry_count++;
209  }
210  if (!fallback) {
211  gpr_log(GPR_ERROR, "Didn't fall back within deadline");
212  GPR_ASSERT(0);
213  }
214  for (int i = 0; i < 30; i++) {
215  GrpclbRouteType grpclb_route_type = DoRPCAndGetPath(stub, 20);
216  GPR_ASSERT(grpclb_route_type ==
217  GrpclbRouteType::GRPCLB_ROUTE_TYPE_FALLBACK);
218  std::this_thread::sleep_for(std::chrono::seconds(1));
219  }
220 }
221 
222 void DoFallbackBeforeStartupTest() {
223  std::unique_ptr<TestService::Stub> stub = CreateFallbackTestStub();
224  RunCommand(absl::GetFlag(FLAGS_induce_fallback_cmd));
225  WaitForFallbackAndDoRPCs(stub.get());
226 }
227 
228 void DoFallbackAfterStartupTest() {
229  std::unique_ptr<TestService::Stub> stub = CreateFallbackTestStub();
230  GrpclbRouteType grpclb_route_type = DoRPCAndGetPath(stub.get(), 20);
231  GPR_ASSERT(grpclb_route_type == GrpclbRouteType::GRPCLB_ROUTE_TYPE_BACKEND);
232  RunCommand(absl::GetFlag(FLAGS_induce_fallback_cmd));
233  WaitForFallbackAndDoRPCs(stub.get());
234 }
235 
236 } // namespace
237 
238 int main(int argc, char** argv) {
239  grpc::testing::InitTest(&argc, &argv, true);
240  gpr_log(GPR_INFO, "Testing: %s", absl::GetFlag(FLAGS_test_case).c_str());
241  if (absl::GetFlag(FLAGS_test_case) == "fallback_before_startup") {
242  DoFallbackBeforeStartupTest();
243  gpr_log(GPR_INFO, "DoFallbackBeforeStartup done!");
244  } else if (absl::GetFlag(FLAGS_test_case) == "fallback_after_startup") {
245  DoFallbackAfterStartupTest();
246  gpr_log(GPR_INFO, "DoFallbackBeforeStartup done!");
247  } else {
248  gpr_log(GPR_ERROR, "Invalid test case: %s",
249  absl::GetFlag(FLAGS_test_case).c_str());
250  abort();
251  }
252 }
253 
254 #else
255 
256 int main(int argc, char** argv) {
257  grpc::testing::InitTest(&argc, &argv, true);
259  "This test requires TCP_USER_TIMEOUT, which isn't available");
260  abort();
261 }
262 
263 #endif // SOCKET_SUPPORTS_TCP_USER_TIMEOUT
GRPC_ARG_SERVICE_CONFIG_DISABLE_RESOLUTION
#define GRPC_ARG_SERVICE_CONFIG_DISABLE_RESOLUTION
Definition: grpc_types.h:306
test_credentials_provider.h
grpc::testing::InitTest
void InitTest(int *argc, char ***argv, bool remove_flags)
Definition: test_config_cc.cc:28
messages_pb2.SimpleRequest
SimpleRequest
Definition: messages_pb2.py:597
absl::time_internal::cctz::seconds
std::chrono::duration< std::int_fast64_t > seconds
Definition: abseil-cpp/absl/time/internal/cctz/include/cctz/time_zone.h:40
GPR_INFO
#define GPR_INFO
Definition: include/grpc/impl/codegen/log.h:56
gen_build_yaml.out
dictionary out
Definition: src/benchmark/gen_build_yaml.py:24
now
static double now(void)
Definition: test/core/fling/client.cc:130
log.h
grpc::testing::CredentialsProvider::GetChannelCredentials
virtual std::shared_ptr< ChannelCredentials > GetChannelCredentials(const std::string &type, ChannelArguments *args)=0
absl::Time
Definition: third_party/abseil-cpp/absl/time/time.h:642
grpc_socket_mutator
struct grpc_socket_mutator grpc_socket_mutator
Definition: grpc_types.h:73
grpc_socket_mutator_init
void grpc_socket_mutator_init(grpc_socket_mutator *mutator, const grpc_socket_mutator_vtable *vtable)
Definition: socket_mutator.cc:30
absl::time_internal::cctz::time_point
std::chrono::time_point< std::chrono::system_clock, D > time_point
Definition: abseil-cpp/absl/time/internal/cctz/include/cctz/time_zone.h:39
grpc::ClientContext::set_wait_for_ready
void set_wait_for_ready(bool wait_for_ready)
Definition: grpcpp/impl/codegen/client_context.h:285
string.h
benchmark.request
request
Definition: benchmark.py:77
testing::internal::string
::std::string string
Definition: bloaty/third_party/protobuf/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:881
grpc::ClientContext::set_deadline
void set_deadline(const T &deadline)
Definition: grpcpp/impl/codegen/client_context.h:274
absl::FormatConversionChar::s
@ s
grpc::ChannelArguments::SetSocketMutator
void SetSocketMutator(grpc_socket_mutator *mutator)
Set a mutator for the underlying socket.
Definition: channel_arguments.cc:96
run_xds_tests.server_uri
string server_uri
Definition: run_xds_tests.py:3320
async_greeter_client.stub
stub
Definition: hellostreamingworld/async_greeter_client.py:26
GPR_ASSERT
#define GPR_ASSERT(x)
Definition: include/grpc/impl/codegen/log.h:94
channel_arguments.h
gen_stats_data.c_str
def c_str(s, encoding='ascii')
Definition: gen_stats_data.py:38
gpr_log
GPRAPI void gpr_log(const char *file, int line, gpr_log_severity severity, const char *format,...) GPR_PRINT_FORMAT_CHECK(4
custom_credentials_type
std::string custom_credentials_type("INSECURE_CREDENTIALS")
grpcpp.h
channel.h
grpc_socket_mutator_vtable
Definition: socket_mutator.h:48
main
int main(int argc, char **argv)
Definition: grpclb_fallback_test.cc:256
absl::GetFlag
ABSL_MUST_USE_RESULT T GetFlag(const absl::Flag< T > &flag)
Definition: abseil-cpp/absl/flags/flag.h:98
GPR_ERROR
#define GPR_ERROR
Definition: include/grpc/impl/codegen/log.h:57
grpc_socket_mutator
Definition: socket_mutator.h:62
ABSL_FLAG
ABSL_FLAG(std::string, custom_credentials_type, "", "User provided credentials type.")
grpc::ClientContext
Definition: grpcpp/impl/codegen/client_context.h:195
absl::Seconds
constexpr Duration Seconds(T n)
Definition: third_party/abseil-cpp/absl/time/time.h:419
absl::Now
ABSL_NAMESPACE_BEGIN Time Now()
Definition: abseil-cpp/absl/time/clock.cc:39
grpc::ChannelArguments
Definition: grpcpp/support/channel_arguments.h:39
client_context.h
grpc::testing::GetCredentialsProvider
CredentialsProvider * GetCredentialsProvider()
Definition: test_credentials_provider.cc:169
port.h
alloc.h
asyncio_get_stats.response
response
Definition: asyncio_get_stats.py:28
grpc::CreateCustomChannel
std::shared_ptr< Channel > CreateCustomChannel(const grpc::string &target, const std::shared_ptr< ChannelCredentials > &creds, const ChannelArguments &args)
grpc::Status
Definition: include/grpcpp/impl/codegen/status.h:35
test_config.h
grpc::ChannelArguments::SetInt
void SetInt(const std::string &key, int value)
Set an integer argument value under key.
Definition: channel_arguments.cc:174
context
grpc::ClientContext context
Definition: istio_echo_server_lib.cc:61
code
Definition: bloaty/third_party/zlib/contrib/infback9/inftree9.h:24
len
int len
Definition: abseil-cpp/absl/base/internal/low_level_alloc_test.cc:46
messages_pb2.SimpleResponse
SimpleResponse
Definition: messages_pb2.py:604
socket_mutator.h
timeout
uv_timer_t timeout
Definition: libuv/docs/code/uvwget/main.c:9
command
const char * command
Definition: grpc_tool.cc:247
i
uint64_t i
Definition: abseil-cpp/absl/container/btree_benchmark.cc:230
port_platform.h


grpc
Author(s):
autogenerated on Thu Mar 13 2025 02:59:48