You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

http_process.cc 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. /**
  2. * Copyright 2020 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <map>
  17. #include <vector>
  18. #include <string>
  19. #include <nlohmann/json.hpp>
  20. #include "serving/ms_service.pb.h"
  21. #include "util/status.h"
  22. #include "core/session.h"
  23. #include "core/http_process.h"
  24. using ms_serving::MSService;
  25. using ms_serving::PredictReply;
  26. using ms_serving::PredictRequest;
  27. using nlohmann::json;
  28. namespace mindspore {
  29. namespace serving {
  30. const int BUF_MAX = 0x1FFFFF;
  31. static constexpr char HTTP_DATA[] = "data";
  32. static constexpr char HTTP_TENSOR[] = "tensor";
  33. enum HTTP_TYPE { TYPE_DATA = 0, TYPE_TENSOR };
  34. enum HTTP_DATA_TYPE { HTTP_DATA_NONE, HTTP_DATA_INT, HTTP_DATA_FLOAT };
  35. static const std::map<HTTP_DATA_TYPE, ms_serving::DataType> http_to_infer_map{
  36. {HTTP_DATA_NONE, ms_serving::MS_UNKNOWN},
  37. {HTTP_DATA_INT, ms_serving::MS_INT32},
  38. {HTTP_DATA_FLOAT, ms_serving::MS_FLOAT32}};
  39. Status GetPostMessage(struct evhttp_request *req, std::string *buf) {
  40. Status status(SUCCESS);
  41. size_t post_size = evbuffer_get_length(req->input_buffer);
  42. if (post_size == 0) {
  43. ERROR_INFER_STATUS(status, INVALID_INPUTS, "http message invalid");
  44. return status;
  45. } else {
  46. size_t copy_len = post_size > BUF_MAX ? BUF_MAX : post_size;
  47. buf->resize(copy_len);
  48. memcpy(buf->data(), evbuffer_pullup(req->input_buffer, -1), copy_len);
  49. return status;
  50. }
  51. }
  52. Status CheckRequestValid(struct evhttp_request *http_request) {
  53. Status status(SUCCESS);
  54. switch (evhttp_request_get_command(http_request)) {
  55. case EVHTTP_REQ_POST:
  56. return status;
  57. default:
  58. ERROR_INFER_STATUS(status, INVALID_INPUTS, "http message only support POST right now");
  59. return status;
  60. }
  61. }
  62. void ErrorMessage(struct evhttp_request *req, Status status) {
  63. json error_json = {{"error_message", status.StatusMessage()}};
  64. std::string out_error_str = error_json.dump();
  65. struct evbuffer *retbuff = evbuffer_new();
  66. evbuffer_add(retbuff, out_error_str.data(), out_error_str.size());
  67. evhttp_send_reply(req, HTTP_OK, "Client", retbuff);
  68. evbuffer_free(retbuff);
  69. }
  70. Status CheckMessageValid(const json &message_info, HTTP_TYPE *type) {
  71. Status status(SUCCESS);
  72. int count = 0;
  73. if (message_info.find(HTTP_DATA) != message_info.end()) {
  74. *type = TYPE_DATA;
  75. count++;
  76. }
  77. if (message_info.find(HTTP_TENSOR) != message_info.end()) {
  78. *type = TYPE_TENSOR;
  79. count++;
  80. }
  81. if (count != 1) {
  82. ERROR_INFER_STATUS(status, INVALID_INPUTS, "http message must have only one type of (data, tensor, text)");
  83. return status;
  84. }
  85. return status;
  86. }
  87. Status GetDataFromJson(const json &json_data, std::string *data, HTTP_DATA_TYPE *type) {
  88. Status status(SUCCESS);
  89. if (json_data.is_number_integer()) {
  90. if (*type == HTTP_DATA_NONE) {
  91. *type = HTTP_DATA_INT;
  92. } else if (*type != HTTP_DATA_INT) {
  93. ERROR_INFER_STATUS(status, INVALID_INPUTS, "the input data type should be consistent");
  94. return status;
  95. }
  96. auto s_data = json_data.get<int32_t>();
  97. data->append(reinterpret_cast<char *>(&s_data), sizeof(int32_t));
  98. } else if (json_data.is_number_float()) {
  99. if (*type == HTTP_DATA_NONE) {
  100. *type = HTTP_DATA_FLOAT;
  101. } else if (*type != HTTP_DATA_FLOAT) {
  102. ERROR_INFER_STATUS(status, INVALID_INPUTS, "the input data type should be consistent");
  103. return status;
  104. }
  105. auto s_data = json_data.get<float>();
  106. data->append(reinterpret_cast<char *>(&s_data), sizeof(float));
  107. } else {
  108. ERROR_INFER_STATUS(status, INVALID_INPUTS, "the input data type should be int or float");
  109. return status;
  110. }
  111. return SUCCESS;
  112. }
  113. Status RecusiveGetTensor(const json &json_data, size_t depth, std::vector<int> *shape, std::string *data,
  114. HTTP_DATA_TYPE *type) {
  115. Status status(SUCCESS);
  116. if (depth >= 10) {
  117. ERROR_INFER_STATUS(status, INVALID_INPUTS, "the tensor shape dims is larger than 10");
  118. return status;
  119. }
  120. if (!json_data.is_array()) {
  121. ERROR_INFER_STATUS(status, INVALID_INPUTS, "the tensor is constructed illegally");
  122. return status;
  123. }
  124. int cur_dim = json_data.size();
  125. if (shape->size() <= depth) {
  126. shape->push_back(cur_dim);
  127. } else if ((*shape)[depth] != cur_dim) {
  128. return INFER_STATUS(INVALID_INPUTS) << "the tensor shape is constructed illegally";
  129. }
  130. if (json_data.at(0).is_array()) {
  131. for (const auto &item : json_data) {
  132. status = RecusiveGetTensor(item, depth + 1, shape, data, type);
  133. if (status != SUCCESS) {
  134. return status;
  135. }
  136. }
  137. } else {
  138. // last dim, read the data
  139. for (auto item : json_data) {
  140. status = GetDataFromJson(item, data, type);
  141. if (status != SUCCESS) {
  142. return status;
  143. }
  144. }
  145. }
  146. return status;
  147. }
  148. Status TransDataToPredictRequest(const json &message_info, PredictRequest *request) {
  149. Status status = SUCCESS;
  150. auto tensors = message_info.find(HTTP_DATA);
  151. if (tensors == message_info.end()) {
  152. ERROR_INFER_STATUS(status, INVALID_INPUTS, "http message do not have data type");
  153. return status;
  154. }
  155. if (tensors->size() == 0) {
  156. ERROR_INFER_STATUS(status, INVALID_INPUTS, "the input tensor list is null");
  157. return status;
  158. }
  159. for (const auto &tensor : *tensors) {
  160. std::string msg_data;
  161. HTTP_DATA_TYPE type{HTTP_DATA_NONE};
  162. if (!tensor.is_array()) {
  163. ERROR_INFER_STATUS(status, INVALID_INPUTS, "the tensor is constructed illegally");
  164. return status;
  165. }
  166. if (tensor.size() == 0) {
  167. ERROR_INFER_STATUS(status, INVALID_INPUTS, "the input tensor is null");
  168. return status;
  169. }
  170. for (const auto &tensor_data : tensor) {
  171. status = GetDataFromJson(tensor_data, &msg_data, &type);
  172. if (status != SUCCESS) {
  173. return status;
  174. }
  175. }
  176. auto iter = http_to_infer_map.find(type);
  177. if (iter == http_to_infer_map.end()) {
  178. ERROR_INFER_STATUS(status, INVALID_INPUTS, "the input type is not supported right now");
  179. return status;
  180. }
  181. auto infer_tensor = request->add_data();
  182. infer_tensor->set_tensor_type(iter->second);
  183. infer_tensor->set_data(msg_data.data(), msg_data.size());
  184. }
  185. // get model required shape
  186. std::vector<inference::InferTensor> tensor_list;
  187. status = Session::Instance().GetModelInputsInfo(tensor_list);
  188. if (status != SUCCESS) {
  189. ERROR_INFER_STATUS(status, FAILED, "get model inputs info failed");
  190. return status;
  191. }
  192. if (request->data_size() != static_cast<int64_t>(tensor_list.size())) {
  193. ERROR_INFER_STATUS(status, INVALID_INPUTS, "the inputs number is not equal to model required");
  194. return status;
  195. }
  196. for (int i = 0; i < request->data_size(); i++) {
  197. for (size_t j = 0; j < tensor_list[i].shape().size(); ++j) {
  198. request->mutable_data(i)->mutable_tensor_shape()->add_dims(tensor_list[i].shape()[i]);
  199. }
  200. }
  201. return SUCCESS;
  202. }
  203. Status TransTensorToPredictRequest(const json &message_info, PredictRequest *request) {
  204. Status status(SUCCESS);
  205. auto tensors = message_info.find(HTTP_TENSOR);
  206. if (tensors == message_info.end()) {
  207. ERROR_INFER_STATUS(status, INVALID_INPUTS, "http message do not have tensor type");
  208. return status;
  209. }
  210. for (const auto &tensor : *tensors) {
  211. std::vector<int> shape;
  212. std::string msg_data;
  213. HTTP_DATA_TYPE type{HTTP_DATA_NONE};
  214. RecusiveGetTensor(tensor, 0, &shape, &msg_data, &type);
  215. auto iter = http_to_infer_map.find(type);
  216. if (iter == http_to_infer_map.end()) {
  217. ERROR_INFER_STATUS(status, INVALID_INPUTS, "the input type is not supported right now");
  218. return status;
  219. }
  220. auto infer_tensor = request->add_data();
  221. infer_tensor->set_tensor_type(iter->second);
  222. infer_tensor->set_data(msg_data.data(), msg_data.size());
  223. for (const auto dim : shape) {
  224. infer_tensor->mutable_tensor_shape()->add_dims(dim);
  225. }
  226. }
  227. return status;
  228. }
  229. Status TransHTTPMsgToPredictRequest(struct evhttp_request *http_request, PredictRequest *request, HTTP_TYPE *type) {
  230. Status status = CheckRequestValid(http_request);
  231. if (status != SUCCESS) {
  232. return status;
  233. }
  234. std::string post_message;
  235. status = GetPostMessage(http_request, &post_message);
  236. if (status != SUCCESS) {
  237. return status;
  238. }
  239. json message_info;
  240. try {
  241. message_info = nlohmann::json::parse(post_message);
  242. } catch (nlohmann::json::exception &e) {
  243. std::string json_exception = e.what();
  244. std::string error_message = "Illegal JSON format." + json_exception;
  245. ERROR_INFER_STATUS(status, INVALID_INPUTS, error_message);
  246. return status;
  247. }
  248. status = CheckMessageValid(message_info, type);
  249. if (status != SUCCESS) {
  250. return status;
  251. }
  252. switch (*type) {
  253. case TYPE_DATA:
  254. status = TransDataToPredictRequest(message_info, request);
  255. break;
  256. case TYPE_TENSOR:
  257. status = TransTensorToPredictRequest(message_info, request);
  258. break;
  259. default:
  260. ERROR_INFER_STATUS(status, INVALID_INPUTS, "http message must have only one type of (data, tensor)");
  261. return status;
  262. }
  263. return status;
  264. }
  265. Status GetJsonFromTensor(const ms_serving::Tensor &tensor, int len, int *pos, json *out_json) {
  266. Status status(SUCCESS);
  267. switch (tensor.tensor_type()) {
  268. case ms_serving::MS_INT32: {
  269. std::vector<int> result_tensor;
  270. for (int j = 0; j < len; j++) {
  271. int val;
  272. memcpy(&val, reinterpret_cast<const int *>(tensor.data().data()) + *pos + j, sizeof(int));
  273. result_tensor.push_back(val);
  274. }
  275. *out_json = result_tensor;
  276. *pos += len;
  277. break;
  278. }
  279. case ms_serving::MS_FLOAT32: {
  280. std::vector<float> result_tensor;
  281. for (int j = 0; j < len; j++) {
  282. float val;
  283. memcpy(&val, reinterpret_cast<const float *>(tensor.data().data()) + *pos + j, sizeof(float));
  284. result_tensor.push_back(val);
  285. }
  286. *out_json = result_tensor;
  287. *pos += len;
  288. break;
  289. }
  290. default:
  291. MSI_LOG(ERROR) << "the result type is not supported in restful api, type is " << tensor.tensor_type();
  292. ERROR_INFER_STATUS(status, FAILED, "reply have unsupported type");
  293. }
  294. return status;
  295. }
  296. Status TransPredictReplyToData(const PredictReply &reply, json *out_json) {
  297. Status status(SUCCESS);
  298. for (int i = 0; i < reply.result_size(); i++) {
  299. json tensor_json;
  300. int num = 1;
  301. for (auto j = 0; j < reply.result(i).tensor_shape().dims_size(); j++) {
  302. num *= reply.result(i).tensor_shape().dims(j);
  303. }
  304. int pos = 0;
  305. status = GetJsonFromTensor(reply.result(i), num, &pos, &tensor_json);
  306. if (status != SUCCESS) {
  307. return status;
  308. }
  309. (*out_json)["data"].push_back(tensor_json);
  310. }
  311. return status;
  312. }
  313. Status RecusiveGetJson(const ms_serving::Tensor &tensor, int depth, int *pos, json *out_json) {
  314. Status status(SUCCESS);
  315. if (depth >= 10) {
  316. ERROR_INFER_STATUS(status, FAILED, "result tensor shape dims is larger than 10");
  317. return status;
  318. }
  319. if (depth == tensor.tensor_shape().dims_size() - 1) {
  320. status = GetJsonFromTensor(tensor, tensor.tensor_shape().dims(depth), pos, out_json);
  321. if (status != SUCCESS) {
  322. return status;
  323. }
  324. } else {
  325. for (int i = 0; i < tensor.tensor_shape().dims(depth); i++) {
  326. json tensor_json;
  327. status = RecusiveGetJson(tensor, depth + 1, pos, &tensor_json);
  328. if (status != SUCCESS) {
  329. return status;
  330. }
  331. out_json->push_back(tensor_json);
  332. }
  333. }
  334. return status;
  335. }
  336. Status TransPredictReplyToTensor(const PredictReply &reply, json *out_json) {
  337. Status status(SUCCESS);
  338. for (int i = 0; i < reply.result_size(); i++) {
  339. json tensor_json;
  340. int pos = 0;
  341. status = RecusiveGetJson(reply.result(i), 0, &pos, &tensor_json);
  342. if (status != SUCCESS) {
  343. return status;
  344. }
  345. (*out_json)["tensor"].push_back(tensor_json);
  346. }
  347. return status;
  348. }
  349. Status TransPredictReplyToHTTPMsg(const PredictReply &reply, const HTTP_TYPE &type, struct evbuffer *buf) {
  350. Status status(SUCCESS);
  351. json out_json;
  352. switch (type) {
  353. case TYPE_DATA:
  354. status = TransPredictReplyToData(reply, &out_json);
  355. break;
  356. case TYPE_TENSOR:
  357. status = TransPredictReplyToTensor(reply, &out_json);
  358. break;
  359. default:
  360. ERROR_INFER_STATUS(status, FAILED, "http message must have only one type of (data, tensor)");
  361. return status;
  362. }
  363. std::string out_str = out_json.dump();
  364. evbuffer_add(buf, out_str.data(), out_str.size());
  365. return status;
  366. }
  367. void http_handler_msg(struct evhttp_request *req, void *arg) {
  368. std::cout << "in handle" << std::endl;
  369. PredictRequest request;
  370. PredictReply reply;
  371. HTTP_TYPE type;
  372. auto status = TransHTTPMsgToPredictRequest(req, &request, &type);
  373. if (status != SUCCESS) {
  374. ErrorMessage(req, status);
  375. MSI_LOG(ERROR) << "restful trans to request failed";
  376. return;
  377. }
  378. MSI_TIME_STAMP_START(Predict)
  379. status = Session::Instance().Predict(request, reply);
  380. if (status != SUCCESS) {
  381. ErrorMessage(req, status);
  382. MSI_LOG(ERROR) << "restful predict failed";
  383. }
  384. MSI_TIME_STAMP_END(Predict)
  385. struct evbuffer *retbuff = evbuffer_new();
  386. status = TransPredictReplyToHTTPMsg(reply, type, retbuff);
  387. if (status != SUCCESS) {
  388. ErrorMessage(req, status);
  389. MSI_LOG(ERROR) << "restful trans to reply failed";
  390. return;
  391. }
  392. evhttp_send_reply(req, HTTP_OK, "Client", retbuff);
  393. evbuffer_free(retbuff);
  394. }
  395. } // namespace serving
  396. } // namespace mindspore