blob: a693ce9b8eea730141b39af833b872cb5eb3c228 [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
Yuchen Zenga42ec212016-04-29 13:03:06 -070036#include <sstream>
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080037#include <utility>
38
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080039#include <grpc++/completion_queue.h>
yang-g9e2f90c2015-08-21 15:35:03 -070040#include <grpc++/generic/async_generic_service.h>
David Garcia Quintase1300de2016-01-27 18:41:26 -080041#include <grpc++/impl/codegen/completion_queue_tag.h>
42#include <grpc++/impl/grpc_library.h>
Craig Tiller15f383c2016-01-07 12:45:32 -080043#include <grpc++/impl/method_handler_impl.h>
yangg1b151092015-01-09 15:31:05 -080044#include <grpc++/impl/rpc_service_method.h>
Yuchen Zenga42ec212016-04-29 13:03:06 -070045#include <grpc++/impl/server_initializer.h>
Craig Tiller8c8d0aa2015-02-12 11:38:36 -080046#include <grpc++/impl/service_type.h>
Julien Boeuf5be92a32015-08-28 16:28:18 -070047#include <grpc++/security/server_credentials.h>
David Garcia Quintase1300de2016-01-27 18:41:26 -080048#include <grpc++/server_context.h>
yang-g9e2f90c2015-08-21 15:35:03 -070049#include <grpc++/support/time.h>
David Garcia Quintase1300de2016-01-27 18:41:26 -080050#include <grpc/grpc.h>
51#include <grpc/support/alloc.h>
52#include <grpc/support/log.h>
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080053
Craig Tiller9533d042016-03-25 17:11:06 -070054#include "src/core/lib/profiling/timers.h"
Vijay Paie8a7e302015-08-24 10:52:33 -070055#include "src/cpp/server/thread_pool_interface.h"
Craig Tillerc4165772015-02-11 10:51:04 -080056
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080057namespace grpc {
58
Craig Tiller7221d992015-11-24 06:59:33 -080059class DefaultGlobalCallbacks GRPC_FINAL : public Server::GlobalCallbacks {
60 public:
Bogdan Drutu618051c2016-01-14 08:54:43 -080061 ~DefaultGlobalCallbacks() GRPC_OVERRIDE {}
Craig Tiller7221d992015-11-24 06:59:33 -080062 void PreSynchronousRequest(ServerContext* context) GRPC_OVERRIDE {}
63 void PostSynchronousRequest(ServerContext* context) GRPC_OVERRIDE {}
64};
65
Craig Tiller64616492016-01-26 14:16:20 -080066static std::shared_ptr<Server::GlobalCallbacks> g_callbacks = nullptr;
Craig Tiller8352b9e2015-12-02 11:43:40 -080067static gpr_once g_once_init_callbacks = GPR_ONCE_INIT;
68
Craig Tiller8352b9e2015-12-02 11:43:40 -080069static void InitGlobalCallbacks() {
Vijay Paib645a2d2016-06-09 18:39:06 -070070 if (!g_callbacks) {
Craig Tiller64616492016-01-26 14:16:20 -080071 g_callbacks.reset(new DefaultGlobalCallbacks());
Craig Tiller8352b9e2015-12-02 11:43:40 -080072 }
73}
Craig Tiller7221d992015-11-24 06:59:33 -080074
Craig Tiller8f7bff72015-08-17 13:23:14 -070075class Server::UnimplementedAsyncRequestContext {
76 protected:
77 UnimplementedAsyncRequestContext() : generic_stream_(&server_context_) {}
78
79 GenericServerContext server_context_;
80 GenericServerAsyncReaderWriter generic_stream_;
81};
82
83class Server::UnimplementedAsyncRequest GRPC_FINAL
84 : public UnimplementedAsyncRequestContext,
85 public GenericAsyncRequest {
86 public:
87 UnimplementedAsyncRequest(Server* server, ServerCompletionQueue* cq)
88 : GenericAsyncRequest(server, &server_context_, &generic_stream_, cq, cq,
89 NULL, false),
90 server_(server),
91 cq_(cq) {}
92
93 bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE;
94
95 ServerContext* context() { return &server_context_; }
96 GenericServerAsyncReaderWriter* stream() { return &generic_stream_; }
97
98 private:
99 Server* const server_;
100 ServerCompletionQueue* const cq_;
101};
102
103typedef SneakyCallOpSet<CallOpSendInitialMetadata, CallOpServerSendStatus>
104 UnimplementedAsyncResponseOp;
105class Server::UnimplementedAsyncResponse GRPC_FINAL
106 : public UnimplementedAsyncResponseOp {
107 public:
108 UnimplementedAsyncResponse(UnimplementedAsyncRequest* request);
109 ~UnimplementedAsyncResponse() { delete request_; }
110
111 bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE {
112 bool r = UnimplementedAsyncResponseOp::FinalizeResult(tag, status);
113 delete this;
114 return r;
115 }
116
117 private:
118 UnimplementedAsyncRequest* const request_;
119};
120
Craig Tillerbce999f2015-05-27 09:55:51 -0700121class Server::ShutdownRequest GRPC_FINAL : public CompletionQueueTag {
122 public:
123 bool FinalizeResult(void** tag, bool* status) {
124 delete this;
125 return false;
126 }
127};
128
Craig Tillercf133f42015-02-26 14:05:56 -0800129class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag {
Craig Tillerc4165772015-02-11 10:51:04 -0800130 public:
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800131 SyncRequest(RpcServiceMethod* method, void* tag)
Craig Tillerc4165772015-02-11 10:51:04 -0800132 : method_(method),
133 tag_(tag),
Craig Tillercf133f42015-02-26 14:05:56 -0800134 in_flight_(false),
Craig Tillerc4165772015-02-11 10:51:04 -0800135 has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC ||
136 method->method_type() ==
137 RpcMethod::SERVER_STREAMING),
yang-g9b7757d2015-08-13 11:15:53 -0700138 call_details_(nullptr),
Vijay Paiced73bd2015-06-17 10:23:28 -0700139 cq_(nullptr) {
Craig Tillerc4165772015-02-11 10:51:04 -0800140 grpc_metadata_array_init(&request_metadata_);
141 }
142
yang-g9b7757d2015-08-13 11:15:53 -0700143 ~SyncRequest() {
144 if (call_details_) {
145 delete call_details_;
146 }
147 grpc_metadata_array_destroy(&request_metadata_);
148 }
Yang Gao7b49a772015-05-28 14:07:54 -0700149
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800150 static SyncRequest* Wait(CompletionQueue* cq, bool* ok) {
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800151 void* tag = nullptr;
Craig Tiller504bd332015-02-11 20:34:33 -0800152 *ok = false;
Craig Tillerc4165772015-02-11 10:51:04 -0800153 if (!cq->Next(&tag, ok)) {
154 return nullptr;
155 }
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800156 auto* mrd = static_cast<SyncRequest*>(tag);
Craig Tillerc4165772015-02-11 10:51:04 -0800157 GPR_ASSERT(mrd->in_flight_);
158 return mrd;
159 }
160
Craig Tillere50e5cb2015-08-18 12:44:57 -0700161 static bool AsyncWait(CompletionQueue* cq, SyncRequest** req, bool* ok,
162 gpr_timespec deadline) {
163 void* tag = nullptr;
164 *ok = false;
165 switch (cq->AsyncNext(&tag, ok, deadline)) {
166 case CompletionQueue::TIMEOUT:
167 *req = nullptr;
168 return true;
169 case CompletionQueue::SHUTDOWN:
170 *req = nullptr;
171 return false;
172 case CompletionQueue::GOT_EVENT:
173 *req = static_cast<SyncRequest*>(tag);
174 GPR_ASSERT((*req)->in_flight_);
175 return true;
176 }
yang-gb063c872015-10-07 11:40:13 -0700177 GPR_UNREACHABLE_CODE(return false);
Craig Tillere50e5cb2015-08-18 12:44:57 -0700178 }
179
Nicolas "Pixel" Nobleebb51402015-07-23 02:41:33 +0200180 void SetupRequest() { cq_ = grpc_completion_queue_create(nullptr); }
Vijay Paiced73bd2015-06-17 10:23:28 -0700181
182 void TeardownRequest() {
183 grpc_completion_queue_destroy(cq_);
184 cq_ = nullptr;
185 }
186
Craig Tillerf9e6adf2015-05-06 11:45:59 -0700187 void Request(grpc_server* server, grpc_completion_queue* notify_cq) {
Vijay Paiced73bd2015-06-17 10:23:28 -0700188 GPR_ASSERT(cq_ && !in_flight_);
Craig Tillerc4165772015-02-11 10:51:04 -0800189 in_flight_ = true;
yang-g9b7757d2015-08-13 11:15:53 -0700190 if (tag_) {
191 GPR_ASSERT(GRPC_CALL_OK ==
192 grpc_server_request_registered_call(
193 server, tag_, &call_, &deadline_, &request_metadata_,
194 has_request_payload_ ? &request_payload_ : nullptr, cq_,
195 notify_cq, this));
196 } else {
197 if (!call_details_) {
198 call_details_ = new grpc_call_details;
199 grpc_call_details_init(call_details_);
200 }
201 GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call(
202 server, &call_, call_details_,
203 &request_metadata_, cq_, notify_cq, this));
204 }
Craig Tillerc4165772015-02-11 10:51:04 -0800205 }
206
Craig Tillercf133f42015-02-26 14:05:56 -0800207 bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE {
Craig Tillerec3257c2015-02-12 15:59:43 -0800208 if (!*status) {
209 grpc_completion_queue_destroy(cq_);
210 }
yang-g9b7757d2015-08-13 11:15:53 -0700211 if (call_details_) {
212 deadline_ = call_details_->deadline;
213 grpc_call_details_destroy(call_details_);
214 grpc_call_details_init(call_details_);
215 }
Craig Tiller645466e2015-02-18 09:18:33 -0800216 return true;
Craig Tillerec3257c2015-02-12 15:59:43 -0800217 }
Craig Tillerc4165772015-02-11 10:51:04 -0800218
Craig Tillercf133f42015-02-26 14:05:56 -0800219 class CallData GRPC_FINAL {
Craig Tillerc4165772015-02-11 10:51:04 -0800220 public:
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800221 explicit CallData(Server* server, SyncRequest* mrd)
Craig Tillerc4165772015-02-11 10:51:04 -0800222 : cq_(mrd->cq_),
Mark D. Roth69803622016-09-06 08:15:36 -0700223 call_(mrd->call_, server, &cq_, server->max_receive_message_size_),
Craig Tillerc4165772015-02-11 10:51:04 -0800224 ctx_(mrd->deadline_, mrd->request_metadata_.metadata,
225 mrd->request_metadata_.count),
226 has_request_payload_(mrd->has_request_payload_),
Craig Tillerc4165772015-02-11 10:51:04 -0800227 request_payload_(mrd->request_payload_),
228 method_(mrd->method_) {
yang-g85c04f92015-07-07 17:47:31 -0700229 ctx_.set_call(mrd->call_);
Yang Gao1205f6f2015-03-22 15:18:14 -0700230 ctx_.cq_ = &cq_;
Craig Tillerc4165772015-02-11 10:51:04 -0800231 GPR_ASSERT(mrd->in_flight_);
232 mrd->in_flight_ = false;
233 mrd->request_metadata_.count = 0;
234 }
235
Craig Tillerec3257c2015-02-12 15:59:43 -0800236 ~CallData() {
237 if (has_request_payload_ && request_payload_) {
238 grpc_byte_buffer_destroy(request_payload_);
239 }
240 }
241
Craig Tiller64616492016-01-26 14:16:20 -0800242 void Run(std::shared_ptr<GlobalCallbacks> global_callbacks) {
Craig Tiller492968f2015-02-18 13:14:03 -0800243 ctx_.BeginCompletionOp(&call_);
Craig Tiller64616492016-01-26 14:16:20 -0800244 global_callbacks->PreSynchronousRequest(&ctx_);
Craig Tillerce40de52015-06-05 07:14:58 -0700245 method_->handler()->RunHandler(MethodHandler::HandlerParameter(
Mark D. Roth69803622016-09-06 08:15:36 -0700246 &call_, &ctx_, request_payload_, call_.max_receive_message_size()));
Craig Tiller64616492016-01-26 14:16:20 -0800247 global_callbacks->PostSynchronousRequest(&ctx_);
Craig Tiller928ec8e2015-06-05 08:45:45 -0700248 request_payload_ = nullptr;
Craig Tiller492968f2015-02-18 13:14:03 -0800249 void* ignored_tag;
250 bool ignored_ok;
251 cq_.Shutdown();
252 GPR_ASSERT(cq_.Next(&ignored_tag, &ignored_ok) == false);
Craig Tillerc4165772015-02-11 10:51:04 -0800253 }
254
255 private:
256 CompletionQueue cq_;
257 Call call_;
258 ServerContext ctx_;
259 const bool has_request_payload_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800260 grpc_byte_buffer* request_payload_;
261 RpcServiceMethod* const method_;
Craig Tillerc4165772015-02-11 10:51:04 -0800262 };
263
264 private:
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800265 RpcServiceMethod* const method_;
266 void* const tag_;
Craig Tillercf133f42015-02-26 14:05:56 -0800267 bool in_flight_;
Craig Tillerc4165772015-02-11 10:51:04 -0800268 const bool has_request_payload_;
Craig Tiller5987c702016-03-09 16:55:23 -0800269 uint32_t incoming_flags_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800270 grpc_call* call_;
yang-g9b7757d2015-08-13 11:15:53 -0700271 grpc_call_details* call_details_;
Craig Tillerc4165772015-02-11 10:51:04 -0800272 gpr_timespec deadline_;
273 grpc_metadata_array request_metadata_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800274 grpc_byte_buffer* request_payload_;
275 grpc_completion_queue* cq_;
Craig Tillerc4165772015-02-11 10:51:04 -0800276};
277
David Garcia Quintasd79ef3a2016-01-28 00:21:27 -0800278static internal::GrpcLibraryInitializer g_gli_initializer;
Yang Gao3921c562015-04-30 16:07:06 -0700279Server::Server(ThreadPoolInterface* thread_pool, bool thread_pool_owned,
Mark D. Roth69803622016-09-06 08:15:36 -0700280 int max_receive_message_size, ChannelArguments* args)
281 : max_receive_message_size_(max_receive_message_size),
Yang Gao3921c562015-04-30 16:07:06 -0700282 started_(false),
vjpaicad5f0a2015-02-18 22:02:52 -0800283 shutdown_(false),
yang-g6ec11f22016-07-14 14:53:35 -0700284 shutdown_notified_(false),
vjpaicad5f0a2015-02-18 22:02:52 -0800285 num_running_cb_(0),
Nicolas Noble30862032015-04-24 18:17:45 -0700286 sync_methods_(new std::list<SyncRequest>),
yang-g9b7757d2015-08-13 11:15:53 -0700287 has_generic_service_(false),
yang-geb62c942016-02-17 15:37:25 -0800288 server_(nullptr),
vjpaicad5f0a2015-02-18 22:02:52 -0800289 thread_pool_(thread_pool),
Yuchen Zenga42ec212016-04-29 13:03:06 -0700290 thread_pool_owned_(thread_pool_owned),
291 server_initializer_(new ServerInitializer(this)) {
David Garcia Quintasd79ef3a2016-01-28 00:21:27 -0800292 g_gli_initializer.summon();
Craig Tiller8352b9e2015-12-02 11:43:40 -0800293 gpr_once_init(&g_once_init_callbacks, InitGlobalCallbacks);
Craig Tiller64616492016-01-26 14:16:20 -0800294 global_callbacks_ = g_callbacks;
yang-geb62c942016-02-17 15:37:25 -0800295 global_callbacks_->UpdateArguments(args);
296 grpc_channel_args channel_args;
297 args->SetChannelArgs(&channel_args);
298 server_ = grpc_server_create(&channel_args, nullptr);
Craig Tiller3eee9b42016-05-19 11:28:41 -0700299 if (thread_pool_ == nullptr) {
300 grpc_server_register_non_listening_completion_queue(server_, cq_.cq(),
301 nullptr);
302 } else {
303 grpc_server_register_completion_queue(server_, cq_.cq(), nullptr);
304 }
Craig Tillerf9e6adf2015-05-06 11:45:59 -0700305}
vjpaicad5f0a2015-02-18 22:02:52 -0800306
307Server::~Server() {
Ruyi Wangb486ba62015-03-14 22:19:44 +0800308 {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200309 grpc::unique_lock<grpc::mutex> lock(mu_);
Ruyi Wangb486ba62015-03-14 22:19:44 +0800310 if (started_ && !shutdown_) {
311 lock.unlock();
312 Shutdown();
yang-gb9711732016-01-15 16:53:08 -0800313 } else if (!started_) {
314 cq_.Shutdown();
Ruyi Wangb486ba62015-03-14 22:19:44 +0800315 }
vjpaicad5f0a2015-02-18 22:02:52 -0800316 }
Craig Tiller29f79dc2015-05-27 15:59:23 -0700317 void* got_tag;
318 bool ok;
319 GPR_ASSERT(!cq_.Next(&got_tag, &ok));
vjpaicad5f0a2015-02-18 22:02:52 -0800320 grpc_server_destroy(server_);
321 if (thread_pool_owned_) {
322 delete thread_pool_;
323 }
Nicolas Noble30862032015-04-24 18:17:45 -0700324 delete sync_methods_;
vjpaicad5f0a2015-02-18 22:02:52 -0800325}
326
Craig Tiller7221d992015-11-24 06:59:33 -0800327void Server::SetGlobalCallbacks(GlobalCallbacks* callbacks) {
Vijay Paib645a2d2016-06-09 18:39:06 -0700328 GPR_ASSERT(!g_callbacks);
329 GPR_ASSERT(callbacks);
Craig Tiller64616492016-01-26 14:16:20 -0800330 g_callbacks.reset(callbacks);
Craig Tiller7221d992015-11-24 06:59:33 -0800331}
332
Adam Michalik4ad746e2016-06-07 15:02:59 -0700333grpc_server* Server::c_server() { return server_; }
Adam Michalikb97e2d12016-06-02 12:12:55 -0700334
Adam Michalik4ad746e2016-06-07 15:02:59 -0700335CompletionQueue* Server::completion_queue() { return &cq_; }
Adam Michalikb97e2d12016-06-02 12:12:55 -0700336
Craig Tiller06cb1a92016-04-04 08:10:47 -0700337static grpc_server_register_method_payload_handling PayloadHandlingForMethod(
338 RpcServiceMethod* method) {
339 switch (method->method_type()) {
340 case RpcMethod::NORMAL_RPC:
341 case RpcMethod::SERVER_STREAMING:
342 return GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER;
343 case RpcMethod::CLIENT_STREAMING:
344 case RpcMethod::BIDI_STREAMING:
345 return GRPC_SRM_PAYLOAD_NONE;
346 }
347 GPR_UNREACHABLE_CODE(return GRPC_SRM_PAYLOAD_NONE;);
348}
349
Craig Tiller15f383c2016-01-07 12:45:32 -0800350bool Server::RegisterService(const grpc::string* host, Service* service) {
351 bool has_async_methods = service->has_async_methods();
352 if (has_async_methods) {
353 GPR_ASSERT(service->server_ == nullptr &&
354 "Can only register an asynchronous service against one server.");
355 service->server_ = this;
356 }
Yuchen Zenga42ec212016-04-29 13:03:06 -0700357 const char* method_name = nullptr;
Craig Tiller15f383c2016-01-07 12:45:32 -0800358 for (auto it = service->methods_.begin(); it != service->methods_.end();
359 ++it) {
yang-g269b8be2016-01-15 10:46:26 -0800360 if (it->get() == nullptr) { // Handled by generic service if any.
361 continue;
362 }
Craig Tiller15f383c2016-01-07 12:45:32 -0800363 RpcServiceMethod* method = it->get();
Craig Tiller06cb1a92016-04-04 08:10:47 -0700364 void* tag = grpc_server_register_method(
365 server_, method->name(), host ? host->c_str() : nullptr,
366 PayloadHandlingForMethod(method), 0);
Craig Tiller15f383c2016-01-07 12:45:32 -0800367 if (tag == nullptr) {
vjpaicad5f0a2015-02-18 22:02:52 -0800368 gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
369 method->name());
370 return false;
371 }
Craig Tiller15f383c2016-01-07 12:45:32 -0800372 if (method->handler() == nullptr) {
373 method->set_server_tag(tag);
374 } else {
375 sync_methods_->emplace_back(method, tag);
vjpaicad5f0a2015-02-18 22:02:52 -0800376 }
Yuchen Zenga42ec212016-04-29 13:03:06 -0700377 method_name = method->name();
378 }
379
380 // Parse service name.
381 if (method_name != nullptr) {
382 std::stringstream ss(method_name);
383 grpc::string service_name;
384 if (std::getline(ss, service_name, '/') &&
385 std::getline(ss, service_name, '/')) {
386 services_.push_back(service_name);
387 }
vjpaicad5f0a2015-02-18 22:02:52 -0800388 }
389 return true;
390}
391
Yang Gao49996492015-03-12 16:40:19 -0700392void Server::RegisterAsyncGenericService(AsyncGenericService* service) {
Yang Gao1c402332015-03-05 16:39:25 -0800393 GPR_ASSERT(service->server_ == nullptr &&
Yang Gao1ad253d2015-03-16 13:11:29 -0700394 "Can only register an async generic service against one server.");
Yang Gao1c402332015-03-05 16:39:25 -0800395 service->server_ = this;
yang-g9b7757d2015-08-13 11:15:53 -0700396 has_generic_service_ = true;
Yang Gao1c402332015-03-05 16:39:25 -0800397}
398
Nicolas Noblecfd60732015-03-18 16:27:43 -0700399int Server::AddListeningPort(const grpc::string& addr,
400 ServerCredentials* creds) {
vjpaicad5f0a2015-02-18 22:02:52 -0800401 GPR_ASSERT(!started_);
Craig Tiller42bc87c2015-02-23 08:50:19 -0800402 return creds->AddPortToServer(addr, server_);
vjpaicad5f0a2015-02-18 22:02:52 -0800403}
404
Craig Tiller8f7bff72015-08-17 13:23:14 -0700405bool Server::Start(ServerCompletionQueue** cqs, size_t num_cqs) {
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800406 GPR_ASSERT(!started_);
407 started_ = true;
408 grpc_server_start(server_);
409
yang-g9b7757d2015-08-13 11:15:53 -0700410 if (!has_generic_service_) {
Craig Tiller86d31772015-08-19 12:52:50 -0700411 if (!sync_methods_->empty()) {
412 unknown_method_.reset(new RpcServiceMethod(
413 "unknown", RpcMethod::BIDI_STREAMING, new UnknownMethodHandler));
414 // Use of emplace_back with just constructor arguments is not accepted
Julien Boeuf5be92a32015-08-28 16:28:18 -0700415 // here by gcc-4.4 because it can't match the anonymous nullptr with a
Craig Tiller849c7ca2015-08-21 16:06:05 -0700416 // proper constructor implicitly. Construct the object and use push_back.
Craig Tiller86d31772015-08-19 12:52:50 -0700417 sync_methods_->push_back(SyncRequest(unknown_method_.get(), nullptr));
418 }
Craig Tiller8f7bff72015-08-17 13:23:14 -0700419 for (size_t i = 0; i < num_cqs; i++) {
Craig Tillere0049582016-05-20 10:31:09 -0700420 if (cqs[i]->IsFrequentlyPolled()) {
421 new UnimplementedAsyncRequest(this, cqs[i]);
422 }
Craig Tillercbd04852015-02-10 17:39:54 -0800423 }
yang-g9b7757d2015-08-13 11:15:53 -0700424 }
Craig Tillercbd04852015-02-10 17:39:54 -0800425 // Start processing rpcs.
426 if (!sync_methods_->empty()) {
427 for (auto m = sync_methods_->begin(); m != sync_methods_->end(); m++) {
428 m->SetupRequest();
Craig Tiller7c72adc2015-02-09 14:07:26 -0800429 m->Request(server_, cq_.cq());
430 }
Craig Tiller0db1bef2015-02-09 13:47:39 -0800431
432 ScheduleCallback();
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800433 }
434
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800435 return true;
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200436}
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800437
Craig Tillere50e5cb2015-08-18 12:44:57 -0700438void Server::ShutdownInternal(gpr_timespec deadline) {
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800439 grpc::unique_lock<grpc::mutex> lock(mu_);
440 if (started_ && !shutdown_) {
441 shutdown_ = true;
Craig Tillerbce999f2015-05-27 09:55:51 -0700442 grpc_server_shutdown_and_notify(server_, cq_.cq(), new ShutdownRequest());
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800443 cq_.Shutdown();
Craig Tiller59256032015-11-02 14:19:15 -0800444 lock.unlock();
Craig Tiller9374ce82015-08-19 10:15:44 -0700445 // Spin, eating requests until the completion queue is completely shutdown.
446 // If the deadline expires then cancel anything that's pending and keep
447 // spinning forever until the work is actually drained.
Julien Boeuf5be92a32015-08-28 16:28:18 -0700448 // Since nothing else needs to touch state guarded by mu_, holding it
Craig Tiller681a2912015-08-19 11:31:25 -0700449 // through this loop is fine.
Craig Tillere50e5cb2015-08-18 12:44:57 -0700450 SyncRequest* request;
451 bool ok;
452 while (SyncRequest::AsyncWait(&cq_, &request, &ok, deadline)) {
453 if (request == NULL) { // deadline expired
454 grpc_server_cancel_all_calls(server_);
Craig Tiller9374ce82015-08-19 10:15:44 -0700455 deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC);
Craig Tillere50e5cb2015-08-18 12:44:57 -0700456 } else if (ok) {
457 SyncRequest::CallData call_data(this, request);
458 }
459 }
Craig Tiller59256032015-11-02 14:19:15 -0800460 lock.lock();
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800461
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800462 // Wait for running callbacks to finish.
463 while (num_running_cb_ != 0) {
464 callback_cv_.wait(lock);
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800465 }
yang-g6ec11f22016-07-14 14:53:35 -0700466
467 shutdown_notified_ = true;
yang-ge89dc6c2016-07-11 15:48:01 -0700468 shutdown_cv_.notify_all();
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800469 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800470}
471
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800472void Server::Wait() {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200473 grpc::unique_lock<grpc::mutex> lock(mu_);
yang-g6ec11f22016-07-14 14:53:35 -0700474 while (started_ && !shutdown_notified_) {
475 shutdown_cv_.wait(lock);
476 }
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800477}
478
Craig Tiller50a7a682015-06-04 12:53:40 -0700479void Server::PerformOpsOnCall(CallOpSetInterface* ops, Call* call) {
Craig Tillerbb5227f2015-02-11 13:34:48 -0800480 static const size_t MAX_OPS = 8;
Craig Tiller50a7a682015-06-04 12:53:40 -0700481 size_t nops = 0;
482 grpc_op cops[MAX_OPS];
483 ops->FillOps(cops, &nops);
Nicolas "Pixel" Nobleebb51402015-07-23 02:41:33 +0200484 auto result = grpc_call_start_batch(call->call(), cops, nops, ops, nullptr);
485 GPR_ASSERT(GRPC_CALL_OK == result);
Craig Tillerbb5227f2015-02-11 13:34:48 -0800486}
487
David Garcia Quintas44f32492016-01-14 18:00:04 -0800488ServerInterface::BaseAsyncRequest::BaseAsyncRequest(
489 ServerInterface* server, ServerContext* context,
Craig Tiller8f7bff72015-08-17 13:23:14 -0700490 ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag,
491 bool delete_on_finalize)
Craig Tillerce40de52015-06-05 07:14:58 -0700492 : server_(server),
493 context_(context),
494 stream_(stream),
495 call_cq_(call_cq),
Craig Tiller50955812015-06-05 08:03:17 -0700496 tag_(tag),
Craig Tiller8f7bff72015-08-17 13:23:14 -0700497 delete_on_finalize_(delete_on_finalize),
Craig Tillerce40de52015-06-05 07:14:58 -0700498 call_(nullptr) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700499 memset(&initial_metadata_array_, 0, sizeof(initial_metadata_array_));
500}
501
David Garcia Quintasf3ddb7c2016-01-20 16:02:22 -0800502bool ServerInterface::BaseAsyncRequest::FinalizeResult(void** tag,
503 bool* status) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700504 if (*status) {
505 for (size_t i = 0; i < initial_metadata_array_.count; i++) {
yang-ge21908f2015-08-25 13:47:51 -0700506 context_->client_metadata_.insert(
507 std::pair<grpc::string_ref, grpc::string_ref>(
508 initial_metadata_array_.metadata[i].key,
509 grpc::string_ref(
510 initial_metadata_array_.metadata[i].value,
511 initial_metadata_array_.metadata[i].value_length)));
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700512 }
513 }
Craig Tiller2f4a49c2015-06-05 09:36:52 -0700514 grpc_metadata_array_destroy(&initial_metadata_array_);
yang-g85c04f92015-07-07 17:47:31 -0700515 context_->set_call(call_);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700516 context_->cq_ = call_cq_;
Mark D. Roth69803622016-09-06 08:15:36 -0700517 Call call(call_, server_, call_cq_, server_->max_receive_message_size());
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700518 if (*status && call_) {
519 context_->BeginCompletionOp(&call);
520 }
521 // just the pointers inside call are copied here
522 stream_->BindCall(&call);
Craig Tiller50955812015-06-05 08:03:17 -0700523 *tag = tag_;
Craig Tiller8f7bff72015-08-17 13:23:14 -0700524 if (delete_on_finalize_) {
525 delete this;
526 }
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700527 return true;
528}
529
David Garcia Quintas44f32492016-01-14 18:00:04 -0800530ServerInterface::RegisteredAsyncRequest::RegisteredAsyncRequest(
531 ServerInterface* server, ServerContext* context,
Craig Tillerce40de52015-06-05 07:14:58 -0700532 ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag)
Craig Tiller8f7bff72015-08-17 13:23:14 -0700533 : BaseAsyncRequest(server, context, stream, call_cq, tag, true) {}
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700534
David Garcia Quintas44f32492016-01-14 18:00:04 -0800535void ServerInterface::RegisteredAsyncRequest::IssueRequest(
Craig Tillerce40de52015-06-05 07:14:58 -0700536 void* registered_method, grpc_byte_buffer** payload,
537 ServerCompletionQueue* notification_cq) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700538 grpc_server_request_registered_call(
David Garcia Quintas44f32492016-01-14 18:00:04 -0800539 server_->server(), registered_method, &call_, &context_->deadline_,
Craig Tillerce40de52015-06-05 07:14:58 -0700540 &initial_metadata_array_, payload, call_cq_->cq(), notification_cq->cq(),
541 this);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700542}
543
David Garcia Quintas44f32492016-01-14 18:00:04 -0800544ServerInterface::GenericAsyncRequest::GenericAsyncRequest(
545 ServerInterface* server, GenericServerContext* context,
Craig Tillerce40de52015-06-05 07:14:58 -0700546 ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
Craig Tiller8f7bff72015-08-17 13:23:14 -0700547 ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
548 : BaseAsyncRequest(server, context, stream, call_cq, tag,
549 delete_on_finalize) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700550 grpc_call_details_init(&call_details_);
551 GPR_ASSERT(notification_cq);
552 GPR_ASSERT(call_cq);
David Garcia Quintas44f32492016-01-14 18:00:04 -0800553 grpc_server_request_call(server->server(), &call_, &call_details_,
Craig Tillerce40de52015-06-05 07:14:58 -0700554 &initial_metadata_array_, call_cq->cq(),
555 notification_cq->cq(), this);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700556}
557
David Garcia Quintasf3ddb7c2016-01-20 16:02:22 -0800558bool ServerInterface::GenericAsyncRequest::FinalizeResult(void** tag,
559 bool* status) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700560 // TODO(yangg) remove the copy here.
yang-g3deb0062015-06-23 14:06:08 -0700561 if (*status) {
yang-ga58cab32015-06-23 14:37:15 -0700562 static_cast<GenericServerContext*>(context_)->method_ =
563 call_details_.method;
yang-g3deb0062015-06-23 14:06:08 -0700564 static_cast<GenericServerContext*>(context_)->host_ = call_details_.host;
yang-g3deb0062015-06-23 14:06:08 -0700565 }
yang-ga58cab32015-06-23 14:37:15 -0700566 gpr_free(call_details_.method);
567 gpr_free(call_details_.host);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700568 return BaseAsyncRequest::FinalizeResult(tag, status);
569}
570
Craig Tiller8f7bff72015-08-17 13:23:14 -0700571bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag,
572 bool* status) {
573 if (GenericAsyncRequest::FinalizeResult(tag, status) && *status) {
574 new UnimplementedAsyncRequest(server_, cq_);
575 new UnimplementedAsyncResponse(this);
576 } else {
577 delete this;
578 }
579 return false;
580}
581
582Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse(
583 UnimplementedAsyncRequest* request)
584 : request_(request) {
585 Status status(StatusCode::UNIMPLEMENTED, "");
586 UnknownMethodHandler::FillOps(request_->context(), this);
587 request_->stream()->call_.PerformOps(this);
588}
589
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800590void Server::ScheduleCallback() {
591 {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200592 grpc::unique_lock<grpc::mutex> lock(mu_);
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800593 num_running_cb_++;
594 }
vjpai72a44172015-07-16 21:44:44 -0700595 thread_pool_->Add(std::bind(&Server::RunRpc, this));
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800596}
597
598void Server::RunRpc() {
599 // Wait for one more incoming rpc.
Craig Tillerc4165772015-02-11 10:51:04 -0800600 bool ok;
Craig Tiller0ba432d2015-10-09 16:57:11 -0700601 GPR_TIMER_SCOPE("Server::RunRpc", 0);
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800602 auto* mrd = SyncRequest::Wait(&cq_, &ok);
Craig Tillercbd04852015-02-10 17:39:54 -0800603 if (mrd) {
Craig Tillerbd217572015-02-11 18:10:56 -0800604 ScheduleCallback();
Craig Tillerc4165772015-02-11 10:51:04 -0800605 if (ok) {
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800606 SyncRequest::CallData cd(this, mrd);
Yang Gaob8a5f862015-05-07 16:26:33 -0700607 {
Vijay Paiced73bd2015-06-17 10:23:28 -0700608 mrd->SetupRequest();
Yang Gaob8a5f862015-05-07 16:26:33 -0700609 grpc::unique_lock<grpc::mutex> lock(mu_);
610 if (!shutdown_) {
Craig Tillera33acb72015-05-08 08:02:55 -0700611 mrd->Request(server_, cq_.cq());
Vijay Paiced73bd2015-06-17 10:23:28 -0700612 } else {
613 // destroy the structure that was created
614 mrd->TeardownRequest();
Yang Gaob8a5f862015-05-07 16:26:33 -0700615 }
616 }
Craig Tiller0ba432d2015-10-09 16:57:11 -0700617 GPR_TIMER_SCOPE("cd.Run()", 0);
Craig Tiller64616492016-01-26 14:16:20 -0800618 cd.Run(global_callbacks_);
Craig Tillerc4165772015-02-11 10:51:04 -0800619 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800620 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800621
622 {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200623 grpc::unique_lock<grpc::mutex> lock(mu_);
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800624 num_running_cb_--;
625 if (shutdown_) {
626 callback_cv_.notify_all();
627 }
628 }
629}
630
Yuchen Zenga42ec212016-04-29 13:03:06 -0700631ServerInitializer* Server::initializer() { return server_initializer_.get(); }
632
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800633} // namespace grpc