ProtoServer.h 9.6 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#pragma once

#include "LightNetwork.h"

#include <map>

#include <google/protobuf/message_lite.h>

namespace paddle {

25 26 27 28 29 30 31 32 33 34 35
/**
 *
 * It implements the rpc framework, which launchs one thread for each
 * connection. Here define one parameter server as single TCP server
 * binding on single port. All connections share single tcp ProtoServer
 * object, each connection handles all requests from specified trainer
 * within single worker thread.
 * to accelerate bandwidth efficiency and harness multicore for pserver
 * optimization to reduce pserver latency, you could launch more port
 * for single NIC hardward with --port=N(N>1) for small cluster job.
 */
Z
zhangjinchao01 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
class ProtoServer : public SocketServer {
public:
  /// rdmaCpu controls the cpu affinity of RDMA server daemon,
  /// which could benifit performance. rdmaCpu = -1 means TCP
  /// is used instead of RDMA transport.
  ProtoServer(const std::string& addr, int port, int rdmaCpu = -1)
      : SocketServer(addr, port, rdmaCpu) {}

  typedef std::function<void(const google::protobuf::MessageLite& protoOut,
                             const std::vector<iovec>& outputIovs)>
      ProtoResponseCallbackEx;

  typedef std::function<void(const google::protobuf::MessageLite& protoOut)>
      ProtoResponseCallback;

  /**
   * Register a service function for this server
   * void(const ProtoIn& request,
   *      ProtoResponseCallback callback)
   * The service function process the request and call the callback
   * after it finishes the request.

   * Use macro REGISTER_SERVICE_FUNCTION as a helper
   * to simplify the use.
   */
  template <class ProtoIn>
  void registerServiceFunction(
      const std::string& funcName,
      std::function<void(const ProtoIn& request,
                         ProtoResponseCallback callback)> func);

  /**
   * Register a service function for this server
   * The signature of the service function is
   * void(const ProtoIn&,
   *      std::unique_ptr<MsgReader> msgReader,
   *      ProtoResponseCallbackEx callback)
   * The service function process the request and call the callback
   * after it finishes the request.
   * The extended service function can take extra input blocks from
   * the communication channel by reading msgReader. It can also
   * send extra blocks to the communication channel by providing
   * outputIovs as the argument for the callback function.

   * Use macro REGISTER_SERVICE_FUNCTION_EX as a helper
   * to simplify the use.
   */
  template <class ProtoIn>
  void registerServiceFunctionEx(
      const std::string& funcName,
86 87
      std::function<void(const ProtoIn&,
                         std::unique_ptr<MsgReader> msgReader,
Z
zhangjinchao01 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
                         ProtoResponseCallbackEx callback)> func);

protected:
  /**
   * @brief handle rpc request
   * @param[in] msgReader  Message reader for reading data from connection
   * @param[in] callback   equal to channel->writeMessage
   *
   * @note  it lookups rpc function mapping table to find function pointer,
   *        then call this function with further reading data from connection
   */
  virtual void handleRequest(std::unique_ptr<MsgReader> msgReader,
                             ResponseCallback callback);

  typedef std::function<void(std::unique_ptr<MsgReader> msgReader,
                             ResponseCallback callback)> ServiceFunction;

  /**
   * @brief register one RPC function in function mapping
   * @param[in] funcName  function name string
   * @param[in] func      rpc function wrapped with reading and writing data
   */
  void registerServiceFunctionImp(const std::string& funcName,
                                  ServiceFunction func);

protected:
  /// Tuning bare network overhead: the beginning of receiving request
  ThreadLocal<struct timeval> handleRequestBegin_;

  /// mapping to find rpc function while handling request
  std::map<std::string, ServiceFunction> nameToFuncMap_;
};

class ProtoClient : public SocketClient {
public:
123 124
  ProtoClient(const std::string& serverAddr,
              int serverPort,
Z
zhangjinchao01 已提交
125 126 127 128 129 130 131 132 133 134 135 136
              enum ChannelType channelType = F_TCP)
      : SocketClient(serverAddr, serverPort, channelType) {}

  /**
   * @brief Make a request to the server.
   * @param[in] funcName  request rpc function name string
   * @param[in] proto     protobuf data for sending to pserver
   * @param[in] iov       additional iov data for sending to pserver
   *
   * @note  iov provides additional blocks which need to be written to the
   *        communication channel
   */
137 138
  void send(const char* funcName,
            const google::protobuf::MessageLite& proto,
Z
zhangjinchao01 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152
            const std::vector<iovec>& iov = std::vector<iovec>());

  /**
   * @brief receive the response from the server.
   * @param[in] proto     proto binary buffer
   *
   * @note  this must be paired with a corresponding send() call. The
   *        returned MsgReader allows the caller to receive additional
   *        blocks from the communication channel.
   */
  std::unique_ptr<MsgReader> recv(google::protobuf::MessageLite* proto);

