GRPC C++  1.62.0
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 
23 
24 #include <list>
25 #include <memory>
26 #include <vector>
27 
28 #include <grpc/compression.h>
29 #include <grpc/support/atm.h>
30 #include <grpcpp/channel.h>
33 #include <grpcpp/impl/call.h>
40 #include <grpcpp/support/config.h>
41 #include <grpcpp/support/status.h>
42 
43 struct grpc_server;
44 
45 namespace grpc {
46 class AsyncGenericService;
47 class ServerContext;
48 class ServerInitializer;
49 
50 namespace internal {
51 class ExternalConnectionAcceptorImpl;
52 } // namespace internal
53 
58 class Server : public ServerInterface, private internal::GrpcLibrary {
59  public:
60  ~Server() ABSL_LOCKS_EXCLUDED(mu_) override;
61 
66  void Wait() ABSL_LOCKS_EXCLUDED(mu_) override;
67 
75  public:
76  virtual ~GlobalCallbacks() {}
78  virtual void UpdateArguments(ChannelArguments* /*args*/) {}
80  virtual void PreSynchronousRequest(ServerContext* context) = 0;
82  virtual void PostSynchronousRequest(ServerContext* context) = 0;
84  virtual void PreServerStart(Server* /*server*/) {}
86  virtual void AddPort(Server* /*server*/, const std::string& /*addr*/,
87  ServerCredentials* /*creds*/, int /*port*/) {}
88  };
94  static void SetGlobalCallbacks(GlobalCallbacks* callbacks);
95 
99 
102  return health_check_service_.get();
103  }
104 
106  std::shared_ptr<Channel> InProcessChannel(const ChannelArguments& args);
107 
112  public:
113  explicit experimental_type(Server* server) : server_(server) {}
114 
117  std::shared_ptr<Channel> InProcessChannelWithInterceptors(
118  const ChannelArguments& args,
119  std::vector<
120  std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
121  interceptor_creators);
122 
123  private:
124  Server* server_;
125  };
126 
131 
132  protected:
135  bool RegisterService(const std::string* addr, Service* service) override;
136 
150  int AddListeningPort(const std::string& addr,
151  ServerCredentials* creds) override;
152 
175  Server(ChannelArguments* args,
176  std::shared_ptr<std::vector<std::unique_ptr<ServerCompletionQueue>>>
177  sync_server_cqs,
178  int min_pollers, int max_pollers, int sync_cq_timeout_msec,
179  std::vector<std::shared_ptr<internal::ExternalConnectionAcceptorImpl>>
180  acceptors,
181  grpc_server_config_fetcher* server_config_fetcher = nullptr,
182  grpc_resource_quota* server_rq = nullptr,
183  std::vector<
184  std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
185  interceptor_creators = std::vector<std::unique_ptr<
187  experimental::ServerMetricRecorder* server_metric_recorder = nullptr);
188 
195  void Start(ServerCompletionQueue** cqs, size_t num_cqs) override;
196 
197  grpc_server* server() override { return server_; }
198 
201  std::unique_ptr<HealthCheckServiceInterface> service) {
202  health_check_service_ = std::move(service);
203  }
204 
205  ContextAllocator* context_allocator() { return context_allocator_.get(); }
206 
209  return health_check_service_disabled_;
210  }
211 
212  private:
213  std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>*
214  interceptor_creators() override {
215  return &interceptor_creators_;
216  }
217 
218  friend class AsyncGenericService;
219  friend class ServerBuilder;
220  friend class ServerInitializer;
221 
222  class SyncRequest;
223  class CallbackRequestBase;
224  template <class ServerContextType>
225  class CallbackRequest;
226  class UnimplementedAsyncRequest;
227  class UnimplementedAsyncResponse;
228 
233  class SyncRequestThreadManager;
234 
237  void RegisterAsyncGenericService(AsyncGenericService* service) override;
238 
242  void RegisterCallbackGenericService(CallbackGenericService* service) override;
243 
244  void RegisterContextAllocator(
245  std::unique_ptr<ContextAllocator> context_allocator) {
246  context_allocator_ = std::move(context_allocator);
247  }
248 
249  void PerformOpsOnCall(internal::CallOpSetInterface* ops,
250  internal::Call* call) override;
251 
252  void ShutdownInternal(gpr_timespec deadline)
253  ABSL_LOCKS_EXCLUDED(mu_) override;
254 
255  int max_receive_message_size() const override {
256  return max_receive_message_size_;
257  }
258 
259  bool call_metric_recording_enabled() const override {
260  return call_metric_recording_enabled_;
261  }
262 
263  experimental::ServerMetricRecorder* server_metric_recorder() const override {
264  return server_metric_recorder_;
265  }
266 
267  CompletionQueue* CallbackCQ() ABSL_LOCKS_EXCLUDED(mu_) override;
268 
269  ServerInitializer* initializer();
270 
271  // Functions to manage the server shutdown ref count. Things that increase
272  // the ref count are the running state of the server (take a ref at start and
273  // drop it at shutdown) and each running callback RPC.
274  void Ref();
275  void UnrefWithPossibleNotify() ABSL_LOCKS_EXCLUDED(mu_);
276  void UnrefAndWaitLocked() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
277 
278  std::vector<std::shared_ptr<internal::ExternalConnectionAcceptorImpl>>
279  acceptors_;
280 
281  // A vector of interceptor factory objects.
282  // This should be destroyed after health_check_service_ and this requirement
283  // is satisfied by declaring interceptor_creators_ before
284  // health_check_service_. (C++ mandates that member objects be destroyed in
285  // the reverse order of initialization.)
286  std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
287  interceptor_creators_;
288 
289  int max_receive_message_size_;
290 
294  std::shared_ptr<std::vector<std::unique_ptr<ServerCompletionQueue>>>
295  sync_server_cqs_;
296 
299  std::vector<std::unique_ptr<SyncRequestThreadManager>> sync_req_mgrs_;
300 
301  // Server status
302  internal::Mutex mu_;
303  bool started_;
304  bool shutdown_ ABSL_GUARDED_BY(mu_);
305  bool shutdown_notified_
306  ABSL_GUARDED_BY(mu_); // Was notify called on the shutdown_cv_
307  internal::CondVar shutdown_done_cv_;
308  bool shutdown_done_ ABSL_GUARDED_BY(mu_) = false;
309  std::atomic_int shutdown_refs_outstanding_{1};
310 
311  internal::CondVar shutdown_cv_;
312 
313  std::shared_ptr<GlobalCallbacks> global_callbacks_;
314 
315  std::vector<std::string> services_;
316  bool has_async_generic_service_ = false;
317  bool has_callback_generic_service_ = false;
318  bool has_callback_methods_ = false;
319 
320  // Pointer to the wrapped grpc_server.
321  grpc_server* server_;
322 
323  std::unique_ptr<ServerInitializer> server_initializer_;
324 
325  std::unique_ptr<ContextAllocator> context_allocator_;
326 
327  std::unique_ptr<HealthCheckServiceInterface> health_check_service_;
328  bool health_check_service_disabled_;
329 
330  // When appropriate, use a default callback generic service to handle
331  // unimplemented methods
332  std::unique_ptr<CallbackGenericService> unimplemented_service_;
333 
334  // A special handler for resource exhausted in sync case
335  std::unique_ptr<internal::MethodHandler> resource_exhausted_handler_;
336 
337  // Handler for callback generic service, if any
338  std::unique_ptr<internal::MethodHandler> generic_handler_;
339 
340  // callback_cq_ references the callbackable completion queue associated
341  // with this server (if any). It is set on the first call to CallbackCQ().
342  // It is _not owned_ by the server; ownership belongs with its internal
343  // shutdown callback tag (invoked when the CQ is fully shutdown).
344  std::atomic<CompletionQueue*> callback_cq_{nullptr};
345 
346  // List of CQs passed in by user that must be Shutdown only after Server is
347  // Shutdown. Even though this is only used with NDEBUG, instantiate it in all
348  // cases since otherwise the size will be inconsistent.
349  std::vector<CompletionQueue*> cq_list_;
350 
351  // Whetner per-call load reporting is enabled.
352  bool call_metric_recording_enabled_ = false;
353 
354  // Interface to read or update server-wide metrics. Optional.
355  experimental::ServerMetricRecorder* server_metric_recorder_ = nullptr;
356 };
357 
358 } // namespace grpc
359 
360 #endif // GRPCPP_SERVER_H
grpc::Server::InProcessChannel
std::shared_ptr< Channel > InProcessChannel(const ChannelArguments &args)
Establish a channel for in-process communication.
compression.h
grpc::experimental::ServerMetricRecorder
Records server wide metrics to be reported to the client.
Definition: server_metric_recorder.h:42
grpc::ServerContext
A ServerContext or CallbackServerContext allows the code implementing a service handler to:
Definition: server_context.h:572
grpc::Server
Represents a gRPC server.
Definition: server.h:58
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:401
grpc::Server::~Server
~Server() ABSL_LOCKS_EXCLUDED(mu_) override
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:208
grpc::Server::context_allocator
ContextAllocator * context_allocator()
Definition: server.h:205
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:69
grpc::internal::Call
Straightforward wrapping of the C call object.
Definition: call.h:36
health_check_service_interface.h
grpc::Server::experimental_type::experimental_type
experimental_type(Server *server)
Definition: server.h:113
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
Descriptor 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:448
grpc::Server::GlobalCallbacks::AddPort
virtual void AddPort(Server *, const std::string &, ServerCredentials *, int)
Called after a server port is added.
Definition: server.h:86
grpc::Server::Wait
void Wait() ABSL_LOCKS_EXCLUDED(mu_) override
Block until the server shuts down.
grpc::Server::GlobalCallbacks::~GlobalCallbacks
virtual ~GlobalCallbacks()
Definition: server.h:76
grpc::ChannelArguments
Options for channel creation.
Definition: channel_arguments.h:39
client_interceptor.h
grpc::Server::ServerInitializer
friend class ServerInitializer
Definition: server.h:220
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::internal::CallOpSetInterface
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:36
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:78
server_interface.h
grpc::Server::GlobalCallbacks::PreServerStart
virtual void PreServerStart(Server *)
Called before server is started.
Definition: server.h:84
grpc::AsyncGenericService
Definition: async_generic_service.h:68
channel.h
grpc::internal::GrpcLibrary
Classes that require gRPC to be initialized should inherit from this class.
Definition: grpc_library.h:32
grpc::Server::experimental_type
NOTE: class experimental_type is not part of the public API of this class.
Definition: server.h:111
grpc::experimental::ServerInterceptorFactoryInterface
Definition: server_interceptor.h:44
server_credentials.h
grpc::Server::GetHealthCheckService
HealthCheckServiceInterface * GetHealthCheckService() const
Returns the health check service.
Definition: server.h:101
grpc::ContextAllocator
A CallbackServerContext allows users to use the contents of the CallbackServerContext or GenericCallb...
Definition: server_context.h:656
grpc_library.h
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.
grpc::ServerCompletionQueue
A specific type of completion queue used by the processing of notifications by servers.
Definition: completion_queue.h:425
std
Definition: async_unary_call.h:405
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.
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:200
grpc::ServerBuilder
A builder class for the creation and startup of grpc::Server instances.
Definition: server_builder.h:85
grpc::ServerInterface
Definition: server_interface.h:60
atm.h
gpr_timespec
Analogous to struct timespec.
Definition: time.h:48
grpc::Server::GlobalCallbacks
Global callbacks are a set of hooks that are called when server events occur.
Definition: server.h:74
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 >>(), experimental::ServerMetricRecorder *server_metric_recorder=nullptr)
NOTE: This is NOT a public API.
grpc::CallbackGenericService
CallbackGenericService is the base class for generic services implemented using the callback API and ...
Definition: async_generic_service.h:102
grpc::Server::experimental
experimental_type experimental()
NOTE: The function experimental() is not stable public API.
Definition: server.h:130
port_platform.h