GRPC C++  1.36.1
server.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_H
20 #define GRPCPP_SERVER_H
21 
22 #include <list>
23 #include <memory>
24 #include <vector>
25 
27 
28 #include <grpc/compression.h>
29 #include <grpc/support/atm.h>
30 #include <grpcpp/channel.h>
33 #include <grpcpp/impl/call.h>
41 #include <grpcpp/support/config.h>
42 #include <grpcpp/support/status.h>
43 
44 struct grpc_server;
45 
46 namespace grpc {
47 class AsyncGenericService;
48 class ServerContext;
49 class ServerInitializer;
50 
51 namespace internal {
52 class ExternalConnectionAcceptorImpl;
53 } // namespace internal
54 
59 class Server : public ServerInterface, private GrpcLibraryCodegen {
60  public:
61  ~Server() override;
62 
67  void Wait() override;
68 
76  public:
77  virtual ~GlobalCallbacks() {}
79  virtual void UpdateArguments(ChannelArguments* /*args*/) {}
81  virtual void PreSynchronousRequest(ServerContext* context) = 0;
83  virtual void PostSynchronousRequest(ServerContext* context) = 0;
85  virtual void PreServerStart(Server* /*server*/) {}
87  virtual void AddPort(Server* /*server*/, const std::string& /*addr*/,
88  ServerCredentials* /*creds*/, int /*port*/) {}
89  };
95  static void SetGlobalCallbacks(GlobalCallbacks* callbacks);
96 
100 
103  return health_check_service_.get();
104  }
105 
107  std::shared_ptr<Channel> InProcessChannel(const ChannelArguments& args);
108 
113  public:
114  explicit experimental_type(Server* server) : server_(server) {}
115 
118  std::shared_ptr<Channel> InProcessChannelWithInterceptors(
119  const ChannelArguments& args,
120  std::vector<
121  std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
122  interceptor_creators);
123 
124  private:
125  Server* server_;
126  };
127 
132 
133  protected:
136  bool RegisterService(const std::string* addr, Service* service) override;
137 
151  int AddListeningPort(const std::string& addr,
152  ServerCredentials* creds) override;
153 
176  Server(ChannelArguments* args,
177  std::shared_ptr<std::vector<std::unique_ptr<ServerCompletionQueue>>>
178  sync_server_cqs,
179  int min_pollers, int max_pollers, int sync_cq_timeout_msec,
180  std::vector<std::shared_ptr<internal::ExternalConnectionAcceptorImpl>>
181  acceptors,
182  grpc_server_config_fetcher* server_config_fetcher = nullptr,
183  grpc_resource_quota* server_rq = nullptr,
184  std::vector<
185  std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
186  interceptor_creators = std::vector<std::unique_ptr<
188 
195  void Start(ServerCompletionQueue** cqs, size_t num_cqs) override;
196 
197  grpc_server* server() override { return server_; }
198 
199  protected:
202  std::unique_ptr<HealthCheckServiceInterface> service) {
203  health_check_service_ = std::move(service);
204  }
205 
206  ContextAllocator* context_allocator() { return context_allocator_.get(); }
207 
210  return health_check_service_disabled_;
211  }
212 
213  private:
214  std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>*
215  interceptor_creators() override {
216  return &interceptor_creators_;
217  }
218 
219  friend class AsyncGenericService;
220  friend class ServerBuilder;
221  friend class ServerInitializer;
222 
223  class SyncRequest;
224  class CallbackRequestBase;
225  template <class ServerContextType>
226  class CallbackRequest;
227  class UnimplementedAsyncRequest;
228  class UnimplementedAsyncResponse;
229 
234  class SyncRequestThreadManager;
235 
238  void RegisterAsyncGenericService(AsyncGenericService* service) override;
239 
240 #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
241  void RegisterCallbackGenericService(CallbackGenericService* service) override;
245 
246  void RegisterContextAllocator(
247  std::unique_ptr<ContextAllocator> context_allocator) {
248  context_allocator_ = std::move(context_allocator);
249  }
250 
251 #else
252  class experimental_registration_type final
257  : public experimental_registration_interface {
258  public:
259  explicit experimental_registration_type(Server* server) : server_(server) {}
260  void RegisterCallbackGenericService(
261  experimental::CallbackGenericService* service) override {
262  server_->RegisterCallbackGenericService(service);
263  }
264 
265  void RegisterContextAllocator(
266  std::unique_ptr<ContextAllocator> context_allocator) override {
267  server_->context_allocator_ = std::move(context_allocator);
268  }
269 
270  private:
271  Server* server_;
272  };
273 
275  void RegisterCallbackGenericService(
276  experimental::CallbackGenericService* service);
277 
281  experimental_registration_interface* experimental_registration() override {
282  return &experimental_registration_;
283  }
284 #endif
285 
286  void PerformOpsOnCall(internal::CallOpSetInterface* ops,
287  internal::Call* call) override;
288 
289  void ShutdownInternal(gpr_timespec deadline) override;
290 
291  int max_receive_message_size() const override {
292  return max_receive_message_size_;
293  }
294 
295  CompletionQueue* CallbackCQ() override;
296 
297  ServerInitializer* initializer();
298 
299  // Functions to manage the server shutdown ref count. Things that increase
300  // the ref count are the running state of the server (take a ref at start and
301  // drop it at shutdown) and each running callback RPC.
302  void Ref();
303  void UnrefWithPossibleNotify() /* LOCKS_EXCLUDED(mu_) */;
304  void UnrefAndWaitLocked() /* EXCLUSIVE_LOCKS_REQUIRED(mu_) */;
305 
306  std::vector<std::shared_ptr<internal::ExternalConnectionAcceptorImpl>>
307  acceptors_;
308 
309  // A vector of interceptor factory objects.
310  // This should be destroyed after health_check_service_ and this requirement
311  // is satisfied by declaring interceptor_creators_ before
312  // health_check_service_. (C++ mandates that member objects be destroyed in
313  // the reverse order of initialization.)
314  std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
315  interceptor_creators_;
316 
317  int max_receive_message_size_;
318 
322  std::shared_ptr<std::vector<std::unique_ptr<ServerCompletionQueue>>>
323  sync_server_cqs_;
324 
327  std::vector<std::unique_ptr<SyncRequestThreadManager>> sync_req_mgrs_;
328 
329 #ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
330  // For registering experimental callback generic service; remove when that
331  // method longer experimental
332  experimental_registration_type experimental_registration_{this};
333 #endif
334 
335  // Server status
336  internal::Mutex mu_;
337  bool started_;
338  bool shutdown_;
339  bool shutdown_notified_; // Was notify called on the shutdown_cv_
340  internal::CondVar shutdown_done_cv_;
341  bool shutdown_done_ = false;
342  std::atomic_int shutdown_refs_outstanding_{1};
343 
344  internal::CondVar shutdown_cv_;
345 
346  std::shared_ptr<GlobalCallbacks> global_callbacks_;
347 
348  std::vector<std::string> services_;
349  bool has_async_generic_service_ = false;
350  bool has_callback_generic_service_ = false;
351  bool has_callback_methods_ = false;
352 
353  // Pointer to the wrapped grpc_server.
354  grpc_server* server_;
355 
356  std::unique_ptr<ServerInitializer> server_initializer_;
357 
358  std::unique_ptr<ContextAllocator> context_allocator_;
359 
360  std::unique_ptr<HealthCheckServiceInterface> health_check_service_;
361  bool health_check_service_disabled_;
362 
363  // When appropriate, use a default callback generic service to handle
364  // unimplemented methods
365 #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
366  std::unique_ptr<CallbackGenericService> unimplemented_service_;
367 #else
368  std::unique_ptr<experimental::CallbackGenericService> unimplemented_service_;
369 #endif
370 
371  // A special handler for resource exhausted in sync case
372  std::unique_ptr<internal::MethodHandler> resource_exhausted_handler_;
373 
374  // Handler for callback generic service, if any
375  std::unique_ptr<internal::MethodHandler> generic_handler_;
376 
377  // callback_cq_ references the callbackable completion queue associated
378  // with this server (if any). It is set on the first call to CallbackCQ().
379  // It is _not owned_ by the server; ownership belongs with its internal
380  // shutdown callback tag (invoked when the CQ is fully shutdown).
381  CompletionQueue* callback_cq_ /* GUARDED_BY(mu_) */ = nullptr;
382 
383  // List of CQs passed in by user that must be Shutdown only after Server is
384  // Shutdown. Even though this is only used with NDEBUG, instantiate it in all
385  // cases since otherwise the size will be inconsistent.
386  std::vector<CompletionQueue*> cq_list_;
387 };
388 
389 } // namespace grpc
390 
391 #endif // GRPCPP_SERVER_H
grpc::GrpcLibraryCodegen
Classes that require gRPC to be initialized should inherit from this class.
Definition: grpc_library.h:38
grpc::Server::InProcessChannel
std::shared_ptr< Channel > InProcessChannel(const ChannelArguments &args)
Establish a channel for in-process communication.
compression.h
grpc::ServerContext
A ServerContext or CallbackServerContext allows the code implementing a service handler to:
Definition: server_context.h:546
grpc::Server
Represents a gRPC server.
Definition: server.h:59
grpc
An Alarm posts the user-provided tag to its associated completion queue or invokes the user-provided ...
Definition: alarm.h:33
grpc_resource_quota
struct grpc_resource_quota grpc_resource_quota
Definition: grpc_types.h:698
grpc::Server::RegisterService
bool RegisterService(const std::string *addr, Service *service) override
Register a service.
grpc::Server::health_check_service_disabled
bool health_check_service_disabled() const
NOTE: This method is not part of the public API for this class.
Definition: server.h:209
grpc::Server::context_allocator
ContextAllocator * context_allocator()
Definition: server.h:206
grpc::ServerInitializer
Definition: server_initializer.h:31
grpc::Server::GlobalCallbacks::PostSynchronousRequest
virtual void PostSynchronousRequest(ServerContext *context)=0
Called after application callback for each synchronous server request.
grpc::HealthCheckServiceInterface
The gRPC server uses this interface to expose the health checking service without depending on protob...
Definition: health_check_service_interface.h:31
grpc::ServerCredentials
Wrapper around grpc_server_credentials, a way to authenticate a server.
Definition: server_credentials.h:70
health_check_service_interface.h
grpc::Server::experimental_type::experimental_type
experimental_type(Server *server)
Definition: server.h:114
rpc_service_method.h
grpc::Server::GlobalCallbacks::PreSynchronousRequest
virtual void PreSynchronousRequest(ServerContext *context)=0
Called before application callback for each synchronous server request.
grpc::Server::Start
void Start(ServerCompletionQueue **cqs, size_t num_cqs) override
Start the server.
grpc::Service
Desriptor of an RPC service and its various RPC methods.
Definition: service_type.h:56
status.h
grpc_server_config_fetcher
struct grpc_server_config_fetcher grpc_server_config_fetcher
Definition: grpc.h:414
grpc::Server::Wait
void Wait() override
Block until the server shuts down.
grpc::Server::GlobalCallbacks::AddPort
virtual void AddPort(Server *, const std::string &, ServerCredentials *, int)
Called after a server port is added.
Definition: server.h:87
grpc::Server::GlobalCallbacks::~GlobalCallbacks
virtual ~GlobalCallbacks()
Definition: server.h:77
grpc::ChannelArguments
Options for channel creation.
Definition: channel_arguments.h:39
grpc::Server::ServerInitializer
friend class ServerInitializer
Definition: server.h:221
grpc::Server::Server
Server(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< internal::ExternalConnectionAcceptorImpl >> acceptors, grpc_server_config_fetcher *server_config_fetcher=nullptr, grpc_resource_quota *server_rq=nullptr, std::vector< std::unique_ptr< experimental::ServerInterceptorFactoryInterface >> interceptor_creators=std::vector< std::unique_ptr< experimental::ServerInterceptorFactoryInterface >>())
NOTE: This is NOT a public API.
channel_arguments.h
completion_queue.h
grpc::Server::AddListeningPort
int AddListeningPort(const std::string &addr, ServerCredentials *creds) override
Try binding the server to the given addr endpoint (port, and optionally including IP address to bind ...
grpc_server
struct grpc_server grpc_server
A server listens to some port and responds to request calls.
Definition: grpc_types.h:65
grpc::Server::server
grpc_server * server() override
Definition: server.h:197
grpc::Server::GlobalCallbacks::UpdateArguments
virtual void UpdateArguments(ChannelArguments *)
Called before server is created.
Definition: server.h:79
grpc::Server::GlobalCallbacks::PreServerStart
virtual void PreServerStart(Server *)
Called before server is started.
Definition: server.h:85
grpc::AsyncGenericService
Definition: async_generic_service.h:68
channel.h
client_interceptor.h
grpc_library.h
grpc::Server::experimental_type
NOTE: class experimental_type is not part of the public API of this class.
Definition: server.h:112
grpc::experimental::ServerInterceptorFactoryInterface
Definition: server_interceptor.h:43
server_credentials.h
grpc::Server::GetHealthCheckService
HealthCheckServiceInterface * GetHealthCheckService() const
Returns the health check service.
Definition: server.h:102
grpc::ContextAllocator
A CallbackServerContext allows users to use the contents of the CallbackServerContext or GenericCallb...
Definition: server_context.h:630
config.h
grpc::Server::experimental_type::InProcessChannelWithInterceptors
std::shared_ptr< Channel > InProcessChannelWithInterceptors(const ChannelArguments &args, std::vector< std::unique_ptr< experimental::ClientInterceptorFactoryInterface >> interceptor_creators)
Establish a channel for in-process communication with client interceptors.
port_platform.h
grpc::ServerCompletionQueue
A specific type of completion queue used by the processing of notifications by servers.
Definition: completion_queue.h:426
call.h
grpc::Server::SetGlobalCallbacks
static void SetGlobalCallbacks(GlobalCallbacks *callbacks)
Set the global callback object.
grpc::Server::c_server
grpc_server * c_server()
Returns a raw pointer to the underlying grpc_server instance.
server_interface.h
grpc::Server::set_health_check_service
void set_health_check_service(std::unique_ptr< HealthCheckServiceInterface > service)
NOTE: This method is not part of the public API for this class.
Definition: server.h:201
completion_queue.h
grpc::ServerBuilder
A builder class for the creation and startup of grpc::Server instances.
Definition: server_builder.h:90
grpc::ServerInterface
Definition: server_interface.h:65
grpc::Server::~Server
~Server() override
atm.h
gpr_timespec
Analogous to struct timespec.
Definition: gpr_types.h:47
grpc::Server::GlobalCallbacks
Global callbacks are a set of hooks that are called when server events occur.
Definition: server.h:75
grpc::Server::experimental
experimental_type experimental()
NOTE: The function experimental() is not stable public API.
Definition: server.h:131