blob: 0d81f0b126e94056117dafab00444e136a19e58c [file] [log] [blame]
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08001/*
2 *
Craig Tiller06059952015-02-18 08:34:56 -08003 * Copyright 2015, Google Inc.
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08004 * 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 Tiller1c9a2a92015-02-12 14:10:25 -080052class Server::SyncRequest final : public CompletionQueueTag {
Craig Tillerc4165772015-02-11 10:51:04 -080053 public:
Craig Tiller1c9a2a92015-02-12 14:10:25 -080054 SyncRequest(RpcServiceMethod* method, void* tag)
Craig Tillerc4165772015-02-11 10:51:04 -080055 : method_(method),
56 tag_(tag),
57 has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC ||
58 method->method_type() ==
59 RpcMethod::SERVER_STREAMING),
60 has_response_payload_(method->method_type() == RpcMethod::NORMAL_RPC ||
61 method->method_type() ==
62 RpcMethod::CLIENT_STREAMING) {
63 grpc_metadata_array_init(&request_metadata_);
64 }
65
Craig Tiller1c9a2a92015-02-12 14:10:25 -080066 static SyncRequest* Wait(CompletionQueue* cq, bool* ok) {
Craig Tiller8c8d0aa2015-02-12 11:38:36 -080067 void* tag = nullptr;
Craig Tiller504bd332015-02-11 20:34:33 -080068 *ok = false;
Craig Tillerc4165772015-02-11 10:51:04 -080069 if (!cq->Next(&tag, ok)) {
70 return nullptr;
71 }
Craig Tiller1c9a2a92015-02-12 14:10:25 -080072 auto* mrd = static_cast<SyncRequest*>(tag);
Craig Tillerc4165772015-02-11 10:51:04 -080073 GPR_ASSERT(mrd->in_flight_);
74 return mrd;
75 }
76
Craig Tiller8c8d0aa2015-02-12 11:38:36 -080077 void Request(grpc_server* server) {
Craig Tillerc4165772015-02-11 10:51:04 -080078 GPR_ASSERT(!in_flight_);
79 in_flight_ = true;
80 cq_ = grpc_completion_queue_create();
81 GPR_ASSERT(GRPC_CALL_OK ==
82 grpc_server_request_registered_call(
83 server, tag_, &call_, &deadline_, &request_metadata_,
Craig Tiller8c8d0aa2015-02-12 11:38:36 -080084 has_request_payload_ ? &request_payload_ : nullptr, cq_,
85 this));
Craig Tillerc4165772015-02-11 10:51:04 -080086 }
87
Craig Tiller645466e2015-02-18 09:18:33 -080088 bool FinalizeResult(void** tag, bool* status) override {
Craig Tillerec3257c2015-02-12 15:59:43 -080089 if (!*status) {
90 grpc_completion_queue_destroy(cq_);
91 }
Craig Tiller645466e2015-02-18 09:18:33 -080092 return true;
Craig Tillerec3257c2015-02-12 15:59:43 -080093 }
Craig Tillerc4165772015-02-11 10:51:04 -080094
Craig Tiller1c9a2a92015-02-12 14:10:25 -080095 class CallData final {
Craig Tillerc4165772015-02-11 10:51:04 -080096 public:
Craig Tiller1c9a2a92015-02-12 14:10:25 -080097 explicit CallData(Server* server, SyncRequest* mrd)
Craig Tillerc4165772015-02-11 10:51:04 -080098 : cq_(mrd->cq_),
Craig Tillerbb5227f2015-02-11 13:34:48 -080099 call_(mrd->call_, server, &cq_),
Craig Tillerc4165772015-02-11 10:51:04 -0800100 ctx_(mrd->deadline_, mrd->request_metadata_.metadata,
101 mrd->request_metadata_.count),
102 has_request_payload_(mrd->has_request_payload_),
103 has_response_payload_(mrd->has_response_payload_),
104 request_payload_(mrd->request_payload_),
105 method_(mrd->method_) {
Craig Tiller3d6ceb62015-02-12 14:33:54 -0800106 ctx_.call_ = mrd->call_;
Craig Tillerc4165772015-02-11 10:51:04 -0800107 GPR_ASSERT(mrd->in_flight_);
108 mrd->in_flight_ = false;
109 mrd->request_metadata_.count = 0;
110 }
111
Craig Tillerec3257c2015-02-12 15:59:43 -0800112 ~CallData() {
113 if (has_request_payload_ && request_payload_) {
114 grpc_byte_buffer_destroy(request_payload_);
115 }
116 }
117
Craig Tillerc4165772015-02-11 10:51:04 -0800118 void Run() {
119 std::unique_ptr<google::protobuf::Message> req;
120 std::unique_ptr<google::protobuf::Message> res;
121 if (has_request_payload_) {
122 req.reset(method_->AllocateRequestProto());
123 if (!DeserializeProto(request_payload_, req.get())) {
124 abort(); // for now
125 }
126 }
127 if (has_response_payload_) {
Craig Tiller7c2f3f72015-02-11 13:21:54 -0800128 res.reset(method_->AllocateResponseProto());
Craig Tillerc4165772015-02-11 10:51:04 -0800129 }
Craig Tiller492968f2015-02-18 13:14:03 -0800130 ctx_.BeginCompletionOp(&call_);
Craig Tillerc4165772015-02-11 10:51:04 -0800131 auto status = method_->handler()->RunHandler(
132 MethodHandler::HandlerParameter(&call_, &ctx_, req.get(), res.get()));
133 CallOpBuffer buf;
Craig Tillerbc8e3db2015-02-12 09:56:02 -0800134 if (!ctx_.sent_initial_metadata_) {
135 buf.AddSendInitialMetadata(&ctx_.initial_metadata_);
136 }
Craig Tillerc4165772015-02-11 10:51:04 -0800137 if (has_response_payload_) {
138 buf.AddSendMessage(*res);
139 }
Craig Tiller9dcb0f82015-02-11 15:36:31 -0800140 buf.AddServerSendStatus(&ctx_.trailing_metadata_, status);
Craig Tillerc4165772015-02-11 10:51:04 -0800141 call_.PerformOps(&buf);
142 GPR_ASSERT(cq_.Pluck(&buf));
Craig Tiller492968f2015-02-18 13:14:03 -0800143 void* ignored_tag;
144 bool ignored_ok;
145 cq_.Shutdown();
146 GPR_ASSERT(cq_.Next(&ignored_tag, &ignored_ok) == false);
Craig Tillerc4165772015-02-11 10:51:04 -0800147 }
148
149 private:
150 CompletionQueue cq_;
151 Call call_;
152 ServerContext ctx_;
153 const bool has_request_payload_;
154 const bool has_response_payload_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800155 grpc_byte_buffer* request_payload_;
156 RpcServiceMethod* const method_;
Craig Tillerc4165772015-02-11 10:51:04 -0800157 };
158
159 private:
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800160 RpcServiceMethod* const method_;
161 void* const tag_;
Craig Tillerc4165772015-02-11 10:51:04 -0800162 bool in_flight_ = false;
163 const bool has_request_payload_;
164 const bool has_response_payload_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800165 grpc_call* call_;
Craig Tillerc4165772015-02-11 10:51:04 -0800166 gpr_timespec deadline_;
167 grpc_metadata_array request_metadata_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800168 grpc_byte_buffer* request_payload_;
169 grpc_completion_queue* cq_;
Craig Tillerc4165772015-02-11 10:51:04 -0800170};
171
Craig Tiller42bc87c2015-02-23 08:50:19 -0800172Server::Server(ThreadPoolInterface* thread_pool, bool thread_pool_owned)
vjpaicad5f0a2015-02-18 22:02:52 -0800173 : started_(false),
174 shutdown_(false),
175 num_running_cb_(0),
Craig Tiller42bc87c2015-02-23 08:50:19 -0800176 server_(grpc_server_create(cq_.cq(), nullptr)),
vjpaicad5f0a2015-02-18 22:02:52 -0800177 thread_pool_(thread_pool),
Craig Tiller42bc87c2015-02-23 08:50:19 -0800178 thread_pool_owned_(thread_pool_owned) {}
vjpaicad5f0a2015-02-18 22:02:52 -0800179
180Server::~Server() {
181 std::unique_lock<std::mutex> lock(mu_);
182 if (started_ && !shutdown_) {
183 lock.unlock();
184 Shutdown();
185 } else {
186 lock.unlock();
187 }
188 grpc_server_destroy(server_);
189 if (thread_pool_owned_) {
190 delete thread_pool_;
191 }
192}
193
194bool Server::RegisterService(RpcService* service) {
195 for (int i = 0; i < service->GetMethodCount(); ++i) {
196 RpcServiceMethod* method = service->GetMethod(i);
197 void* tag =
198 grpc_server_register_method(server_, method->name(), nullptr, cq_.cq());
199 if (!tag) {
200 gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
201 method->name());
202 return false;
203 }
204 sync_methods_.emplace_back(method, tag);
205 }
206 return true;
207}
208
209bool Server::RegisterAsyncService(AsynchronousService* service) {
210 GPR_ASSERT(service->dispatch_impl_ == nullptr &&
211 "Can only register an asynchronous service against one server.");
212 service->dispatch_impl_ = this;
213 service->request_args_ = new void* [service->method_count_];
214 for (size_t i = 0; i < service->method_count_; ++i) {
215 void* tag =
216 grpc_server_register_method(server_, service->method_names_[i], nullptr,
217 service->completion_queue()->cq());
218 if (!tag) {
219 gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
220 service->method_names_[i]);
221 return false;
222 }
223 service->request_args_[i] = tag;
224 }
225 return true;
226}
227
Craig Tiller42bc87c2015-02-23 08:50:19 -0800228int Server::AddPort(const grpc::string& addr, ServerCredentials* creds) {
vjpaicad5f0a2015-02-18 22:02:52 -0800229 GPR_ASSERT(!started_);
Craig Tiller42bc87c2015-02-23 08:50:19 -0800230 return creds->AddPortToServer(addr, server_);
vjpaicad5f0a2015-02-18 22:02:52 -0800231}
232
Craig Tiller0db1bef2015-02-09 13:47:39 -0800233bool Server::Start() {
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800234 GPR_ASSERT(!started_);
235 started_ = true;
236 grpc_server_start(server_);
237
238 // Start processing rpcs.
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800239 if (!sync_methods_.empty()) {
240 for (auto& m : sync_methods_) {
Craig Tiller3b29b562015-02-11 12:58:46 -0800241 m.Request(server_);
Craig Tillercbd04852015-02-10 17:39:54 -0800242 }
243
Craig Tiller7c72adc2015-02-09 14:07:26 -0800244 ScheduleCallback();
245 }
Craig Tiller0db1bef2015-02-09 13:47:39 -0800246
247 return true;
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800248}
249
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800250void Server::Shutdown() {
251 {
252 std::unique_lock<std::mutex> lock(mu_);
253 if (started_ && !shutdown_) {
254 shutdown_ = true;
255 grpc_server_shutdown(server_);
Craig Tillerbd217572015-02-11 18:10:56 -0800256 cq_.Shutdown();
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800257
258 // Wait for running callbacks to finish.
259 while (num_running_cb_ != 0) {
260 callback_cv_.wait(lock);
261 }
262 }
263 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800264}
265
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800266void Server::PerformOpsOnCall(CallOpBuffer* buf, Call* call) {
Craig Tillerbb5227f2015-02-11 13:34:48 -0800267 static const size_t MAX_OPS = 8;
268 size_t nops = MAX_OPS;
269 grpc_op ops[MAX_OPS];
270 buf->FillOps(ops, &nops);
271 GPR_ASSERT(GRPC_CALL_OK ==
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800272 grpc_call_start_batch(call->call(), ops, nops, buf));
Craig Tillerbb5227f2015-02-11 13:34:48 -0800273}
274
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800275class Server::AsyncRequest final : public CompletionQueueTag {
276 public:
277 AsyncRequest(Server* server, void* registered_method, ServerContext* ctx,
278 ::google::protobuf::Message* request,
279 ServerAsyncStreamingInterface* stream, CompletionQueue* cq,
280 void* tag)
Craig Tiller3d6ceb62015-02-12 14:33:54 -0800281 : tag_(tag),
282 request_(request),
283 stream_(stream),
284 cq_(cq),
285 ctx_(ctx),
286 server_(server) {
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800287 memset(&array_, 0, sizeof(array_));
288 grpc_server_request_registered_call(
289 server->server_, registered_method, &call_, &deadline_, &array_,
290 request ? &payload_ : nullptr, cq->cq(), this);
291 }
292
Craig Tiller3d6ceb62015-02-12 14:33:54 -0800293 ~AsyncRequest() {
294 if (payload_) {
295 grpc_byte_buffer_destroy(payload_);
296 }
297 grpc_metadata_array_destroy(&array_);
298 }
299
Craig Tiller645466e2015-02-18 09:18:33 -0800300 bool FinalizeResult(void** tag, bool* status) override {
Craig Tiller3d6ceb62015-02-12 14:33:54 -0800301 *tag = tag_;
302 if (*status && request_) {
303 if (payload_) {
Craig Tiller645466e2015-02-18 09:18:33 -0800304 *status = DeserializeProto(payload_, request_);
Craig Tiller3d6ceb62015-02-12 14:33:54 -0800305 } else {
306 *status = false;
307 }
308 }
309 if (*status) {
310 ctx_->deadline_ = Timespec2Timepoint(deadline_);
311 for (size_t i = 0; i < array_.count; i++) {
312 ctx_->client_metadata_.insert(std::make_pair(
313 grpc::string(array_.metadata[i].key),
314 grpc::string(
315 array_.metadata[i].value,
316 array_.metadata[i].value + array_.metadata[i].value_length)));
317 }
318 }
319 ctx_->call_ = call_;
320 Call call(call_, server_, cq_);
Craig Tiller492968f2015-02-18 13:14:03 -0800321 ctx_->BeginCompletionOp(&call);
Craig Tiller645466e2015-02-18 09:18:33 -0800322 // just the pointers inside call are copied here
Craig Tiller3d6ceb62015-02-12 14:33:54 -0800323 stream_->BindCall(&call);
324 delete this;
Craig Tiller645466e2015-02-18 09:18:33 -0800325 return true;
Craig Tiller3d6ceb62015-02-12 14:33:54 -0800326 }
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