grpc_server.cc 25.6 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 <unistd.h>
16
#include <limits>
Q
Qiao Longfei 已提交
17
#include <memory>
18
#include <string>
G
gongweibao 已提交
19

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

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

25
DECLARE_bool(rpc_disable_reuse_port);
26
DECLARE_int32(rpc_retry_bind_port);
27

G
gongweibao 已提交
28 29
namespace paddle {
namespace operators {
30
namespace distributed {
31

G
gongweibao 已提交
32 33 34 35 36 37
enum CallStatus { PROCESS = 0, FINISH };

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

G
gongweibao 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63
  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 已提交
64 65 66 67 68 69 70 71 72 73 74 75
  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_)));
  }
76
  virtual std::string GetReqName() = 0;
G
gongweibao 已提交
77 78

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

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

  void Process() override {
C
chengmo 已提交
106
    platform::PushEvent("RequestSend::Process", platform::EventRole::kInnerOp);
107
    std::string varname = GetReqName();
G
gongweibao 已提交
108

109 110
    auto scope = request_->GetMutableLocalScope();
    auto invar = request_->GetVar();
W
Wu Yi 已提交
111
    int trainer_id = request_->GetTrainerId();
112 113 114

    VLOG(4) << "RequestSend var_name:" << varname << " trainer: " << trainer_id;

115
    framework::Variable* outvar = nullptr;
W
Wu Yi 已提交
116
    request_handler_->Handle(varname, scope, invar, &outvar, trainer_id);
X
Xin Pan 已提交
117
    Finish(reply_, &responder_);
C
chengmo 已提交
118
    platform::PopEvent("RequestSend::Process", platform::EventRole::kInnerOp);
G
gongweibao 已提交
119 120 121
  }

 protected:
X
Xin Pan 已提交
122
  sendrecv::VoidMessage reply_;
123
  std::shared_ptr<GRPCVariableResponse> request_;
G
gongweibao 已提交
124 125 126 127 128
  ServerAsyncResponseWriter<sendrecv::VoidMessage> responder_;
};

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

  virtual ~RequestGet() {}

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

143
  void Process() override {
C
chengmo 已提交
144
    platform::PushEvent("RequestGet::Process", platform::EventRole::kInnerOp);
G
gongweibao 已提交
145
    // proc request.
146
    std::string varname = request_.varname();
147
    std::string out_varname = request_.out_varname();
Q
Qiao Longfei 已提交
148
    std::string table_name = request_.table_name();
W
Wu Yi 已提交
149
    int trainer_id = request_.trainer_id();
150 151

    VLOG(4) << "RequestGet " << out_varname << " from " << varname;
152 153

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

Q
Qiao Longfei 已提交
157
    tmp_scope_ = std::move(scope->NewTmpScope());
Q
Qiao Longfei 已提交
158 159
    request_handler_->Handle(varname, tmp_scope_.get(), invar, &outvar,
                             trainer_id, out_varname, table_name);
160

Q
Qiao Longfei 已提交
161
    VLOG(1) << "before SerializeToByteBuffer";
162
    if (outvar) {
163 164 165
      SerializeToByteBuffer(out_varname, outvar, *request_handler_->dev_ctx(),
                            &reply_);
    }
Q
Qiao Longfei 已提交
166
    VLOG(1) << "after SerializeToByteBuffer";
167
    Finish(reply_, &responder_);
C
chengmo 已提交
168
    platform::PopEvent("RequestGet::Process", platform::EventRole::kInnerOp);
169 170 171 172 173
  }

 protected:
  sendrecv::VariableMessage request_;
  ::grpc::ByteBuffer reply_;
Q
Qiao Longfei 已提交
174
  std::unique_ptr<framework::Scope> tmp_scope_;
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
  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 {
C
chengmo 已提交
196 197
    platform::PushEvent("RequestGetNoBarrier::Process",
                        platform::EventRole::kInnerOp);
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
    // 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(),
214
                            &reply_);
