grpc_server.cc 13.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 16
#include <limits>
#include <string>
G
gongweibao 已提交
17

18
#include "paddle/fluid/operators/distributed/grpc_serde.h"
19
#include "paddle/fluid/operators/distributed/grpc_server.h"
G
gongweibao 已提交
20

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

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

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

G
gongweibao 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57
  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 已提交
58 59 60 61 62 63 64 65 66 67 68 69
  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_)));
  }
70
  virtual std::string GetReqName() = 0;
G
gongweibao 已提交
71 72

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

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

  void Process() override {
    std::string varname = GetReqName();
101
    VLOG(40) << "RequestSend var_name:" << varname;
G
gongweibao 已提交
102

103 104
    auto scope = request_->GetMutableLocalScope();
    auto invar = request_->GetVar();
W
Wu Yi 已提交
105
    int trainer_id = request_->GetTrainerId();
106 107
    framework::Variable* outvar = nullptr;

W
Wu Yi 已提交
108
    request_handler_->Handle(varname, scope, invar, &outvar, trainer_id);
X
Xin Pan 已提交
109
    Finish(reply_, &responder_);
G
gongweibao 已提交
110 111 112
  }

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

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

  virtual ~RequestGet() {}

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

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

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

W
Wu Yi 已提交
144
    request_handler_->Handle(varname, scope, invar, &outvar, trainer_id);
145 146 147 148

    if (outvar) {
      SerializeToByteBuffer(varname, outvar, *request_handler_->dev_ctx(),
                            &reply_);
149
    }
X
Xin Pan 已提交
150
    Finish(reply_, &responder_);
G
gongweibao 已提交
151 152 153 154
  }

 protected:
  sendrecv::VariableMessage request_;
X
Xin Pan 已提交
155
  ::grpc::ByteBuffer reply_;
156
  ServerAsyncResponseWriter<::grpc::ByteBuffer> responder_;
G
gongweibao 已提交
157 158
};

