xref: /aosp_15_r20/external/grpc-grpc/test/cpp/qps/qps_json_driver.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 //
2 //
3 // Copyright 2015-2016 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 <fstream>
20 #include <iostream>
21 #include <memory>
22 #include <set>
23 
24 #include "absl/flags/flag.h"
25 
26 #include <grpc/support/log.h>
27 #include <grpcpp/impl/codegen/config_protobuf.h>
28 
29 #include "src/core/lib/gprpp/crash.h"
30 #include "test/core/util/test_config.h"
31 #include "test/cpp/qps/benchmark_config.h"
32 #include "test/cpp/qps/driver.h"
33 #include "test/cpp/qps/parse_json.h"
34 #include "test/cpp/qps/report.h"
35 #include "test/cpp/qps/server.h"
36 #include "test/cpp/util/test_config.h"
37 #include "test/cpp/util/test_credentials_provider.h"
38 
39 ABSL_FLAG(std::string, scenarios_file, "",
40           "JSON file containing an array of Scenario objects");
41 ABSL_FLAG(std::string, scenarios_json, "",
42           "JSON string containing an array of Scenario objects");
43 ABSL_FLAG(bool, quit, false, "Quit the workers");
44 ABSL_FLAG(std::string, search_param, "",
45           "The parameter, whose value is to be searched for to achieve "
46           "targeted cpu load. For now, we have 'offered_load'. Later, "
47           "'num_channels', 'num_outstanding_requests', etc. shall be "
48           "added.");
49 ABSL_FLAG(
50     double, initial_search_value, 0.0,
51     "initial parameter value to start the search with (i.e. lower bound)");
52 ABSL_FLAG(double, targeted_cpu_load, 70.0,
53           "Targeted cpu load (unit: %, range [0,100])");
54 ABSL_FLAG(double, stride, 1,
55           "Defines each stride of the search. The larger the stride is, "
56           "the coarser the result will be, but will also be faster.");
57 ABSL_FLAG(double, error_tolerance, 0.01,
58           "Defines threshold for stopping the search. When current search "
59           "range is narrower than the error_tolerance computed range, we "
60           "stop the search.");
61 
62 ABSL_FLAG(std::string, qps_server_target_override, "",
63           "Override QPS server target to configure in client configs."
64           "Only applicable if there is a single benchmark server.");
65 
66 ABSL_FLAG(std::string, json_file_out, "", "File to write the JSON output to.");
67 
68 ABSL_FLAG(std::string, credential_type, grpc::testing::kInsecureCredentialsType,
69           "Credential type for communication with workers");
70 ABSL_FLAG(
71     std::string, per_worker_credential_types, "",
72     "A map of QPS worker addresses to credential types. When creating a "
73     "channel to a QPS worker's driver port, the qps_json_driver first checks "
74     "if the 'name:port' string is in the map, and it uses the corresponding "
75     "credential type if so. If the QPS worker's 'name:port' string is not "
76     "in the map, then the driver -> worker channel will be created with "
77     "the credentials specified in --credential_type. The value of this flag "
78     "is a semicolon-separated list of map entries, where each map entry is "
79     "a comma-separated pair.");
80 ABSL_FLAG(bool, run_inproc, false, "Perform an in-process transport test");
81 ABSL_FLAG(
82     int32_t, median_latency_collection_interval_millis, 0,
83     "Specifies the period between gathering latency medians in "
84     "milliseconds. The medians will be logged out on the client at the "
85     "end of the benchmark run. If 0, this periodic collection is disabled.");
86 
87 namespace grpc {
88 namespace testing {
89 
90 static std::map<std::string, std::string>
ConstructPerWorkerCredentialTypesMap()91 ConstructPerWorkerCredentialTypesMap() {
92   // Parse a list of the form: "addr1,cred_type1;addr2,cred_type2;..." into
93   // a map.
94   std::string remaining = absl::GetFlag(FLAGS_per_worker_credential_types);
95   std::map<std::string, std::string> out;
96   while (!remaining.empty()) {
97     size_t next_semicolon = remaining.find(';');
98     std::string next_entry = remaining.substr(0, next_semicolon);
99     if (next_semicolon == std::string::npos) {
100       remaining = "";
101     } else {
102       remaining = remaining.substr(next_semicolon + 1, std::string::npos);
103     }
104     size_t comma = next_entry.find(',');
105     if (comma == std::string::npos) {
106       gpr_log(GPR_ERROR,
107               "Expectd --per_worker_credential_types to be a list "
108               "of the form: 'addr1,cred_type1;addr2,cred_type2;...' "
109               "into.");
110       abort();
111     }
112     std::string addr = next_entry.substr(0, comma);
113     std::string cred_type = next_entry.substr(comma + 1, std::string::npos);
114     if (out.find(addr) != out.end()) {
115       grpc_core::Crash("Found duplicate addr in per_worker_credential_types.");
116     }
117     out[addr] = cred_type;
118   }
119   return out;
120 }
121 
RunAndReport(const Scenario & scenario,const std::map<std::string,std::string> & per_worker_credential_types,bool * success)122 static std::unique_ptr<ScenarioResult> RunAndReport(
123     const Scenario& scenario,
124     const std::map<std::string, std::string>& per_worker_credential_types,
125     bool* success) {
126   std::cerr << "RUNNING SCENARIO: " << scenario.name() << "\n";
127   auto result = RunScenario(
128       scenario.client_config(), scenario.num_clients(),
129       scenario.server_config(), scenario.num_servers(),
130       scenario.warmup_seconds(), scenario.benchmark_seconds(),
131       !absl::GetFlag(FLAGS_run_inproc) ? scenario.spawn_local_worker_count()
132                                        : -2,
133       absl::GetFlag(FLAGS_qps_server_target_override),
134       absl::GetFlag(FLAGS_credential_type), per_worker_credential_types,
135       absl::GetFlag(FLAGS_run_inproc),
136       absl::GetFlag(FLAGS_median_latency_collection_interval_millis));
137 
138   // Amend the result with scenario config. Eventually we should adjust
139   // RunScenario contract so we don't need to touch the result here.
140   result->mutable_scenario()->CopyFrom(scenario);
141 
142   GetReporter()->ReportQPS(*result);
143   GetReporter()->ReportQPSPerCore(*result);
144   GetReporter()->ReportLatency(*result);
145   GetReporter()->ReportTimes(*result);
146   GetReporter()->ReportCpuUsage(*result);
147   GetReporter()->ReportPollCount(*result);
148   GetReporter()->ReportQueriesPerCpuSec(*result);
149 
150   for (int i = 0; *success && i < result->client_success_size(); i++) {
151     *success = result->client_success(i);
152   }
153   for (int i = 0; *success && i < result->server_success_size(); i++) {
154     *success = result->server_success(i);
155   }
156 
157   if (!absl::GetFlag(FLAGS_json_file_out).empty()) {
158     std::ofstream json_outfile;
159     json_outfile.open(absl::GetFlag(FLAGS_json_file_out));
160     json_outfile << "{\"qps\": " << result->summary().qps() << "}\n";
161     json_outfile.close();
162   }
163 
164   return result;
165 }
166 
GetCpuLoad(Scenario * scenario,double offered_load,const std::map<std::string,std::string> & per_worker_credential_types,bool * success)167 static double GetCpuLoad(
168     Scenario* scenario, double offered_load,
169     const std::map<std::string, std::string>& per_worker_credential_types,
170     bool* success) {
171   scenario->mutable_client_config()
172       ->mutable_load_params()
173       ->mutable_poisson()
174       ->set_offered_load(offered_load);
175   auto result = RunAndReport(*scenario, per_worker_credential_types, success);
176   return result->summary().server_cpu_usage();
177 }
178 
BinarySearch(Scenario * scenario,double targeted_cpu_load,double low,double high,const std::map<std::string,std::string> & per_worker_credential_types,bool * success)179 static double BinarySearch(
180     Scenario* scenario, double targeted_cpu_load, double low, double high,
181     const std::map<std::string, std::string>& per_worker_credential_types,
182     bool* success) {
183   while (low <= high * (1 - absl::GetFlag(FLAGS_error_tolerance))) {
184     double mid = low + (high - low) / 2;
185     double current_cpu_load =
186         GetCpuLoad(scenario, mid, per_worker_credential_types, success);
187     gpr_log(GPR_DEBUG, "Binary Search: current_offered_load %.0f", mid);
188     if (!*success) {
189       gpr_log(GPR_ERROR, "Client/Server Failure");
190       break;
191     }
192     if (targeted_cpu_load <= current_cpu_load) {
193       high = mid - absl::GetFlag(FLAGS_stride);
194     } else {
195       low = mid + absl::GetFlag(FLAGS_stride);
196     }
197   }
198 
199   return low;
200 }
201 
SearchOfferedLoad(double initial_offered_load,double targeted_cpu_load,Scenario * scenario,const std::map<std::string,std::string> & per_worker_credential_types,bool * success)202 static double SearchOfferedLoad(
203     double initial_offered_load, double targeted_cpu_load, Scenario* scenario,
204     const std::map<std::string, std::string>& per_worker_credential_types,
205     bool* success) {
206   std::cerr << "RUNNING SCENARIO: " << scenario->name() << "\n";
207   double current_offered_load = initial_offered_load;
208   double current_cpu_load = GetCpuLoad(scenario, current_offered_load,
209                                        per_worker_credential_types, success);
210   if (current_cpu_load > targeted_cpu_load) {
211     gpr_log(GPR_ERROR, "Initial offered load too high");
212     return -1;
213   }
214 
215   while (*success && (current_cpu_load < targeted_cpu_load)) {
216     current_offered_load *= 2;
217     current_cpu_load = GetCpuLoad(scenario, current_offered_load,
218                                   per_worker_credential_types, success);
219     gpr_log(GPR_DEBUG, "Binary Search: current_offered_load  %.0f",
220             current_offered_load);
221   }
222 
223   double targeted_offered_load =
224       BinarySearch(scenario, targeted_cpu_load, current_offered_load / 2,
225                    current_offered_load, per_worker_credential_types, success);
226 
227   return targeted_offered_load;
228 }
229 
QpsDriver()230 static bool QpsDriver() {
231   std::string json;
232 
233   bool scfile = (!absl::GetFlag(FLAGS_scenarios_file).empty());
234   bool scjson = (!absl::GetFlag(FLAGS_scenarios_json).empty());
235   if ((!scfile && !scjson && !absl::GetFlag(FLAGS_quit)) ||
236       (scfile && (scjson || absl::GetFlag(FLAGS_quit))) ||
237       (scjson && absl::GetFlag(FLAGS_quit))) {
238     grpc_core::Crash(
239         "Exactly one of --scenarios_file, --scenarios_json, "
240         "or --quit must be set");
241   }
242 
243   auto per_worker_credential_types = ConstructPerWorkerCredentialTypesMap();
244   if (scfile) {
245     // Read the json data from disk
246     FILE* json_file = fopen(absl::GetFlag(FLAGS_scenarios_file).c_str(), "r");
247     GPR_ASSERT(json_file != nullptr);
248     fseek(json_file, 0, SEEK_END);
249     long len = ftell(json_file);
250     char* data = new char[len];
251     fseek(json_file, 0, SEEK_SET);
252     GPR_ASSERT(len == (long)fread(data, 1, len, json_file));
253     fclose(json_file);
254     json = std::string(data, data + len);
255     delete[] data;
256   } else if (scjson) {
257     json = absl::GetFlag(FLAGS_scenarios_json);
258   } else if (absl::GetFlag(FLAGS_quit)) {
259     return RunQuit(absl::GetFlag(FLAGS_credential_type),
260                    per_worker_credential_types);
261   }
262 
263   // Parse into an array of scenarios
264   Scenarios scenarios;
265   ParseJson(json, "grpc.testing.Scenarios", &scenarios);
266   bool success = true;
267 
268   // Make sure that there is at least some valid scenario here
269   GPR_ASSERT(scenarios.scenarios_size() > 0);
270 
271   for (int i = 0; i < scenarios.scenarios_size(); i++) {
272     if (absl::GetFlag(FLAGS_search_param).empty()) {
273       const Scenario& scenario = scenarios.scenarios(i);
274       RunAndReport(scenario, per_worker_credential_types, &success);
275     } else {
276       if (absl::GetFlag(FLAGS_search_param) == "offered_load") {
277         Scenario* scenario = scenarios.mutable_scenarios(i);
278         double targeted_offered_load =
279             SearchOfferedLoad(absl::GetFlag(FLAGS_initial_search_value),
280                               absl::GetFlag(FLAGS_targeted_cpu_load), scenario,
281                               per_worker_credential_types, &success);
282         gpr_log(GPR_INFO, "targeted_offered_load %f", targeted_offered_load);
283         GetCpuLoad(scenario, targeted_offered_load, per_worker_credential_types,
284                    &success);
285       } else {
286         gpr_log(GPR_ERROR, "Unimplemented search param");
287       }
288     }
289   }
290   return success;
291 }
292 
293 }  // namespace testing
294 }  // namespace grpc
295 
main(int argc,char ** argv)296 int main(int argc, char** argv) {
297   grpc::testing::TestEnvironment env(&argc, argv);
298   grpc::testing::InitTest(&argc, &argv, true);
299 
300   bool ok = grpc::testing::QpsDriver();
301 
302   return ok ? 0 : 1;
303 }
304