  /// combines send() and recv()
  std::unique_ptr<MsgReader> sendAndRecv(
153 154
      const char* funcName,
      const google::protobuf::MessageLite& protoIn,
Z
zhangjinchao01 已提交
155 156 157 158 159 160 161
      google::protobuf::MessageLite* protoOut) {
    send(funcName, protoIn);
    return recv(protoOut);
  }

  /// combines send() and recv()
  std::unique_ptr<MsgReader> sendAndRecv(
162 163 164 165
      const char* funcName,
      const google::protobuf::MessageLite& protoIn,
      const std::vector<iovec>& iov,
      google::protobuf::MessageLite* protoOut) {
Z
zhangjinchao01 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179
    send(funcName, protoIn, iov);
    return recv(protoOut);
  }
};

template <class>
struct service_arg_type;
/// helper class for obtaining the argument type of a service function
template <class R, class C, class Arg1, class Arg2>
struct service_arg_type<R (C::*)(const Arg1&, Arg2)> {
  typedef Arg1 _1;
};

template <class R, class C, class Arg1, class Arg2>
180 181 182 183
struct service_arg_type<R (C::*)(  // NOLINT
    const Arg1&,
    std::unique_ptr<MsgReader>,
    Arg2)> {
Z
zhangjinchao01 已提交
184 185 186 187 188
  typedef Arg1 _1;
};

/// register a service function to the ProtoServer
/// This should only be used within a member function of className
189 190 191 192 193 194 195 196
#define REGISTER_SERVICE_FUNCTION(className, funcName)       \
  registerServiceFunction<                                   \
      service_arg_type<decltype(&className::funcName)>::_1>( \
      #funcName,                                             \
      std::bind(&className::funcName,                        \
                this,                                        \
                std::placeholders::_1,                       \
                std::placeholders::_2))
Z
zhangjinchao01 已提交
197 198 199

/// register a service function to the ProtoServer
/// This should only be used within a member function of className
200 201 202 203 204 205 206 207 208
#define REGISTER_SERVICE_FUNCTION_EX(className, funcName)    \
  registerServiceFunctionEx<                                 \
      service_arg_type<decltype(&className::funcName)>::_1>( \
      #funcName,                                             \
      std::bind(&className::funcName,                        \
                this,                                        \
                std::placeholders::_1,                       \
                std::placeholders::_2,                       \
                std::placeholders::_3))
Z
zhangjinchao01 已提交
209 210 211 212 213 214

/// create wrapper function for parameter server high level function and
/// register the wrapper function into function mapping.
template <class ProtoIn>
void ProtoServer::registerServiceFunctionEx(
    const std::string& funcName,
215 216
    std::function<void(const ProtoIn&,
                       std::unique_ptr<MsgReader> msgReader,
Z
zhangjinchao01 已提交
217
                       ProtoResponseCallbackEx callback)> func) {
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
  auto f = [func](std::unique_ptr<MsgReader> msgReader,
                  ResponseCallback callback) {
    ProtoIn request;
    std::string str(msgReader->getNextBlockLength(), 0);
    msgReader->readNextBlock(&str[0]);
    CHECK(request.ParseFromString(str));
    auto pcob = [callback](const google::protobuf::MessageLite& response,
                           const std::vector<iovec>& outputIovs) {
      std::string out;
      CHECK(response.SerializeToString(&out));
      std::vector<iovec> iovs;
      iovs.push_back({&out[0], out.size()});
      iovs.insert(iovs.end(), outputIovs.begin(), outputIovs.end());
      callback(iovs);
    };

    func(request, std::move(msgReader), pcob);
  };
Z
zhangjinchao01 已提交
236 237 238 239 240 241 242 243

  registerServiceFunctionImp(funcName, f);
}

template <class ProtoIn>
void ProtoServer::registerServiceFunction(
    const std::string& funcName,
    std::function<void(const ProtoIn&, ProtoResponseCallback callback)> func) {
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
  auto f = [func](std::unique_ptr<MsgReader> msgReader,
                  ResponseCallback callback) {
    ProtoIn request;
    std::string str(msgReader->getNextBlockLength(), 0);
    msgReader->readNextBlock(&str[0]);
    CHECK(request.ParseFromString(str));
    msgReader.reset();

    auto pcob = [callback](const google::protobuf::MessageLite& response) {
      std::string out;
      CHECK(response.SerializeToString(&out));
      std::vector<iovec> iovs;
      iovs.push_back({&out[0], out.size()});
      callback(iovs);
    };

    func(request, pcob);
  };
Z
zhangjinchao01 已提交
262 263 264 265 266

  registerServiceFunctionImp(funcName, f);
}

}  // namespace paddle