xref: /aosp_15_r20/external/grpc-grpc/test/cpp/interop/client.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
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 //
17 //
18 
19 #include <memory>
20 #include <unordered_map>
21 
22 #include "absl/flags/flag.h"
23 
24 #include <grpc/grpc.h>
25 #include <grpc/support/alloc.h>
26 #include <grpc/support/log.h>
27 #include <grpcpp/channel.h>
28 #include <grpcpp/client_context.h>
29 #include <grpcpp/support/channel_arguments.h>
30 
31 #include "src/core/lib/gpr/string.h"
32 #include "src/core/lib/gprpp/crash.h"
33 #include "test/core/util/test_config.h"
34 #include "test/cpp/interop/client_helper.h"
35 #include "test/cpp/interop/interop_client.h"
36 #include "test/cpp/util/test_config.h"
37 
38 ABSL_FLAG(bool, use_alts, false,
39           "Whether to use alts. Enable alts will disable tls.");
40 ABSL_FLAG(bool, use_tls, false, "Whether to use tls.");
41 ABSL_FLAG(std::string, custom_credentials_type, "",
42           "User provided credentials type.");
43 ABSL_FLAG(bool, use_test_ca, false, "False to use SSL roots for google");
44 ABSL_FLAG(int32_t, server_port, 0, "Server port.");
45 ABSL_FLAG(std::string, server_host, "localhost", "Server host to connect to");
46 ABSL_FLAG(std::string, server_host_override, "",
47           "Override the server host which is sent in HTTP header");
48 ABSL_FLAG(
49     std::string, test_case, "large_unary",
50     "Configure different test cases. Valid options are:\n\n"
51     "all : all test cases;\n"
52 
53     // TODO(veblush): Replace the help message with the following full message
54     // once Abseil fixes the flag-help compiler error on Windows. (b/171659833)
55     //
56     //"cancel_after_begin : cancel stream after starting it;\n"
57     //"cancel_after_first_response: cancel on first response;\n"
58     //"channel_soak: sends 'soak_iterations' rpcs, rebuilds channel each
59     // time;\n" "client_compressed_streaming : compressed request streaming with
60     //" "client_compressed_unary : single compressed request;\n"
61     //"client_streaming : request streaming with single response;\n"
62     //"compute_engine_creds: large_unary with compute engine auth;\n"
63     //"custom_metadata: server will echo custom metadata;\n"
64     //"empty_stream : bi-di stream with no request/response;\n"
65     //"empty_unary : empty (zero bytes) request and response;\n"
66     //"google_default_credentials: large unary using GDC;\n"
67     //"half_duplex : half-duplex streaming;\n"
68     //"jwt_token_creds: large_unary with JWT token auth;\n"
69     //"large_unary : single request and (large) response;\n"
70     //"long_lived_channel: sends large_unary rpcs over a long-lived channel;\n"
71     //"oauth2_auth_token: raw oauth2 access token auth;\n"
72     //"orca_per_rpc: custom LB policy receives per-query metric reports;\n"
73     //"orca_oob: receives out-of-band metric reports from the backend;\n"
74     //"per_rpc_creds: raw oauth2 access token on a single rpc;\n"
75     //"ping_pong : full-duplex streaming;\n"
76     //"response streaming;\n"
77     //"rpc_soak: 'sends soak_iterations' large_unary rpcs;\n"
78     //"server_compressed_streaming : single request with compressed "
79     //"server_compressed_unary : single compressed response;\n"
80     //"server_streaming : single request with response streaming;\n"
81     //"slow_consumer : single request with response streaming with "
82     //"slow client consumer;\n"
83     //"special_status_message: verify Unicode and whitespace in status
84     // message;\n" "status_code_and_message: verify status code & message;\n"
85     //"timeout_on_sleeping_server: deadline exceeds on stream;\n"
86     //"unimplemented_method: client calls an unimplemented method;\n"
87     //"unimplemented_service: client calls an unimplemented service;\n"
88     //
89 );
90 ABSL_FLAG(std::string, default_service_account, "",
91           "Email of GCE default service account");
92 ABSL_FLAG(std::string, service_account_key_file, "",
93           "Path to service account json key file.");
94 ABSL_FLAG(std::string, oauth_scope, "", "Scope for OAuth tokens.");
95 ABSL_FLAG(bool, do_not_abort_on_transient_failures, false,
96           "If set to 'true', abort() is not called in case of transient "
97           "failures (i.e failures that are temporary and will likely go away "
98           "on retrying; like a temporary connection failure) and an error "
99           "message is printed instead. Note that this flag just controls "
100           "whether abort() is called or not. It does not control whether the "
101           "test is retried in case of transient failures (and currently the "
102           "interop tests are not retried even if this flag is set to true)");
103 ABSL_FLAG(int32_t, soak_iterations, 1000,
104           "The number of iterations to use for the two soak tests; rpc_soak "
105           "and channel_soak.");
106 ABSL_FLAG(int32_t, soak_max_failures, 0,
107           "The number of iterations in soak tests that are allowed to fail "
108           "(either due to non-OK status code or exceeding the "
109           "per-iteration max acceptable latency).");
110 ABSL_FLAG(int32_t, soak_per_iteration_max_acceptable_latency_ms, 0,
111           "The number of milliseconds a single iteration in the two soak "
112           "tests (rpc_soak and channel_soak) should take.");
113 ABSL_FLAG(int32_t, soak_overall_timeout_seconds, 0,
114           "The overall number of seconds after which a soak test should "
115           "stop and fail, if the desired number of iterations have not yet "
116           "completed.");
117 ABSL_FLAG(int32_t, soak_min_time_ms_between_rpcs, 0,
118           "The minimum time in milliseconds between consecutive RPCs in a "
119           "soak test (rpc_soak or channel_soak), useful for limiting QPS");
120 ABSL_FLAG(int32_t, iteration_interval, 10,
121           "The interval in seconds between rpcs. This is used by "
122           "long_connection test");
123 ABSL_FLAG(
124     int32_t, soak_request_size, 271828,
125     "The request size in a soak RPC. "
126     "The default value is set based on the interop large unary test case.");
127 ABSL_FLAG(
128     int32_t, soak_response_size, 314159,
129     "The response size in a soak RPC. "
130     "The default value is set based on the interop large unary test case.");
131 ABSL_FLAG(std::string, additional_metadata, "",
132           "Additional metadata to send in each request, as a "
133           "semicolon-separated list of key:value pairs.");
134 ABSL_FLAG(
135     bool, log_metadata_and_status, false,
136     "If set to 'true', will print received initial and trailing metadata, "
137     "grpc-status and error message to the console, in a stable format.");
138 ABSL_FLAG(std::string, service_config_json, "",
139           "Disables service config lookups and sets the provided string as the "
140           "default service config");
141 
142 using grpc::testing::CreateChannelForTestCase;
143 using grpc::testing::GetServiceAccountJsonKey;
144 using grpc::testing::UpdateActions;
145 
146 namespace {
147 
148 // Parse the contents of FLAGS_additional_metadata into a map. Allow
149 // alphanumeric characters and dashes in keys, and any character but semicolons
150 // in values. Convert keys to lowercase. On failure, log an error and return
151 // false.
152 absl::StatusOr<std::multimap<std::string, std::string>>
ParseAdditionalMetadataFlag(const std::string & flag)153 ParseAdditionalMetadataFlag(const std::string& flag) {
154   std::multimap<std::string, std::string> additional_metadata;
155   if (flag.empty()) {
156     return additional_metadata;
157   }
158   size_t start_pos = 0;
159   while (start_pos < flag.length()) {
160     size_t colon_pos = flag.find(':', start_pos);
161     if (colon_pos == std::string::npos) {
162       return absl::InvalidArgumentError(
163           "Couldn't parse metadata flag: extra characters at end of flag");
164     }
165     size_t semicolon_pos = flag.find(';', colon_pos);
166 
167     std::string key = flag.substr(start_pos, colon_pos - start_pos);
168     std::string value =
169         flag.substr(colon_pos + 1, semicolon_pos - colon_pos - 1);
170 
171     constexpr char alphanum_and_hyphen[] =
172         "-0123456789"
173         "abcdefghijklmnopqrstuvwxyz"
174         "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
175     if (key.find_first_not_of(alphanum_and_hyphen) != std::string::npos) {
176       return absl::InvalidArgumentError(absl::StrCat(
177           "Couldn't parse metadata flag: key contains characters other "
178           "than alphanumeric and hyphens: ",
179           key));
180     }
181 
182     // Convert to lowercase.
183     for (char& c : key) {
184       if (c >= 'A' && c <= 'Z') {
185         c += ('a' - 'A');
186       }
187     }
188 
189     gpr_log(GPR_INFO, "Adding additional metadata with key %s and value %s",
190             key.c_str(), value.c_str());
191     additional_metadata.insert({key, value});
192 
193     if (semicolon_pos == std::string::npos) {
194       break;
195     } else {
196       start_pos = semicolon_pos + 1;
197     }
198   }
199 
200   return additional_metadata;
201 }
202 
203 }  // namespace
204 
main(int argc,char ** argv)205 int main(int argc, char** argv) {
206   grpc::testing::TestEnvironment env(&argc, argv);
207   grpc::testing::InitTest(&argc, &argv, true);
208   gpr_log(GPR_INFO, "Testing these cases: %s",
209           absl::GetFlag(FLAGS_test_case).c_str());
210   int ret = 0;
211 
212   std::string test_case = absl::GetFlag(FLAGS_test_case);
213   auto additional_metadata =
214       ParseAdditionalMetadataFlag(absl::GetFlag(FLAGS_additional_metadata));
215   if (!additional_metadata.ok()) {
216     gpr_log(GPR_ERROR, "%s",
217             std::string(additional_metadata.status().message()).c_str());
218     return 1;
219   }
220   grpc::testing::ChannelCreationFunc channel_creation_func =
221       [test_case, &additional_metadata](grpc::ChannelArguments arguments) {
222         std::vector<std::unique_ptr<
223             grpc::experimental::ClientInterceptorFactoryInterface>>
224             factories;
225         if (!additional_metadata->empty()) {
226           factories.emplace_back(
227               new grpc::testing::AdditionalMetadataInterceptorFactory(
228                   *additional_metadata));
229         }
230         if (absl::GetFlag(FLAGS_log_metadata_and_status)) {
231           factories.emplace_back(
232               new grpc::testing::MetadataAndStatusLoggerInterceptorFactory());
233         }
234         std::string service_config_json =
235             absl::GetFlag(FLAGS_service_config_json);
236         if (!service_config_json.empty()) {
237           arguments.SetServiceConfigJSON(service_config_json);
238         }
239         return CreateChannelForTestCase(test_case, std::move(factories),
240                                         arguments);
241       };
242 
243   grpc::testing::InteropClient client(
244       channel_creation_func, true,
245       absl::GetFlag(FLAGS_do_not_abort_on_transient_failures));
246 
247   std::unordered_map<std::string, std::function<bool()>> actions;
248   actions["empty_unary"] =
249       std::bind(&grpc::testing::InteropClient::DoEmpty, &client);
250   actions["large_unary"] =
251       std::bind(&grpc::testing::InteropClient::DoLargeUnary, &client);
252   actions["server_compressed_unary"] = std::bind(
253       &grpc::testing::InteropClient::DoServerCompressedUnary, &client);
254   actions["client_compressed_unary"] = std::bind(
255       &grpc::testing::InteropClient::DoClientCompressedUnary, &client);
256   actions["client_streaming"] =
257       std::bind(&grpc::testing::InteropClient::DoRequestStreaming, &client);
258   actions["server_streaming"] =
259       std::bind(&grpc::testing::InteropClient::DoResponseStreaming, &client);
260   actions["server_compressed_streaming"] = std::bind(
261       &grpc::testing::InteropClient::DoServerCompressedStreaming, &client);
262   actions["client_compressed_streaming"] = std::bind(
263       &grpc::testing::InteropClient::DoClientCompressedStreaming, &client);
264   actions["slow_consumer"] = std::bind(
265       &grpc::testing::InteropClient::DoResponseStreamingWithSlowConsumer,
266       &client);
267   actions["half_duplex"] =
268       std::bind(&grpc::testing::InteropClient::DoHalfDuplex, &client);
269   actions["ping_pong"] =
270       std::bind(&grpc::testing::InteropClient::DoPingPong, &client);
271   actions["cancel_after_begin"] =
272       std::bind(&grpc::testing::InteropClient::DoCancelAfterBegin, &client);
273   actions["cancel_after_first_response"] = std::bind(
274       &grpc::testing::InteropClient::DoCancelAfterFirstResponse, &client);
275   actions["timeout_on_sleeping_server"] = std::bind(
276       &grpc::testing::InteropClient::DoTimeoutOnSleepingServer, &client);
277   actions["empty_stream"] =
278       std::bind(&grpc::testing::InteropClient::DoEmptyStream, &client);
279   actions["pick_first_unary"] =
280       std::bind(&grpc::testing::InteropClient::DoPickFirstUnary, &client);
281   actions["orca_per_rpc"] =
282       std::bind(&grpc::testing::InteropClient::DoOrcaPerRpc, &client);
283   actions["orca_oob"] =
284       std::bind(&grpc::testing::InteropClient::DoOrcaOob, &client);
285   if (absl::GetFlag(FLAGS_use_tls)) {
286     actions["compute_engine_creds"] =
287         std::bind(&grpc::testing::InteropClient::DoComputeEngineCreds, &client,
288                   absl::GetFlag(FLAGS_default_service_account),
289                   absl::GetFlag(FLAGS_oauth_scope));
290     actions["jwt_token_creds"] =
291         std::bind(&grpc::testing::InteropClient::DoJwtTokenCreds, &client,
292                   GetServiceAccountJsonKey());
293     actions["oauth2_auth_token"] =
294         std::bind(&grpc::testing::InteropClient::DoOauth2AuthToken, &client,
295                   absl::GetFlag(FLAGS_default_service_account),
296                   absl::GetFlag(FLAGS_oauth_scope));
297     actions["per_rpc_creds"] =
298         std::bind(&grpc::testing::InteropClient::DoPerRpcCreds, &client,
299                   GetServiceAccountJsonKey());
300   }
301   if (absl::GetFlag(FLAGS_custom_credentials_type) ==
302       "google_default_credentials") {
303     actions["google_default_credentials"] =
304         std::bind(&grpc::testing::InteropClient::DoGoogleDefaultCredentials,
305                   &client, absl::GetFlag(FLAGS_default_service_account));
306   }
307   actions["status_code_and_message"] =
308       std::bind(&grpc::testing::InteropClient::DoStatusWithMessage, &client);
309   actions["special_status_message"] =
310       std::bind(&grpc::testing::InteropClient::DoSpecialStatusMessage, &client);
311   actions["custom_metadata"] =
312       std::bind(&grpc::testing::InteropClient::DoCustomMetadata, &client);
313   actions["unimplemented_method"] =
314       std::bind(&grpc::testing::InteropClient::DoUnimplementedMethod, &client);
315   actions["unimplemented_service"] =
316       std::bind(&grpc::testing::InteropClient::DoUnimplementedService, &client);
317   actions["channel_soak"] = std::bind(
318       &grpc::testing::InteropClient::DoChannelSoakTest, &client,
319       absl::GetFlag(FLAGS_server_host), absl::GetFlag(FLAGS_soak_iterations),
320       absl::GetFlag(FLAGS_soak_max_failures),
321       absl::GetFlag(FLAGS_soak_per_iteration_max_acceptable_latency_ms),
322       absl::GetFlag(FLAGS_soak_min_time_ms_between_rpcs),
323       absl::GetFlag(FLAGS_soak_overall_timeout_seconds),
324       absl::GetFlag(FLAGS_soak_request_size),
325       absl::GetFlag(FLAGS_soak_response_size));
326   actions["rpc_soak"] = std::bind(
327       &grpc::testing::InteropClient::DoRpcSoakTest, &client,
328       absl::GetFlag(FLAGS_server_host), absl::GetFlag(FLAGS_soak_iterations),
329       absl::GetFlag(FLAGS_soak_max_failures),
330       absl::GetFlag(FLAGS_soak_per_iteration_max_acceptable_latency_ms),
331       absl::GetFlag(FLAGS_soak_min_time_ms_between_rpcs),
332       absl::GetFlag(FLAGS_soak_overall_timeout_seconds),
333       absl::GetFlag(FLAGS_soak_request_size),
334       absl::GetFlag(FLAGS_soak_response_size));
335   actions["long_lived_channel"] =
336       std::bind(&grpc::testing::InteropClient::DoLongLivedChannelTest, &client,
337                 absl::GetFlag(FLAGS_soak_iterations),
338                 absl::GetFlag(FLAGS_iteration_interval));
339 
340   UpdateActions(&actions);
341 
342   if (absl::GetFlag(FLAGS_test_case) == "all") {
343     for (const auto& action : actions) {
344       action.second();
345     }
346   } else if (actions.find(absl::GetFlag(FLAGS_test_case)) != actions.end()) {
347     actions.find(absl::GetFlag(FLAGS_test_case))->second();
348   } else {
349     std::string test_cases;
350     for (const auto& action : actions) {
351       if (!test_cases.empty()) test_cases += "\n";
352       test_cases += action.first;
353     }
354     gpr_log(GPR_ERROR, "Unsupported test case %s. Valid options are\n%s",
355             absl::GetFlag(FLAGS_test_case).c_str(), test_cases.c_str());
356     ret = 1;
357   }
358 
359   return ret;
360 }
361