grpc_server.cc 10.5 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
G
gongweibao 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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. */

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/detail/grpc_server.h"
Q
qiaolongfei 已提交
16
#include <paddle/fluid/operators/detail/send_recv.pb.h>
G
gongweibao 已提交
17

18
using ::grpc::ServerAsyncResponseWriter;
G
gongweibao 已提交
19 20 21 22 23 24 25 26 27 28 29

namespace paddle {
namespace operators {
namespace detail {

enum CallStatus { PROCESS = 0, FINISH };

// reference:
// https://stackoverflow.com/questions/41732884/grpc-multiple-services-in-cpp-async-server
class RequestBase {
 public:
30 31 32 33
  explicit RequestBase(GrpcService::AsyncService* service,
                       ::grpc::ServerCompletionQueue* cq,
                       const platform::DeviceContext* dev_ctx)
      : service_(service), cq_(cq), status_(PROCESS), dev_ctx_(dev_ctx) {
G
gongweibao 已提交
34 35
    PADDLE_ENFORCE(cq_);
  }
G
gongweibao 已提交
36 37 38 39 40
  virtual ~RequestBase() {}
  virtual void Process() { assert(false); }

  CallStatus Status() { return status_; }
  void SetStatus(CallStatus status) { status_ = status; }
T
typhoonzero 已提交
41 42 43 44
  virtual std::string GetReqName() {
    assert(false);
    return "";
  }
G
gongweibao 已提交
45 46

 protected:
47 48 49
  ::grpc::ServerContext ctx_;
  GrpcService::AsyncService* service_;
  ::grpc::ServerCompletionQueue* cq_;
G
gongweibao 已提交
50
  CallStatus status_;
51
  const platform::DeviceContext* dev_ctx_;
G
gongweibao 已提交
52 53 54 55
};

class RequestSend final : public RequestBase {
 public:
56 57 58 59 60 61 62 63 64
  explicit RequestSend(GrpcService::AsyncService* service,
                       ::grpc::ServerCompletionQueue* cq,
                       framework::Scope* scope, ReceivedQueue* queue,
                       const platform::DeviceContext* dev_ctx)
      : RequestBase(service, cq, dev_ctx), queue_(queue), responder_(&ctx_) {
    request_.reset(new VariableResponse(scope, dev_ctx_));
    int method_id = static_cast<int>(detail::GrpcMethod::kSendVariable);
    service_->RequestAsyncUnary(method_id, &ctx_, request_.get(), &responder_,
                                cq_, cq_, this);
G
gongweibao 已提交
65 66 67 68
  }

  virtual ~RequestSend() {}

69
  virtual std::string GetReqName() { return request_->Varname(); }
G
gongweibao 已提交
70

G
gongweibao 已提交
71
  virtual void Process() {
72 73 74 75
    queue_->Push(std::make_pair(request_->Varname(), request_));

    sendrecv::VoidMessage reply;
    responder_.Finish(reply, ::grpc::Status::OK, this);
G
gongweibao 已提交
76
    status_ = FINISH;
G
gongweibao 已提交
77 78 79
  }

 protected:
80 81
  std::shared_ptr<VariableResponse> request_;
  ReceivedQueue* queue_;
G
gongweibao 已提交
82 83 84 85 86
  ServerAsyncResponseWriter<sendrecv::VoidMessage> responder_;
};

class RequestGet final : public RequestBase {
 public:
87 88 89
  explicit RequestGet(GrpcService::AsyncService* service,
                      ::grpc::ServerCompletionQueue* cq,
                      framework::Scope* scope,
T
typhoonzero 已提交
90
                      const platform::DeviceContext* dev_ctx,
91
                      SimpleBlockQueue<MessageWithName>* queue)
92
      : RequestBase(service, cq, dev_ctx),
Y
Yancey1989 已提交
93 94
        responder_(&ctx_),
        scope_(scope),
T
typhoonzero 已提交
95
        queue_(queue) {
96 97 98
    int method_id = static_cast<int>(detail::GrpcMethod::kGetVariable);
    service_->RequestAsyncUnary(method_id, &ctx_, &request_, &responder_, cq_,
                                cq_, this);
G
gongweibao 已提交
99 100 101 102
  }

  virtual ~RequestGet() {}

G
gongweibao 已提交
103 104
  virtual std::string GetReqName() { return request_.varname(); }

G
gongweibao 已提交
105 106 107 108
  virtual void Process() {
    // proc request.
    std::string var_name = request_.varname();
    auto* var = scope_->FindVar(var_name);
109 110

    ::grpc::ByteBuffer reply;
111
    if (var_name != FETCH_BARRIER_MESSAGE) {
112
      SerializeToByteBuffer(var_name, var, *dev_ctx_, &reply);
113
    }
114 115

    responder_.Finish(reply, ::grpc::Status::OK, this);
G
gongweibao 已提交
116
    status_ = FINISH;
117 118 119 120 121 122

    if (var_name == FETCH_BARRIER_MESSAGE) {
      sendrecv::VariableMessage msg;
      MessageWithName msg_with_name = std::make_pair(var_name, msg);
      queue_->Push(msg_with_name);
    }
G
gongweibao 已提交
123 124 125 126
  }

