grpc_server.cc 11.2 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/detail/grpc_server.h"
G
gongweibao 已提交
19

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

G
gongweibao 已提交
22 23 24 25 26 27 28 29 30
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:
31
  explicit RequestBase(GrpcService::AsyncService* service,
32 33
                       ::grpc::ServerCompletionQueue* cq,
                       RequestHandler* request_handler, int req_id)
Q
qiaolongfei 已提交
34 35 36
      : service_(service),
        cq_(cq),
        status_(PROCESS),
37 38
        request_handler_(request_handler),
        req_id_(req_id) {
G
gongweibao 已提交
39 40
    PADDLE_ENFORCE(cq_);
  }
G
gongweibao 已提交
41
  virtual ~RequestBase() {}
42
  virtual void Process() = 0;
G
gongweibao 已提交
43 44 45

  CallStatus Status() { return status_; }
  void SetStatus(CallStatus status) { status_ = status; }
46
  virtual std::string GetReqName() = 0;
G
gongweibao 已提交
47 48

 protected:
49 50 51
  ::grpc::ServerContext ctx_;
  GrpcService::AsyncService* service_;
  ::grpc::ServerCompletionQueue* cq_;
G
gongweibao 已提交
52
  CallStatus status_;
53 54
  RequestHandler* request_handler_;
  int req_id_;
G
gongweibao 已提交
55 56 57 58
};

class RequestSend final : public RequestBase {
 public:
59
  explicit RequestSend(GrpcService::AsyncService* service,
60 61 62 63 64 65
                       ::grpc::ServerCompletionQueue* cq,
                       RequestHandler* request_handler, int req_id)
      : RequestBase(service, cq, request_handler, req_id), responder_(&ctx_) {
    request_.reset(new VariableResponse(request_handler->scope(),
                                        request_handler->dev_ctx(),
                                        !request_handler->sync_mode()));
66
    int method_id = static_cast<int>(detail::GrpcMethod::kSendVariable);
X
Xin Pan 已提交
67 68
    service_->RequestAsyncUnary(
        method_id, &ctx_, request_.get(), &responder_, cq_, cq_,
X
Xin Pan 已提交
69
        reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
G
gongweibao 已提交
70 71
  }
  virtual ~RequestSend() {}
72 73 74 75 76
  std::string GetReqName() override { return request_->Varname(); }

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

78 79 80 81 82
    auto scope = request_->GetMutableLocalScope();
    auto invar = request_->GetVar();
    framework::Variable* outvar = nullptr;

    request_handler_->Handle(varname, scope, invar, &outvar);
G
gongweibao 已提交
83
    status_ = FINISH;
X
Xin Pan 已提交
84
    responder_.Finish(reply_, ::grpc::Status::OK,
X
Xin Pan 已提交
85
                      reinterpret_cast<void*>(static_cast<intptr_t>(req_id_)));
G
gongweibao 已提交
86 87 88
  }

 protected:
X
Xin Pan 已提交
89
  sendrecv::VoidMessage reply_;
90
  std::shared_ptr<VariableResponse> request_;
G
gongweibao 已提交
91 92 93 94 95
  ServerAsyncResponseWriter<sendrecv::VoidMessage> responder_;
};

