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 "test/cpp/util/proto_file_parser.h"
20
21 #include <algorithm>
22 #include <iostream>
23 #include <sstream>
24 #include <unordered_set>
25
26 #include <grpcpp/support/config.h>
27
28 namespace grpc {
29 namespace testing {
30 namespace {
31
32 // Match the user input method string to the full_name from method descriptor.
MethodNameMatch(const std::string & full_name,const std::string & input)33 bool MethodNameMatch(const std::string& full_name, const std::string& input) {
34 std::string clean_input = input;
35 std::replace(clean_input.begin(), clean_input.end(), '/', '.');
36 if (clean_input.size() > full_name.size()) {
37 return false;
38 }
39 return full_name.compare(full_name.size() - clean_input.size(),
40 clean_input.size(), clean_input) == 0;
41 }
42 } // namespace
43
44 class ErrorPrinter : public protobuf::compiler::MultiFileErrorCollector {
45 public:
ErrorPrinter(ProtoFileParser * parser)46 explicit ErrorPrinter(ProtoFileParser* parser) : parser_(parser) {}
47
AddError(const std::string & filename,int line,int column,const std::string & message)48 void AddError(const std::string& filename, int line, int column,
49 const std::string& message) override {
50 std::ostringstream oss;
51 oss << "error " << filename << " " << line << " " << column << " "
52 << message << "\n";
53 parser_->LogError(oss.str());
54 }
55
AddWarning(const std::string & filename,int line,int column,const std::string & message)56 void AddWarning(const std::string& filename, int line, int column,
57 const std::string& message) override {
58 std::cerr << "warning " << filename << " " << line << " " << column << " "
59 << message << std::endl;
60 }
61
62 private:
63 ProtoFileParser* parser_; // not owned
64 };
65
ProtoFileParser(const std::shared_ptr<grpc::Channel> & channel,const std::string & proto_path,const std::string & protofiles)66 ProtoFileParser::ProtoFileParser(const std::shared_ptr<grpc::Channel>& channel,
67 const std::string& proto_path,
68 const std::string& protofiles)
69 : has_error_(false),
70 dynamic_factory_(new protobuf::DynamicMessageFactory()) {
71 std::vector<std::string> service_list;
72 if (channel) {
73 reflection_db_.reset(new grpc::ProtoReflectionDescriptorDatabase(channel));
74 reflection_db_->GetServices(&service_list);
75 }
76
77 std::unordered_set<std::string> known_services;
78 if (!protofiles.empty()) {
79 source_tree_.MapPath("", proto_path);
80 error_printer_.reset(new ErrorPrinter(this));
81 importer_.reset(
82 new protobuf::compiler::Importer(&source_tree_, error_printer_.get()));
83
84 std::string file_name;
85 std::stringstream ss(protofiles);
86 while (std::getline(ss, file_name, ',')) {
87 const auto* file_desc = importer_->Import(file_name);
88 if (file_desc) {
89 for (int i = 0; i < file_desc->service_count(); i++) {
90 service_desc_list_.push_back(file_desc->service(i));
91 known_services.insert(file_desc->service(i)->full_name());
92 }
93 } else {
94 std::cerr << file_name << " not found" << std::endl;
95 }
96 }
97
98 file_db_.reset(new protobuf::DescriptorPoolDatabase(*importer_->pool()));
99 }
100
101 if (!reflection_db_ && !file_db_) {
102 LogError("No available proto database");
103 return;
104 }
105
106 if (!reflection_db_) {
107 desc_db_ = std::move(file_db_);
108 } else if (!file_db_) {
109 desc_db_ = std::move(reflection_db_);
110 } else {
111 desc_db_.reset(new protobuf::MergedDescriptorDatabase(reflection_db_.get(),
112 file_db_.get()));
113 }
114
115 desc_pool_.reset(new protobuf::DescriptorPool(desc_db_.get()));
116
117 for (auto it = service_list.begin(); it != service_list.end(); it++) {
118 if (known_services.find(*it) == known_services.end()) {
119 if (const protobuf::ServiceDescriptor* service_desc =
120 desc_pool_->FindServiceByName(*it)) {
121 service_desc_list_.push_back(service_desc);
122 known_services.insert(*it);
123 }
124 }
125 }
126 }
127
~ProtoFileParser()128 ProtoFileParser::~ProtoFileParser() {}
129
GetFullMethodName(const std::string & method)130 std::string ProtoFileParser::GetFullMethodName(const std::string& method) {
131 has_error_ = false;
132
133 if (known_methods_.find(method) != known_methods_.end()) {
134 return known_methods_[method];
135 }
136
137 const protobuf::MethodDescriptor* method_descriptor = nullptr;
138 for (auto it = service_desc_list_.begin(); it != service_desc_list_.end();
139 it++) {
140 const auto* service_desc = *it;
141 for (int j = 0; j < service_desc->method_count(); j++) {
142 const auto* method_desc = service_desc->method(j);
143 if (MethodNameMatch(method_desc->full_name(), method)) {
144 if (method_descriptor) {
145 std::ostringstream error_stream;
146 error_stream << "Ambiguous method names: ";
147 error_stream << method_descriptor->full_name() << " ";
148 error_stream << method_desc->full_name();
149 LogError(error_stream.str());
150 }
151 method_descriptor = method_desc;
152 }
153 }
154 }
155 if (!method_descriptor) {
156 LogError("Method name not found");
157 }
158 if (has_error_) {
159 return "";
160 }
161
162 known_methods_[method] = method_descriptor->full_name();
163
164 return method_descriptor->full_name();
165 }
166
GetFormattedMethodName(const std::string & method)167 std::string ProtoFileParser::GetFormattedMethodName(const std::string& method) {
168 has_error_ = false;
169 std::string formatted_method_name = GetFullMethodName(method);
170 if (has_error_) {
171 return "";
172 }
173 size_t last_dot = formatted_method_name.find_last_of('.');
174 if (last_dot != std::string::npos) {
175 formatted_method_name[last_dot] = '/';
176 }
177 formatted_method_name.insert(formatted_method_name.begin(), '/');
178 return formatted_method_name;
179 }
180
GetMessageTypeFromMethod(const std::string & method,bool is_request)181 std::string ProtoFileParser::GetMessageTypeFromMethod(const std::string& method,
182 bool is_request) {
183 has_error_ = false;
184 std::string full_method_name = GetFullMethodName(method);
185 if (has_error_) {
186 return "";
187 }
188 const protobuf::MethodDescriptor* method_desc =
189 desc_pool_->FindMethodByName(full_method_name);
190 if (!method_desc) {
191 LogError("Method not found");
192 return "";
193 }
194
195 return is_request ? method_desc->input_type()->full_name()
196 : method_desc->output_type()->full_name();
197 }
198
IsStreaming(const std::string & method,bool is_request)199 bool ProtoFileParser::IsStreaming(const std::string& method, bool is_request) {
200 has_error_ = false;
201
202 std::string full_method_name = GetFullMethodName(method);
203 if (has_error_) {
204 return false;
205 }
206
207 const protobuf::MethodDescriptor* method_desc =
208 desc_pool_->FindMethodByName(full_method_name);
209 if (!method_desc) {
210 LogError("Method not found");
211 return false;
212 }
213
214 return is_request ? method_desc->client_streaming()
215 : method_desc->server_streaming();
216 }
217
GetSerializedProtoFromMethod(const std::string & method,const std::string & formatted_proto,bool is_request,bool is_json_format)218 std::string ProtoFileParser::GetSerializedProtoFromMethod(
219 const std::string& method, const std::string& formatted_proto,
220 bool is_request, bool is_json_format) {
221 has_error_ = false;
222 std::string message_type_name = GetMessageTypeFromMethod(method, is_request);
223 if (has_error_) {
224 return "";
225 }
226 return GetSerializedProtoFromMessageType(message_type_name, formatted_proto,
227 is_json_format);
228 }
229
GetFormattedStringFromMethod(const std::string & method,const std::string & serialized_proto,bool is_request,bool is_json_format)230 std::string ProtoFileParser::GetFormattedStringFromMethod(
231 const std::string& method, const std::string& serialized_proto,
232 bool is_request, bool is_json_format) {
233 has_error_ = false;
234 std::string message_type_name = GetMessageTypeFromMethod(method, is_request);
235 if (has_error_) {
236 return "";
237 }
238 return GetFormattedStringFromMessageType(message_type_name, serialized_proto,
239 is_json_format);
240 }
241
GetSerializedProtoFromMessageType(const std::string & message_type_name,const std::string & formatted_proto,bool is_json_format)242 std::string ProtoFileParser::GetSerializedProtoFromMessageType(
243 const std::string& message_type_name, const std::string& formatted_proto,
244 bool is_json_format) {
245 has_error_ = false;
246 std::string serialized;
247 const protobuf::Descriptor* desc =
248 desc_pool_->FindMessageTypeByName(message_type_name);
249 if (!desc) {
250 LogError("Message type not found");
251 return "";
252 }
253 std::unique_ptr<grpc::protobuf::Message> msg(
254 dynamic_factory_->GetPrototype(desc)->New());
255
256 bool ok;
257 if (is_json_format) {
258 ok = grpc::protobuf::json::JsonStringToMessage(formatted_proto, msg.get())
259 .ok();
260 if (!ok) {
261 LogError("Failed to convert json format to proto.");
262 return "";
263 }
264 } else {
265 ok = protobuf::TextFormat::ParseFromString(formatted_proto, msg.get());
266 if (!ok) {
267 LogError("Failed to convert text format to proto.");
268 return "";
269 }
270 }
271
272 ok = msg->SerializeToString(&serialized);
273 if (!ok) {
274 LogError("Failed to serialize proto.");
275 return "";
276 }
277 return serialized;
278 }
279
GetFormattedStringFromMessageType(const std::string & message_type_name,const std::string & serialized_proto,bool is_json_format)280 std::string ProtoFileParser::GetFormattedStringFromMessageType(
281 const std::string& message_type_name, const std::string& serialized_proto,
282 bool is_json_format) {
283 has_error_ = false;
284 const protobuf::Descriptor* desc =
285 desc_pool_->FindMessageTypeByName(message_type_name);
286 if (!desc) {
287 LogError("Message type not found");
288 return "";
289 }
290 std::unique_ptr<grpc::protobuf::Message> msg(
291 dynamic_factory_->GetPrototype(desc)->New());
292 if (!msg->ParseFromString(serialized_proto)) {
293 LogError("Failed to deserialize proto.");
294 return "";
295 }
296 std::string formatted_string;
297
298 if (is_json_format) {
299 grpc::protobuf::json::JsonPrintOptions jsonPrintOptions;
300 jsonPrintOptions.add_whitespace = true;
301 if (!grpc::protobuf::json::MessageToJsonString(
302 *msg.get(), &formatted_string, jsonPrintOptions)
303 .ok()) {
304 LogError("Failed to print proto message to json format");
305 return "";
306 }
307 } else {
308 if (!protobuf::TextFormat::PrintToString(*msg.get(), &formatted_string)) {
309 LogError("Failed to print proto message to text format");
310 return "";
311 }
312 }
313 return formatted_string;
314 }
315
LogError(const std::string & error_msg)316 void ProtoFileParser::LogError(const std::string& error_msg) {
317 if (!error_msg.empty()) {
318 std::cerr << error_msg << std::endl;
319 }
320 has_error_ = true;
321 }
322
323 } // namespace testing
324 } // namespace grpc
325