1 /*
2 *
3 * Copyright 2015 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 *is % allowed in string
17 */
18
19 #include <memory>
20 #include <string>
21 #include <thread>
22 #include <utility>
23 #include <vector>
24
25 #include <gflags/gflags.h>
26 #include <grpc/support/log.h>
27 #include <grpc/support/time.h>
28 #include <grpcpp/create_channel.h>
29 #include <grpcpp/grpcpp.h>
30
31 #include "src/proto/grpc/testing/metrics.grpc.pb.h"
32 #include "src/proto/grpc/testing/metrics.pb.h"
33 #include "test/cpp/interop/interop_client.h"
34 #include "test/cpp/interop/stress_interop_client.h"
35 #include "test/cpp/util/create_test_channel.h"
36 #include "test/cpp/util/metrics_server.h"
37 #include "test/cpp/util/test_config.h"
38
39 extern void gpr_default_log(gpr_log_func_args* args);
40
41 DEFINE_int32(metrics_port, 8081, "The metrics server port.");
42
43 DEFINE_int32(sleep_duration_ms, 0,
44 "The duration (in millisec) between two"
45 " consecutive test calls (per server) issued by the server.");
46
47 DEFINE_int32(test_duration_secs, -1,
48 "The length of time (in seconds) to run"
49 " the test. Enter -1 if the test should run continuously until"
50 " forcefully terminated.");
51
52 DEFINE_string(server_addresses, "localhost:8080",
53 "The list of server addresses. The format is: \n"
54 " \"<name_1>:<port_1>,<name_2>:<port_1>...<name_N>:<port_N>\"\n"
55 " Note: <name> can be servername or IP address.");
56
57 DEFINE_int32(num_channels_per_server, 1, "Number of channels for each server");
58
59 DEFINE_int32(num_stubs_per_channel, 1,
60 "Number of stubs per each channels to server. This number also "
61 "indicates the max number of parallel RPC calls on each channel "
62 "at any given time.");
63
64 // TODO(sreek): Add more test cases here in future
65 DEFINE_string(test_cases, "",
66 "List of test cases to call along with the"
67 " relative weights in the following format:\n"
68 " \"<testcase_1:w_1>,<testcase_2:w_2>...<testcase_n:w_n>\"\n"
69 " The following testcases are currently supported:\n"
70 " empty_unary\n"
71 " large_unary\n"
72 " large_compressed_unary\n"
73 " client_streaming\n"
74 " server_streaming\n"
75 " server_compressed_streaming\n"
76 " slow_consumer\n"
77 " half_duplex\n"
78 " ping_pong\n"
79 " cancel_after_begin\n"
80 " cancel_after_first_response\n"
81 " timeout_on_sleeping_server\n"
82 " empty_stream\n"
83 " status_code_and_message\n"
84 " custom_metadata\n"
85 " Example: \"empty_unary:20,large_unary:10,empty_stream:70\"\n"
86 " The above will execute 'empty_unary', 20% of the time,"
87 " 'large_unary', 10% of the time and 'empty_stream' the remaining"
88 " 70% of the time");
89
90 DEFINE_int32(log_level, GPR_LOG_SEVERITY_INFO,
91 "Severity level of messages that should be logged. Any messages "
92 "greater than or equal to the level set here will be logged. "
93 "The choices are: 0 (GPR_LOG_SEVERITY_DEBUG), 1 "
94 "(GPR_LOG_SEVERITY_INFO) and 2 (GPR_LOG_SEVERITY_ERROR)");
95
96 DEFINE_bool(do_not_abort_on_transient_failures, true,
97 "If set to 'true', abort() is not called in case of transient "
98 "failures like temporary connection failures.");
99
100 // Options from client.cc (for compatibility with interop test).
101 // TODO(sreek): Consolidate overlapping options
102 DEFINE_bool(use_alts, false,
103 "Whether to use alts. Enable alts will disable tls.");
104 DEFINE_bool(use_tls, false, "Whether to use tls.");
105 DEFINE_bool(use_test_ca, false, "False to use SSL roots for google");
106 DEFINE_string(server_host_override, "foo.test.google.fr",
107 "Override the server host which is sent in HTTP header");
108
109 using grpc::testing::ALTS;
110 using grpc::testing::INSECURE;
111 using grpc::testing::MetricsService;
112 using grpc::testing::MetricsServiceImpl;
113 using grpc::testing::StressTestInteropClient;
114 using grpc::testing::TLS;
115 using grpc::testing::TestCaseType;
116 using grpc::testing::UNKNOWN_TEST;
117 using grpc::testing::WeightedRandomTestSelector;
118 using grpc::testing::kTestCaseList;
119 using grpc::testing::transport_security;
120
121 static int log_level = GPR_LOG_SEVERITY_DEBUG;
122
123 // A simple wrapper to grp_default_log() function. This only logs messages at or
124 // above the current log level (set in 'log_level' variable)
TestLogFunction(gpr_log_func_args * args)125 void TestLogFunction(gpr_log_func_args* args) {
126 if (args->severity >= log_level) {
127 gpr_default_log(args);
128 }
129 }
130
GetTestTypeFromName(const grpc::string & test_name)131 TestCaseType GetTestTypeFromName(const grpc::string& test_name) {
132 TestCaseType test_case = UNKNOWN_TEST;
133
134 for (auto it = kTestCaseList.begin(); it != kTestCaseList.end(); it++) {
135 if (test_name == it->second) {
136 test_case = it->first;
137 break;
138 }
139 }
140
141 return test_case;
142 }
143
144 // Converts a string of comma delimited tokens to a vector of tokens
ParseCommaDelimitedString(const grpc::string & comma_delimited_str,std::vector<grpc::string> & tokens)145 bool ParseCommaDelimitedString(const grpc::string& comma_delimited_str,
146 std::vector<grpc::string>& tokens) {
147 size_t bpos = 0;
148 size_t epos = grpc::string::npos;
149
150 while ((epos = comma_delimited_str.find(',', bpos)) != grpc::string::npos) {
151 tokens.emplace_back(comma_delimited_str.substr(bpos, epos - bpos));
152 bpos = epos + 1;
153 }
154
155 tokens.emplace_back(comma_delimited_str.substr(bpos)); // Last token
156 return true;
157 }
158
159 // Input: Test case string "<testcase_name:weight>,<testcase_name:weight>...."
160 // Output:
161 // - Whether parsing was successful (return value)
162 // - Vector of (test_type_enum, weight) pairs returned via 'tests' parameter
ParseTestCasesString(const grpc::string & test_cases,std::vector<std::pair<TestCaseType,int>> & tests)163 bool ParseTestCasesString(const grpc::string& test_cases,
164 std::vector<std::pair<TestCaseType, int>>& tests) {
165 bool is_success = true;
166
167 std::vector<grpc::string> tokens;
168 ParseCommaDelimitedString(test_cases, tokens);
169
170 for (auto it = tokens.begin(); it != tokens.end(); it++) {
171 // Token is in the form <test_name>:<test_weight>
172 size_t colon_pos = it->find(':');
173 if (colon_pos == grpc::string::npos) {
174 gpr_log(GPR_ERROR, "Error in parsing test case string: %s", it->c_str());
175 is_success = false;
176 break;
177 }
178
179 grpc::string test_name = it->substr(0, colon_pos);
180 int weight = std::stoi(it->substr(colon_pos + 1));
181 TestCaseType test_case = GetTestTypeFromName(test_name);
182 if (test_case == UNKNOWN_TEST) {
183 gpr_log(GPR_ERROR, "Unknown test case: %s", test_name.c_str());
184 is_success = false;
185 break;
186 }
187
188 tests.emplace_back(std::make_pair(test_case, weight));
189 }
190
191 return is_success;
192 }
193
194 // For debugging purposes
LogParameterInfo(const std::vector<grpc::string> & addresses,const std::vector<std::pair<TestCaseType,int>> & tests)195 void LogParameterInfo(const std::vector<grpc::string>& addresses,
196 const std::vector<std::pair<TestCaseType, int>>& tests) {
197 gpr_log(GPR_INFO, "server_addresses: %s", FLAGS_server_addresses.c_str());
198 gpr_log(GPR_INFO, "test_cases : %s", FLAGS_test_cases.c_str());
199 gpr_log(GPR_INFO, "sleep_duration_ms: %d", FLAGS_sleep_duration_ms);
200 gpr_log(GPR_INFO, "test_duration_secs: %d", FLAGS_test_duration_secs);
201 gpr_log(GPR_INFO, "num_channels_per_server: %d",
202 FLAGS_num_channels_per_server);
203 gpr_log(GPR_INFO, "num_stubs_per_channel: %d", FLAGS_num_stubs_per_channel);
204 gpr_log(GPR_INFO, "log_level: %d", FLAGS_log_level);
205 gpr_log(GPR_INFO, "do_not_abort_on_transient_failures: %s",
206 FLAGS_do_not_abort_on_transient_failures ? "true" : "false");
207
208 int num = 0;
209 for (auto it = addresses.begin(); it != addresses.end(); it++) {
210 gpr_log(GPR_INFO, "%d:%s", ++num, it->c_str());
211 }
212
213 num = 0;
214 for (auto it = tests.begin(); it != tests.end(); it++) {
215 TestCaseType test_case = it->first;
216 int weight = it->second;
217 gpr_log(GPR_INFO, "%d. TestCaseType: %d, Weight: %d", ++num, test_case,
218 weight);
219 }
220 }
221
main(int argc,char ** argv)222 int main(int argc, char** argv) {
223 grpc::testing::InitTest(&argc, &argv, true);
224
225 if (FLAGS_log_level > GPR_LOG_SEVERITY_ERROR ||
226 FLAGS_log_level < GPR_LOG_SEVERITY_DEBUG) {
227 gpr_log(GPR_ERROR, "log_level should be an integer between %d and %d",
228 GPR_LOG_SEVERITY_DEBUG, GPR_LOG_SEVERITY_ERROR);
229 return 1;
230 }
231
232 // Change the default log function to TestLogFunction which respects the
233 // log_level setting.
234 log_level = FLAGS_log_level;
235 gpr_set_log_function(TestLogFunction);
236
237 srand(time(nullptr));
238
239 // Parse the server addresses
240 std::vector<grpc::string> server_addresses;
241 ParseCommaDelimitedString(FLAGS_server_addresses, server_addresses);
242
243 // Parse test cases and weights
244 if (FLAGS_test_cases.length() == 0) {
245 gpr_log(GPR_ERROR, "No test cases supplied");
246 return 1;
247 }
248
249 std::vector<std::pair<TestCaseType, int>> tests;
250 if (!ParseTestCasesString(FLAGS_test_cases, tests)) {
251 gpr_log(GPR_ERROR, "Error in parsing test cases string %s ",
252 FLAGS_test_cases.c_str());
253 return 1;
254 }
255
256 LogParameterInfo(server_addresses, tests);
257
258 WeightedRandomTestSelector test_selector(tests);
259 MetricsServiceImpl metrics_service;
260
261 gpr_log(GPR_INFO, "Starting test(s)..");
262
263 std::vector<std::thread> test_threads;
264 std::vector<std::unique_ptr<StressTestInteropClient>> clients;
265
266 // Create and start the test threads.
267 // Note that:
268 // - Each server can have multiple channels (as configured by
269 // FLAGS_num_channels_per_server).
270 //
271 // - Each channel can have multiple stubs (as configured by
272 // FLAGS_num_stubs_per_channel). This is to test calling multiple RPCs in
273 // parallel on the same channel.
274 int thread_idx = 0;
275 int server_idx = -1;
276 char buffer[256];
277 transport_security security_type =
278 FLAGS_use_alts ? ALTS : (FLAGS_use_tls ? TLS : INSECURE);
279 for (auto it = server_addresses.begin(); it != server_addresses.end(); it++) {
280 ++server_idx;
281 // Create channel(s) for each server
282 for (int channel_idx = 0; channel_idx < FLAGS_num_channels_per_server;
283 channel_idx++) {
284 gpr_log(GPR_INFO, "Starting test with %s channel_idx=%d..", it->c_str(),
285 channel_idx);
286 grpc::testing::ChannelCreationFunc channel_creation_func = std::bind(
287 static_cast<std::shared_ptr<grpc::Channel> (*)(
288 const grpc::string&, const grpc::string&,
289 grpc::testing::transport_security, bool)>(
290 grpc::CreateTestChannel),
291 *it, FLAGS_server_host_override, security_type, !FLAGS_use_test_ca);
292
293 // Create stub(s) for each channel
294 for (int stub_idx = 0; stub_idx < FLAGS_num_stubs_per_channel;
295 stub_idx++) {
296 clients.emplace_back(new StressTestInteropClient(
297 ++thread_idx, *it, channel_creation_func, test_selector,
298 FLAGS_test_duration_secs, FLAGS_sleep_duration_ms,
299 FLAGS_do_not_abort_on_transient_failures));
300
301 bool is_already_created = false;
302 // QpsGauge name
303 std::snprintf(buffer, sizeof(buffer),
304 "/stress_test/server_%d/channel_%d/stub_%d/qps",
305 server_idx, channel_idx, stub_idx);
306
307 test_threads.emplace_back(std::thread(
308 &StressTestInteropClient::MainLoop, clients.back().get(),
309 metrics_service.CreateQpsGauge(buffer, &is_already_created)));
310
311 // The QpsGauge should not have been already created
312 GPR_ASSERT(!is_already_created);
313 }
314 }
315 }
316
317 // Start metrics server before waiting for the stress test threads
318 std::unique_ptr<grpc::Server> metrics_server;
319 if (FLAGS_metrics_port > 0) {
320 metrics_server = metrics_service.StartServer(FLAGS_metrics_port);
321 }
322
323 // Wait for the stress test threads to complete
324 for (auto it = test_threads.begin(); it != test_threads.end(); it++) {
325 it->join();
326 }
327
328 return 0;
329 }
330