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 17 #ifndef MINDSPORE_CCSRC_PS_CORE_COMMUNICATOR_HTTP_SERVER_H_ 18 #define MINDSPORE_CCSRC_PS_CORE_COMMUNICATOR_HTTP_SERVER_H_ 19 20 #include "ps/core/communicator/http_message_handler.h" 21 22 #include <event2/buffer.h> 23 #include <event2/event.h> 24 #include <event2/http.h> 25 #include <event2/keyvalq_struct.h> 26 #include <event2/listener.h> 27 #include <event2/util.h> 28 #include <event2/thread.h> 29 #include <fcntl.h> 30 #include <unistd.h> 31 32 #include <cstdio> 33 #include <cstdlib> 34 #include <cstring> 35 #include <functional> 36 #include <memory> 37 #include <string> 38 #include <atomic> 39 #include <unordered_map> 40 #include <vector> 41 42 #include "ps/core/communicator/http_request_handler.h" 43 44 namespace mindspore { 45 namespace ps { 46 namespace core { 47 constexpr int kRequestTimeout = 300; 48 constexpr int32_t kBacklog = 1024; 49 class HttpServer { 50 public: 51 // Server address only support IPV4 now, and should be in format of "x.x.x.x" 52 explicit HttpServer(const std::string &address, std::uint16_t port, size_t thread_num = 10) server_address_(address)53 : server_address_(address), 54 server_port_(port), 55 is_stop_(true), 56 request_timeout_(kRequestTimeout), 57 thread_num_(thread_num), 58 backlog_(kBacklog), 59 fd_(-1) {} 60 61 ~HttpServer(); 62 63 bool InitServer(); 64 void SetTimeOut(int seconds); 65 66 // Return: true if success, false if failed, check log to find failure reason 67 bool RegisterRoute(const std::string &url, OnRequestReceive *func); 68 69 bool Start(); 70 bool Wait(); 71 bool Stop(); 72 73 private: 74 std::string server_address_; 75 std::uint16_t server_port_; 76 std::atomic<bool> is_stop_; 77 int request_timeout_; 78 size_t thread_num_; 79 std::vector<std::shared_ptr<std::thread>> worker_threads_; 80 std::vector<std::shared_ptr<HttpRequestHandler>> http_request_handlers; 81 int32_t backlog_; 82 std::unordered_map<std::string, OnRequestReceive *> request_handlers_; 83 int fd_; 84 }; 85 } // namespace core 86 } // namespace ps 87 } // namespace mindspore 88 #endif // MINDSPORE_CCSRC_PS_CORE_COMMUNICATOR_HTTP_SERVER_H_ 89