159 160 161
class RequestPrefetch final : public RequestBase {
 public:
  explicit RequestPrefetch(GrpcService::AsyncService* service,
162 163 164
                           ::grpc::ServerCompletionQueue* cq,
                           RequestHandler* request_handler, int req_id)
      : RequestBase(service, cq, request_handler, req_id),
165
        responder_(&ctx_),
166
        local_scope_(nullptr) {
167 168
    request_.reset(new GRPCVariableResponse(request_handler->scope(),
                                            request_handler->dev_ctx(), true));
169 170
    int method_id =
        static_cast<int>(distributed::GrpcMethod::kPrefetchVariable);
X
Xin Pan 已提交
171 172
    service_->RequestAsyncUnary(
        method_id, &ctx_, request_.get(), &responder_, cq_, cq_,
173
        reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
174 175 176 177
  }

  virtual ~RequestPrefetch() {}

178
  std::string GetReqName() override { return request_->Varname(); }
179

180
  void Process() override {
181
    // prefetch process...
182 183
    std::string in_var_name = request_->Varname();
    std::string out_var_name = request_->OutVarname();
Q
Qiao Longfei 已提交
184
    std::string table_name = request_->TableName();
W
Wu Yi 已提交
185
    int trainer_id = request_->GetTrainerId();
186 187
    VLOG(40) << "RequestPrefetch, in_var_name: " << in_var_name
             << " out_var_name: " << out_var_name;
188 189

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

W
Wu Yi 已提交
194 195
    request_handler_->Handle(in_var_name, scope, invar, &outvar, trainer_id,
                             out_var_name);
Y
Yancey1989 已提交
196

197
    SerializeToByteBuffer(out_var_name, outvar, *request_handler_->dev_ctx(),
198
                          &reply_);
X
Xin Pan 已提交
199
    Finish(reply_, &responder_);
200 201 202
  }

 protected:
203
  std::shared_ptr<GRPCVariableResponse> request_;
X
Xin Pan 已提交
204
  ::grpc::ByteBuffer reply_;
205
  ServerAsyncResponseWriter<::grpc::ByteBuffer> responder_;
206
  framework::Scope* local_scope_;
207 208
};

T
tangwei12 已提交
209 210 211 212 213
class RequestCheckpointNotify final : public RequestBase {
 public:
  explicit RequestCheckpointNotify(GrpcService::AsyncService* service,
                                   ::grpc::ServerCompletionQueue* cq,
                                   RequestHandler* request_handler, int req_id)
T
tangwei12 已提交
214
      : RequestBase(service, cq, request_handler, req_id), responder_(&ctx_) {
215 216
    request_.reset(new GRPCVariableResponse(request_handler->scope(),
                                            request_handler->dev_ctx()));
T
tangwei12 已提交
217 218
    int method_id =
        static_cast<int>(distributed::GrpcMethod::kCheckpointNotify);
T
tangwei12 已提交
219 220 221 222 223 224 225
    service_->RequestAsyncUnary(
        method_id, &ctx_, request_.get(), &responder_, cq_, cq_,
        reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
  }

  virtual ~RequestCheckpointNotify() {}

226
  std::string GetReqName() override { return request_->Varname(); }
T
tangwei12 已提交
227 228 229

  void Process() override {
    auto scope = request_->GetMutableLocalScope();
230 231

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

235 236
    VLOG(40) << "RequestCheckpointNotify notify: " << checkpoint_notify
             << ", dir: " << checkpoint_dir;
T
tangwei12 已提交
237

T
tangwei12 已提交
238
    request_handler_->Handle(checkpoint_notify, scope, nullptr, nullptr,
W
Wu Yi 已提交
239
                             trainer_id, checkpoint_dir);
T
tangwei12 已提交
240 241
    Finish(reply_, &responder_);
  }
T
tangwei12 已提交
242 243

 protected:
244
  std::shared_ptr<GRPCVariableResponse> request_;
T
tangwei12 已提交
245 246
  sendrecv::VoidMessage reply_;
  ServerAsyncResponseWriter<sendrecv::VoidMessage> responder_;
T
tangwei12 已提交
247
};
T
tangwei12 已提交
248

T
done  
typhoonzero 已提交
249
void AsyncGRPCServer::WaitServerReady() {
250
  VLOG(40) << "AsyncGRPCServer is wait server ready";
T
update  
typhoonzero 已提交
251
  std::unique_lock<std::mutex> lock(this->mutex_ready_);
T
done  
typhoonzero 已提交
252
  condition_ready_.wait(lock, [=] { return this->ready_ == 1; });
253
  VLOG(40) << "AsyncGRPCServer WaitSeverReady";
T
update  
typhoonzero 已提交
254 255
}

256
void AsyncGRPCServer::StartServer() {
257
  ::grpc::ServerBuilder builder;
258
  builder.AddListeningPort(bind_address_, ::grpc::InsecureServerCredentials(),
T
typhoonzero 已提交
259
                           &selected_port_);
260

G
gongweibao 已提交
261 262
  builder.SetMaxSendMessageSize(std::numeric_limits<int>::max());
  builder.SetMaxReceiveMessageSize(std::numeric_limits<int>::max());
G
gongweibao 已提交
263 264
  builder.RegisterService(&service_);

265 266 267
  for (auto t : rpc_call_map_) {
    rpc_cq_[t.first].reset(builder.AddCompletionQueue().release());
  }
Y
Yancey 已提交
268

G
gongweibao 已提交
269
  server_ = builder.BuildAndStart();
270
  LOG(INFO) << "Server listening on " << bind_address_
T
typhoonzero 已提交
271
            << " selected port: " << selected_port_;
G
gongweibao 已提交
272

273 274 275
  std::function<void(const std::string&, int)> f =
      std::bind(&AsyncGRPCServer::TryToRegisterNewOne, this,
                std::placeholders::_1, std::placeholders::_2);
X
Xin Pan 已提交
276

277 278 279 280 281
  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 已提交
282

283 284 285
    reqs.reserve(kRequestBufSize);

    for (int i = 0; i < kRequestBufSize; i++) {
286 287
      VLOG(60) << "TryToRegisterNewOne on RPC NAME: " << rpc_name
               << " I: " << i;
288 289 290 291 292 293
      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)));
294
      VLOG(40) << t.first << " creates threads!";
295
    }
X
Xin Pan 已提交
296
  }
297

T
wip  
typhoonzero 已提交
298 299 300 301 302
  {
    std::lock_guard<std::mutex> lock(this->mutex_ready_);
    ready_ = 1;
  }
  condition_ready_.notify_all();
303

G
gongweibao 已提交
304 305
  // wait server
  server_->Wait();
306 307 308 309 310

  for (auto& t : rpc_threads_) {
    auto& threads = t.second;
    for (size_t i = 0; i < threads.size(); ++i) {
      threads[i]->join();
311
      VLOG(40) << t.first << " threads ends!";
312
    }
X
Xin Pan 已提交
313
  }
