blob: 878775bbeefefe6bde02cde04d8fefc263533960 [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>
yang-g9e2f90c2015-08-21 15:35:03 -070035
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080036#include <utility>
37
38#include <grpc/grpc.h>
Yang Gao2a3c96a2015-03-11 23:32:40 -070039#include <grpc/support/alloc.h>
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080040#include <grpc/support/log.h>
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080041#include <grpc++/completion_queue.h>
yang-g9e2f90c2015-08-21 15:35:03 -070042#include <grpc++/generic/async_generic_service.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>
Craig Tillerb4701692015-02-09 16:12:00 -080045#include <grpc++/server_context.h>
Julien Boeuf5be92a32015-08-28 16:28:18 -070046#include <grpc++/security/server_credentials.h>
yang-g9e2f90c2015-08-21 15:35:03 -070047#include <grpc++/support/time.h>
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080048
Vijay Pai9ffbd0c2015-04-15 01:02:50 -070049#include "src/core/profiling/timers.h"
Vijay Paie8a7e302015-08-24 10:52:33 -070050#include "src/cpp/server/thread_pool_interface.h"
Craig Tillerc4165772015-02-11 10:51:04 -080051
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080052namespace grpc {
53
Craig Tiller7221d992015-11-24 06:59:33 -080054class DefaultGlobalCallbacks GRPC_FINAL : public Server::GlobalCallbacks {
55 public:
56 void PreSynchronousRequest(ServerContext* context) GRPC_OVERRIDE {}
57 void PostSynchronousRequest(ServerContext* context) GRPC_OVERRIDE {}
58};
59
Craig Tiller8352b9e2015-12-02 11:43:40 -080060static Server::GlobalCallbacks* g_callbacks = nullptr;
61static gpr_once g_once_init_callbacks = GPR_ONCE_INIT;
62
Craig Tiller8352b9e2015-12-02 11:43:40 -080063static void InitGlobalCallbacks() {
64 if (g_callbacks == nullptr) {
Craig Tiller06dd04c2015-12-02 15:56:27 -080065 static DefaultGlobalCallbacks default_global_callbacks;
66 g_callbacks = &default_global_callbacks;
Craig Tiller8352b9e2015-12-02 11:43:40 -080067 }
68}
Craig Tiller7221d992015-11-24 06:59:33 -080069
Craig Tiller8f7bff72015-08-17 13:23:14 -070070class Server::UnimplementedAsyncRequestContext {
71 protected:
72 UnimplementedAsyncRequestContext() : generic_stream_(&server_context_) {}
73
74 GenericServerContext server_context_;
75 GenericServerAsyncReaderWriter generic_stream_;
76};
77
78class Server::UnimplementedAsyncRequest GRPC_FINAL
79 : public UnimplementedAsyncRequestContext,
80 public GenericAsyncRequest {
81 public:
82 UnimplementedAsyncRequest(Server* server, ServerCompletionQueue* cq)
83 : GenericAsyncRequest(server, &server_context_, &generic_stream_, cq, cq,
84 NULL, false),
85 server_(server),
86 cq_(cq) {}
87
88 bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE;
89
90 ServerContext* context() { return &server_context_; }
91 GenericServerAsyncReaderWriter* stream() { return &generic_stream_; }
92
93 private:
94 Server* const server_;
95 ServerCompletionQueue* const cq_;
96};
97
98typedef SneakyCallOpSet<CallOpSendInitialMetadata, CallOpServerSendStatus>
99 UnimplementedAsyncResponseOp;
100class Server::UnimplementedAsyncResponse GRPC_FINAL
101 : public UnimplementedAsyncResponseOp {
102 public:
103 UnimplementedAsyncResponse(UnimplementedAsyncRequest* request);
104 ~UnimplementedAsyncResponse() { delete request_; }
105
106 bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE {
107 bool r = UnimplementedAsyncResponseOp::FinalizeResult(tag, status);
108 delete this;
109 return r;
110 }
111
112 private:
113 UnimplementedAsyncRequest* const request_;
114};
115
Craig Tillerbce999f2015-05-27 09:55:51 -0700116class Server::ShutdownRequest GRPC_FINAL : public CompletionQueueTag {
117 public:
118 bool FinalizeResult(void** tag, bool* status) {
119 delete this;
120 return false;
121 }
122};
123
Craig Tillercf133f42015-02-26 14:05:56 -0800124class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag {
Craig Tillerc4165772015-02-11 10:51:04 -0800125 public:
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800126 SyncRequest(RpcServiceMethod* method, void* tag)
Craig Tillerc4165772015-02-11 10:51:04 -0800127 : method_(method),
128 tag_(tag),
Craig Tillercf133f42015-02-26 14:05:56 -0800129 in_flight_(false),
Craig Tillerc4165772015-02-11 10:51:04 -0800130 has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC ||
131 method->method_type() ==
132 RpcMethod::SERVER_STREAMING),
yang-g9b7757d2015-08-13 11:15:53 -0700133 call_details_(nullptr),
Vijay Paiced73bd2015-06-17 10:23:28 -0700134 cq_(nullptr) {
Craig Tillerc4165772015-02-11 10:51:04 -0800135 grpc_metadata_array_init(&request_metadata_);
136 }
137
yang-g9b7757d2015-08-13 11:15:53 -0700138 ~SyncRequest() {
139 if (call_details_) {
140 delete call_details_;
141 }
142 grpc_metadata_array_destroy(&request_metadata_);
143 }
Yang Gao7b49a772015-05-28 14:07:54 -0700144
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800145 static SyncRequest* Wait(CompletionQueue* cq, bool* ok) {
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800146 void* tag = nullptr;
Craig Tiller504bd332015-02-11 20:34:33 -0800147 *ok = false;
Craig Tillerc4165772015-02-11 10:51:04 -0800148 if (!cq->Next(&tag, ok)) {
149 return nullptr;
150 }
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800151 auto* mrd = static_cast<SyncRequest*>(tag);
Craig Tillerc4165772015-02-11 10:51:04 -0800152 GPR_ASSERT(mrd->in_flight_);
153 return mrd;
154 }
155
Craig Tillere50e5cb2015-08-18 12:44:57 -0700156 static bool AsyncWait(CompletionQueue* cq, SyncRequest** req, bool* ok,
157 gpr_timespec deadline) {
158 void* tag = nullptr;
159 *ok = false;
160 switch (cq->AsyncNext(&tag, ok, deadline)) {
161 case CompletionQueue::TIMEOUT:
162 *req = nullptr;
163 return true;
164 case CompletionQueue::SHUTDOWN:
165 *req = nullptr;
166 return false;
167 case CompletionQueue::GOT_EVENT:
168 *req = static_cast<SyncRequest*>(tag);
169 GPR_ASSERT((*req)->in_flight_);
170 return true;
171 }
yang-gb063c872015-10-07 11:40:13 -0700172 GPR_UNREACHABLE_CODE(return false);
Craig Tillere50e5cb2015-08-18 12:44:57 -0700173 }
174
Nicolas "Pixel" Nobleebb51402015-07-23 02:41:33 +0200175 void SetupRequest() { cq_ = grpc_completion_queue_create(nullptr); }
Vijay Paiced73bd2015-06-17 10:23:28 -0700176
177 void TeardownRequest() {
178 grpc_completion_queue_destroy(cq_);
179 cq_ = nullptr;
180 }
181
Craig Tillerf9e6adf2015-05-06 11:45:59 -0700182 void Request(grpc_server* server, grpc_completion_queue* notify_cq) {
Vijay Paiced73bd2015-06-17 10:23:28 -0700183 GPR_ASSERT(cq_ && !in_flight_);
Craig Tillerc4165772015-02-11 10:51:04 -0800184 in_flight_ = true;
yang-g9b7757d2015-08-13 11:15:53 -0700185 if (tag_) {
186 GPR_ASSERT(GRPC_CALL_OK ==
187 grpc_server_request_registered_call(
188 server, tag_, &call_, &deadline_, &request_metadata_,
189 has_request_payload_ ? &request_payload_ : nullptr, cq_,
190 notify_cq, this));
191 } else {
192 if (!call_details_) {
193 call_details_ = new grpc_call_details;
194 grpc_call_details_init(call_details_);
195 }
196 GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call(
197 server, &call_, call_details_,
198 &request_metadata_, cq_, notify_cq, this));
199 }
Craig Tillerc4165772015-02-11 10:51:04 -0800200 }
201
Craig Tillercf133f42015-02-26 14:05:56 -0800202 bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE {
Craig Tillerec3257c2015-02-12 15:59:43 -0800203 if (!*status) {
204 grpc_completion_queue_destroy(cq_);
205 }
yang-g9b7757d2015-08-13 11:15:53 -0700206 if (call_details_) {
207 deadline_ = call_details_->deadline;
208 grpc_call_details_destroy(call_details_);
209 grpc_call_details_init(call_details_);
210 }
Craig Tiller645466e2015-02-18 09:18:33 -0800211 return true;
Craig Tillerec3257c2015-02-12 15:59:43 -0800212 }
Craig Tillerc4165772015-02-11 10:51:04 -0800213
Craig Tillercf133f42015-02-26 14:05:56 -0800214 class CallData GRPC_FINAL {
Craig Tillerc4165772015-02-11 10:51:04 -0800215 public:
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800216 explicit CallData(Server* server, SyncRequest* mrd)
Craig Tillerc4165772015-02-11 10:51:04 -0800217 : cq_(mrd->cq_),
Yang Gao3921c562015-04-30 16:07:06 -0700218 call_(mrd->call_, server, &cq_, server->max_message_size_),
Craig Tillerc4165772015-02-11 10:51:04 -0800219 ctx_(mrd->deadline_, mrd->request_metadata_.metadata,
220 mrd->request_metadata_.count),
221 has_request_payload_(mrd->has_request_payload_),
Craig Tillerc4165772015-02-11 10:51:04 -0800222 request_payload_(mrd->request_payload_),
223 method_(mrd->method_) {
yang-g85c04f92015-07-07 17:47:31 -0700224 ctx_.set_call(mrd->call_);
Yang Gao1205f6f2015-03-22 15:18:14 -0700225 ctx_.cq_ = &cq_;
Craig Tillerc4165772015-02-11 10:51:04 -0800226 GPR_ASSERT(mrd->in_flight_);
227 mrd->in_flight_ = false;
228 mrd->request_metadata_.count = 0;
229 }
230
Craig Tillerec3257c2015-02-12 15:59:43 -0800231 ~CallData() {
232 if (has_request_payload_ && request_payload_) {
233 grpc_byte_buffer_destroy(request_payload_);
234 }
235 }
236
Craig Tillerc4165772015-02-11 10:51:04 -0800237 void Run() {
Craig Tiller492968f2015-02-18 13:14:03 -0800238 ctx_.BeginCompletionOp(&call_);
Craig Tiller7221d992015-11-24 06:59:33 -0800239 g_callbacks->PreSynchronousRequest(&ctx_);
Craig Tillerce40de52015-06-05 07:14:58 -0700240 method_->handler()->RunHandler(MethodHandler::HandlerParameter(
241 &call_, &ctx_, request_payload_, call_.max_message_size()));
Craig Tiller7221d992015-11-24 06:59:33 -0800242 g_callbacks->PostSynchronousRequest(&ctx_);
Craig Tiller928ec8e2015-06-05 08:45:45 -0700243 request_payload_ = nullptr;
Craig Tiller492968f2015-02-18 13:14:03 -0800244 void* ignored_tag;
245 bool ignored_ok;
246 cq_.Shutdown();
247 GPR_ASSERT(cq_.Next(&ignored_tag, &ignored_ok) == false);
Craig Tillerc4165772015-02-11 10:51:04 -0800248 }
249
250 private:
251 CompletionQueue cq_;
252 Call call_;
253 ServerContext ctx_;
254 const bool has_request_payload_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800255 grpc_byte_buffer* request_payload_;
256 RpcServiceMethod* const method_;
Craig Tillerc4165772015-02-11 10:51:04 -0800257 };
258
259 private:
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800260 RpcServiceMethod* const method_;
261 void* const tag_;
Craig Tillercf133f42015-02-26 14:05:56 -0800262 bool in_flight_;
Craig Tillerc4165772015-02-11 10:51:04 -0800263 const bool has_request_payload_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800264 grpc_call* call_;
yang-g9b7757d2015-08-13 11:15:53 -0700265 grpc_call_details* call_details_;
Craig Tillerc4165772015-02-11 10:51:04 -0800266 gpr_timespec deadline_;
267 grpc_metadata_array request_metadata_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800268 grpc_byte_buffer* request_payload_;
269 grpc_completion_queue* cq_;
Craig Tillerc4165772015-02-11 10:51:04 -0800270};
271
yang-ga23f17b2015-11-25 10:21:05 -0800272static grpc_server* CreateServer(const ChannelArguments& args) {
273 grpc_channel_args channel_args;
274 args.SetChannelArgs(&channel_args);
David Garcia Quintascb304102015-08-19 15:50:54 -0700275 return grpc_server_create(&channel_args, nullptr);
Yang Gao3921c562015-04-30 16:07:06 -0700276}
277
278Server::Server(ThreadPoolInterface* thread_pool, bool thread_pool_owned,
yang-ga23f17b2015-11-25 10:21:05 -0800279 int max_message_size, const ChannelArguments& args)
Yang Gao3921c562015-04-30 16:07:06 -0700280 : max_message_size_(max_message_size),
281 started_(false),
vjpaicad5f0a2015-02-18 22:02:52 -0800282 shutdown_(false),
283 num_running_cb_(0),
Nicolas Noble30862032015-04-24 18:17:45 -0700284 sync_methods_(new std::list<SyncRequest>),
yang-g9b7757d2015-08-13 11:15:53 -0700285 has_generic_service_(false),
yang-ga23f17b2015-11-25 10:21:05 -0800286 server_(CreateServer(args)),
vjpaicad5f0a2015-02-18 22:02:52 -0800287 thread_pool_(thread_pool),
Craig Tillerf9e6adf2015-05-06 11:45:59 -0700288 thread_pool_owned_(thread_pool_owned) {
Craig Tiller8352b9e2015-12-02 11:43:40 -0800289 gpr_once_init(&g_once_init_callbacks, InitGlobalCallbacks);
Nicolas "Pixel" Nobleebb51402015-07-23 02:41:33 +0200290 grpc_server_register_completion_queue(server_, cq_.cq(), nullptr);
Craig Tillerf9e6adf2015-05-06 11:45:59 -0700291}
vjpaicad5f0a2015-02-18 22:02:52 -0800292
293Server::~Server() {
Ruyi Wangb486ba62015-03-14 22:19:44 +0800294 {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200295 grpc::unique_lock<grpc::mutex> lock(mu_);
Ruyi Wangb486ba62015-03-14 22:19:44 +0800296 if (started_ && !shutdown_) {
297 lock.unlock();
298 Shutdown();
299 }
vjpaicad5f0a2015-02-18 22:02:52 -0800300 }
Craig Tiller29f79dc2015-05-27 15:59:23 -0700301 void* got_tag;
302 bool ok;
303 GPR_ASSERT(!cq_.Next(&got_tag, &ok));
vjpaicad5f0a2015-02-18 22:02:52 -0800304 grpc_server_destroy(server_);
305 if (thread_pool_owned_) {
306 delete thread_pool_;
307 }
Nicolas Noble30862032015-04-24 18:17:45 -0700308 delete sync_methods_;
vjpaicad5f0a2015-02-18 22:02:52 -0800309}
310
Craig Tiller7221d992015-11-24 06:59:33 -0800311void Server::SetGlobalCallbacks(GlobalCallbacks* callbacks) {
Craig Tiller8352b9e2015-12-02 11:43:40 -0800312 GPR_ASSERT(g_callbacks == nullptr);
313 GPR_ASSERT(callbacks != nullptr);
Craig Tiller7221d992015-11-24 06:59:33 -0800314 g_callbacks = callbacks;
315}
316
Craig Tillerd6c98df2015-08-18 09:33:44 -0700317bool Server::RegisterService(const grpc::string* host, RpcService* service) {
vjpaicad5f0a2015-02-18 22:02:52 -0800318 for (int i = 0; i < service->GetMethodCount(); ++i) {
319 RpcServiceMethod* method = service->GetMethod(i);
Craig Tillerd6c98df2015-08-18 09:33:44 -0700320 void* tag = grpc_server_register_method(server_, method->name(),
321 host ? host->c_str() : nullptr);
vjpaicad5f0a2015-02-18 22:02:52 -0800322 if (!tag) {
323 gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
324 method->name());
325 return false;
326 }
Vijay Pai8fe60a82015-08-14 17:02:31 +0000327 sync_methods_->emplace_back(method, tag);
vjpaicad5f0a2015-02-18 22:02:52 -0800328 }
329 return true;
330}
331
yang-g9b7757d2015-08-13 11:15:53 -0700332bool Server::RegisterAsyncService(const grpc::string* host,
333 AsynchronousService* service) {
Craig Tiller50a7a682015-06-04 12:53:40 -0700334 GPR_ASSERT(service->server_ == nullptr &&
Yang Gao1ad253d2015-03-16 13:11:29 -0700335 "Can only register an asynchronous service against one server.");
Craig Tiller50a7a682015-06-04 12:53:40 -0700336 service->server_ = this;
Craig Tiller71a0f9d2015-09-28 17:22:01 -0700337 service->request_args_ = new void* [service->method_count_];
vjpaicad5f0a2015-02-18 22:02:52 -0800338 for (size_t i = 0; i < service->method_count_; ++i) {
Craig Tillerf9e6adf2015-05-06 11:45:59 -0700339 void* tag = grpc_server_register_method(server_, service->method_names_[i],
Craig Tiller822d2c72015-07-07 16:08:00 -0700340 host ? host->c_str() : nullptr);
vjpaicad5f0a2015-02-18 22:02:52 -0800341 if (!tag) {
342 gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
343 service->method_names_[i]);
344 return false;
345 }
346 service->request_args_[i] = tag;
347 }
348 return true;
349}
350
Yang Gao49996492015-03-12 16:40:19 -0700351void Server::RegisterAsyncGenericService(AsyncGenericService* service) {
Yang Gao1c402332015-03-05 16:39:25 -0800352 GPR_ASSERT(service->server_ == nullptr &&
Yang Gao1ad253d2015-03-16 13:11:29 -0700353 "Can only register an async generic service against one server.");
Yang Gao1c402332015-03-05 16:39:25 -0800354 service->server_ = this;
yang-g9b7757d2015-08-13 11:15:53 -0700355 has_generic_service_ = true;
Yang Gao1c402332015-03-05 16:39:25 -0800356}
357
Nicolas Noblecfd60732015-03-18 16:27:43 -0700358int Server::AddListeningPort(const grpc::string& addr,
359 ServerCredentials* creds) {
vjpaicad5f0a2015-02-18 22:02:52 -0800360 GPR_ASSERT(!started_);
Craig Tiller42bc87c2015-02-23 08:50:19 -0800361 return creds->AddPortToServer(addr, server_);
vjpaicad5f0a2015-02-18 22:02:52 -0800362}
363
Craig Tiller8f7bff72015-08-17 13:23:14 -0700364bool Server::Start(ServerCompletionQueue** cqs, size_t num_cqs) {
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800365 GPR_ASSERT(!started_);
366 started_ = true;
367 grpc_server_start(server_);
368
yang-g9b7757d2015-08-13 11:15:53 -0700369 if (!has_generic_service_) {
Craig Tiller86d31772015-08-19 12:52:50 -0700370 if (!sync_methods_->empty()) {
371 unknown_method_.reset(new RpcServiceMethod(
372 "unknown", RpcMethod::BIDI_STREAMING, new UnknownMethodHandler));
373 // Use of emplace_back with just constructor arguments is not accepted
Julien Boeuf5be92a32015-08-28 16:28:18 -0700374 // here by gcc-4.4 because it can't match the anonymous nullptr with a
Craig Tiller849c7ca2015-08-21 16:06:05 -0700375 // proper constructor implicitly. Construct the object and use push_back.
Craig Tiller86d31772015-08-19 12:52:50 -0700376 sync_methods_->push_back(SyncRequest(unknown_method_.get(), nullptr));
377 }
Craig Tiller8f7bff72015-08-17 13:23:14 -0700378 for (size_t i = 0; i < num_cqs; i++) {
379 new UnimplementedAsyncRequest(this, cqs[i]);
Craig Tillercbd04852015-02-10 17:39:54 -0800380 }
yang-g9b7757d2015-08-13 11:15:53 -0700381 }
Craig Tillercbd04852015-02-10 17:39:54 -0800382 // Start processing rpcs.
383 if (!sync_methods_->empty()) {
384 for (auto m = sync_methods_->begin(); m != sync_methods_->end(); m++) {
385 m->SetupRequest();
Craig Tiller7c72adc2015-02-09 14:07:26 -0800386 m->Request(server_, cq_.cq());
387 }
Craig Tiller0db1bef2015-02-09 13:47:39 -0800388
389 ScheduleCallback();
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800390 }
391
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800392 return true;
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200393}
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800394
Craig Tillere50e5cb2015-08-18 12:44:57 -0700395void Server::ShutdownInternal(gpr_timespec deadline) {
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800396 grpc::unique_lock<grpc::mutex> lock(mu_);
397 if (started_ && !shutdown_) {
398 shutdown_ = true;
Craig Tillerbce999f2015-05-27 09:55:51 -0700399 grpc_server_shutdown_and_notify(server_, cq_.cq(), new ShutdownRequest());
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800400 cq_.Shutdown();
Craig Tiller59256032015-11-02 14:19:15 -0800401 lock.unlock();
Craig Tiller9374ce82015-08-19 10:15:44 -0700402 // Spin, eating requests until the completion queue is completely shutdown.
403 // If the deadline expires then cancel anything that's pending and keep
404 // spinning forever until the work is actually drained.
Julien Boeuf5be92a32015-08-28 16:28:18 -0700405 // Since nothing else needs to touch state guarded by mu_, holding it
Craig Tiller681a2912015-08-19 11:31:25 -0700406 // through this loop is fine.
Craig Tillere50e5cb2015-08-18 12:44:57 -0700407 SyncRequest* request;
408 bool ok;
409 while (SyncRequest::AsyncWait(&cq_, &request, &ok, deadline)) {
410 if (request == NULL) { // deadline expired
411 grpc_server_cancel_all_calls(server_);
Craig Tiller9374ce82015-08-19 10:15:44 -0700412 deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC);
Craig Tillere50e5cb2015-08-18 12:44:57 -0700413 } else if (ok) {
414 SyncRequest::CallData call_data(this, request);
415 }
416 }
Craig Tiller59256032015-11-02 14:19:15 -0800417 lock.lock();
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800418
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800419 // Wait for running callbacks to finish.
420 while (num_running_cb_ != 0) {
421 callback_cv_.wait(lock);
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800422 }
423 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800424}
425
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800426void Server::Wait() {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200427 grpc::unique_lock<grpc::mutex> lock(mu_);
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800428 while (num_running_cb_ != 0) {
429 callback_cv_.wait(lock);
430 }
431}
432
Craig Tiller50a7a682015-06-04 12:53:40 -0700433void Server::PerformOpsOnCall(CallOpSetInterface* ops, Call* call) {
Craig Tillerbb5227f2015-02-11 13:34:48 -0800434 static const size_t MAX_OPS = 8;
Craig Tiller50a7a682015-06-04 12:53:40 -0700435 size_t nops = 0;
436 grpc_op cops[MAX_OPS];
437 ops->FillOps(cops, &nops);
Nicolas "Pixel" Nobleebb51402015-07-23 02:41:33 +0200438 auto result = grpc_call_start_batch(call->call(), cops, nops, ops, nullptr);
439 GPR_ASSERT(GRPC_CALL_OK == result);
Craig Tillerbb5227f2015-02-11 13:34:48 -0800440}
441
Craig Tillerce40de52015-06-05 07:14:58 -0700442Server::BaseAsyncRequest::BaseAsyncRequest(
443 Server* server, ServerContext* context,
Craig Tiller8f7bff72015-08-17 13:23:14 -0700444 ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag,
445 bool delete_on_finalize)
Craig Tillerce40de52015-06-05 07:14:58 -0700446 : server_(server),
447 context_(context),
448 stream_(stream),
449 call_cq_(call_cq),
Craig Tiller50955812015-06-05 08:03:17 -0700450 tag_(tag),
Craig Tiller8f7bff72015-08-17 13:23:14 -0700451 delete_on_finalize_(delete_on_finalize),
Craig Tillerce40de52015-06-05 07:14:58 -0700452 call_(nullptr) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700453 memset(&initial_metadata_array_, 0, sizeof(initial_metadata_array_));
454}
455
Craig Tillerce40de52015-06-05 07:14:58 -0700456Server::BaseAsyncRequest::~BaseAsyncRequest() {}
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700457
458bool Server::BaseAsyncRequest::FinalizeResult(void** tag, bool* status) {
459 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_;
472 Call call(call_, server_, call_cq_, server_->max_message_size_);
473 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
Craig Tillerce40de52015-06-05 07:14:58 -0700485Server::RegisteredAsyncRequest::RegisteredAsyncRequest(
486 Server* server, ServerContext* context,
487 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
Craig Tillerce40de52015-06-05 07:14:58 -0700490void Server::RegisteredAsyncRequest::IssueRequest(
491 void* registered_method, grpc_byte_buffer** payload,
492 ServerCompletionQueue* notification_cq) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700493 grpc_server_request_registered_call(
Craig Tillerce40de52015-06-05 07:14:58 -0700494 server_->server_, registered_method, &call_, &context_->deadline_,
495 &initial_metadata_array_, payload, call_cq_->cq(), notification_cq->cq(),
496 this);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700497}
498
Craig Tillerce40de52015-06-05 07:14:58 -0700499Server::GenericAsyncRequest::GenericAsyncRequest(
500 Server* server, GenericServerContext* context,
501 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);
Craig Tillerce40de52015-06-05 07:14:58 -0700508 grpc_server_request_call(server->server_, &call_, &call_details_,
509 &initial_metadata_array_, call_cq->cq(),
510 notification_cq->cq(), this);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700511}
512
513bool Server::GenericAsyncRequest::FinalizeResult(void** tag, bool* status) {
514 // TODO(yangg) remove the copy here.
yang-g3deb0062015-06-23 14:06:08 -0700515 if (*status) {
yang-ga58cab32015-06-23 14:37:15 -0700516 static_cast<GenericServerContext*>(context_)->method_ =
517 call_details_.method;
yang-g3deb0062015-06-23 14:06:08 -0700518 static_cast<GenericServerContext*>(context_)->host_ = call_details_.host;
yang-g3deb0062015-06-23 14:06:08 -0700519 }
yang-ga58cab32015-06-23 14:37:15 -0700520 gpr_free(call_details_.method);
521 gpr_free(call_details_.host);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700522 return BaseAsyncRequest::FinalizeResult(tag, status);
523}
524
Craig Tiller8f7bff72015-08-17 13:23:14 -0700525bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag,
526 bool* status) {
527 if (GenericAsyncRequest::FinalizeResult(tag, status) && *status) {
528 new UnimplementedAsyncRequest(server_, cq_);
529 new UnimplementedAsyncResponse(this);
530 } else {
531 delete this;
532 }
533 return false;
534}
535
536Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse(
537 UnimplementedAsyncRequest* request)
538 : request_(request) {
539 Status status(StatusCode::UNIMPLEMENTED, "");
540 UnknownMethodHandler::FillOps(request_->context(), this);
541 request_->stream()->call_.PerformOps(this);
542}
543
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800544void Server::ScheduleCallback() {
545 {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200546 grpc::unique_lock<grpc::mutex> lock(mu_);
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800547 num_running_cb_++;
548 }
vjpai72a44172015-07-16 21:44:44 -0700549 thread_pool_->Add(std::bind(&Server::RunRpc, this));
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800550}
551
552void Server::RunRpc() {
553 // Wait for one more incoming rpc.
Craig Tillerc4165772015-02-11 10:51:04 -0800554 bool ok;
Craig Tiller0ba432d2015-10-09 16:57:11 -0700555 GPR_TIMER_SCOPE("Server::RunRpc", 0);
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800556 auto* mrd = SyncRequest::Wait(&cq_, &ok);
Craig Tillercbd04852015-02-10 17:39:54 -0800557 if (mrd) {
Craig Tillerbd217572015-02-11 18:10:56 -0800558 ScheduleCallback();
Craig Tillerc4165772015-02-11 10:51:04 -0800559 if (ok) {
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800560 SyncRequest::CallData cd(this, mrd);
Yang Gaob8a5f862015-05-07 16:26:33 -0700561 {
Vijay Paiced73bd2015-06-17 10:23:28 -0700562 mrd->SetupRequest();
Yang Gaob8a5f862015-05-07 16:26:33 -0700563 grpc::unique_lock<grpc::mutex> lock(mu_);
564 if (!shutdown_) {
Craig Tillera33acb72015-05-08 08:02:55 -0700565 mrd->Request(server_, cq_.cq());
Vijay Paiced73bd2015-06-17 10:23:28 -0700566 } else {
567 // destroy the structure that was created
568 mrd->TeardownRequest();
Yang Gaob8a5f862015-05-07 16:26:33 -0700569 }
570 }
Craig Tiller0ba432d2015-10-09 16:57:11 -0700571 GPR_TIMER_SCOPE("cd.Run()", 0);
Craig Tillerc4165772015-02-11 10:51:04 -0800572 cd.Run();
573 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800574 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800575
576 {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200577 grpc::unique_lock<grpc::mutex> lock(mu_);
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800578 num_running_cb_--;
579 if (shutdown_) {
580 callback_cv_.notify_all();
581 }
582 }
583}
584
585} // namespace grpc