Debian Codegraph @

test/cpp/util/grpc_tool.cc

raw
1 /*
2 *
3 * Copyright 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 <grpc/support/port_platform.h>
20
21 #include "test/cpp/util/grpc_tool.h"
22
23 #include <cstdio>
24 #include <fstream>
25 #include <iostream>
26 #include <memory>
27 #include <sstream>
28 #include <string>
29 #include <thread>
30
31 #include "absl/flags/flag.h"
32 #include "absl/memory/memory.h"
33
34 #include <grpc/grpc.h>
35 #include <grpcpp/channel.h>
36 #include <grpcpp/create_channel.h>
37 #include <grpcpp/grpcpp.h>
38 #include <grpcpp/security/credentials.h>
39 #include <grpcpp/support/string_ref.h>
40
41 #include "test/cpp/util/cli_call.h"
42 #include "test/cpp/util/proto_file_parser.h"
43 #include "test/cpp/util/proto_reflection_descriptor_database.h"
44 #include "test/cpp/util/service_describer.h"
45
46 #if GPR_WINDOWS
47 #include <io.h>
48 #else
49 #include <unistd.h>
50 #endif
51
52 ABSL_FLAG(bool, l, false, "Use a long listing format");
53 ABSL_FLAG(bool, remotedb, true,
54 "Use server types to parse and format messages");
55 ABSL_FLAG(std::string, metadata, "",
56 "Metadata to send to server, in the form of key1:val1:key2:val2");
57 ABSL_FLAG(std::string, proto_path, ".",
58 "Path to look for the proto file. "
59 "Multiple paths can be separated by " GRPC_CLI_PATH_SEPARATOR);
60 ABSL_FLAG(std::string, protofiles, "", "Name of the proto file.");
61 ABSL_FLAG(bool, binary_input, false, "Input in binary format");
62 ABSL_FLAG(bool, binary_output, false, "Output in binary format");
63 ABSL_FLAG(std::string, default_service_config, "",
64 "Default service config to use on the channel, if non-empty. Note "
65 "that this will be ignored if the name resolver returns a service "
66 "config.");
67 ABSL_FLAG(bool, display_peer_address, false,
68 "Log the peer socket address of the connection that each RPC is made "
69 "on to stderr.");
70 ABSL_FLAG(bool, json_input, false, "Input in json format");
71 ABSL_FLAG(bool, json_output, false, "Output in json format");
72 ABSL_FLAG(std::string, infile, "", "Input file (default is stdin)");
73 ABSL_FLAG(bool, batch, false,
74 "Input contains multiple requests. Please do not use this to send "
75 "more than a few RPCs. gRPC CLI has very different performance "
76 "characteristics compared with normal RPC calls which make it "
77 "unsuitable for loadtesting or significant production traffic.");
78 // TODO(Capstan): Consider using absl::Duration
79 ABSL_FLAG(double, timeout, -1,
80 "Specify timeout in seconds, used to set the deadline for all "
81 "RPCs. The default value of -1 means no deadline has been set.");
82 ABSL_FLAG(
83 int, max_recv_msg_size, 0,
84 "Specify the max receive message size in bytes for all RPCs. -1 indicates "
85 "unlimited. The default value of 0 means to use the gRPC default.");
86
87 namespace grpc {
88 namespace testing {
89 namespace {
90
91 class GrpcTool {
92 public:
93 explicit GrpcTool();
94 virtual ~GrpcTool() {}
95
96 bool Help(int argc, const char** argv, const CliCredentials& cred,
97 const GrpcToolOutputCallback& callback);
98 bool CallMethod(int argc, const char** argv, const CliCredentials& cred,
99 const GrpcToolOutputCallback& callback);
100 bool ListServices(int argc, const char** argv, const CliCredentials& cred,
101 const GrpcToolOutputCallback& callback);
102 bool PrintType(int argc, const char** argv, const CliCredentials& cred,
103 const GrpcToolOutputCallback& callback);
104 // TODO(zyc): implement the following methods
105 // bool ListServices(int argc, const char** argv, GrpcToolOutputCallback
106 // callback);
107 // bool PrintTypeId(int argc, const char** argv, GrpcToolOutputCallback
108 // callback);
109 bool ParseMessage(int argc, const char** argv, const CliCredentials& cred,
110 const GrpcToolOutputCallback& callback);
111 bool ToText(int argc, const char** argv, const CliCredentials& cred,
112 const GrpcToolOutputCallback& callback);
113 bool ToJson(int argc, const char** argv, const CliCredentials& cred,
114 const GrpcToolOutputCallback& callback);
115 bool ToBinary(int argc, const char** argv, const CliCredentials& cred,
116 const GrpcToolOutputCallback& callback);
117
118 void SetPrintCommandMode(int exit_status) {
119 print_command_usage_ = true;
120 usage_exit_status_ = exit_status;
121 }
122
123 private:
124 void CommandUsage(const std::string& usage) const;
125 bool print_command_usage_;
126 int usage_exit_status_;
127 const std::string cred_usage_;
128 };
129
130 template <typename T>
131 std::function<bool(GrpcTool*, int, const char**, const CliCredentials&,
132 GrpcToolOutputCallback)>
133 BindWith5Args(T&& func) {
134 return std::bind(std::forward<T>(func), std::placeholders::_1,
135 std::placeholders::_2, std::placeholders::_3,
136 std::placeholders::_4, std::placeholders::_5);
137 }
138
139 template <typename T>
140 size_t ArraySize(T& a) {
141 return ((sizeof(a) / sizeof(*(a))) /
142 static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))));
143 }
144
145 void ParseMetadataFlag(
146 std::multimap<std::string, std::string>* client_metadata) {
147 if (absl::GetFlag(FLAGS_metadata).empty()) {
148 return;
149 }
150 std::vector<std::string> fields;
151 const char delim = ':';
152 const char escape = '\\';
153 size_t cur = -1;
154 std::stringstream ss;
155 while (++cur < absl::GetFlag(FLAGS_metadata).length()) {
156 switch (absl::GetFlag(FLAGS_metadata).at(cur)) {
157 case escape:
158 if (cur < absl::GetFlag(FLAGS_metadata).length() - 1) {
159 char c = absl::GetFlag(FLAGS_metadata).at(++cur);
160 if (c == delim || c == escape) {
161 ss << c;
162 continue;
163 }
164 }
165 fprintf(stderr, "Failed to parse metadata flag.\n");
166 exit(1);
167 case delim:
168 fields.push_back(ss.str());
169 ss.str("");
170 ss.clear();
171 break;
172 default:
173 ss << absl::GetFlag(FLAGS_metadata).at(cur);
174 }
175 }
176 fields.push_back(ss.str());
177 if (fields.size() % 2) {
178 fprintf(stderr, "Failed to parse metadata flag.\n");
179 exit(1);
180 }
181 for (size_t i = 0; i < fields.size(); i += 2) {
182 client_metadata->insert(
183 std::pair<std::string, std::string>(fields[i], fields[i + 1]));
184 }
185 }
186
187 template <typename T>
188 void PrintMetadata(const T& m, const std::string& message) {
189 if (m.empty()) {
190 return;
191 }
192 fprintf(stderr, "%s\n", message.c_str());
193 std::string pair;
194 for (typename T::const_iterator iter = m.begin(); iter != m.end(); ++iter) {
195 pair.clear();
196 pair.append(iter->first.data(), iter->first.size());
197 pair.append(" : ");
198 pair.append(iter->second.data(), iter->second.size());
199 fprintf(stderr, "%s\n", pair.c_str());
200 }
201 }
202
203 void ReadResponse(CliCall* call, const std::string& method_name,
204 const GrpcToolOutputCallback& callback,
205 ProtoFileParser* parser, gpr_mu* parser_mu, bool print_mode) {
206 std::string serialized_response_proto;
207 std::multimap<grpc::string_ref, grpc::string_ref> server_initial_metadata;
208
209 for (bool receive_initial_metadata = true; call->ReadAndMaybeNotifyWrite(
210 &serialized_response_proto,
211 receive_initial_metadata ? &server_initial_metadata : nullptr);
212 receive_initial_metadata = false) {
213 fprintf(stderr, "got response.\n");
214 if (!absl::GetFlag(FLAGS_binary_output)) {
215 gpr_mu_lock(parser_mu);
216 serialized_response_proto = parser->GetFormattedStringFromMethod(
217 method_name, serialized_response_proto, false /* is_request */,
218 absl::GetFlag(FLAGS_json_output));
219 if (parser->HasError() && print_mode) {
220 fprintf(stderr, "Failed to parse response.\n");
221 }
222 gpr_mu_unlock(parser_mu);
223 }
224 if (receive_initial_metadata) {
225 PrintMetadata(server_initial_metadata,
226 "Received initial metadata from server:");
227 }
228 if (!callback(serialized_response_proto) && print_mode) {
229 fprintf(stderr, "Failed to output response.\n");
230 }
231 }
232 }
233
234 std::shared_ptr<grpc::Channel> CreateCliChannel(
235 const std::string& server_address, const CliCredentials& cred,
236 const grpc::ChannelArguments& extra_args) {
237 grpc::ChannelArguments args(extra_args);
238 if (!cred.GetSslTargetNameOverride().empty()) {
239 args.SetSslTargetNameOverride(cred.GetSslTargetNameOverride());
240 }
241 if (!absl::GetFlag(FLAGS_default_service_config).empty()) {
242 args.SetString(GRPC_ARG_SERVICE_CONFIG,
243 absl::GetFlag(FLAGS_default_service_config).c_str());
244 }
245 // See |GRPC_ARG_MAX_METADATA_SIZE| in |grpc_types.h|.
246 // Set to large enough size (10M) that should work for most use cases.
247 args.SetInt(GRPC_ARG_MAX_METADATA_SIZE, 10 * 1024 * 1024);
248 return grpc::CreateCustomChannel(server_address, cred.GetCredentials(), args);
249 }
250
251 struct Command {
252 const char* command;
253 std::function<bool(GrpcTool*, int, const char**, const CliCredentials&,
254 GrpcToolOutputCallback)>
255 function;
256 int min_args;
257 int max_args;
258 };
259
260 const Command ops[] = {
261 {"help", BindWith5Args(&GrpcTool::Help), 0, INT_MAX},
262 {"ls", BindWith5Args(&GrpcTool::ListServices), 1, 3},
263 {"list", BindWith5Args(&GrpcTool::ListServices), 1, 3},
264 {"call", BindWith5Args(&GrpcTool::CallMethod), 2, 3},
265 {"type", BindWith5Args(&GrpcTool::PrintType), 2, 2},
266 {"parse", BindWith5Args(&GrpcTool::ParseMessage), 2, 3},
267 {"totext", BindWith5Args(&GrpcTool::ToText), 2, 3},
268 {"tobinary", BindWith5Args(&GrpcTool::ToBinary), 2, 3},
269 {"tojson", BindWith5Args(&GrpcTool::ToJson), 2, 3},
270 };
271
272 void Usage(const std::string& msg) {
273 fprintf(
274 stderr,
275 "%s\n"
276 " grpc_cli ls ... ; List services\n"
277 " grpc_cli call ... ; Call method\n"
278 " grpc_cli type ... ; Print type\n"
279 " grpc_cli parse ... ; Parse message\n"
280 " grpc_cli totext ... ; Convert binary message to text\n"
281 " grpc_cli tojson ... ; Convert binary message to json\n"
282 " grpc_cli tobinary ... ; Convert text message to binary\n"
283 " grpc_cli help ... ; Print this message, or per-command usage\n"
284 "\n",
285 msg.c_str());
286
287 exit(1);
288 }
289
290 const Command* FindCommand(const std::string& name) {
291 for (int i = 0; i < static_cast<int>(ArraySize(ops)); i++) {
292 if (name == ops[i].command) {
293 return &ops[i];
294 }
295 }
296 return nullptr;
297 }
298 } // namespace
299
300 int GrpcToolMainLib(int argc, const char** argv, const CliCredentials& cred,
301 const GrpcToolOutputCallback& callback) {
302 if (argc < 2) {
303 Usage("No command specified");
304 }
305
306 std::string command = argv[1];
307 argc -= 2;
308 argv += 2;
309
310 const Command* cmd = FindCommand(command);
311 if (cmd != nullptr) {
312 GrpcTool grpc_tool;
313 if (argc < cmd->min_args || argc > cmd->max_args) {
314 // Force the command to print its usage message
315 fprintf(stderr, "\nWrong number of arguments for %s\n", command.c_str());
316 grpc_tool.SetPrintCommandMode(1);
317 return cmd->function(&grpc_tool, -1, nullptr, cred, callback);
318 }
319 const bool ok = cmd->function(&grpc_tool, argc, argv, cred, callback);
320 return ok ? 0 : 1;
321 } else {
322 Usage("Invalid command '" + std::string(command.c_str()) + "'");
323 }
324 return 1;
325 }
326
327 GrpcTool::GrpcTool() : print_command_usage_(false), usage_exit_status_(0) {}
328
329 void GrpcTool::CommandUsage(const std::string& usage) const {
330 if (print_command_usage_) {
331 fprintf(stderr, "\n%s%s\n", usage.c_str(),
332 (usage.empty() || usage[usage.size() - 1] != '\n') ? "\n" : "");
333 exit(usage_exit_status_);
334 }
335 }
336
337 bool GrpcTool::Help(int argc, const char** argv, const CliCredentials& cred,
338 const GrpcToolOutputCallback& callback) {
339 CommandUsage(
340 "Print help\n"
341 " grpc_cli help [subcommand]\n");
342
343 if (argc == 0) {
344 Usage("");
345 } else {
346 const Command* cmd = FindCommand(argv[0]);
347 if (cmd == nullptr) {
348 Usage("Unknown command '" + std::string(argv[0]) + "'");
349 }
350 SetPrintCommandMode(0);
351 cmd->function(this, -1, nullptr, cred, callback);
352 }
353 return true;
354 }
355
356 bool GrpcTool::ListServices(int argc, const char** argv,
357 const CliCredentials& cred,
358 const GrpcToolOutputCallback& callback) {
359 CommandUsage(
360 "List services\n"
361 " grpc_cli ls <address> [<service>[/<method>]]\n"
362 " <address> ; host:port\n"
363 " <service> ; Exported service name\n"
364 " <method> ; Method name\n"
365 " --l ; Use a long listing format\n"
366 " --outfile ; Output filename (defaults to stdout)\n" +
367 cred.GetCredentialUsage());
368
369 std::string server_address(argv[0]);
370 std::shared_ptr<grpc::Channel> channel =
371 CreateCliChannel(server_address, cred, grpc::ChannelArguments());
372 grpc::ProtoReflectionDescriptorDatabase desc_db(channel);
373 grpc::protobuf::DescriptorPool desc_pool(&desc_db);
374
375 std::vector<std::string> service_list;
376 if (!desc_db.GetServices(&service_list)) {
377 fprintf(stderr, "Received an error when querying services endpoint.\n");
378 return false;
379 }
380
381 // If no service is specified, dump the list of services.
382 std::string output;
383 if (argc < 2) {
384 // List all services, if --l is passed, then include full description,
385 // otherwise include a summarized list only.
386 if (absl::GetFlag(FLAGS_l)) {
387 output = DescribeServiceList(service_list, desc_pool);
388 } else {
389 for (auto it = service_list.begin(); it != service_list.end(); it++) {
390 auto const& service = *it;
391 output.append(service);
392 output.append("\n");
393 }
394 }
395 } else {
396 std::string service_name;
397 std::string method_name;
398 std::stringstream ss(argv[1]);
399
400 // Remove leading slashes.
401 while (ss.peek() == '/') {
402 ss.get();
403 }
404
405 // Parse service and method names. Support the following patterns:
406 // Service
407 // Service Method
408 // Service.Method
409 // Service/Method
410 if (argc == 3) {
411 std::getline(ss, service_name, '/');
412 method_name = argv[2];
413 } else {
414 if (std::getline(ss, service_name, '/')) {
415 std::getline(ss, method_name);
416 }
417 }
418
419 const grpc::protobuf::ServiceDescriptor* service =
420 desc_pool.FindServiceByName(service_name);
421 if (service != nullptr) {
422 if (method_name.empty()) {
423 output = absl::GetFlag(FLAGS_l) ? DescribeService(service)
424 : SummarizeService(service);
425 } else {
426 method_name.insert(0, 1, '.');
427 method_name.insert(0, service_name);
428 const grpc::protobuf::MethodDescriptor* method =
429 desc_pool.FindMethodByName(method_name);
430 if (method != nullptr) {
431 output = absl::GetFlag(FLAGS_l) ? DescribeMethod(method)
432 : SummarizeMethod(method);
433 } else {
434 fprintf(stderr, "Method %s not found in service %s.\n",
435 method_name.c_str(), service_name.c_str());
436 return false;
437 }
438 }
439 } else {
440 if (!method_name.empty()) {
441 fprintf(stderr, "Service %s not found.\n", service_name.c_str());
442 return false;
443 } else {
444 const grpc::protobuf::MethodDescriptor* method =
445 desc_pool.FindMethodByName(service_name);
446 if (method != nullptr) {
447 output = absl::GetFlag(FLAGS_l) ? DescribeMethod(method)
448 : SummarizeMethod(method);
449 } else {
450 fprintf(stderr, "Service or method %s not found.\n",
451 service_name.c_str());
452 return false;
453 }
454 }
455 }
456 }
457 return callback(output);
458 }
459
460 bool GrpcTool::PrintType(int /*argc*/, const char** argv,
461 const CliCredentials& cred,
462 const GrpcToolOutputCallback& callback) {
463 CommandUsage(
464 "Print type\n"
465 " grpc_cli type <address> <type>\n"
466 " <address> ; host:port\n"
467 " <type> ; Protocol buffer type name\n" +
468 cred.GetCredentialUsage());
469
470 std::string server_address(argv[0]);
471 std::shared_ptr<grpc::Channel> channel =
472 CreateCliChannel(server_address, cred, grpc::ChannelArguments());
473 grpc::ProtoReflectionDescriptorDatabase desc_db(channel);
474 grpc::protobuf::DescriptorPool desc_pool(&desc_db);
475
476 std::string output;
477 const grpc::protobuf::Descriptor* descriptor =
478 desc_pool.FindMessageTypeByName(argv[1]);
479 if (descriptor != nullptr) {
480 output = descriptor->DebugString();
481 } else {
482 fprintf(stderr, "Type %s not found.\n", argv[1]);
483 return false;
484 }
485 return callback(output);
486 }
487
488 bool GrpcTool::CallMethod(int argc, const char** argv,
489 const CliCredentials& cred,
490 const GrpcToolOutputCallback& callback) {
491 CommandUsage(
492 "Call method\n"
493 " grpc_cli call <address> <service>[.<method>] <request>\n"
494 " <address> ; host:port\n"
495 " <service> ; Exported service name\n"
496 " <method> ; Method name\n"
497 " <request> ; Text protobuffer (overrides infile)\n"
498 " --protofiles ; Comma separated proto files used as a"
499 " fallback when parsing request/response\n"
500 " --proto_path ; The search paths of proto files"
501 " (" GRPC_CLI_PATH_SEPARATOR
502 " separated), valid only when --protofiles is given\n"
503 " --noremotedb ; Don't attempt to use reflection service"
504 " at all\n"
505 " --metadata ; The metadata to be sent to the server\n"
506 " --infile ; Input filename (defaults to stdin)\n"
507 " --outfile ; Output filename (defaults to stdout)\n"
508 " --binary_input ; Input in binary format\n"
509 " --binary_output ; Output in binary format\n"
510 " --json_input ; Input in json format\n"
511 " --json_output ; Output in json format\n"
512 " --max_recv_msg_size ; Specify max receive message size in "
513 "bytes. -1 indicates unlimited. The default value of 0 means to use the "
514 "gRPC default.\n"
515 " --timeout ; Specify timeout (in seconds), used to "
516 "set the deadline for RPCs. The default value of -1 means no "
517 "deadline has been set.\n" +
518 cred.GetCredentialUsage());
519
520 std::stringstream output_ss;
521 std::string request_text;
522 std::string server_address(argv[0]);
523 std::string method_name(argv[1]);
524 std::string formatted_method_name;
525 std::unique_ptr<ProtoFileParser> parser;
526 std::string serialized_request_proto;
527 CliArgs cli_args;
528 cli_args.timeout = absl::GetFlag(FLAGS_timeout);
529 bool print_mode = false;
530
531 grpc::ChannelArguments args;
532 if (absl::GetFlag(FLAGS_max_recv_msg_size) != 0) {
533 args.SetMaxReceiveMessageSize(absl::GetFlag(FLAGS_max_recv_msg_size));
534 }
535 std::shared_ptr<grpc::Channel> channel =
536 CreateCliChannel(server_address, cred, args);
537
538 if (!absl::GetFlag(FLAGS_binary_input) ||
539 !absl::GetFlag(FLAGS_binary_output)) {
540 parser = std::make_unique<grpc::testing::ProtoFileParser>(
541 absl::GetFlag(FLAGS_remotedb) ? channel : nullptr,
542 absl::GetFlag(FLAGS_proto_path), absl::GetFlag(FLAGS_protofiles));
543 if (parser->HasError()) {
544 fprintf(
545 stderr,
546 "Failed to find remote reflection service and local proto files.\n");
547 return false;
548 }
549 }
550
551 if (absl::GetFlag(FLAGS_binary_input)) {
552 formatted_method_name = method_name;
553 } else {
554 formatted_method_name = parser->GetFormattedMethodName(method_name);
555 if (parser->HasError()) {
556 fprintf(stderr, "Failed to find method %s in proto files.\n",
557 method_name.c_str());
558 }
559 }
560
561 if (argc == 3) {
562 request_text = argv[2];
563 }
564
565 if (parser != nullptr &&
566 parser->IsStreaming(method_name, true /* is_request */)) {
567 std::istream* input_stream;
568 std::ifstream input_file;
569
570 if (absl::GetFlag(FLAGS_batch)) {
571 fprintf(stderr, "Batch mode for streaming RPC is not supported.\n");
572 return false;
573 }
574
575 std::multimap<std::string, std::string> client_metadata;
576 ParseMetadataFlag(&client_metadata);
577 PrintMetadata(client_metadata, "Sending client initial metadata:");
578
579 CliCall call(channel, formatted_method_name, client_metadata, cli_args);
580 if (absl::GetFlag(FLAGS_display_peer_address)) {
581 fprintf(stderr, "New call for method_name:%s has peer address:|%s|\n",
582 formatted_method_name.c_str(), call.peer().c_str());
583 }
584
585 if (absl::GetFlag(FLAGS_infile).empty()) {
586 if (isatty(fileno(stdin))) {
587 print_mode = true;
588 fprintf(stderr, "reading streaming request message from stdin...\n");
589 }
590 input_stream = &std::cin;
591 } else {
592 input_file.open(absl::GetFlag(FLAGS_infile),
593 std::ios::in | std::ios::binary);
594 if (!input_file) {
595 fprintf(stderr, "Failed to open infile %s.\n",
596 absl::GetFlag(FLAGS_infile).c_str());
597 return false;
598 }
599
600 input_stream = &input_file;
601 }
602
603 gpr_mu parser_mu;
604 gpr_mu_init(&parser_mu);
605 std::thread read_thread(ReadResponse, &call, method_name, callback,
606 parser.get(), &parser_mu, print_mode);
607
608 std::stringstream request_ss;
609 std::string line;
610 while (!request_text.empty() ||
611 (!input_stream->eof() && getline(*input_stream, line))) {
612 if (!request_text.empty()) {
613 if (absl::GetFlag(FLAGS_binary_input)) {
614 serialized_request_proto = request_text;
615 request_text.clear();
616 } else {
617 gpr_mu_lock(&parser_mu);
618 serialized_request_proto = parser->GetSerializedProtoFromMethod(
619 method_name, request_text, true /* is_request */,
620 absl::GetFlag(FLAGS_json_input));
621 request_text.clear();
622 if (parser->HasError()) {
623 if (print_mode) {
624 fprintf(stderr, "Failed to parse request.\n");
625 }
626 gpr_mu_unlock(&parser_mu);
627 continue;
628 }
629 gpr_mu_unlock(&parser_mu);
630 }
631
632 call.WriteAndWait(serialized_request_proto);
633 if (print_mode) {
634 fprintf(stderr, "Request sent.\n");
635 }
636 } else {
637 if (line.length() == 0) {
638 request_text = request_ss.str();
639 request_ss.str(std::string());
640 request_ss.clear();
641 } else {
642 request_ss << line << ' ';
643 }
644 }
645 }
646 if (input_file.is_open()) {
647 input_file.close();
648 }
649
650 call.WritesDoneAndWait();
651 read_thread.join();
652 gpr_mu_destroy(&parser_mu);
653
654 std::multimap<grpc::string_ref, grpc::string_ref> server_trailing_metadata;
655 Status status = call.Finish(&server_trailing_metadata);
656 PrintMetadata(server_trailing_metadata,
657 "Received trailing metadata from server:");
658
659 if (status.ok()) {
660 fprintf(stderr, "Stream RPC succeeded with OK status\n");
661 return true;
662 } else {
663 fprintf(stderr, "Rpc failed with status code %d, error message: %s\n",
664 status.error_code(), status.error_message().c_str());
665 return false;
666 }
667
668 } else { // parser->IsStreaming(method_name, true /* is_request */)
669 if (absl::GetFlag(FLAGS_batch)) {
670 if (parser != nullptr &&
671 parser->IsStreaming(method_name, false /* is_request */)) {
672 fprintf(stderr, "Batch mode for streaming RPC is not supported.\n");
673 return false;
674 }
675
676 std::istream* input_stream;
677 std::ifstream input_file;
678
679 if (absl::GetFlag(FLAGS_infile).empty()) {
680 if (isatty(fileno(stdin))) {
681 print_mode = true;
682 fprintf(stderr, "reading request messages from stdin...\n");
683 }
684 input_stream = &std::cin;
685 } else {
686 input_file.open(absl::GetFlag(FLAGS_infile),
687 std::ios::in | std::ios::binary);
688 input_stream = &input_file;
689 }
690
691 std::multimap<std::string, std::string> client_metadata;
692 ParseMetadataFlag(&client_metadata);
693 if (print_mode) {
694 PrintMetadata(client_metadata, "Sending client initial metadata:");
695 }
696
697 std::stringstream request_ss;
698 std::string line;
699 while (!request_text.empty() ||
700 (!input_stream->eof() && getline(*input_stream, line))) {
701 if (!request_text.empty()) {
702 if (absl::GetFlag(FLAGS_binary_input)) {
703 serialized_request_proto = request_text;
704 request_text.clear();
705 } else {
706 serialized_request_proto = parser->GetSerializedProtoFromMethod(
707 method_name, request_text, true /* is_request */,
708 absl::GetFlag(FLAGS_json_input));
709 request_text.clear();
710 if (parser->HasError()) {
711 if (print_mode) {
712 fprintf(stderr, "Failed to parse request.\n");
713 }
714 continue;
715 }
716 }
717
718 std::string serialized_response_proto;
719 std::multimap<grpc::string_ref, grpc::string_ref>
720 server_initial_metadata, server_trailing_metadata;
721 CliCall call(channel, formatted_method_name, client_metadata,
722 cli_args);
723 if (absl::GetFlag(FLAGS_display_peer_address)) {
724 fprintf(stderr,
725 "New call for method_name:%s has peer address:|%s|\n",
726 formatted_method_name.c_str(), call.peer().c_str());
727 }
728 call.Write(serialized_request_proto);
729 call.WritesDone();
730 if (!call.Read(&serialized_response_proto,
731 &server_initial_metadata)) {
732 fprintf(stderr, "Failed to read response.\n");
733 }
734 Status status = call.Finish(&server_trailing_metadata);
735
736 if (status.ok()) {
737 if (print_mode) {
738 fprintf(stderr, "Rpc succeeded with OK status.\n");
739 PrintMetadata(server_initial_metadata,
740 "Received initial metadata from server:");
741 PrintMetadata(server_trailing_metadata,
742 "Received trailing metadata from server:");
743 }
744
745 if (absl::GetFlag(FLAGS_binary_output)) {
746 if (!callback(serialized_response_proto)) {
747 break;
748 }
749 } else {
750 std::string response_text = parser->GetFormattedStringFromMethod(
751 method_name, serialized_response_proto,
752 false /* is_request */, absl::GetFlag(FLAGS_json_output));
753
754 if (parser->HasError() && print_mode) {
755 fprintf(stderr, "Failed to parse response.\n");
756 } else {
757 if (!callback(response_text)) {
758 break;
759 }
760 }
761 }
762 } else {
763 if (print_mode) {
764 fprintf(stderr,
765 "Rpc failed with status code %d, error message: %s\n",
766 status.error_code(), status.error_message().c_str());
767 }
768 }
769 } else {
770 if (line.length() == 0) {
771 request_text = request_ss.str();
772 request_ss.str(std::string());
773 request_ss.clear();
774 } else {
775 request_ss << line << ' ';
776 }
777 }
778 }
779
780 if (input_file.is_open()) {
781 input_file.close();
782 }
783
784 return true;
785 }
786
787 if (argc == 3) {
788 if (!absl::GetFlag(FLAGS_infile).empty()) {
789 fprintf(stderr, "warning: request given in argv, ignoring --infile\n");
790 }
791 } else {
792 std::stringstream input_stream;
793 if (absl::GetFlag(FLAGS_infile).empty()) {
794 if (isatty(fileno(stdin))) {
795 fprintf(stderr, "reading request message from stdin...\n");
796 }
797 input_stream << std::cin.rdbuf();
798 } else {
799 std::ifstream input_file(absl::GetFlag(FLAGS_infile),
800 std::ios::in | std::ios::binary);
801 input_stream << input_file.rdbuf();
802 input_file.close();
803 }
804 request_text = input_stream.str();
805 }
806
807 if (absl::GetFlag(FLAGS_binary_input)) {
808 serialized_request_proto = request_text;
809 } else {
810 serialized_request_proto = parser->GetSerializedProtoFromMethod(
811 method_name, request_text, true /* is_request */,
812 absl::GetFlag(FLAGS_json_input));
813 if (parser->HasError()) {
814 fprintf(stderr, "Failed to parse request.\n");
815 return false;
816 }
817 }
818 fprintf(stderr, "connecting to %s\n", server_address.c_str());
819
820 std::string serialized_response_proto;
821 std::multimap<std::string, std::string> client_metadata;
822 std::multimap<grpc::string_ref, grpc::string_ref> server_initial_metadata,
823 server_trailing_metadata;
824 ParseMetadataFlag(&client_metadata);
825 PrintMetadata(client_metadata, "Sending client initial metadata:");
826
827 CliCall call(channel, formatted_method_name, client_metadata, cli_args);
828 if (absl::GetFlag(FLAGS_display_peer_address)) {
829 fprintf(stderr, "New call for method_name:%s has peer address:|%s|\n",
830 formatted_method_name.c_str(), call.peer().c_str());
831 }
832 call.Write(serialized_request_proto);
833 call.WritesDone();
834
835 for (bool receive_initial_metadata = true; call.Read(
836 &serialized_response_proto,
837 receive_initial_metadata ? &server_initial_metadata : nullptr);
838 receive_initial_metadata = false) {
839 if (!absl::GetFlag(FLAGS_binary_output)) {
840 serialized_response_proto = parser->GetFormattedStringFromMethod(
841 method_name, serialized_response_proto, false /* is_request */,
842 absl::GetFlag(FLAGS_json_output));
843 if (parser->HasError()) {
844 fprintf(stderr, "Failed to parse response.\n");
845 return false;
846 }
847 }
848
849 if (receive_initial_metadata) {
850 PrintMetadata(server_initial_metadata,
851 "Received initial metadata from server:");
852 }
853 if (!callback(serialized_response_proto)) {
854 return false;
855 }
856 }
857 Status status = call.Finish(&server_trailing_metadata);
858 PrintMetadata(server_trailing_metadata,
859 "Received trailing metadata from server:");
860 if (status.ok()) {
861 fprintf(stderr, "Rpc succeeded with OK status\n");
862 return true;
863 } else {
864 fprintf(stderr, "Rpc failed with status code %d, error message: %s\n",
865 status.error_code(), status.error_message().c_str());
866 return false;
867 }
868 }
869 GPR_UNREACHABLE_CODE(return false);
870 }
871
872 bool GrpcTool::ParseMessage(int argc, const char** argv,
873 const CliCredentials& cred,
874 const GrpcToolOutputCallback& callback) {
875 CommandUsage(
876 "Parse message\n"
877 " grpc_cli parse <address> <type> [<message>]\n"
878 " <address> ; host:port\n"
879 " <type> ; Protocol buffer type name\n"
880 " <message> ; Text protobuffer (overrides --infile)\n"
881 " --protofiles ; Comma separated proto files used as a"
882 " fallback when parsing request/response\n"
883 " --proto_path ; The search paths of proto files"
884 " (" GRPC_CLI_PATH_SEPARATOR
885 " separated), valid only when --protofiles is given\n"
886 " --noremotedb ; Don't attempt to use reflection service"
887 " at all\n"
888 " --infile ; Input filename (defaults to stdin)\n"
889 " --outfile ; Output filename (defaults to stdout)\n"
890 " --binary_input ; Input in binary format\n"
891 " --binary_output ; Output in binary format\n"
892 " --json_input ; Input in json format\n"
893 " --json_output ; Output in json format\n" +
894 cred.GetCredentialUsage());
895
896 std::stringstream output_ss;
897 std::string message_text;
898 std::string server_address(argv[0]);
899 std::string type_name(argv[1]);
900 std::unique_ptr<grpc::testing::ProtoFileParser> parser;
901 std::string serialized_request_proto;
902
903 if (argc == 3) {
904 message_text = argv[2];
905 if (!absl::GetFlag(FLAGS_infile).empty()) {
906 fprintf(stderr, "warning: message given in argv, ignoring --infile.\n");
907 }
908 } else {
909 std::stringstream input_stream;
910 if (absl::GetFlag(FLAGS_infile).empty()) {
911 if (isatty(fileno(stdin))) {
912 fprintf(stderr, "reading request message from stdin...\n");
913 }
914 input_stream << std::cin.rdbuf();
915 } else {
916 std::ifstream input_file(absl::GetFlag(FLAGS_infile),
917 std::ios::in | std::ios::binary);
918 input_stream << input_file.rdbuf();
919 input_file.close();
920 }
921 message_text = input_stream.str();
922 }
923
924 if (!absl::GetFlag(FLAGS_binary_input) ||
925 !absl::GetFlag(FLAGS_binary_output)) {
926 std::shared_ptr<grpc::Channel> channel =
927 CreateCliChannel(server_address, cred, grpc::ChannelArguments());
928 parser = std::make_unique<grpc::testing::ProtoFileParser>(
929 absl::GetFlag(FLAGS_remotedb) ? channel : nullptr,
930 absl::GetFlag(FLAGS_proto_path), absl::GetFlag(FLAGS_protofiles));
931 if (parser->HasError()) {
932 fprintf(
933 stderr,
934 "Failed to find remote reflection service and local proto files.\n");
935 return false;
936 }
937 }
938
939 if (absl::GetFlag(FLAGS_binary_input)) {
940 serialized_request_proto = message_text;
941 } else {
942 serialized_request_proto = parser->GetSerializedProtoFromMessageType(
943 type_name, message_text, absl::GetFlag(FLAGS_json_input));
944 if (parser->HasError()) {
945 fprintf(stderr, "Failed to serialize the message.\n");
946 return false;
947 }
948 }
949
950 if (absl::GetFlag(FLAGS_binary_output)) {
951 output_ss << serialized_request_proto;
952 } else {
953 std::string output_text;
954 output_text = parser->GetFormattedStringFromMessageType(
955 type_name, serialized_request_proto, absl::GetFlag(FLAGS_json_output));
956 if (parser->HasError()) {
957 fprintf(stderr, "Failed to deserialize the message.\n");
958 return false;
959 }
960
961 output_ss << output_text << std::endl;
962 }
963
964 return callback(output_ss.str());
965 }
966
967 bool GrpcTool::ToText(int argc, const char** argv, const CliCredentials& cred,
968 const GrpcToolOutputCallback& callback) {
969 CommandUsage(
970 "Convert binary message to text\n"
971 " grpc_cli totext <protofiles> <type>\n"
972 " <protofiles> ; Comma separated list of proto files\n"
973 " <type> ; Protocol buffer type name\n"
974 " --proto_path ; The search paths of proto files"
975 " (" GRPC_CLI_PATH_SEPARATOR
976 " separated)\n"
977 " --infile ; Input filename (defaults to stdin)\n"
978 " --outfile ; Output filename (defaults to stdout)\n");
979
980 absl::SetFlag(&FLAGS_protofiles, argv[0]);
981 absl::SetFlag(&FLAGS_remotedb, false);
982 absl::SetFlag(&FLAGS_binary_input, true);
983 absl::SetFlag(&FLAGS_binary_output, false);
984 return ParseMessage(argc, argv, cred, callback);
985 }
986
987 bool GrpcTool::ToJson(int argc, const char** argv, const CliCredentials& cred,
988 const GrpcToolOutputCallback& callback) {
989 CommandUsage(
990 "Convert binary message to json\n"
991 " grpc_cli tojson <protofiles> <type>\n"
992 " <protofiles> ; Comma separated list of proto files\n"
993 " <type> ; Protocol buffer type name\n"
994 " --proto_path ; The search paths of proto files"
995 " (" GRPC_CLI_PATH_SEPARATOR
996 " separated)\n"
997 " --infile ; Input filename (defaults to stdin)\n"
998 " --outfile ; Output filename (defaults to stdout)\n");
999
1000 absl::SetFlag(&FLAGS_protofiles, argv[0]);
1001 absl::SetFlag(&FLAGS_remotedb, false);
1002 absl::SetFlag(&FLAGS_binary_input, true);
1003 absl::SetFlag(&FLAGS_binary_output, false);
1004 absl::SetFlag(&FLAGS_json_output, true);
1005 return ParseMessage(argc, argv, cred, callback);
1006 }
1007
1008 bool GrpcTool::ToBinary(int argc, const char** argv, const CliCredentials& cred,
1009 const GrpcToolOutputCallback& callback) {
1010 CommandUsage(
1011 "Convert text message to binary\n"
1012 " grpc_cli tobinary <protofiles> <type> [<message>]\n"
1013 " <protofiles> ; Comma separated list of proto files\n"
1014 " <type> ; Protocol buffer type name\n"
1015 " --proto_path ; The search paths of proto files"
1016 " (" GRPC_CLI_PATH_SEPARATOR
1017 " separated)\n"
1018 " --infile ; Input filename (defaults to stdin)\n"
1019 " --outfile ; Output filename (defaults to stdout)\n");
1020
1021 absl::SetFlag(&FLAGS_protofiles, argv[0]);
1022 absl::SetFlag(&FLAGS_remotedb, false);
1023 absl::SetFlag(&FLAGS_binary_input, false);
1024 absl::SetFlag(&FLAGS_binary_output, true);
1025 return ParseMessage(argc, argv, cred, callback);
1026 }
1027
1028 } // namespace testing
1029 } // namespace grpc