G
gongweibao 已提交
314 315 316
}

void AsyncGRPCServer::ShutdownQueue() {
317 318
  for (auto& t : rpc_cq_) {
    t.second->Shutdown();
319
    VLOG(40) << t.first << " queue shutdown!";
320
  }
G
gongweibao 已提交
321 322
}

323 324
void AsyncGRPCServer::ShutDownImpl() {
  std::unique_lock<std::mutex> lock(cq_mutex_);
T
typhoonzero 已提交
325
  is_shut_down_ = true;
G
gongweibao 已提交
326
  ShutdownQueue();
327

328
  VLOG(40) << "server_ shutdown!";
T
typhoonzero 已提交
329
  server_->Shutdown();
G
gongweibao 已提交
330 331
}

332 333
void AsyncGRPCServer::TryToRegisterNewOne(const std::string& rpc_name,
                                          int req_id) {
G
gongweibao 已提交
334 335
  std::unique_lock<std::mutex> lock(cq_mutex_);
  if (is_shut_down_) {
336
    VLOG(40) << "shutdown, do not TryToRegisterNewSendOne";
G
gongweibao 已提交
337 338 339
    return;
  }

340 341
  VLOG(40) << "TryToRegisterNewOne on RPC NAME: " << rpc_name
           << " REQ ID: " << req_id;
T
tangwei12 已提交
342

343 344 345 346 347 348 349 350 351 352 353
  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);
  } else if (rpc_name == kRequestPrefetch) {
    b = new RequestPrefetch(&service_, cq.get(), handler, req_id);
T
tangwei12 已提交
354
  } else if (rpc_name == kRequestCheckpoint) {
T
tangwei12 已提交
355
    b = new RequestCheckpointNotify(&service_, cq.get(), handler, req_id);
356
  } else {
Q
qiaolongfei 已提交
357
    PADDLE_ENFORCE(false, "not supported rpc");
G
gongweibao 已提交
358 359
  }

360
  reqs[req_id] = b;
361

362
  VLOG(40) << "Create RequestSend status:" << b->Status();
363 364
}

X
Xin Pan 已提交
365
void AsyncGRPCServer::HandleRequest(
366 367
    ::grpc::ServerCompletionQueue* cq, const std::string& rpc_name,
    std::function<void(const std::string&, int)> TryToRegisterNewOne) {
G
gongweibao 已提交
368 369
  void* tag = NULL;
  bool ok = false;
370

G
gongweibao 已提交
371
  while (true) {
372
    VLOG(40) << "HandleRequest " << rpc_name << " wait next";
G
gongweibao 已提交
373
    if (!cq->Next(&tag, &ok)) {
374
      VLOG(30) << "CompletionQueue " << rpc_name << " shutdown!";
G
gongweibao 已提交
375 376
      break;
    }
Q
qiaolongfei 已提交
377

378
    int req_id = static_cast<int>(reinterpret_cast<intptr_t>(tag));
379 380
    VLOG(40) << "HandleRequest " << rpc_name << ", req_id:" << req_id
             << " get next";
G
gongweibao 已提交
381

382
    auto& reqs = rpc_reqs_[rpc_name];
X
Xin Pan 已提交
383 384
    RequestBase* base = nullptr;
    {
385 386 387
      PADDLE_ENFORCE(req_id >= 0 && req_id < kRequestBufSize);
      std::unique_lock<std::mutex> lock(cq_mutex_);
      base = reqs[req_id];
X
Xin Pan 已提交
388
    }
389

390
    VLOG(30) << base->Status2String(rpc_name);
G
gongweibao 已提交
391

G
gongweibao 已提交
392 393 394 395
    // 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 已提交
396
    if (!ok) {
397
      LOG(WARNING) << "completion queue:" << rpc_name
G
gongweibao 已提交
398 399
                   << " recv no regular event"
                   << " context:" << base->Status2String(rpc_name);
400
      TryToRegisterNewOne(rpc_name, req_id);
G
gongweibao 已提交
401 402 403 404 405 406 407 408 409 410
      delete base;
      continue;
    }

    switch (base->Status()) {
      case PROCESS: {
        base->Process();
        break;
      }
      case FINISH: {
411
        TryToRegisterNewOne(rpc_name, req_id);
G
gongweibao 已提交
412 413 414 415 416 417 418 419
        delete base;
        break;
      }
      default: { assert(false); }
    }
  }
}

420
}  // namespace distributed
G
gongweibao 已提交
421 422
}  // namespace operators
}  // namespace paddle