client_channel_stress_test.cc
Go to the documentation of this file.
1 /*
2  *
3  * Copyright 2017 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 
19 #include <atomic>
20 #include <memory>
21 #include <mutex>
22 #include <random>
23 #include <sstream>
24 #include <string>
25 #include <thread>
26 
27 #include "absl/memory/memory.h"
28 #include "absl/strings/str_cat.h"
29 
30 #include <grpc/grpc.h>
31 #include <grpc/support/alloc.h>
32 #include <grpc/support/log.h>
33 #include <grpc/support/time.h>
34 #include <grpcpp/channel.h>
35 #include <grpcpp/client_context.h>
36 #include <grpcpp/create_channel.h>
38 #include <grpcpp/server.h>
39 #include <grpcpp/server_builder.h>
40 
45 #include "src/core/lib/gprpp/thd.h"
50 #include "src/proto/grpc/lb/v1/load_balancer.grpc.pb.h"
51 #include "src/proto/grpc/testing/echo.grpc.pb.h"
52 #include "test/core/util/port.h"
55 
56 using grpc::lb::v1::LoadBalancer;
57 using grpc::lb::v1::LoadBalanceRequest;
58 using grpc::lb::v1::LoadBalanceResponse;
59 
60 namespace grpc {
61 namespace testing {
62 namespace {
63 
64 const size_t kNumBackends = 10;
65 const size_t kNumBalancers = 5;
66 const size_t kNumClientThreads = 100;
67 const int kResolutionUpdateIntervalMs = 50;
68 const int kServerlistUpdateIntervalMs = 10;
69 const int kTestDurationSec = 30;
70 
71 using BackendServiceImpl = TestServiceImpl;
72 
73 class BalancerServiceImpl : public LoadBalancer::Service {
74  public:
75  using Stream = ServerReaderWriter<LoadBalanceResponse, LoadBalanceRequest>;
76 
77  explicit BalancerServiceImpl(const std::vector<int>& all_backend_ports)
78  : all_backend_ports_(all_backend_ports) {}
79 
80  Status BalanceLoad(ServerContext* /*context*/, Stream* stream) override {
81  gpr_log(GPR_INFO, "LB[%p]: Start BalanceLoad.", this);
82  LoadBalanceRequest request;
83  stream->Read(&request);
84  while (!shutdown_) {
85  stream->Write(BuildRandomResponseForBackends());
86  std::this_thread::sleep_for(
87  std::chrono::milliseconds(kServerlistUpdateIntervalMs));
88  }
89  gpr_log(GPR_INFO, "LB[%p]: Finish BalanceLoad.", this);
90  return Status::OK;
91  }
92 
93  void Shutdown() { shutdown_ = true; }
94 
95  private:
96  std::string Ip4ToPackedString(const char* ip_str) {
97  struct in_addr ip4;
98  GPR_ASSERT(inet_pton(AF_INET, ip_str, &ip4) == 1);
99  return std::string(reinterpret_cast<const char*>(&ip4), sizeof(ip4));
100  }
101 
102  LoadBalanceResponse BuildRandomResponseForBackends() {
103  // Generate a random serverlist with varying size (if N =
104  // all_backend_ports_.size(), num_non_drop_entry is in [0, 2N],
105  // num_drop_entry is in [0, N]), order, duplicate, and drop rate.
106  size_t num_non_drop_entry =
107  std::rand() % (all_backend_ports_.size() * 2 + 1);
108  size_t num_drop_entry = std::rand() % (all_backend_ports_.size() + 1);
109  std::vector<int> random_backend_indices;
110  for (size_t i = 0; i < num_non_drop_entry; ++i) {
111  random_backend_indices.push_back(std::rand() % all_backend_ports_.size());
112  }
113  for (size_t i = 0; i < num_drop_entry; ++i) {
114  random_backend_indices.push_back(-1);
115  }
116  std::shuffle(random_backend_indices.begin(), random_backend_indices.end(),
117  std::mt19937(std::random_device()()));
118  // Build the response according to the random list generated above.
119  LoadBalanceResponse response;
120  for (int index : random_backend_indices) {
121  auto* server = response.mutable_server_list()->add_servers();
122  if (index < 0) {
123  server->set_drop(true);
124  server->set_load_balance_token("load_balancing");
125  } else {
126  server->set_ip_address(Ip4ToPackedString("127.0.0.1"));
127  server->set_port(all_backend_ports_[index]);
128  }
129  }
130  return response;
131  }
132 
133  std::atomic_bool shutdown_{false};
134  const std::vector<int> all_backend_ports_;
135 };
136 
137 class ClientChannelStressTest {
138  public:
139  void Run() {
140  Start();
141  // Keep updating resolution for the test duration.
142  gpr_log(GPR_INFO, "Start updating resolution.");
143  const auto wait_duration =
144  std::chrono::milliseconds(kResolutionUpdateIntervalMs);
145  std::vector<AddressData> addresses;
147  while (true) {
148  if (std::chrono::duration_cast<std::chrono::seconds>(
150  .count() > kTestDurationSec) {
151  break;
152  }
153  // Generate a random subset of balancers.
154  addresses.clear();
155  for (const auto& balancer_server : balancer_servers_) {
156  // Select each address with probability of 0.8.
157  if (std::rand() % 10 < 8) {
158  addresses.emplace_back(AddressData{balancer_server.port_, ""});
159  }
160  }
161  std::shuffle(addresses.begin(), addresses.end(),
162  std::mt19937(std::random_device()()));
163  SetNextResolution(addresses);
164  std::this_thread::sleep_for(wait_duration);
165  }
166  gpr_log(GPR_INFO, "Finish updating resolution.");
167  Shutdown();
168  }
169 
170  private:
171  template <typename T>
172  struct ServerThread {
173  explicit ServerThread(const std::string& type,
174  const std::string& server_host, T* service)
175  : type_(type), service_(service) {
177  // We need to acquire the lock here in order to prevent the notify_one
178  // by ServerThread::Start from firing before the wait below is hit.
181  gpr_log(GPR_INFO, "starting %s server on port %d", type_.c_str(), port_);
183  thread_ = absl::make_unique<std::thread>(
184  std::bind(&ServerThread::Start, this, server_host, &mu, &cond));
185  cond.Wait(&mu);
186  gpr_log(GPR_INFO, "%s server startup complete", type_.c_str());
187  }
188 
189  void Start(const std::string& server_host, grpc::internal::Mutex* mu,
191  // We need to acquire the lock here in order to prevent the notify_one
192  // below from firing before its corresponding wait is executed.
194  std::ostringstream server_address;
195  server_address << server_host << ":" << port_;
196  ServerBuilder builder;
197  builder.AddListeningPort(server_address.str(),
199  builder.RegisterService(service_);
200  server_ = builder.BuildAndStart();
201  cond->Signal();
202  }
203 
204  void Shutdown() {
205  gpr_log(GPR_INFO, "%s about to shutdown", type_.c_str());
207  thread_->join();
208  gpr_log(GPR_INFO, "%s shutdown completed", type_.c_str());
209  }
210 
211  int port_;
213  std::unique_ptr<Server> server_;
215  std::unique_ptr<std::thread> thread_;
216  };
217 
218  struct AddressData {
219  int port;
221  };
222 
223  static grpc_core::ServerAddressList CreateAddressListFromAddressDataList(
224  const std::vector<AddressData>& address_data) {
226  for (const auto& addr : address_data) {
227  std::string lb_uri_str = absl::StrCat("ipv4:127.0.0.1:", addr.port);
229  GPR_ASSERT(lb_uri.ok());
230  grpc_resolved_address address;
231  GPR_ASSERT(grpc_parse_uri(*lb_uri, &address));
233  const_cast<char*>(GRPC_ARG_DEFAULT_AUTHORITY),
234  const_cast<char*>(addr.balancer_name.c_str()));
236  grpc_channel_args_copy_and_add(nullptr, &arg, 1);
237  addresses.emplace_back(address.addr, address.len, args);
238  }
239  return addresses;
240  }
241 
242  static grpc_core::Resolver::Result MakeResolverResult(
243  const std::vector<AddressData>& balancer_address_data) {
247  nullptr, "{\"loadBalancingConfig\":[{\"grpclb\":{}}]}", &error);
249  grpc_core::ServerAddressList balancer_addresses =
250  CreateAddressListFromAddressDataList(balancer_address_data);
251  grpc_arg arg = CreateGrpclbBalancerAddressesArg(&balancer_addresses);
252  result.args = grpc_channel_args_copy_and_add(nullptr, &arg, 1);
253  return result;
254  }
255 
256  void SetNextResolution(const std::vector<AddressData>& address_data) {
258  grpc_core::Resolver::Result result = MakeResolverResult(address_data);
260  }
261 
262  void KeepSendingRequests() {
263  gpr_log(GPR_INFO, "Start sending requests.");
264  while (!shutdown_) {
265  ClientContext context;
267  EchoRequest request;
268  request.set_message("test");
269  EchoResponse response;
270  {
271  std::lock_guard<std::mutex> lock(stub_mutex_);
272  Status status = stub_->Echo(&context, request, &response);
273  }
274  }
275  gpr_log(GPR_INFO, "Finish sending requests.");
276  }
277 
278  void CreateStub() {
279  ChannelArguments args;
281  grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
284  std::ostringstream uri;
285  uri << "fake:///servername_not_used";
288  stub_ = grpc::testing::EchoTestService::NewStub(channel_);
289  }
290 
291  void Start() {
292  // Start the backends.
293  std::vector<int> backend_ports;
294  for (size_t i = 0; i < kNumBackends; ++i) {
295  backends_.emplace_back(new BackendServiceImpl());
296  backend_servers_.emplace_back(ServerThread<BackendServiceImpl>(
297  "backend", server_host_, backends_.back().get()));
298  backend_ports.push_back(backend_servers_.back().port_);
299  }
300  // Start the load balancers.
301  for (size_t i = 0; i < kNumBalancers; ++i) {
302  balancers_.emplace_back(new BalancerServiceImpl(backend_ports));
303  balancer_servers_.emplace_back(ServerThread<BalancerServiceImpl>(
304  "balancer", server_host_, balancers_.back().get()));
305  }
306  // Start sending RPCs in multiple threads.
307  CreateStub();
308  for (size_t i = 0; i < kNumClientThreads; ++i) {
309  client_threads_.emplace_back(
310  std::thread(&ClientChannelStressTest::KeepSendingRequests, this));
311  }
312  }
313 
314  void Shutdown() {
315  shutdown_ = true;
316  for (size_t i = 0; i < client_threads_.size(); ++i) {
317  client_threads_[i].join();
318  }
319  for (size_t i = 0; i < balancers_.size(); ++i) {
320  balancers_[i]->Shutdown();
321  balancer_servers_[i].Shutdown();
322  }
323  for (size_t i = 0; i < backends_.size(); ++i) {
324  backend_servers_[i].Shutdown();
325  }
326  }
327 
328  std::atomic_bool shutdown_{false};
329  const std::string server_host_ = "localhost";
330  std::shared_ptr<Channel> channel_;
331  std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
333  std::vector<std::unique_ptr<BackendServiceImpl>> backends_;
334  std::vector<std::unique_ptr<BalancerServiceImpl>> balancers_;
335  std::vector<ServerThread<BackendServiceImpl>> backend_servers_;
336  std::vector<ServerThread<BalancerServiceImpl>> balancer_servers_;
339  std::vector<std::thread> client_threads_;
340 };
341 
342 } // namespace
343 } // namespace testing
344 } // namespace grpc
345 
346 int main(int argc, char** argv) {
347  grpc::testing::TestEnvironment env(&argc, argv);
348  grpc::testing::ClientChannelStressTest test;
349  grpc_init();
350  test.Run();
351  grpc_shutdown();
352  return 0;
353 }
grpc_arg
Definition: grpc_types.h:103
Stream
Definition: bm_chttp2_transport.cc:199
_gevent_test_main.result
result
Definition: _gevent_test_main.py:96
GPR_INFO
#define GPR_INFO
Definition: include/grpc/impl/codegen/log.h:56
testing
Definition: aws_request_signer_test.cc:25
grpc::status
auto status
Definition: cpp/client/credentials_test.cc:200
now
static double now(void)
Definition: test/core/fling/client.cc:130
GRPC_ERROR_NONE
#define GRPC_ERROR_NONE
Definition: error.h:234
log.h
stub_
std::unique_ptr< grpc::testing::EchoTestService::Stub > stub_
Definition: client_channel_stress_test.cc:331
port.h
generate.env
env
Definition: generate.py:37
absl::StrCat
std::string StrCat(const AlphaNum &a, const AlphaNum &b)
Definition: abseil-cpp/absl/strings/str_cat.cc:98
backend_servers_
std::vector< ServerThread< BackendServiceImpl > > backend_servers_
Definition: client_channel_stress_test.cc:335
port
int port
Definition: client_channel_stress_test.cc:219
grpc::internal::Mutex
Definition: include/grpcpp/impl/codegen/sync.h:59
grpc
Definition: grpcpp/alarm.h:33
stub_mutex_
std::mutex stub_mutex_
Definition: client_channel_stress_test.cc:332
grpc_core::RefCountedPtr::get
T * get() const
Definition: ref_counted_ptr.h:146
grpc_core::FakeResolverResponseGenerator::SetResponse
void SetResponse(Resolver::Result result)
Definition: fake_resolver.cc:229
mutex
static uv_mutex_t mutex
Definition: threadpool.c:34
backends_
std::vector< std::unique_ptr< BackendServiceImpl > > backends_
Definition: client_channel_stress_test.cc:333
test
Definition: spinlock_test.cc:36
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
error
grpc_error_handle error
Definition: retry_filter.cc:499
fake_resolver.h
type_
std::string type_
Definition: client_channel_stress_test.cc:212
grpc::ClientContext::set_deadline
void set_deadline(const T &deadline)
Definition: grpcpp/impl/codegen/client_context.h:274
grpc_resolved_address
Definition: resolved_address.h:34
time.h
grpc_channel_arg_string_create
grpc_arg grpc_channel_arg_string_create(char *name, char *value)
Definition: channel_args.cc:476
start_time
static int64_t start_time
Definition: benchmark-getaddrinfo.c:37
grpc_core::URI::Parse
static absl::StatusOr< URI > Parse(absl::string_view uri_text)
Definition: uri_parser.cc:209
sockaddr.h
grpc::testing::TestServiceImpl
TestMultipleServiceImpl< grpc::testing::EchoTestService::Service > TestServiceImpl
Definition: test_service_impl.h:498
grpc_channel_args
Definition: grpc_types.h:132
grpc::internal::MutexLock
Definition: include/grpcpp/impl/codegen/sync.h:86
server_address
std::string server_address("0.0.0.0:10000")
T
#define T(upbtypeconst, upbtype, ctype, default_value)
grpc_core::CreateGrpclbBalancerAddressesArg
grpc_arg CreateGrpclbBalancerAddressesArg(const ServerAddressList *address_list)
Definition: grpclb_balancer_addresses.cc:66
test_service_impl.h
grpc_parse_uri
bool grpc_parse_uri(const grpc_core::URI &uri, grpc_resolved_address *resolved_addr)
Definition: parse_address.cc:293
GRPC_ARG_DEFAULT_AUTHORITY
#define GRPC_ARG_DEFAULT_AUTHORITY
Definition: grpc_types.h:251
parse_address.h
shutdown_
std::atomic_bool shutdown_
Definition: client_channel_stress_test.cc:133
profile_analyzer.builder
builder
Definition: profile_analyzer.py:159
asyncio_get_stats.args
args
Definition: asyncio_get_stats.py:40
sync.h
client_threads_
std::vector< std::thread > client_threads_
Definition: client_channel_stress_test.cc:339
grpc_core::RefCountedPtr< grpc_core::FakeResolverResponseGenerator >
absl::move
constexpr absl::remove_reference_t< T > && move(T &&t) noexcept
Definition: abseil-cpp/absl/utility/utility.h:221
GPR_ASSERT
#define GPR_ASSERT(x)
Definition: include/grpc/impl/codegen/log.h:94
grpc_timeout_milliseconds_to_deadline
gpr_timespec grpc_timeout_milliseconds_to_deadline(int64_t time_ms)
Definition: test/core/util/test_config.cc:89
gpr_log
GPRAPI void gpr_log(const char *file, int line, gpr_log_severity severity, const char *format,...) GPR_PRINT_FORMAT_CHECK(4
grpc_core::Resolver::Result
Results returned by the resolver.
Definition: resolver/resolver.h:56
GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR
#define GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR
Definition: fake_resolver.h:31
grpc.h
cond
static uv_cond_t cond
Definition: threadpool.c:33
channel.h
arg
Definition: cmdline.cc:40
server_address.h
grpc_resolved_address::len
socklen_t len
Definition: resolved_address.h:36
grpc::Status::OK
static const Status & OK
An OK pre-defined instance.
Definition: include/grpcpp/impl/codegen/status.h:113
benchmark::Shutdown
void Shutdown()
Definition: benchmark/src/benchmark.cc:607
grpc_pick_unused_port_or_die
int grpc_pick_unused_port_or_die(void)
main
int main(int argc, char **argv)
Definition: client_channel_stress_test.cc:346
grpc_core::ServerAddressList
std::vector< ServerAddress > ServerAddressList
Definition: server_address.h:120
grpc_core::ExecCtx
Definition: exec_ctx.h:97
grpc_core::ServiceConfigImpl::Create
static RefCountedPtr< ServiceConfig > Create(const grpc_channel_args *args, absl::string_view json_string, grpc_error_handle *error)
Definition: service_config_impl.cc:41
grpclb_balancer_addresses.h
server_
std::unique_ptr< Server > server_
Definition: client_channel_stress_test.cc:213
server_host_
const std::string server_host_
Definition: client_channel_stress_test.cc:329
test_config.h
update_failure_list.test
test
Definition: bloaty/third_party/protobuf/conformance/update_failure_list.py:69
absl::StatusOr::ok
ABSL_MUST_USE_RESULT bool ok() const
Definition: abseil-cpp/absl/status/statusor.h:491
port_
int port_
Definition: client_channel_stress_test.cc:211
client_context.h
http2_server_health_check.server_host
server_host
Definition: http2_server_health_check.py:27
server
Definition: examples/python/async_streaming/server.py:1
count
int * count
Definition: bloaty/third_party/googletest/googlemock/test/gmock_stress_test.cc:96
exec_ctx
grpc_core::ExecCtx exec_ctx
Definition: end2end_binder_transport_test.cc:75
index
int index
Definition: bloaty/third_party/protobuf/php/ext/google/protobuf/protobuf.h:1184
alloc.h
asyncio_get_stats.response
response
Definition: asyncio_get_stats.py:28
grpc::testing::TestEnvironment
Definition: test/core/util/test_config.h:54
service_config_impl.h
grpc::CreateCustomChannel
std::shared_ptr< Channel > CreateCustomChannel(const grpc::string &target, const std::shared_ptr< ChannelCredentials > &creds, const ChannelArguments &args)
thd.h
grpc::protobuf::util::Status
GRPC_CUSTOM_UTIL_STATUS Status
Definition: include/grpcpp/impl/codegen/config_protobuf.h:93
exec_ctx.h
ref_counted_ptr.h
grpc::InsecureServerCredentials
std::shared_ptr< ServerCredentials > InsecureServerCredentials()
Definition: insecure_server_credentials.cc:52
service_
T * service_
Definition: client_channel_stress_test.cc:214
channel_
std::shared_ptr< Channel > channel_
Definition: client_channel_stress_test.cc:330
grpc::internal::CondVar
Definition: include/grpcpp/impl/codegen/sync.h:124
all_backend_ports_
const std::vector< int > all_backend_ports_
Definition: client_channel_stress_test.cc:134
context
grpc::ClientContext context
Definition: istio_echo_server_lib.cc:61
response_generator_
grpc_core::RefCountedPtr< grpc_core::FakeResolverResponseGenerator > response_generator_
Definition: client_channel_stress_test.cc:338
absl::StatusOr
Definition: abseil-cpp/absl/status/statusor.h:187
asyncio_get_stats.type
type
Definition: asyncio_get_stats.py:37
server.h
googletest-break-on-failure-unittest.Run
def Run(command)
Definition: bloaty/third_party/googletest/googletest/test/googletest-break-on-failure-unittest.py:76
grpc::InsecureChannelCredentials
std::shared_ptr< ChannelCredentials > InsecureChannelCredentials()
Credentials for an unencrypted, unauthenticated channel.
Definition: cpp/client/insecure_credentials.cc:69
grpc_init
GRPCAPI void grpc_init(void)
Definition: init.cc:146
service
__attribute__((deprecated("Please use GRPCProtoMethod."))) @interface ProtoMethod NSString * service
Definition: ProtoMethod.h:25
grpc_error
Definition: error_internal.h:42
balancer_servers_
std::vector< ServerThread< BalancerServiceImpl > > balancer_servers_
Definition: client_channel_stress_test.cc:336
grpc_resolved_address::addr
char addr[GRPC_MAX_SOCKADDR_SIZE]
Definition: resolved_address.h:35
grpc_shutdown
GRPCAPI void grpc_shutdown(void)
Definition: init.cc:209
thread_
std::unique_ptr< std::thread > thread_
Definition: client_channel_stress_test.cc:215
addr
struct sockaddr_in addr
Definition: libuv/docs/code/tcp-echo-server/main.c:10
thread
static uv_thread_t thread
Definition: test-async-null-cb.c:29
server_builder.h
balancers_
std::vector< std::unique_ptr< BalancerServiceImpl > > balancers_
Definition: client_channel_stress_test.cc:334
grpc_channel_args_copy_and_add
grpc_channel_args * grpc_channel_args_copy_and_add(const grpc_channel_args *src, const grpc_arg *to_add, size_t num_to_add)
Definition: channel_args.cc:224
i
uint64_t i
Definition: abseil-cpp/absl/container/btree_benchmark.cc:230
create_channel.h
grpc::testing::mu
static gpr_mu mu
Definition: bm_cq.cc:162
balancer_name
std::string balancer_name
Definition: client_channel_stress_test.cc:220
GRPC_ERROR_IS_NONE
#define GRPC_ERROR_IS_NONE(err)
Definition: error.h:241
stream
voidpf stream
Definition: bloaty/third_party/zlib/contrib/minizip/ioapi.h:136


grpc
Author(s):
autogenerated on Fri May 16 2025 02:57:55