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();
W
Wu Yi 已提交
101
    VLOG(4) << "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();
W
Wu Yi 已提交
138
    VLOG(4) << "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();
W
Wu Yi 已提交
184
    int trainer_id = request_->GetTrainerId();
W
Wu Yi 已提交
185
    VLOG(4) << "RequestPrefetch, in_var_name: " << in_var_name
186
            << " out_var_name: " << out_var_name;
187 188

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

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

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

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

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

  virtual ~RequestCheckpointNotify() {}

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

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

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

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

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

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

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

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

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

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

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

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

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

282 283 284
    reqs.reserve(kRequestBufSize);

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

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

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

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

void AsyncGRPCServer::ShutdownQueue() {
315 316
  for (auto& t : rpc_cq_) {
    t.second->Shutdown();
W
Wu Yi 已提交
317
    VLOG(4) << t.first << " queue shutdown!";
318
  }
G
gongweibao 已提交
319 320
}

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

W
Wu Yi 已提交
326
  VLOG(4) << "server_ shutdown!";
T
typhoonzero 已提交
327
  server_->Shutdown();
G
gongweibao 已提交
328 329
}

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

T
tangwei12 已提交
338 339
  VLOG(4) << "TryToRegisterNewOne on RPC NAME: " << rpc_name
          << " REQ ID: " << req_id;
T
tangwei12 已提交
340

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

358
  reqs[req_id] = b;
359

360
  VLOG(4) << "Create RequestSend status:" << b->Status();
361 362
}

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

G
gongweibao 已提交
369
  while (true) {
G
gongweibao 已提交
370
    VLOG(4) << "HandleRequest " << rpc_name << " wait next";
G
gongweibao 已提交
371
    if (!cq->Next(&tag, &ok)) {
T
tangwei12 已提交
372
      VLOG(3) << "CompletionQueue " << rpc_name << " shutdown!";
G
gongweibao 已提交
373 374
      break;
    }
Q
qiaolongfei 已提交
375

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

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

G
gongweibao 已提交
388 389
    VLOG(3) << base->Status2String(rpc_name);

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

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

418
}  // namespace distributed
G
gongweibao 已提交
419 420
}  // namespace operators
}  // namespace paddle