1 /** 2 * Copyright 2021 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_COMMUNICATOR_BASE_H_ 18 #define MINDSPORE_CCSRC_PS_CORE_COMMUNICATOR_COMMUNICATOR_BASE_H_ 19 20 #include <string> 21 #include <memory> 22 #include <unordered_map> 23 #include <functional> 24 #include <thread> 25 #include "ps/core/communicator/message_handler.h" 26 #include "utils/log_adapter.h" 27 #include "ps/core/communicator/http_message_handler.h" 28 #include "ps/core/communicator/tcp_server.h" 29 #include "ps/core/node_info.h" 30 #include "include/backend/distributed/ps/constants.h" 31 32 namespace mindspore { 33 namespace ps { 34 namespace core { 35 enum class TcpUserCommand { kPush, kPull }; 36 37 // CommunicatorBase is used to receive request and send response for server. 38 // It is the base class of HttpCommunicator and TcpCommunicator. 39 class CommunicatorBase { 40 public: 41 using MessageCallback = std::function<void(std::shared_ptr<MessageHandler>)>; 42 using HttpMsgCallback = std::function<void(std::shared_ptr<HttpMessageHandler>)>; 43 using OnNodeEventCallback = std::function<void(const ClusterEvent &)>; 44 using TcpMsgCallback = std::function<void(std::shared_ptr<core::TcpConnection> conn, 45 std::shared_ptr<core::MessageMeta> meta, const void *data, size_t size)>; CommunicatorBase()46 CommunicatorBase() : running_(false) {} 47 48 virtual ~CommunicatorBase(); 49 50 virtual bool Start() = 0; 51 virtual bool Stop() = 0; 52 // You need to call the Start() function before calling the Join() function, it will block server's main thread. 53 // if you want to exit the Join() function, then you should call the Stop() function in another thread. 54 void Join(); 55 56 virtual void RegisterMsgCallBack(const std::string &msg_type, const MessageCallback &cb) = 0; 57 58 bool SendResponse(const void *rsp_data, size_t rsp_len, const std::shared_ptr<MessageHandler> &msg_handler); 59 60 bool running() const; 61 62 protected: 63 std::unordered_map<std::string, MessageCallback> msg_callbacks_; 64 std::thread running_thread_; 65 bool running_; 66 }; 67 } // namespace core 68 } // namespace ps 69 } // namespace mindspore 70 #endif // MINDSPORE_CCSRC_PS_CORE_COMMUNICATOR_COMMUNICATOR_BASE_H_ 71