grpc_server.cc 11.4 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"
16 17 18

#include <limits>
#include <string>
G
gongweibao 已提交
19

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

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:
32 33 34 35
  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 已提交
36 37
    PADDLE_ENFORCE(cq_);
  }
G
gongweibao 已提交
38 39 40 41 42
  virtual ~RequestBase() {}
  virtual void Process() { assert(false); }

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

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

class RequestSend final : public RequestBase {
 public:
58 59 60 61 62 63 64 65 66
  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 已提交
67 68 69 70
  }

  virtual ~RequestSend() {}

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

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

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

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

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

  virtual ~RequestGet() {}

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

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

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

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

    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 已提交
125 126 127 128
  }

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

134 135 136 137 138 139 140
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,
Y
Yancey1989 已提交
141 142
                           framework::ProgramDesc* program,
                           framework::ExecutorPrepareContext* prefetch_ctx)
143 144 145 146 147
      : RequestBase(service, cq, dev_ctx),
        responder_(&ctx_),
        scope_(scope),
        executor_(executor),
        program_(program),
Y
Yancey1989 已提交
148
        prefetch_ctx_(prefetch_ctx) {
Y
Yancey1989 已提交
149
    request_.reset(new VariableResponse(scope, dev_ctx_));
150
    int method_id = static_cast<int>(detail::GrpcMethod::kPrefetchVariable);
Y
Yancey1989 已提交
151 152
    service_->RequestAsyncUnary(method_id, &ctx_, request_.get(), &responder_,
                                cq_, cq_, this);
153 154 155 156
  }

  virtual ~RequestPrefetch() {}

Y
Yancey1989 已提交
157
  virtual std::string GetReqName() { return request_->Varname(); }
158 159 160

  virtual void Process() {
    // prefetch process...
Y
Yancey1989 已提交
161
    ::grpc::ByteBuffer reply;
162

Y
Yancey1989 已提交
163
    std::string var_name = request_->OutVarname();
164
    VLOG(3) << "prefetch var " << var_name;
Y
Yancey1989 已提交
165 166 167 168
    auto var_desc = program_->Block(0).FindVar(var_name);
    framework::Scope* local_scope = &scope_->NewScope();
    auto* var = local_scope->FindVar(var_name);
    InitializeVariable(var, var_desc->GetType());
Y
Yancey1989 已提交
169
    executor_->RunPreparedContext(prefetch_ctx_, scope_, false, false);
Y
Yancey1989 已提交
170 171

    SerializeToByteBuffer(var_name, var, *dev_ctx_, &reply);
Q
qiaolongfei 已提交
172

Y
Yancey1989 已提交
173
    responder_.Finish(reply, ::grpc::Status::OK, this);
174 175 176 177
    status_ = FINISH;
  }

 protected:
Y
Yancey1989 已提交
178
  std::shared_ptr<VariableResponse> request_;
179 180 181 182
  ServerAsyncResponseWriter<::grpc::ByteBuffer> responder_;
  framework::Scope* scope_;
  framework::Executor* executor_;
  framework::ProgramDesc* program_;
Y
Yancey1989 已提交
183
  framework::ExecutorPrepareContext* prefetch_ctx_;
184 185 186
  int blkid_;
};

T
typhoonzero 已提交
187
void AsyncGRPCServer::WaitClientGet(int count) {
188 189 190 191 192 193
  int fetch_barriers = 0;
  while (fetch_barriers < count) {
    auto msg = var_get_queue_.Pop();
    if (msg.first == FETCH_BARRIER_MESSAGE) {
      fetch_barriers++;
    }
T
typhoonzero 已提交
194 195 196
  }
}