class RequestGet final : public RequestBase {
 public:
96
  explicit RequestGet(GrpcService::AsyncService* service,
97 98 99
                      ::grpc::ServerCompletionQueue* cq,
                      RequestHandler* request_handler, int req_id)
      : RequestBase(service, cq, request_handler, req_id), responder_(&ctx_) {
Q
qiaolongfei 已提交
100
    auto method_id = static_cast<int>(detail::GrpcMethod::kGetVariable);
X
Xin Pan 已提交
101 102
    service_->RequestAsyncUnary(
        method_id, &ctx_, &request_, &responder_, cq_, cq_,
103
        reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
G
gongweibao 已提交
104 105 106 107
  }

  virtual ~RequestGet() {}

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

110
  void Process() override {
G
gongweibao 已提交
111
    // proc request.
112 113 114 115 116 117
    std::string varname = request_.varname();
    VLOG(3) << "RequestGet " << varname;

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

119 120 121 122 123
    request_handler_->Handle(varname, scope, invar, &outvar);

    if (outvar) {
      SerializeToByteBuffer(varname, outvar, *request_handler_->dev_ctx(),
                            &reply_);
124
    }
G
gongweibao 已提交
125
    status_ = FINISH;
X
Xin Pan 已提交
126
    responder_.Finish(reply_, ::grpc::Status::OK,
X
Xin Pan 已提交
127
                      reinterpret_cast<void*>(static_cast<intptr_t>(req_id_)));
G
gongweibao 已提交
128 129 130 131
  }

 protected:
  sendrecv::VariableMessage request_;
X
Xin Pan 已提交
132
  ::grpc::ByteBuffer reply_;
133
  ServerAsyncResponseWriter<::grpc::ByteBuffer> responder_;
G
gongweibao 已提交
134 135
};

136 137 138
class RequestPrefetch final : public RequestBase {
 public:
  explicit RequestPrefetch(GrpcService::AsyncService* service,
139 140 141
                           ::grpc::ServerCompletionQueue* cq,
                           RequestHandler* request_handler, int req_id)
      : RequestBase(service, cq, request_handler, req_id),
142
        responder_(&ctx_),
143 144 145
        local_scope_(nullptr) {
    request_.reset(new VariableResponse(request_handler->scope(),
                                        request_handler->dev_ctx(), true));
146
    int method_id = static_cast<int>(detail::GrpcMethod::kPrefetchVariable);
X
Xin Pan 已提交
147 148
    service_->RequestAsyncUnary(
        method_id, &ctx_, request_.get(), &responder_, cq_, cq_,
149
        reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
150 151 152 153
  }

  virtual ~RequestPrefetch() {}

154
  std::string GetReqName() override { return request_->Varname(); }
155

156
  void Process() override {
157
    // prefetch process...
158 159 160
    std::string in_var_name = request_->Varname();
    std::string out_var_name = request_->OutVarname();
    VLOG(3) << "in_var_name: " << in_var_name
Q
qiaolongfei 已提交
161
            << "out_var_name: " << out_var_name
162
            << " RequestPrefetch: " << out_var_name;
163 164

    auto scope = request_->GetMutableLocalScope();
165
    auto invar = scope->FindVar(in_var_name);
Q
qiaolongfei 已提交
166
    framework::Variable* outvar = scope->FindVar(out_var_name);
167

Q
qiaolongfei 已提交
168
    request_handler_->Handle(in_var_name, scope, invar, &outvar, out_var_name);
Y
Yancey1989 已提交
169

170
    SerializeToByteBuffer(out_var_name, outvar, *request_handler_->dev_ctx(),
171
                          &reply_);
X
Xin Pan 已提交
172 173
    responder_.Finish(reply_, ::grpc::Status::OK,
                      reinterpret_cast<void*>(static_cast<intptr_t>(req_id_)));
W
Wu Yi 已提交
174
    status_ = FINISH;
175 176 177
  }

 protected:
Y
Yancey1989 已提交
178
  std::shared_ptr<VariableResponse> request_;
X
Xin Pan 已提交
179
  ::grpc::ByteBuffer reply_;
180
  ServerAsyncResponseWriter<::grpc::ByteBuffer> responder_;
181
  framework::Scope* local_scope_;
182 183
};

T
done  
typhoonzero 已提交
184
void AsyncGRPCServer::WaitServerReady() {
185
  VLOG(3) << "AsyncGRPCServer is wait server ready";
T
update  
typhoonzero 已提交
186
  std::unique_lock<std::mutex> lock(this->mutex_ready_);
T
done  
typhoonzero 已提交
187
  condition_ready_.wait(lock, [=] { return this->ready_ == 1; });
188
  VLOG(3) << "AsyncGRPCServer WaitSeverReady";
T
update  
typhoonzero 已提交
189 190
}

191
void AsyncGRPCServer::StartServer() {
192
  ::grpc::ServerBuilder builder;
193
  builder.AddListeningPort(bind_address_, ::grpc::InsecureServerCredentials(),
T
typhoonzero 已提交
194
                           &selected_port_);
195

G
gongweibao 已提交
196 197
  builder.SetMaxSendMessageSize(std::numeric_limits<int>::max());
  builder.SetMaxReceiveMessageSize(std::numeric_limits<int>::max());
G
gongweibao 已提交
198 199
  builder.RegisterService(&service_);

200 201 202
  for (auto t : rpc_call_map_) {
    rpc_cq_[t.first].reset(builder.AddCompletionQueue().release());
  }
Y
Yancey 已提交
203

G
gongweibao 已提交
204
  server_ = builder.BuildAndStart();
205
  LOG(INFO) << "Server listening on " << bind_address_
T
typhoonzero 已提交
206
            << " selected port: " << selected_port_;
G
gongweibao 已提交
207

208 209 210
  std::function<void(const std::string&, int)> f =
      std::bind(&AsyncGRPCServer::TryToRegisterNewOne, this,
                std::placeholders::_1, std::placeholders::_2);
X
Xin Pan 已提交
211

212 213 214 215 216
  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 已提交
217

218 219 220 221 222 223 224 225 226 227 228
    reqs.reserve(kRequestBufSize);

    for (int i = 0; i < kRequestBufSize; i++) {
      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)));
      VLOG(3) << t.first << " creates threads!";
    }