215
    }
X
Xin Pan 已提交
216
    Finish(reply_, &responder_);
C
chengmo 已提交
217 218
    platform::PopEvent("RequestGetNoBarrier::Process",
                       platform::EventRole::kInnerOp);
G
gongweibao 已提交
219 220 221 222
  }

 protected:
  sendrecv::VariableMessage request_;
X
Xin Pan 已提交
223
  ::grpc::ByteBuffer reply_;
224
  ServerAsyncResponseWriter<::grpc::ByteBuffer> responder_;
G
gongweibao 已提交
225 226
};

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
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 {
C
chengmo 已提交
248 249
    platform::PushEvent("RequestGetMonomerVariable::Process",
                        platform::EventRole::kInnerOp);
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    // 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_);
C
chengmo 已提交
267 268
    platform::PopEvent("RequestGetMonomerVariable::Process",
                       platform::EventRole::kInnerOp);
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
  }

 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 {
C
chengmo 已提交
299 300
    platform::PushEvent("RequestGetMonomerBarrier::Process",
                        platform::EventRole::kInnerOp);
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    // 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_);
C
chengmo 已提交
316 317
    platform::PopEvent("RequestGetMonomerBarrier::Process",
                       platform::EventRole::kInnerOp);
318 319 320 321 322 323 324 325 326
  }

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

