blob: 76f89716310c9b49069228577f014471d38c00a9 [file] [log] [blame]
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08001/*
2 *
Craig Tiller6169d5f2016-03-31 07:46:18 -07003 * 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>
yang-g9e2f90c2015-08-21 15:35:03 -070035
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080036#include <utility>
37
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080038#include <grpc++/completion_queue.h>
yang-g9e2f90c2015-08-21 15:35:03 -070039#include <grpc++/generic/async_generic_service.h>
David Garcia Quintase1300de2016-01-27 18:41:26 -080040#include <grpc++/impl/codegen/completion_queue_tag.h>
41#include <grpc++/impl/grpc_library.h>
Craig Tiller15f383c2016-01-07 12:45:32 -080042#include <grpc++/impl/method_handler_impl.h>
yangg1b151092015-01-09 15:31:05 -080043#include <grpc++/impl/rpc_service_method.h>
Craig Tiller8c8d0aa2015-02-12 11:38:36 -080044#include <grpc++/impl/service_type.h>
Julien Boeuf5be92a32015-08-28 16:28:18 -070045#include <grpc++/security/server_credentials.h>
David Garcia Quintase1300de2016-01-27 18:41:26 -080046#include <grpc++/server_context.h>
yang-g9e2f90c2015-08-21 15:35:03 -070047#include <grpc++/support/time.h>
David Garcia Quintase1300de2016-01-27 18:41:26 -080048#include <grpc/grpc.h>
49#include <grpc/support/alloc.h>
50#include <grpc/support/log.h>
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080051
Craig Tiller9533d042016-03-25 17:11:06 -070052#include "src/core/lib/profiling/timers.h"
Vijay Paie8a7e302015-08-24 10:52:33 -070053#include "src/cpp/server/thread_pool_interface.h"
Craig Tillerc4165772015-02-11 10:51:04 -080054
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080055namespace grpc {
56
Craig Tiller7221d992015-11-24 06:59:33 -080057class DefaultGlobalCallbacks GRPC_FINAL : public Server::GlobalCallbacks {
58 public:
Bogdan Drutu618051c2016-01-14 08:54:43 -080059 ~DefaultGlobalCallbacks() GRPC_OVERRIDE {}
Craig Tiller7221d992015-11-24 06:59:33 -080060 void PreSynchronousRequest(ServerContext* context) GRPC_OVERRIDE {}
61 void PostSynchronousRequest(ServerContext* context) GRPC_OVERRIDE {}
62};
63
Craig Tiller64616492016-01-26 14:16:20 -080064static std::shared_ptr<Server::GlobalCallbacks> g_callbacks = nullptr;
Craig Tiller8352b9e2015-12-02 11:43:40 -080065static gpr_once g_once_init_callbacks = GPR_ONCE_INIT;
66
Craig Tiller8352b9e2015-12-02 11:43:40 -080067static void InitGlobalCallbacks() {
68 if (g_callbacks == nullptr) {
Craig Tiller64616492016-01-26 14:16:20 -080069 g_callbacks.reset(new DefaultGlobalCallbacks());
Craig Tiller8352b9e2015-12-02 11:43:40 -080070 }
71}
Craig Tiller7221d992015-11-24 06:59:33 -080072
Craig Tiller8f7bff72015-08-17 13:23:14 -070073class Server::UnimplementedAsyncRequestContext {
74 protected:
75 UnimplementedAsyncRequestContext() : generic_stream_(&server_context_) {}
76
77 GenericServerContext server_context_;
78 GenericServerAsyncReaderWriter generic_stream_;
79};
80
81class Server::UnimplementedAsyncRequest GRPC_FINAL
82 : public UnimplementedAsyncRequestContext,
83 public GenericAsyncRequest {
84 public:
85 UnimplementedAsyncRequest(Server* server, ServerCompletionQueue* cq)
86 : GenericAsyncRequest(server, &server_context_, &generic_stream_, cq, cq,
87 NULL, false),
88 server_(server),
89 cq_(cq) {}
90
91 bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE;
92
93 ServerContext* context() { return &server_context_; }
94 GenericServerAsyncReaderWriter* stream() { return &generic_stream_; }
95
96 private:
97 Server* const server_;
98 ServerCompletionQueue* const cq_;
99};
100
101typedef SneakyCallOpSet<CallOpSendInitialMetadata, CallOpServerSendStatus>
102 UnimplementedAsyncResponseOp;
103class Server::UnimplementedAsyncResponse GRPC_FINAL
104 : public UnimplementedAsyncResponseOp {
105 public:
106 UnimplementedAsyncResponse(UnimplementedAsyncRequest* request);
107 ~UnimplementedAsyncResponse() { delete request_; }
108
109 bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE {
110 bool r = UnimplementedAsyncResponseOp::FinalizeResult(tag, status);
111 delete this;
112 return r;
113 }
114
115 private:
116 UnimplementedAsyncRequest* const request_;
117};
118
Craig Tillerbce999f2015-05-27 09:55:51 -0700119class Server::ShutdownRequest GRPC_FINAL : public CompletionQueueTag {
120 public:
121 bool FinalizeResult(void** tag, bool* status) {
122 delete this;
123 return false;
124 }
125};
126
Craig Tillercf133f42015-02-26 14:05:56 -0800127class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag {
Craig Tillerc4165772015-02-11 10:51:04 -0800128 public:
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800129 SyncRequest(RpcServiceMethod* method, void* tag)
Craig Tillerc4165772015-02-11 10:51:04 -0800130 : method_(method),
131 tag_(tag),
Craig Tillercf133f42015-02-26 14:05:56 -0800132 in_flight_(false),
Craig Tillerc4165772015-02-11 10:51:04 -0800133 has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC ||
134 method->method_type() ==
135 RpcMethod::SERVER_STREAMING),
yang-g9b7757d2015-08-13 11:15:53 -0700136 call_details_(nullptr),
Vijay Paiced73bd2015-06-17 10:23:28 -0700137 cq_(nullptr) {
Craig Tillerc4165772015-02-11 10:51:04 -0800138 grpc_metadata_array_init(&request_metadata_);
139 }
140
yang-g9b7757d2015-08-13 11:15:53 -0700141 ~SyncRequest() {
142 if (call_details_) {
143 delete call_details_;
144 }
145 grpc_metadata_array_destroy(&request_metadata_);
146 }
Yang Gao7b49a772015-05-28 14:07:54 -0700147
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800148 static SyncRequest* Wait(CompletionQueue* cq, bool* ok) {
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800149 void* tag = nullptr;
Craig Tiller504bd332015-02-11 20:34:33 -0800150 *ok = false;
Craig Tillerc4165772015-02-11 10:51:04 -0800151 if (!cq->Next(&tag, ok)) {
152 return nullptr;
153 }
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800154 auto* mrd = static_cast<SyncRequest*>(tag);
Craig Tillerc4165772015-02-11 10:51:04 -0800155 GPR_ASSERT(mrd->in_flight_);
156 return mrd;
157 }
158
Craig Tillere50e5cb2015-08-18 12:44:57 -0700159 static bool AsyncWait(CompletionQueue* cq, SyncRequest** req, bool* ok,
160 gpr_timespec deadline) {
161 void* tag = nullptr;
162 *ok = false;
163 switch (cq->AsyncNext(&tag, ok, deadline)) {
164 case CompletionQueue::TIMEOUT:
165 *req = nullptr;
166 return true;
167 case CompletionQueue::SHUTDOWN:
168 *req = nullptr;
169 return false;
170 case CompletionQueue::GOT_EVENT:
171 *req = static_cast<SyncRequest*>(tag);
172 GPR_ASSERT((*req)->in_flight_);
173 return true;
174 }
yang-gb063c872015-10-07 11:40:13 -0700175 GPR_UNREACHABLE_CODE(return false);
Craig Tillere50e5cb2015-08-18 12:44:57 -0700176 }
177
Nicolas "Pixel" Nobleebb51402015-07-23 02:41:33 +0200178 void SetupRequest() { cq_ = grpc_completion_queue_create(nullptr); }
Vijay Paiced73bd2015-06-17 10:23:28 -0700179
180 void TeardownRequest() {
181 grpc_completion_queue_destroy(cq_);
182 cq_ = nullptr;
183 }
184
Craig Tillerf9e6adf2015-05-06 11:45:59 -0700185 void Request(grpc_server* server, grpc_completion_queue* notify_cq) {
Vijay Paiced73bd2015-06-17 10:23:28 -0700186 GPR_ASSERT(cq_ && !in_flight_);
Craig Tillerc4165772015-02-11 10:51:04 -0800187 in_flight_ = true;
yang-g9b7757d2015-08-13 11:15:53 -0700188 if (tag_) {
189 GPR_ASSERT(GRPC_CALL_OK ==
190 grpc_server_request_registered_call(
191 server, tag_, &call_, &deadline_, &request_metadata_,
192 has_request_payload_ ? &request_payload_ : nullptr, cq_,
193 notify_cq, this));
194 } else {
195 if (!call_details_) {
196 call_details_ = new grpc_call_details;
197 grpc_call_details_init(call_details_);
198 }
199 GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call(
200 server, &call_, call_details_,
201 &request_metadata_, cq_, notify_cq, this));
202 }
Craig Tillerc4165772015-02-11 10:51:04 -0800203 }
204
Craig Tillercf133f42015-02-26 14:05:56 -0800205 bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE {
Craig Tillerec3257c2015-02-12 15:59:43 -0800206 if (!*status) {
207 grpc_completion_queue_destroy(cq_);
208 }
yang-g9b7757d2015-08-13 11:15:53 -0700209 if (call_details_) {
210 deadline_ = call_details_->deadline;
211 grpc_call_details_destroy(call_details_);
212 grpc_call_details_init(call_details_);
213 }
Craig Tiller645466e2015-02-18 09:18:33 -0800214 return true;
Craig Tillerec3257c2015-02-12 15:59:43 -0800215 }
Craig Tillerc4165772015-02-11 10:51:04 -0800216
Craig Tillercf133f42015-02-26 14:05:56 -0800217 class CallData GRPC_FINAL {
Craig Tillerc4165772015-02-11 10:51:04 -0800218 public:
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800219 explicit CallData(Server* server, SyncRequest* mrd)
Craig Tillerc4165772015-02-11 10:51:04 -0800220 : cq_(mrd->cq_),
Yang Gao3921c562015-04-30 16:07:06 -0700221 call_(mrd->call_, server, &cq_, server->max_message_size_),
Craig Tillerc4165772015-02-11 10:51:04 -0800222 ctx_(mrd->deadline_, mrd->request_metadata_.metadata,
223 mrd->request_metadata_.count),
224 has_request_payload_(mrd->has_request_payload_),
Craig Tillerc4165772015-02-11 10:51:04 -0800225 request_payload_(mrd->request_payload_),
226 method_(mrd->method_) {
yang-g85c04f92015-07-07 17:47:31 -0700227 ctx_.set_call(mrd->call_);
Yang Gao1205f6f2015-03-22 15:18:14 -0700228 ctx_.cq_ = &cq_;
Craig Tillerc4165772015-02-11 10:51:04 -0800229 GPR_ASSERT(mrd->in_flight_);
230 mrd->in_flight_ = false;
231 mrd->request_metadata_.count = 0;
232 }
233
Craig Tillerec3257c2015-02-12 15:59:43 -0800234 ~CallData() {
235 if (has_request_payload_ && request_payload_) {
236 grpc_byte_buffer_destroy(request_payload_);
237 }
238 }
239
Craig Tiller64616492016-01-26 14:16:20 -0800240 void Run(std::shared_ptr<GlobalCallbacks> global_callbacks) {
Craig Tiller492968f2015-02-18 13:14:03 -0800241 ctx_.BeginCompletionOp(&call_);
Craig Tiller64616492016-01-26 14:16:20 -0800242 global_callbacks->PreSynchronousRequest(&ctx_);
Craig Tillerce40de52015-06-05 07:14:58 -0700243 method_->handler()->RunHandler(MethodHandler::HandlerParameter(
244 &call_, &ctx_, request_payload_, call_.max_message_size()));
Craig Tiller64616492016-01-26 14:16:20 -0800245 global_callbacks->PostSynchronousRequest(&ctx_);
Craig Tiller928ec8e2015-06-05 08:45:45 -0700246 request_payload_ = nullptr;
Craig Tiller492968f2015-02-18 13:14:03 -0800247 void* ignored_tag;
248 bool ignored_ok;
249 cq_.Shutdown();
250 GPR_ASSERT(cq_.Next(&ignored_tag, &ignored_ok) == false);
Craig Tillerc4165772015-02-11 10:51:04 -0800251 }
252
253 private:
254 CompletionQueue cq_;
255 Call call_;
256 ServerContext ctx_;
257 const bool has_request_payload_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800258 grpc_byte_buffer* request_payload_;
259 RpcServiceMethod* const method_;
Craig Tillerc4165772015-02-11 10:51:04 -0800260 };
261
262 private:
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800263 RpcServiceMethod* const method_;
264 void* const tag_;
Craig Tillercf133f42015-02-26 14:05:56 -0800265 bool in_flight_;
Craig Tillerc4165772015-02-11 10:51:04 -0800266 const bool has_request_payload_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800267 grpc_call* call_;
yang-g9b7757d2015-08-13 11:15:53 -0700268 grpc_call_details* call_details_;
Craig Tillerc4165772015-02-11 10:51:04 -0800269 gpr_timespec deadline_;
270 grpc_metadata_array request_metadata_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800271 grpc_byte_buffer* request_payload_;
272 grpc_completion_queue* cq_;
Craig Tillerc4165772015-02-11 10:51:04 -0800273};
274
David Garcia Quintasd79ef3a2016-01-28 00:21:27 -0800275static internal::GrpcLibraryInitializer g_gli_initializer;
Yang Gao3921c562015-04-30 16:07:06 -0700276Server::Server(ThreadPoolInterface* thread_pool, bool thread_pool_owned,
yang-geb62c942016-02-17 15:37:25 -0800277 int max_message_size, ChannelArguments* args)
Yang Gao3921c562015-04-30 16:07:06 -0700278 : max_message_size_(max_message_size),
279 started_(false),
vjpaicad5f0a2015-02-18 22:02:52 -0800280 shutdown_(false),
281 num_running_cb_(0),
Nicolas Noble30862032015-04-24 18:17:45 -0700282 sync_methods_(new std::list<SyncRequest>),
yang-g9b7757d2015-08-13 11:15:53 -0700283 has_generic_service_(false),
yang-geb62c942016-02-17 15:37:25 -0800284 server_(nullptr),
vjpaicad5f0a2015-02-18 22:02:52 -0800285 thread_pool_(thread_pool),
Craig Tillerf9e6adf2015-05-06 11:45:59 -0700286 thread_pool_owned_(thread_pool_owned) {
David Garcia Quintasd79ef3a2016-01-28 00:21:27 -0800287 g_gli_initializer.summon();
Craig Tiller8352b9e2015-12-02 11:43:40 -0800288 gpr_once_init(&g_once_init_callbacks, InitGlobalCallbacks);
Craig Tiller64616492016-01-26 14:16:20 -0800289 global_callbacks_ = g_callbacks;
yang-geb62c942016-02-17 15:37:25 -0800290 global_callbacks_->UpdateArguments(args);
291 grpc_channel_args channel_args;
292 args->SetChannelArgs(&channel_args);
293 server_ = grpc_server_create(&channel_args, nullptr);
Nicolas "Pixel" Nobleebb51402015-07-23 02:41:33 +0200294 grpc_server_register_completion_queue(server_, cq_.cq(), nullptr);
Craig Tillerf9e6adf2015-05-06 11:45:59 -0700295}
vjpaicad5f0a2015-02-18 22:02:52 -0800296
297Server::~Server() {
Ruyi Wangb486ba62015-03-14 22:19:44 +0800298 {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200299 grpc::unique_lock<grpc::mutex> lock(mu_);
Ruyi Wangb486ba62015-03-14 22:19:44 +0800300 if (started_ && !shutdown_) {
301 lock.unlock();
302 Shutdown();
yang-gb9711732016-01-15 16:53:08 -0800303 } else if (!started_) {
304 cq_.Shutdown();
Ruyi Wangb486ba62015-03-14 22:19:44 +0800305 }
vjpaicad5f0a2015-02-18 22:02:52 -0800306 }
Craig Tiller29f79dc2015-05-27 15:59:23 -0700307 void* got_tag;
308 bool ok;
309 GPR_ASSERT(!cq_.Next(&got_tag, &ok));
vjpaicad5f0a2015-02-18 22:02:52 -0800310 grpc_server_destroy(server_);
311 if (thread_pool_owned_) {
312 delete thread_pool_;
313 }
Nicolas Noble30862032015-04-24 18:17:45 -0700314 delete sync_methods_;
vjpaicad5f0a2015-02-18 22:02:52 -0800315}
316
Craig Tiller7221d992015-11-24 06:59:33 -0800317void Server::SetGlobalCallbacks(GlobalCallbacks* callbacks) {
Craig Tiller8352b9e2015-12-02 11:43:40 -0800318 GPR_ASSERT(g_callbacks == nullptr);
319 GPR_ASSERT(callbacks != nullptr);
Craig Tiller64616492016-01-26 14:16:20 -0800320 g_callbacks.reset(callbacks);
Craig Tiller7221d992015-11-24 06:59:33 -0800321}
322
Craig Tiller15f383c2016-01-07 12:45:32 -0800323bool Server::RegisterService(const grpc::string* host, Service* service) {
324 bool has_async_methods = service->has_async_methods();
325 if (has_async_methods) {
326 GPR_ASSERT(service->server_ == nullptr &&
327 "Can only register an asynchronous service against one server.");
328 service->server_ = this;
329 }
330 for (auto it = service->methods_.begin(); it != service->methods_.end();
331 ++it) {
yang-g269b8be2016-01-15 10:46:26 -0800332 if (it->get() == nullptr) { // Handled by generic service if any.
333 continue;
334 }
Craig Tiller15f383c2016-01-07 12:45:32 -0800335 RpcServiceMethod* method = it->get();
Craig Tillerd6c98df2015-08-18 09:33:44 -0700336 void* tag = grpc_server_register_method(server_, method->name(),
337 host ? host->c_str() : nullptr);
Craig Tiller15f383c2016-01-07 12:45:32 -0800338 if (tag == nullptr) {
vjpaicad5f0a2015-02-18 22:02:52 -0800339 gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
340 method->name());
341 return false;
342 }
Craig Tiller15f383c2016-01-07 12:45:32 -0800343 if (method->handler() == nullptr) {
344 method->set_server_tag(tag);
345 } else {
346 sync_methods_->emplace_back(method, tag);
vjpaicad5f0a2015-02-18 22:02:52 -0800347 }
vjpaicad5f0a2015-02-18 22:02:52 -0800348 }
349 return true;
350}
351
Yang Gao49996492015-03-12 16:40:19 -0700352void Server::RegisterAsyncGenericService(AsyncGenericService* service) {
Yang Gao1c402332015-03-05 16:39:25 -0800353 GPR_ASSERT(service->server_ == nullptr &&
Yang Gao1ad253d2015-03-16 13:11:29 -0700354 "Can only register an async generic service against one server.");
Yang Gao1c402332015-03-05 16:39:25 -0800355 service->server_ = this;
yang-g9b7757d2015-08-13 11:15:53 -0700356 has_generic_service_ = true;
Yang Gao1c402332015-03-05 16:39:25 -0800357}
358
Nicolas Noblecfd60732015-03-18 16:27:43 -0700359int Server::AddListeningPort(const grpc::string& addr,
360 ServerCredentials* creds) {
vjpaicad5f0a2015-02-18 22:02:52 -0800361 GPR_ASSERT(!started_);
Craig Tiller42bc87c2015-02-23 08:50:19 -0800362 return creds->AddPortToServer(addr, server_);
vjpaicad5f0a2015-02-18 22:02:52 -0800363}
364
Craig Tiller8f7bff72015-08-17 13:23:14 -0700365bool Server::Start(ServerCompletionQueue** cqs, size_t num_cqs) {
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800366 GPR_ASSERT(!started_);
367 started_ = true;
368 grpc_server_start(server_);
369
yang-g9b7757d2015-08-13 11:15:53 -0700370 if (!has_generic_service_) {
Craig Tiller86d31772015-08-19 12:52:50 -0700371 if (!sync_methods_->empty()) {
372 unknown_method_.reset(new RpcServiceMethod(
373 "unknown", RpcMethod::BIDI_STREAMING, new UnknownMethodHandler));
374 // Use of emplace_back with just constructor arguments is not accepted
Julien Boeuf5be92a32015-08-28 16:28:18 -0700375 // here by gcc-4.4 because it can't match the anonymous nullptr with a
Craig Tiller849c7ca2015-08-21 16:06:05 -0700376 // proper constructor implicitly. Construct the object and use push_back.
Craig Tiller86d31772015-08-19 12:52:50 -0700377 sync_methods_->push_back(SyncRequest(unknown_method_.get(), nullptr));
378 }
Craig Tiller8f7bff72015-08-17 13:23:14 -0700379 for (size_t i = 0; i < num_cqs; i++) {
380 new UnimplementedAsyncRequest(this, cqs[i]);
Craig Tillercbd04852015-02-10 17:39:54 -0800381 }
yang-g9b7757d2015-08-13 11:15:53 -0700382 }
Craig Tillercbd04852015-02-10 17:39:54 -0800383 // Start processing rpcs.
384 if (!sync_methods_->empty()) {
385 for (auto m = sync_methods_->begin(); m != sync_methods_->end(); m++) {
386 m->SetupRequest();
Craig Tiller7c72adc2015-02-09 14:07:26 -0800387 m->Request(server_, cq_.cq());
388 }
Craig Tiller0db1bef2015-02-09 13:47:39 -0800389
390 ScheduleCallback();
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800391 }
392
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800393 return true;
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200394}
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800395
Craig Tillere50e5cb2015-08-18 12:44:57 -0700396void Server::ShutdownInternal(gpr_timespec deadline) {
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800397 grpc::unique_lock<grpc::mutex> lock(mu_);
398 if (started_ && !shutdown_) {
399 shutdown_ = true;
Craig Tillerbce999f2015-05-27 09:55:51 -0700400 grpc_server_shutdown_and_notify(server_, cq_.cq(), new ShutdownRequest());
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800401 cq_.Shutdown();
Craig Tiller59256032015-11-02 14:19:15 -0800402 lock.unlock();
Craig Tiller9374ce82015-08-19 10:15:44 -0700403 // Spin, eating requests until the completion queue is completely shutdown.
404 // If the deadline expires then cancel anything that's pending and keep
405 // spinning forever until the work is actually drained.
Julien Boeuf5be92a32015-08-28 16:28:18 -0700406 // Since nothing else needs to touch state guarded by mu_, holding it
Craig Tiller681a2912015-08-19 11:31:25 -0700407 // through this loop is fine.
Craig Tillere50e5cb2015-08-18 12:44:57 -0700408 SyncRequest* request;
409 bool ok;
410 while (SyncRequest::AsyncWait(&cq_, &request, &ok, deadline)) {
411 if (request == NULL) { // deadline expired
412 grpc_server_cancel_all_calls(server_);
Craig Tiller9374ce82015-08-19 10:15:44 -0700413 deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC);
Craig Tillere50e5cb2015-08-18 12:44:57 -0700414 } else if (ok) {
415 SyncRequest::CallData call_data(this, request);
416 }
417 }
Craig Tiller59256032015-11-02 14:19:15 -0800418 lock.lock();
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800419
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800420 // Wait for running callbacks to finish.
421 while (num_running_cb_ != 0) {
422 callback_cv_.wait(lock);
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800423 }
424 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800425}
426
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800427void Server::Wait() {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200428 grpc::unique_lock<grpc::mutex> lock(mu_);
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800429 while (num_running_cb_ != 0) {
430 callback_cv_.wait(lock);
431 }
432}
433
Craig Tiller50a7a682015-06-04 12:53:40 -0700434void Server::PerformOpsOnCall(CallOpSetInterface* ops, Call* call) {
Craig Tillerbb5227f2015-02-11 13:34:48 -0800435 static const size_t MAX_OPS = 8;
Craig Tiller50a7a682015-06-04 12:53:40 -0700436 size_t nops = 0;
437 grpc_op cops[MAX_OPS];
438 ops->FillOps(cops, &nops);
Nicolas "Pixel" Nobleebb51402015-07-23 02:41:33 +0200439 auto result = grpc_call_start_batch(call->call(), cops, nops, ops, nullptr);
440 GPR_ASSERT(GRPC_CALL_OK == result);
Craig Tillerbb5227f2015-02-11 13:34:48 -0800441}
442
David Garcia Quintas44f32492016-01-14 18:00:04 -0800443ServerInterface::BaseAsyncRequest::BaseAsyncRequest(
444 ServerInterface* server, ServerContext* context,
Craig Tiller8f7bff72015-08-17 13:23:14 -0700445 ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag,
446 bool delete_on_finalize)
Craig Tillerce40de52015-06-05 07:14:58 -0700447 : server_(server),
448 context_(context),
449 stream_(stream),
450 call_cq_(call_cq),
Craig Tiller50955812015-06-05 08:03:17 -0700451 tag_(tag),
Craig Tiller8f7bff72015-08-17 13:23:14 -0700452 delete_on_finalize_(delete_on_finalize),
Craig Tillerce40de52015-06-05 07:14:58 -0700453 call_(nullptr) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700454 memset(&initial_metadata_array_, 0, sizeof(initial_metadata_array_));
455}
456
David Garcia Quintasf3ddb7c2016-01-20 16:02:22 -0800457bool ServerInterface::BaseAsyncRequest::FinalizeResult(void** tag,
458 bool* status) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700459 if (*status) {
460 for (size_t i = 0; i < initial_metadata_array_.count; i++) {
yang-ge21908f2015-08-25 13:47:51 -0700461 context_->client_metadata_.insert(
462 std::pair<grpc::string_ref, grpc::string_ref>(
463 initial_metadata_array_.metadata[i].key,
464 grpc::string_ref(
465 initial_metadata_array_.metadata[i].value,
466 initial_metadata_array_.metadata[i].value_length)));
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700467 }
468 }
Craig Tiller2f4a49c2015-06-05 09:36:52 -0700469 grpc_metadata_array_destroy(&initial_metadata_array_);
yang-g85c04f92015-07-07 17:47:31 -0700470 context_->set_call(call_);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700471 context_->cq_ = call_cq_;
David Garcia Quintas44f32492016-01-14 18:00:04 -0800472 Call call(call_, server_, call_cq_, server_->max_message_size());
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700473 if (*status && call_) {
474 context_->BeginCompletionOp(&call);
475 }
476 // just the pointers inside call are copied here
477 stream_->BindCall(&call);
Craig Tiller50955812015-06-05 08:03:17 -0700478 *tag = tag_;
Craig Tiller8f7bff72015-08-17 13:23:14 -0700479 if (delete_on_finalize_) {
480 delete this;
481 }
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700482 return true;
483}
484
David Garcia Quintas44f32492016-01-14 18:00:04 -0800485ServerInterface::RegisteredAsyncRequest::RegisteredAsyncRequest(
486 ServerInterface* server, ServerContext* context,
Craig Tillerce40de52015-06-05 07:14:58 -0700487 ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag)
Craig Tiller8f7bff72015-08-17 13:23:14 -0700488 : BaseAsyncRequest(server, context, stream, call_cq, tag, true) {}
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700489
David Garcia Quintas44f32492016-01-14 18:00:04 -0800490void ServerInterface::RegisteredAsyncRequest::IssueRequest(
Craig Tillerce40de52015-06-05 07:14:58 -0700491 void* registered_method, grpc_byte_buffer** payload,
492 ServerCompletionQueue* notification_cq) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700493 grpc_server_request_registered_call(
David Garcia Quintas44f32492016-01-14 18:00:04 -0800494 server_->server(), registered_method, &call_, &context_->deadline_,
Craig Tillerce40de52015-06-05 07:14:58 -0700495 &initial_metadata_array_, payload, call_cq_->cq(), notification_cq->cq(),
496 this);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700497}
498
David Garcia Quintas44f32492016-01-14 18:00:04 -0800499ServerInterface::GenericAsyncRequest::GenericAsyncRequest(
500 ServerInterface* server, GenericServerContext* context,
Craig Tillerce40de52015-06-05 07:14:58 -0700501 ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
Craig Tiller8f7bff72015-08-17 13:23:14 -0700502 ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
503 : BaseAsyncRequest(server, context, stream, call_cq, tag,
504 delete_on_finalize) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700505 grpc_call_details_init(&call_details_);
506 GPR_ASSERT(notification_cq);
507 GPR_ASSERT(call_cq);
David Garcia Quintas44f32492016-01-14 18:00:04 -0800508 grpc_server_request_call(server->server(), &call_, &call_details_,
Craig Tillerce40de52015-06-05 07:14:58 -0700509 &initial_metadata_array_, call_cq->cq(),
510 notification_cq->cq(), this);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700511}
512
David Garcia Quintasf3ddb7c2016-01-20 16:02:22 -0800513bool ServerInterface::GenericAsyncRequest::FinalizeResult(void** tag,
514 bool* status) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700515 // TODO(yangg) remove the copy here.
yang-g3deb0062015-06-23 14:06:08 -0700516 if (*status) {
yang-ga58cab32015-06-23 14:37:15 -0700517 static_cast<GenericServerContext*>(context_)->method_ =
518 call_details_.method;
yang-g3deb0062015-06-23 14:06:08 -0700519 static_cast<GenericServerContext*>(context_)->host_ = call_details_.host;
yang-g3deb0062015-06-23 14:06:08 -0700520 }
yang-ga58cab32015-06-23 14:37:15 -0700521 gpr_free(call_details_.method);
522 gpr_free(call_details_.host);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700523 return BaseAsyncRequest::FinalizeResult(tag, status);
524}
525
Craig Tiller8f7bff72015-08-17 13:23:14 -0700526bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag,
527 bool* status) {
528 if (GenericAsyncRequest::FinalizeResult(tag, status) && *status) {
529 new UnimplementedAsyncRequest(server_, cq_);
530 new UnimplementedAsyncResponse(this);
531 } else {
532 delete this;
533 }
534 return false;
535}
536
537Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse(
538 UnimplementedAsyncRequest* request)
539 : request_(request) {
540 Status status(StatusCode::UNIMPLEMENTED, "");
541 UnknownMethodHandler::FillOps(request_->context(), this);
542 request_->stream()->call_.PerformOps(this);
543}
544
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800545void Server::ScheduleCallback() {
546 {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200547 grpc::unique_lock<grpc::mutex> lock(mu_);
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800548 num_running_cb_++;
549 }
vjpai72a44172015-07-16 21:44:44 -0700550 thread_pool_->Add(std::bind(&Server::RunRpc, this));
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800551}
552
553void Server::RunRpc() {
554 // Wait for one more incoming rpc.
Craig Tillerc4165772015-02-11 10:51:04 -0800555 bool ok;
Craig Tiller0ba432d2015-10-09 16:57:11 -0700556 GPR_TIMER_SCOPE("Server::RunRpc", 0);
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800557 auto* mrd = SyncRequest::Wait(&cq_, &ok);
Craig Tillercbd04852015-02-10 17:39:54 -0800558 if (mrd) {
Craig Tillerbd217572015-02-11 18:10:56 -0800559 ScheduleCallback();
Craig Tillerc4165772015-02-11 10:51:04 -0800560 if (ok) {
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800561 SyncRequest::CallData cd(this, mrd);
Yang Gaob8a5f862015-05-07 16:26:33 -0700562 {
Vijay Paiced73bd2015-06-17 10:23:28 -0700563 mrd->SetupRequest();
Yang Gaob8a5f862015-05-07 16:26:33 -0700564 grpc::unique_lock<grpc::mutex> lock(mu_);
565 if (!shutdown_) {
Craig Tillera33acb72015-05-08 08:02:55 -0700566 mrd->Request(server_, cq_.cq());
Vijay Paiced73bd2015-06-17 10:23:28 -0700567 } else {
568 // destroy the structure that was created
569 mrd->TeardownRequest();
Yang Gaob8a5f862015-05-07 16:26:33 -0700570 }
571 }
Craig Tiller0ba432d2015-10-09 16:57:11 -0700572 GPR_TIMER_SCOPE("cd.Run()", 0);
Craig Tiller64616492016-01-26 14:16:20 -0800573 cd.Run(global_callbacks_);
Craig Tillerc4165772015-02-11 10:51:04 -0800574 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800575 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800576
577 {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200578 grpc::unique_lock<grpc::mutex> lock(mu_);
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800579 num_running_cb_--;
580 if (shutdown_) {
581 callback_cv_.notify_all();
582 }
583 }
584}
585
586} // namespace grpc