grpc_server.cc 19.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. */

15
#include <limits>
Q
Qiao Longfei 已提交
16
#include <memory>
17
#include <string>
G
gongweibao 已提交
18

W
Wu Yi 已提交
19 20
#include "paddle/fluid/operators/distributed/grpc/grpc_serde.h"
#include "paddle/fluid/operators/distributed/grpc/grpc_server.h"
G
gongweibao 已提交
21

22
using ::grpc::ServerAsyncResponseWriter;
X
Xin Pan 已提交
23

24 25
DECLARE_bool(rpc_disable_reuse_port);

G
gongweibao 已提交
26 27
namespace paddle {
namespace operators {
28
namespace distributed {
G
gongweibao 已提交
29 30 31 32 33 34
enum CallStatus { PROCESS = 0, FINISH };

// reference:
// https://stackoverflow.com/questions/41732884/grpc-multiple-services-in-cpp-async-server
class RequestBase {
 public:
35
  explicit RequestBase(GrpcService::AsyncService* service,
36 37
                       ::grpc::ServerCompletionQueue* cq,
                       RequestHandler* request_handler, int req_id)
Q
qiaolongfei 已提交
38 39 40
      : service_(service),
        cq_(cq),
        status_(PROCESS),
41 42
        request_handler_(request_handler),
        req_id_(req_id) {
G
gongweibao 已提交
43 44
    PADDLE_ENFORCE(cq_);
  }
G
gongweibao 已提交
45
  virtual ~RequestBase() {}
46
  virtual void Process() = 0;
G
gongweibao 已提交
47

G
gongweibao 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60
  std::string Status2String(const std::string& method) {
    std::string status = "Process";
    if (status_ == FINISH) {
      status = "Finish";
    }

    std::ostringstream s;
    s << method << " name:[" << GetReqName() << "]"
      << ", ep:[" << ctx_.peer() << "]"
      << " " << status << " using req_id:" << req_id_;
    return s.str();
  }

X
Xin Pan 已提交
61 62 63 64 65 66 67 68 69 70 71 72
  CallStatus Status() const {
    std::lock_guard<std::mutex> l(status_mu_);
    return status_;
  }

  template <typename T>
  void Finish(const T& reply, ServerAsyncResponseWriter<T>* responder) {
    std::lock_guard<std::mutex> l(status_mu_);
    status_ = FINISH;
    responder->Finish(reply, ::grpc::Status::OK,
                      reinterpret_cast<void*>(static_cast<intptr_t>(req_id_)));
  }
73
  virtual std::string GetReqName() = 0;
G
gongweibao 已提交
74 75

