/
http_rest_api_handler.cc
363 lines (317 loc) · 14.2 KB
/
http_rest_api_handler.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/* Copyright 2018 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_serving/model_servers/http_rest_api_handler.h"
#include <string>
#include "google/protobuf/any.pb.h"
#include "google/protobuf/arena.h"
#include "google/protobuf/util/json_util.h"
#include "absl/strings/escaping.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_replace.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "tensorflow/cc/saved_model/loader.h"
#include "tensorflow/cc/saved_model/signature_constants.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/threadpool_options.h"
#include "tensorflow_serving/apis/model.pb.h"
#include "tensorflow_serving/apis/predict.pb.h"
#include "tensorflow_serving/core/servable_handle.h"
#include "tensorflow_serving/model_servers/get_model_status_impl.h"
#include "tensorflow_serving/model_servers/server_core.h"
#include "tensorflow_serving/servables/tensorflow/classification_service.h"
#include "tensorflow_serving/servables/tensorflow/get_model_metadata_impl.h"
#include "tensorflow_serving/servables/tensorflow/predict_impl.h"
#include "tensorflow_serving/servables/tensorflow/regression_service.h"
#include "tensorflow_serving/util/json_tensor.h"
namespace tensorflow {
namespace serving {
using protobuf::util::JsonPrintOptions;
using protobuf::util::MessageToJsonString;
using tensorflow::serving::ServerCore;
using tensorflow::serving::TensorflowPredictor;
const char* const HttpRestApiHandler::kPathRegex = "(?i)/v1/.*";
HttpRestApiHandler::HttpRestApiHandler(const RunOptions& run_options,
ServerCore* core)
: run_options_(run_options),
core_(core),
predictor_(new TensorflowPredictor()),
prediction_api_regex_(
R"((?i)/v1/models/([^/:]+)(?:(?:/versions/(\d+))|(?:/labels/(\w+)))?:(classify|regress|predict))"),
modelstatus_api_regex_(
R"((?i)/v1/models(?:/([^/:]+))?(?:(?:/versions/(\d+))|(?:/labels/(\w+)))?(?:\/(metadata))?)") {
}
HttpRestApiHandler::~HttpRestApiHandler() {}
namespace {
void AddHeaders(std::vector<std::pair<string, string>>* headers) {
headers->push_back({"Content-Type", "application/json"});
}
Status FillModelSpecWithNameVersionAndLabel(
const absl::string_view model_name,
const absl::optional<int64>& model_version,
const absl::optional<absl::string_view> model_version_label,
::tensorflow::serving::ModelSpec* model_spec) {
model_spec->set_name(string(model_name));
if (model_version.has_value() && model_version_label.has_value()) {
return errors::InvalidArgument(
"Both model version (", model_version.value(),
") and model version label (", model_version_label.value(),
") cannot be supplied.");
}
if (model_version.has_value()) {
model_spec->mutable_version()->set_value(model_version.value());
}
if (model_version_label.has_value()) {
model_spec->set_version_label(string(model_version_label.value()));
}
return Status::OK();
}
} // namespace
Status HttpRestApiHandler::ProcessRequest(
const absl::string_view http_method, const absl::string_view request_path,
const absl::string_view request_body,
std::vector<std::pair<string, string>>* headers, string* output) {
headers->clear();
output->clear();
AddHeaders(headers);
string model_name;
string model_version_str;
string model_version_label_str;
string method;
string model_subresource;
Status status = errors::InvalidArgument("Malformed request: ", http_method,
" ", request_path);
// Parse request parameters
bool parse_successful = false;
if (http_method == "POST") {
parse_successful =
RE2::FullMatch(string(request_path), prediction_api_regex_, &model_name,
&model_version_str, &model_version_label_str, &method);
} else if (http_method == "GET") {
parse_successful = RE2::FullMatch(
string(request_path), modelstatus_api_regex_, &model_name,
&model_version_str, &model_version_label_str, &model_subresource);
}
absl::optional<int64> model_version;
absl::optional<absl::string_view> model_version_label;
if (!model_version_str.empty()) {
int64 version;
if (!absl::SimpleAtoi(model_version_str, &version)) {
return errors::InvalidArgument(
"Failed to convert version: ", model_version_str, " to numeric.");
}
model_version = version;
}
if (!model_version_label_str.empty()) {
model_version_label = model_version_label_str;
}
// Dispatch request to appropriate processor
if (http_method == "POST" && parse_successful) {
if (method == "classify") {
status = ProcessClassifyRequest(
model_name, model_version, model_version_label, request_body, output);
} else if (method == "regress") {
status = ProcessRegressRequest(model_name, model_version,
model_version_label, request_body, output);
} else if (method == "predict") {
status = ProcessPredictRequest(model_name, model_version,
model_version_label, request_body, output);
}
} else if (http_method == "GET" && parse_successful) {
if (!model_subresource.empty() && model_subresource == "metadata") {
status = ProcessModelMetadataRequest(model_name, model_version,
model_version_label, output);
} else {
status = ProcessModelStatusRequest(model_name, model_version,
model_version_label, output);
}
}
MakeJsonFromStatus(status, output);
return status;
}
Status HttpRestApiHandler::ProcessClassifyRequest(
const absl::string_view model_name,
const absl::optional<int64>& model_version,
const absl::optional<absl::string_view>& model_version_label,
const absl::string_view request_body, string* output) {
::google::protobuf::Arena arena;
auto* request = ::google::protobuf::Arena::CreateMessage<ClassificationRequest>(&arena);
TF_RETURN_IF_ERROR(FillModelSpecWithNameVersionAndLabel(
model_name, model_version, model_version_label,
request->mutable_model_spec()));
TF_RETURN_IF_ERROR(FillClassificationRequestFromJson(request_body, request));
auto* response =
::google::protobuf::Arena::CreateMessage<ClassificationResponse>(&arena);
TF_RETURN_IF_ERROR(TensorflowClassificationServiceImpl::Classify(
run_options_, core_, thread::ThreadPoolOptions(), *request, response));
TF_RETURN_IF_ERROR(
MakeJsonFromClassificationResult(response->result(), output));
return Status::OK();
}
Status HttpRestApiHandler::ProcessRegressRequest(
const absl::string_view model_name,
const absl::optional<int64>& model_version,
const absl::optional<absl::string_view>& model_version_label,
const absl::string_view request_body, string* output) {
::google::protobuf::Arena arena;
auto* request = ::google::protobuf::Arena::CreateMessage<RegressionRequest>(&arena);
TF_RETURN_IF_ERROR(FillModelSpecWithNameVersionAndLabel(
model_name, model_version, model_version_label,
request->mutable_model_spec()));
TF_RETURN_IF_ERROR(FillRegressionRequestFromJson(request_body, request));
auto* response = ::google::protobuf::Arena::CreateMessage<RegressionResponse>(&arena);
TF_RETURN_IF_ERROR(TensorflowRegressionServiceImpl::Regress(
run_options_, core_, thread::ThreadPoolOptions(), *request, response));
TF_RETURN_IF_ERROR(MakeJsonFromRegressionResult(response->result(), output));
return Status::OK();
}
Status HttpRestApiHandler::ProcessPredictRequest(
const absl::string_view model_name,
const absl::optional<int64>& model_version,
const absl::optional<absl::string_view>& model_version_label,
const absl::string_view request_body, string* output) {
::google::protobuf::Arena arena;
auto* request = ::google::protobuf::Arena::CreateMessage<PredictRequest>(&arena);
TF_RETURN_IF_ERROR(FillModelSpecWithNameVersionAndLabel(
model_name, model_version, model_version_label,
request->mutable_model_spec()));
JsonPredictRequestFormat format;
TF_RETURN_IF_ERROR(FillPredictRequestFromJson(
request_body,
[this, request](const string& sig,
::google::protobuf::Map<string, TensorInfo>* map) {
return this->GetInfoMap(request->model_spec(), sig, map);
},
request, &format));
auto* response = ::google::protobuf::Arena::CreateMessage<PredictResponse>(&arena);
TF_RETURN_IF_ERROR(
predictor_->Predict(run_options_, core_, *request, response));
TF_RETURN_IF_ERROR(MakeJsonFromTensors(response->outputs(), format, output));
return Status::OK();
}
Status HttpRestApiHandler::ProcessModelStatusRequest(
const absl::string_view model_name,
const absl::optional<int64>& model_version,
const absl::optional<absl::string_view>& model_version_label,
string* output) {
// We do not yet support returning status of all models
// to be in-sync with the gRPC GetModelStatus API.
if (model_name.empty()) {
return errors::InvalidArgument("Missing model name in request.");
}
::google::protobuf::Arena arena;
auto* request = ::google::protobuf::Arena::CreateMessage<GetModelStatusRequest>(&arena);
TF_RETURN_IF_ERROR(FillModelSpecWithNameVersionAndLabel(
model_name, model_version, model_version_label,
request->mutable_model_spec()));
auto* response =
::google::protobuf::Arena::CreateMessage<GetModelStatusResponse>(&arena);
TF_RETURN_IF_ERROR(
GetModelStatusImpl::GetModelStatus(core_, *request, response));
JsonPrintOptions opts;
opts.add_whitespace = true;
opts.always_print_primitive_fields = true;
// Note this is protobuf::util::Status (not TF Status) object.
const auto& status = MessageToJsonString(*response, output, opts);
if (!status.ok()) {
return errors::Internal("Failed to convert proto to json. Error: ",
status.ToString());
}
return Status::OK();
}
Status HttpRestApiHandler::ProcessModelMetadataRequest(
const absl::string_view model_name,
const absl::optional<int64>& model_version,
const absl::optional<absl::string_view>& model_version_label,
string* output) {
if (model_name.empty()) {
return errors::InvalidArgument("Missing model name in request.");
}
::google::protobuf::Arena arena;
auto* request =
::google::protobuf::Arena::CreateMessage<GetModelMetadataRequest>(&arena);
// We currently only support the kSignatureDef metadata field
request->add_metadata_field(GetModelMetadataImpl::kSignatureDef);
TF_RETURN_IF_ERROR(FillModelSpecWithNameVersionAndLabel(
model_name, model_version, model_version_label,
request->mutable_model_spec()));
auto* response =
::google::protobuf::Arena::CreateMessage<GetModelMetadataResponse>(&arena);
TF_RETURN_IF_ERROR(
GetModelMetadataImpl::GetModelMetadata(core_, *request, response));
JsonPrintOptions opts;
opts.add_whitespace = true;
opts.always_print_primitive_fields = true;
// TODO(b/118381513): preserving proto field names on 'Any' fields has been
// fixed in the master branch of OSS protobuf but the TF ecosystem is
// currently using v3.6.0 where the fix is not present. To resolve the issue
// we invoke MessageToJsonString on invididual fields and concatenate the
// resulting strings and make it valid JSON that conforms with the response we
// expect.
opts.preserve_proto_field_names = true;
string model_spec_output;
const auto& status1 =
MessageToJsonString(response->model_spec(), &model_spec_output, opts);
if (!status1.ok()) {
return errors::Internal(
"Failed to convert model spec proto to json. Error: ",
status1.ToString());
}
tensorflow::serving::SignatureDefMap signature_def_map;
if (response->metadata().end() ==
response->metadata().find(GetModelMetadataImpl::kSignatureDef)) {
return errors::Internal(
"Failed to find 'signature_def' key in the GetModelMetadataResponse "
"metadata map.");
}
bool unpack_status = response->metadata()
.at(GetModelMetadataImpl::kSignatureDef)
.UnpackTo(&signature_def_map);
if (!unpack_status) {
return errors::Internal(
"Failed to unpack 'Any' object to 'SignatureDefMap'.");
}
string signature_def_output;
const auto& status2 =
MessageToJsonString(signature_def_map, &signature_def_output, opts);
if (!status2.ok()) {
return errors::Internal(
"Failed to convert signature def proto to json. Error: ",
status2.ToString());
}
// Concatenate the resulting strings into a valid JSON format.
absl::StrAppend(output, "{\n");
absl::StrAppend(output, "\"model_spec\":", model_spec_output, ",\n");
absl::StrAppend(output, "\"metadata\": {");
absl::StrAppend(output, "\"signature_def\": ", signature_def_output, "}\n");
absl::StrAppend(output, "}\n");
return Status::OK();
}
Status HttpRestApiHandler::GetInfoMap(
const ModelSpec& model_spec, const string& signature_name,
::google::protobuf::Map<string, tensorflow::TensorInfo>* infomap) {
ServableHandle<SavedModelBundle> bundle;
TF_RETURN_IF_ERROR(core_->GetServableHandle(model_spec, &bundle));
const string& signame =
signature_name.empty() ? kDefaultServingSignatureDefKey : signature_name;
auto iter = bundle->meta_graph_def.signature_def().find(signame);
if (iter == bundle->meta_graph_def.signature_def().end()) {
return errors::InvalidArgument("Serving signature name: \"", signame,
"\" not found in signature def");
}
*infomap = iter->second.inputs();
return Status::OK();
}
} // namespace serving
} // namespace tensorflow