 protected:
  sendrecv::VariableMessage request_;
127
  ServerAsyncResponseWriter<::grpc::ByteBuffer> responder_;
G
gongweibao 已提交
128
  framework::Scope* scope_;
129
  SimpleBlockQueue<MessageWithName>* queue_;
G
gongweibao 已提交
130 131
};

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
class RequestPrefetch final : public RequestBase {
 public:
  explicit RequestPrefetch(GrpcService::AsyncService* service,
                           ::grpc::ServerCompletionQueue* cq,
                           framework::Scope* scope,
                           const platform::DeviceContext* dev_ctx,
                           framework::Executor* executor,
                           framework::ProgramDesc* program, int blkid)
      : RequestBase(service, cq, dev_ctx),
        responder_(&ctx_),
        scope_(scope),
        executor_(executor),
        program_(program),
        blkid_(blkid) {
    int method_id = static_cast<int>(detail::GrpcMethod::kPrefetchVariable);
    service_->RequestAsyncUnary(method_id, &ctx_, &request_, &responder_, cq_,
                                cq_, this);
  }

  virtual ~RequestPrefetch() {}

  virtual std::string GetReqName() { return request_.varname(); }

  virtual void Process() {
    // prefetch process...
    ::grpc::ByteBuffer relay;
    // TODO(Yancey1989): execute the Block which containers prefetch ops

Q
qiaolongfei 已提交
160 161
    VLOG(3) << "RequestPrefetch Process in";

162 163 164 165 166 167 168 169 170 171 172 173 174
    responder_.Finish(relay, ::grpc::Status::OK, this);
    status_ = FINISH;
  }

