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