X
Xin Pan 已提交
229
  }
230

T
wip  
typhoonzero 已提交
231 232 233 234 235
  {
    std::lock_guard<std::mutex> lock(this->mutex_ready_);
    ready_ = 1;
  }
  condition_ready_.notify_all();
236

G
gongweibao 已提交
237 238
  // wait server
  server_->Wait();
239 240 241 242 243 244 245

  for (auto& t : rpc_threads_) {
    auto& threads = t.second;
    for (size_t i = 0; i < threads.size(); ++i) {
      threads[i]->join();
      VLOG(3) << t.first << " threads ends!";
    }
X
Xin Pan 已提交
246
  }
G
gongweibao 已提交
247 248 249
}

void AsyncGRPCServer::ShutdownQueue() {
250 251 252 253
  for (auto& t : rpc_cq_) {
    t.second->Shutdown();
    VLOG(3) << t.first << " shutdown!";
  }
G
gongweibao 已提交
254 255
}

256 257
void AsyncGRPCServer::ShutDownImpl() {
  std::unique_lock<std::mutex> lock(cq_mutex_);
T
typhoonzero 已提交
258
  is_shut_down_ = true;
G
gongweibao 已提交
259
  ShutdownQueue();
260 261

  VLOG(3) << "server_ shutdown!";
T
typhoonzero 已提交
262
  server_->Shutdown();
G
gongweibao 已提交
263 264
}

265 266
void AsyncGRPCServer::TryToRegisterNewOne(const std::string& rpc_name,
                                          int req_id) {
G
gongweibao 已提交
267 268
  std::unique_lock<std::mutex> lock(cq_mutex_);
  if (is_shut_down_) {
269
    VLOG(3) << "shutdown, do not TryToRegisterNewSendOne";
G
gongweibao 已提交
270 271 272
    return;
  }

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
  VLOG(4) << "register send rpc_name:" << rpc_name
          << ", handler:" << rpc_call_map_[kRequestSend];

  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);
  } else {
Q
qiaolongfei 已提交
288
    PADDLE_ENFORCE(false, "not supported rpc");
G
gongweibao 已提交
289 290
  }

291
  reqs[req_id] = b;
292

293
  VLOG(4) << "Create RequestSend status:" << b->Status();
294 295
}

X
Xin Pan 已提交
296
void AsyncGRPCServer::HandleRequest(
297 298
    ::grpc::ServerCompletionQueue* cq, const std::string& rpc_name,
    std::function<void(const std::string&, int)> TryToRegisterNewOne) {
G
gongweibao 已提交
299 300
  void* tag = NULL;
  bool ok = false;
301

G
gongweibao 已提交
302
  while (true) {
303
    VLOG(3) << "HandleRequest " << rpc_name << " wait next";
G
gongweibao 已提交
304
    if (!cq->Next(&tag, &ok)) {
305
      LOG(INFO) << "CompletionQueue " << rpc_name << " shutdown!";
G
gongweibao 已提交
306 307
      break;
    }
Q
qiaolongfei 已提交
308

309 310 311
    int req_id = static_cast<int>(reinterpret_cast<intptr_t>(tag));
    VLOG(3) << "HandleRequest " << rpc_name << ", req_id:" << req_id
            << " get next";
G
gongweibao 已提交
312

313
    auto& reqs = rpc_reqs_[rpc_name];
X
Xin Pan 已提交
314 315
    RequestBase* base = nullptr;
    {
316 317 318
      PADDLE_ENFORCE(req_id >= 0 && req_id < kRequestBufSize);
      std::unique_lock<std::mutex> lock(cq_mutex_);
      base = reqs[req_id];
X
Xin Pan 已提交
319
    }
320

G
gongweibao 已提交
321 322 323 324
    // 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 已提交
325
    if (!ok) {
326 327
      LOG(WARNING) << "completion queue:" << rpc_name
                   << " recv no regular event:argument name["
Q
qiaolongfei 已提交
328
                   << base->GetReqName() << "]";
329
      TryToRegisterNewOne(rpc_name, req_id);
G
gongweibao 已提交
330 331 332 333
      delete base;
      continue;
    }

334 335 336
    VLOG(3) << "queue id:" << rpc_name << ", req_id:" << req_id
            << ", status:" << base->Status();

G
gongweibao 已提交
337 338 339 340 341 342
    switch (base->Status()) {
      case PROCESS: {
        base->Process();
        break;
      }
      case FINISH: {
343
        TryToRegisterNewOne(rpc_name, req_id);
G
gongweibao 已提交
344 345 346 347 348 349 350 351 352 353 354
        delete base;
        break;
      }
      default: { assert(false); }
    }
  }
}

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