 protected:
  sendrecv::VariableMessage request_;
  ServerAsyncResponseWriter<::grpc::ByteBuffer> responder_;
  framework::Scope* scope_;
  framework::Executor* executor_;
  framework::ProgramDesc* program_;
  int blkid_;
};

T
typhoonzero 已提交
175
void AsyncGRPCServer::WaitClientGet(int count) {
176 177 178 179 180 181
  int fetch_barriers = 0;
  while (fetch_barriers < count) {
    auto msg = var_get_queue_.Pop();
    if (msg.first == FETCH_BARRIER_MESSAGE) {
      fetch_barriers++;
    }
T
typhoonzero 已提交
182 183 184
  }
}

G
gongweibao 已提交
185
void AsyncGRPCServer::RunSyncUpdate() {
186 187
  ::grpc::ServerBuilder builder;
  builder.AddListeningPort(address_, ::grpc::InsecureServerCredentials());
G
gongweibao 已提交
188 189
  builder.SetMaxSendMessageSize(std::numeric_limits<int>::max());
  builder.SetMaxReceiveMessageSize(std::numeric_limits<int>::max());
G
gongweibao 已提交
190 191 192 193
  builder.RegisterService(&service_);

  cq_send_ = builder.AddCompletionQueue();
  cq_get_ = builder.AddCompletionQueue();
194
  cq_prefetch_ = builder.AddCompletionQueue();
Y
Yancey 已提交
195

G
gongweibao 已提交
196 197 198 199 200 201 202
  server_ = builder.BuildAndStart();
  LOG(INFO) << "Server listening on " << address_ << std::endl;

  std::function<void()> send_register =
      std::bind(&AsyncGRPCServer::TryToRegisterNewSendOne, this);
  std::function<void()> get_register =
      std::bind(&AsyncGRPCServer::TryToRegisterNewGetOne, this);
203 204
  std::function<void()> prefetch_register =
      std::bind(&AsyncGRPCServer::TryToRegisterNewPrefetchOne, this);
G
gongweibao 已提交
205 206

  t_send_.reset(
Y
Yancey 已提交
207
      new std::thread(std::bind(&AsyncGRPCServer::HandleRequest, this,
G
gongweibao 已提交
208 209 210
                                cq_send_.get(), "cq_send", send_register)));

  t_get_.reset(
Y
Yancey 已提交
211
      new std::thread(std::bind(&AsyncGRPCServer::HandleRequest, this,
G
gongweibao 已提交
212
                                cq_get_.get(), "cq_get", get_register)));
213 214 215
  t_prefetch_.reset(new std::thread(
      std::bind(&AsyncGRPCServer::HandleRequest, this, cq_prefetch_.get(),
                "cq_prefetch", prefetch_register)));
G
gongweibao 已提交
216 217 218 219
  // wait server
  server_->Wait();
  t_send_->join();
  t_get_->join();
220
  t_prefetch_->join();
G
gongweibao 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
}

void AsyncGRPCServer::ShutdownQueue() {
  std::unique_lock<std::mutex> lock(cq_mutex_);
  cq_send_->Shutdown();
  cq_get_->Shutdown();
  is_shut_down_ = true;
}

// This URL explains why shutdown is complicate:
void AsyncGRPCServer::ShutDown() {
  server_->Shutdown();
  ShutdownQueue();
}

void AsyncGRPCServer::TryToRegisterNewSendOne() {
  std::unique_lock<std::mutex> lock(cq_mutex_);
  if (is_shut_down_) {
    return;
  }
241 242
  RequestSend* send = new RequestSend(&service_, cq_send_.get(), scope_,
                                      &var_recv_queue_, dev_ctx_);
Y
Yancey 已提交
243
  VLOG(4) << "Create RequestSend status:" << send->Status();
G
gongweibao 已提交
244 245 246 247 248 249 250
}

void AsyncGRPCServer::TryToRegisterNewGetOne() {
  std::unique_lock<std::mutex> lock(cq_mutex_);
  if (is_shut_down_) {
    return;
  }
T
typhoonzero 已提交
251 252
  RequestGet* get = new RequestGet(&service_, cq_get_.get(), scope_, dev_ctx_,
                                   &var_get_queue_);
Y
Yancey 已提交
253
  VLOG(4) << "Create RequestGet status:" << get->Status();
G
gongweibao 已提交
254 255
}

256
void AsyncGRPCServer::TryToRegisterNewPrefetchOne() {
Q
qiaolongfei 已提交
257
  VLOG(4) << "TryToRegisterNewPrefetchOne in";
258 259 260 261 262 263 264 265 266 267 268
  std::unique_lock<std::mutex> lock(cq_mutex_);
  if (is_shut_down_) {
    return;
  }
  RequestPrefetch* prefetch =
      new RequestPrefetch(&service_, cq_prefetch_.get(), scope_, dev_ctx_,
                          executor_, program_, prefetch_blk_id_);

  VLOG(4) << "Create RequestPrefetch status:" << prefetch->Status();
}

Y
Yancey 已提交
269
// FIXME(typhoonzero): change cq_name to enum.
270
void AsyncGRPCServer::HandleRequest(::grpc::ServerCompletionQueue* cq,
G
gongweibao 已提交
271 272 273 274 275 276 277 278 279 280 281 282
                                    std::string cq_name,
                                    std::function<void()> TryToRegisterNewOne) {
  TryToRegisterNewOne();

  void* tag = NULL;
  bool ok = false;
  while (true) {
    if (!cq->Next(&tag, &ok)) {
      LOG(INFO) << cq_name << " get CompletionQueue shutdown!";
      break;
    }

G
gongweibao 已提交
283
    PADDLE_ENFORCE(tag);
T
typhoonzero 已提交
284 285
    // FIXME(typhoonzero): de-couple the barriers with recv_op
    if (cq_name == "cq_get") WaitCond(1);
T
typhoonzero 已提交
286
    if (cq_name == "cq_send") WaitCond(0);
G
gongweibao 已提交
287 288

    RequestBase* base = (RequestBase*)tag;
G
gongweibao 已提交
289 290 291 292
    // reference:
    // https://github.com/tensorflow/tensorflow/issues/5596
    // https://groups.google.com/forum/#!topic/grpc-io/xftlRy-IQwM
    // https://groups.google.com/forum/#!topic/grpc-io/ywATt88Ef_I
G
gongweibao 已提交
293
    if (!ok) {
Q
qiaolongfei 已提交
294 295
      LOG(WARNING) << cq_name << " recv no regular event:argument name["
                   << base->GetReqName() << "]";
G
gongweibao 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
      TryToRegisterNewOne();
      delete base;
      continue;
    }

    switch (base->Status()) {
      case PROCESS: {
        VLOG(4) << cq_name << " status:" << base->Status();
        TryToRegisterNewOne();
        base->Process();
        break;
      }
      case FINISH: {
        VLOG(4) << cq_name << " status:" << base->Status();
        delete base;
        break;
      }
      default: { assert(false); }
    }
  }
}

T
typhoonzero 已提交
318 319 320 321
void AsyncGRPCServer::WaitCond(int cond) {
  std::unique_lock<std::mutex> lock(this->barrier_mutex_);
  barrier_condition_.wait(lock,
                          [=] { return this->barrier_cond_step_ == cond; });
G
gongweibao 已提交
322 323
}

T
typhoonzero 已提交
324
void AsyncGRPCServer::SetCond(int cond) {
G
gongweibao 已提交
325
  {
T
typhoonzero 已提交
326 327
    std::lock_guard<std::mutex> lock(this->barrier_mutex_);
    barrier_cond_step_ = cond;
G
gongweibao 已提交
328
  }
T
typhoonzero 已提交
329
  barrier_condition_.notify_all();
G
gongweibao 已提交
330 331 332 333 334
}

}  // namespace detail
}  // namespace operators
}  // namespace paddle