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.

server.cc 10 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 "core/server.h"
  17. #include <evhttp.h>
  18. #include <event.h>
  19. #include <event2/thread.h>
  20. #include <event2/listener.h>
  21. #include <grpcpp/grpcpp.h>
  22. #include <grpcpp/health_check_service_interface.h>
  23. #include <grpcpp/ext/proto_server_reflection_plugin.h>
  24. #include <future>
  25. #include <memory>
  26. #include <string>
  27. #include <vector>
  28. #include <utility>
  29. #include "include/infer_log.h"
  30. #include "serving/ms_service.grpc.pb.h"
  31. #include "core/util/option_parser.h"
  32. #include "core/version_control/version_controller.h"
  33. #include "core/session.h"
  34. #include "core/serving_tensor.h"
  35. #include "core/http_process.h"
  36. using ms_serving::MSService;
  37. using ms_serving::PredictReply;
  38. using ms_serving::PredictRequest;
  39. namespace mindspore {
  40. namespace serving {
  41. namespace {
  42. static const uint32_t uint32max = 0x7FFFFFFF;
  43. std::promise<void> exit_requested;
  44. static const char kServerHttpIp[] = "0.0.0.0";
  45. void ClearEnv() { Session::Instance().Clear(); }
  46. void HandleSignal(int sig) { exit_requested.set_value(); }
  47. grpc::Status CreatGRPCStatus(const Status &status) {
  48. switch (status.StatusCode()) {
  49. case SUCCESS:
  50. return grpc::Status::OK;
  51. case FAILED:
  52. return grpc::Status::CANCELLED;
  53. case INVALID_INPUTS: {
  54. auto status_msg = status.StatusMessage();
  55. if (status_msg.empty()) {
  56. status_msg = "The Predict Inputs do not match the Model Request!";
  57. }
  58. return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, status_msg);
  59. }
  60. default:
  61. return grpc::Status::CANCELLED;
  62. }
  63. }
  64. } // namespace
  65. // Service Implement
  66. class MSServiceImpl final : public MSService::Service {
  67. grpc::Status Predict(grpc::ServerContext *context, const PredictRequest *request, PredictReply *reply) override {
  68. MSI_TIME_STAMP_START(Predict)
  69. auto res = Session::Instance().Predict(*request, *reply);
  70. MSI_TIME_STAMP_END(Predict)
  71. if (res != inference::SUCCESS) {
  72. return CreatGRPCStatus(res);
  73. }
  74. MSI_LOG(INFO) << "Finish call service Eval";
  75. return grpc::Status::OK;
  76. }
  77. grpc::Status Test(grpc::ServerContext *context, const PredictRequest *request, PredictReply *reply) override {
  78. MSI_LOG(INFO) << "TestService call";
  79. return grpc::Status::OK;
  80. }
  81. };
  82. static std::pair<struct evhttp *, struct event_base *> NewHttpServer() {
  83. auto option_args = Options::Instance().GetArgs();
  84. int32_t http_port = option_args->rest_api_port;
  85. // init http server
  86. event_init();
  87. evthread_use_pthreads();
  88. struct event_base *eb = event_base_new();
  89. if (eb == nullptr) {
  90. MSI_LOG(ERROR) << "Serving Error: RESTful server start failed, new http event failed";
  91. std::cout << "Serving Error: RESTful server start failed, new http event failed" << std::endl;
  92. return std::make_pair(nullptr, nullptr);
  93. }
  94. struct evhttp *http_server = evhttp_new(eb);
  95. if (http_server == nullptr) {
  96. MSI_LOG(ERROR) << "Serving Error: RESTful server start failed, create http server faild";
  97. std::cout << "Serving Error: RESTful server start failed, create http server faild" << std::endl;
  98. event_base_free(eb);
  99. return std::make_pair(nullptr, nullptr);
  100. }
  101. struct sockaddr_in sin = {};
  102. sin.sin_family = AF_INET;
  103. sin.sin_port = htons(http_port);
  104. auto listener =
  105. evconnlistener_new_bind(eb, nullptr, nullptr, LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_EXEC | LEV_OPT_CLOSE_ON_FREE, -1,
  106. reinterpret_cast<struct sockaddr *>(&sin), sizeof(sin));
  107. if (listener == nullptr) {
  108. MSI_LOG_ERROR << "Serving Error: RESTful server start failed, create http listener faild, port " << http_port;
  109. std::cout << "Serving Error: RESTful server start failed, create http listener faild, port " << http_port
  110. << std::endl;
  111. event_base_free(eb);
  112. evhttp_free(http_server);
  113. return std::make_pair(nullptr, nullptr);
  114. }
  115. auto bound = evhttp_bind_listener(http_server, listener);
  116. if (bound == nullptr) {
  117. MSI_LOG_ERROR << "Serving Error: RESTful server start failed, bind http listener to server faild, port "
  118. << http_port;
  119. std::cout << "Serving Error: RESTful server start failed, bind http listener to server faild, port " << http_port
  120. << std::endl;
  121. evconnlistener_free(listener);
  122. event_base_free(eb);
  123. evhttp_free(http_server);
  124. return std::make_pair(nullptr, nullptr);
  125. }
  126. return std::make_pair(http_server, eb);
  127. }
  128. Status BuildAndStartModelInner() {
  129. Status res;
  130. auto option_args = Options::Instance().GetArgs();
  131. std::string model_path = option_args->model_path;
  132. std::string model_name = option_args->model_name;
  133. std::string device_type = option_args->device_type;
  134. auto device_id = option_args->device_id;
  135. res = Session::Instance().CreatDeviceSession(device_type, device_id);
  136. if (res != SUCCESS) {
  137. MSI_LOG(ERROR) << "Serving Error: create inference session failed, device type " << device_type << " device id "
  138. << device_id;
  139. std::cout << "Serving Error: create inference session failed, device type " << device_type << " device id "
  140. << device_id << std::endl;
  141. return res;
  142. }
  143. VersionController version_controller(option_args->poll_model_wait_seconds, model_path, model_name);
  144. res = version_controller.Run();
  145. if (res != SUCCESS) {
  146. MSI_LOG(ERROR) << "Serving Error: load model failed, model directory " << option_args->model_path << " model name "
  147. << option_args->model_name;
  148. std::cout << "Serving Error: load model failed, model directory " << option_args->model_path << " model name "
  149. << option_args->model_name << std::endl;
  150. return res;
  151. }
  152. return SUCCESS;
  153. }
  154. Status BuildAndStartModel() {
  155. try {
  156. auto status = BuildAndStartModelInner();
  157. return status;
  158. } catch (const std::bad_alloc &ex) {
  159. MSI_LOG(ERROR) << "Serving Error: malloc memory failed";
  160. std::cout << "Serving Error: malloc memory failed" << std::endl;
  161. } catch (const std::runtime_error &ex) {
  162. MSI_LOG(ERROR) << "Serving Error: runtime error occurred: " << ex.what();
  163. std::cout << "Serving Error: runtime error occurred: " << ex.what() << std::endl;
  164. } catch (const std::exception &ex) {
  165. MSI_LOG(ERROR) << "Serving Error: exception occurred: " << ex.what();
  166. std::cout << "Serving Error: exception occurred: " << ex.what() << std::endl;
  167. } catch (...) {
  168. MSI_LOG(ERROR) << "Serving Error: exception occurred";
  169. std::cout << "Serving Error: exception occurred";
  170. }
  171. return FAILED;
  172. }
  173. Status Server::BuildAndStart() {
  174. // handle exit signal
  175. signal(SIGINT, HandleSignal);
  176. signal(SIGTERM, HandleSignal);
  177. Status res = BuildAndStartModel();
  178. if (res != SUCCESS) {
  179. ClearEnv();
  180. return res;
  181. }
  182. auto option_args = Options::Instance().GetArgs();
  183. std::string server_address = std::string(kServerHttpIp) + ":" + std::to_string(option_args->grpc_port);
  184. auto http_server_new_ret = NewHttpServer();
  185. struct evhttp *http_server = http_server_new_ret.first;
  186. struct event_base *eb = http_server_new_ret.second;
  187. if (http_server == nullptr || eb == nullptr) {
  188. MSI_LOG(ERROR) << "Serving Error: RESTful server start failed";
  189. std::cout << "Serving Error: RESTful server start failed" << std::endl;
  190. ClearEnv();
  191. return FAILED;
  192. }
  193. auto exit_http = [eb, http_server]() {
  194. evhttp_free(http_server);
  195. event_base_free(eb);
  196. };
  197. int32_t http_port = option_args->rest_api_port;
  198. std::string http_addr = kServerHttpIp;
  199. evhttp_set_timeout(http_server, 60);
  200. evhttp_set_gencb(http_server, http_handler_msg, nullptr);
  201. // grpc server
  202. MSServiceImpl ms_service;
  203. grpc::EnableDefaultHealthCheckService(true);
  204. grpc::reflection::InitProtoReflectionServerBuilderPlugin();
  205. // Set the port is not reuseable
  206. auto option = grpc::MakeChannelArgumentOption(GRPC_ARG_ALLOW_REUSEPORT, 0);
  207. grpc::ServerBuilder serverBuilder;
  208. serverBuilder.SetOption(std::move(option));
  209. serverBuilder.SetMaxMessageSize(uint32max);
  210. serverBuilder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
  211. serverBuilder.RegisterService(&ms_service);
  212. std::unique_ptr<grpc::Server> server(serverBuilder.BuildAndStart());
  213. if (server == nullptr) {
  214. MSI_LOG(ERROR) << "Serving Error: create server failed, gRPC address " << server_address << ", RESTful address "
  215. << http_addr << ":" << http_port << ", model directory " << option_args->model_path << " model name "
  216. << option_args->model_name << ", device type " << option_args->device_type << ", device id "
  217. << option_args->device_id;
  218. std::cout << "Serving Error: create server failed, gRPC address " << server_address << ", RESTful address "
  219. << http_addr << ":" << http_port << ", model directory " << option_args->model_path << " model name "
  220. << option_args->model_name << ", device type " << option_args->device_type << ", device id "
  221. << option_args->device_id << std::endl;
  222. ClearEnv();
  223. exit_http();
  224. return FAILED;
  225. }
  226. auto grpc_server_run = [&server, &server_address]() {
  227. MSI_LOG(INFO) << "MS Serving grpc listening on " << server_address;
  228. std::cout << "Serving: MS Serving gRPC start success, listening on " << server_address << std::endl;
  229. server->Wait();
  230. };
  231. auto http_server_run = [&eb, &http_addr, &http_port]() {
  232. MSI_LOG(INFO) << "MS Serving restful listening on " << http_addr << ":" << http_port;
  233. std::cout << "Serving: MS Serving RESTful start success, listening on " << http_addr << ":" << http_port
  234. << std::endl;
  235. event_base_dispatch(eb);
  236. };
  237. std::thread grpc_thread(grpc_server_run);
  238. std::thread restful_thread(http_server_run);
  239. auto exit_future = exit_requested.get_future();
  240. exit_future.wait();
  241. ClearEnv();
  242. server->Shutdown();
  243. event_base_loopexit(eb, nullptr);
  244. exit_http();
  245. grpc_thread.join();
  246. restful_thread.join();
  247. return SUCCESS;
  248. }
  249. } // namespace serving
  250. } // namespace mindspore