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