GRPC C++  1.39.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() ABSL_LOCKS_EXCLUDED(mu_) override;
62 
67  void Wait() ABSL_LOCKS_EXCLUDED(mu_) 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 
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;
229 
235 
238  void RegisterAsyncGenericService(AsyncGenericService* service) override;
239 
243  void RegisterCallbackGenericService(CallbackGenericService* service) override;
244 
245  void RegisterContextAllocator(
246  std::unique_ptr<ContextAllocator> context_allocator) {
247  context_allocator_ = std::move(context_allocator);
248  }
249 
250  void PerformOpsOnCall(internal::CallOpSetInterface* ops,
251  internal::Call* call) override;
252 
253  void ShutdownInternal(gpr_timespec deadline)
254  ABSL_LOCKS_EXCLUDED(mu_) override;
255 
256  int max_receive_message_size() const override {
257  return max_receive_message_size_;
258  }
259 
260  CompletionQueue* CallbackCQ() ABSL_LOCKS_EXCLUDED(mu_) override;
261 
262  ServerInitializer* initializer();
263 
264  // Functions to manage the server shutdown ref count. Things that increase
265  // the ref count are the running state of the server (take a ref at start and
266  // drop it at shutdown) and each running callback RPC.
267  void Ref();
268  void UnrefWithPossibleNotify() ABSL_LOCKS_EXCLUDED(mu_);
269  void UnrefAndWaitLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
270 
271  std::vector<std::shared_ptr<internal::ExternalConnectionAcceptorImpl>>
272  acceptors_;
273 
274  // A vector of interceptor factory objects.
275  // This should be destroyed after health_check_service_ and this requirement
276  // is satisfied by declaring interceptor_creators_ before
277  // health_check_service_. (C++ mandates that member objects be destroyed in
278  // the reverse order of initialization.)
279  std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
280  interceptor_creators_;
281 
282  int max_receive_message_size_;
283 
287  std::shared_ptr<std::vector<std::unique_ptr<ServerCompletionQueue>>>
288  sync_server_cqs_;
289 
292  std::vector<std::unique_ptr<SyncRequestThreadManager>> sync_req_mgrs_;
293 
294  // Server status
295  internal::Mutex mu_;
296  bool started_;
297  bool shutdown_ ABSL_GUARDED_BY(mu_);
298  bool shutdown_notified_
299  ABSL_GUARDED_BY(mu_); // Was notify called on the shutdown_cv_
300  internal::CondVar shutdown_done_cv_;
301  bool shutdown_done_ ABSL_GUARDED_BY(mu_) = false;
302  std::atomic_int shutdown_refs_outstanding_{1};
303 
304  internal::CondVar shutdown_cv_;
305 
306  std::shared_ptr<GlobalCallbacks> global_callbacks_;
307 
308  std::vector<std::string> services_;
309  bool has_async_generic_service_ = false;
310  bool has_callback_generic_service_ = false;
311  bool has_callback_methods_ = false;
312 
313  // Pointer to the wrapped grpc_server.
314  grpc_server* server_;
315 
316  std::unique_ptr<ServerInitializer> server_initializer_;
317 
318  std::unique_ptr<ContextAllocator> context_allocator_;
319 
320  std::unique_ptr<HealthCheckServiceInterface> health_check_service_;
321  bool health_check_service_disabled_;
322 
323  // When appropriate, use a default callback generic service to handle
324  // unimplemented methods
325  std::unique_ptr<CallbackGenericService> unimplemented_service_;
326 
327  // A special handler for resource exhausted in sync case
328  std::unique_ptr<internal::MethodHandler> resource_exhausted_handler_;
329 
330  // Handler for callback generic service, if any
331  std::unique_ptr<internal::MethodHandler> generic_handler_;
332 
333  // callback_cq_ references the callbackable completion queue associated
334  // with this server (if any). It is set on the first call to CallbackCQ().
335  // It is _not owned_ by the server; ownership belongs with its internal
336  // shutdown callback tag (invoked when the CQ is fully shutdown).
337  std::atomic<CompletionQueue*> callback_cq_{nullptr};
338 
339  // List of CQs passed in by user that must be Shutdown only after Server is
340  // Shutdown. Even though this is only used with NDEBUG, instantiate it in all
341  // cases since otherwise the size will be inconsistent.
342  std::vector<CompletionQueue*> cq_list_;
343 };
344 
345 } // namespace grpc
346 
347 #endif // GRPCPP_SERVER_H
Definition: async_generic_service.h:68
CallbackGenericService is the base class for generic services implemented using the callback API and ...
Definition: async_generic_service.h:102
Options for channel creation.
Definition: channel_arguments.h:39
A CallbackServerContext allows users to use the contents of the CallbackServerContext or GenericCallb...
Definition: server_context.h:622
Classes that require gRPC to be initialized should inherit from this class.
Definition: grpc_library.h:38
The gRPC server uses this interface to expose the health checking service without depending on protob...
Definition: health_check_service_interface.h:31
Global callbacks are a set of hooks that are called when server events occur.
Definition: server.h:75
virtual void PreSynchronousRequest(ServerContext *context)=0
Called before application callback for each synchronous server request.
virtual void PostSynchronousRequest(ServerContext *context)=0
Called after application callback for each synchronous server request.
virtual void UpdateArguments(ChannelArguments *)
Called before server is created.
Definition: server.h:79
virtual ~GlobalCallbacks()
Definition: server.h:77
virtual void PreServerStart(Server *)
Called before server is started.
Definition: server.h:85
virtual void AddPort(Server *, const std::string &, ServerCredentials *, int)
Called after a server port is added.
Definition: server.h:87
Definition: server_cc.cc:339
Definition: server_cc.cc:750
Use private inheritance rather than composition only to establish order of construction,...
Definition: server_cc.cc:300
UnimplementedAsyncResponse should not post user-visible completions to the C++ completion queue,...
Definition: server_cc.cc:318
NOTE: class experimental_type is not part of the public API of this class.
Definition: server.h:112
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.
Definition: server_cc.cc:975
experimental_type(Server *server)
Definition: server.h:114
A builder class for the creation and startup of grpc::Server instances.
Definition: server_builder.h:85
A specific type of completion queue used by the processing of notifications by servers.
Definition: completion_queue.h:429
A ServerContext or CallbackServerContext allows the code implementing a service handler to:
Definition: server_context.h:538
Wrapper around grpc_server_credentials, a way to authenticate a server.
Definition: server_credentials.h:70
Represents a gRPC server.
Definition: server.h:59
void Wait() ABSL_LOCKS_EXCLUDED(mu_) override
Block until the server shuts down.
Definition: server_cc.cc:1296
grpc_server * server() override
Definition: server.h:197
experimental_type experimental()
NOTE: The function experimental() is not stable public API.
Definition: server.h:131
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.
friend class ServerInitializer
Definition: server.h:221
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 ...
Definition: server_cc.cc:1083
~Server() ABSL_LOCKS_EXCLUDED(mu_) override
Definition: server_cc.cc:926
grpc_server * c_server()
Returns a raw pointer to the underlying grpc_server instance.
Definition: server_cc.cc:963
bool health_check_service_disabled() const
NOTE: This method is not part of the public API for this class.
Definition: server.h:209
HealthCheckServiceInterface * GetHealthCheckService() const
Returns the health check service.
Definition: server.h:102
bool RegisterService(const std::string *addr, Service *service) override
Register a service.
Definition: server_cc.cc:1000
ContextAllocator * context_allocator()
Definition: server.h:206
static void SetGlobalCallbacks(GlobalCallbacks *callbacks)
Set the global callback object.
Definition: server_cc.cc:957
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
std::shared_ptr< Channel > InProcessChannel(const ChannelArguments &args)
Establish a channel for in-process communication.
Definition: server_cc.cc:965
void Start(ServerCompletionQueue **cqs, size_t num_cqs) override
Start the server.
Definition: server_cc.cc:1118
Definition: server_initializer.h:31
Definition: server_interface.h:59
Desriptor of an RPC service and its various RPC methods.
Definition: service_type.h:56
Straightforward wrapping of the C call object.
Definition: call.h:35
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
An Alarm posts the user-provided tag to its associated completion queue or invokes the user-provided ...
Definition: alarm.h:33
Definition: async_unary_call.h:398
Analogous to struct timespec.
Definition: gpr_types.h:47
Definition: resource_quota.cc:127
Definition: server.h:460
Definition: server.h:450