327 328 329
class RequestPrefetch final : public RequestBase {
 public:
  explicit RequestPrefetch(GrpcService::AsyncService* service,
330 331 332
                           ::grpc::ServerCompletionQueue* cq,
                           RequestHandler* request_handler, int req_id)
      : RequestBase(service, cq, request_handler, req_id),
333
        responder_(&ctx_),
334
        local_scope_(nullptr) {
335 336
    request_.reset(new GRPCVariableResponse(request_handler->scope(),
                                            request_handler->dev_ctx(), true));
337 338
    int method_id =
        static_cast<int>(distributed::GrpcMethod::kPrefetchVariable);
X
Xin Pan 已提交
339 340
    service_->RequestAsyncUnary(
        method_id, &ctx_, request_.get(), &responder_, cq_, cq_,
341
        reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
342 343 344 345
  }

  virtual ~RequestPrefetch() {}

346
  std::string GetReqName() override { return request_->Varname(); }
347

348
  void Process() override {
C
chengmo 已提交
349 350
    platform::PushEvent("RequestPrefetch::Process",
                        platform::EventRole::kInnerOp);
351
    // prefetch process...
352 353
    std::string in_var_name = request_->Varname();
    std::string out_var_name = request_->OutVarname();
Q
Qiao Longfei 已提交
354
    std::string table_name = request_->TableName();
W
Wu Yi 已提交
355
    int trainer_id = request_->GetTrainerId();
356

M
minqiyang 已提交
357
    VLOG(4) << "RequestPrefetch, in_var_name: " << in_var_name
358
            << " out_var_name: " << out_var_name << " trainer: " << trainer_id;
359 360

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

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

368
    SerializeToByteBuffer(out_var_name, outvar, *request_handler_->dev_ctx(),
369
                          &reply_);
X
Xin Pan 已提交
370
    Finish(reply_, &responder_);
C
chengmo 已提交
371 372
    platform::PopEvent("RequestPrefetch::Process",
                       platform::EventRole::kInnerOp);
373 374 375
  }

 protected:
376
  std::shared_ptr<GRPCVariableResponse> request_;
X
Xin Pan 已提交
377
  ::grpc::ByteBuffer reply_;
378
  ServerAsyncResponseWriter<::grpc::ByteBuffer> responder_;
379
  framework::Scope* local_scope_;
380 381
};

T
tangwei12 已提交
382 383 384 385 386
class RequestCheckpointNotify final : public RequestBase {
 public:
  explicit RequestCheckpointNotify(GrpcService::AsyncService* service,
                                   ::grpc::ServerCompletionQueue* cq,
                                   RequestHandler* request_handler, int req_id)
T
tangwei12 已提交
387
      : RequestBase(service, cq, request_handler, req_id), responder_(&ctx_) {
388 389
    request_.reset(new GRPCVariableResponse(request_handler->scope(),
                                            request_handler->dev_ctx()));
T
tangwei12 已提交
390 391
    int method_id =
        static_cast<int>(distributed::GrpcMethod::kCheckpointNotify);
T
tangwei12 已提交
392 393 394 395 396 397 398
    service_->RequestAsyncUnary(
        method_id, &ctx_, request_.get(), &responder_, cq_, cq_,
        reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
  }

  virtual ~RequestCheckpointNotify() {}

399
  std::string GetReqName() override { return request_->Varname(); }
T
tangwei12 已提交
400 401

  void Process() override {
C
chengmo 已提交
402 403
    platform::PushEvent("RequestCheckpointNotify::Process",
                        platform::EventRole::kInnerOp);
T
tangwei12 已提交
404
    auto scope = request_->GetMutableLocalScope();
405 406

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

M
minqiyang 已提交
410 411
    VLOG(4) << "RequestCheckpointNotify notify: " << checkpoint_notify
            << ", dir: " << checkpoint_dir;
T
tangwei12 已提交
412

T
tangwei12 已提交
413
    request_handler_->Handle(checkpoint_notify, scope, nullptr, nullptr,
W
Wu Yi 已提交
414
                             trainer_id, checkpoint_dir);
T
tangwei12 已提交
415
    Finish(reply_, &responder_);
C
chengmo 已提交
416 417
    platform::PopEvent("RequestCheckpointNotify::Process",
                       platform::EventRole::kInnerOp);
T
tangwei12 已提交
418
  }
T
tangwei12 已提交
419 420

 protected:
421
  std::shared_ptr<GRPCVariableResponse> request_;
T
tangwei12 已提交
422 423
  sendrecv::VoidMessage reply_;
  ServerAsyncResponseWriter<sendrecv::VoidMessage> responder_;
T
tangwei12 已提交
424
};
T
tangwei12 已提交
425

426 427 428 429 430 431
class RequestNotify final : public RequestBase {
 public:
  explicit RequestNotify(GrpcService::AsyncService* service,
                         ::grpc::ServerCompletionQueue* cq,
                         RequestHandler* request_handler, int req_id)
      : RequestBase(service, cq, request_handler, req_id), responder_(&ctx_) {
1
123malin 已提交
432 433 434
    request_.reset(new GRPCVariableResponse(
        request_handler->scope(), request_handler->dev_ctx(),
        request_handler->distributed_mode()));
435 436 437 438 439 440 441 442 443
    int method_id = static_cast<int>(distributed::GrpcMethod::kRequestNotify);
    service_->RequestAsyncUnary(
        method_id, &ctx_, request_.get(), &responder_, cq_, cq_,
        reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
  }
  virtual ~RequestNotify() {}
  std::string GetReqName() override { return request_->Varname(); }

  void Process() override {
C
chengmo 已提交
444 445
    platform::PushEvent("RequestNotify::Process",
                        platform::EventRole::kInnerOp);
1
123malin 已提交
446 447
    std::string varname = GetReqName();
    VLOG(4) << "RequestNotify var_name:" << varname;
448

1
123malin 已提交
449 450
    auto scope = request_->GetMutableLocalScope();
    auto invar = request_->GetVar();
451
    int trainer_id = request_->GetTrainerId();
1
123malin 已提交
452 453
    framework::Variable* outvar = nullptr;
    request_handler_->Handle(varname, scope, invar, &outvar, trainer_id);
454
    Finish(reply_, &responder_);
C
chengmo 已提交
455
    platform::PopEvent("RequestNotify::Process", platform::EventRole::kInnerOp);
456 457 458 459
  }

 protected:
  sendrecv::VoidMessage reply_;
1
123malin 已提交
460
  std::shared_ptr<GRPCVariableResponse> request_;
461 462 463
  ServerAsyncResponseWriter<sendrecv::VoidMessage> responder_;
};

464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
class RequestSendAndRecv final : public RequestBase {
 public:
  explicit RequestSendAndRecv(GrpcService::AsyncService* service,
                              ::grpc::ServerCompletionQueue* cq,
                              RequestHandler* request_handler, int req_id)
      : RequestBase(service, cq, request_handler, req_id), responder_(&ctx_) {
    request_.reset(new GRPCVariableResponse(
        request_handler->scope(), request_handler->dev_ctx(),
        request_handler->distributed_mode()));

    int method_id =
        static_cast<int>(distributed::GrpcMethod::kRequestSendAndRecv);

    service_->RequestAsyncUnary(
        method_id, &ctx_, request_.get(), &responder_, cq_, cq_,
        reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
  }

  virtual ~RequestSendAndRecv() {}
  std::string GetReqName() override { return request_->Varname(); }

  void Process() override {
C
chengmo 已提交
486 487
    platform::PushEvent("RequestSendAndRecv::Process",
                        platform::EventRole::kInnerOp);
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    std::string in_var_name = request_->Varname();
    std::string out_var_name = request_->OutVarname();
    std::string table_name = request_->TableName();
    int trainer_id = request_->GetTrainerId();

    VLOG(4) << "RequestSendAndRecv, in_var_name: " << in_var_name
            << " out_var_name: " << out_var_name << " trainer: " << trainer_id;
    auto scope = request_->GetMutableLocalScope();
    auto invar = scope->FindVar(in_var_name);
    framework::Variable* outvar = nullptr;
    request_handler_->Handle(in_var_name, scope, invar, &outvar, trainer_id,
                             out_var_name, table_name);
    SerializeToByteBuffer(out_var_name, outvar, *request_handler_->dev_ctx(),
                          &reply_);
    Finish(reply_, &responder_);
C
chengmo 已提交
503 504
    platform::PopEvent("RequestSendAndRecv::Process",
                       platform::EventRole::kInnerOp);
505 506 507 508 509 510 511 512
  }

 protected:
  std::shared_ptr<GRPCVariableResponse> request_;
  ::grpc::ByteBuffer reply_;
  ServerAsyncResponseWriter<::grpc::ByteBuffer> responder_;
};

T
done  
typhoonzero 已提交
513
void AsyncGRPCServer::WaitServerReady() {
514
  VLOG(4) << "AsyncGRPCServer is waiting server ready";
T
update  
typhoonzero 已提交
515
  std::unique_lock<std::mutex> lock(this->mutex_ready_);
T
done  
typhoonzero 已提交
516
  condition_ready_.wait(lock, [=] { return this->ready_ == 1; });
M
minqiyang 已提交
517
  VLOG(4) << "AsyncGRPCServer WaitSeverReady";
T
update  
typhoonzero 已提交
518 519
}

520 521 522 523 524 525 526 527 528 529 530 531 532 533
// 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 {}
};

534
void AsyncGRPCServer::StartServer() {
535 536 537 538 539 540 541 542 543 544 545 546
  for (int i = 0; i < FLAGS_rpc_retry_bind_port; i++) {
    ::grpc::ServerBuilder builder;
    std::unique_ptr<GrpcService::AsyncService> service(
        new GrpcService::AsyncService());
    builder.AddListeningPort(bind_address_, ::grpc::InsecureServerCredentials(),
                             &selected_port_);

    builder.SetMaxSendMessageSize(std::numeric_limits<int>::max());
    builder.SetMaxReceiveMessageSize(std::numeric_limits<int>::max());
    if (FLAGS_rpc_disable_reuse_port) {
      builder.SetOption(
          std::unique_ptr<::grpc::ServerBuilderOption>(new NoReusePortOption));
547
      LOG(INFO) << "set FLAGS_rpc_disable_reuse_port";
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
    }
    builder.RegisterService(service.get());

    for (auto t : rpc_call_map_) {
      rpc_cq_[t.first].reset(builder.AddCompletionQueue().release());
    }

    server_ = builder.BuildAndStart();
    if (selected_port_ != 0) {
      LOG(INFO) << "Server listening on " << bind_address_
                << " successful, selected port: " << selected_port_;
      service_.reset(service.release());
      break;
    }

    LOG(WARNING) << "Server listening on " << bind_address_
                 << " failed, selected port: " << selected_port_
                 << ", retry after 3 seconds!";
G
gongweibao 已提交
566

567
    sleep(3);
568
  }
Y
Yancey 已提交
569

570 571
  PADDLE_ENFORCE_NE(selected_port_, 0, "can't bind to address:%s",
                    bind_address_);
G
gongweibao 已提交
572

573 574 575
  std::function<void(const std::string&, int)> f =
      std::bind(&AsyncGRPCServer::TryToRegisterNewOne, this,
                std::placeholders::_1, std::placeholders::_2);
X
Xin Pan 已提交
576

577 578 579 580 581
  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 已提交
582

583 584 585
    reqs.reserve(kRequestBufSize);

    for (int i = 0; i < kRequestBufSize; i++) {
M
minqiyang 已提交
586
      VLOG(6) << "TryToRegisterNewOne on RPC NAME: " << rpc_name << " I: " << i;
587 588 589 590 591 592
      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 已提交
593
      VLOG(4) << t.first << " creates threads!";
594
    }
X
Xin Pan 已提交
595
  }
596

T
wip  
typhoonzero 已提交
597 598 599 600 601
  {
    std::lock_guard<std::mutex> lock(this->mutex_ready_);
    ready_ = 1;
  }
  condition_ready_.notify_all();
602

G
gongweibao 已提交
603 604
  // wait server
  server_->Wait();
605 606 607 608 609