G
gongweibao 已提交
197
void AsyncGRPCServer::RunSyncUpdate() {
198
  ::grpc::ServerBuilder builder;
T
typhoonzero 已提交
199 200
  builder.AddListeningPort(address_, ::grpc::InsecureServerCredentials(),
                           &selected_port_);
G
gongweibao 已提交
201 202
  builder.SetMaxSendMessageSize(std::numeric_limits<int>::max());
  builder.SetMaxReceiveMessageSize(std::numeric_limits<int>::max());
G
gongweibao 已提交
203 204 205 206
  builder.RegisterService(&service_);

  cq_send_ = builder.AddCompletionQueue();
  cq_get_ = builder.AddCompletionQueue();
207
  cq_prefetch_ = builder.AddCompletionQueue();
Y
Yancey 已提交
208

G
gongweibao 已提交
209
  server_ = builder.BuildAndStart();
T
typhoonzero 已提交
210 211
  LOG(INFO) << "Server listening on " << address_
            << " selected port: " << selected_port_;
G
gongweibao 已提交
212 213 214 215 216

  std::function<void()> send_register =
      std::bind(&AsyncGRPCServer::TryToRegisterNewSendOne, this);
  std::function<void()> get_register =
      std::bind(&AsyncGRPCServer::TryToRegisterNewGetOne, this);
217 218
  std::function<void()> prefetch_register =
      std::bind(&AsyncGRPCServer::TryToRegisterNewPrefetchOne, this);
G
gongweibao 已提交
219 220

  t_send_.reset(
Y
Yancey 已提交
221
      new std::thread(std::bind(&AsyncGRPCServer::HandleRequest, this,
G
gongweibao 已提交
222 223 224
                                cq_send_.get(), "cq_send", send_register)));

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

void AsyncGRPCServer::ShutdownQueue() {
  std::unique_lock<std::mutex> lock(cq_mutex_);
  cq_send_->Shutdown();
  cq_get_->Shutdown();
241
  cq_prefetch_->Shutdown();
G
gongweibao 已提交
242 243 244 245
}

// This URL explains why shutdown is complicate:
void AsyncGRPCServer::ShutDown() {
T
typhoonzero 已提交
246
  is_shut_down_ = true;
G
gongweibao 已提交
247
  ShutdownQueue();
T
typhoonzero 已提交
248
  server_->Shutdown();
G
gongweibao 已提交
249 250 251 252 253
}

void AsyncGRPCServer::TryToRegisterNewSendOne() {
  std::unique_lock<std::mutex> lock(cq_mutex_);
  if (is_shut_down_) {
254
    VLOG(3) << "shutdown, do not TryToRegisterNewSendOne";
G
gongweibao 已提交
255 256
    return;
  }
257 258
  RequestSend* send = new RequestSend(&service_, cq_send_.get(), scope_,
                                      &var_recv_queue_, dev_ctx_);
Y
Yancey 已提交
259
  VLOG(4) << "Create RequestSend status:" << send->Status();
G
gongweibao 已提交
260 261 262 263 264
}

void AsyncGRPCServer::TryToRegisterNewGetOne() {
  std::unique_lock<std::mutex> lock(cq_mutex_);
  if (is_shut_down_) {
265
    VLOG(3) << "shutdown, do not TryToRegisterNewGetOne";
G
gongweibao 已提交
266 267
    return;
  }
T
typhoonzero 已提交
268 269
  RequestGet* get = new RequestGet(&service_, cq_get_.get(), scope_, dev_ctx_,
                                   &var_get_queue_);
Y
Yancey 已提交
270
  VLOG(4) << "Create RequestGet status:" << get->Status();
G
gongweibao 已提交
271 272
}

273 274 275
void AsyncGRPCServer::TryToRegisterNewPrefetchOne() {
  std::unique_lock<std::mutex> lock(cq_mutex_);
  if (is_shut_down_) {
276
    VLOG(3) << "shutdown, do not TryToRegisterNewPrefetchOne";
277 278 279 280
    return;
  }
  RequestPrefetch* prefetch =
      new RequestPrefetch(&service_, cq_prefetch_.get(), scope_, dev_ctx_,
Y
Yancey1989 已提交
281
                          executor_, program_, prefetch_ctx_);
282 283 284 285

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

Y
Yancey 已提交
286
// FIXME(typhoonzero): change cq_name to enum.
287
void AsyncGRPCServer::HandleRequest(::grpc::ServerCompletionQueue* cq,
Y
Yi Wang 已提交
288
                                    const std::string& cq_name,
G
gongweibao 已提交
289 290 291 292 293
                                    std::function<void()> TryToRegisterNewOne) {
  TryToRegisterNewOne();

  void* tag = NULL;
  bool ok = false;
294

G
gongweibao 已提交
295
  while (true) {
296
    VLOG(3) << "HandleRequest for " << cq_name << " while in";
G
gongweibao 已提交
297
    if (!cq->Next(&tag, &ok)) {
T
typhoonzero 已提交
298
      LOG(INFO) << cq_name << " CompletionQueue shutdown!";
G
gongweibao 已提交
299 300
      break;
    }
301
    VLOG(3) << "HandleRequest for " << cq_name << " while after Next";
G
gongweibao 已提交
302

G
gongweibao 已提交
303
    PADDLE_ENFORCE(tag);
T
typhoonzero 已提交
304
    // FIXME(typhoonzero): de-couple the barriers with recv_op
T
typhoonzero 已提交
305 306
    if (!is_shut_down_ && cq_name == "cq_get") WaitCond(1);
    if (!is_shut_down_ && cq_name == "cq_send") WaitCond(0);
G
gongweibao 已提交
307

308
    RequestBase* base = reinterpret_cast<RequestBase*>(tag);
G
gongweibao 已提交
309 310 311 312
    // 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 已提交
313
    if (!ok) {
Q
qiaolongfei 已提交
314 315
      LOG(WARNING) << cq_name << " recv no regular event:argument name["
                   << base->GetReqName() << "]";
G
gongweibao 已提交
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
      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 已提交
338 339 340 341
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 已提交
342 343
}

T
typhoonzero 已提交
344
void AsyncGRPCServer::SetCond(int cond) {
G
gongweibao 已提交
345
  {
T
typhoonzero 已提交
346 347
    std::lock_guard<std::mutex> lock(this->barrier_mutex_);
    barrier_cond_step_ = cond;
G
gongweibao 已提交
348
  }
T
typhoonzero 已提交
349
  barrier_condition_.notify_all();
G
gongweibao 已提交
350 351 352 353 354
}

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