• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2015 gRPC authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17 
18 #include <grpcpp/server.h>
19 
20 #include <cstdlib>
21 #include <sstream>
22 #include <type_traits>
23 #include <utility>
24 
25 #include <grpc/grpc.h>
26 #include <grpc/impl/codegen/grpc_types.h>
27 #include <grpc/support/alloc.h>
28 #include <grpc/support/log.h>
29 #include <grpcpp/completion_queue.h>
30 #include <grpcpp/generic/async_generic_service.h>
31 #include <grpcpp/impl/codegen/async_unary_call.h>
32 #include <grpcpp/impl/codegen/byte_buffer.h>
33 #include <grpcpp/impl/codegen/call.h>
34 #include <grpcpp/impl/codegen/completion_queue_tag.h>
35 #include <grpcpp/impl/codegen/method_handler.h>
36 #include <grpcpp/impl/codegen/server_interceptor.h>
37 #include <grpcpp/impl/grpc_library.h>
38 #include <grpcpp/impl/rpc_service_method.h>
39 #include <grpcpp/impl/server_initializer.h>
40 #include <grpcpp/impl/service_type.h>
41 #include <grpcpp/security/server_credentials.h>
42 #include <grpcpp/server_context.h>
43 #include <grpcpp/support/time.h>
44 
45 #include "src/core/ext/transport/inproc/inproc_transport.h"
46 #include "src/core/lib/iomgr/exec_ctx.h"
47 #include "src/core/lib/profiling/timers.h"
48 #include "src/core/lib/surface/call.h"
49 #include "src/core/lib/surface/completion_queue.h"
50 #include "src/core/lib/surface/server.h"
51 #include "src/cpp/client/create_channel_internal.h"
52 #include "src/cpp/server/external_connection_acceptor_impl.h"
53 #include "src/cpp/server/health/default_health_check_service.h"
54 #include "src/cpp/thread_manager/thread_manager.h"
55 
56 namespace grpc {
57 namespace {
58 
59 // The default value for maximum number of threads that can be created in the
60 // sync server. This value of INT_MAX is chosen to match the default behavior if
61 // no ResourceQuota is set. To modify the max number of threads in a sync
62 // server, pass a custom ResourceQuota object  (with the desired number of
63 // max-threads set) to the server builder.
64 #define DEFAULT_MAX_SYNC_SERVER_THREADS INT_MAX
65 
66 class DefaultGlobalCallbacks final : public Server::GlobalCallbacks {
67  public:
~DefaultGlobalCallbacks()68   ~DefaultGlobalCallbacks() override {}
PreSynchronousRequest(ServerContext *)69   void PreSynchronousRequest(ServerContext* /*context*/) override {}
PostSynchronousRequest(ServerContext *)70   void PostSynchronousRequest(ServerContext* /*context*/) override {}
71 };
72 
73 std::shared_ptr<Server::GlobalCallbacks> g_callbacks = nullptr;
74 gpr_once g_once_init_callbacks = GPR_ONCE_INIT;
75 
InitGlobalCallbacks()76 void InitGlobalCallbacks() {
77   if (!g_callbacks) {
78     g_callbacks.reset(new DefaultGlobalCallbacks());
79   }
80 }
81 
82 class ShutdownTag : public internal::CompletionQueueTag {
83  public:
FinalizeResult(void **,bool *)84   bool FinalizeResult(void** /*tag*/, bool* /*status*/) { return false; }
85 };
86 
87 class DummyTag : public internal::CompletionQueueTag {
88  public:
FinalizeResult(void **,bool *)89   bool FinalizeResult(void** /*tag*/, bool* /*status*/) { return true; }
90 };
91 
92 class UnimplementedAsyncRequestContext {
93  protected:
UnimplementedAsyncRequestContext()94   UnimplementedAsyncRequestContext() : generic_stream_(&server_context_) {}
95 
96   GenericServerContext server_context_;
97   GenericServerAsyncReaderWriter generic_stream_;
98 };
99 
100 // TODO(vjpai): Just for this file, use some contents of the experimental
101 // namespace here to make the code easier to read below. Remove this when
102 // de-experimentalized fully.
103 #ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
104 using ::grpc::experimental::CallbackGenericService;
105 using ::grpc::experimental::CallbackServerContext;
106 using ::grpc::experimental::GenericCallbackServerContext;
107 #endif
108 
109 }  // namespace
110 
BaseAsyncRequest(ServerInterface * server,ServerContext * context,internal::ServerAsyncStreamingInterface * stream,CompletionQueue * call_cq,ServerCompletionQueue * notification_cq,void * tag,bool delete_on_finalize)111 ServerInterface::BaseAsyncRequest::BaseAsyncRequest(
112     ServerInterface* server, ServerContext* context,
113     internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
114     ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
115     : server_(server),
116       context_(context),
117       stream_(stream),
118       call_cq_(call_cq),
119       notification_cq_(notification_cq),
120       tag_(tag),
121       delete_on_finalize_(delete_on_finalize),
122       call_(nullptr),
123       done_intercepting_(false) {
124   /* Set up interception state partially for the receive ops. call_wrapper_ is
125    * not filled at this point, but it will be filled before the interceptors are
126    * run. */
127   interceptor_methods_.SetCall(&call_wrapper_);
128   interceptor_methods_.SetReverse();
129   call_cq_->RegisterAvalanching();  // This op will trigger more ops
130 }
131 
~BaseAsyncRequest()132 ServerInterface::BaseAsyncRequest::~BaseAsyncRequest() {
133   call_cq_->CompleteAvalanching();
134 }
135 
FinalizeResult(void ** tag,bool * status)136 bool ServerInterface::BaseAsyncRequest::FinalizeResult(void** tag,
137                                                        bool* status) {
138   if (done_intercepting_) {
139     *tag = tag_;
140     if (delete_on_finalize_) {
141       delete this;
142     }
143     return true;
144   }
145   context_->set_call(call_);
146   context_->cq_ = call_cq_;
147   if (call_wrapper_.call() == nullptr) {
148     // Fill it since it is empty.
149     call_wrapper_ = internal::Call(
150         call_, server_, call_cq_, server_->max_receive_message_size(), nullptr);
151   }
152 
153   // just the pointers inside call are copied here
154   stream_->BindCall(&call_wrapper_);
155 
156   if (*status && call_ && call_wrapper_.server_rpc_info()) {
157     done_intercepting_ = true;
158     // Set interception point for RECV INITIAL METADATA
159     interceptor_methods_.AddInterceptionHookPoint(
160         experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA);
161     interceptor_methods_.SetRecvInitialMetadata(&context_->client_metadata_);
162     if (interceptor_methods_.RunInterceptors(
163             [this]() { ContinueFinalizeResultAfterInterception(); })) {
164       // There are no interceptors to run. Continue
165     } else {
166       // There were interceptors to be run, so
167       // ContinueFinalizeResultAfterInterception will be run when interceptors
168       // are done.
169       return false;
170     }
171   }
172   if (*status && call_) {
173     context_->BeginCompletionOp(&call_wrapper_, nullptr, nullptr);
174   }
175   *tag = tag_;
176   if (delete_on_finalize_) {
177     delete this;
178   }
179   return true;
180 }
181 
182 void ServerInterface::BaseAsyncRequest::
ContinueFinalizeResultAfterInterception()183     ContinueFinalizeResultAfterInterception() {
184   context_->BeginCompletionOp(&call_wrapper_, nullptr, nullptr);
185   // Queue a tag which will be returned immediately
186   grpc_core::ExecCtx exec_ctx;
187   grpc_cq_begin_op(notification_cq_->cq(), this);
188   grpc_cq_end_op(
189       notification_cq_->cq(), this, GRPC_ERROR_NONE,
190       [](void* /*arg*/, grpc_cq_completion* completion) { delete completion; },
191       nullptr, new grpc_cq_completion());
192 }
193 
RegisteredAsyncRequest(ServerInterface * server,ServerContext * context,internal::ServerAsyncStreamingInterface * stream,CompletionQueue * call_cq,ServerCompletionQueue * notification_cq,void * tag,const char * name,internal::RpcMethod::RpcType type)194 ServerInterface::RegisteredAsyncRequest::RegisteredAsyncRequest(
195     ServerInterface* server, ServerContext* context,
196     internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
197     ServerCompletionQueue* notification_cq, void* tag, const char* name,
198     internal::RpcMethod::RpcType type)
199     : BaseAsyncRequest(server, context, stream, call_cq, notification_cq, tag,
200                        true),
201       name_(name),
202       type_(type) {}
203 
IssueRequest(void * registered_method,grpc_byte_buffer ** payload,ServerCompletionQueue * notification_cq)204 void ServerInterface::RegisteredAsyncRequest::IssueRequest(
205     void* registered_method, grpc_byte_buffer** payload,
206     ServerCompletionQueue* notification_cq) {
207   // The following call_start_batch is internally-generated so no need for an
208   // explanatory log on failure.
209   GPR_ASSERT(grpc_server_request_registered_call(
210                  server_->server(), registered_method, &call_,
211                  &context_->deadline_, context_->client_metadata_.arr(),
212                  payload, call_cq_->cq(), notification_cq->cq(),
213                  this) == GRPC_CALL_OK);
214 }
215 
GenericAsyncRequest(ServerInterface * server,GenericServerContext * context,internal::ServerAsyncStreamingInterface * stream,CompletionQueue * call_cq,ServerCompletionQueue * notification_cq,void * tag,bool delete_on_finalize)216 ServerInterface::GenericAsyncRequest::GenericAsyncRequest(
217     ServerInterface* server, GenericServerContext* context,
218     internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
219     ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
220     : BaseAsyncRequest(server, context, stream, call_cq, notification_cq, tag,
221                        delete_on_finalize) {
222   grpc_call_details_init(&call_details_);
223   GPR_ASSERT(notification_cq);
224   GPR_ASSERT(call_cq);
225   // The following call_start_batch is internally-generated so no need for an
226   // explanatory log on failure.
227   GPR_ASSERT(grpc_server_request_call(server->server(), &call_, &call_details_,
228                                       context->client_metadata_.arr(),
229                                       call_cq->cq(), notification_cq->cq(),
230                                       this) == GRPC_CALL_OK);
231 }
232 
FinalizeResult(void ** tag,bool * status)233 bool ServerInterface::GenericAsyncRequest::FinalizeResult(void** tag,
234                                                           bool* status) {
235   // If we are done intercepting, there is nothing more for us to do
236   if (done_intercepting_) {
237     return BaseAsyncRequest::FinalizeResult(tag, status);
238   }
239   // TODO(yangg) remove the copy here.
240   if (*status) {
241     static_cast<GenericServerContext*>(context_)->method_ =
242         StringFromCopiedSlice(call_details_.method);
243     static_cast<GenericServerContext*>(context_)->host_ =
244         StringFromCopiedSlice(call_details_.host);
245     context_->deadline_ = call_details_.deadline;
246   }
247   grpc_slice_unref(call_details_.method);
248   grpc_slice_unref(call_details_.host);
249   call_wrapper_ = internal::Call(
250       call_, server_, call_cq_, server_->max_receive_message_size(),
251       context_->set_server_rpc_info(
252           static_cast<GenericServerContext*>(context_)->method_.c_str(),
253           internal::RpcMethod::BIDI_STREAMING,
254           *server_->interceptor_creators()));
255   return BaseAsyncRequest::FinalizeResult(tag, status);
256 }
257 
258 namespace {
259 class ShutdownCallback : public grpc_experimental_completion_queue_functor {
260  public:
ShutdownCallback()261   ShutdownCallback() {
262     functor_run = &ShutdownCallback::Run;
263     // Set inlineable to true since this callback is trivial and thus does not
264     // need to be run from the executor (triggering a thread hop). This should
265     // only be used by internal callbacks like this and not by user application
266     // code.
267     inlineable = true;
268   }
269   // TakeCQ takes ownership of the cq into the shutdown callback
270   // so that the shutdown callback will be responsible for destroying it
TakeCQ(CompletionQueue * cq)271   void TakeCQ(CompletionQueue* cq) { cq_ = cq; }
272 
273   // The Run function will get invoked by the completion queue library
274   // when the shutdown is actually complete
Run(grpc_experimental_completion_queue_functor * cb,int)275   static void Run(grpc_experimental_completion_queue_functor* cb, int) {
276     auto* callback = static_cast<ShutdownCallback*>(cb);
277     delete callback->cq_;
278     delete callback;
279   }
280 
281  private:
282   CompletionQueue* cq_ = nullptr;
283 };
284 }  // namespace
285 
286 }  // namespace grpc
287 
288 namespace grpc_impl {
289 
290 /// Use private inheritance rather than composition only to establish order
291 /// of construction, since the public base class should be constructed after the
292 /// elements belonging to the private base class are constructed. This is not
293 /// possible using true composition.
294 class Server::UnimplementedAsyncRequest final
295     : private grpc::UnimplementedAsyncRequestContext,
296       public GenericAsyncRequest {
297  public:
UnimplementedAsyncRequest(Server * server,grpc::ServerCompletionQueue * cq)298   UnimplementedAsyncRequest(Server* server, grpc::ServerCompletionQueue* cq)
299       : GenericAsyncRequest(server, &server_context_, &generic_stream_, cq, cq,
300                             nullptr, false),
301         server_(server),
302         cq_(cq) {}
303 
304   bool FinalizeResult(void** tag, bool* status) override;
305 
context()306   grpc::ServerContext* context() { return &server_context_; }
stream()307   grpc::GenericServerAsyncReaderWriter* stream() { return &generic_stream_; }
308 
309  private:
310   Server* const server_;
311   grpc::ServerCompletionQueue* const cq_;
312 };
313 
314 /// UnimplementedAsyncResponse should not post user-visible completions to the
315 /// C++ completion queue, but is generated as a CQ event by the core
316 class Server::UnimplementedAsyncResponse final
317     : public grpc::internal::CallOpSet<
318           grpc::internal::CallOpSendInitialMetadata,
319           grpc::internal::CallOpServerSendStatus> {
320  public:
321   UnimplementedAsyncResponse(UnimplementedAsyncRequest* request);
~UnimplementedAsyncResponse()322   ~UnimplementedAsyncResponse() { delete request_; }
323 
FinalizeResult(void ** tag,bool * status)324   bool FinalizeResult(void** tag, bool* status) override {
325     if (grpc::internal::CallOpSet<
326             grpc::internal::CallOpSendInitialMetadata,
327             grpc::internal::CallOpServerSendStatus>::FinalizeResult(tag,
328                                                                     status)) {
329       delete this;
330     } else {
331       // The tag was swallowed due to interception. We will see it again.
332     }
333     return false;
334   }
335 
336  private:
337   UnimplementedAsyncRequest* const request_;
338 };
339 
340 class Server::SyncRequest final : public grpc::internal::CompletionQueueTag {
341  public:
SyncRequest(grpc::internal::RpcServiceMethod * method,void * method_tag)342   SyncRequest(grpc::internal::RpcServiceMethod* method, void* method_tag)
343       : method_(method),
344         method_tag_(method_tag),
345         in_flight_(false),
346         has_request_payload_(method->method_type() ==
347                                  grpc::internal::RpcMethod::NORMAL_RPC ||
348                              method->method_type() ==
349                                  grpc::internal::RpcMethod::SERVER_STREAMING),
350         call_details_(nullptr),
351         cq_(nullptr) {
352     grpc_metadata_array_init(&request_metadata_);
353   }
354 
~SyncRequest()355   ~SyncRequest() {
356     if (call_details_) {
357       delete call_details_;
358     }
359     grpc_metadata_array_destroy(&request_metadata_);
360   }
361 
SetupRequest()362   void SetupRequest() { cq_ = grpc_completion_queue_create_for_pluck(nullptr); }
363 
TeardownRequest()364   void TeardownRequest() {
365     grpc_completion_queue_destroy(cq_);
366     cq_ = nullptr;
367   }
368 
Request(grpc_server * server,grpc_completion_queue * notify_cq)369   void Request(grpc_server* server, grpc_completion_queue* notify_cq) {
370     GPR_ASSERT(cq_ && !in_flight_);
371     in_flight_ = true;
372     if (method_tag_) {
373       if (grpc_server_request_registered_call(
374               server, method_tag_, &call_, &deadline_, &request_metadata_,
375               has_request_payload_ ? &request_payload_ : nullptr, cq_,
376               notify_cq, this) != GRPC_CALL_OK) {
377         TeardownRequest();
378         return;
379       }
380     } else {
381       if (!call_details_) {
382         call_details_ = new grpc_call_details;
383         grpc_call_details_init(call_details_);
384       }
385       if (grpc_server_request_call(server, &call_, call_details_,
386                                    &request_metadata_, cq_, notify_cq,
387                                    this) != GRPC_CALL_OK) {
388         TeardownRequest();
389         return;
390       }
391     }
392   }
393 
PostShutdownCleanup()394   void PostShutdownCleanup() {
395     if (call_) {
396       grpc_call_unref(call_);
397       call_ = nullptr;
398     }
399     if (cq_) {
400       grpc_completion_queue_destroy(cq_);
401       cq_ = nullptr;
402     }
403   }
404 
FinalizeResult(void **,bool * status)405   bool FinalizeResult(void** /*tag*/, bool* status) override {
406     if (!*status) {
407       grpc_completion_queue_destroy(cq_);
408       cq_ = nullptr;
409     }
410     if (call_details_) {
411       deadline_ = call_details_->deadline;
412       grpc_call_details_destroy(call_details_);
413       grpc_call_details_init(call_details_);
414     }
415     return true;
416   }
417 
418   // The CallData class represents a call that is "active" as opposed
419   // to just being requested. It wraps and takes ownership of the cq from
420   // the call request
421   class CallData final {
422    public:
CallData(Server * server,SyncRequest * mrd)423     explicit CallData(Server* server, SyncRequest* mrd)
424         : cq_(mrd->cq_),
425           ctx_(mrd->deadline_, &mrd->request_metadata_),
426           has_request_payload_(mrd->has_request_payload_),
427           request_payload_(has_request_payload_ ? mrd->request_payload_
428                                                 : nullptr),
429           request_(nullptr),
430           method_(mrd->method_),
431           call_(
432               mrd->call_, server, &cq_, server->max_receive_message_size(),
433               ctx_.set_server_rpc_info(method_->name(), method_->method_type(),
434                                        server->interceptor_creators_)),
435           server_(server),
436           global_callbacks_(nullptr),
437           resources_(false) {
438       ctx_.set_call(mrd->call_);
439       ctx_.cq_ = &cq_;
440       GPR_ASSERT(mrd->in_flight_);
441       mrd->in_flight_ = false;
442       mrd->request_metadata_.count = 0;
443     }
444 
~CallData()445     ~CallData() {
446       if (has_request_payload_ && request_payload_) {
447         grpc_byte_buffer_destroy(request_payload_);
448       }
449     }
450 
Run(const std::shared_ptr<GlobalCallbacks> & global_callbacks,bool resources)451     void Run(const std::shared_ptr<GlobalCallbacks>& global_callbacks,
452              bool resources) {
453       global_callbacks_ = global_callbacks;
454       resources_ = resources;
455 
456       interceptor_methods_.SetCall(&call_);
457       interceptor_methods_.SetReverse();
458       // Set interception point for RECV INITIAL METADATA
459       interceptor_methods_.AddInterceptionHookPoint(
460           grpc::experimental::InterceptionHookPoints::
461               POST_RECV_INITIAL_METADATA);
462       interceptor_methods_.SetRecvInitialMetadata(&ctx_.client_metadata_);
463 
464       if (has_request_payload_) {
465         // Set interception point for RECV MESSAGE
466         auto* handler = resources_ ? method_->handler()
467                                    : server_->resource_exhausted_handler_.get();
468         request_ = handler->Deserialize(call_.call(), request_payload_,
469                                         &request_status_, nullptr);
470 
471         request_payload_ = nullptr;
472         interceptor_methods_.AddInterceptionHookPoint(
473             grpc::experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
474         interceptor_methods_.SetRecvMessage(request_, nullptr);
475       }
476 
477       if (interceptor_methods_.RunInterceptors(
478               [this]() { ContinueRunAfterInterception(); })) {
479         ContinueRunAfterInterception();
480       } else {
481         // There were interceptors to be run, so ContinueRunAfterInterception
482         // will be run when interceptors are done.
483       }
484     }
485 
ContinueRunAfterInterception()486     void ContinueRunAfterInterception() {
487       {
488         ctx_.BeginCompletionOp(&call_, nullptr, nullptr);
489         global_callbacks_->PreSynchronousRequest(&ctx_);
490         auto* handler = resources_ ? method_->handler()
491                                    : server_->resource_exhausted_handler_.get();
492         handler->RunHandler(grpc::internal::MethodHandler::HandlerParameter(
493             &call_, &ctx_, request_, request_status_, nullptr, nullptr));
494         request_ = nullptr;
495         global_callbacks_->PostSynchronousRequest(&ctx_);
496 
497         cq_.Shutdown();
498 
499         grpc::internal::CompletionQueueTag* op_tag = ctx_.GetCompletionOpTag();
500         cq_.TryPluck(op_tag, gpr_inf_future(GPR_CLOCK_REALTIME));
501 
502         /* Ensure the cq_ is shutdown */
503         grpc::DummyTag ignored_tag;
504         GPR_ASSERT(cq_.Pluck(&ignored_tag) == false);
505       }
506       delete this;
507     }
508 
509    private:
510     grpc::CompletionQueue cq_;
511     grpc::ServerContext ctx_;
512     const bool has_request_payload_;
513     grpc_byte_buffer* request_payload_;
514     void* request_;
515     grpc::Status request_status_;
516     grpc::internal::RpcServiceMethod* const method_;
517     grpc::internal::Call call_;
518     Server* server_;
519     std::shared_ptr<GlobalCallbacks> global_callbacks_;
520     bool resources_;
521     grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_;
522   };
523 
524  private:
525   grpc::internal::RpcServiceMethod* const method_;
526   void* const method_tag_;
527   bool in_flight_;
528   const bool has_request_payload_;
529   grpc_call* call_;
530   grpc_call_details* call_details_;
531   gpr_timespec deadline_;
532   grpc_metadata_array request_metadata_;
533   grpc_byte_buffer* request_payload_;
534   grpc_completion_queue* cq_;
535 };
536 
537 template <class ServerContextType>
538 class Server::CallbackRequest final
539     : public grpc::internal::CompletionQueueTag {
540  public:
541   static_assert(
542       std::is_base_of<grpc::CallbackServerContext, ServerContextType>::value,
543       "ServerContextType must be derived from CallbackServerContext");
544 
545   // For codegen services, the value of method represents the defined
546   // characteristics of the method being requested. For generic services, method
547   // is nullptr since these services don't have pre-defined methods.
CallbackRequest(Server * server,grpc::internal::RpcServiceMethod * method,grpc::CompletionQueue * cq,grpc_core::ServerRegisteredCallAllocation * data)548   CallbackRequest(Server* server, grpc::internal::RpcServiceMethod* method,
549                   grpc::CompletionQueue* cq,
550                   grpc_core::ServerRegisteredCallAllocation* data)
551       : server_(server),
552         method_(method),
553         has_request_payload_(method->method_type() ==
554                                  grpc::internal::RpcMethod::NORMAL_RPC ||
555                              method->method_type() ==
556                                  grpc::internal::RpcMethod::SERVER_STREAMING),
557         cq_(cq),
558         tag_(this) {
559     server->Ref();
560     Setup();
561     data->tag = &tag_;
562     data->call = &call_;
563     data->initial_metadata = &request_metadata_;
564     data->deadline = &deadline_;
565     data->optional_payload = has_request_payload_ ? &request_payload_ : nullptr;
566   }
567 
568   // For generic services, method is nullptr since these services don't have
569   // pre-defined methods.
CallbackRequest(Server * server,grpc::CompletionQueue * cq,grpc_core::ServerBatchCallAllocation * data)570   CallbackRequest(Server* server, grpc::CompletionQueue* cq,
571                   grpc_core::ServerBatchCallAllocation* data)
572       : server_(server),
573         method_(nullptr),
574         has_request_payload_(false),
575         cq_(cq),
576         tag_(this) {
577     server->Ref();
578     Setup();
579     data->tag = &tag_;
580     data->call = &call_;
581     data->initial_metadata = &request_metadata_;
582     if (!call_details_) {
583       call_details_ = new grpc_call_details;
584       grpc_call_details_init(call_details_);
585     }
586     data->details = call_details_;
587   }
588 
~CallbackRequest()589   ~CallbackRequest() {
590     Clear();
591     server_->UnrefWithPossibleNotify();
592   }
593 
594   // Needs specialization to account for different processing of metadata
595   // in generic API
596   bool FinalizeResult(void** tag, bool* status) override;
597 
598  private:
599   // method_name needs to be specialized between named method and generic
600   const char* method_name() const;
601 
602   class CallbackCallTag : public grpc_experimental_completion_queue_functor {
603    public:
CallbackCallTag(Server::CallbackRequest<ServerContextType> * req)604     CallbackCallTag(Server::CallbackRequest<ServerContextType>* req)
605         : req_(req) {
606       functor_run = &CallbackCallTag::StaticRun;
607       // Set inlineable to true since this callback is internally-controlled
608       // without taking any locks, and thus does not need to be run from the
609       // executor (which triggers a thread hop). This should only be used by
610       // internal callbacks like this and not by user application code. The work
611       // here is actually non-trivial, but there is no chance of having user
612       // locks conflict with each other so it's ok to run inlined.
613       inlineable = true;
614     }
615 
616     // force_run can not be performed on a tag if operations using this tag
617     // have been sent to PerformOpsOnCall. It is intended for error conditions
618     // that are detected before the operations are internally processed.
force_run(bool ok)619     void force_run(bool ok) { Run(ok); }
620 
621    private:
622     Server::CallbackRequest<ServerContextType>* req_;
623     grpc::internal::Call* call_;
624 
StaticRun(grpc_experimental_completion_queue_functor * cb,int ok)625     static void StaticRun(grpc_experimental_completion_queue_functor* cb,
626                           int ok) {
627       static_cast<CallbackCallTag*>(cb)->Run(static_cast<bool>(ok));
628     }
Run(bool ok)629     void Run(bool ok) {
630       void* ignored = req_;
631       bool new_ok = ok;
632       GPR_ASSERT(!req_->FinalizeResult(&ignored, &new_ok));
633       GPR_ASSERT(ignored == req_);
634 
635       if (!ok) {
636         // The call has been shutdown.
637         // Delete its contents to free up the request.
638         delete req_;
639         return;
640       }
641 
642       // Bind the call, deadline, and metadata from what we got
643       req_->ctx_.set_call(req_->call_);
644       req_->ctx_.cq_ = req_->cq_;
645       req_->ctx_.BindDeadlineAndMetadata(req_->deadline_,
646                                          &req_->request_metadata_);
647       req_->request_metadata_.count = 0;
648 
649       // Create a C++ Call to control the underlying core call
650       call_ =
651           new (grpc_call_arena_alloc(req_->call_, sizeof(grpc::internal::Call)))
652               grpc::internal::Call(
653                   req_->call_, req_->server_, req_->cq_,
654                   req_->server_->max_receive_message_size(),
655                   req_->ctx_.set_server_rpc_info(
656                       req_->method_name(),
657                       (req_->method_ != nullptr)
658                           ? req_->method_->method_type()
659                           : grpc::internal::RpcMethod::BIDI_STREAMING,
660                       req_->server_->interceptor_creators_));
661 
662       req_->interceptor_methods_.SetCall(call_);
663       req_->interceptor_methods_.SetReverse();
664       // Set interception point for RECV INITIAL METADATA
665       req_->interceptor_methods_.AddInterceptionHookPoint(
666           grpc::experimental::InterceptionHookPoints::
667               POST_RECV_INITIAL_METADATA);
668       req_->interceptor_methods_.SetRecvInitialMetadata(
669           &req_->ctx_.client_metadata_);
670 
671       if (req_->has_request_payload_) {
672         // Set interception point for RECV MESSAGE
673         req_->request_ = req_->method_->handler()->Deserialize(
674             req_->call_, req_->request_payload_, &req_->request_status_,
675             &req_->handler_data_);
676         req_->request_payload_ = nullptr;
677         req_->interceptor_methods_.AddInterceptionHookPoint(
678             grpc::experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
679         req_->interceptor_methods_.SetRecvMessage(req_->request_, nullptr);
680       }
681 
682       if (req_->interceptor_methods_.RunInterceptors(
683               [this] { ContinueRunAfterInterception(); })) {
684         ContinueRunAfterInterception();
685       } else {
686         // There were interceptors to be run, so ContinueRunAfterInterception
687         // will be run when interceptors are done.
688       }
689     }
ContinueRunAfterInterception()690     void ContinueRunAfterInterception() {
691       auto* handler = (req_->method_ != nullptr)
692                           ? req_->method_->handler()
693                           : req_->server_->generic_handler_.get();
694       handler->RunHandler(grpc::internal::MethodHandler::HandlerParameter(
695           call_, &req_->ctx_, req_->request_, req_->request_status_,
696           req_->handler_data_, [this] { delete req_; }));
697     }
698   };
699 
Clear()700   void Clear() {
701     if (call_details_) {
702       delete call_details_;
703       call_details_ = nullptr;
704     }
705     grpc_metadata_array_destroy(&request_metadata_);
706     if (has_request_payload_ && request_payload_) {
707       grpc_byte_buffer_destroy(request_payload_);
708     }
709     ctx_.Clear();
710     interceptor_methods_.ClearState();
711   }
712 
Setup()713   void Setup() {
714     grpc_metadata_array_init(&request_metadata_);
715     ctx_.Setup(gpr_inf_future(GPR_CLOCK_REALTIME));
716     request_payload_ = nullptr;
717     request_ = nullptr;
718     handler_data_ = nullptr;
719     request_status_ = grpc::Status();
720   }
721 
722   Server* const server_;
723   grpc::internal::RpcServiceMethod* const method_;
724   const bool has_request_payload_;
725   grpc_byte_buffer* request_payload_;
726   void* request_;
727   void* handler_data_;
728   grpc::Status request_status_;
729   grpc_call_details* call_details_ = nullptr;
730   grpc_call* call_;
731   gpr_timespec deadline_;
732   grpc_metadata_array request_metadata_;
733   grpc::CompletionQueue* cq_;
734   CallbackCallTag tag_;
735   ServerContextType ctx_;
736   grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_;
737 };
738 
739 template <>
FinalizeResult(void **,bool *)740 bool Server::CallbackRequest<grpc::CallbackServerContext>::FinalizeResult(
741     void** /*tag*/, bool* /*status*/) {
742   return false;
743 }
744 
745 template <>
746 bool Server::CallbackRequest<
FinalizeResult(void **,bool * status)747     grpc::GenericCallbackServerContext>::FinalizeResult(void** /*tag*/,
748                                                         bool* status) {
749   if (*status) {
750     deadline_ = call_details_->deadline;
751     // TODO(yangg) remove the copy here
752     ctx_.method_ = grpc::StringFromCopiedSlice(call_details_->method);
753     ctx_.host_ = grpc::StringFromCopiedSlice(call_details_->host);
754   }
755   grpc_slice_unref(call_details_->method);
756   grpc_slice_unref(call_details_->host);
757   return false;
758 }
759 
760 template <>
method_name() const761 const char* Server::CallbackRequest<grpc::CallbackServerContext>::method_name()
762     const {
763   return method_->name();
764 }
765 
766 template <>
767 const char* Server::CallbackRequest<
method_name() const768     grpc::GenericCallbackServerContext>::method_name() const {
769   return ctx_.method().c_str();
770 }
771 
772 // Implementation of ThreadManager. Each instance of SyncRequestThreadManager
773 // manages a pool of threads that poll for incoming Sync RPCs and call the
774 // appropriate RPC handlers
775 class Server::SyncRequestThreadManager : public grpc::ThreadManager {
776  public:
SyncRequestThreadManager(Server * server,grpc::CompletionQueue * server_cq,std::shared_ptr<GlobalCallbacks> global_callbacks,grpc_resource_quota * rq,int min_pollers,int max_pollers,int cq_timeout_msec)777   SyncRequestThreadManager(Server* server, grpc::CompletionQueue* server_cq,
778                            std::shared_ptr<GlobalCallbacks> global_callbacks,
779                            grpc_resource_quota* rq, int min_pollers,
780                            int max_pollers, int cq_timeout_msec)
781       : ThreadManager("SyncServer", rq, min_pollers, max_pollers),
782         server_(server),
783         server_cq_(server_cq),
784         cq_timeout_msec_(cq_timeout_msec),
785         global_callbacks_(std::move(global_callbacks)) {}
786 
PollForWork(void ** tag,bool * ok)787   WorkStatus PollForWork(void** tag, bool* ok) override {
788     *tag = nullptr;
789     // TODO(ctiller): workaround for GPR_TIMESPAN based deadlines not working
790     // right now
791     gpr_timespec deadline =
792         gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
793                      gpr_time_from_millis(cq_timeout_msec_, GPR_TIMESPAN));
794 
795     switch (server_cq_->AsyncNext(tag, ok, deadline)) {
796       case grpc::CompletionQueue::TIMEOUT:
797         return TIMEOUT;
798       case grpc::CompletionQueue::SHUTDOWN:
799         return SHUTDOWN;
800       case grpc::CompletionQueue::GOT_EVENT:
801         return WORK_FOUND;
802     }
803 
804     GPR_UNREACHABLE_CODE(return TIMEOUT);
805   }
806 
DoWork(void * tag,bool ok,bool resources)807   void DoWork(void* tag, bool ok, bool resources) override {
808     SyncRequest* sync_req = static_cast<SyncRequest*>(tag);
809 
810     if (!sync_req) {
811       // No tag. Nothing to work on. This is an unlikley scenario and possibly a
812       // bug in RPC Manager implementation.
813       gpr_log(GPR_ERROR, "Sync server. DoWork() was called with NULL tag");
814       return;
815     }
816 
817     if (ok) {
818       // Calldata takes ownership of the completion queue and interceptors
819       // inside sync_req
820       auto* cd = new SyncRequest::CallData(server_, sync_req);
821       // Prepare for the next request
822       if (!IsShutdown()) {
823         sync_req->SetupRequest();  // Create new completion queue for sync_req
824         sync_req->Request(server_->c_server(), server_cq_->cq());
825       }
826 
827       GPR_TIMER_SCOPE("cd.Run()", 0);
828       cd->Run(global_callbacks_, resources);
829     }
830     // TODO (sreek) If ok is false here (which it isn't in case of
831     // grpc_request_registered_call), we should still re-queue the request
832     // object
833   }
834 
AddSyncMethod(grpc::internal::RpcServiceMethod * method,void * tag)835   void AddSyncMethod(grpc::internal::RpcServiceMethod* method, void* tag) {
836     sync_requests_.emplace_back(new SyncRequest(method, tag));
837   }
838 
AddUnknownSyncMethod()839   void AddUnknownSyncMethod() {
840     if (!sync_requests_.empty()) {
841       unknown_method_.reset(new grpc::internal::RpcServiceMethod(
842           "unknown", grpc::internal::RpcMethod::BIDI_STREAMING,
843           new grpc::internal::UnknownMethodHandler));
844       sync_requests_.emplace_back(
845           new SyncRequest(unknown_method_.get(), nullptr));
846     }
847   }
848 
Shutdown()849   void Shutdown() override {
850     ThreadManager::Shutdown();
851     server_cq_->Shutdown();
852   }
853 
Wait()854   void Wait() override {
855     ThreadManager::Wait();
856     // Drain any pending items from the queue
857     void* tag;
858     bool ok;
859     while (server_cq_->Next(&tag, &ok)) {
860       if (ok) {
861         // If a request was pulled off the queue, it means that the thread
862         // handling the request added it to the completion queue after shutdown
863         // was called - because the thread had already started and checked the
864         // shutdown flag before shutdown was called. In this case, we simply
865         // clean it up here, *after* calling wait on all the worker threads, at
866         // which point we are certain no in-flight requests will add more to the
867         // queue. This fixes an intermittent memory leak on shutdown.
868         SyncRequest* sync_req = static_cast<SyncRequest*>(tag);
869         sync_req->PostShutdownCleanup();
870       }
871     }
872   }
873 
Start()874   void Start() {
875     if (!sync_requests_.empty()) {
876       for (const auto& value : sync_requests_) {
877         value->SetupRequest();
878         value->Request(server_->c_server(), server_cq_->cq());
879       }
880 
881       Initialize();  // ThreadManager's Initialize()
882     }
883   }
884 
885  private:
886   Server* server_;
887   grpc::CompletionQueue* server_cq_;
888   int cq_timeout_msec_;
889   std::vector<std::unique_ptr<SyncRequest>> sync_requests_;
890   std::unique_ptr<grpc::internal::RpcServiceMethod> unknown_method_;
891   std::shared_ptr<Server::GlobalCallbacks> global_callbacks_;
892 };
893 
894 static grpc::internal::GrpcLibraryInitializer g_gli_initializer;
Server(grpc::ChannelArguments * args,std::shared_ptr<std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>> sync_server_cqs,int min_pollers,int max_pollers,int sync_cq_timeout_msec,std::vector<std::shared_ptr<grpc::internal::ExternalConnectionAcceptorImpl>> acceptors,grpc_resource_quota * server_rq,std::vector<std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>> interceptor_creators)895 Server::Server(
896     grpc::ChannelArguments* args,
897     std::shared_ptr<std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>>
898         sync_server_cqs,
899     int min_pollers, int max_pollers, int sync_cq_timeout_msec,
900     std::vector<std::shared_ptr<grpc::internal::ExternalConnectionAcceptorImpl>>
901         acceptors,
902     grpc_resource_quota* server_rq,
903     std::vector<
904         std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>>
905         interceptor_creators)
906     : acceptors_(std::move(acceptors)),
907       interceptor_creators_(std::move(interceptor_creators)),
908       max_receive_message_size_(INT_MIN),
909       sync_server_cqs_(std::move(sync_server_cqs)),
910       started_(false),
911       shutdown_(false),
912       shutdown_notified_(false),
913       server_(nullptr),
914       server_initializer_(new grpc_impl::ServerInitializer(this)),
915       health_check_service_disabled_(false) {
916   g_gli_initializer.summon();
917   gpr_once_init(&grpc::g_once_init_callbacks, grpc::InitGlobalCallbacks);
918   global_callbacks_ = grpc::g_callbacks;
919   global_callbacks_->UpdateArguments(args);
920 
921   if (sync_server_cqs_ != nullptr) {
922     bool default_rq_created = false;
923     if (server_rq == nullptr) {
924       server_rq = grpc_resource_quota_create("SyncServer-default-rq");
925       grpc_resource_quota_set_max_threads(server_rq,
926                                           DEFAULT_MAX_SYNC_SERVER_THREADS);
927       default_rq_created = true;
928     }
929 
930     for (const auto& it : *sync_server_cqs_) {
931       sync_req_mgrs_.emplace_back(new SyncRequestThreadManager(
932           this, it.get(), global_callbacks_, server_rq, min_pollers,
933           max_pollers, sync_cq_timeout_msec));
934     }
935 
936     if (default_rq_created) {
937       grpc_resource_quota_unref(server_rq);
938     }
939   }
940 
941   for (auto& acceptor : acceptors_) {
942     acceptor->SetToChannelArgs(args);
943   }
944 
945   grpc_channel_args channel_args;
946   args->SetChannelArgs(&channel_args);
947 
948   for (size_t i = 0; i < channel_args.num_args; i++) {
949     if (0 == strcmp(channel_args.args[i].key,
950                     grpc::kHealthCheckServiceInterfaceArg)) {
951       if (channel_args.args[i].value.pointer.p == nullptr) {
952         health_check_service_disabled_ = true;
953       } else {
954         health_check_service_.reset(
955             static_cast<grpc::HealthCheckServiceInterface*>(
956                 channel_args.args[i].value.pointer.p));
957       }
958     }
959     if (0 ==
960         strcmp(channel_args.args[i].key, GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH)) {
961       max_receive_message_size_ = channel_args.args[i].value.integer;
962     }
963   }
964   server_ = grpc_server_create(&channel_args, nullptr);
965 }
966 
~Server()967 Server::~Server() {
968   {
969     grpc::internal::ReleasableMutexLock lock(&mu_);
970     if (started_ && !shutdown_) {
971       lock.Unlock();
972       Shutdown();
973     } else if (!started_) {
974       // Shutdown the completion queues
975       for (const auto& value : sync_req_mgrs_) {
976         value->Shutdown();
977       }
978       if (callback_cq_ != nullptr) {
979         callback_cq_->Shutdown();
980         callback_cq_ = nullptr;
981       }
982     }
983   }
984 
985   grpc_server_destroy(server_);
986 }
987 
SetGlobalCallbacks(GlobalCallbacks * callbacks)988 void Server::SetGlobalCallbacks(GlobalCallbacks* callbacks) {
989   GPR_ASSERT(!grpc::g_callbacks);
990   GPR_ASSERT(callbacks);
991   grpc::g_callbacks.reset(callbacks);
992 }
993 
c_server()994 grpc_server* Server::c_server() { return server_; }
995 
InProcessChannel(const grpc::ChannelArguments & args)996 std::shared_ptr<grpc::Channel> Server::InProcessChannel(
997     const grpc::ChannelArguments& args) {
998   grpc_channel_args channel_args = args.c_channel_args();
999   return grpc::CreateChannelInternal(
1000       "inproc", grpc_inproc_channel_create(server_, &channel_args, nullptr),
1001       std::vector<std::unique_ptr<
1002           grpc::experimental::ClientInterceptorFactoryInterface>>());
1003 }
1004 
1005 std::shared_ptr<grpc::Channel>
InProcessChannelWithInterceptors(const grpc::ChannelArguments & args,std::vector<std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>> interceptor_creators)1006 Server::experimental_type::InProcessChannelWithInterceptors(
1007     const grpc::ChannelArguments& args,
1008     std::vector<
1009         std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
1010         interceptor_creators) {
1011   grpc_channel_args channel_args = args.c_channel_args();
1012   return grpc::CreateChannelInternal(
1013       "inproc",
1014       grpc_inproc_channel_create(server_->server_, &channel_args, nullptr),
1015       std::move(interceptor_creators));
1016 }
1017 
PayloadHandlingForMethod(grpc::internal::RpcServiceMethod * method)1018 static grpc_server_register_method_payload_handling PayloadHandlingForMethod(
1019     grpc::internal::RpcServiceMethod* method) {
1020   switch (method->method_type()) {
1021     case grpc::internal::RpcMethod::NORMAL_RPC:
1022     case grpc::internal::RpcMethod::SERVER_STREAMING:
1023       return GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER;
1024     case grpc::internal::RpcMethod::CLIENT_STREAMING:
1025     case grpc::internal::RpcMethod::BIDI_STREAMING:
1026       return GRPC_SRM_PAYLOAD_NONE;
1027   }
1028   GPR_UNREACHABLE_CODE(return GRPC_SRM_PAYLOAD_NONE;);
1029 }
1030 
RegisterService(const std::string * host,grpc::Service * service)1031 bool Server::RegisterService(const std::string* host, grpc::Service* service) {
1032   bool has_async_methods = service->has_async_methods();
1033   if (has_async_methods) {
1034     GPR_ASSERT(service->server_ == nullptr &&
1035                "Can only register an asynchronous service against one server.");
1036     service->server_ = this;
1037   }
1038 
1039   const char* method_name = nullptr;
1040 
1041   for (const auto& method : service->methods_) {
1042     if (method.get() == nullptr) {  // Handled by generic service if any.
1043       continue;
1044     }
1045 
1046     void* method_registration_tag = grpc_server_register_method(
1047         server_, method->name(), host ? host->c_str() : nullptr,
1048         PayloadHandlingForMethod(method.get()), 0);
1049     if (method_registration_tag == nullptr) {
1050       gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
1051               method->name());
1052       return false;
1053     }
1054 
1055     if (method->handler() == nullptr) {  // Async method without handler
1056       method->set_server_tag(method_registration_tag);
1057     } else if (method->api_type() ==
1058                grpc::internal::RpcServiceMethod::ApiType::SYNC) {
1059       for (const auto& value : sync_req_mgrs_) {
1060         value->AddSyncMethod(method.get(), method_registration_tag);
1061       }
1062     } else {
1063       has_callback_methods_ = true;
1064       grpc::internal::RpcServiceMethod* method_value = method.get();
1065       grpc::CompletionQueue* cq = CallbackCQ();
1066       grpc_core::SetServerRegisteredMethodAllocator(
1067           server_, cq->cq(), method_registration_tag, [this, cq, method_value] {
1068             grpc_core::ServerRegisteredCallAllocation result;
1069             new CallbackRequest<grpc::CallbackServerContext>(this, method_value,
1070                                                              cq, &result);
1071             return result;
1072           });
1073     }
1074 
1075     method_name = method->name();
1076   }
1077 
1078   // Parse service name.
1079   if (method_name != nullptr) {
1080     std::stringstream ss(method_name);
1081     std::string service_name;
1082     if (std::getline(ss, service_name, '/') &&
1083         std::getline(ss, service_name, '/')) {
1084       services_.push_back(service_name);
1085     }
1086   }
1087   return true;
1088 }
1089 
RegisterAsyncGenericService(grpc::AsyncGenericService * service)1090 void Server::RegisterAsyncGenericService(grpc::AsyncGenericService* service) {
1091   GPR_ASSERT(service->server_ == nullptr &&
1092              "Can only register an async generic service against one server.");
1093   service->server_ = this;
1094   has_async_generic_service_ = true;
1095 }
1096 
RegisterCallbackGenericService(grpc::CallbackGenericService * service)1097 void Server::RegisterCallbackGenericService(
1098     grpc::CallbackGenericService* service) {
1099   GPR_ASSERT(
1100       service->server_ == nullptr &&
1101       "Can only register a callback generic service against one server.");
1102   service->server_ = this;
1103   has_callback_generic_service_ = true;
1104   generic_handler_.reset(service->Handler());
1105 
1106   grpc::CompletionQueue* cq = CallbackCQ();
1107   grpc_core::SetServerBatchMethodAllocator(server_, cq->cq(), [this, cq] {
1108     grpc_core::ServerBatchCallAllocation result;
1109     new CallbackRequest<grpc::GenericCallbackServerContext>(this, cq, &result);
1110     return result;
1111   });
1112 }
1113 
AddListeningPort(const std::string & addr,grpc::ServerCredentials * creds)1114 int Server::AddListeningPort(const std::string& addr,
1115                              grpc::ServerCredentials* creds) {
1116   GPR_ASSERT(!started_);
1117   int port = creds->AddPortToServer(addr, server_);
1118   global_callbacks_->AddPort(this, addr, creds, port);
1119   return port;
1120 }
1121 
Ref()1122 void Server::Ref() {
1123   shutdown_refs_outstanding_.fetch_add(1, std::memory_order_relaxed);
1124 }
1125 
UnrefWithPossibleNotify()1126 void Server::UnrefWithPossibleNotify() {
1127   if (GPR_UNLIKELY(shutdown_refs_outstanding_.fetch_sub(
1128                        1, std::memory_order_acq_rel) == 1)) {
1129     // No refs outstanding means that shutdown has been initiated and no more
1130     // callback requests are outstanding.
1131     grpc::internal::MutexLock lock(&mu_);
1132     GPR_ASSERT(shutdown_);
1133     shutdown_done_ = true;
1134     shutdown_done_cv_.Signal();
1135   }
1136 }
1137 
UnrefAndWaitLocked()1138 void Server::UnrefAndWaitLocked() {
1139   if (GPR_UNLIKELY(shutdown_refs_outstanding_.fetch_sub(
1140                        1, std::memory_order_acq_rel) == 1)) {
1141     shutdown_done_ = true;
1142     return;  // no need to wait on CV since done condition already set
1143   }
1144   shutdown_done_cv_.WaitUntil(&mu_, [this] { return shutdown_done_; });
1145 }
1146 
Start(grpc::ServerCompletionQueue ** cqs,size_t num_cqs)1147 void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) {
1148   GPR_ASSERT(!started_);
1149   global_callbacks_->PreServerStart(this);
1150   started_ = true;
1151 
1152   // Only create default health check service when user did not provide an
1153   // explicit one.
1154   grpc::ServerCompletionQueue* health_check_cq = nullptr;
1155   grpc::DefaultHealthCheckService::HealthCheckServiceImpl*
1156       default_health_check_service_impl = nullptr;
1157   if (health_check_service_ == nullptr && !health_check_service_disabled_ &&
1158       grpc::DefaultHealthCheckServiceEnabled()) {
1159     auto* default_hc_service = new grpc::DefaultHealthCheckService;
1160     health_check_service_.reset(default_hc_service);
1161     // We create a non-polling CQ to avoid impacting application
1162     // performance.  This ensures that we don't introduce thread hops
1163     // for application requests that wind up on this CQ, which is polled
1164     // in its own thread.
1165     health_check_cq = new grpc::ServerCompletionQueue(
1166         GRPC_CQ_NEXT, GRPC_CQ_NON_POLLING, nullptr);
1167     grpc_server_register_completion_queue(server_, health_check_cq->cq(),
1168                                           nullptr);
1169     default_health_check_service_impl =
1170         default_hc_service->GetHealthCheckService(
1171             std::unique_ptr<grpc::ServerCompletionQueue>(health_check_cq));
1172     RegisterService(nullptr, default_health_check_service_impl);
1173   }
1174 
1175   for (auto& acceptor : acceptors_) {
1176     acceptor->GetCredentials()->AddPortToServer(acceptor->name(), server_);
1177   }
1178 
1179   // If this server uses callback methods, then create a callback generic
1180   // service to handle any unimplemented methods using the default reactor
1181   // creator
1182   if (has_callback_methods_ && !has_callback_generic_service_) {
1183     unimplemented_service_.reset(new grpc::CallbackGenericService);
1184     RegisterCallbackGenericService(unimplemented_service_.get());
1185   }
1186 
1187 #ifndef NDEBUG
1188   for (size_t i = 0; i < num_cqs; i++) {
1189     cq_list_.push_back(cqs[i]);
1190   }
1191 #endif
1192 
1193   grpc_server_start(server_);
1194 
1195   if (!has_async_generic_service_ && !has_callback_generic_service_) {
1196     for (const auto& value : sync_req_mgrs_) {
1197       value->AddUnknownSyncMethod();
1198     }
1199 
1200     for (size_t i = 0; i < num_cqs; i++) {
1201       if (cqs[i]->IsFrequentlyPolled()) {
1202         new UnimplementedAsyncRequest(this, cqs[i]);
1203       }
1204     }
1205     if (health_check_cq != nullptr) {
1206       new UnimplementedAsyncRequest(this, health_check_cq);
1207     }
1208   }
1209 
1210   // If this server has any support for synchronous methods (has any sync
1211   // server CQs), make sure that we have a ResourceExhausted handler
1212   // to deal with the case of thread exhaustion
1213   if (sync_server_cqs_ != nullptr && !sync_server_cqs_->empty()) {
1214     resource_exhausted_handler_.reset(
1215         new grpc::internal::ResourceExhaustedHandler);
1216   }
1217 
1218   for (const auto& value : sync_req_mgrs_) {
1219     value->Start();
1220   }
1221 
1222   if (default_health_check_service_impl != nullptr) {
1223     default_health_check_service_impl->StartServingThread();
1224   }
1225 
1226   for (auto& acceptor : acceptors_) {
1227     acceptor->Start();
1228   }
1229 }
1230 
ShutdownInternal(gpr_timespec deadline)1231 void Server::ShutdownInternal(gpr_timespec deadline) {
1232   grpc::internal::MutexLock lock(&mu_);
1233   if (shutdown_) {
1234     return;
1235   }
1236 
1237   shutdown_ = true;
1238 
1239   for (auto& acceptor : acceptors_) {
1240     acceptor->Shutdown();
1241   }
1242 
1243   /// The completion queue to use for server shutdown completion notification
1244   grpc::CompletionQueue shutdown_cq;
1245   grpc::ShutdownTag shutdown_tag;  // Dummy shutdown tag
1246   grpc_server_shutdown_and_notify(server_, shutdown_cq.cq(), &shutdown_tag);
1247 
1248   shutdown_cq.Shutdown();
1249 
1250   void* tag;
1251   bool ok;
1252   grpc::CompletionQueue::NextStatus status =
1253       shutdown_cq.AsyncNext(&tag, &ok, deadline);
1254 
1255   // If this timed out, it means we are done with the grace period for a clean
1256   // shutdown. We should force a shutdown now by cancelling all inflight calls
1257   if (status == grpc::CompletionQueue::NextStatus::TIMEOUT) {
1258     grpc_server_cancel_all_calls(server_);
1259   }
1260   // Else in case of SHUTDOWN or GOT_EVENT, it means that the server has
1261   // successfully shutdown
1262 
1263   // Shutdown all ThreadManagers. This will try to gracefully stop all the
1264   // threads in the ThreadManagers (once they process any inflight requests)
1265   for (const auto& value : sync_req_mgrs_) {
1266     value->Shutdown();  // ThreadManager's Shutdown()
1267   }
1268 
1269   // Wait for threads in all ThreadManagers to terminate
1270   for (const auto& value : sync_req_mgrs_) {
1271     value->Wait();
1272   }
1273 
1274   // Drop the shutdown ref and wait for all other refs to drop as well.
1275   UnrefAndWaitLocked();
1276 
1277   // Shutdown the callback CQ. The CQ is owned by its own shutdown tag, so it
1278   // will delete itself at true shutdown.
1279   if (callback_cq_ != nullptr) {
1280     callback_cq_->Shutdown();
1281     callback_cq_ = nullptr;
1282   }
1283 
1284   // Drain the shutdown queue (if the previous call to AsyncNext() timed out
1285   // and we didn't remove the tag from the queue yet)
1286   while (shutdown_cq.Next(&tag, &ok)) {
1287     // Nothing to be done here. Just ignore ok and tag values
1288   }
1289 
1290   shutdown_notified_ = true;
1291   shutdown_cv_.Broadcast();
1292 
1293 #ifndef NDEBUG
1294   // Unregister this server with the CQs passed into it by the user so that
1295   // those can be checked for properly-ordered shutdown.
1296   for (auto* cq : cq_list_) {
1297     cq->UnregisterServer(this);
1298   }
1299   cq_list_.clear();
1300 #endif
1301 }
1302 
Wait()1303 void Server::Wait() {
1304   grpc::internal::MutexLock lock(&mu_);
1305   while (started_ && !shutdown_notified_) {
1306     shutdown_cv_.Wait(&mu_);
1307   }
1308 }
1309 
PerformOpsOnCall(grpc::internal::CallOpSetInterface * ops,grpc::internal::Call * call)1310 void Server::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops,
1311                               grpc::internal::Call* call) {
1312   ops->FillOps(call);
1313 }
1314 
FinalizeResult(void ** tag,bool * status)1315 bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag,
1316                                                        bool* status) {
1317   if (GenericAsyncRequest::FinalizeResult(tag, status)) {
1318     // We either had no interceptors run or we are done intercepting
1319     if (*status) {
1320       new UnimplementedAsyncRequest(server_, cq_);
1321       new UnimplementedAsyncResponse(this);
1322     } else {
1323       delete this;
1324     }
1325   } else {
1326     // The tag was swallowed due to interception. We will see it again.
1327   }
1328   return false;
1329 }
1330 
UnimplementedAsyncResponse(UnimplementedAsyncRequest * request)1331 Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse(
1332     UnimplementedAsyncRequest* request)
1333     : request_(request) {
1334   grpc::Status status(grpc::StatusCode::UNIMPLEMENTED, "");
1335   grpc::internal::UnknownMethodHandler::FillOps(request_->context(), this);
1336   request_->stream()->call_.PerformOps(this);
1337 }
1338 
initializer()1339 grpc::ServerInitializer* Server::initializer() {
1340   return server_initializer_.get();
1341 }
1342 
CallbackCQ()1343 grpc::CompletionQueue* Server::CallbackCQ() {
1344   // TODO(vjpai): Consider using a single global CQ for the default CQ
1345   // if there is no explicit per-server CQ registered
1346   grpc::internal::MutexLock l(&mu_);
1347   if (callback_cq_ != nullptr) {
1348     return callback_cq_;
1349   }
1350   auto* shutdown_callback = new grpc::ShutdownCallback;
1351   callback_cq_ = new grpc::CompletionQueue(grpc_completion_queue_attributes{
1352       GRPC_CQ_CURRENT_VERSION, GRPC_CQ_CALLBACK, GRPC_CQ_DEFAULT_POLLING,
1353       shutdown_callback});
1354 
1355   // Transfer ownership of the new cq to its own shutdown callback
1356   shutdown_callback->TakeCQ(callback_cq_);
1357 
1358   return callback_cq_;
1359 }
1360 
1361 }  // namespace grpc_impl
1362