• 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     CommonSetup(server, data);
557     data->deadline = &deadline_;
558     data->optional_payload = has_request_payload_ ? &request_payload_ : nullptr;
559   }
560 
561   // For generic services, method is nullptr since these services don't have
562   // pre-defined methods.
CallbackRequest(Server * server,grpc::CompletionQueue * cq,grpc_core::Server::BatchCallAllocation * data)563   CallbackRequest(Server* server, grpc::CompletionQueue* cq,
564                   grpc_core::Server::BatchCallAllocation* data)
565       : server_(server),
566         method_(nullptr),
567         has_request_payload_(false),
568         call_details_(new grpc_call_details),
569         cq_(cq),
570         tag_(this) {
571     CommonSetup(server, data);
572     grpc_call_details_init(call_details_);
573     data->details = call_details_;
574   }
575 
~CallbackRequest()576   ~CallbackRequest() override {
577     delete call_details_;
578     grpc_metadata_array_destroy(&request_metadata_);
579     if (has_request_payload_ && request_payload_) {
580       grpc_byte_buffer_destroy(request_payload_);
581     }
582     server_->UnrefWithPossibleNotify();
583   }
584 
585   // Needs specialization to account for different processing of metadata
586   // in generic API
587   bool FinalizeResult(void** tag, bool* status) override;
588 
589  private:
590   // method_name needs to be specialized between named method and generic
591   const char* method_name() const;
592 
593   class CallbackCallTag : public grpc_experimental_completion_queue_functor {
594    public:
CallbackCallTag(Server::CallbackRequest<ServerContextType> * req)595     explicit CallbackCallTag(Server::CallbackRequest<ServerContextType>* req)
596         : req_(req) {
597       functor_run = &CallbackCallTag::StaticRun;
598       // Set inlineable to true since this callback is internally-controlled
599       // without taking any locks, and thus does not need to be run from the
600       // executor (which triggers a thread hop). This should only be used by
601       // internal callbacks like this and not by user application code. The work
602       // here is actually non-trivial, but there is no chance of having user
603       // locks conflict with each other so it's ok to run inlined.
604       inlineable = true;
605     }
606 
607     // force_run can not be performed on a tag if operations using this tag
608     // have been sent to PerformOpsOnCall. It is intended for error conditions
609     // that are detected before the operations are internally processed.
force_run(bool ok)610     void force_run(bool ok) { Run(ok); }
611 
612    private:
613     Server::CallbackRequest<ServerContextType>* req_;
614     grpc::internal::Call* call_;
615 
StaticRun(grpc_experimental_completion_queue_functor * cb,int ok)616     static void StaticRun(grpc_experimental_completion_queue_functor* cb,
617                           int ok) {
618       static_cast<CallbackCallTag*>(cb)->Run(static_cast<bool>(ok));
619     }
Run(bool ok)620     void Run(bool ok) {
621       void* ignored = req_;
622       bool new_ok = ok;
623       GPR_ASSERT(!req_->FinalizeResult(&ignored, &new_ok));
624       GPR_ASSERT(ignored == req_);
625 
626       if (!ok) {
627         // The call has been shutdown.
628         // Delete its contents to free up the request.
629         delete req_;
630         return;
631       }
632 
633       // Bind the call, deadline, and metadata from what we got
634       req_->ctx_.set_call(req_->call_);
635       req_->ctx_.cq_ = req_->cq_;
636       req_->ctx_.BindDeadlineAndMetadata(req_->deadline_,
637                                          &req_->request_metadata_);
638       req_->request_metadata_.count = 0;
639 
640       // Create a C++ Call to control the underlying core call
641       call_ =
642           new (grpc_call_arena_alloc(req_->call_, sizeof(grpc::internal::Call)))
643               grpc::internal::Call(
644                   req_->call_, req_->server_, req_->cq_,
645                   req_->server_->max_receive_message_size(),
646                   req_->ctx_.set_server_rpc_info(
647                       req_->method_name(),
648                       (req_->method_ != nullptr)
649                           ? req_->method_->method_type()
650                           : grpc::internal::RpcMethod::BIDI_STREAMING,
651                       req_->server_->interceptor_creators_));
652 
653       req_->interceptor_methods_.SetCall(call_);
654       req_->interceptor_methods_.SetReverse();
655       // Set interception point for RECV INITIAL METADATA
656       req_->interceptor_methods_.AddInterceptionHookPoint(
657           grpc::experimental::InterceptionHookPoints::
658               POST_RECV_INITIAL_METADATA);
659       req_->interceptor_methods_.SetRecvInitialMetadata(
660           &req_->ctx_.client_metadata_);
661 
662       if (req_->has_request_payload_) {
663         // Set interception point for RECV MESSAGE
664         req_->request_ = req_->method_->handler()->Deserialize(
665             req_->call_, req_->request_payload_, &req_->request_status_,
666             &req_->handler_data_);
667         req_->request_payload_ = nullptr;
668         req_->interceptor_methods_.AddInterceptionHookPoint(
669             grpc::experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
670         req_->interceptor_methods_.SetRecvMessage(req_->request_, nullptr);
671       }
672 
673       if (req_->interceptor_methods_.RunInterceptors(
674               [this] { ContinueRunAfterInterception(); })) {
675         ContinueRunAfterInterception();
676       } else {
677         // There were interceptors to be run, so ContinueRunAfterInterception
678         // will be run when interceptors are done.
679       }
680     }
ContinueRunAfterInterception()681     void ContinueRunAfterInterception() {
682       auto* handler = (req_->method_ != nullptr)
683                           ? req_->method_->handler()
684                           : req_->server_->generic_handler_.get();
685       handler->RunHandler(grpc::internal::MethodHandler::HandlerParameter(
686           call_, &req_->ctx_, req_->request_, req_->request_status_,
687           req_->handler_data_, [this] { delete req_; }));
688     }
689   };
690 
691   template <class CallAllocation>
CommonSetup(Server * server,CallAllocation * data)692   void CommonSetup(Server* server, CallAllocation* data) {
693     server->Ref();
694     grpc_metadata_array_init(&request_metadata_);
695     data->tag = &tag_;
696     data->call = &call_;
697     data->initial_metadata = &request_metadata_;
698   }
699 
700   Server* const server_;
701   grpc::internal::RpcServiceMethod* const method_;
702   const bool has_request_payload_;
703   grpc_byte_buffer* request_payload_ = nullptr;
704   void* request_ = nullptr;
705   void* handler_data_ = nullptr;
706   grpc::Status request_status_;
707   grpc_call_details* const call_details_ = nullptr;
708   grpc_call* call_;
709   gpr_timespec deadline_;
710   grpc_metadata_array request_metadata_;
711   grpc::CompletionQueue* const cq_;
712   CallbackCallTag tag_;
713   ServerContextType ctx_;
714   grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_;
715 };
716 
717 template <>
FinalizeResult(void **,bool *)718 bool Server::CallbackRequest<grpc::CallbackServerContext>::FinalizeResult(
719     void** /*tag*/, bool* /*status*/) {
720   return false;
721 }
722 
723 template <>
724 bool Server::CallbackRequest<
FinalizeResult(void **,bool * status)725     grpc::GenericCallbackServerContext>::FinalizeResult(void** /*tag*/,
726                                                         bool* status) {
727   if (*status) {
728     deadline_ = call_details_->deadline;
729     // TODO(yangg) remove the copy here
730     ctx_.method_ = grpc::StringFromCopiedSlice(call_details_->method);
731     ctx_.host_ = grpc::StringFromCopiedSlice(call_details_->host);
732   }
733   grpc_slice_unref(call_details_->method);
734   grpc_slice_unref(call_details_->host);
735   return false;
736 }
737 
738 template <>
method_name() const739 const char* Server::CallbackRequest<grpc::CallbackServerContext>::method_name()
740     const {
741   return method_->name();
742 }
743 
744 template <>
745 const char* Server::CallbackRequest<
method_name() const746     grpc::GenericCallbackServerContext>::method_name() const {
747   return ctx_.method().c_str();
748 }
749 
750 // Implementation of ThreadManager. Each instance of SyncRequestThreadManager
751 // manages a pool of threads that poll for incoming Sync RPCs and call the
752 // appropriate RPC handlers
753 class Server::SyncRequestThreadManager : public grpc::ThreadManager {
754  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)755   SyncRequestThreadManager(Server* server, grpc::CompletionQueue* server_cq,
756                            std::shared_ptr<GlobalCallbacks> global_callbacks,
757                            grpc_resource_quota* rq, int min_pollers,
758                            int max_pollers, int cq_timeout_msec)
759       : ThreadManager("SyncServer", rq, min_pollers, max_pollers),
760         server_(server),
761         server_cq_(server_cq),
762         cq_timeout_msec_(cq_timeout_msec),
763         global_callbacks_(std::move(global_callbacks)) {}
764 
PollForWork(void ** tag,bool * ok)765   WorkStatus PollForWork(void** tag, bool* ok) override {
766     *tag = nullptr;
767     // TODO(ctiller): workaround for GPR_TIMESPAN based deadlines not working
768     // right now
769     gpr_timespec deadline =
770         gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
771                      gpr_time_from_millis(cq_timeout_msec_, GPR_TIMESPAN));
772 
773     switch (server_cq_->AsyncNext(tag, ok, deadline)) {
774       case grpc::CompletionQueue::TIMEOUT:
775         return TIMEOUT;
776       case grpc::CompletionQueue::SHUTDOWN:
777         return SHUTDOWN;
778       case grpc::CompletionQueue::GOT_EVENT:
779         return WORK_FOUND;
780     }
781 
782     GPR_UNREACHABLE_CODE(return TIMEOUT);
783   }
784 
DoWork(void * tag,bool ok,bool resources)785   void DoWork(void* tag, bool ok, bool resources) override {
786     SyncRequest* sync_req = static_cast<SyncRequest*>(tag);
787 
788     if (!sync_req) {
789       // No tag. Nothing to work on. This is an unlikley scenario and possibly a
790       // bug in RPC Manager implementation.
791       gpr_log(GPR_ERROR, "Sync server. DoWork() was called with NULL tag");
792       return;
793     }
794 
795     if (ok) {
796       // Calldata takes ownership of the completion queue and interceptors
797       // inside sync_req
798       auto* cd = new SyncRequest::CallData(server_, sync_req);
799       // Prepare for the next request
800       if (!IsShutdown()) {
801         sync_req->SetupRequest();  // Create new completion queue for sync_req
802         sync_req->Request(server_->c_server(), server_cq_->cq());
803       }
804 
805       GPR_TIMER_SCOPE("cd.Run()", 0);
806       cd->Run(global_callbacks_, resources);
807     }
808     // TODO (sreek) If ok is false here (which it isn't in case of
809     // grpc_request_registered_call), we should still re-queue the request
810     // object
811   }
812 
AddSyncMethod(grpc::internal::RpcServiceMethod * method,void * tag)813   void AddSyncMethod(grpc::internal::RpcServiceMethod* method, void* tag) {
814     sync_requests_.emplace_back(new SyncRequest(method, tag));
815   }
816 
AddUnknownSyncMethod()817   void AddUnknownSyncMethod() {
818     if (!sync_requests_.empty()) {
819       unknown_method_ = absl::make_unique<grpc::internal::RpcServiceMethod>(
820           "unknown", grpc::internal::RpcMethod::BIDI_STREAMING,
821           new grpc::internal::UnknownMethodHandler);
822       sync_requests_.emplace_back(
823           new SyncRequest(unknown_method_.get(), nullptr));
824     }
825   }
826 
Shutdown()827   void Shutdown() override {
828     ThreadManager::Shutdown();
829     server_cq_->Shutdown();
830   }
831 
Wait()832   void Wait() override {
833     ThreadManager::Wait();
834     // Drain any pending items from the queue
835     void* tag;
836     bool ok;
837     while (server_cq_->Next(&tag, &ok)) {
838       if (ok) {
839         // If a request was pulled off the queue, it means that the thread
840         // handling the request added it to the completion queue after shutdown
841         // was called - because the thread had already started and checked the
842         // shutdown flag before shutdown was called. In this case, we simply
843         // clean it up here, *after* calling wait on all the worker threads, at
844         // which point we are certain no in-flight requests will add more to the
845         // queue. This fixes an intermittent memory leak on shutdown.
846         SyncRequest* sync_req = static_cast<SyncRequest*>(tag);
847         sync_req->PostShutdownCleanup();
848       }
849     }
850   }
851 
Start()852   void Start() {
853     if (!sync_requests_.empty()) {
854       for (const auto& value : sync_requests_) {
855         value->SetupRequest();
856         value->Request(server_->c_server(), server_cq_->cq());
857       }
858 
859       Initialize();  // ThreadManager's Initialize()
860     }
861   }
862 
863  private:
864   Server* server_;
865   grpc::CompletionQueue* server_cq_;
866   int cq_timeout_msec_;
867   std::vector<std::unique_ptr<SyncRequest>> sync_requests_;
868   std::unique_ptr<grpc::internal::RpcServiceMethod> unknown_method_;
869   std::shared_ptr<Server::GlobalCallbacks> global_callbacks_;
870 };
871 
872 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)873 Server::Server(
874     grpc::ChannelArguments* args,
875     std::shared_ptr<std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>>
876         sync_server_cqs,
877     int min_pollers, int max_pollers, int sync_cq_timeout_msec,
878     std::vector<std::shared_ptr<grpc::internal::ExternalConnectionAcceptorImpl>>
879         acceptors,
880     grpc_server_config_fetcher* server_config_fetcher,
881     grpc_resource_quota* server_rq,
882     std::vector<
883         std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>>
884         interceptor_creators)
885     : acceptors_(std::move(acceptors)),
886       interceptor_creators_(std::move(interceptor_creators)),
887       max_receive_message_size_(INT_MIN),
888       sync_server_cqs_(std::move(sync_server_cqs)),
889       started_(false),
890       shutdown_(false),
891       shutdown_notified_(false),
892       server_(nullptr),
893       server_initializer_(new ServerInitializer(this)),
894       health_check_service_disabled_(false) {
895   g_gli_initializer.summon();
896   gpr_once_init(&grpc::g_once_init_callbacks, grpc::InitGlobalCallbacks);
897   global_callbacks_ = grpc::g_callbacks;
898   global_callbacks_->UpdateArguments(args);
899 
900   if (sync_server_cqs_ != nullptr) {
901     bool default_rq_created = false;
902     if (server_rq == nullptr) {
903       server_rq = grpc_resource_quota_create("SyncServer-default-rq");
904       grpc_resource_quota_set_max_threads(server_rq,
905                                           DEFAULT_MAX_SYNC_SERVER_THREADS);
906       default_rq_created = true;
907     }
908 
909     for (const auto& it : *sync_server_cqs_) {
910       sync_req_mgrs_.emplace_back(new SyncRequestThreadManager(
911           this, it.get(), global_callbacks_, server_rq, min_pollers,
912           max_pollers, sync_cq_timeout_msec));
913     }
914 
915     if (default_rq_created) {
916       grpc_resource_quota_unref(server_rq);
917     }
918   }
919 
920   for (auto& acceptor : acceptors_) {
921     acceptor->SetToChannelArgs(args);
922   }
923 
924   grpc_channel_args channel_args;
925   args->SetChannelArgs(&channel_args);
926 
927   for (size_t i = 0; i < channel_args.num_args; i++) {
928     if (0 == strcmp(channel_args.args[i].key,
929                     grpc::kHealthCheckServiceInterfaceArg)) {
930       if (channel_args.args[i].value.pointer.p == nullptr) {
931         health_check_service_disabled_ = true;
932       } else {
933         health_check_service_.reset(
934             static_cast<grpc::HealthCheckServiceInterface*>(
935                 channel_args.args[i].value.pointer.p));
936       }
937     }
938     if (0 ==
939         strcmp(channel_args.args[i].key, GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH)) {
940       max_receive_message_size_ = channel_args.args[i].value.integer;
941     }
942   }
943   server_ = grpc_server_create(&channel_args, nullptr);
944   grpc_server_set_config_fetcher(server_, server_config_fetcher);
945 }
946 
~Server()947 Server::~Server() {
948   {
949     grpc::internal::ReleasableMutexLock lock(&mu_);
950     if (started_ && !shutdown_) {
951       lock.Unlock();
952       Shutdown();
953     } else if (!started_) {
954       // Shutdown the completion queues
955       for (const auto& value : sync_req_mgrs_) {
956         value->Shutdown();
957       }
958       if (callback_cq_ != nullptr) {
959         callback_cq_->Shutdown();
960         callback_cq_ = nullptr;
961       }
962     }
963   }
964   // Destroy health check service before we destroy the C server so that
965   // it does not call grpc_server_request_registered_call() after the C
966   // server has been destroyed.
967   health_check_service_.reset();
968   grpc_server_destroy(server_);
969 }
970 
SetGlobalCallbacks(GlobalCallbacks * callbacks)971 void Server::SetGlobalCallbacks(GlobalCallbacks* callbacks) {
972   GPR_ASSERT(!grpc::g_callbacks);
973   GPR_ASSERT(callbacks);
974   grpc::g_callbacks.reset(callbacks);
975 }
976 
c_server()977 grpc_server* Server::c_server() { return server_; }
978 
InProcessChannel(const grpc::ChannelArguments & args)979 std::shared_ptr<grpc::Channel> Server::InProcessChannel(
980     const grpc::ChannelArguments& args) {
981   grpc_channel_args channel_args = args.c_channel_args();
982   return grpc::CreateChannelInternal(
983       "inproc", grpc_inproc_channel_create(server_, &channel_args, nullptr),
984       std::vector<std::unique_ptr<
985           grpc::experimental::ClientInterceptorFactoryInterface>>());
986 }
987 
988 std::shared_ptr<grpc::Channel>
InProcessChannelWithInterceptors(const grpc::ChannelArguments & args,std::vector<std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>> interceptor_creators)989 Server::experimental_type::InProcessChannelWithInterceptors(
990     const grpc::ChannelArguments& args,
991     std::vector<
992         std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
993         interceptor_creators) {
994   grpc_channel_args channel_args = args.c_channel_args();
995   return grpc::CreateChannelInternal(
996       "inproc",
997       grpc_inproc_channel_create(server_->server_, &channel_args, nullptr),
998       std::move(interceptor_creators));
999 }
1000 
PayloadHandlingForMethod(grpc::internal::RpcServiceMethod * method)1001 static grpc_server_register_method_payload_handling PayloadHandlingForMethod(
1002     grpc::internal::RpcServiceMethod* method) {
1003   switch (method->method_type()) {
1004     case grpc::internal::RpcMethod::NORMAL_RPC:
1005     case grpc::internal::RpcMethod::SERVER_STREAMING:
1006       return GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER;
1007     case grpc::internal::RpcMethod::CLIENT_STREAMING:
1008     case grpc::internal::RpcMethod::BIDI_STREAMING:
1009       return GRPC_SRM_PAYLOAD_NONE;
1010   }
1011   GPR_UNREACHABLE_CODE(return GRPC_SRM_PAYLOAD_NONE;);
1012 }
1013 
RegisterService(const std::string * addr,grpc::Service * service)1014 bool Server::RegisterService(const std::string* addr, grpc::Service* service) {
1015   bool has_async_methods = service->has_async_methods();
1016   if (has_async_methods) {
1017     GPR_ASSERT(service->server_ == nullptr &&
1018                "Can only register an asynchronous service against one server.");
1019     service->server_ = this;
1020   }
1021 
1022   const char* method_name = nullptr;
1023 
1024   for (const auto& method : service->methods_) {
1025     if (method == nullptr) {  // Handled by generic service if any.
1026       continue;
1027     }
1028 
1029     void* method_registration_tag = grpc_server_register_method(
1030         server_, method->name(), addr ? addr->c_str() : nullptr,
1031         PayloadHandlingForMethod(method.get()), 0);
1032     if (method_registration_tag == nullptr) {
1033       gpr_log(GPR_DEBUG, "Attempt to register %s multiple times",
1034               method->name());
1035       return false;
1036     }
1037 
1038     if (method->handler() == nullptr) {  // Async method without handler
1039       method->set_server_tag(method_registration_tag);
1040     } else if (method->api_type() ==
1041                grpc::internal::RpcServiceMethod::ApiType::SYNC) {
1042       for (const auto& value : sync_req_mgrs_) {
1043         value->AddSyncMethod(method.get(), method_registration_tag);
1044       }
1045     } else {
1046       has_callback_methods_ = true;
1047       grpc::internal::RpcServiceMethod* method_value = method.get();
1048       grpc::CompletionQueue* cq = CallbackCQ();
1049       server_->core_server->SetRegisteredMethodAllocator(
1050           cq->cq(), method_registration_tag, [this, cq, method_value] {
1051             grpc_core::Server::RegisteredCallAllocation result;
1052             new CallbackRequest<grpc::CallbackServerContext>(this, method_value,
1053                                                              cq, &result);
1054             return result;
1055           });
1056     }
1057 
1058     method_name = method->name();
1059   }
1060 
1061   // Parse service name.
1062   if (method_name != nullptr) {
1063     std::stringstream ss(method_name);
1064     std::string service_name;
1065     if (std::getline(ss, service_name, '/') &&
1066         std::getline(ss, service_name, '/')) {
1067       services_.push_back(service_name);
1068     }
1069   }
1070   return true;
1071 }
1072 
RegisterAsyncGenericService(grpc::AsyncGenericService * service)1073 void Server::RegisterAsyncGenericService(grpc::AsyncGenericService* service) {
1074   GPR_ASSERT(service->server_ == nullptr &&
1075              "Can only register an async generic service against one server.");
1076   service->server_ = this;
1077   has_async_generic_service_ = true;
1078 }
1079 
RegisterCallbackGenericService(grpc::CallbackGenericService * service)1080 void Server::RegisterCallbackGenericService(
1081     grpc::CallbackGenericService* service) {
1082   GPR_ASSERT(
1083       service->server_ == nullptr &&
1084       "Can only register a callback generic service against one server.");
1085   service->server_ = this;
1086   has_callback_generic_service_ = true;
1087   generic_handler_.reset(service->Handler());
1088 
1089   grpc::CompletionQueue* cq = CallbackCQ();
1090   server_->core_server->SetBatchMethodAllocator(cq->cq(), [this, cq] {
1091     grpc_core::Server::BatchCallAllocation result;
1092     new CallbackRequest<grpc::GenericCallbackServerContext>(this, cq, &result);
1093     return result;
1094   });
1095 }
1096 
AddListeningPort(const std::string & addr,grpc::ServerCredentials * creds)1097 int Server::AddListeningPort(const std::string& addr,
1098                              grpc::ServerCredentials* creds) {
1099   GPR_ASSERT(!started_);
1100   int port = creds->AddPortToServer(addr, server_);
1101   global_callbacks_->AddPort(this, addr, creds, port);
1102   return port;
1103 }
1104 
Ref()1105 void Server::Ref() {
1106   shutdown_refs_outstanding_.fetch_add(1, std::memory_order_relaxed);
1107 }
1108 
UnrefWithPossibleNotify()1109 void Server::UnrefWithPossibleNotify() {
1110   if (GPR_UNLIKELY(shutdown_refs_outstanding_.fetch_sub(
1111                        1, std::memory_order_acq_rel) == 1)) {
1112     // No refs outstanding means that shutdown has been initiated and no more
1113     // callback requests are outstanding.
1114     grpc::internal::MutexLock lock(&mu_);
1115     GPR_ASSERT(shutdown_);
1116     shutdown_done_ = true;
1117     shutdown_done_cv_.Signal();
1118   }
1119 }
1120 
UnrefAndWaitLocked()1121 void Server::UnrefAndWaitLocked() {
1122   if (GPR_UNLIKELY(shutdown_refs_outstanding_.fetch_sub(
1123                        1, std::memory_order_acq_rel) == 1)) {
1124     shutdown_done_ = true;
1125     return;  // no need to wait on CV since done condition already set
1126   }
1127   shutdown_done_cv_.WaitUntil(&mu_, [this] { return shutdown_done_; });
1128 }
1129 
Start(grpc::ServerCompletionQueue ** cqs,size_t num_cqs)1130 void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) {
1131   GPR_ASSERT(!started_);
1132   global_callbacks_->PreServerStart(this);
1133   started_ = true;
1134 
1135   // Only create default health check service when user did not provide an
1136   // explicit one.
1137   grpc::ServerCompletionQueue* health_check_cq = nullptr;
1138   grpc::DefaultHealthCheckService::HealthCheckServiceImpl*
1139       default_health_check_service_impl = nullptr;
1140   if (health_check_service_ == nullptr && !health_check_service_disabled_ &&
1141       grpc::DefaultHealthCheckServiceEnabled()) {
1142     auto* default_hc_service = new grpc::DefaultHealthCheckService;
1143     health_check_service_.reset(default_hc_service);
1144     // We create a non-polling CQ to avoid impacting application
1145     // performance.  This ensures that we don't introduce thread hops
1146     // for application requests that wind up on this CQ, which is polled
1147     // in its own thread.
1148     health_check_cq = new grpc::ServerCompletionQueue(
1149         GRPC_CQ_NEXT, GRPC_CQ_NON_POLLING, nullptr);
1150     grpc_server_register_completion_queue(server_, health_check_cq->cq(),
1151                                           nullptr);
1152     default_health_check_service_impl =
1153         default_hc_service->GetHealthCheckService(
1154             std::unique_ptr<grpc::ServerCompletionQueue>(health_check_cq));
1155     RegisterService(nullptr, default_health_check_service_impl);
1156   }
1157 
1158   for (auto& acceptor : acceptors_) {
1159     acceptor->GetCredentials()->AddPortToServer(acceptor->name(), server_);
1160   }
1161 
1162   // If this server uses callback methods, then create a callback generic
1163   // service to handle any unimplemented methods using the default reactor
1164   // creator
1165   if (has_callback_methods_ && !has_callback_generic_service_) {
1166     unimplemented_service_ = absl::make_unique<grpc::CallbackGenericService>();
1167     RegisterCallbackGenericService(unimplemented_service_.get());
1168   }
1169 
1170 #ifndef NDEBUG
1171   for (size_t i = 0; i < num_cqs; i++) {
1172     cq_list_.push_back(cqs[i]);
1173   }
1174 #endif
1175 
1176   grpc_server_start(server_);
1177 
1178   if (!has_async_generic_service_ && !has_callback_generic_service_) {
1179     for (const auto& value : sync_req_mgrs_) {
1180       value->AddUnknownSyncMethod();
1181     }
1182 
1183     for (size_t i = 0; i < num_cqs; i++) {
1184       if (cqs[i]->IsFrequentlyPolled()) {
1185         new UnimplementedAsyncRequest(this, cqs[i]);
1186       }
1187     }
1188     if (health_check_cq != nullptr) {
1189       new UnimplementedAsyncRequest(this, health_check_cq);
1190     }
1191   }
1192 
1193   // If this server has any support for synchronous methods (has any sync
1194   // server CQs), make sure that we have a ResourceExhausted handler
1195   // to deal with the case of thread exhaustion
1196   if (sync_server_cqs_ != nullptr && !sync_server_cqs_->empty()) {
1197     resource_exhausted_handler_ =
1198         absl::make_unique<grpc::internal::ResourceExhaustedHandler>();
1199   }
1200 
1201   for (const auto& value : sync_req_mgrs_) {
1202     value->Start();
1203   }
1204 
1205   if (default_health_check_service_impl != nullptr) {
1206     default_health_check_service_impl->StartServingThread();
1207   }
1208 
1209   for (auto& acceptor : acceptors_) {
1210     acceptor->Start();
1211   }
1212 }
1213 
ShutdownInternal(gpr_timespec deadline)1214 void Server::ShutdownInternal(gpr_timespec deadline) {
1215   grpc::internal::MutexLock lock(&mu_);
1216   if (shutdown_) {
1217     return;
1218   }
1219 
1220   shutdown_ = true;
1221 
1222   for (auto& acceptor : acceptors_) {
1223     acceptor->Shutdown();
1224   }
1225 
1226   /// The completion queue to use for server shutdown completion notification
1227   grpc::CompletionQueue shutdown_cq;
1228   grpc::ShutdownTag shutdown_tag;  // Dummy shutdown tag
1229   grpc_server_shutdown_and_notify(server_, shutdown_cq.cq(), &shutdown_tag);
1230 
1231   shutdown_cq.Shutdown();
1232 
1233   void* tag;
1234   bool ok;
1235   grpc::CompletionQueue::NextStatus status =
1236       shutdown_cq.AsyncNext(&tag, &ok, deadline);
1237 
1238   // If this timed out, it means we are done with the grace period for a clean
1239   // shutdown. We should force a shutdown now by cancelling all inflight calls
1240   if (status == grpc::CompletionQueue::NextStatus::TIMEOUT) {
1241     grpc_server_cancel_all_calls(server_);
1242   }
1243   // Else in case of SHUTDOWN or GOT_EVENT, it means that the server has
1244   // successfully shutdown
1245 
1246   // Shutdown all ThreadManagers. This will try to gracefully stop all the
1247   // threads in the ThreadManagers (once they process any inflight requests)
1248   for (const auto& value : sync_req_mgrs_) {
1249     value->Shutdown();  // ThreadManager's Shutdown()
1250   }
1251 
1252   // Wait for threads in all ThreadManagers to terminate
1253   for (const auto& value : sync_req_mgrs_) {
1254     value->Wait();
1255   }
1256 
1257   // Drop the shutdown ref and wait for all other refs to drop as well.
1258   UnrefAndWaitLocked();
1259 
1260   // Shutdown the callback CQ. The CQ is owned by its own shutdown tag, so it
1261   // will delete itself at true shutdown.
1262   if (callback_cq_ != nullptr) {
1263     callback_cq_->Shutdown();
1264     callback_cq_ = nullptr;
1265   }
1266 
1267   // Drain the shutdown queue (if the previous call to AsyncNext() timed out
1268   // and we didn't remove the tag from the queue yet)
1269   while (shutdown_cq.Next(&tag, &ok)) {
1270     // Nothing to be done here. Just ignore ok and tag values
1271   }
1272 
1273   shutdown_notified_ = true;
1274   shutdown_cv_.Broadcast();
1275 
1276 #ifndef NDEBUG
1277   // Unregister this server with the CQs passed into it by the user so that
1278   // those can be checked for properly-ordered shutdown.
1279   for (auto* cq : cq_list_) {
1280     cq->UnregisterServer(this);
1281   }
1282   cq_list_.clear();
1283 #endif
1284 }
1285 
Wait()1286 void Server::Wait() {
1287   grpc::internal::MutexLock lock(&mu_);
1288   while (started_ && !shutdown_notified_) {
1289     shutdown_cv_.Wait(&mu_);
1290   }
1291 }
1292 
PerformOpsOnCall(grpc::internal::CallOpSetInterface * ops,grpc::internal::Call * call)1293 void Server::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops,
1294                               grpc::internal::Call* call) {
1295   ops->FillOps(call);
1296 }
1297 
FinalizeResult(void ** tag,bool * status)1298 bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag,
1299                                                        bool* status) {
1300   if (GenericAsyncRequest::FinalizeResult(tag, status)) {
1301     // We either had no interceptors run or we are done intercepting
1302     if (*status) {
1303       // Create a new request/response pair using the server and CQ values
1304       // stored in this object's base class.
1305       new UnimplementedAsyncRequest(server_, notification_cq_);
1306       new UnimplementedAsyncResponse(this);
1307     } else {
1308       delete this;
1309     }
1310   } else {
1311     // The tag was swallowed due to interception. We will see it again.
1312   }
1313   return false;
1314 }
1315 
UnimplementedAsyncResponse(UnimplementedAsyncRequest * request)1316 Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse(
1317     UnimplementedAsyncRequest* request)
1318     : request_(request) {
1319   grpc::Status status(grpc::StatusCode::UNIMPLEMENTED, "");
1320   grpc::internal::UnknownMethodHandler::FillOps(request_->context(), this);
1321   request_->stream()->call_.PerformOps(this);
1322 }
1323 
initializer()1324 grpc::ServerInitializer* Server::initializer() {
1325   return server_initializer_.get();
1326 }
1327 
CallbackCQ()1328 grpc::CompletionQueue* Server::CallbackCQ() {
1329   // TODO(vjpai): Consider using a single global CQ for the default CQ
1330   // if there is no explicit per-server CQ registered
1331   grpc::internal::MutexLock l(&mu_);
1332   if (callback_cq_ != nullptr) {
1333     return callback_cq_;
1334   }
1335   auto* shutdown_callback = new grpc::ShutdownCallback;
1336   callback_cq_ = new grpc::CompletionQueue(grpc_completion_queue_attributes{
1337       GRPC_CQ_CURRENT_VERSION, GRPC_CQ_CALLBACK, GRPC_CQ_DEFAULT_POLLING,
1338       shutdown_callback});
1339 
1340   // Transfer ownership of the new cq to its own shutdown callback
1341   shutdown_callback->TakeCQ(callback_cq_);
1342 
1343   return callback_cq_;
1344 }
1345 
1346 }  // namespace grpc
1347