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
                         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,
Y
Yu Yang 已提交
103 104
                             ResponseCallback callback)>
      ServiceFunction;
Z
zhangjinchao01 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

  /**
   * @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:
124 125
  ProtoClient(const std::string& serverAddr,
              int serverPort,
Z
zhangjinchao01 已提交
126 127 128 129 130 131 132 133 134 135 136 137
              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
   */
138 139
  void send(const char* funcName,
            const google::protobuf::MessageLite& proto,
Z
zhangjinchao01 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153
            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(
154 155
      const char* funcName,
      const google::protobuf::MessageLite& protoIn,
Z
zhangjinchao01 已提交
156 157 158 159 160 161 162
      google::protobuf::MessageLite* protoOut) {
    send(funcName, protoIn);
    return recv(protoOut);
  }

  /// combines send() and recv()
  std::unique_ptr<MsgReader> sendAndRecv(
163 164 165 166
      const char* funcName,
      const google::protobuf::MessageLite& protoIn,
      const std::vector<iovec>& iov,
      google::protobuf::MessageLite* protoOut) {
Z
zhangjinchao01 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180
    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>
181 182 183 184
struct service_arg_type<R (C::*)(  // NOLINT
    const Arg1&,
    std::unique_ptr<MsgReader>,
    Arg2)> {
Z
zhangjinchao01 已提交
185 186 187 188 189
  typedef Arg1 _1;
};

/// register a service function to the ProtoServer
/// This should only be used within a member function of className
190 191 192 193 194 195 196 197
#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 已提交
198 199 200

/// register a service function to the ProtoServer
/// This should only be used within a member function of className
201 202 203 204 205 206 207 208 209
#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 已提交
210 211 212 213 214 215

/// 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,
216 217
    std::function<void(const ProtoIn&,
                       std::unique_ptr<MsgReader> msgReader,
Z
zhangjinchao01 已提交
218
                       ProtoResponseCallbackEx callback)> func) {
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
  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 已提交
237 238 239 240 241 242 243 244

  registerServiceFunctionImp(funcName, f);
}

template <class ProtoIn>
void ProtoServer::registerServiceFunction(
    const std::string& funcName,
    std::function<void(const ProtoIn&, ProtoResponseCallback callback)> func) {
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
  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 已提交
263 264 265 266 267

  registerServiceFunctionImp(funcName, f);
}

}  // namespace paddle