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/strings/str_cat.h"
28
29 #include <grpc/grpc.h>
30 #include <grpc/support/alloc.h>
31 #include <grpc/support/log.h>
32 #include <grpc/support/time.h>
33 #include <grpcpp/channel.h>
34 #include <grpcpp/client_context.h>
35 #include <grpcpp/create_channel.h>
36 #include <grpcpp/impl/codegen/sync.h>
37 #include <grpcpp/server.h>
38 #include <grpcpp/server_builder.h>
39
40 #include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_balancer_addresses.h"
41 #include "src/core/ext/filters/client_channel/parse_address.h"
42 #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h"
43 #include "src/core/ext/filters/client_channel/server_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/sockaddr.h"
47
48 #include "test/core/util/port.h"
49 #include "test/core/util/test_config.h"
50 #include "test/cpp/end2end/test_service_impl.h"
51
52 #include "src/proto/grpc/lb/v1/load_balancer.grpc.pb.h"
53 #include "src/proto/grpc/testing/echo.grpc.pb.h"
54
55 using grpc::lb::v1::LoadBalancer;
56 using grpc::lb::v1::LoadBalanceRequest;
57 using grpc::lb::v1::LoadBalanceResponse;
58
59 namespace grpc {
60 namespace testing {
61 namespace {
62
63 const size_t kNumBackends = 10;
64 const size_t kNumBalancers = 5;
65 const size_t kNumClientThreads = 100;
66 const int kResolutionUpdateIntervalMs = 50;
67 const int kServerlistUpdateIntervalMs = 10;
68 const int kTestDurationSec = 30;
69
70 using BackendServiceImpl = TestServiceImpl;
71
72 class BalancerServiceImpl : public LoadBalancer::Service {
73 public:
74 using Stream = ServerReaderWriter<LoadBalanceResponse, LoadBalanceRequest>;
75
BalancerServiceImpl(const std::vector<int> & all_backend_ports)76 explicit BalancerServiceImpl(const std::vector<int>& all_backend_ports)
77 : all_backend_ports_(all_backend_ports) {}
78
BalanceLoad(ServerContext *,Stream * stream)79 Status BalanceLoad(ServerContext* /*context*/, Stream* stream) override {
80 gpr_log(GPR_INFO, "LB[%p]: Start BalanceLoad.", this);
81 LoadBalanceRequest request;
82 stream->Read(&request);
83 while (!shutdown_) {
84 stream->Write(BuildRandomResponseForBackends());
85 std::this_thread::sleep_for(
86 std::chrono::milliseconds(kServerlistUpdateIntervalMs));
87 }
88 gpr_log(GPR_INFO, "LB[%p]: Finish BalanceLoad.", this);
89 return Status::OK;
90 }
91
Shutdown()92 void Shutdown() { shutdown_ = true; }
93
94 private:
Ip4ToPackedString(const char * ip_str)95 std::string Ip4ToPackedString(const char* ip_str) {
96 struct in_addr ip4;
97 GPR_ASSERT(inet_pton(AF_INET, ip_str, &ip4) == 1);
98 return std::string(reinterpret_cast<const char*>(&ip4), sizeof(ip4));
99 }
100
BuildRandomResponseForBackends()101 LoadBalanceResponse BuildRandomResponseForBackends() {
102 // Generate a random serverlist with varying size (if N =
103 // all_backend_ports_.size(), num_non_drop_entry is in [0, 2N],
104 // num_drop_entry is in [0, N]), order, duplicate, and drop rate.
105 size_t num_non_drop_entry =
106 std::rand() % (all_backend_ports_.size() * 2 + 1);
107 size_t num_drop_entry = std::rand() % (all_backend_ports_.size() + 1);
108 std::vector<int> random_backend_indices;
109 for (size_t i = 0; i < num_non_drop_entry; ++i) {
110 random_backend_indices.push_back(std::rand() % all_backend_ports_.size());
111 }
112 for (size_t i = 0; i < num_drop_entry; ++i) {
113 random_backend_indices.push_back(-1);
114 }
115 std::shuffle(random_backend_indices.begin(), random_backend_indices.end(),
116 std::mt19937(std::random_device()()));
117 // Build the response according to the random list generated above.
118 LoadBalanceResponse response;
119 for (int index : random_backend_indices) {
120 auto* server = response.mutable_server_list()->add_servers();
121 if (index < 0) {
122 server->set_drop(true);
123 server->set_load_balance_token("load_balancing");
124 } else {
125 server->set_ip_address(Ip4ToPackedString("127.0.0.1"));
126 server->set_port(all_backend_ports_[index]);
127 }
128 }
129 return response;
130 }
131
132 std::atomic_bool shutdown_{false};
133 const std::vector<int> all_backend_ports_;
134 };
135
136 class ClientChannelStressTest {
137 public:
Run()138 void Run() {
139 Start();
140 // Keep updating resolution for the test duration.
141 gpr_log(GPR_INFO, "Start updating resolution.");
142 const auto wait_duration =
143 std::chrono::milliseconds(kResolutionUpdateIntervalMs);
144 std::vector<AddressData> addresses;
145 auto start_time = std::chrono::steady_clock::now();
146 while (true) {
147 if (std::chrono::duration_cast<std::chrono::seconds>(
148 std::chrono::steady_clock::now() - start_time)
149 .count() > kTestDurationSec) {
150 break;
151 }
152 // Generate a random subset of balancers.
153 addresses.clear();
154 for (const auto& balancer_server : balancer_servers_) {
155 // Select each address with probability of 0.8.
156 if (std::rand() % 10 < 8) {
157 addresses.emplace_back(AddressData{balancer_server.port_, ""});
158 }
159 }
160 std::shuffle(addresses.begin(), addresses.end(),
161 std::mt19937(std::random_device()()));
162 SetNextResolution(addresses);
163 std::this_thread::sleep_for(wait_duration);
164 }
165 gpr_log(GPR_INFO, "Finish updating resolution.");
166 Shutdown();
167 }
168
169 private:
170 template <typename T>
171 struct ServerThread {
ServerThreadgrpc::testing::__anonb6bb16fe0111::ClientChannelStressTest::ServerThread172 explicit ServerThread(const std::string& type,
173 const std::string& server_host, T* service)
174 : type_(type), service_(service) {
175 grpc::internal::Mutex mu;
176 // We need to acquire the lock here in order to prevent the notify_one
177 // by ServerThread::Start from firing before the wait below is hit.
178 grpc::internal::MutexLock lock(&mu);
179 port_ = grpc_pick_unused_port_or_die();
180 gpr_log(GPR_INFO, "starting %s server on port %d", type_.c_str(), port_);
181 grpc::internal::CondVar cond;
182 thread_.reset(new std::thread(
183 std::bind(&ServerThread::Start, this, server_host, &mu, &cond)));
184 cond.Wait(&mu);
185 gpr_log(GPR_INFO, "%s server startup complete", type_.c_str());
186 }
187
Startgrpc::testing::__anonb6bb16fe0111::ClientChannelStressTest::ServerThread188 void Start(const std::string& server_host, grpc::internal::Mutex* mu,
189 grpc::internal::CondVar* cond) {
190 // We need to acquire the lock here in order to prevent the notify_one
191 // below from firing before its corresponding wait is executed.
192 grpc::internal::MutexLock lock(mu);
193 std::ostringstream server_address;
194 server_address << server_host << ":" << port_;
195 ServerBuilder builder;
196 builder.AddListeningPort(server_address.str(),
197 InsecureServerCredentials());
198 builder.RegisterService(service_);
199 server_ = builder.BuildAndStart();
200 cond->Signal();
201 }
202
Shutdowngrpc::testing::__anonb6bb16fe0111::ClientChannelStressTest::ServerThread203 void Shutdown() {
204 gpr_log(GPR_INFO, "%s about to shutdown", type_.c_str());
205 server_->Shutdown(grpc_timeout_milliseconds_to_deadline(0));
206 thread_->join();
207 gpr_log(GPR_INFO, "%s shutdown completed", type_.c_str());
208 }
209
210 int port_;
211 std::string type_;
212 std::unique_ptr<Server> server_;
213 T* service_;
214 std::unique_ptr<std::thread> thread_;
215 };
216
217 struct AddressData {
218 int port;
219 std::string balancer_name;
220 };
221
CreateAddressListFromAddressDataList(const std::vector<AddressData> & address_data)222 static grpc_core::ServerAddressList CreateAddressListFromAddressDataList(
223 const std::vector<AddressData>& address_data) {
224 grpc_core::ServerAddressList addresses;
225 for (const auto& addr : address_data) {
226 std::string lb_uri_str = absl::StrCat("ipv4:127.0.0.1:", addr.port);
227 grpc_uri* lb_uri = grpc_uri_parse(lb_uri_str.c_str(), true);
228 GPR_ASSERT(lb_uri != nullptr);
229 grpc_resolved_address address;
230 GPR_ASSERT(grpc_parse_uri(lb_uri, &address));
231 grpc_arg arg =
232 grpc_core::CreateGrpclbBalancerNameArg(addr.balancer_name.c_str());
233 grpc_channel_args* args =
234 grpc_channel_args_copy_and_add(nullptr, &arg, 1);
235 addresses.emplace_back(address.addr, address.len, args);
236 grpc_uri_destroy(lb_uri);
237 }
238 return addresses;
239 }
240
MakeResolverResult(const std::vector<AddressData> & balancer_address_data)241 static grpc_core::Resolver::Result MakeResolverResult(
242 const std::vector<AddressData>& balancer_address_data) {
243 grpc_core::Resolver::Result result;
244 grpc_error* error = GRPC_ERROR_NONE;
245 result.service_config = grpc_core::ServiceConfig::Create(
246 "{\"loadBalancingConfig\":[{\"grpclb\":{}}]}", &error);
247 GPR_ASSERT(error == GRPC_ERROR_NONE);
248 grpc_core::ServerAddressList balancer_addresses =
249 CreateAddressListFromAddressDataList(balancer_address_data);
250 grpc_arg arg = CreateGrpclbBalancerAddressesArg(&balancer_addresses);
251 result.args = grpc_channel_args_copy_and_add(nullptr, &arg, 1);
252 return result;
253 }
254
SetNextResolution(const std::vector<AddressData> & address_data)255 void SetNextResolution(const std::vector<AddressData>& address_data) {
256 grpc_core::ExecCtx exec_ctx;
257 grpc_core::Resolver::Result result = MakeResolverResult(address_data);
258 response_generator_->SetResponse(std::move(result));
259 }
260
KeepSendingRequests()261 void KeepSendingRequests() {
262 gpr_log(GPR_INFO, "Start sending requests.");
263 while (!shutdown_) {
264 ClientContext context;
265 context.set_deadline(grpc_timeout_milliseconds_to_deadline(1000));
266 EchoRequest request;
267 request.set_message("test");
268 EchoResponse response;
269 {
270 std::lock_guard<std::mutex> lock(stub_mutex_);
271 Status status = stub_->Echo(&context, request, &response);
272 }
273 }
274 gpr_log(GPR_INFO, "Finish sending requests.");
275 }
276
CreateStub()277 void CreateStub() {
278 ChannelArguments args;
279 response_generator_ =
280 grpc_core::MakeRefCounted<grpc_core::FakeResolverResponseGenerator>();
281 args.SetPointer(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR,
282 response_generator_.get());
283 std::ostringstream uri;
284 uri << "fake:///servername_not_used";
285 channel_ = ::grpc::CreateCustomChannel(uri.str(),
286 InsecureChannelCredentials(), args);
287 stub_ = grpc::testing::EchoTestService::NewStub(channel_);
288 }
289
Start()290 void Start() {
291 // Start the backends.
292 std::vector<int> backend_ports;
293 for (size_t i = 0; i < kNumBackends; ++i) {
294 backends_.emplace_back(new BackendServiceImpl());
295 backend_servers_.emplace_back(ServerThread<BackendServiceImpl>(
296 "backend", server_host_, backends_.back().get()));
297 backend_ports.push_back(backend_servers_.back().port_);
298 }
299 // Start the load balancers.
300 for (size_t i = 0; i < kNumBalancers; ++i) {
301 balancers_.emplace_back(new BalancerServiceImpl(backend_ports));
302 balancer_servers_.emplace_back(ServerThread<BalancerServiceImpl>(
303 "balancer", server_host_, balancers_.back().get()));
304 }
305 // Start sending RPCs in multiple threads.
306 CreateStub();
307 for (size_t i = 0; i < kNumClientThreads; ++i) {
308 client_threads_.emplace_back(
309 std::thread(&ClientChannelStressTest::KeepSendingRequests, this));
310 }
311 }
312
Shutdown()313 void Shutdown() {
314 shutdown_ = true;
315 for (size_t i = 0; i < client_threads_.size(); ++i) {
316 client_threads_[i].join();
317 }
318 for (size_t i = 0; i < balancers_.size(); ++i) {
319 balancers_[i]->Shutdown();
320 balancer_servers_[i].Shutdown();
321 }
322 for (size_t i = 0; i < backends_.size(); ++i) {
323 backend_servers_[i].Shutdown();
324 }
325 }
326
327 std::atomic_bool shutdown_{false};
328 const std::string server_host_ = "localhost";
329 std::shared_ptr<Channel> channel_;
330 std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;
331 std::mutex stub_mutex_;
332 std::vector<std::unique_ptr<BackendServiceImpl>> backends_;
333 std::vector<std::unique_ptr<BalancerServiceImpl>> balancers_;
334 std::vector<ServerThread<BackendServiceImpl>> backend_servers_;
335 std::vector<ServerThread<BalancerServiceImpl>> balancer_servers_;
336 grpc_core::RefCountedPtr<grpc_core::FakeResolverResponseGenerator>
337 response_generator_;
338 std::vector<std::thread> client_threads_;
339 };
340
341 } // namespace
342 } // namespace testing
343 } // namespace grpc
344
main(int argc,char ** argv)345 int main(int argc, char** argv) {
346 grpc::testing::TestEnvironment env(argc, argv);
347 grpc::testing::ClientChannelStressTest test;
348 grpc_init();
349 test.Run();
350 grpc_shutdown();
351 return 0;
352 }
353