blob: da7de130886bf2b0d26b775e6a7c3cdb889e7fec [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
Sree Kuchibhotla4028d2c2016-09-21 10:45:33 -0700121class ShutdownTag : public CompletionQueueTag {
122 public:
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700123 bool FinalizeResult(void** tag, bool* status) { return false; }
Sree Kuchibhotla4028d2c2016-09-21 10:45:33 -0700124};
125
Craig Tillercf133f42015-02-26 14:05:56 -0800126class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag {
Craig Tillerc4165772015-02-11 10:51:04 -0800127 public:
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800128 SyncRequest(RpcServiceMethod* method, void* tag)
Craig Tillerc4165772015-02-11 10:51:04 -0800129 : method_(method),
130 tag_(tag),
Craig Tillercf133f42015-02-26 14:05:56 -0800131 in_flight_(false),
Craig Tillerc4165772015-02-11 10:51:04 -0800132 has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC ||
133 method->method_type() ==
134 RpcMethod::SERVER_STREAMING),
yang-g9b7757d2015-08-13 11:15:53 -0700135 call_details_(nullptr),
Vijay Paiced73bd2015-06-17 10:23:28 -0700136 cq_(nullptr) {
Craig Tillerc4165772015-02-11 10:51:04 -0800137 grpc_metadata_array_init(&request_metadata_);
138 }
139
yang-g9b7757d2015-08-13 11:15:53 -0700140 ~SyncRequest() {
141 if (call_details_) {
142 delete call_details_;
143 }
144 grpc_metadata_array_destroy(&request_metadata_);
145 }
Yang Gao7b49a772015-05-28 14:07:54 -0700146
Nicolas "Pixel" Nobleebb51402015-07-23 02:41:33 +0200147 void SetupRequest() { cq_ = grpc_completion_queue_create(nullptr); }
Vijay Paiced73bd2015-06-17 10:23:28 -0700148
149 void TeardownRequest() {
150 grpc_completion_queue_destroy(cq_);
151 cq_ = nullptr;
152 }
153
Craig Tillerf9e6adf2015-05-06 11:45:59 -0700154 void Request(grpc_server* server, grpc_completion_queue* notify_cq) {
Vijay Paiced73bd2015-06-17 10:23:28 -0700155 GPR_ASSERT(cq_ && !in_flight_);
Craig Tillerc4165772015-02-11 10:51:04 -0800156 in_flight_ = true;
yang-g9b7757d2015-08-13 11:15:53 -0700157 if (tag_) {
158 GPR_ASSERT(GRPC_CALL_OK ==
159 grpc_server_request_registered_call(
160 server, tag_, &call_, &deadline_, &request_metadata_,
161 has_request_payload_ ? &request_payload_ : nullptr, cq_,
162 notify_cq, this));
163 } else {
164 if (!call_details_) {
165 call_details_ = new grpc_call_details;
166 grpc_call_details_init(call_details_);
167 }
168 GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call(
169 server, &call_, call_details_,
170 &request_metadata_, cq_, notify_cq, this));
171 }
Craig Tillerc4165772015-02-11 10:51:04 -0800172 }
173
Craig Tillercf133f42015-02-26 14:05:56 -0800174 bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE {
Craig Tillerec3257c2015-02-12 15:59:43 -0800175 if (!*status) {
176 grpc_completion_queue_destroy(cq_);
177 }
yang-g9b7757d2015-08-13 11:15:53 -0700178 if (call_details_) {
179 deadline_ = call_details_->deadline;
180 grpc_call_details_destroy(call_details_);
181 grpc_call_details_init(call_details_);
182 }
Craig Tiller645466e2015-02-18 09:18:33 -0800183 return true;
Craig Tillerec3257c2015-02-12 15:59:43 -0800184 }
Craig Tillerc4165772015-02-11 10:51:04 -0800185
Craig Tillercf133f42015-02-26 14:05:56 -0800186 class CallData GRPC_FINAL {
Craig Tillerc4165772015-02-11 10:51:04 -0800187 public:
Craig Tiller1c9a2a92015-02-12 14:10:25 -0800188 explicit CallData(Server* server, SyncRequest* mrd)
Craig Tillerc4165772015-02-11 10:51:04 -0800189 : cq_(mrd->cq_),
Mark D. Roth69803622016-09-06 08:15:36 -0700190 call_(mrd->call_, server, &cq_, server->max_receive_message_size_),
Craig Tillerc4165772015-02-11 10:51:04 -0800191 ctx_(mrd->deadline_, mrd->request_metadata_.metadata,
192 mrd->request_metadata_.count),
193 has_request_payload_(mrd->has_request_payload_),
Craig Tillerc4165772015-02-11 10:51:04 -0800194 request_payload_(mrd->request_payload_),
195 method_(mrd->method_) {
yang-g85c04f92015-07-07 17:47:31 -0700196 ctx_.set_call(mrd->call_);
Yang Gao1205f6f2015-03-22 15:18:14 -0700197 ctx_.cq_ = &cq_;
Craig Tillerc4165772015-02-11 10:51:04 -0800198 GPR_ASSERT(mrd->in_flight_);
199 mrd->in_flight_ = false;
200 mrd->request_metadata_.count = 0;
201 }
202
Craig Tillerec3257c2015-02-12 15:59:43 -0800203 ~CallData() {
204 if (has_request_payload_ && request_payload_) {
205 grpc_byte_buffer_destroy(request_payload_);
206 }
207 }
208
Craig Tiller64616492016-01-26 14:16:20 -0800209 void Run(std::shared_ptr<GlobalCallbacks> global_callbacks) {
Craig Tiller492968f2015-02-18 13:14:03 -0800210 ctx_.BeginCompletionOp(&call_);
Craig Tiller64616492016-01-26 14:16:20 -0800211 global_callbacks->PreSynchronousRequest(&ctx_);
Craig Tillerce40de52015-06-05 07:14:58 -0700212 method_->handler()->RunHandler(MethodHandler::HandlerParameter(
Mark D. Roth69803622016-09-06 08:15:36 -0700213 &call_, &ctx_, request_payload_, call_.max_receive_message_size()));
Craig Tiller64616492016-01-26 14:16:20 -0800214 global_callbacks->PostSynchronousRequest(&ctx_);
Craig Tiller928ec8e2015-06-05 08:45:45 -0700215 request_payload_ = nullptr;
Craig Tiller492968f2015-02-18 13:14:03 -0800216 void* ignored_tag;
217 bool ignored_ok;
218 cq_.Shutdown();
219 GPR_ASSERT(cq_.Next(&ignored_tag, &ignored_ok) == false);
Craig Tillerc4165772015-02-11 10:51:04 -0800220 }
221
222 private:
223 CompletionQueue cq_;
224 Call call_;
225 ServerContext ctx_;
226 const bool has_request_payload_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800227 grpc_byte_buffer* request_payload_;
228 RpcServiceMethod* const method_;
Craig Tillerc4165772015-02-11 10:51:04 -0800229 };
230
231 private:
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800232 RpcServiceMethod* const method_;
233 void* const tag_;
Craig Tillercf133f42015-02-26 14:05:56 -0800234 bool in_flight_;
Craig Tillerc4165772015-02-11 10:51:04 -0800235 const bool has_request_payload_;
Craig Tiller5987c702016-03-09 16:55:23 -0800236 uint32_t incoming_flags_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800237 grpc_call* call_;
yang-g9b7757d2015-08-13 11:15:53 -0700238 grpc_call_details* call_details_;
Craig Tillerc4165772015-02-11 10:51:04 -0800239 gpr_timespec deadline_;
240 grpc_metadata_array request_metadata_;
Craig Tiller8c8d0aa2015-02-12 11:38:36 -0800241 grpc_byte_buffer* request_payload_;
242 grpc_completion_queue* cq_;
Craig Tillerc4165772015-02-11 10:51:04 -0800243};
244
Sree Kuchibhotla8f7739b2016-10-13 15:12:55 -0700245// Implementation of ThreadManager. Each instance of SyncRequestThreadManager
246// manages a pool of threads that poll for incoming Sync RPCs and call the
247// appropriate RPC handlers
248class Server::SyncRequestThreadManager : public ThreadManager {
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700249 public:
Sree Kuchibhotla8f7739b2016-10-13 15:12:55 -0700250 SyncRequestThreadManager(Server* server, CompletionQueue* server_cq,
251 std::shared_ptr<GlobalCallbacks> global_callbacks,
252 int min_pollers, int max_pollers,
253 int cq_timeout_msec)
254 : ThreadManager(min_pollers, max_pollers),
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700255 server_(server),
256 server_cq_(server_cq),
Sree Kuchibhotla892dbf42016-09-27 19:42:27 -0700257 cq_timeout_msec_(cq_timeout_msec),
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700258 global_callbacks_(global_callbacks) {}
259
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700260 WorkStatus PollForWork(void** tag, bool* ok) GRPC_OVERRIDE {
261 *tag = nullptr;
262 gpr_timespec deadline =
Sree Kuchibhotla892dbf42016-09-27 19:42:27 -0700263 gpr_time_from_millis(cq_timeout_msec_, GPR_TIMESPAN);
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700264
265 switch (server_cq_->AsyncNext(tag, ok, deadline)) {
266 case CompletionQueue::TIMEOUT:
267 return TIMEOUT;
268 case CompletionQueue::SHUTDOWN:
269 return SHUTDOWN;
270 case CompletionQueue::GOT_EVENT:
271 return WORK_FOUND;
272 }
273
274 GPR_UNREACHABLE_CODE(return TIMEOUT);
275 }
276
277 void DoWork(void* tag, bool ok) GRPC_OVERRIDE {
278 SyncRequest* sync_req = static_cast<SyncRequest*>(tag);
Sree Kuchibhotla4306eee2016-09-21 09:56:29 -0700279
280 if (!sync_req) {
Sree Kuchibhotla33382d02016-10-03 15:08:48 -0700281 // No tag. Nothing to work on. This is an unlikley scenario and possibly a
282 // bug in RPC Manager implementation.
283 gpr_log(GPR_ERROR, "Sync server. DoWork() was called with NULL tag");
Sree Kuchibhotla4306eee2016-09-21 09:56:29 -0700284 return;
285 }
286
287 if (ok) {
Sree Kuchibhotla33382d02016-10-03 15:08:48 -0700288 // Calldata takes ownership of the completion queue inside sync_req
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700289 SyncRequest::CallData cd(server_, sync_req);
290 {
Sree Kuchibhotla33382d02016-10-03 15:08:48 -0700291 // Prepare for the next request
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700292 if (!IsShutdown()) {
Sree Kuchibhotla33382d02016-10-03 15:08:48 -0700293 sync_req->SetupRequest(); // Create new completion queue for sync_req
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700294 sync_req->Request(server_->c_server(), server_cq_->cq());
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700295 }
296 }
Sree Kuchibhotla33382d02016-10-03 15:08:48 -0700297
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700298 GPR_TIMER_SCOPE("cd.Run()", 0);
299 cd.Run(global_callbacks_);
300 }
Sree Kuchibhotla33382d02016-10-03 15:08:48 -0700301 // TODO (sreek) If ok is false here (which it isn't in case of
302 // grpc_request_registered_call), we should still re-queue the request
303 // object
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700304 }
305
306 void AddSyncMethod(RpcServiceMethod* method, void* tag) {
307 sync_methods_.emplace_back(method, tag);
308 }
309
310 void AddUnknownSyncMethod() {
311 // TODO (sreek) - Check if !sync_methods_.empty() is really needed here
312 if (!sync_methods_.empty()) {
313 unknown_method_.reset(new RpcServiceMethod(
314 "unknown", RpcMethod::BIDI_STREAMING, new UnknownMethodHandler));
315 // Use of emplace_back with just constructor arguments is not accepted
316 // here by gcc-4.4 because it can't match the anonymous nullptr with a
317 // proper constructor implicitly. Construct the object and use push_back.
318 sync_methods_.push_back(SyncRequest(unknown_method_.get(), nullptr));
319 }
320 }
321
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700322 void ShutdownAndDrainCompletionQueue() {
323 server_cq_->Shutdown();
324
325 // Drain any pending items from the queue
326 void* tag;
327 bool ok;
328 while (server_cq_->Next(&tag, &ok)) {
329 // Nothing to be done here
330 }
331 }
332
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700333 void Start() {
334 if (!sync_methods_.empty()) {
335 for (auto m = sync_methods_.begin(); m != sync_methods_.end(); m++) {
336 m->SetupRequest();
337 m->Request(server_->c_server(), server_cq_->cq());
338 }
339
Sree Kuchibhotla8f7739b2016-10-13 15:12:55 -0700340 ThreadManager::Initialize();
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700341 }
342 }
343
344 private:
345 Server* server_;
346 CompletionQueue* server_cq_;
Sree Kuchibhotla892dbf42016-09-27 19:42:27 -0700347 int cq_timeout_msec_;
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700348 std::vector<SyncRequest> sync_methods_;
349 std::unique_ptr<RpcServiceMethod> unknown_method_;
350 std::shared_ptr<Server::GlobalCallbacks> global_callbacks_;
351};
352
David Garcia Quintasd79ef3a2016-01-28 00:21:27 -0800353static internal::GrpcLibraryInitializer g_gli_initializer;
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700354Server::Server(
Sree Kuchibhotlae4eb51f2016-10-18 11:51:28 -0700355 int max_receive_message_size, ChannelArguments* args,
Sree Kuchibhotla4028d2c2016-09-21 10:45:33 -0700356 std::shared_ptr<std::vector<std::unique_ptr<ServerCompletionQueue>>>
357 sync_server_cqs,
Sree Kuchibhotlae4eb51f2016-10-18 11:51:28 -0700358 int min_pollers, int max_pollers, int sync_cq_timeout_msec)
Mark D. Roth69803622016-09-06 08:15:36 -0700359 : max_receive_message_size_(max_receive_message_size),
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700360 sync_server_cqs_(sync_server_cqs),
Yang Gao3921c562015-04-30 16:07:06 -0700361 started_(false),
vjpaicad5f0a2015-02-18 22:02:52 -0800362 shutdown_(false),
yang-g6ec11f22016-07-14 14:53:35 -0700363 shutdown_notified_(false),
yang-g9b7757d2015-08-13 11:15:53 -0700364 has_generic_service_(false),
yang-geb62c942016-02-17 15:37:25 -0800365 server_(nullptr),
Yuchen Zenga42ec212016-04-29 13:03:06 -0700366 server_initializer_(new ServerInitializer(this)) {
David Garcia Quintasd79ef3a2016-01-28 00:21:27 -0800367 g_gli_initializer.summon();
Craig Tiller8352b9e2015-12-02 11:43:40 -0800368 gpr_once_init(&g_once_init_callbacks, InitGlobalCallbacks);
Craig Tiller64616492016-01-26 14:16:20 -0800369 global_callbacks_ = g_callbacks;
yang-geb62c942016-02-17 15:37:25 -0800370 global_callbacks_->UpdateArguments(args);
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700371
372 for (auto it = sync_server_cqs_->begin(); it != sync_server_cqs_->end();
373 it++) {
Sree Kuchibhotla8f7739b2016-10-13 15:12:55 -0700374 sync_req_mgrs_.emplace_back(new SyncRequestThreadManager(
375 this, (*it).get(), global_callbacks_, min_pollers, max_pollers,
376 sync_cq_timeout_msec));
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700377 }
378
yang-geb62c942016-02-17 15:37:25 -0800379 grpc_channel_args channel_args;
380 args->SetChannelArgs(&channel_args);
Sree Kuchibhotla3ea9e242016-08-22 14:15:43 -0700381
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700382 server_ = grpc_server_create(&channel_args, nullptr);
Craig Tillerf9e6adf2015-05-06 11:45:59 -0700383}
vjpaicad5f0a2015-02-18 22:02:52 -0800384
385Server::~Server() {
Ruyi Wangb486ba62015-03-14 22:19:44 +0800386 {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200387 grpc::unique_lock<grpc::mutex> lock(mu_);
Ruyi Wangb486ba62015-03-14 22:19:44 +0800388 if (started_ && !shutdown_) {
389 lock.unlock();
390 Shutdown();
yang-gb9711732016-01-15 16:53:08 -0800391 } else if (!started_) {
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700392 // Shutdown the completion queues
393 for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
394 (*it)->ShutdownAndDrainCompletionQueue();
Sree Kuchibhotla4306eee2016-09-21 09:56:29 -0700395 }
Ruyi Wangb486ba62015-03-14 22:19:44 +0800396 }
vjpaicad5f0a2015-02-18 22:02:52 -0800397 }
Sree Kuchibhotlabb5519f2016-07-19 11:00:39 -0700398
vjpaicad5f0a2015-02-18 22:02:52 -0800399 grpc_server_destroy(server_);
vjpaicad5f0a2015-02-18 22:02:52 -0800400}
401
Craig Tiller7221d992015-11-24 06:59:33 -0800402void Server::SetGlobalCallbacks(GlobalCallbacks* callbacks) {
Vijay Paib645a2d2016-06-09 18:39:06 -0700403 GPR_ASSERT(!g_callbacks);
404 GPR_ASSERT(callbacks);
Craig Tiller64616492016-01-26 14:16:20 -0800405 g_callbacks.reset(callbacks);
Craig Tiller7221d992015-11-24 06:59:33 -0800406}
407
Adam Michalik4ad746e2016-06-07 15:02:59 -0700408grpc_server* Server::c_server() { return server_; }
Adam Michalikb97e2d12016-06-02 12:12:55 -0700409
Craig Tiller06cb1a92016-04-04 08:10:47 -0700410static grpc_server_register_method_payload_handling PayloadHandlingForMethod(
411 RpcServiceMethod* method) {
412 switch (method->method_type()) {
413 case RpcMethod::NORMAL_RPC:
414 case RpcMethod::SERVER_STREAMING:
415 return GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER;
416 case RpcMethod::CLIENT_STREAMING:
417 case RpcMethod::BIDI_STREAMING:
418 return GRPC_SRM_PAYLOAD_NONE;
419 }
420 GPR_UNREACHABLE_CODE(return GRPC_SRM_PAYLOAD_NONE;);
421}
422
Craig Tiller15f383c2016-01-07 12:45:32 -0800423bool Server::RegisterService(const grpc::string* host, Service* service) {
424 bool has_async_methods = service->has_async_methods();
425 if (has_async_methods) {
426 GPR_ASSERT(service->server_ == nullptr &&
427 "Can only register an asynchronous service against one server.");
428 service->server_ = this;
429 }
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700430
Yuchen Zenga42ec212016-04-29 13:03:06 -0700431 const char* method_name = nullptr;
Craig Tiller15f383c2016-01-07 12:45:32 -0800432 for (auto it = service->methods_.begin(); it != service->methods_.end();
433 ++it) {
yang-g269b8be2016-01-15 10:46:26 -0800434 if (it->get() == nullptr) { // Handled by generic service if any.
435 continue;
436 }
Craig Tiller15f383c2016-01-07 12:45:32 -0800437 RpcServiceMethod* method = it->get();
Craig Tiller06cb1a92016-04-04 08:10:47 -0700438 void* tag = grpc_server_register_method(
439 server_, method->name(), host ? host->c_str() : nullptr,
440 PayloadHandlingForMethod(method), 0);
Craig Tiller15f383c2016-01-07 12:45:32 -0800441 if (tag == nullptr) {
vjpaicad5f0a2015-02-18 22:02:52 -0800442 gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
443 method->name());
444 return false;
445 }
Craig Tiller15f383c2016-01-07 12:45:32 -0800446 if (method->handler() == nullptr) {
447 method->set_server_tag(tag);
448 } else {
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700449 for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
450 (*it)->AddSyncMethod(method, tag);
451 }
vjpaicad5f0a2015-02-18 22:02:52 -0800452 }
Yuchen Zenga42ec212016-04-29 13:03:06 -0700453 method_name = method->name();
454 }
455
456 // Parse service name.
457 if (method_name != nullptr) {
458 std::stringstream ss(method_name);
459 grpc::string service_name;
460 if (std::getline(ss, service_name, '/') &&
461 std::getline(ss, service_name, '/')) {
462 services_.push_back(service_name);
463 }
vjpaicad5f0a2015-02-18 22:02:52 -0800464 }
465 return true;
466}
467
Yang Gao49996492015-03-12 16:40:19 -0700468void Server::RegisterAsyncGenericService(AsyncGenericService* service) {
Yang Gao1c402332015-03-05 16:39:25 -0800469 GPR_ASSERT(service->server_ == nullptr &&
Yang Gao1ad253d2015-03-16 13:11:29 -0700470 "Can only register an async generic service against one server.");
Yang Gao1c402332015-03-05 16:39:25 -0800471 service->server_ = this;
yang-g9b7757d2015-08-13 11:15:53 -0700472 has_generic_service_ = true;
Yang Gao1c402332015-03-05 16:39:25 -0800473}
474
Nicolas Noblecfd60732015-03-18 16:27:43 -0700475int Server::AddListeningPort(const grpc::string& addr,
476 ServerCredentials* creds) {
vjpaicad5f0a2015-02-18 22:02:52 -0800477 GPR_ASSERT(!started_);
Craig Tiller42bc87c2015-02-23 08:50:19 -0800478 return creds->AddPortToServer(addr, server_);
vjpaicad5f0a2015-02-18 22:02:52 -0800479}
480
Craig Tiller8f7bff72015-08-17 13:23:14 -0700481bool Server::Start(ServerCompletionQueue** cqs, size_t num_cqs) {
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800482 GPR_ASSERT(!started_);
483 started_ = true;
484 grpc_server_start(server_);
485
yang-g9b7757d2015-08-13 11:15:53 -0700486 if (!has_generic_service_) {
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700487 for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
488 (*it)->AddUnknownSyncMethod();
Craig Tiller86d31772015-08-19 12:52:50 -0700489 }
Sree Kuchibhotla3ea9e242016-08-22 14:15:43 -0700490
Craig Tiller8f7bff72015-08-17 13:23:14 -0700491 for (size_t i = 0; i < num_cqs; i++) {
Craig Tillere0049582016-05-20 10:31:09 -0700492 if (cqs[i]->IsFrequentlyPolled()) {
493 new UnimplementedAsyncRequest(this, cqs[i]);
494 }
Craig Tillercbd04852015-02-10 17:39:54 -0800495 }
yang-g9b7757d2015-08-13 11:15:53 -0700496 }
Sree Kuchibhotla3ea9e242016-08-22 14:15:43 -0700497
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700498 for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
499 (*it)->Start();
500 }
501
Craig Tiller0db1bef2015-02-09 13:47:39 -0800502 return true;
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800503}
504
Sree Kuchibhotla4306eee2016-09-21 09:56:29 -0700505/* TODO (sreek) check if started_ and shutdown_ are needed anymore */
Craig Tillere50e5cb2015-08-18 12:44:57 -0700506void Server::ShutdownInternal(gpr_timespec deadline) {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200507 grpc::unique_lock<grpc::mutex> lock(mu_);
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800508 if (started_ && !shutdown_) {
509 shutdown_ = true;
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700510
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700511 /// The completion queue to use for server shutdown completion notification
512 CompletionQueue shutdown_cq;
Sree Kuchibhotla4028d2c2016-09-21 10:45:33 -0700513 ShutdownTag shutdown_tag; // Dummy shutdown tag
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700514 grpc_server_shutdown_and_notify(server_, shutdown_cq.cq(), &shutdown_tag);
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700515
Sree Kuchibhotla8f7739b2016-10-13 15:12:55 -0700516 // Shutdown all ThreadManagers. This will try to gracefully stop all the
517 // threads in the ThreadManagers (once they process any inflight requests)
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700518 for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
Sree Kuchibhotla8f7739b2016-10-13 15:12:55 -0700519 (*it)->Shutdown();
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700520 }
521
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700522 shutdown_cq.Shutdown();
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700523
524 void* tag;
525 bool ok;
526 CompletionQueue::NextStatus status =
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700527 shutdown_cq.AsyncNext(&tag, &ok, deadline);
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700528
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700529 // If this timed out, it means we are done with the grace period for a clean
530 // shutdown. We should force a shutdown now by cancelling all inflight calls
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700531 if (status == CompletionQueue::NextStatus::TIMEOUT) {
532 grpc_server_cancel_all_calls(server_);
533 }
534 // Else in case of SHUTDOWN or GOT_EVENT, it means that the server has
535 // successfully shutdown
536
Sree Kuchibhotla8f7739b2016-10-13 15:12:55 -0700537 // Wait for threads in all ThreadManagers to terminate
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700538 for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
539 (*it)->Wait();
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700540 (*it)->ShutdownAndDrainCompletionQueue();
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700541 }
542
Sree Kuchibhotla862acb92016-09-26 09:48:48 -0700543 // Drain the shutdown queue (if the previous call to AsyncNext() timed out
544 // and we didn't remove the tag from the queue yet)
Sree Kuchibhotla892dbf42016-09-27 19:42:27 -0700545 while (shutdown_cq.Next(&tag, &ok)) {
Sree Kuchibhotla33382d02016-10-03 15:08:48 -0700546 // Nothing to be done here. Just ignore ok and tag values
Sree Kuchibhotlaaabada92016-08-24 10:01:13 -0700547 }
548
yang-g6ec11f22016-07-14 14:53:35 -0700549 shutdown_notified_ = true;
yang-ge89dc6c2016-07-11 15:48:01 -0700550 shutdown_cv_.notify_all();
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800551 }
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800552}
553
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800554void Server::Wait() {
Nicolas "Pixel" Nobleff2828b2015-04-03 03:16:46 +0200555 grpc::unique_lock<grpc::mutex> lock(mu_);
yang-g6ec11f22016-07-14 14:53:35 -0700556 while (started_ && !shutdown_notified_) {
557 shutdown_cv_.wait(lock);
558 }
Craig Tiller6e57b9e2015-02-24 15:46:22 -0800559}
560
Craig Tiller50a7a682015-06-04 12:53:40 -0700561void Server::PerformOpsOnCall(CallOpSetInterface* ops, Call* call) {
Craig Tillerbb5227f2015-02-11 13:34:48 -0800562 static const size_t MAX_OPS = 8;
Craig Tiller50a7a682015-06-04 12:53:40 -0700563 size_t nops = 0;
564 grpc_op cops[MAX_OPS];
565 ops->FillOps(cops, &nops);
Nicolas "Pixel" Nobleebb51402015-07-23 02:41:33 +0200566 auto result = grpc_call_start_batch(call->call(), cops, nops, ops, nullptr);
567 GPR_ASSERT(GRPC_CALL_OK == result);
Craig Tillerbb5227f2015-02-11 13:34:48 -0800568}
569
David Garcia Quintas44f32492016-01-14 18:00:04 -0800570ServerInterface::BaseAsyncRequest::BaseAsyncRequest(
571 ServerInterface* server, ServerContext* context,
Craig Tiller8f7bff72015-08-17 13:23:14 -0700572 ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag,
573 bool delete_on_finalize)
Craig Tillerce40de52015-06-05 07:14:58 -0700574 : server_(server),
575 context_(context),
576 stream_(stream),
577 call_cq_(call_cq),
Craig Tiller50955812015-06-05 08:03:17 -0700578 tag_(tag),
Craig Tiller8f7bff72015-08-17 13:23:14 -0700579 delete_on_finalize_(delete_on_finalize),
Craig Tillerce40de52015-06-05 07:14:58 -0700580 call_(nullptr) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700581 memset(&initial_metadata_array_, 0, sizeof(initial_metadata_array_));
582}
583
David Garcia Quintasf3ddb7c2016-01-20 16:02:22 -0800584bool ServerInterface::BaseAsyncRequest::FinalizeResult(void** tag,
585 bool* status) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700586 if (*status) {
587 for (size_t i = 0; i < initial_metadata_array_.count; i++) {
yang-ge21908f2015-08-25 13:47:51 -0700588 context_->client_metadata_.insert(
589 std::pair<grpc::string_ref, grpc::string_ref>(
590 initial_metadata_array_.metadata[i].key,
591 grpc::string_ref(
592 initial_metadata_array_.metadata[i].value,
593 initial_metadata_array_.metadata[i].value_length)));
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700594 }
595 }
Craig Tiller2f4a49c2015-06-05 09:36:52 -0700596 grpc_metadata_array_destroy(&initial_metadata_array_);
yang-g85c04f92015-07-07 17:47:31 -0700597 context_->set_call(call_);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700598 context_->cq_ = call_cq_;
Mark D. Roth69803622016-09-06 08:15:36 -0700599 Call call(call_, server_, call_cq_, server_->max_receive_message_size());
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700600 if (*status && call_) {
601 context_->BeginCompletionOp(&call);
602 }
603 // just the pointers inside call are copied here
604 stream_->BindCall(&call);
Craig Tiller50955812015-06-05 08:03:17 -0700605 *tag = tag_;
Craig Tiller8f7bff72015-08-17 13:23:14 -0700606 if (delete_on_finalize_) {
607 delete this;
608 }
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700609 return true;
610}
611
David Garcia Quintas44f32492016-01-14 18:00:04 -0800612ServerInterface::RegisteredAsyncRequest::RegisteredAsyncRequest(
613 ServerInterface* server, ServerContext* context,
Craig Tillerce40de52015-06-05 07:14:58 -0700614 ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag)
Craig Tiller8f7bff72015-08-17 13:23:14 -0700615 : BaseAsyncRequest(server, context, stream, call_cq, tag, true) {}
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700616
David Garcia Quintas44f32492016-01-14 18:00:04 -0800617void ServerInterface::RegisteredAsyncRequest::IssueRequest(
Craig Tillerce40de52015-06-05 07:14:58 -0700618 void* registered_method, grpc_byte_buffer** payload,
619 ServerCompletionQueue* notification_cq) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700620 grpc_server_request_registered_call(
David Garcia Quintas44f32492016-01-14 18:00:04 -0800621 server_->server(), registered_method, &call_, &context_->deadline_,
Craig Tillerce40de52015-06-05 07:14:58 -0700622 &initial_metadata_array_, payload, call_cq_->cq(), notification_cq->cq(),
623 this);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700624}
625
David Garcia Quintas44f32492016-01-14 18:00:04 -0800626ServerInterface::GenericAsyncRequest::GenericAsyncRequest(
627 ServerInterface* server, GenericServerContext* context,
Craig Tillerce40de52015-06-05 07:14:58 -0700628 ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
Craig Tiller8f7bff72015-08-17 13:23:14 -0700629 ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
630 : BaseAsyncRequest(server, context, stream, call_cq, tag,
631 delete_on_finalize) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700632 grpc_call_details_init(&call_details_);
633 GPR_ASSERT(notification_cq);
634 GPR_ASSERT(call_cq);
David Garcia Quintas44f32492016-01-14 18:00:04 -0800635 grpc_server_request_call(server->server(), &call_, &call_details_,
Craig Tillerce40de52015-06-05 07:14:58 -0700636 &initial_metadata_array_, call_cq->cq(),
637 notification_cq->cq(), this);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700638}
639
David Garcia Quintasf3ddb7c2016-01-20 16:02:22 -0800640bool ServerInterface::GenericAsyncRequest::FinalizeResult(void** tag,
641 bool* status) {
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700642 // TODO(yangg) remove the copy here.
yang-g3deb0062015-06-23 14:06:08 -0700643 if (*status) {
yang-ga58cab32015-06-23 14:37:15 -0700644 static_cast<GenericServerContext*>(context_)->method_ =
645 call_details_.method;
yang-g3deb0062015-06-23 14:06:08 -0700646 static_cast<GenericServerContext*>(context_)->host_ = call_details_.host;
yang-g3deb0062015-06-23 14:06:08 -0700647 }
yang-ga58cab32015-06-23 14:37:15 -0700648 gpr_free(call_details_.method);
649 gpr_free(call_details_.host);
Craig Tiller7bc97bc2015-06-04 17:22:54 -0700650 return BaseAsyncRequest::FinalizeResult(tag, status);
651}
652
Craig Tiller8f7bff72015-08-17 13:23:14 -0700653bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag,
654 bool* status) {
655 if (GenericAsyncRequest::FinalizeResult(tag, status) && *status) {
656 new UnimplementedAsyncRequest(server_, cq_);
657 new UnimplementedAsyncResponse(this);
658 } else {
659 delete this;
660 }
661 return false;
662}
663
664Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse(
665 UnimplementedAsyncRequest* request)
666 : request_(request) {
667 Status status(StatusCode::UNIMPLEMENTED, "");
668 UnknownMethodHandler::FillOps(request_->context(), this);
669 request_->stream()->call_.PerformOps(this);
670}
671
Yuchen Zenga42ec212016-04-29 13:03:06 -0700672ServerInitializer* Server::initializer() { return server_initializer_.get(); }
673
Nicolas Nobleb7ebd3b2014-11-26 16:33:03 -0800674} // namespace grpc