Debian Codegraph @

test/cpp/client/client_channel_stress_test.cc

raw
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>
37 #include <grpcpp/impl/codegen/sync.h>
38 #include <grpcpp/server.h>
39 #include <grpcpp/server_builder.h>
40
41 #include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_balancer_addresses.h"
42 #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
43 #include "src/core/lib/address_utils/parse_address.h"
44 #include "src/core/lib/gprpp/ref_counted_ptr.h"
45 #include "src/core/lib/gprpp/thd.h"
46 #include "src/core/lib/iomgr/exec_ctx.h"
47 #include "src/core/lib/iomgr/sockaddr.h"
48 #include "src/core/lib/resolver/server_address.h"
49 #include "src/core/lib/service_config/service_config_impl.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"
53 #include "test/core/util/test_config.h"
54 #include "test/cpp/end2end/test_service_impl.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 = 10;
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;
146 auto start_time = std::chrono::steady_clock::now();
147 while (true) {
148 if (std::chrono::duration_cast<std::chrono::seconds>(
149 std::chrono::steady_clock::now() - start_time)
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) {
176 grpc::internal::Mutex mu;
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.
179 grpc::internal::MutexLock lock(&mu);
180 port_ = grpc_pick_unused_port_or_die();
181 gpr_log(GPR_INFO, "starting %s server on port %d", type_.c_str(), port_);
182 grpc::internal::CondVar cond;
183 thread_ = std::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,
190 grpc::internal::CondVar* cond) {
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.
193 grpc::internal::MutexLock lock(mu);
194 std::ostringstream server_address;
195 server_address << server_host << ":" << port_;
196 ServerBuilder builder;
197 builder.AddListeningPort(server_address.str(),
198 InsecureServerCredentials());
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());
206 server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
207 thread_->join();
208 gpr_log(GPR_INFO, "%s shutdown completed", type_.c_str());
209 }
210
211 int port_;
212 std::string type_;
213 std::unique_ptr<Server> server_;
214 T* service_;
215 std::unique_ptr<std::thread> thread_;
216 };
217
218 struct AddressData {
219 int port;
220 std::string balancer_name;
221 };
222
223 static grpc_core::ServerAddressList CreateAddressListFromAddressDataList(
224 const std::vector<AddressData>& address_data) {
225 grpc_core::ServerAddressList addresses;
226 for (const auto& addr : address_data) {
227 std::string lb_uri_str = absl::StrCat("ipv4:127.0.0.1:", addr.port);
228 absl::StatusOr<grpc_core::URI> lb_uri = grpc_core::URI::Parse(lb_uri_str);
229 GPR_ASSERT(lb_uri.ok());
230 grpc_resolved_address address;
231 GPR_ASSERT(grpc_parse_uri(*lb_uri, &address));
232 addresses.emplace_back(
233 address.addr, address.len,
234 grpc_core::ChannelArgs().Set(GRPC_ARG_DEFAULT_AUTHORITY,
235 addr.balancer_name));
236 }
237 return addresses;
238 }
239
240 static grpc_core::Resolver::Result MakeResolverResult(
241 const std::vector<AddressData>& balancer_address_data) {
242 grpc_core::Resolver::Result result;
243 result.service_config = grpc_core::ServiceConfigImpl::Create(
244 grpc_core::ChannelArgs(),
245 "{\"loadBalancingConfig\":[{\"grpclb\":{}}]}");
246 GPR_ASSERT(result.service_config.ok());
247 grpc_core::ServerAddressList balancer_addresses =
248 CreateAddressListFromAddressDataList(balancer_address_data);
249 result.args = grpc_core::SetGrpcLbBalancerAddresses(
250 grpc_core::ChannelArgs(), std::move(balancer_addresses));
251 return result;
252 }
253
254 void SetNextResolution(const std::vector<AddressData>& address_data) {
255 grpc_core::ExecCtx exec_ctx;
256 grpc_core::Resolver::Result result = MakeResolverResult(address_data);
257 response_generator_->SetResponse(std::move(result));
258 }
259
260 void KeepSendingRequests() {
261 gpr_log(GPR_INFO, "Start sending requests.");
262 while (!shutdown_) {
263 ClientContext context;
264 context.set_deadline(grpc_timeout_milliseconds_to_deadline(1000));
265 EchoRequest request;
266 request.set_message("test");
267 EchoResponse response;
268 {
269 std::lock_guard<std::mutex> lock(stub_mutex_);
270 Status status = stub_->Echo(&context, request, &response);
271 }
272 }
273 gpr_log(GPR_INFO, "Finish sending requests.");
274 }
275
276 void CreateStub() {
277 ChannelArguments args;
278 response_generator_ =
279 grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
280 args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
281 response_generator_.get());
282 std::ostringstream uri;
283 uri << "fake:///servername_not_used";
284 channel_ = grpc::CreateCustomChannel(uri.str(),
285 InsecureChannelCredentials(), args);
286 stub_ = grpc::testing::EchoTestService::NewStub(channel_);
287 }
288
289 void Start() {
290 // Start the backends.
291 std::vector<int> backend_ports;
292 for (size_t i = 0; i < kNumBackends; ++i) {
293 backends_.emplace_back(new BackendServiceImpl());
294 backend_servers_.emplace_back(ServerThread<BackendServiceImpl>(
295 "backend", server_host_, backends_.back().get()));
296 backend_ports.push_back(backend_servers_.back().port_);
297 }
298 // Start the load balancers.
299 for (size_t i = 0; i < kNumBalancers; ++i) {
300 balancers_.emplace_back(new BalancerServiceImpl(backend_ports));
301 balancer_servers_.emplace_back(ServerThread<BalancerServiceImpl>(
302 "balancer", server_host_, balancers_.back().get()));
303 }
304 // Start sending RPCs in multiple threads.
305 CreateStub();
306 for (size_t i = 0; i < kNumClientThreads; ++i) {
307 client_threads_.emplace_back(
308 std::thread(&ClientChannelStressTest::KeepSendingRequests, this));
309 }
310 }
311
312 void Shutdown() {
313 shutdown_ = true;
314 for (size_t i = 0; i < client_threads_.size(); ++i) {
315 client_threads_[i].join();
316 }
317 for (size_t i = 0; i < balancers_.size(); ++i) {
318 balancers_[i]->Shutdown();
319 balancer_servers_[i].Shutdown();
320 }
321 for (size_t i = 0; i < backends_.size(); ++i) {
322 backend_servers_[i].Shutdown();
323 }
324 }
325
326 std::atomic_bool shutdown_{false};
327 const std::string server_host_ = "localhost";
328 std::shared_ptr<Channel> channel_;
329 std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
330 std::mutex stub_mutex_;
331 std::vector<std::unique_ptr<BackendServiceImpl>> backends_;
332 std::vector<std::unique_ptr<BalancerServiceImpl>> balancers_;
333 std::vector<ServerThread<BackendServiceImpl>> backend_servers_;
334 std::vector<ServerThread<BalancerServiceImpl>> balancer_servers_;
335 grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
336 response_generator_;
337 std::vector<std::thread> client_threads_;
338 };
339
340 } // namespace
341 } // namespace testing
342 } // namespace grpc
343
344 int main(int argc, char** argv) {
345 grpc::testing::TestEnvironment env(&argc, argv);
346 grpc::testing::ClientChannelStressTest test;
347 grpc_init();
348 test.Run();
349 grpc_shutdown();
350 return 0;
351 }