3 * Copyright 2015-2016 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #ifndef GRPCPP_SERVER_BUILDER_H
20 #define GRPCPP_SERVER_BUILDER_H
27 #include <grpc/compression.h>
28 #include <grpc/support/cpu.h>
29 #include <grpc/support/workaround_list.h>
30 #include <grpcpp/impl/channel_argument_option.h>
31 #include <grpcpp/impl/codegen/server_interceptor.h>
32 #include <grpcpp/impl/server_builder_option.h>
33 #include <grpcpp/impl/server_builder_plugin.h>
34 #include <grpcpp/support/config.h>
36 struct grpc_resource_quota;
40 class AsyncGenericService;
42 class CompletionQueue;
44 class ServerCompletionQueue;
45 class ServerCredentials;
49 class ServerBuilderPluginTest;
50 } // namespace testing
52 namespace experimental {
53 class CallbackGenericService;
54 } // namespace experimental
56 /// A builder class for the creation and startup of \a grpc::Server instances.
60 virtual ~ServerBuilder();
62 //////////////////////////////////////////////////////////////////////////////
65 /// Return a running server which is ready for processing calls.
66 /// Before calling, one typically needs to ensure that:
67 /// 1. a service is registered - so that the server knows what to serve
68 /// (via RegisterService, or RegisterAsyncGenericService)
69 /// 2. a listening port has been added - so the server knows where to receive
70 /// traffic (via AddListeningPort)
71 /// 3. [for async api only] completion queues have been added via
72 /// AddCompletionQueue
73 virtual std::unique_ptr<Server> BuildAndStart();
75 /// Register a service. This call does not take ownership of the service.
76 /// The service must exist for the lifetime of the \a Server instance returned
77 /// by \a BuildAndStart().
78 /// Matches requests with any :authority
79 ServerBuilder& RegisterService(Service* service);
81 /// Enlists an endpoint \a addr (port with an optional IP address) to
82 /// bind the \a grpc::Server object to be created to.
84 /// It can be invoked multiple times.
86 /// \param addr_uri The address to try to bind to the server in URI form. If
87 /// the scheme name is omitted, "dns:///" is assumed. To bind to any address,
88 /// please use IPv6 any, i.e., [::]:<port>, which also accepts IPv4
89 /// connections. Valid values include dns:///localhost:1234, /
90 /// 192.168.1.1:31416, dns:///[::1]:27182, etc.).
91 /// \param creds The credentials associated with the server.
92 /// \param selected_port[out] If not `nullptr`, gets populated with the port
93 /// number bound to the \a grpc::Server for the corresponding endpoint after
94 /// it is successfully bound by BuildAndStart(), 0 otherwise. AddListeningPort
95 /// does not modify this pointer.
96 ServerBuilder& AddListeningPort(const grpc::string& addr_uri,
97 std::shared_ptr<ServerCredentials> creds,
98 int* selected_port = nullptr);
100 /// Add a completion queue for handling asynchronous services.
102 /// Best performance is typically obtained by using one thread per polling
103 /// completion queue.
105 /// Caller is required to shutdown the server prior to shutting down the
106 /// returned completion queue. Caller is also required to drain the
107 /// completion queue after shutting it down. A typical usage scenario:
109 /// // While building the server:
110 /// ServerBuilder builder;
112 /// cq_ = builder.AddCompletionQueue();
113 /// server_ = builder.BuildAndStart();
115 /// // While shutting down the server;
116 /// server_->Shutdown();
117 /// cq_->Shutdown(); // Always *after* the associated server's Shutdown()!
118 /// // Drain the cq_ that was created
119 /// void* ignored_tag;
121 /// while (cq_->Next(&ignored_tag, &ignored_ok)) { }
123 /// \param is_frequently_polled This is an optional parameter to inform gRPC
124 /// library about whether this completion queue would be frequently polled
125 /// (i.e. by calling \a Next() or \a AsyncNext()). The default value is
126 /// 'true' and is the recommended setting. Setting this to 'false' (i.e.
127 /// not polling the completion queue frequently) will have a significantly
128 /// negative performance impact and hence should not be used in production
130 std::unique_ptr<ServerCompletionQueue> AddCompletionQueue(
131 bool is_frequently_polled = true);
133 //////////////////////////////////////////////////////////////////////////////
134 // Less commonly used RegisterService variants
136 /// Register a service. This call does not take ownership of the service.
137 /// The service must exist for the lifetime of the \a Server instance returned
138 /// by \a BuildAndStart().
139 /// Only matches requests with :authority \a host
140 ServerBuilder& RegisterService(const grpc::string& host, Service* service);
142 /// Register a generic service.
143 /// Matches requests with any :authority
144 /// This is mostly useful for writing generic gRPC Proxies where the exact
145 /// serialization format is unknown
146 ServerBuilder& RegisterAsyncGenericService(AsyncGenericService* service);
148 //////////////////////////////////////////////////////////////////////////////
149 // Fine control knobs
151 /// Set max receive message size in bytes.
152 /// The default is GRPC_DEFAULT_MAX_RECV_MESSAGE_LENGTH.
153 ServerBuilder& SetMaxReceiveMessageSize(int max_receive_message_size) {
154 max_receive_message_size_ = max_receive_message_size;
158 /// Set max send message size in bytes.
159 /// The default is GRPC_DEFAULT_MAX_SEND_MESSAGE_LENGTH.
160 ServerBuilder& SetMaxSendMessageSize(int max_send_message_size) {
161 max_send_message_size_ = max_send_message_size;
165 /// \deprecated For backward compatibility.
166 ServerBuilder& SetMaxMessageSize(int max_message_size) {
167 return SetMaxReceiveMessageSize(max_message_size);
170 /// Set the support status for compression algorithms. All algorithms are
171 /// enabled by default.
173 /// Incoming calls compressed with an unsupported algorithm will fail with
174 /// \a GRPC_STATUS_UNIMPLEMENTED.
175 ServerBuilder& SetCompressionAlgorithmSupportStatus(
176 grpc_compression_algorithm algorithm, bool enabled);
178 /// The default compression level to use for all channel calls in the
179 /// absence of a call-specific level.
180 ServerBuilder& SetDefaultCompressionLevel(grpc_compression_level level);
182 /// The default compression algorithm to use for all channel calls in the
183 /// absence of a call-specific level. Note that it overrides any compression
184 /// level set by \a SetDefaultCompressionLevel.
185 ServerBuilder& SetDefaultCompressionAlgorithm(
186 grpc_compression_algorithm algorithm);
188 /// Set the attached buffer pool for this server
189 ServerBuilder& SetResourceQuota(const ResourceQuota& resource_quota);
191 ServerBuilder& SetOption(std::unique_ptr<ServerBuilderOption> option);
193 /// Options for synchronous servers.
194 enum SyncServerOption {
195 NUM_CQS, ///< Number of completion queues.
196 MIN_POLLERS, ///< Minimum number of polling threads.
197 MAX_POLLERS, ///< Maximum number of polling threads.
198 CQ_TIMEOUT_MSEC ///< Completion queue timeout in milliseconds.
201 /// Only useful if this is a Synchronous server.
202 ServerBuilder& SetSyncServerOption(SyncServerOption option, int value);
204 /// Add a channel argument (an escape hatch to tuning core library parameters
207 ServerBuilder& AddChannelArgument(const grpc::string& arg, const T& value) {
208 return SetOption(MakeChannelArgumentOption(arg, value));
211 /// For internal use only: Register a ServerBuilderPlugin factory function.
212 static void InternalAddPluginFactory(
213 std::unique_ptr<ServerBuilderPlugin> (*CreatePlugin)());
215 /// Enable a server workaround. Do not use unless you know what the workaround
216 /// does. For explanation and detailed descriptions of workarounds, see
217 /// doc/workarounds.md.
218 ServerBuilder& EnableWorkaround(grpc_workaround_list id);
220 /// NOTE: class experimental_type is not part of the public API of this class.
221 /// TODO(yashykt): Integrate into public API when this is no longer
223 class experimental_type {
225 explicit experimental_type(ServerBuilder* builder) : builder_(builder) {}
227 void SetInterceptorCreators(
229 std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
230 interceptor_creators) {
231 builder_->interceptor_creators_ = std::move(interceptor_creators);
234 /// Register a generic service that uses the callback API.
235 /// Matches requests with any :authority
236 /// This is mostly useful for writing generic gRPC Proxies where the exact
237 /// serialization format is unknown
238 ServerBuilder& RegisterCallbackGenericService(
239 experimental::CallbackGenericService* service);
242 ServerBuilder* builder_;
245 /// NOTE: The function experimental() is not stable public API. It is a view
246 /// to the experimental components of this class. It may be changed or removed
248 experimental_type experimental() { return experimental_type(this); }
251 /// Experimental, to be deprecated
254 std::shared_ptr<ServerCredentials> creds;
258 /// Experimental, to be deprecated
259 typedef std::unique_ptr<grpc::string> HostString;
260 struct NamedService {
261 explicit NamedService(Service* s) : service(s) {}
262 NamedService(const grpc::string& h, Service* s)
263 : host(new grpc::string(h)), service(s) {}
268 /// Experimental, to be deprecated
269 std::vector<Port> ports() { return ports_; }
271 /// Experimental, to be deprecated
272 std::vector<NamedService*> services() {
273 std::vector<NamedService*> service_refs;
274 for (auto& ptr : services_) {
275 service_refs.push_back(ptr.get());
280 /// Experimental, to be deprecated
281 std::vector<ServerBuilderOption*> options() {
282 std::vector<ServerBuilderOption*> option_refs;
283 for (auto& ptr : options_) {
284 option_refs.push_back(ptr.get());
290 friend class ::grpc::testing::ServerBuilderPluginTest;
292 struct SyncServerSettings {
294 : num_cqs(1), min_pollers(1), max_pollers(2), cq_timeout_msec(10000) {}
296 /// Number of server completion queues to create to listen to incoming RPCs.
299 /// Minimum number of threads per completion queue that should be listening
300 /// to incoming RPCs.
303 /// Maximum number of threads per completion queue that can be listening to
307 /// The timeout for server completion queue's AsyncNext call.
311 int max_receive_message_size_;
312 int max_send_message_size_;
313 std::vector<std::unique_ptr<ServerBuilderOption>> options_;
314 std::vector<std::unique_ptr<NamedService>> services_;
315 std::vector<Port> ports_;
317 SyncServerSettings sync_server_settings_;
319 /// List of completion queues added via \a AddCompletionQueue method.
320 std::vector<ServerCompletionQueue*> cqs_;
322 std::shared_ptr<ServerCredentials> creds_;
323 std::vector<std::unique_ptr<ServerBuilderPlugin>> plugins_;
324 grpc_resource_quota* resource_quota_;
325 AsyncGenericService* generic_service_{nullptr};
326 experimental::CallbackGenericService* callback_generic_service_{nullptr};
329 grpc_compression_level level;
330 } maybe_default_compression_level_;
333 grpc_compression_algorithm algorithm;
334 } maybe_default_compression_algorithm_;
335 uint32_t enabled_compression_algorithms_bitset_;
336 std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
337 interceptor_creators_;
342 #endif // GRPCPP_SERVER_BUILDER_H