  for (auto& t : rpc_threads_) {
    auto& threads = t.second;
    for (size_t i = 0; i < threads.size(); ++i) {
      threads[i]->join();
M
minqiyang 已提交
610
      VLOG(4) << t.first << " threads ends!";
611
    }
X
Xin Pan 已提交
612
  }
G
gongweibao 已提交
613 614 615
}

void AsyncGRPCServer::ShutdownQueue() {
616 617
  for (auto& t : rpc_cq_) {
    t.second->Shutdown();
M
minqiyang 已提交
618
    VLOG(4) << t.first << " queue shutdown!";
619
  }
G
gongweibao 已提交
620 621
}

622 623
void AsyncGRPCServer::ShutDownImpl() {
  std::unique_lock<std::mutex> lock(cq_mutex_);
T
typhoonzero 已提交
624
  is_shut_down_ = true;
G
gongweibao 已提交
625
  ShutdownQueue();
626

M
minqiyang 已提交
627
  VLOG(4) << "server_ shutdown!";
T
typhoonzero 已提交
628
  server_->Shutdown();
G
gongweibao 已提交
629 630
}

631 632
void AsyncGRPCServer::TryToRegisterNewOne(const std::string& rpc_name,
                                          int req_id) {
G
gongweibao 已提交
633 634
  std::unique_lock<std::mutex> lock(cq_mutex_);
  if (is_shut_down_) {
M
minqiyang 已提交
635
    VLOG(4) << "shutdown, do not TryToRegisterNewSendOne";
G
gongweibao 已提交
636 637 638
    return;
  }

M
minqiyang 已提交
639 640
  VLOG(4) << "TryToRegisterNewOne on RPC NAME: " << rpc_name
          << " REQ ID: " << req_id;
T
tangwei12 已提交
641

642 643 644 645 646 647
  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) {
648
    b = new RequestSend(service_.get(), cq.get(), handler, req_id);
649
  } else if (rpc_name == kRequestGet) {
650
    b = new RequestGet(service_.get(), cq.get(), handler, req_id);
651 652

  } else if (rpc_name == kRequestGetNoBarrier) {
653
    b = new RequestGetNoBarrier(service_.get(), cq.get(), handler, req_id);
654
  } else if (rpc_name == kRequestGetMonomerVariable) {
655
    b = new RequestGetMonomerVariable(service_.get(), cq.get(), handler, req_id,
656 657
                                      this);
  } else if (rpc_name == kRequestGetMonomerBarrier) {
658
    b = new RequestGetMonomerBarrier(service_.get(), cq.get(), handler, req_id,
659
                                     this);
660
  } else if (rpc_name == kRequestPrefetch) {
661
    b = new RequestPrefetch(service_.get(), cq.get(), handler, req_id);
T
tangwei12 已提交
662
  } else if (rpc_name == kRequestCheckpoint) {
663
    b = new RequestCheckpointNotify(service_.get(), cq.get(), handler, req_id);
664
  } else if (rpc_name == kRequestNotify) {
665
    b = new RequestNotify(service_.get(), cq.get(), handler, req_id);
666 667
  } else if (rpc_name == kRequestSendAndRecv) {
    b = new RequestSendAndRecv(service_.get(), cq.get(), handler, req_id);
668
  } else {
Q
qiaolongfei 已提交
669
    PADDLE_ENFORCE(false, "not supported rpc");
G
gongweibao 已提交
670 671
  }

672
  reqs[req_id] = b;
673

674
  VLOG(4) << "TryToRegisterNewOne status:" << b->Status();
675 676
}

X
Xin Pan 已提交
677
void AsyncGRPCServer::HandleRequest(
678 679
    ::grpc::ServerCompletionQueue* cq, const std::string& rpc_name,
    std::function<void(const std::string&, int)> TryToRegisterNewOne) {
G
gongweibao 已提交
680 681
  void* tag = NULL;
  bool ok = false;
682

G
gongweibao 已提交
683
  while (true) {
M
minqiyang 已提交
684
    VLOG(4) << "HandleRequest " << rpc_name << " wait next";
G
gongweibao 已提交
685
    if (!cq->Next(&tag, &ok)) {
686
      VLOG(4) << "CompletionQueue " << rpc_name << " shutdown!";
G
gongweibao 已提交
687 688
      break;
    }
Q
qiaolongfei 已提交
689

690
    int req_id = static_cast<int>(reinterpret_cast<intptr_t>(tag));
M
minqiyang 已提交
691 692
    VLOG(4) << "HandleRequest " << rpc_name << ", req_id:" << req_id
            << " get next";
G
gongweibao 已提交
693

694
    auto& reqs = rpc_reqs_[rpc_name];
X
Xin Pan 已提交
695 696
    RequestBase* base = nullptr;
    {
697 698 699
      PADDLE_ENFORCE(req_id >= 0 && req_id < kRequestBufSize);
      std::unique_lock<std::mutex> lock(cq_mutex_);
      base = reqs[req_id];
X
Xin Pan 已提交
700
    }
701

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

G
gongweibao 已提交
704 705 706 707
    // 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 已提交
708
    if (!ok) {
G
gongweibao 已提交
709 710
      VLOG(4) << "completion queue:" << rpc_name << " recv no regular event"
              << " context:" << base->Status2String(rpc_name);
711
      TryToRegisterNewOne(rpc_name, req_id);
G
gongweibao 已提交
712 713 714 715 716 717 718 719 720 721
      delete base;
      continue;
    }

    switch (base->Status()) {
      case PROCESS: {
        base->Process();
        break;
      }
      case FINISH: {
722
        TryToRegisterNewOne(rpc_name, req_id);
G
gongweibao 已提交
723 724 725 726 727 728 729 730
        delete base;
        break;
      }
      default: { assert(false); }
    }
  }
}

731
}  // namespace distributed
G
gongweibao 已提交
732 733
}  // namespace operators
}  // namespace paddle