blob: 7d198347999e37862c97386c6bdc3a80501db940 [file] [log] [blame]
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08001/*
2 *
3 * Copyright 2014, Google Inc.
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are
8 * met:
9 *
10 * * Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * * Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following disclaimer
14 * in the documentation and/or other materials provided with the
15 * distribution.
16 * * Neither the name of Google Inc. nor the names of its
17 * contributors may be used to endorse or promote products derived from
18 * this software without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 *
32 */
33
34#include <grpc++/server.h>
35#include <utility>
36
37#include <grpc/grpc.h>
yangg9e21f722014-12-08 15:49:52 -080038#include <grpc/grpc_security.h>
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080039#include <grpc/support/log.h>
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080040#include <grpc++/completion_queue.h>
yangg1b151092015-01-09 15:31:05 -080041#include <grpc++/impl/rpc_service_method.h>
Craig Tiller8c8d0aa2015-02-12 11:38:36 -080042#include <grpc++/impl/service_type.h>
Craig Tillerb4701692015-02-09 16:12:00 -080043#include <grpc++/server_context.h>
yangg9e21f722014-12-08 15:49:52 -080044#include <grpc++/server_credentials.h>
Craig Tiller0db1bef2015-02-09 13:47:39 -080045#include <grpc++/thread_pool_interface.h>
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080046
Craig Tillerc4165772015-02-11 10:51:04 -080047#include "src/cpp/proto/proto_utils.h"
Craig Tiller3d6ceb62015-02-12 14:33:54 -080048#include "src/cpp/util/time.h"
Craig Tillerc4165772015-02-11 10:51:04 -080049
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080050namespace grpc {
51
Craig Tiller8c8d0aa2015-02-12 11:38:36 -080052Server::Server(ThreadPoolInterface* thread_pool, bool thread_pool_owned,
53 ServerCredentials* creds)
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080054 : started_(false),
55 shutdown_(false),
56 num_running_cb_(0),
Craig Tiller0db1bef2015-02-09 13:47:39 -080057 thread_pool_(thread_pool),
58 thread_pool_owned_(thread_pool_owned),
yangg9e21f722014-12-08 15:49:52 -080059 secure_(creds != nullptr) {
60 if (creds) {
Craig Tiller8c8d0aa2015-02-12 11:38:36 -080061 server_ =
62 grpc_secure_server_create(creds->GetRawCreds(), cq_.cq(), nullptr);
yangg9e21f722014-12-08 15:49:52 -080063 } else {
Craig Tiller3b29b562015-02-11 12:58:46 -080064 server_ = grpc_server_create(cq_.cq(), nullptr);
yangg9e21f722014-12-08 15:49:52 -080065 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080066}
67
68Server::Server() {
69 // Should not be called.
70 GPR_ASSERT(false);
71}
72
73Server::~Server() {
74 std::unique_lock<std::mutex> lock(mu_);
75 if (started_ && !shutdown_) {
76 lock.unlock();
77 Shutdown();
Craig Tiller061754a2015-02-09 14:56:49 -080078 } else {
79 lock.unlock();
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080080 }
81 grpc_server_destroy(server_);
82 if (thread_pool_owned_) {
83 delete thread_pool_;
84 }
85}
86
Craig Tiller8c8d0aa2015-02-12 11:38:36 -080087bool Server::RegisterService(RpcService* service) {
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080088 for (int i = 0; i < service->GetMethodCount(); ++i) {
Craig Tiller8c8d0aa2015-02-12 11:38:36 -080089 RpcServiceMethod* method = service->GetMethod(i);
90 void* tag =
91 grpc_server_register_method(server_, method->name(), nullptr, cq_.cq());
Craig Tillercbd04852015-02-10 17:39:54 -080092 if (!tag) {
Craig Tillerc4165772015-02-11 10:51:04 -080093 gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
94 method->name());
Craig Tiller0db1bef2015-02-09 13:47:39 -080095 return false;
96 }
Craig Tiller1c9a2a92015-02-12 14:10:25 -080097 sync_methods_.emplace_back(method, tag);
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080098 }
Craig Tiller7c72adc2015-02-09 14:07:26 -080099 return true;
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800100}
101
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800102bool Server::RegisterAsyncService(AsynchronousService* service) {
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800103 GPR_ASSERT(service->dispatch_impl_ == nullptr &&
104 "Can only register an asynchronous service against one server.");
105 service->dispatch_impl_ = this;
106 service->request_args_ = new void* [service->method_count_];
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800107 for (size_t i = 0; i < service->method_count_; ++i) {
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800108 void* tag =
109 grpc_server_register_method(server_, service->method_names_[i], nullptr,
110 service->completion_queue()->cq());
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800111 if (!tag) {
112 gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
113 service->method_names_[i]);
114 return false;
115 }
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800116 service->request_args_[i] = tag;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800117 }
118 return true;
119}
120
121int Server::AddPort(const grpc::string& addr) {
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800122 GPR_ASSERT(!started_);
yangg9e21f722014-12-08 15:49:52 -0800123 if (secure_) {
Craig Tiller0db1bef2015-02-09 13:47:39 -0800124 return grpc_server_add_secure_http2_port(server_, addr.c_str());
yangg9e21f722014-12-08 15:49:52 -0800125 } else {
Craig Tiller0db1bef2015-02-09 13:47:39 -0800126 return grpc_server_add_http2_port(server_, addr.c_str());
yangg9e21f722014-12-08 15:49:52 -0800127 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800128}
129
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800130class Server::SyncRequest final : public CompletionQueueTag {
Craig Tillerc4165772015-02-11 10:51:04 -0800131 public:
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800132 SyncRequest(RpcServiceMethod* method, void* tag)
Craig Tillerc4165772015-02-11 10:51:04 -0800133 : method_(method),
134 tag_(tag),
135 has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC ||
136 method->method_type() ==
137 RpcMethod::SERVER_STREAMING),
138 has_response_payload_(method->method_type() == RpcMethod::NORMAL_RPC ||
139 method->method_type() ==
140 RpcMethod::CLIENT_STREAMING) {
141 grpc_metadata_array_init(&request_metadata_);
142 }
143
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800144 static SyncRequest* Wait(CompletionQueue* cq, bool* ok) {
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800145 void* tag = nullptr;
Craig Tiller504bd332015-02-11 20:34:33 -0800146 *ok = false;
Craig Tillerc4165772015-02-11 10:51:04 -0800147 if (!cq->Next(&tag, ok)) {
148 return nullptr;
149 }
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800150 auto* mrd = static_cast<SyncRequest*>(tag);
Craig Tillerc4165772015-02-11 10:51:04 -0800151 GPR_ASSERT(mrd->in_flight_);
152 return mrd;
153 }
154
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800155 void Request(grpc_server* server) {
Craig Tillerc4165772015-02-11 10:51:04 -0800156 GPR_ASSERT(!in_flight_);
157 in_flight_ = true;
158 cq_ = grpc_completion_queue_create();
159 GPR_ASSERT(GRPC_CALL_OK ==
160 grpc_server_request_registered_call(
161 server, tag_, &call_, &deadline_, &request_metadata_,
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800162 has_request_payload_ ? &request_payload_ : nullptr, cq_,
163 this));
Craig Tillerc4165772015-02-11 10:51:04 -0800164 }
165
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800166 void FinalizeResult(void** tag, bool* status) override {}
Craig Tillerc4165772015-02-11 10:51:04 -0800167
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800168 class CallData final {
Craig Tillerc4165772015-02-11 10:51:04 -0800169 public:
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800170 explicit CallData(Server* server, SyncRequest* mrd)
Craig Tillerc4165772015-02-11 10:51:04 -0800171 : cq_(mrd->cq_),
Craig Tillerbb5227f2015-02-11 13:34:48 -0800172 call_(mrd->call_, server, &cq_),
Craig Tillerc4165772015-02-11 10:51:04 -0800173 ctx_(mrd->deadline_, mrd->request_metadata_.metadata,
174 mrd->request_metadata_.count),
175 has_request_payload_(mrd->has_request_payload_),
176 has_response_payload_(mrd->has_response_payload_),
177 request_payload_(mrd->request_payload_),
178 method_(mrd->method_) {
Craig Tiller3d6ceb62015-02-12 14:33:54 -0800179 ctx_.call_ = mrd->call_;
Craig Tillerc4165772015-02-11 10:51:04 -0800180 GPR_ASSERT(mrd->in_flight_);
181 mrd->in_flight_ = false;
182 mrd->request_metadata_.count = 0;
183 }
184
185 void Run() {
186 std::unique_ptr<google::protobuf::Message> req;
187 std::unique_ptr<google::protobuf::Message> res;
188 if (has_request_payload_) {
189 req.reset(method_->AllocateRequestProto());
190 if (!DeserializeProto(request_payload_, req.get())) {
191 abort(); // for now
192 }
193 }
194 if (has_response_payload_) {
Craig Tiller7c2f3f72015-02-11 13:21:54 -0800195 res.reset(method_->AllocateResponseProto());
Craig Tillerc4165772015-02-11 10:51:04 -0800196 }
197 auto status = method_->handler()->RunHandler(
198 MethodHandler::HandlerParameter(&call_, &ctx_, req.get(), res.get()));
199 CallOpBuffer buf;
Craig Tillerbc8e3db2015-02-12 09:56:02 -0800200 if (!ctx_.sent_initial_metadata_) {
201 buf.AddSendInitialMetadata(&ctx_.initial_metadata_);
202 }
Craig Tillerc4165772015-02-11 10:51:04 -0800203 if (has_response_payload_) {
204 buf.AddSendMessage(*res);
205 }
Craig Tiller9dcb0f82015-02-11 15:36:31 -0800206 buf.AddServerSendStatus(&ctx_.trailing_metadata_, status);
Craig Tiller504bd332015-02-11 20:34:33 -0800207 bool cancelled;
208 buf.AddServerRecvClose(&cancelled);
Craig Tillerc4165772015-02-11 10:51:04 -0800209 call_.PerformOps(&buf);
210 GPR_ASSERT(cq_.Pluck(&buf));
211 }
212
213 private:
214 CompletionQueue cq_;
215 Call call_;
216 ServerContext ctx_;
217 const bool has_request_payload_;
218 const bool has_response_payload_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800219 grpc_byte_buffer* request_payload_;
220 RpcServiceMethod* const method_;
Craig Tillerc4165772015-02-11 10:51:04 -0800221 };
222
223 private:
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800224 RpcServiceMethod* const method_;
225 void* const tag_;
Craig Tillerc4165772015-02-11 10:51:04 -0800226 bool in_flight_ = false;
227 const bool has_request_payload_;
228 const bool has_response_payload_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800229 grpc_call* call_;
Craig Tillerc4165772015-02-11 10:51:04 -0800230 gpr_timespec deadline_;
231 grpc_metadata_array request_metadata_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800232 grpc_byte_buffer* request_payload_;
233 grpc_completion_queue* cq_;
Craig Tillerc4165772015-02-11 10:51:04 -0800234};
235
Craig Tiller0db1bef2015-02-09 13:47:39 -0800236bool Server::Start() {
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800237 GPR_ASSERT(!started_);
238 started_ = true;
239 grpc_server_start(server_);
240
241 // Start processing rpcs.
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800242 if (!sync_methods_.empty()) {
243 for (auto& m : sync_methods_) {
Craig Tiller3b29b562015-02-11 12:58:46 -0800244 m.Request(server_);
Craig Tillercbd04852015-02-10 17:39:54 -0800245 }
246
Craig Tiller7c72adc2015-02-09 14:07:26 -0800247 ScheduleCallback();
248 }
Craig Tiller0db1bef2015-02-09 13:47:39 -0800249
250 return true;
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800251}
252
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800253void Server::Shutdown() {
254 {
255 std::unique_lock<std::mutex> lock(mu_);
256 if (started_ && !shutdown_) {
257 shutdown_ = true;
258 grpc_server_shutdown(server_);
Craig Tillerbd217572015-02-11 18:10:56 -0800259 cq_.Shutdown();
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800260
261 // Wait for running callbacks to finish.
262 while (num_running_cb_ != 0) {
263 callback_cv_.wait(lock);
264 }
265 }
266 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800267}
268
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800269void Server::PerformOpsOnCall(CallOpBuffer* buf, Call* call) {
Craig Tillerbb5227f2015-02-11 13:34:48 -0800270 static const size_t MAX_OPS = 8;
271 size_t nops = MAX_OPS;
272 grpc_op ops[MAX_OPS];
273 buf->FillOps(ops, &nops);
274 GPR_ASSERT(GRPC_CALL_OK ==
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800275 grpc_call_start_batch(call->call(), ops, nops, buf));
Craig Tillerbb5227f2015-02-11 13:34:48 -0800276}
277
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800278class Server::AsyncRequest final : public CompletionQueueTag {
279 public:
280 AsyncRequest(Server* server, void* registered_method, ServerContext* ctx,
281 ::google::protobuf::Message* request,
282 ServerAsyncStreamingInterface* stream, CompletionQueue* cq,
283 void* tag)
Craig Tiller3d6ceb62015-02-12 14:33:54 -0800284 : tag_(tag),
285 request_(request),
286 stream_(stream),
287 cq_(cq),
288 ctx_(ctx),
289 server_(server) {
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800290 memset(&array_, 0, sizeof(array_));
291 grpc_server_request_registered_call(
292 server->server_, registered_method, &call_, &deadline_, &array_,
293 request ? &payload_ : nullptr, cq->cq(), this);
294 }
295
Craig Tiller3d6ceb62015-02-12 14:33:54 -0800296 ~AsyncRequest() {
297 if (payload_) {
298 grpc_byte_buffer_destroy(payload_);
299 }
300 grpc_metadata_array_destroy(&array_);
301 }
302
303 void FinalizeResult(void** tag, bool* status) override {
304 *tag = tag_;
305 if (*status && request_) {
306 if (payload_) {
307 *status = DeserializeProto(payload_, request_);
308 } else {
309 *status = false;
310 }
311 }
312 if (*status) {
313 ctx_->deadline_ = Timespec2Timepoint(deadline_);
314 for (size_t i = 0; i < array_.count; i++) {
315 ctx_->client_metadata_.insert(std::make_pair(
316 grpc::string(array_.metadata[i].key),
317 grpc::string(
318 array_.metadata[i].value,
319 array_.metadata[i].value + array_.metadata[i].value_length)));
320 }
321 }
322 ctx_->call_ = call_;
323 Call call(call_, server_, cq_);
324 stream_->BindCall(&call);
325 delete this;
326 }
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800327
328 private:
329 void* const tag_;
330 ::google::protobuf::Message* const request_;
331 ServerAsyncStreamingInterface* const stream_;
Craig Tiller3d6ceb62015-02-12 14:33:54 -0800332 CompletionQueue* const cq_;
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800333 ServerContext* const ctx_;
Craig Tiller3d6ceb62015-02-12 14:33:54 -0800334 Server* const server_;
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800335 grpc_call* call_ = nullptr;
336 gpr_timespec deadline_;
337 grpc_metadata_array array_;
338 grpc_byte_buffer* payload_ = nullptr;
339};
340
341void Server::RequestAsyncCall(void* registered_method, ServerContext* context,
342 ::google::protobuf::Message* request,
343 ServerAsyncStreamingInterface* stream,
344 CompletionQueue* cq, void* tag) {
345 new AsyncRequest(this, registered_method, context, request, stream, cq, tag);
346}
347
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800348void Server::ScheduleCallback() {
349 {
350 std::unique_lock<std::mutex> lock(mu_);
351 num_running_cb_++;
352 }
Craig Tiller0db1bef2015-02-09 13:47:39 -0800353 thread_pool_->ScheduleCallback(std::bind(&Server::RunRpc, this));
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800354}
355
356void Server::RunRpc() {
357 // Wait for one more incoming rpc.
Craig Tillerc4165772015-02-11 10:51:04 -0800358 bool ok;
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800359 auto* mrd = SyncRequest::Wait(&cq_, &ok);
Craig Tillercbd04852015-02-10 17:39:54 -0800360 if (mrd) {
Craig Tillerbd217572015-02-11 18:10:56 -0800361 ScheduleCallback();
Craig Tillerc4165772015-02-11 10:51:04 -0800362 if (ok) {
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800363 SyncRequest::CallData cd(this, mrd);
Craig Tiller3b29b562015-02-11 12:58:46 -0800364 mrd->Request(server_);
Craig Tillercbd04852015-02-10 17:39:54 -0800365
Craig Tillerc4165772015-02-11 10:51:04 -0800366 cd.Run();
367 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800368 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800369
370 {
371 std::unique_lock<std::mutex> lock(mu_);
372 num_running_cb_--;
373 if (shutdown_) {
374 callback_cv_.notify_all();
375 }
376 }
377}
378
379} // namespace grpc