 protected:
X
Xin Pan 已提交
76
  mutable std::mutex status_mu_;
77 78 79
  ::grpc::ServerContext ctx_;
  GrpcService::AsyncService* service_;
  ::grpc::ServerCompletionQueue* cq_;
G
gongweibao 已提交
80
  CallStatus status_;
81 82
  RequestHandler* request_handler_;
  int req_id_;
G
gongweibao 已提交
83 84 85 86
};

class RequestSend final : public RequestBase {
 public:
87
  explicit RequestSend(GrpcService::AsyncService* service,
88 89 90
                       ::grpc::ServerCompletionQueue* cq,
                       RequestHandler* request_handler, int req_id)
      : RequestBase(service, cq, request_handler, req_id), responder_(&ctx_) {
91 92 93
    request_.reset(new GRPCVariableResponse(request_handler->scope(),
                                            request_handler->dev_ctx(),
                                            !request_handler->sync_mode()));
94
    int method_id = static_cast<int>(distributed::GrpcMethod::kSendVariable);
X
Xin Pan 已提交
95 96
    service_->RequestAsyncUnary(
        method_id, &ctx_, request_.get(), &responder_, cq_, cq_,
X
Xin Pan 已提交
97
        reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
G
gongweibao 已提交
98 99
  }
  virtual ~RequestSend() {}
100 101 102 103
  std::string GetReqName() override { return request_->Varname(); }

  void Process() override {
    std::string varname = GetReqName();
M
minqiyang 已提交
104
    VLOG(4) << "RequestSend var_name:" << varname;
G
gongweibao 已提交
105

106 107
    auto scope = request_->GetMutableLocalScope();
    auto invar = request_->GetVar();
W
Wu Yi 已提交
108
    int trainer_id = request_->GetTrainerId();
109
    framework::Variable* outvar = nullptr;
W
Wu Yi 已提交
110
    request_handler_->Handle(varname, scope, invar, &outvar, trainer_id);
X
Xin Pan 已提交
111
    Finish(reply_, &responder_);
G
gongweibao 已提交
112 113 114
  }

 protected:
X
Xin Pan 已提交
115
  sendrecv::VoidMessage reply_;
116
  std::shared_ptr<GRPCVariableResponse> request_;
G
gongweibao 已提交
117 118 119 120 121
  ServerAsyncResponseWriter<sendrecv::VoidMessage> responder_;
};

class RequestGet final : public RequestBase {
 public:
122
  explicit RequestGet(GrpcService::AsyncService* service,
123 124 125
                      ::grpc::ServerCompletionQueue* cq,
                      RequestHandler* request_handler, int req_id)
      : RequestBase(service, cq, request_handler, req_id), responder_(&ctx_) {
126
    auto method_id = static_cast<int>(distributed::GrpcMethod::kGetVariable);
X
Xin Pan 已提交
127 128
    service_->RequestAsyncUnary(
        method_id, &ctx_, &request_, &responder_, cq_, cq_,
129
        reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
G
gongweibao 已提交
130 131 132 133
  }

  virtual ~RequestGet() {}

134
  std::string GetReqName() override { return request_.varname(); }
G
gongweibao 已提交
135

136
  void Process() override {
G
gongweibao 已提交
137
    // proc request.
138
    std::string varname = request_.varname();
139
    std::string out_varname = request_.out_varname();
W
Wu Yi 已提交
140
    int trainer_id = request_.trainer_id();
141 142

    VLOG(4) << "RequestGet " << out_varname << " from " << varname;
143 144

    auto scope = request_handler_->scope();
145
    framework::Variable* invar = nullptr;
146
    framework::Variable* outvar = nullptr;
147

148 149
    request_handler_->Handle(varname, scope, invar, &outvar, trainer_id,
                             out_varname);
150 151

    if (outvar) {
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
      SerializeToByteBuffer(out_varname, outvar, *request_handler_->dev_ctx(),
                            &reply_);
    }
    Finish(reply_, &responder_);
  }

 protected:
  sendrecv::VariableMessage request_;
  ::grpc::ByteBuffer reply_;
  ServerAsyncResponseWriter<::grpc::ByteBuffer> responder_;
};

class RequestGetNoBarrier final : public RequestBase {
 public:
  explicit RequestGetNoBarrier(GrpcService::AsyncService* service,
                               ::grpc::ServerCompletionQueue* cq,
                               RequestHandler* request_handler, int req_id)
      : RequestBase(service, cq, request_handler, req_id), responder_(&ctx_) {
    auto method_id =
        static_cast<int>(distributed::GrpcMethod::kGetVariableNoBarrier);
    service_->RequestAsyncUnary(
        method_id, &ctx_, &request_, &responder_, cq_, cq_,
        reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
  }

  virtual ~RequestGetNoBarrier() {}

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

  void Process() override {
    // proc request.
    std::string varname = request_.varname();
    std::string out_varname = request_.out_varname();
    int trainer_id = request_.trainer_id();

    VLOG(4) << "RequestGetNoBarrier " << out_varname << " from " << varname;

    auto scope = request_handler_->scope();
    framework::Variable* invar = nullptr;
    framework::Variable* outvar = nullptr;

    request_handler_->Handle(varname, scope, invar, &outvar, trainer_id,
                             out_varname);

    if (outvar) {
      SerializeToByteBuffer(out_varname, outvar, *request_handler_->dev_ctx(),
198
                            &reply_);
199
    }
X
Xin Pan 已提交
200
    Finish(reply_, &responder_);
G
gongweibao 已提交
201 202 203 204
  }

 protected:
  sendrecv::VariableMessage request_;
X
Xin Pan 已提交
205
  ::grpc::ByteBuffer reply_;
206
  ServerAsyncResponseWriter<::grpc::ByteBuffer> responder_;
G
gongweibao 已提交
207 208
};

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
class RequestGetMonomerVariable final : public RequestBase {
 public:
  explicit RequestGetMonomerVariable(GrpcService::AsyncService* service,
                                     ::grpc::ServerCompletionQueue* cq,
                                     RequestHandler* request_handler,
                                     int req_id, RPCServer* rpc_server)
      : RequestBase(service, cq, request_handler, req_id),
        responder_(&ctx_),
        rpc_server_(rpc_server) {
    auto method_id =
        static_cast<int>(distributed::GrpcMethod::kGetMonomerVariable);
    service_->RequestAsyncUnary(
        method_id, &ctx_, &request_, &responder_, cq_, cq_,
        reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
  }

  virtual ~RequestGetMonomerVariable() {}

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

  void Process() override {
    // proc request.
    std::string varname = request_.varname();

    rpc_server_->WaitVarCond(varname);
    MonomerHandle h = rpc_server_->GetMonomer(varname);

    auto scope = h.scope_;
    auto invar = scope->FindVar(varname);
    framework::Variable* outvar = nullptr;

    request_handler_->Handle(varname, scope, invar, &outvar,
                             request_.trainer_id());

    if (outvar) {
      SerializeToByteBuffer(varname, outvar, *h.dev_ctx_, &reply_);
    }
    Finish(reply_, &responder_);
  }

 protected:
  sendrecv::VariableMessage request_;
  ::grpc::ByteBuffer reply_;
  ServerAsyncResponseWriter<::grpc::ByteBuffer> responder_;
  RPCServer* rpc_server_{nullptr};
};

class RequestGetMonomerBarrier final : public RequestBase {
 public:
  explicit RequestGetMonomerBarrier(GrpcService::AsyncService* service,
                                    ::grpc::ServerCompletionQueue* cq,
                                    RequestHandler* request_handler, int req_id,
                                    RPCServer* rpc_server)
      : RequestBase(service, cq, request_handler, req_id),
        responder_(&ctx_),
        rpc_server_(rpc_server) {
    auto method_id =
        static_cast<int>(distributed::GrpcMethod::kGetMonomerBarrier);
    service_->RequestAsyncUnary(
        method_id, &ctx_, &request_, &responder_, cq_, cq_,
        reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
  }

  virtual ~RequestGetMonomerBarrier() {}

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

  void Process() override {
    // proc request.
    std::string varname = request_.varname();
    VLOG(4) << "RequestGetMonomerBarrier " << varname;

    rpc_server_->WaitVarCond(varname);
    MonomerHandle h = rpc_server_->GetMonomer(varname);

    framework::Scope* scope = nullptr;
    framework::Variable* invar = nullptr;
    framework::Variable* outvar = nullptr;

    request_handler_->Handle(varname, scope, invar, &outvar,
                             request_.trainer_id());

    Finish(reply_, &responder_);
  }

 protected:
  sendrecv::VariableMessage request_;
  sendrecv::VoidMessage reply_;
  ServerAsyncResponseWriter<sendrecv::VoidMessage> responder_;
  RPCServer* rpc_server_{nullptr};
};

301 302 303
class RequestPrefetch final : public RequestBase {
 public:
  explicit RequestPrefetch(GrpcService::AsyncService* service,
304 305 306
                           ::grpc::ServerCompletionQueue* cq,
                           RequestHandler* request_handler, int req_id)
      : RequestBase(service, cq, request_handler, req_id),
307
        responder_(&ctx_),
308
        local_scope_(nullptr) {
309 310
    request_.reset(new GRPCVariableResponse(request_handler->scope(),
                                            request_handler->dev_ctx(), true));
311 312
    int method_id =
        static_cast<int>(distributed::GrpcMethod::kPrefetchVariable);
X
Xin Pan 已提交
313 314
    service_->RequestAsyncUnary(
        method_id, &ctx_, request_.get(), &responder_, cq_, cq_,
315
        reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
316 317 318 319
  }

  virtual ~RequestPrefetch() {}

320
  std::string GetReqName() override { return request_->Varname(); }
321

322
  void Process() override {
323
    // prefetch process...
324 325
    std::string in_var_name = request_->Varname();
    std::string out_var_name = request_->OutVarname();
Q
Qiao Longfei 已提交
326
    std::string table_name = request_->TableName();
W
Wu Yi 已提交
327
    int trainer_id = request_->GetTrainerId();
M
minqiyang 已提交
328 329
    VLOG(4) << "RequestPrefetch, in_var_name: " << in_var_name
            << " out_var_name: " << out_var_name;
330 331

    auto scope = request_->GetMutableLocalScope();
332
    auto invar = scope->FindVar(in_var_name);
333
    // out var must be created in local scope!
Q
qiaolongfei 已提交
334
    framework::Variable* outvar = scope->Var(out_var_name);
335

W
Wu Yi 已提交
336
    request_handler_->Handle(in_var_name, scope, invar, &outvar, trainer_id,
Q
can run  
Qiao Longfei 已提交
337
                             out_var_name, table_name);
Y
Yancey1989 已提交
338

339
    SerializeToByteBuffer(out_var_name, outvar, *request_handler_->dev_ctx(),
340
                          &reply_);
X
Xin Pan 已提交
341
    Finish(reply_, &responder_);
342 343 344
  }

 protected:
345
  std::shared_ptr<GRPCVariableResponse> request_;
X
Xin Pan 已提交
346
  ::grpc::ByteBuffer reply_;
347
  ServerAsyncResponseWriter<::grpc::ByteBuffer> responder_;
348
  framework::Scope* local_scope_;
349 350
};

T
tangwei12 已提交
351 352 353 354 355
class RequestCheckpointNotify final : public RequestBase {
 public:
  explicit RequestCheckpointNotify(GrpcService::AsyncService* service,
                                   ::grpc::ServerCompletionQueue* cq,
                                   RequestHandler* request_handler, int req_id)
T
tangwei12 已提交
356
      : RequestBase(service, cq, request_handler, req_id), responder_(&ctx_) {
357 358
    request_.reset(new GRPCVariableResponse(request_handler->scope(),
                                            request_handler->dev_ctx()));
T
tangwei12 已提交
359 360
    int method_id =
        static_cast<int>(distributed::GrpcMethod::kCheckpointNotify);
T
tangwei12 已提交
361 362 363 364 365 366 367
    service_->RequestAsyncUnary(
        method_id, &ctx_, request_.get(), &responder_, cq_, cq_,
        reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
  }

  virtual ~RequestCheckpointNotify() {}

368
  std::string GetReqName() override { return request_->Varname(); }
T
tangwei12 已提交
369 370 371

  void Process() override {
    auto scope = request_->GetMutableLocalScope();
372 373

    std::string checkpoint_notify = request_->Varname();
T
tangwei12 已提交
374
    std::string checkpoint_dir = request_->OutVarname();
W
Wu Yi 已提交
375
    int trainer_id = request_->GetTrainerId();
376

M
minqiyang 已提交
377 378
    VLOG(4) << "RequestCheckpointNotify notify: " << checkpoint_notify
            << ", dir: " << checkpoint_dir;
T
tangwei12 已提交
379

T
tangwei12 已提交
380
    request_handler_->Handle(checkpoint_notify, scope, nullptr, nullptr,
W
Wu Yi 已提交
381
                             trainer_id, checkpoint_dir);
T
tangwei12 已提交
382 383
    Finish(reply_, &responder_);
  }
T
tangwei12 已提交
384 385

 protected:
386
  std::shared_ptr<GRPCVariableResponse> request_;
T
tangwei12 已提交
387 388
  sendrecv::VoidMessage reply_;
  ServerAsyncResponseWriter<sendrecv::VoidMessage> responder_;
T
tangwei12 已提交
389
};
T
tangwei12 已提交
390

T
done  
typhoonzero 已提交
391
void AsyncGRPCServer::WaitServerReady() {
392
  VLOG(4) << "AsyncGRPCServer is waiting server ready";
T
update  
typhoonzero 已提交
393
  std::unique_lock<std::mutex> lock(this->mutex_ready_);
T
done  
typhoonzero 已提交
394
  condition_ready_.wait(lock, [=] { return this->ready_ == 1; });
M
minqiyang 已提交
395
  VLOG(4) << "AsyncGRPCServer WaitSeverReady";
T
update  
typhoonzero 已提交
396 397
}

398 399 400 401 402 403 404 405 406 407 408 409 410 411
// Define an option subclass in order to disable SO_REUSEPORT for the
// server socket.
// Come from:
// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc
class NoReusePortOption : public ::grpc::ServerBuilderOption {
 public:
  void UpdateArguments(::grpc::ChannelArguments* args) override {
    args->SetInt(GRPC_ARG_ALLOW_REUSEPORT, 0);
  }

