• 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 "absl/memory/memory.h"
46 
47 #include "src/core/ext/transport/inproc/inproc_transport.h"
48 #include "src/core/lib/iomgr/exec_ctx.h"
49 #include "src/core/lib/profiling/timers.h"
50 #include "src/core/lib/surface/call.h"
51 #include "src/core/lib/surface/completion_queue.h"
52 #include "src/core/lib/surface/server.h"
53 #include "src/cpp/client/create_channel_internal.h"
54 #include "src/cpp/server/external_connection_acceptor_impl.h"
55 #include "src/cpp/server/health/default_health_check_service.h"
56 #include "src/cpp/thread_manager/thread_manager.h"
57 
58 namespace grpc {
59 namespace {
60 
61 // The default value for maximum number of threads that can be created in the
62 // sync server. This value of INT_MAX is chosen to match the default behavior if
63 // no ResourceQuota is set. To modify the max number of threads in a sync
64 // server, pass a custom ResourceQuota object  (with the desired number of
65 // max-threads set) to the server builder.
66 #define DEFAULT_MAX_SYNC_SERVER_THREADS INT_MAX
67 
68 class DefaultGlobalCallbacks final : public Server::GlobalCallbacks {
69  public:
~DefaultGlobalCallbacks()70   ~DefaultGlobalCallbacks() override {}
PreSynchronousRequest(ServerContext *)71   void PreSynchronousRequest(ServerContext* /*context*/) override {}
PostSynchronousRequest(ServerContext *)72   void PostSynchronousRequest(ServerContext* /*context*/) override {}
73 };
74 
75 std::shared_ptr<Server::GlobalCallbacks> g_callbacks = nullptr;
76 gpr_once g_once_init_callbacks = GPR_ONCE_INIT;
77 
InitGlobalCallbacks()78 void InitGlobalCallbacks() {
79   if (!g_callbacks) {
80     g_callbacks.reset(new DefaultGlobalCallbacks());
81   }
82 }
83 
84 class ShutdownTag : public internal::CompletionQueueTag {
85  public:
FinalizeResult(void **,bool *)86   bool FinalizeResult(void** /*tag*/, bool* /*status*/) override {
87     return false;
88   }
89 };
90 
91 class DummyTag : public internal::CompletionQueueTag {
92  public:
FinalizeResult(void **,bool *)93   bool FinalizeResult(void** /*tag*/, bool* /*status*/) override {
94     return true;
95   }
96 };
97 
98 class UnimplementedAsyncRequestContext {
99  protected:
UnimplementedAsyncRequestContext()100   UnimplementedAsyncRequestContext() : generic_stream_(&server_context_) {}
101 
102   GenericServerContext server_context_;
103   GenericServerAsyncReaderWriter generic_stream_;
104 };
105 
106 // TODO(vjpai): Just for this file, use some contents of the experimental
107 // namespace here to make the code easier to read below. Remove this when
108 // de-experimentalized fully.
109 #ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
110 using ::grpc::experimental::CallbackGenericService;
111 using ::grpc::experimental::CallbackServerContext;
112 using ::grpc::experimental::GenericCallbackServerContext;
113 #endif
114 
115 }  // namespace
116 
BaseAsyncRequest(ServerInterface * server,ServerContext * context,internal::ServerAsyncStreamingInterface * stream,CompletionQueue * call_cq,ServerCompletionQueue * notification_cq,void * tag,bool delete_on_finalize)117 ServerInterface::BaseAsyncRequest::BaseAsyncRequest(
118     ServerInterface* server, ServerContext* context,
119     internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
120     ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
121     : server_(server),
122       context_(context),
123       stream_(stream),
124       call_cq_(call_cq),
125       notification_cq_(notification_cq),
126       tag_(tag),
127       delete_on_finalize_(delete_on_finalize),
128       call_(nullptr),
129       done_intercepting_(false) {
130   /* Set up interception state partially for the receive ops. call_wrapper_ is
131    * not filled at this point, but it will be filled before the interceptors are
132    * run. */
133   interceptor_methods_.SetCall(&call_wrapper_);
134   interceptor_methods_.SetReverse();
135   call_cq_->RegisterAvalanching();  // This op will trigger more ops
136 }
137 
~BaseAsyncRequest()138 ServerInterface::BaseAsyncRequest::~BaseAsyncRequest() {
139   call_cq_->CompleteAvalanching();
140 }
141 
FinalizeResult(void ** tag,bool * status)142 bool ServerInterface::BaseAsyncRequest::FinalizeResult(void** tag,
143                                                        bool* status) {
144   if (done_intercepting_) {
145     *tag = tag_;
146     if (delete_on_finalize_) {
147       delete this;
148     }
149     return true;
150   }
151   context_->set_call(call_);
152   context_->cq_ = call_cq_;
153   if (call_wrapper_.call() == nullptr) {
154     // Fill it since it is empty.
155     call_wrapper_ = internal::Call(
156         call_, server_, call_cq_, server_->max_receive_message_size(), nullptr);
157   }
158 
159   // just the pointers inside call are copied here
160   stream_->BindCall(&call_wrapper_);
161 
162   if (*status && call_ && call_wrapper_.server_rpc_info()) {
163     done_intercepting_ = true;
164     // Set interception point for RECV INITIAL METADATA
165     interceptor_methods_.AddInterceptionHookPoint(
166         experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA);
167     interceptor_methods_.SetRecvInitialMetadata(&context_->client_metadata_);
168     if (interceptor_methods_.RunInterceptors(
169             [this]() { ContinueFinalizeResultAfterInterception(); })) {
170       // There are no interceptors to run. Continue
171     } else {
172       // There were interceptors to be run, so
173       // ContinueFinalizeResultAfterInterception will be run when interceptors
174       // are done.
175       return false;
176     }
177   }
178   if (*status && call_) {
179     context_->BeginCompletionOp(&call_wrapper_, nullptr, nullptr);
180   }
181   *tag = tag_;
182   if (delete_on_finalize_) {
183     delete this;
184   }
185   return true;
186 }
187 
188 void ServerInterface::BaseAsyncRequest::
ContinueFinalizeResultAfterInterception()189     ContinueFinalizeResultAfterInterception() {
190   context_->BeginCompletionOp(&call_wrapper_, nullptr, nullptr);
191   // Queue a tag which will be returned immediately
192   grpc_core::ExecCtx exec_ctx;
193   grpc_cq_begin_op(notification_cq_->cq(), this);
194   grpc_cq_end_op(
195       notification_cq_->cq(), this, GRPC_ERROR_NONE,
196       [](void* /*arg*/, grpc_cq_completion* completion) { delete completion; },
197       nullptr, new grpc_cq_completion());
198 }
199 
RegisteredAsyncRequest(ServerInterface * server,ServerContext * context,internal::ServerAsyncStreamingInterface * stream,CompletionQueue * call_cq,ServerCompletionQueue * notification_cq,void * tag,const char * name,internal::RpcMethod::RpcType type)200 ServerInterface::RegisteredAsyncRequest::RegisteredAsyncRequest(
201     ServerInterface* server, ServerContext* context,
202     internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
203     ServerCompletionQueue* notification_cq, void* tag, const char* name,
204     internal::RpcMethod::RpcType type)
205     : BaseAsyncRequest(server, context, stream, call_cq, notification_cq, tag,
206                        true),
207       name_(name),
208       type_(type) {}
209 
IssueRequest(void * registered_method,grpc_byte_buffer ** payload,ServerCompletionQueue * notification_cq)210 void ServerInterface::RegisteredAsyncRequest::IssueRequest(
211     void* registered_method, grpc_byte_buffer** payload,
212     ServerCompletionQueue* notification_cq) {
213   // The following call_start_batch is internally-generated so no need for an
214   // explanatory log on failure.
215   GPR_ASSERT(grpc_server_request_registered_call(
216                  server_->server(), registered_method, &call_,
217                  &context_->deadline_, context_->client_metadata_.arr(),
218                  payload, call_cq_->cq(), notification_cq->cq(),
219                  this) == GRPC_CALL_OK);
220 }
221 
GenericAsyncRequest(ServerInterface * server,GenericServerContext * context,internal::ServerAsyncStreamingInterface * stream,CompletionQueue * call_cq,ServerCompletionQueue * notification_cq,void * tag,bool delete_on_finalize)222 ServerInterface::GenericAsyncRequest::GenericAsyncRequest(
223     ServerInterface* server, GenericServerContext* context,
224     internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
225     ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
226     : BaseAsyncRequest(server, context, stream, call_cq, notification_cq, tag,
227                        delete_on_finalize) {
228   grpc_call_details_init(&call_details_);
229   GPR_ASSERT(notification_cq);
230   GPR_ASSERT(call_cq);
231   // The following call_start_batch is internally-generated so no need for an
232   // explanatory log on failure.
233   GPR_ASSERT(grpc_server_request_call(server->server(), &call_, &call_details_,
234                                       context->client_metadata_.arr(),
235                                       call_cq->cq(), notification_cq->cq(),
236                                       this) == GRPC_CALL_OK);
237 }
238 
FinalizeResult(void ** tag,bool * status)239 bool ServerInterface::GenericAsyncRequest::FinalizeResult(void** tag,
240                                                           bool* status) {
241   // If we are done intercepting, there is nothing more for us to do
242   if (done_intercepting_) {
243     return BaseAsyncRequest::FinalizeResult(tag, status);
244   }
245   // TODO(yangg) remove the copy here.
246   if (*status) {
247     static_cast<GenericServerContext*>(context_)->method_ =
248         StringFromCopiedSlice(call_details_.method);
249     static_cast<GenericServerContext*>(context_)->host_ =
250         StringFromCopiedSlice(call_details_.host);
251     context_->deadline_ = call_details_.deadline;
252   }
253   grpc_slice_unref(call_details_.method);
254   grpc_slice_unref(call_details_.host);
255   call_wrapper_ = internal::Call(
256       call_, server_, call_cq_, server_->max_receive_message_size(),
257       context_->set_server_rpc_info(
258           static_cast<GenericServerContext*>(context_)->method_.c_str(),
259           internal::RpcMethod::BIDI_STREAMING,
260           *server_->interceptor_creators()));
261   return BaseAsyncRequest::FinalizeResult(tag, status);
262 }
263 
264 namespace {
265 class ShutdownCallback : public grpc_experimental_completion_queue_functor {
266  public:
ShutdownCallback()267   ShutdownCallback() {
268     functor_run = &ShutdownCallback::Run;
269     // Set inlineable to true since this callback is trivial and thus does not
270     // need to be run from the executor (triggering a thread hop). This should
271     // only be used by internal callbacks like this and not by user application
272     // code.
273     inlineable = true;
274   }
275   // TakeCQ takes ownership of the cq into the shutdown callback
276   // so that the shutdown callback will be responsible for destroying it
TakeCQ(CompletionQueue * cq)277   void TakeCQ(CompletionQueue* cq) { cq_ = cq; }
278 
279   // The Run function will get invoked by the completion queue library
280   // when the shutdown is actually complete
Run(grpc_experimental_completion_queue_functor * cb,int)281   static void Run(grpc_experimental_completion_queue_functor* cb, int) {
282     auto* callback = static_cast<ShutdownCallback*>(cb);
283     delete callback->cq_;
284     delete callback;
285   }
286 
287  private:
288   CompletionQueue* cq_ = nullptr;
289 };
290 }  // namespace
291 
292 /// Use private inheritance rather than composition only to establish order
293 /// of construction, since the public base class should be constructed after the
294 /// elements belonging to the private base class are constructed. This is not
295 /// possible using true composition.
296 class Server::UnimplementedAsyncRequest final
297     : private grpc::UnimplementedAsyncRequestContext,
298       public GenericAsyncRequest {
299  public:
UnimplementedAsyncRequest(ServerInterface * server,grpc::ServerCompletionQueue * cq)300   UnimplementedAsyncRequest(ServerInterface* server,
301                             grpc::ServerCompletionQueue* cq)
302       : GenericAsyncRequest(server, &server_context_, &generic_stream_, cq, cq,
303                             nullptr, false) {}
304 
305   bool FinalizeResult(void** tag, bool* status) override;
306 
context()307   grpc::ServerContext* context() { return &server_context_; }
stream()308   grpc::GenericServerAsyncReaderWriter* stream() { return &generic_stream_; }
309 };
310 
311 /// UnimplementedAsyncResponse should not post user-visible completions to the
312 /// C++ completion queue, but is generated as a CQ event by the core
313 class Server::UnimplementedAsyncResponse final
314     : public grpc::internal::CallOpSet<
315           grpc::internal::CallOpSendInitialMetadata,
316           grpc::internal::CallOpServerSendStatus> {
317  public:
318   explicit UnimplementedAsyncResponse(UnimplementedAsyncRequest* request);
~UnimplementedAsyncResponse()319   ~UnimplementedAsyncResponse() override { delete request_; }
320 
FinalizeResult(void ** tag,bool * status)321   bool FinalizeResult(void** tag, bool* status) override {
322     if (grpc::internal::CallOpSet<
323             grpc::internal::CallOpSendInitialMetadata,
324             grpc::internal::CallOpServerSendStatus>::FinalizeResult(tag,
325                                                                     status)) {
326       delete this;
327     } else {
328       // The tag was swallowed due to interception. We will see it again.
329     }
330     return false;
331   }
332 
333  private:
334   UnimplementedAsyncRequest* const request_;
335 };
336 
337 class Server::SyncRequest final : public grpc::internal::CompletionQueueTag {
338  public:
SyncRequest(grpc::internal::RpcServiceMethod * method,void * method_tag)339   SyncRequest(grpc::internal::RpcServiceMethod* method, void* method_tag)
340       : method_(method),
341         method_tag_(method_tag),
342         in_flight_(false),
343         has_request_payload_(method->method_type() ==
344                                  grpc::internal::RpcMethod::NORMAL_RPC ||
345                              method->method_type() ==
346                                  grpc::internal::RpcMethod::SERVER_STREAMING),
347         call_details_(nullptr),
348         cq_(nullptr) {
349     grpc_metadata_array_init(&request_metadata_);
350   }
351 
~SyncRequest()352   ~SyncRequest() override {
353     if (call_details_) {
354       delete call_details_;
355     }
356     grpc_metadata_array_destroy(&request_metadata_);
357   }
358 
SetupRequest()359   void SetupRequest() { cq_ = grpc_completion_queue_create_for_pluck(nullptr); }
360 
TeardownRequest()361   void TeardownRequest() {
362     grpc_completion_queue_destroy(cq_);
363     cq_ = nullptr;
364   }
365 
Request(grpc_server * server,grpc_completion_queue * notify_cq)366   void Request(grpc_server* server, grpc_completion_queue* notify_cq) {
367     GPR_ASSERT(cq_ && !in_flight_);
368     in_flight_ = true;
369     if (method_tag_) {
370       if (grpc_server_request_registered_call(
371               server, method_tag_, &call_, &deadline_, &request_metadata_,
372               has_request_payload_ ? &request_payload_ : nullptr, cq_,
373               notify_cq, this) != GRPC_CALL_OK) {
374         TeardownRequest();
375         return;
376       }
377     } else {
378       if (!call_details_) {
379         call_details_ = new grpc_call_details;
380         grpc_call_details_init(call_details_);
381       }
382       if (grpc_server_request_call(server, &call_, call_details_,
383                                    &request_metadata_, cq_, notify_cq,
384                                    this) != GRPC_CALL_OK) {
385         TeardownRequest();
386         return;
387       }
388     }
389   }
390 
PostShutdownCleanup()391   void PostShutdownCleanup() {
392     if (call_) {
393       grpc_call_unref(call_);
394       call_ = nullptr;
395     }
396     if (cq_) {
397       grpc_completion_queue_destroy(cq_);
398       cq_ = nullptr;
399     }
400   }
401 
FinalizeResult(void **,bool * status)402   bool FinalizeResult(void** /*tag*/, bool* status) override {
403     if (!*status) {
404       grpc_completion_queue_destroy(cq_);
405       cq_ = nullptr;
406     }
407     if (call_details_) {
408       deadline_ = call_details_->deadline;
409       grpc_call_details_destroy(call_details_);
410       grpc_call_details_init(call_details_);
411     }
412     return true;
413   }
414 
415   // The CallData class represents a call that is "active" as opposed
416   // to just being requested. It wraps and takes ownership of the cq from
417   // the call request
418   class CallData final {
419    public:
CallData(Server * server,SyncRequest * mrd)420     explicit CallData(Server* server, SyncRequest* mrd)
421         : cq_(mrd->cq_),
422           ctx_(mrd->deadline_, &mrd->request_metadata_),
423           has_request_payload_(mrd->has_request_payload_),
424           request_payload_(has_request_payload_ ? mrd->request_payload_
425                                                 : nullptr),
426           request_(nullptr),
427           method_(mrd->method_),
428           call_(
429               mrd->call_, server, &cq_, server->max_receive_message_size(),
430               ctx_.set_server_rpc_info(method_->name(), method_->method_type(),
431                                        server->interceptor_creators_)),
432           server_(server),
433           global_callbacks_(nullptr),
434           resources_(false) {
435       ctx_.set_call(mrd->call_);
436       ctx_.cq_ = &cq_;
437       GPR_ASSERT(mrd->in_flight_);
438       mrd->in_flight_ = false;
439       mrd->request_metadata_.count = 0;
440     }
441 
~CallData()442     ~CallData() {
443       if (has_request_payload_ && request_payload_) {
444         grpc_byte_buffer_destroy(request_payload_);
445       }
446     }
447 
Run(const std::shared_ptr<GlobalCallbacks> & global_callbacks,bool resources)448     void Run(const std::shared_ptr<GlobalCallbacks>& global_callbacks,
449              bool resources) {
450       global_callbacks_ = global_callbacks;
451       resources_ = resources;
452 
453       interceptor_methods_.SetCall(&call_);
454       interceptor_methods_.SetReverse();
455       // Set interception point for RECV INITIAL METADATA
456       interceptor_methods_.AddInterceptionHookPoint(
457           grpc::experimental::InterceptionHookPoints::
458               POST_RECV_INITIAL_METADATA);
459       interceptor_methods_.SetRecvInitialMetadata(&ctx_.client_metadata_);
460 
461       if (has_request_payload_) {
462         // Set interception point for RECV MESSAGE
463         auto* handler = resources_ ? method_->handler()
464                                    : server_->resource_exhausted_handler_.get();
465         request_ = handler->Deserialize(call_.call(), request_payload_,
466                                         &request_status_, nullptr);
467 
468         request_payload_ = nullptr;
469         interceptor_methods_.AddInterceptionHookPoint(
470             grpc::experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
471         interceptor_methods_.SetRecvMessage(request_, nullptr);
472       }
473 
474       if (interceptor_methods_.RunInterceptors(
475               [this]() { ContinueRunAfterInterception(); })) {
476         ContinueRunAfterInterception();
477       } else {
478         // There were interceptors to be run, so ContinueRunAfterInterception
479         // will be run when interceptors are done.
480       }
481     }
482 
ContinueRunAfterInterception()483     void ContinueRunAfterInterception() {
484       {
485         ctx_.BeginCompletionOp(&call_, nullptr, nullptr);
486         global_callbacks_->PreSynchronousRequest(&ctx_);
487         auto* handler = resources_ ? method_->handler()
488                                    : server_->resource_exhausted_handler_.get();
489         handler->RunHandler(grpc::internal::MethodHandler::HandlerParameter(
490             &call_, &ctx_, request_, request_status_, nullptr, nullptr));
491         request_ = nullptr;
492         global_callbacks_->PostSynchronousRequest(&ctx_);
493 
494         cq_.Shutdown();
495 
496         grpc::internal::CompletionQueueTag* op_tag = ctx_.GetCompletionOpTag();
497         cq_.TryPluck(op_tag, gpr_inf_future(GPR_CLOCK_REALTIME));
498 
499         /* Ensure the cq_ is shutdown */
500         grpc::DummyTag ignored_tag;
501         GPR_ASSERT(cq_.Pluck(&ignored_tag) == false);
502       }
503       delete this;
504     }
505 
506    private:
507     grpc::CompletionQueue cq_;
508     grpc::ServerContext ctx_;
509     const bool has_request_payload_;
510     grpc_byte_buffer* request_payload_;
511     void* request_;
512     grpc::Status request_status_;
513     grpc::internal::RpcServiceMethod* const method_;
514     grpc::internal::Call call_;
515     Server* server_;
516     std::shared_ptr<GlobalCallbacks> global_callbacks_;
517     bool resources_;
518     grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_;
519   };
520 
521  private:
522   grpc::internal::RpcServiceMethod* const method_;
523   void* const method_tag_;
524   bool in_flight_;
525   const bool has_request_payload_;
526   grpc_call* call_;
527   grpc_call_details* call_details_;
528   gpr_timespec deadline_;
529   grpc_metadata_array request_metadata_;
530   grpc_byte_buffer* request_payload_;
531   grpc_completion_queue* cq_;
532 };
533 
534 template <class ServerContextType>
535 class Server::CallbackRequest final
536     : public grpc::internal::CompletionQueueTag {
537  public:
538   static_assert(
539       std::is_base_of<grpc::CallbackServerContext, ServerContextType>::value,
540       "ServerContextType must be derived from CallbackServerContext");
541 
542   // For codegen services, the value of method represents the defined
543   // characteristics of the method being requested. For generic services, method
544   // is nullptr since these services don't have pre-defined methods.
CallbackRequest(Server * server,grpc::internal::RpcServiceMethod * method,grpc::CompletionQueue * cq,grpc_core::Server::RegisteredCallAllocation * data)545   CallbackRequest(Server* server, grpc::internal::RpcServiceMethod* method,
546                   grpc::CompletionQueue* cq,
547                   grpc_core::Server::RegisteredCallAllocation* data)
548       : server_(server),
549         method_(method),
550         has_request_payload_(method->method_type() ==
551                                  grpc::internal::RpcMethod::NORMAL_RPC ||
552                              method->method_type() ==
553                                  grpc::internal::RpcMethod::SERVER_STREAMING),
554         cq_(cq),
555         tag_(this),
556         ctx_(server_->context_allocator() != nullptr
557                  ? server_->context_allocator()->NewCallbackServerContext()
558                  : nullptr) {
559     CommonSetup(server, data);
560     data->deadline = &deadline_;
561     data->optional_payload = has_request_payload_ ? &request_payload_ : nullptr;
562   }
563 
564   // For generic services, method is nullptr since these services don't have
565   // pre-defined methods.
CallbackRequest(Server * server,grpc::CompletionQueue * cq,grpc_core::Server::BatchCallAllocation * data)566   CallbackRequest(Server* server, grpc::CompletionQueue* cq,
567                   grpc_core::Server::BatchCallAllocation* data)
568       : server_(server),
569         method_(nullptr),
570         has_request_payload_(false),
571         call_details_(new grpc_call_details),
572         cq_(cq),
573         tag_(this),
574         ctx_(server_->context_allocator() != nullptr
575                  ? server_->context_allocator()
576                        ->NewGenericCallbackServerContext()
577                  : nullptr) {
578     CommonSetup(server, data);
579     grpc_call_details_init(call_details_);
580     data->details = call_details_;
581   }
582 
~CallbackRequest()583   ~CallbackRequest() override {
584     delete call_details_;
585     grpc_metadata_array_destroy(&request_metadata_);
586     if (has_request_payload_ && request_payload_) {
587       grpc_byte_buffer_destroy(request_payload_);
588     }
589     if (server_->context_allocator() == nullptr || ctx_alloc_by_default_) {
590       delete ctx_;
591     }
592     server_->UnrefWithPossibleNotify();
593   }
594 
595   // Needs specialization to account for different processing of metadata
596   // in generic API
597   bool FinalizeResult(void** tag, bool* status) override;
598 
599  private:
600   // method_name needs to be specialized between named method and generic
601   const char* method_name() const;
602 
603   class CallbackCallTag : public grpc_experimental_completion_queue_functor {
604    public:
CallbackCallTag(Server::CallbackRequest<ServerContextType> * req)605     explicit CallbackCallTag(Server::CallbackRequest<ServerContextType>* req)
606         : req_(req) {
607       functor_run = &CallbackCallTag::StaticRun;
608       // Set inlineable to true since this callback is internally-controlled
609       // without taking any locks, and thus does not need to be run from the
610       // executor (which triggers a thread hop). This should only be used by
611       // internal callbacks like this and not by user application code. The work
612       // here is actually non-trivial, but there is no chance of having user
613       // locks conflict with each other so it's ok to run inlined.
614       inlineable = true;
615     }
616 
617     // force_run can not be performed on a tag if operations using this tag
618     // have been sent to PerformOpsOnCall. It is intended for error conditions
619     // that are detected before the operations are internally processed.
force_run(bool ok)620     void force_run(bool ok) { Run(ok); }
621 
622    private:
623     Server::CallbackRequest<ServerContextType>* req_;
624     grpc::internal::Call* call_;
625 
StaticRun(grpc_experimental_completion_queue_functor * cb,int ok)626     static void StaticRun(grpc_experimental_completion_queue_functor* cb,
627                           int ok) {
628       static_cast<CallbackCallTag*>(cb)->Run(static_cast<bool>(ok));
629     }
Run(bool ok)630     void Run(bool ok) {
631       void* ignored = req_;
632       bool new_ok = ok;
633       GPR_ASSERT(!req_->FinalizeResult(&ignored, &new_ok));
634       GPR_ASSERT(ignored == req_);
635 
636       if (!ok) {
637         // The call has been shutdown.
638         // Delete its contents to free up the request.
639         delete req_;
640         return;
641       }
642 
643       // Bind the call, deadline, and metadata from what we got
644       req_->ctx_->set_call(req_->call_);
645       req_->ctx_->cq_ = req_->cq_;
646       req_->ctx_->BindDeadlineAndMetadata(req_->deadline_,
647                                           &req_->request_metadata_);
648       req_->request_metadata_.count = 0;
649 
650       // Create a C++ Call to control the underlying core call
651       call_ =
652           new (grpc_call_arena_alloc(req_->call_, sizeof(grpc::internal::Call)))
653               grpc::internal::Call(
654                   req_->call_, req_->server_, req_->cq_,
655                   req_->server_->max_receive_message_size(),
656                   req_->ctx_->set_server_rpc_info(
657                       req_->method_name(),
658                       (req_->method_ != nullptr)
659                           ? req_->method_->method_type()
660                           : grpc::internal::RpcMethod::BIDI_STREAMING,
661                       req_->server_->interceptor_creators_));
662 
663       req_->interceptor_methods_.SetCall(call_);
664       req_->interceptor_methods_.SetReverse();
665       // Set interception point for RECV INITIAL METADATA
666       req_->interceptor_methods_.AddInterceptionHookPoint(
667           grpc::experimental::InterceptionHookPoints::
668               POST_RECV_INITIAL_METADATA);
669       req_->interceptor_methods_.SetRecvInitialMetadata(
670           &req_->ctx_->client_metadata_);
671 
672       if (req_->has_request_payload_) {
673         // Set interception point for RECV MESSAGE
674         req_->request_ = req_->method_->handler()->Deserialize(
675             req_->call_, req_->request_payload_, &req_->request_status_,
676             &req_->handler_data_);
677         req_->request_payload_ = nullptr;
678         req_->interceptor_methods_.AddInterceptionHookPoint(
679             grpc::experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
680         req_->interceptor_methods_.SetRecvMessage(req_->request_, nullptr);
681       }
682 
683       if (req_->interceptor_methods_.RunInterceptors(
684               [this] { ContinueRunAfterInterception(); })) {
685         ContinueRunAfterInterception();
686       } else {
687         // There were interceptors to be run, so ContinueRunAfterInterception
688         // will be run when interceptors are done.
689       }
690     }
ContinueRunAfterInterception()691     void ContinueRunAfterInterception() {
692       auto* handler = (req_->method_ != nullptr)
693                           ? req_->method_->handler()
694                           : req_->server_->generic_handler_.get();
695       handler->RunHandler(grpc::internal::MethodHandler::HandlerParameter(
696           call_, req_->ctx_, req_->request_, req_->request_status_,
697           req_->handler_data_, [this] { delete req_; }));
698     }
699   };
700 
701   template <class CallAllocation>
CommonSetup(Server * server,CallAllocation * data)702   void CommonSetup(Server* server, CallAllocation* data) {
703     server->Ref();
704     grpc_metadata_array_init(&request_metadata_);
705     data->tag = &tag_;
706     data->call = &call_;
707     data->initial_metadata = &request_metadata_;
708     if (ctx_ == nullptr) {
709       // TODO(ddyihai): allocate the context with grpc_call_arena_alloc.
710       ctx_ = new ServerContextType();
711       ctx_alloc_by_default_ = true;
712     }
713     ctx_->set_context_allocator(server->context_allocator());
714   }
715 
716   Server* const server_;
717   grpc::internal::RpcServiceMethod* const method_;
718   const bool has_request_payload_;
719   grpc_byte_buffer* request_payload_ = nullptr;
720   void* request_ = nullptr;
721   void* handler_data_ = nullptr;
722   grpc::Status request_status_;
723   grpc_call_details* const call_details_ = nullptr;
724   grpc_call* call_;
725   gpr_timespec deadline_;
726   grpc_metadata_array request_metadata_;
727   grpc::CompletionQueue* const cq_;
728   bool ctx_alloc_by_default_ = false;
729   CallbackCallTag tag_;
730   ServerContextType* ctx_ = nullptr;
731   grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_;
732 };
733 
734 template <>
FinalizeResult(void **,bool *)735 bool Server::CallbackRequest<grpc::CallbackServerContext>::FinalizeResult(
736     void** /*tag*/, bool* /*status*/) {
737   return false;
738 }
739 
740 template <>
741 bool Server::CallbackRequest<
FinalizeResult(void **,bool * status)742     grpc::GenericCallbackServerContext>::FinalizeResult(void** /*tag*/,
743                                                         bool* status) {
744   if (*status) {
745     deadline_ = call_details_->deadline;
746     // TODO(yangg) remove the copy here
747     ctx_->method_ = grpc::StringFromCopiedSlice(call_details_->method);
748     ctx_->host_ = grpc::StringFromCopiedSlice(call_details_->host);
749   }
750   grpc_slice_unref(call_details_->method);
751   grpc_slice_unref(call_details_->host);
752   return false;
753 }
754 
755 template <>
method_name() const756 const char* Server::CallbackRequest<grpc::CallbackServerContext>::method_name()
757     const {
758   return method_->name();
759 }
760 
761 template <>
762 const char* Server::CallbackRequest<
method_name() const763     grpc::GenericCallbackServerContext>::method_name() const {
764   return ctx_->method().c_str();
765 }
766 
767 // Implementation of ThreadManager. Each instance of SyncRequestThreadManager
768 // manages a pool of threads that poll for incoming Sync RPCs and call the
769 // appropriate RPC handlers
770 class Server::SyncRequestThreadManager : public grpc::ThreadManager {
771  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)772   SyncRequestThreadManager(Server* server, grpc::CompletionQueue* server_cq,
773                            std::shared_ptr<GlobalCallbacks> global_callbacks,
774                            grpc_resource_quota* rq, int min_pollers,
775                            int max_pollers, int cq_timeout_msec)
776       : ThreadManager("SyncServer", rq, min_pollers, max_pollers),
777         server_(server),
778         server_cq_(server_cq),
779         cq_timeout_msec_(cq_timeout_msec),
780         global_callbacks_(std::move(global_callbacks)) {}
781 
PollForWork(void ** tag,bool * ok)782   WorkStatus PollForWork(void** tag, bool* ok) override {
783     *tag = nullptr;
784     // TODO(ctiller): workaround for GPR_TIMESPAN based deadlines not working
785     // right now
786     gpr_timespec deadline =
787         gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
788                      gpr_time_from_millis(cq_timeout_msec_, GPR_TIMESPAN));
789 
790     switch (server_cq_->AsyncNext(tag, ok, deadline)) {
791       case grpc::CompletionQueue::TIMEOUT:
792         return TIMEOUT;
793       case grpc::CompletionQueue::SHUTDOWN:
794         return SHUTDOWN;
795       case grpc::CompletionQueue::GOT_EVENT:
796         return WORK_FOUND;
797     }
798 
799     GPR_UNREACHABLE_CODE(return TIMEOUT);
800   }
801 
DoWork(void * tag,bool ok,bool resources)802   void DoWork(void* tag, bool ok, bool resources) override {
803     SyncRequest* sync_req = static_cast<SyncRequest*>(tag);
804 
805     if (!sync_req) {
806       // No tag. Nothing to work on. This is an unlikley scenario and possibly a
807       // bug in RPC Manager implementation.
808       gpr_log(GPR_ERROR, "Sync server. DoWork() was called with NULL tag");
809       return;
810     }
811 
812     if (ok) {
813       // Calldata takes ownership of the completion queue and interceptors
814       // inside sync_req
815       auto* cd = new SyncRequest::CallData(server_, sync_req);
816       // Prepare for the next request
817       if (!IsShutdown()) {
818         sync_req->SetupRequest();  // Create new completion queue for sync_req
819         sync_req->Request(server_->c_server(), server_cq_->cq());
820       }
821 
822       GPR_TIMER_SCOPE("cd.Run()", 0);
823       cd->Run(global_callbacks_, resources);
824     }
825     // TODO (sreek) If ok is false here (which it isn't in case of
826     // grpc_request_registered_call), we should still re-queue the request
827     // object
828   }
829 
AddSyncMethod(grpc::internal::RpcServiceMethod * method,void * tag)830   void AddSyncMethod(grpc::internal::RpcServiceMethod* method, void* tag) {
831     sync_requests_.emplace_back(new SyncRequest(method, tag));
832   }
833 
AddUnknownSyncMethod()834   void AddUnknownSyncMethod() {
835     if (!sync_requests_.empty()) {
836       unknown_method_ = absl::make_unique<grpc::internal::RpcServiceMethod>(
837           "unknown", grpc::internal::RpcMethod::BIDI_STREAMING,
838           new grpc::internal::UnknownMethodHandler);
839       sync_requests_.emplace_back(
840           new SyncRequest(unknown_method_.get(), nullptr));
841     }
842   }
843 
Shutdown()844   void Shutdown() override {
845     ThreadManager::Shutdown();
846     server_cq_->Shutdown();
847   }
848 
Wait()849   void Wait() override {
850     ThreadManager::Wait();
851     // Drain any pending items from the queue
852     void* tag;
853     bool ok;
854     while (server_cq_->Next(&tag, &ok)) {
855       if (ok) {
856         // If a request was pulled off the queue, it means that the thread
857         // handling the request added it to the completion queue after shutdown
858         // was called - because the thread had already started and checked the
859         // shutdown flag before shutdown was called. In this case, we simply
860         // clean it up here, *after* calling wait on all the worker threads, at
861         // which point we are certain no in-flight requests will add more to the
862         // queue. This fixes an intermittent memory leak on shutdown.
863         SyncRequest* sync_req = static_cast<SyncRequest*>(tag);
864         sync_req->PostShutdownCleanup();
865       }
866     }
867   }
868 
Start()869   void Start() {
870     if (!sync_requests_.empty()) {
871       for (const auto& value : sync_requests_) {
872         value->SetupRequest();
873         value->Request(server_->c_server(), server_cq_->cq());
874       }
875 
876       Initialize();  // ThreadManager's Initialize()
877     }
878   }
879 
880  private:
881   Server* server_;
882   grpc::CompletionQueue* server_cq_;
883   int cq_timeout_msec_;
884   std::vector<std::unique_ptr<SyncRequest>> sync_requests_;
885   std::unique_ptr<grpc::internal::RpcServiceMethod> unknown_method_;
886   std::shared_ptr<Server::GlobalCallbacks> global_callbacks_;
887 };
888 
889 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_server_config_fetcher * server_config_fetcher,grpc_resource_quota * server_rq,std::vector<std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>> interceptor_creators)890 Server::Server(
891     grpc::ChannelArguments* args,
892     std::shared_ptr<std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>>
893         sync_server_cqs,
894     int min_pollers, int max_pollers, int sync_cq_timeout_msec,
895     std::vector<std::shared_ptr<grpc::internal::ExternalConnectionAcceptorImpl>>
896         acceptors,
897     grpc_server_config_fetcher* server_config_fetcher,
898     grpc_resource_quota* server_rq,
899     std::vector<
900         std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>>
901         interceptor_creators)
902     : acceptors_(std::move(acceptors)),
903       interceptor_creators_(std::move(interceptor_creators)),
904       max_receive_message_size_(INT_MIN),
905       sync_server_cqs_(std::move(sync_server_cqs)),
906       started_(false),
907       shutdown_(false),
908       shutdown_notified_(false),
909       server_(nullptr),
910       server_initializer_(new ServerInitializer(this)),
911       health_check_service_disabled_(false) {
912   g_gli_initializer.summon();
913   gpr_once_init(&grpc::g_once_init_callbacks, grpc::InitGlobalCallbacks);
914   global_callbacks_ = grpc::g_callbacks;
915   global_callbacks_->UpdateArguments(args);
916 
917   if (sync_server_cqs_ != nullptr) {
918     bool default_rq_created = false;
919     if (server_rq == nullptr) {
920       server_rq = grpc_resource_quota_create("SyncServer-default-rq");
921       grpc_resource_quota_set_max_threads(server_rq,
922                                           DEFAULT_MAX_SYNC_SERVER_THREADS);
923       default_rq_created = true;
924     }
925 
926     for (const auto& it : *sync_server_cqs_) {
927       sync_req_mgrs_.emplace_back(new SyncRequestThreadManager(
928           this, it.get(), global_callbacks_, server_rq, min_pollers,
929           max_pollers, sync_cq_timeout_msec));
930     }
931 
932     if (default_rq_created) {
933       grpc_resource_quota_unref(server_rq);
934     }
935   }
936 
937   for (auto& acceptor : acceptors_) {
938     acceptor->SetToChannelArgs(args);
939   }
940 
941   grpc_channel_args channel_args;
942   args->SetChannelArgs(&channel_args);
943 
944   for (size_t i = 0; i < channel_args.num_args; i++) {
945     if (0 == strcmp(channel_args.args[i].key,
946                     grpc::kHealthCheckServiceInterfaceArg)) {
947       if (channel_args.args[i].value.pointer.p == nullptr) {
948         health_check_service_disabled_ = true;
949       } else {
950         health_check_service_.reset(
951             static_cast<grpc::HealthCheckServiceInterface*>(
952                 channel_args.args[i].value.pointer.p));
953       }
954     }
955     if (0 ==
956         strcmp(channel_args.args[i].key, GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH)) {
957       max_receive_message_size_ = channel_args.args[i].value.integer;
958     }
959   }
960   server_ = grpc_server_create(&channel_args, nullptr);
961   grpc_server_set_config_fetcher(server_, server_config_fetcher);
962 }
963 
~Server()964 Server::~Server() {
965   {
966     grpc::internal::ReleasableMutexLock lock(&mu_);
967     if (started_ && !shutdown_) {
968       lock.Unlock();
969       Shutdown();
970     } else if (!started_) {
971       // Shutdown the completion queues
972       for (const auto& value : sync_req_mgrs_) {
973         value->Shutdown();
974       }
975       if (callback_cq_ != nullptr) {
976         callback_cq_->Shutdown();
977         callback_cq_ = nullptr;
978       }
979     }
980   }
981   // Destroy health check service before we destroy the C server so that
982   // it does not call grpc_server_request_registered_call() after the C
983   // server has been destroyed.
984   health_check_service_.reset();
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 * addr,grpc::Service * service)1031 bool Server::RegisterService(const std::string* addr, 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 == nullptr) {  // Handled by generic service if any.
1043       continue;
1044     }
1045 
1046     void* method_registration_tag = grpc_server_register_method(
1047         server_, method->name(), addr ? addr->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       server_->core_server->SetRegisteredMethodAllocator(
1067           cq->cq(), method_registration_tag, [this, cq, method_value] {
1068             grpc_core::Server::RegisteredCallAllocation 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   server_->core_server->SetBatchMethodAllocator(cq->cq(), [this, cq] {
1108     grpc_core::Server::BatchCallAllocation 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_ = absl::make_unique<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_ =
1215         absl::make_unique<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       // Create a new request/response pair using the server and CQ values
1321       // stored in this object's base class.
1322       new UnimplementedAsyncRequest(server_, notification_cq_);
1323       new UnimplementedAsyncResponse(this);
1324     } else {
1325       delete this;
1326     }
1327   } else {
1328     // The tag was swallowed due to interception. We will see it again.
1329   }
1330   return false;
1331 }
1332 
UnimplementedAsyncResponse(UnimplementedAsyncRequest * request)1333 Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse(
1334     UnimplementedAsyncRequest* request)
1335     : request_(request) {
1336   grpc::Status status(grpc::StatusCode::UNIMPLEMENTED, "");
1337   grpc::internal::UnknownMethodHandler::FillOps(request_->context(), this);
1338   request_->stream()->call_.PerformOps(this);
1339 }
1340 
initializer()1341 grpc::ServerInitializer* Server::initializer() {
1342   return server_initializer_.get();
1343 }
1344 
CallbackCQ()1345 grpc::CompletionQueue* Server::CallbackCQ() {
1346   // TODO(vjpai): Consider using a single global CQ for the default CQ
1347   // if there is no explicit per-server CQ registered
1348   grpc::internal::MutexLock l(&mu_);
1349   if (callback_cq_ != nullptr) {
1350     return callback_cq_;
1351   }
1352   auto* shutdown_callback = new grpc::ShutdownCallback;
1353   callback_cq_ = new grpc::CompletionQueue(grpc_completion_queue_attributes{
1354       GRPC_CQ_CURRENT_VERSION, GRPC_CQ_CALLBACK, GRPC_CQ_DEFAULT_POLLING,
1355       shutdown_callback});
1356 
1357   // Transfer ownership of the new cq to its own shutdown callback
1358   shutdown_callback->TakeCQ(callback_cq_);
1359 
1360   return callback_cq_;
1361 }
1362 
1363 }  // namespace grpc
1364