blob: 7f32848e29e9c27c1010c2de541dee8e1cc4eca7 [file] [log] [blame]
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08001/*
Craig Tiller6169d5f2016-03-31 07:46:18 -07002 * Copyright 2015, Google Inc.
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -08003 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met:
8 *
9 * * Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following disclaimer
13 * in the documentation and/or other materials provided with the
14 * distribution.
15 * * Neither the name of Google Inc. nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 *
31 */
32
33#include <grpc++/server.h>
yang-g9e2f90c2015-08-21 15:35:03 -070034
Yuchen Zenga42ec212016-04-29 13:03:06 -070035#include <sstream>
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>
Yuchen Zenga42ec212016-04-29 13:03:06 -070044#include <grpc++/impl/server_initializer.h>
Craig Tiller8c8d0aa2015-02-12 11:38:36 -080045#include <grpc++/impl/service_type.h>
Julien Boeuf5be92a32015-08-28 16:28:18 -070046#include <grpc++/security/server_credentials.h>
David Garcia Quintase1300de2016-01-27 18:41:26 -080047#include <grpc++/server_context.h>
yang-g9e2f90c2015-08-21 15:35:03 -070048#include <grpc++/support/time.h>
David Garcia Quintase1300de2016-01-27 18:41:26 -080049#include <grpc/grpc.h>
50#include <grpc/support/alloc.h>
51#include <grpc/support/log.h>
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080052
Craig Tiller9533d042016-03-25 17:11:06 -070053#include "src/core/lib/profiling/timers.h"
Sree Kuchibhotlaf72ec6b2016-10-24 11:09:43 -070054#include "src/cpp/thread_manager/thread_manager.h"
Craig Tillerc4165772015-02-11 10:51:04 -080055
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -080056namespace grpc {
57
Vijay Paic0b2acb2016-11-01 16:31:56 -070058class DefaultGlobalCallbacks final : public Server::GlobalCallbacks {
Craig Tiller7221d992015-11-24 06:59:33 -080059 public:
Vijay Paic0b2acb2016-11-01 16:31:56 -070060 ~DefaultGlobalCallbacks() override {}
61 void PreSynchronousRequest(ServerContext* context) override {}
62 void PostSynchronousRequest(ServerContext* context) override {}
Craig Tiller7221d992015-11-24 06:59:33 -080063};
64
Craig Tiller64616492016-01-26 14:16:20 -080065static std::shared_ptr<Server::GlobalCallbacks> g_callbacks = nullptr;
Craig Tiller8352b9e2015-12-02 11:43:40 -080066static gpr_once g_once_init_callbacks = GPR_ONCE_INIT;
67
Craig Tiller8352b9e2015-12-02 11:43:40 -080068static void InitGlobalCallbacks() {
Vijay Paib645a2d2016-06-09 18:39:06 -070069 if (!g_callbacks) {
Craig Tiller64616492016-01-26 14:16:20 -080070 g_callbacks.reset(new DefaultGlobalCallbacks());
Craig Tiller8352b9e2015-12-02 11:43:40 -080071 }
72}
Craig Tiller7221d992015-11-24 06:59:33 -080073
Craig Tiller8f7bff72015-08-17 13:23:14 -070074class Server::UnimplementedAsyncRequestContext {
75 protected:
76 UnimplementedAsyncRequestContext() : generic_stream_(&server_context_) {}
77
78 GenericServerContext server_context_;
79 GenericServerAsyncReaderWriter generic_stream_;
80};
81
Vijay Paic0b2acb2016-11-01 16:31:56 -070082class Server::UnimplementedAsyncRequest final
Craig Tiller8f7bff72015-08-17 13:23:14 -070083 : public UnimplementedAsyncRequestContext,
84 public GenericAsyncRequest {
85 public:
86 UnimplementedAsyncRequest(Server* server, ServerCompletionQueue* cq)
87 : GenericAsyncRequest(server, &server_context_, &generic_stream_, cq, cq,
88 NULL, false),
89 server_(server),
90 cq_(cq) {}
91
Vijay Paic0b2acb2016-11-01 16:31:56 -070092 bool FinalizeResult(void** tag, bool* status) override;
Craig Tiller8f7bff72015-08-17 13:23:14 -070093
94 ServerContext* context() { return &server_context_; }
95 GenericServerAsyncReaderWriter* stream() { return &generic_stream_; }
96
97 private:
98 Server* const server_;
99 ServerCompletionQueue* const cq_;
100};
101
102typedef SneakyCallOpSet<CallOpSendInitialMetadata, CallOpServerSendStatus>
103 UnimplementedAsyncResponseOp;
Vijay Paic0b2acb2016-11-01 16:31:56 -0700104class Server::UnimplementedAsyncResponse final
Craig Tiller8f7bff72015-08-17 13:23:14 -0700105 : public UnimplementedAsyncResponseOp {
106 public:
107 UnimplementedAsyncResponse(UnimplementedAsyncRequest* request);
108 ~UnimplementedAsyncResponse() { delete request_; }
109
Vijay Paic0b2acb2016-11-01 16:31:56 -0700110 bool FinalizeResult(void** tag, bool* status) override {
Craig Tiller8f7bff72015-08-17 13:23:14 -0700111 bool r = UnimplementedAsyncResponseOp::FinalizeResult(tag, status);
112 delete this;
113 return r;
114 }
115
116 private:
117 UnimplementedAsyncRequest* const request_;
118};
119
Sree Kuchibhotla4028d2c2016-09-21 10:45:33 -0700120class ShutdownTag : public CompletionQueueTag {
121 public:
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700122 bool FinalizeResult(void** tag, bool* status) { return false; }
Sree Kuchibhotla4028d2c2016-09-21 10:45:33 -0700123};
124
Vijay Paic0b2acb2016-11-01 16:31:56 -0700125class Server::SyncRequest final : public CompletionQueueTag {
Craig Tillerc4165772015-02-11 10:51:04 -0800126 public:
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800127 SyncRequest(RpcServiceMethod* method, void* tag)
Craig Tillerc4165772015-02-11 10:51:04 -0800128 : method_(method),
129 tag_(tag),
Craig Tillercf133f42015-02-26 14:05:56 -0800130 in_flight_(false),
Craig Tillerc4165772015-02-11 10:51:04 -0800131 has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC ||
132 method->method_type() ==
133 RpcMethod::SERVER_STREAMING),
yang-g9b7757d2015-08-13 11:15:53 -0700134 call_details_(nullptr),
Vijay Paiced73bd2015-06-17 10:23:28 -0700135 cq_(nullptr) {
Craig Tillerc4165772015-02-11 10:51:04 -0800136 grpc_metadata_array_init(&request_metadata_);
137 }
138
yang-g9b7757d2015-08-13 11:15:53 -0700139 ~SyncRequest() {
140 if (call_details_) {
141 delete call_details_;
142 }
143 grpc_metadata_array_destroy(&request_metadata_);
144 }
Yang Gao7b49a772015-05-28 14:07:54 -0700145
Nicolas "Pixel" Nobleebb51402015-07-23 02:41:33 +0200146 void SetupRequest() { cq_ = grpc_completion_queue_create(nullptr); }
Vijay Paiced73bd2015-06-17 10:23:28 -0700147
148 void TeardownRequest() {
149 grpc_completion_queue_destroy(cq_);
150 cq_ = nullptr;
151 }
152
Craig Tillerf9e6adf2015-05-06 11:45:59 -0700153 void Request(grpc_server* server, grpc_completion_queue* notify_cq) {
Vijay Paiced73bd2015-06-17 10:23:28 -0700154 GPR_ASSERT(cq_ && !in_flight_);
Craig Tillerc4165772015-02-11 10:51:04 -0800155 in_flight_ = true;
yang-g9b7757d2015-08-13 11:15:53 -0700156 if (tag_) {
157 GPR_ASSERT(GRPC_CALL_OK ==
158 grpc_server_request_registered_call(
159 server, tag_, &call_, &deadline_, &request_metadata_,
160 has_request_payload_ ? &request_payload_ : nullptr, cq_,
161 notify_cq, this));
162 } else {
163 if (!call_details_) {
164 call_details_ = new grpc_call_details;
165 grpc_call_details_init(call_details_);
166 }
167 GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call(
168 server, &call_, call_details_,
169 &request_metadata_, cq_, notify_cq, this));
170 }
Craig Tillerc4165772015-02-11 10:51:04 -0800171 }
172
Vijay Paic0b2acb2016-11-01 16:31:56 -0700173 bool FinalizeResult(void** tag, bool* status) override {
Craig Tillerec3257c2015-02-12 15:59:43 -0800174 if (!*status) {
175 grpc_completion_queue_destroy(cq_);
176 }
yang-g9b7757d2015-08-13 11:15:53 -0700177 if (call_details_) {
178 deadline_ = call_details_->deadline;
179 grpc_call_details_destroy(call_details_);
180 grpc_call_details_init(call_details_);
181 }
Craig Tiller645466e2015-02-18 09:18:33 -0800182 return true;
Craig Tillerec3257c2015-02-12 15:59:43 -0800183 }
Craig Tillerc4165772015-02-11 10:51:04 -0800184
Vijay Paic0b2acb2016-11-01 16:31:56 -0700185 class CallData final {
Craig Tillerc4165772015-02-11 10:51:04 -0800186 public:
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800187 explicit CallData(Server* server, SyncRequest* mrd)
Craig Tillerc4165772015-02-11 10:51:04 -0800188 : cq_(mrd->cq_),
Mark D. Roth69803622016-09-06 08:15:36 -0700189 call_(mrd->call_, server, &cq_, server->max_receive_message_size_),
Craig Tillerc4165772015-02-11 10:51:04 -0800190 ctx_(mrd->deadline_, mrd->request_metadata_.metadata,
191 mrd->request_metadata_.count),
192 has_request_payload_(mrd->has_request_payload_),
Craig Tillerc4165772015-02-11 10:51:04 -0800193 request_payload_(mrd->request_payload_),
194 method_(mrd->method_) {
yang-g85c04f92015-07-07 17:47:31 -0700195 ctx_.set_call(mrd->call_);
Yang Gao1205f6f2015-03-22 15:18:14 -0700196 ctx_.cq_ = &cq_;
Craig Tillerc4165772015-02-11 10:51:04 -0800197 GPR_ASSERT(mrd->in_flight_);
198 mrd->in_flight_ = false;
199 mrd->request_metadata_.count = 0;
200 }
201
Craig Tillerec3257c2015-02-12 15:59:43 -0800202 ~CallData() {
203 if (has_request_payload_ && request_payload_) {
204 grpc_byte_buffer_destroy(request_payload_);
205 }
206 }
207
Craig Tiller64616492016-01-26 14:16:20 -0800208 void Run(std::shared_ptr<GlobalCallbacks> global_callbacks) {
Craig Tiller492968f2015-02-18 13:14:03 -0800209 ctx_.BeginCompletionOp(&call_);
Craig Tiller64616492016-01-26 14:16:20 -0800210 global_callbacks->PreSynchronousRequest(&ctx_);
Craig Tillerce40de52015-06-05 07:14:58 -0700211 method_->handler()->RunHandler(MethodHandler::HandlerParameter(
Mark D. Roth69803622016-09-06 08:15:36 -0700212 &call_, &ctx_, request_payload_, call_.max_receive_message_size()));
Craig Tiller64616492016-01-26 14:16:20 -0800213 global_callbacks->PostSynchronousRequest(&ctx_);
Craig Tiller928ec8e2015-06-05 08:45:45 -0700214 request_payload_ = nullptr;
Craig Tiller492968f2015-02-18 13:14:03 -0800215 void* ignored_tag;
216 bool ignored_ok;
217 cq_.Shutdown();
218 GPR_ASSERT(cq_.Next(&ignored_tag, &ignored_ok) == false);
Craig Tillerc4165772015-02-11 10:51:04 -0800219 }
220
221 private:
222 CompletionQueue cq_;
223 Call call_;
224 ServerContext ctx_;
225 const bool has_request_payload_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800226 grpc_byte_buffer* request_payload_;
227 RpcServiceMethod* const method_;
Craig Tillerc4165772015-02-11 10:51:04 -0800228 };
229
230 private:
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800231 RpcServiceMethod* const method_;
232 void* const tag_;
Craig Tillercf133f42015-02-26 14:05:56 -0800233 bool in_flight_;
Craig Tillerc4165772015-02-11 10:51:04 -0800234 const bool has_request_payload_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800235 grpc_call* call_;
yang-g9b7757d2015-08-13 11:15:53 -0700236 grpc_call_details* call_details_;
Craig Tillerc4165772015-02-11 10:51:04 -0800237 gpr_timespec deadline_;
238 grpc_metadata_array request_metadata_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800239 grpc_byte_buffer* request_payload_;
240 grpc_completion_queue* cq_;
Craig Tillerc4165772015-02-11 10:51:04 -0800241};
242
Sree Kuchibhotla8f7739b2016-10-13 15:12:55 -0700243// Implementation of ThreadManager. Each instance of SyncRequestThreadManager
244// manages a pool of threads that poll for incoming Sync RPCs and call the
245// appropriate RPC handlers
246class Server::SyncRequestThreadManager : public ThreadManager {
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700247 public:
Sree Kuchibhotla8f7739b2016-10-13 15:12:55 -0700248 SyncRequestThreadManager(Server* server, CompletionQueue* server_cq,
249 std::shared_ptr<GlobalCallbacks> global_callbacks,
250 int min_pollers, int max_pollers,
251 int cq_timeout_msec)
252 : ThreadManager(min_pollers, max_pollers),
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700253 server_(server),
254 server_cq_(server_cq),
Sree Kuchibhotla892dbf42016-09-27 19:42:27 -0700255 cq_timeout_msec_(cq_timeout_msec),
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700256 global_callbacks_(global_callbacks) {}
257
Vijay Paic0b2acb2016-11-01 16:31:56 -0700258 WorkStatus PollForWork(void** tag, bool* ok) override {
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700259 *tag = nullptr;
260 gpr_timespec deadline =
Sree Kuchibhotla892dbf42016-09-27 19:42:27 -0700261 gpr_time_from_millis(cq_timeout_msec_, GPR_TIMESPAN);
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700262
263 switch (server_cq_->AsyncNext(tag, ok, deadline)) {
264 case CompletionQueue::TIMEOUT:
265 return TIMEOUT;
266 case CompletionQueue::SHUTDOWN:
267 return SHUTDOWN;
268 case CompletionQueue::GOT_EVENT:
269 return WORK_FOUND;
270 }
271
272 GPR_UNREACHABLE_CODE(return TIMEOUT);
273 }
274
Vijay Paic0b2acb2016-11-01 16:31:56 -0700275 void DoWork(void* tag, bool ok) override {
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700276 SyncRequest* sync_req = static_cast<SyncRequest*>(tag);
Sree Kuchibhotla4306eee2016-09-21 09:56:29 -0700277
278 if (!sync_req) {
Sree Kuchibhotla33382d02016-10-03 15:08:48 -0700279 // No tag. Nothing to work on. This is an unlikley scenario and possibly a
280 // bug in RPC Manager implementation.
281 gpr_log(GPR_ERROR, "Sync server. DoWork() was called with NULL tag");
Sree Kuchibhotla4306eee2016-09-21 09:56:29 -0700282 return;
283 }
284
285 if (ok) {
Sree Kuchibhotla33382d02016-10-03 15:08:48 -0700286 // Calldata takes ownership of the completion queue inside sync_req
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700287 SyncRequest::CallData cd(server_, sync_req);
288 {
Sree Kuchibhotla33382d02016-10-03 15:08:48 -0700289 // Prepare for the next request
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700290 if (!IsShutdown()) {
Sree Kuchibhotla33382d02016-10-03 15:08:48 -0700291 sync_req->SetupRequest(); // Create new completion queue for sync_req
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700292 sync_req->Request(server_->c_server(), server_cq_->cq());
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700293 }
294 }
Sree Kuchibhotla33382d02016-10-03 15:08:48 -0700295
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700296 GPR_TIMER_SCOPE("cd.Run()", 0);
297 cd.Run(global_callbacks_);
298 }
Sree Kuchibhotla33382d02016-10-03 15:08:48 -0700299 // TODO (sreek) If ok is false here (which it isn't in case of
300 // grpc_request_registered_call), we should still re-queue the request
301 // object
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700302 }
303
304 void AddSyncMethod(RpcServiceMethod* method, void* tag) {
Sree Kuchibhotlacb18d7a2016-10-20 12:39:30 -0700305 sync_requests_.emplace_back(new SyncRequest(method, tag));
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700306 }
307
308 void AddUnknownSyncMethod() {
Sree Kuchibhotlada069a52016-10-19 11:22:29 -0700309 if (!sync_requests_.empty()) {
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700310 unknown_method_.reset(new RpcServiceMethod(
311 "unknown", RpcMethod::BIDI_STREAMING, new UnknownMethodHandler));
Sree Kuchibhotlacb18d7a2016-10-20 12:39:30 -0700312 sync_requests_.emplace_back(
313 new SyncRequest(unknown_method_.get(), nullptr));
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700314 }
315 }
316
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700317 void ShutdownAndDrainCompletionQueue() {
318 server_cq_->Shutdown();
319
320 // Drain any pending items from the queue
321 void* tag;
322 bool ok;
323 while (server_cq_->Next(&tag, &ok)) {
324 // Nothing to be done here
325 }
326 }
327
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700328 void Start() {
Sree Kuchibhotlada069a52016-10-19 11:22:29 -0700329 if (!sync_requests_.empty()) {
330 for (auto m = sync_requests_.begin(); m != sync_requests_.end(); m++) {
Sree Kuchibhotlacb18d7a2016-10-20 12:39:30 -0700331 (*m)->SetupRequest();
332 (*m)->Request(server_->c_server(), server_cq_->cq());
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700333 }
334
Sree Kuchibhotlacb18d7a2016-10-20 12:39:30 -0700335 Initialize(); // ThreadManager's Initialize()
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700336 }
337 }
338
339 private:
340 Server* server_;
341 CompletionQueue* server_cq_;
Sree Kuchibhotla892dbf42016-09-27 19:42:27 -0700342 int cq_timeout_msec_;
Sree Kuchibhotlacb18d7a2016-10-20 12:39:30 -0700343 std::vector<std::unique_ptr<SyncRequest>> sync_requests_;
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700344 std::unique_ptr<RpcServiceMethod> unknown_method_;
345 std::shared_ptr<Server::GlobalCallbacks> global_callbacks_;
346};
347
David Garcia Quintasd79ef3a2016-01-28 00:21:27 -0800348static internal::GrpcLibraryInitializer g_gli_initializer;
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700349Server::Server(
Sree Kuchibhotlae4eb51f2016-10-18 11:51:28 -0700350 int max_receive_message_size, ChannelArguments* args,
Sree Kuchibhotla4028d2c2016-09-21 10:45:33 -0700351 std::shared_ptr<std::vector<std::unique_ptr<ServerCompletionQueue>>>
352 sync_server_cqs,
Sree Kuchibhotlae4eb51f2016-10-18 11:51:28 -0700353 int min_pollers, int max_pollers, int sync_cq_timeout_msec)
Mark D. Roth69803622016-09-06 08:15:36 -0700354 : max_receive_message_size_(max_receive_message_size),
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700355 sync_server_cqs_(sync_server_cqs),
Yang Gao3921c562015-04-30 16:07:06 -0700356 started_(false),
vjpaicad5f0a2015-02-18 22:02:52 -0800357 shutdown_(false),
yang-g6ec11f22016-07-14 14:53:35 -0700358 shutdown_notified_(false),
yang-g9b7757d2015-08-13 11:15:53 -0700359 has_generic_service_(false),
yang-geb62c942016-02-17 15:37:25 -0800360 server_(nullptr),
Yuchen Zenga42ec212016-04-29 13:03:06 -0700361 server_initializer_(new ServerInitializer(this)) {
David Garcia Quintasd79ef3a2016-01-28 00:21:27 -0800362 g_gli_initializer.summon();
Craig Tiller8352b9e2015-12-02 11:43:40 -0800363 gpr_once_init(&g_once_init_callbacks, InitGlobalCallbacks);
Craig Tiller64616492016-01-26 14:16:20 -0800364 global_callbacks_ = g_callbacks;
yang-geb62c942016-02-17 15:37:25 -0800365 global_callbacks_->UpdateArguments(args);
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700366
367 for (auto it = sync_server_cqs_->begin(); it != sync_server_cqs_->end();
368 it++) {
Sree Kuchibhotla8f7739b2016-10-13 15:12:55 -0700369 sync_req_mgrs_.emplace_back(new SyncRequestThreadManager(
370 this, (*it).get(), global_callbacks_, min_pollers, max_pollers,
371 sync_cq_timeout_msec));
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700372 }
373
yang-geb62c942016-02-17 15:37:25 -0800374 grpc_channel_args channel_args;
375 args->SetChannelArgs(&channel_args);
Sree Kuchibhotla3ea9e242016-08-22 14:15:43 -0700376
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700377 server_ = grpc_server_create(&channel_args, nullptr);
Craig Tillerf9e6adf2015-05-06 11:45:59 -0700378}
vjpaicad5f0a2015-02-18 22:02:52 -0800379
380Server::~Server() {
Ruyi Wangb486ba62015-03-14 22:19:44 +0800381 {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200382 grpc::unique_lock<grpc::mutex> lock(mu_);
Ruyi Wangb486ba62015-03-14 22:19:44 +0800383 if (started_ && !shutdown_) {
384 lock.unlock();
385 Shutdown();
yang-gb9711732016-01-15 16:53:08 -0800386 } else if (!started_) {
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700387 // Shutdown the completion queues
388 for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
389 (*it)->ShutdownAndDrainCompletionQueue();
Sree Kuchibhotla4306eee2016-09-21 09:56:29 -0700390 }
Ruyi Wangb486ba62015-03-14 22:19:44 +0800391 }
vjpaicad5f0a2015-02-18 22:02:52 -0800392 }
Sree Kuchibhotlabb5519f2016-07-19 11:00:39 -0700393
vjpaicad5f0a2015-02-18 22:02:52 -0800394 grpc_server_destroy(server_);
vjpaicad5f0a2015-02-18 22:02:52 -0800395}
396
Craig Tiller7221d992015-11-24 06:59:33 -0800397void Server::SetGlobalCallbacks(GlobalCallbacks* callbacks) {
Vijay Paib645a2d2016-06-09 18:39:06 -0700398 GPR_ASSERT(!g_callbacks);
399 GPR_ASSERT(callbacks);
Craig Tiller64616492016-01-26 14:16:20 -0800400 g_callbacks.reset(callbacks);
Craig Tiller7221d992015-11-24 06:59:33 -0800401}
402
Adam Michalik4ad746e2016-06-07 15:02:59 -0700403grpc_server* Server::c_server() { return server_; }
Adam Michalikb97e2d12016-06-02 12:12:55 -0700404
Craig Tiller06cb1a92016-04-04 08:10:47 -0700405static grpc_server_register_method_payload_handling PayloadHandlingForMethod(
406 RpcServiceMethod* method) {
407 switch (method->method_type()) {
408 case RpcMethod::NORMAL_RPC:
409 case RpcMethod::SERVER_STREAMING:
410 return GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER;
411 case RpcMethod::CLIENT_STREAMING:
412 case RpcMethod::BIDI_STREAMING:
413 return GRPC_SRM_PAYLOAD_NONE;
414 }
415 GPR_UNREACHABLE_CODE(return GRPC_SRM_PAYLOAD_NONE;);
416}
417
Craig Tiller15f383c2016-01-07 12:45:32 -0800418bool Server::RegisterService(const grpc::string* host, Service* service) {
419 bool has_async_methods = service->has_async_methods();
420 if (has_async_methods) {
421 GPR_ASSERT(service->server_ == nullptr &&
422 "Can only register an asynchronous service against one server.");
423 service->server_ = this;
424 }
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700425
Yuchen Zenga42ec212016-04-29 13:03:06 -0700426 const char* method_name = nullptr;
Craig Tiller15f383c2016-01-07 12:45:32 -0800427 for (auto it = service->methods_.begin(); it != service->methods_.end();
428 ++it) {
yang-g269b8be2016-01-15 10:46:26 -0800429 if (it->get() == nullptr) { // Handled by generic service if any.
430 continue;
431 }
Sree Kuchibhotlada069a52016-10-19 11:22:29 -0700432
Craig Tiller15f383c2016-01-07 12:45:32 -0800433 RpcServiceMethod* method = it->get();
Craig Tiller06cb1a92016-04-04 08:10:47 -0700434 void* tag = grpc_server_register_method(
435 server_, method->name(), host ? host->c_str() : nullptr,
436 PayloadHandlingForMethod(method), 0);
Craig Tiller15f383c2016-01-07 12:45:32 -0800437 if (tag == nullptr) {
vjpaicad5f0a2015-02-18 22:02:52 -0800438 gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
439 method->name());
440 return false;
441 }
Sree Kuchibhotlada069a52016-10-19 11:22:29 -0700442
Sree Kuchibhotlacb18d7a2016-10-20 12:39:30 -0700443 if (method->handler() == nullptr) { // Async method
Craig Tiller15f383c2016-01-07 12:45:32 -0800444 method->set_server_tag(tag);
445 } else {
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700446 for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
447 (*it)->AddSyncMethod(method, tag);
448 }
vjpaicad5f0a2015-02-18 22:02:52 -0800449 }
Sree Kuchibhotlada069a52016-10-19 11:22:29 -0700450
Yuchen Zenga42ec212016-04-29 13:03:06 -0700451 method_name = method->name();
452 }
453
454 // Parse service name.
455 if (method_name != nullptr) {
456 std::stringstream ss(method_name);
457 grpc::string service_name;
458 if (std::getline(ss, service_name, '/') &&
459 std::getline(ss, service_name, '/')) {
460 services_.push_back(service_name);
461 }
vjpaicad5f0a2015-02-18 22:02:52 -0800462 }
463 return true;
464}
465
Yang Gao49996492015-03-12 16:40:19 -0700466void Server::RegisterAsyncGenericService(AsyncGenericService* service) {
Yang Gao1c402332015-03-05 16:39:25 -0800467 GPR_ASSERT(service->server_ == nullptr &&
Yang Gao1ad253d2015-03-16 13:11:29 -0700468 "Can only register an async generic service against one server.");
Yang Gao1c402332015-03-05 16:39:25 -0800469 service->server_ = this;
yang-g9b7757d2015-08-13 11:15:53 -0700470 has_generic_service_ = true;
Yang Gao1c402332015-03-05 16:39:25 -0800471}
472
Nicolas Noblecfd60732015-03-18 16:27:43 -0700473int Server::AddListeningPort(const grpc::string& addr,
474 ServerCredentials* creds) {
vjpaicad5f0a2015-02-18 22:02:52 -0800475 GPR_ASSERT(!started_);
Craig Tiller42bc87c2015-02-23 08:50:19 -0800476 return creds->AddPortToServer(addr, server_);
vjpaicad5f0a2015-02-18 22:02:52 -0800477}
478
Craig Tiller8f7bff72015-08-17 13:23:14 -0700479bool Server::Start(ServerCompletionQueue** cqs, size_t num_cqs) {
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800480 GPR_ASSERT(!started_);
481 started_ = true;
482 grpc_server_start(server_);
483
yang-g9b7757d2015-08-13 11:15:53 -0700484 if (!has_generic_service_) {
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700485 for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
486 (*it)->AddUnknownSyncMethod();
Craig Tiller86d31772015-08-19 12:52:50 -0700487 }
Sree Kuchibhotla3ea9e242016-08-22 14:15:43 -0700488
Craig Tiller8f7bff72015-08-17 13:23:14 -0700489 for (size_t i = 0; i < num_cqs; i++) {
Craig Tillere0049582016-05-20 10:31:09 -0700490 if (cqs[i]->IsFrequentlyPolled()) {
491 new UnimplementedAsyncRequest(this, cqs[i]);
492 }
Craig Tillercbd04852015-02-10 17:39:54 -0800493 }
yang-g9b7757d2015-08-13 11:15:53 -0700494 }
Sree Kuchibhotla3ea9e242016-08-22 14:15:43 -0700495
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700496 for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
497 (*it)->Start();
498 }
499
Craig Tiller0db1bef2015-02-09 13:47:39 -0800500 return true;
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800501}
502
Craig Tillere50e5cb2015-08-18 12:44:57 -0700503void Server::ShutdownInternal(gpr_timespec deadline) {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200504 grpc::unique_lock<grpc::mutex> lock(mu_);
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800505 if (started_ && !shutdown_) {
506 shutdown_ = true;
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700507
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700508 /// The completion queue to use for server shutdown completion notification
509 CompletionQueue shutdown_cq;
Sree Kuchibhotla4028d2c2016-09-21 10:45:33 -0700510 ShutdownTag shutdown_tag; // Dummy shutdown tag
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700511 grpc_server_shutdown_and_notify(server_, shutdown_cq.cq(), &shutdown_tag);
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700512
Sree Kuchibhotla8f7739b2016-10-13 15:12:55 -0700513 // Shutdown all ThreadManagers. This will try to gracefully stop all the
514 // threads in the ThreadManagers (once they process any inflight requests)
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700515 for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
Sree Kuchibhotlacb18d7a2016-10-20 12:39:30 -0700516 (*it)->Shutdown(); // ThreadManager's Shutdown()
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700517 }
518
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700519 shutdown_cq.Shutdown();
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700520
521 void* tag;
522 bool ok;
523 CompletionQueue::NextStatus status =
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700524 shutdown_cq.AsyncNext(&tag, &ok, deadline);
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700525
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700526 // If this timed out, it means we are done with the grace period for a clean
527 // shutdown. We should force a shutdown now by cancelling all inflight calls
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700528 if (status == CompletionQueue::NextStatus::TIMEOUT) {
529 grpc_server_cancel_all_calls(server_);
530 }
531 // Else in case of SHUTDOWN or GOT_EVENT, it means that the server has
532 // successfully shutdown
533
Sree Kuchibhotla8f7739b2016-10-13 15:12:55 -0700534 // Wait for threads in all ThreadManagers to terminate
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700535 for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
536 (*it)->Wait();
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700537 (*it)->ShutdownAndDrainCompletionQueue();
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700538 }
539
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700540 // Drain the shutdown queue (if the previous call to AsyncNext() timed out
541 // and we didn't remove the tag from the queue yet)
Sree Kuchibhotla892dbf42016-09-27 19:42:27 -0700542 while (shutdown_cq.Next(&tag, &ok)) {
Sree Kuchibhotla33382d02016-10-03 15:08:48 -0700543 // Nothing to be done here. Just ignore ok and tag values
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700544 }
545
yang-g6ec11f22016-07-14 14:53:35 -0700546 shutdown_notified_ = true;
yang-ge89dc6c2016-07-11 15:48:01 -0700547 shutdown_cv_.notify_all();
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800548 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800549}
550
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800551void Server::Wait() {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200552 grpc::unique_lock<grpc::mutex> lock(mu_);
yang-g6ec11f22016-07-14 14:53:35 -0700553 while (started_ && !shutdown_notified_) {
554 shutdown_cv_.wait(lock);
555 }
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800556}
557
Craig Tiller50a7a682015-06-04 12:53:40 -0700558void Server::PerformOpsOnCall(CallOpSetInterface* ops, Call* call) {
Craig Tillerbb5227f2015-02-11 13:34:48 -0800559 static const size_t MAX_OPS = 8;
Craig Tiller50a7a682015-06-04 12:53:40 -0700560 size_t nops = 0;
561 grpc_op cops[MAX_OPS];
562 ops->FillOps(cops, &nops);
Nicolas "Pixel" Nobleebb51402015-07-23 02:41:33 +0200563 auto result = grpc_call_start_batch(call->call(), cops, nops, ops, nullptr);
564 GPR_ASSERT(GRPC_CALL_OK == result);
Craig Tillerbb5227f2015-02-11 13:34:48 -0800565}
566
David Garcia Quintas44f32492016-01-14 18:00:04 -0800567ServerInterface::BaseAsyncRequest::BaseAsyncRequest(
568 ServerInterface* server, ServerContext* context,
Craig Tiller8f7bff72015-08-17 13:23:14 -0700569 ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag,
570 bool delete_on_finalize)
Craig Tillerce40de52015-06-05 07:14:58 -0700571 : server_(server),
572 context_(context),
573 stream_(stream),
574 call_cq_(call_cq),
Craig Tiller50955812015-06-05 08:03:17 -0700575 tag_(tag),
Craig Tiller8f7bff72015-08-17 13:23:14 -0700576 delete_on_finalize_(delete_on_finalize),
Craig Tillerce40de52015-06-05 07:14:58 -0700577 call_(nullptr) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700578 memset(&initial_metadata_array_, 0, sizeof(initial_metadata_array_));
579}
580
David Garcia Quintasf3ddb7c2016-01-20 16:02:22 -0800581bool ServerInterface::BaseAsyncRequest::FinalizeResult(void** tag,
582 bool* status) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700583 if (*status) {
584 for (size_t i = 0; i < initial_metadata_array_.count; i++) {
yang-ge21908f2015-08-25 13:47:51 -0700585 context_->client_metadata_.insert(
586 std::pair<grpc::string_ref, grpc::string_ref>(
587 initial_metadata_array_.metadata[i].key,
588 grpc::string_ref(
589 initial_metadata_array_.metadata[i].value,
590 initial_metadata_array_.metadata[i].value_length)));
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700591 }
592 }
Craig Tiller2f4a49c2015-06-05 09:36:52 -0700593 grpc_metadata_array_destroy(&initial_metadata_array_);
yang-g85c04f92015-07-07 17:47:31 -0700594 context_->set_call(call_);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700595 context_->cq_ = call_cq_;
Mark D. Roth69803622016-09-06 08:15:36 -0700596 Call call(call_, server_, call_cq_, server_->max_receive_message_size());
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700597 if (*status && call_) {
598 context_->BeginCompletionOp(&call);
599 }
600 // just the pointers inside call are copied here
601 stream_->BindCall(&call);
Craig Tiller50955812015-06-05 08:03:17 -0700602 *tag = tag_;
Craig Tiller8f7bff72015-08-17 13:23:14 -0700603 if (delete_on_finalize_) {
604 delete this;
605 }
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700606 return true;
607}
608
David Garcia Quintas44f32492016-01-14 18:00:04 -0800609ServerInterface::RegisteredAsyncRequest::RegisteredAsyncRequest(
610 ServerInterface* server, ServerContext* context,
Craig Tillerce40de52015-06-05 07:14:58 -0700611 ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag)
Craig Tiller8f7bff72015-08-17 13:23:14 -0700612 : BaseAsyncRequest(server, context, stream, call_cq, tag, true) {}
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700613
David Garcia Quintas44f32492016-01-14 18:00:04 -0800614void ServerInterface::RegisteredAsyncRequest::IssueRequest(
Craig Tillerce40de52015-06-05 07:14:58 -0700615 void* registered_method, grpc_byte_buffer** payload,
616 ServerCompletionQueue* notification_cq) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700617 grpc_server_request_registered_call(
David Garcia Quintas44f32492016-01-14 18:00:04 -0800618 server_->server(), registered_method, &call_, &context_->deadline_,
Craig Tillerce40de52015-06-05 07:14:58 -0700619 &initial_metadata_array_, payload, call_cq_->cq(), notification_cq->cq(),
620 this);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700621}
622
David Garcia Quintas44f32492016-01-14 18:00:04 -0800623ServerInterface::GenericAsyncRequest::GenericAsyncRequest(
624 ServerInterface* server, GenericServerContext* context,
Craig Tillerce40de52015-06-05 07:14:58 -0700625 ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
Craig Tiller8f7bff72015-08-17 13:23:14 -0700626 ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
627 : BaseAsyncRequest(server, context, stream, call_cq, tag,
628 delete_on_finalize) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700629 grpc_call_details_init(&call_details_);
630 GPR_ASSERT(notification_cq);
631 GPR_ASSERT(call_cq);
David Garcia Quintas44f32492016-01-14 18:00:04 -0800632 grpc_server_request_call(server->server(), &call_, &call_details_,
Craig Tillerce40de52015-06-05 07:14:58 -0700633 &initial_metadata_array_, call_cq->cq(),
634 notification_cq->cq(), this);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700635}
636
David Garcia Quintasf3ddb7c2016-01-20 16:02:22 -0800637bool ServerInterface::GenericAsyncRequest::FinalizeResult(void** tag,
638 bool* status) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700639 // TODO(yangg) remove the copy here.
yang-g3deb0062015-06-23 14:06:08 -0700640 if (*status) {
yang-ga58cab32015-06-23 14:37:15 -0700641 static_cast<GenericServerContext*>(context_)->method_ =
642 call_details_.method;
yang-g3deb0062015-06-23 14:06:08 -0700643 static_cast<GenericServerContext*>(context_)->host_ = call_details_.host;
yang-g3deb0062015-06-23 14:06:08 -0700644 }
yang-ga58cab32015-06-23 14:37:15 -0700645 gpr_free(call_details_.method);
646 gpr_free(call_details_.host);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700647 return BaseAsyncRequest::FinalizeResult(tag, status);
648}
649
Craig Tiller8f7bff72015-08-17 13:23:14 -0700650bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag,
651 bool* status) {
652 if (GenericAsyncRequest::FinalizeResult(tag, status) && *status) {
653 new UnimplementedAsyncRequest(server_, cq_);
654 new UnimplementedAsyncResponse(this);
655 } else {
656 delete this;
657 }
658 return false;
659}
660
661Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse(
662 UnimplementedAsyncRequest* request)
663 : request_(request) {
664 Status status(StatusCode::UNIMPLEMENTED, "");
665 UnknownMethodHandler::FillOps(request_->context(), this);
666 request_->stream()->call_.PerformOps(this);
667}
668
Yuchen Zenga42ec212016-04-29 13:03:06 -0700669ServerInitializer* Server::initializer() { return server_initializer_.get(); }
670
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800671} // namespace grpc