  void UpdatePlugins(std::vector<std::unique_ptr<::grpc::ServerBuilderPlugin>>*
                         plugins) override {}
};

412
void AsyncGRPCServer::StartServer() {
413
  ::grpc::ServerBuilder builder;
414
  builder.AddListeningPort(bind_address_, ::grpc::InsecureServerCredentials(),
T
typhoonzero 已提交
415
                           &selected_port_);
416

G
gongweibao 已提交
417 418
  builder.SetMaxSendMessageSize(std::numeric_limits<int>::max());
  builder.SetMaxReceiveMessageSize(std::numeric_limits<int>::max());
419 420 421 422
  if (FLAGS_rpc_disable_reuse_port) {
    builder.SetOption(
        std::unique_ptr<::grpc::ServerBuilderOption>(new NoReusePortOption));
  }
G
gongweibao 已提交
423 424
  builder.RegisterService(&service_);

425 426 427
  for (auto t : rpc_call_map_) {
    rpc_cq_[t.first].reset(builder.AddCompletionQueue().release());
  }
Y
Yancey 已提交
428

G
gongweibao 已提交
429
  server_ = builder.BuildAndStart();
430
  LOG(INFO) << "Server listening on " << bind_address_
T
typhoonzero 已提交
431
            << " selected port: " << selected_port_;
G
gongweibao 已提交
432

433 434 435
  std::function<void(const std::string&, int)> f =
      std::bind(&AsyncGRPCServer::TryToRegisterNewOne, this,
                std::placeholders::_1, std::placeholders::_2);
X
Xin Pan 已提交
436

437 438 439 440 441
  for (auto& t : rpc_call_map_) {
    auto& rpc_name = t.first;
    auto& cq = rpc_cq_[rpc_name];
    auto threadnum = rpc_thread_num_[rpc_name];
    auto& reqs = rpc_reqs_[rpc_name];
X
Xin Pan 已提交
442

443 444 445
    reqs.reserve(kRequestBufSize);

    for (int i = 0; i < kRequestBufSize; i++) {
M
minqiyang 已提交
446
      VLOG(6) << "TryToRegisterNewOne on RPC NAME: " << rpc_name << " I: " << i;
447 448 449 450 451 452
      TryToRegisterNewOne(rpc_name, i);
    }

    for (int i = 0; i < threadnum; i++) {
      rpc_threads_[rpc_name].emplace_back(new std::thread(std::bind(
          &AsyncGRPCServer::HandleRequest, this, cq.get(), rpc_name, f)));
M
minqiyang 已提交
453
      VLOG(4) << t.first << " creates threads!";
454
    }
X
Xin Pan 已提交
455
  }
456

T
wip  
typhoonzero 已提交
457 458 459 460 461
  {
    std::lock_guard<std::mutex> lock(this->mutex_ready_);
    ready_ = 1;
  }
  condition_ready_.notify_all();
462

G
gongweibao 已提交
463 464
  // wait server
  server_->Wait();
465 466 467 468 469

  for (auto& t : rpc_threads_) {
    auto& threads = t.second;
    for (size_t i = 0; i < threads.size(); ++i) {
      threads[i]->join();
M
minqiyang 已提交
470
      VLOG(4) << t.first << " threads ends!";
471
    }
X
Xin Pan 已提交
472
  }
G
gongweibao 已提交
473 474 475
}

void AsyncGRPCServer::ShutdownQueue() {
476 477
  for (auto& t : rpc_cq_) {
    t.second->Shutdown();
M
minqiyang 已提交
478
    VLOG(4) << t.first << " queue shutdown!";
479
  }
G
gongweibao 已提交
480 481
}

482 483
void AsyncGRPCServer::ShutDownImpl() {
  std::unique_lock<std::mutex> lock(cq_mutex_);
T
typhoonzero 已提交
484
  is_shut_down_ = true;
G
gongweibao 已提交
485
  ShutdownQueue();
486

M
minqiyang 已提交
487
  VLOG(4) << "server_ shutdown!";
T
typhoonzero 已提交
488
  server_->Shutdown();
G
gongweibao 已提交
489 490
}

491 492
void AsyncGRPCServer::TryToRegisterNewOne(const std::string& rpc_name,
                                          int req_id) {
G
gongweibao 已提交
493 494
  std::unique_lock<std::mutex> lock(cq_mutex_);
  if (is_shut_down_) {
M
minqiyang 已提交
495
    VLOG(4) << "shutdown, do not TryToRegisterNewSendOne";
G
gongweibao 已提交
496 497 498
    return;
  }

M
minqiyang 已提交
499 500
  VLOG(4) << "TryToRegisterNewOne on RPC NAME: " << rpc_name
          << " REQ ID: " << req_id;
T
tangwei12 已提交
501

502 503 504 505 506 507 508 509 510
  auto& reqs = rpc_reqs_[rpc_name];
  auto& handler = rpc_call_map_[rpc_name];
  auto& cq = rpc_cq_[rpc_name];

  RequestBase* b = nullptr;
  if (rpc_name == kRequestSend) {
    b = new RequestSend(&service_, cq.get(), handler, req_id);
  } else if (rpc_name == kRequestGet) {
    b = new RequestGet(&service_, cq.get(), handler, req_id);
511 512 513

  } else if (rpc_name == kRequestGetNoBarrier) {
    b = new RequestGetNoBarrier(&service_, cq.get(), handler, req_id);
514 515 516 517 518 519
  } else if (rpc_name == kRequestGetMonomerVariable) {
    b = new RequestGetMonomerVariable(&service_, cq.get(), handler, req_id,
                                      this);
  } else if (rpc_name == kRequestGetMonomerBarrier) {
    b = new RequestGetMonomerBarrier(&service_, cq.get(), handler, req_id,
                                     this);
520 521
  } else if (rpc_name == kRequestPrefetch) {
    b = new RequestPrefetch(&service_, cq.get(), handler, req_id);
T
tangwei12 已提交
522
  } else if (rpc_name == kRequestCheckpoint) {
T
tangwei12 已提交
523
    b = new RequestCheckpointNotify(&service_, cq.get(), handler, req_id);
524
  } else {
Q
qiaolongfei 已提交
525
    PADDLE_ENFORCE(false, "not supported rpc");
G
gongweibao 已提交
526 527
  }

528
  reqs[req_id] = b;
529

530
  VLOG(4) << "TryToRegisterNewOne status:" << b->Status();
531 532
}

X
Xin Pan 已提交
533
void AsyncGRPCServer::HandleRequest(
534 535
    ::grpc::ServerCompletionQueue* cq, const std::string& rpc_name,
    std::function<void(const std::string&, int)> TryToRegisterNewOne) {
G
gongweibao 已提交
536 537
  void* tag = NULL;
  bool ok = false;
538

G
gongweibao 已提交
539
  while (true) {
M
minqiyang 已提交
540
    VLOG(4) << "HandleRequest " << rpc_name << " wait next";
G
gongweibao 已提交
541
    if (!cq->Next(&tag, &ok)) {
G
gongweibao 已提交
542
      LOG(WARNING) << "CompletionQueue " << rpc_name << " shutdown!";
G
gongweibao 已提交
543 544
      break;
    }
Q
qiaolongfei 已提交
545

546
    int req_id = static_cast<int>(reinterpret_cast<intptr_t>(tag));
M
minqiyang 已提交
547 548
    VLOG(4) << "HandleRequest " << rpc_name << ", req_id:" << req_id
            << " get next";
G
gongweibao 已提交
549

550
    auto& reqs = rpc_reqs_[rpc_name];
X
Xin Pan 已提交
551 552
    RequestBase* base = nullptr;
    {
553 554 555
      PADDLE_ENFORCE(req_id >= 0 && req_id < kRequestBufSize);
      std::unique_lock<std::mutex> lock(cq_mutex_);
      base = reqs[req_id];
X
Xin Pan 已提交
556
    }
557

M
minqiyang 已提交
558
    VLOG(3) << base->Status2String(rpc_name);
G
gongweibao 已提交
559

G
gongweibao 已提交
560 561 562 563
    // 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 已提交
564
    if (!ok) {
G
gongweibao 已提交
565 566
      VLOG(4) << "completion queue:" << rpc_name << " recv no regular event"
              << " context:" << base->Status2String(rpc_name);
567
      TryToRegisterNewOne(rpc_name, req_id);
G
gongweibao 已提交
568 569 570 571 572 573 574 575 576 577
      delete base;
      continue;
    }

    switch (base->Status()) {
      case PROCESS: {
        base->Process();
        break;
      }
      case FINISH: {
578
        TryToRegisterNewOne(rpc_name, req_id);
G
gongweibao 已提交
579 580 581 582 583 584 585 586
        delete base;
        break;
      }
      default: { assert(false); }
    }
  }
}

587
}  // namespace distributed
G
gongweibao 已提交
588 589
}  // namespace operators
}  // namespace paddle