GRPC C++  1.26.0
server_impl.h
Go to the documentation of this file.
1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 #ifndef GRPCPP_SERVER_IMPL_H
20 #define GRPCPP_SERVER_IMPL_H
21 
22 #include <list>
23 #include <memory>
24 #include <vector>
25 
26 #include <grpc/compression.h>
27 #include <grpc/support/atm.h>
28 #include <grpcpp/channel_impl.h>
31 #include <grpcpp/impl/call.h>
39 #include <grpcpp/support/config.h>
40 #include <grpcpp/support/status.h>
41 
42 struct grpc_server;
43 
44 namespace grpc {
45 class AsyncGenericService;
46 
47 namespace internal {
48 class ExternalConnectionAcceptorImpl;
49 } // namespace internal
50 
51 } // namespace grpc
52 
53 namespace grpc_impl {
55 class ServerContext;
56 class ServerInitializer;
57 
63  public:
64  ~Server();
65 
70  void Wait() override;
71 
79  public:
80  virtual ~GlobalCallbacks() {}
82  virtual void UpdateArguments(ChannelArguments* /*args*/) {}
84  virtual void PreSynchronousRequest(grpc_impl::ServerContext* context) = 0;
86  virtual void PostSynchronousRequest(grpc_impl::ServerContext* context) = 0;
88  virtual void PreServerStart(Server* /*server*/) {}
90  virtual void AddPort(Server* /*server*/, const grpc::string& /*addr*/,
91  grpc::ServerCredentials* /*creds*/, int /*port*/) {}
92  };
98  static void SetGlobalCallbacks(GlobalCallbacks* callbacks);
99 
103 
106  return health_check_service_.get();
107  }
108 
110  std::shared_ptr<Channel> InProcessChannel(const ChannelArguments& args);
111 
116  public:
117  explicit experimental_type(Server* server) : server_(server) {}
118 
121  std::shared_ptr<Channel> InProcessChannelWithInterceptors(
122  const ChannelArguments& args,
123  std::vector<std::unique_ptr<
125  interceptor_creators);
126 
127  private:
128  Server* server_;
129  };
130 
135 
136  protected:
139  bool RegisterService(const grpc::string* host,
140  grpc::Service* service) override;
141 
155  int AddListeningPort(const grpc::string& addr,
156  grpc::ServerCredentials* creds) override;
157 
183  Server(int max_message_size, ChannelArguments* args,
184  std::shared_ptr<std::vector<std::unique_ptr<ServerCompletionQueue>>>
185  sync_server_cqs,
186  int min_pollers, int max_pollers, int sync_cq_timeout_msec,
187  std::vector<
188  std::shared_ptr<grpc::internal::ExternalConnectionAcceptorImpl>>
189  acceptors,
190  grpc_resource_quota* server_rq = nullptr,
191  std::vector<std::unique_ptr<
193  interceptor_creators = std::vector<std::unique_ptr<
195 
202  void Start(ServerCompletionQueue** cqs, size_t num_cqs) override;
203 
204  grpc_server* server() override { return server_; }
205 
206  protected:
209  std::unique_ptr<grpc::HealthCheckServiceInterface> service) {
210  health_check_service_ = std::move(service);
211  }
212 
215  return health_check_service_disabled_;
216  }
217 
218  private:
219  std::vector<
220  std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>>*
221  interceptor_creators() override {
222  return &interceptor_creators_;
223  }
224 
228 
229  class SyncRequest;
230  class CallbackRequestBase;
231  template <class ServerContextType>
232  class CallbackRequest;
235 
241 
244  void RegisterAsyncGenericService(grpc::AsyncGenericService* service) override;
245 
250  class experimental_registration_type final
252  public:
253  explicit experimental_registration_type(Server* server) : server_(server) {}
254  void RegisterCallbackGenericService(
255  grpc::experimental::CallbackGenericService* service) override {
256  server_->RegisterCallbackGenericService(service);
257  }
258 
259  private:
260  Server* server_;
261  };
262 
264  void RegisterCallbackGenericService(
266 
270  experimental_registration_interface* experimental_registration() override {
271  return &experimental_registration_;
272  }
273 
274  void PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops,
275  grpc::internal::Call* call) override;
276 
277  void ShutdownInternal(gpr_timespec deadline) override;
278 
279  int max_receive_message_size() const override {
280  return max_receive_message_size_;
281  }
282 
283  CompletionQueue* CallbackCQ() override;
284 
285  grpc_impl::ServerInitializer* initializer();
286 
287  std::vector<std::shared_ptr<grpc::internal::ExternalConnectionAcceptorImpl>>
288  acceptors_;
289 
290  // A vector of interceptor factory objects.
291  // This should be destroyed after health_check_service_ and this requirement
292  // is satisfied by declaring interceptor_creators_ before
293  // health_check_service_. (C++ mandates that member objects be destroyed in
294  // the reverse order of initialization.)
295  std::vector<
296  std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>>
297  interceptor_creators_;
298 
299  const int max_receive_message_size_;
300 
304  std::shared_ptr<std::vector<std::unique_ptr<ServerCompletionQueue>>>
305  sync_server_cqs_;
306 
309  std::vector<std::unique_ptr<SyncRequestThreadManager>> sync_req_mgrs_;
310 
311  // Outstanding unmatched callback requests, indexed by method.
312  // NOTE: Using a gpr_atm rather than atomic_int because atomic_int isn't
313  // copyable or movable and thus will cause compilation errors. We
314  // actually only want to extend the vector before the threaded use
315  // starts, but this is still a limitation.
316  std::vector<gpr_atm> callback_unmatched_reqs_count_;
317 
318  // List of callback requests to start when server actually starts.
319  std::list<CallbackRequestBase*> callback_reqs_to_start_;
320 
321  // For registering experimental callback generic service; remove when that
322  // method longer experimental
323  experimental_registration_type experimental_registration_{this};
324 
325  // Server status
327  bool started_;
328  bool shutdown_;
329  bool shutdown_notified_; // Was notify called on the shutdown_cv_
330 
331  grpc::internal::CondVar shutdown_cv_;
332 
333  // It is ok (but not required) to nest callback_reqs_mu_ under mu_ .
334  // Incrementing callback_reqs_outstanding_ is ok without a lock but it must be
335  // decremented under the lock in case it is the last request and enables the
336  // server shutdown. The increment is performance-critical since it happens
337  // during periods of increasing load; the decrement happens only when memory
338  // is maxed out, during server shutdown, or (possibly in a future version)
339  // during decreasing load, so it is less performance-critical.
340  grpc::internal::Mutex callback_reqs_mu_;
341  grpc::internal::CondVar callback_reqs_done_cv_;
342  std::atomic<intptr_t> callback_reqs_outstanding_{0};
343 
344  std::shared_ptr<GlobalCallbacks> global_callbacks_;
345 
346  std::vector<grpc::string> services_;
347  bool has_async_generic_service_{false};
348  bool has_callback_generic_service_{false};
349 
350  // Pointer to the wrapped grpc_server.
351  grpc_server* server_;
352 
353  std::unique_ptr<grpc_impl::ServerInitializer> server_initializer_;
354 
355  std::unique_ptr<grpc::HealthCheckServiceInterface> health_check_service_;
356  bool health_check_service_disabled_;
357 
358  // When appropriate, use a default callback generic service to handle
359  // unimplemented methods
360  std::unique_ptr<grpc::experimental::CallbackGenericService>
361  unimplemented_service_;
362 
363  // A special handler for resource exhausted in sync case
364  std::unique_ptr<grpc::internal::MethodHandler> resource_exhausted_handler_;
365 
366  // Handler for callback generic service, if any
367  std::unique_ptr<grpc::internal::MethodHandler> generic_handler_;
368 
369  // callback_cq_ references the callbackable completion queue associated
370  // with this server (if any). It is set on the first call to CallbackCQ().
371  // It is _not owned_ by the server; ownership belongs with its internal
372  // shutdown callback tag (invoked when the CQ is fully shutdown).
373  // It is protected by mu_
374  CompletionQueue* callback_cq_ = nullptr;
375 };
376 
377 } // namespace grpc_impl
378 
379 #endif // GRPCPP_SERVER_IMPL_H
std::shared_ptr< Channel > InProcessChannel(const ChannelArguments &args)
Establish a channel for in-process communication.
Definition: server_cc.cc:1061
virtual void PreServerStart(Server *)
Called before server is started.
Definition: server_impl.h:88
grpc::HealthCheckServiceInterface * GetHealthCheckService() const
Returns the health check service.
Definition: server_impl.h:105
std::string string
Definition: config.h:35
Use private inheritance rather than composition only to establish order of construction, since the public base class should be constructed after the elements belonging to the private base class are constructed.
Definition: server_cc.cc:294
bool health_check_service_disabled() const
NOTE: This method is not part of the public API for this class.
Definition: server_impl.h:214
Represents a gRPC server.
Definition: server_impl.h:62
NOTE: class experimental_registration_interface is not part of the public API of this class TODO(vjpa...
Definition: server_interface.h:130
Server(int max_message_size, ChannelArguments *args, std::shared_ptr< std::vector< std::unique_ptr< ServerCompletionQueue >>> sync_server_cqs, int min_pollers, int max_pollers, int sync_cq_timeout_msec, std::vector< std::shared_ptr< grpc::internal::ExternalConnectionAcceptorImpl >> acceptors, grpc_resource_quota *server_rq=nullptr, std::vector< std::unique_ptr< grpc::experimental::ServerInterceptorFactoryInterface >> interceptor_creators=std::vector< std::unique_ptr< grpc::experimental::ServerInterceptorFactoryInterface >>())
NOTE: This is NOT a public API.
Definition: server_cc.cc:955
grpc_server * c_server()
Returns a raw pointer to the underlying grpc_server instance.
Definition: server_cc.cc:1059
Desriptor of an RPC service and its various RPC methods.
Definition: service_type.h:60
Global callbacks are a set of hooks that are called when server events occur.
Definition: server_impl.h:78
struct grpc_server grpc_server
A server listens to some port and responds to request calls.
Definition: grpc_types.h:65
virtual void PreSynchronousRequest(grpc_impl::ServerContext *context)=0
Called before application callback for each synchronous server request.
Definition: async_generic_service.h:75
void Wait() override
Block until the server shuts down.
Definition: server_cc.cc:1352
Classes that require gRPC to be initialized should inherit from this class.
Definition: grpc_library.h:38
NOTE: class experimental_type is not part of the public API of this class.
Definition: server_impl.h:115
::grpc_impl::ServerContext ServerContext
Definition: server_context.h:26
A ServerContext or CallbackServerContext allows the code implementing a service handler to: ...
Definition: server_context_impl.h:488
Definition: server_cc.cc:537
void set_health_check_service(std::unique_ptr< grpc::HealthCheckServiceInterface > service)
NOTE: This method is not part of the public API for this class.
Definition: server_impl.h:208
UnimplementedAsyncResponse should not post user-visible completions to the C++ completion queue...
Definition: server_cc.cc:316
void Start(ServerCompletionQueue **cqs, size_t num_cqs) override
Start the server.
Definition: server_cc.cc:1190
std::shared_ptr< Channel > InProcessChannelWithInterceptors(const ChannelArguments &args, std::vector< std::unique_ptr< grpc::experimental::ClientInterceptorFactoryInterface >> interceptor_creators)
Establish a channel for in-process communication with client interceptors.
Definition: server_cc.cc:1071
static void SetGlobalCallbacks(GlobalCallbacks *callbacks)
Set the global callback object.
Definition: server_cc.cc:1053
::grpc_impl::CompletionQueue CompletionQueue
Definition: completion_queue.h:26
The gRPC server uses this interface to expose the health checking service without depending on protob...
Definition: health_check_service_interface_impl.h:28
Definition: sync.h:47
This header provides an object that reads bytes directly from a grpc::ByteBuffer, via the ZeroCopyInp...
Definition: alarm.h:24
Options for channel creation.
Definition: channel_arguments_impl.h:43
Definition: server_interface.h:59
::grpc_impl::HealthCheckServiceInterface HealthCheckServiceInterface
Definition: health_check_service_interface.h:29
An Alarm posts the user-provided tag to its associated completion queue or invokes the user-provided ...
Definition: alarm_impl.h:33
CallbackGenericService is the base class for generic services implemented using the callback API and ...
Definition: async_generic_service.h:121
Wrapper around grpc_server_credentials, a way to authenticate a server.
Definition: server_credentials_impl.h:40
An abstract collection of call ops, used to generate the grpc_call_op structure to pass down to the l...
Definition: call_op_set_interface.h:34
int AddListeningPort(const grpc::string &addr, grpc::ServerCredentials *creds) override
Try binding the server to the given addr endpoint (port, and optionally including IP address to bind ...
Definition: server_cc.cc:1182
virtual void PostSynchronousRequest(grpc_impl::ServerContext *context)=0
Called after application callback for each synchronous server request.
experimental_type(Server *server)
Definition: server_impl.h:117
Definition: server_cc.cc:340
struct grpc_resource_quota grpc_resource_quota
Definition: grpc_types.h:677
experimental_type experimental()
NOTE: The function experimental() is not stable public API.
Definition: server_impl.h:134
Analogous to struct timespec.
Definition: gpr_types.h:47
::grpc_impl::ServerInitializer ServerInitializer
Definition: server_initializer.h:26
A specific type of completion queue used by the processing of notifications by servers.
Definition: completion_queue_impl.h:389
virtual void AddPort(Server *, const grpc::string &, grpc::ServerCredentials *, int)
Called after a server port is added.
Definition: server_impl.h:90
~Server()
Definition: server_cc.cc:1025
bool RegisterService(const grpc::string *host, grpc::Service *service) override
Register a service.
Definition: server_cc.cc:1096
A builder class for the creation and startup of grpc::Server instances.
Definition: server_builder_impl.h:86
virtual void UpdateArguments(ChannelArguments *)
Called before server is created.
Definition: server_impl.h:82
virtual ~GlobalCallbacks()
Definition: server_impl.h:80
grpc_server * server() override
Definition: server_impl.h:204
Definition: server_initializer_impl.h:34
Straightforward wrapping of the C call object.
Definition: call.h:38
Definition: sync.h:118