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 48 class HttpServer { 49 public: 50 // Server address only support IPV4 now, and should be in format of "x.x.x.x" 51 explicit HttpServer(const std::string &address, std::uint16_t port, size_t thread_num = 10) server_address_(address)52 : server_address_(address), 53 server_port_(port), 54 is_stop_(true), 55 request_timeout_(300), 56 thread_num_(thread_num), 57 backlog_(1024), 58 fd_(-1) {} 59 60 ~HttpServer(); 61 62 bool InitServer(); 63 void SetTimeOut(int seconds); 64 65 // Return: true if success, false if failed, check log to find failure reason 66 bool RegisterRoute(const std::string &url, OnRequestReceive *func); 67 68 bool Start(bool is_detach = true); 69 bool Wait(); 70 bool Stop(); 71 72 private: 73 std::string server_address_; 74 std::uint16_t server_port_; 75 std::atomic<bool> is_stop_; 76 int request_timeout_; 77 size_t thread_num_; 78 std::vector<std::shared_ptr<std::thread>> worker_threads_; 79 std::vector<std::shared_ptr<HttpRequestHandler>> http_request_handlers; 80 int32_t backlog_; 81 std::unordered_map<std::string, OnRequestReceive *> request_handlers_; 82 int fd_; 83 }; 84 } // namespace core 85 } // namespace ps 86 } // namespace mindspore 87 #endif // MINDSPORE_CCSRC_PS_CORE_COMMUNICATOR_HTTP_SERVER_H_ 88