1/*
2 *
3 * Copyright 2015-2016 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_BUILDER_H
20#define GRPCPP_SERVER_BUILDER_H
21
22#include <grpc/impl/codegen/port_platform.h>
23
24#include <climits>
25#include <map>
26#include <memory>
27#include <vector>
28
29#include <grpc/compression.h>
30#include <grpc/support/cpu.h>
31#include <grpc/support/workaround_list.h>
32#include <grpcpp/impl/channel_argument_option.h>
33#include <grpcpp/impl/server_builder_option.h>
34#include <grpcpp/impl/server_builder_plugin.h>
35#include <grpcpp/security/authorization_policy_provider.h>
36#include <grpcpp/server.h>
37#include <grpcpp/support/config.h>
38#include <grpcpp/support/server_interceptor.h>
39
40struct grpc_resource_quota;
41
42namespace grpc {
43
44class CompletionQueue;
45class Server;
46class ServerCompletionQueue;
47class AsyncGenericService;
48class ResourceQuota;
49class ServerCredentials;
50class Service;
51namespace testing {
52class ServerBuilderPluginTest;
53} // namespace testing
54
55namespace internal {
56class ExternalConnectionAcceptorImpl;
57} // namespace internal
58
59class CallbackGenericService;
60
61namespace experimental {
62class OrcaServerInterceptorFactory;
63// EXPERIMENTAL API:
64// Interface for a grpc server to build transports with connections created out
65// of band.
66// See ServerBuilder's AddExternalConnectionAcceptor API.
67class ExternalConnectionAcceptor {
68 public:
69 struct NewConnectionParameters {
70 int listener_fd = -1;
71 int fd = -1;
72 ByteBuffer read_buffer; // data intended for the grpc server
73 };
74 virtual ~ExternalConnectionAcceptor() {}
75 // If called before grpc::Server is started or after it is shut down, the new
76 // connection will be closed.
77 virtual void HandleNewConnection(NewConnectionParameters* p) = 0;
78};
79
80} // namespace experimental
81} // namespace grpc
82
83namespace grpc {
84
85/// A builder class for the creation and startup of \a grpc::Server instances.
86class ServerBuilder {
87 public:
88 ServerBuilder();
89 virtual ~ServerBuilder();
90
91 //////////////////////////////////////////////////////////////////////////////
92 // Primary API's
93
94 /// Return a running server which is ready for processing calls.
95 /// Before calling, one typically needs to ensure that:
96 /// 1. a service is registered - so that the server knows what to serve
97 /// (via RegisterService, or RegisterAsyncGenericService)
98 /// 2. a listening port has been added - so the server knows where to receive
99 /// traffic (via AddListeningPort)
100 /// 3. [for async api only] completion queues have been added via
101 /// AddCompletionQueue
102 ///
103 /// Will return a nullptr on errors.
104 virtual std::unique_ptr<grpc::Server> BuildAndStart();
105
106 /// Register a service. This call does not take ownership of the service.
107 /// The service must exist for the lifetime of the \a Server instance returned
108 /// by \a BuildAndStart().
109 /// Matches requests with any :authority
110 ServerBuilder& RegisterService(grpc::Service* service);
111
112 /// Enlists an endpoint \a addr (port with an optional IP address) to
113 /// bind the \a grpc::Server object to be created to.
114 ///
115 /// It can be invoked multiple times.
116 ///
117 /// \param addr_uri The address to try to bind to the server in URI form. If
118 /// the scheme name is omitted, "dns:///" is assumed. To bind to any address,
119 /// please use IPv6 any, i.e., [::]:<port>, which also accepts IPv4
120 /// connections. Valid values include dns:///localhost:1234,
121 /// 192.168.1.1:31416, dns:///[::1]:27182, etc.
122 /// \param creds The credentials associated with the server.
123 /// \param[out] selected_port If not `nullptr`, gets populated with the port
124 /// number bound to the \a grpc::Server for the corresponding endpoint after
125 /// it is successfully bound by BuildAndStart(), 0 otherwise. AddListeningPort
126 /// does not modify this pointer.
127 ServerBuilder& AddListeningPort(
128 const std::string& addr_uri,
129 std::shared_ptr<grpc::ServerCredentials> creds,
130 int* selected_port = nullptr);
131
132 /// Add a completion queue for handling asynchronous services.
133 ///
134 /// Best performance is typically obtained by using one thread per polling
135 /// completion queue.
136 ///
137 /// Caller is required to shutdown the server prior to shutting down the
138 /// returned completion queue. Caller is also required to drain the
139 /// completion queue after shutting it down. A typical usage scenario:
140 ///
141 /// // While building the server:
142 /// ServerBuilder builder;
143 /// ...
144 /// cq_ = builder.AddCompletionQueue();
145 /// server_ = builder.BuildAndStart();
146 ///
147 /// // While shutting down the server;
148 /// server_->Shutdown();
149 /// cq_->Shutdown(); // Always *after* the associated server's Shutdown()!
150 /// // Drain the cq_ that was created
151 /// void* ignored_tag;
152 /// bool ignored_ok;
153 /// while (cq_->Next(&ignored_tag, &ignored_ok)) { }
154 ///
155 /// \param is_frequently_polled This is an optional parameter to inform gRPC
156 /// library about whether this completion queue would be frequently polled
157 /// (i.e. by calling \a Next() or \a AsyncNext()). The default value is
158 /// 'true' and is the recommended setting. Setting this to 'false' (i.e.
159 /// not polling the completion queue frequently) will have a significantly
160 /// negative performance impact and hence should not be used in production
161 /// use cases.
162 std::unique_ptr<grpc::ServerCompletionQueue> AddCompletionQueue(
163 bool is_frequently_polled = true);
164
165 //////////////////////////////////////////////////////////////////////////////
166 // Less commonly used RegisterService variants
167
168 /// Register a service. This call does not take ownership of the service.
169 /// The service must exist for the lifetime of the \a Server instance
170 /// returned by \a BuildAndStart(). Only matches requests with :authority \a
171 /// host
172 ServerBuilder& RegisterService(const std::string& host,
173 grpc::Service* service);
174
175 /// Register a generic service.
176 /// Matches requests with any :authority
177 /// This is mostly useful for writing generic gRPC Proxies where the exact
178 /// serialization format is unknown
179 ServerBuilder& RegisterAsyncGenericService(
180 grpc::AsyncGenericService* service);
181
182 //////////////////////////////////////////////////////////////////////////////
183 // Fine control knobs
184
185 /// Set max receive message size in bytes.
186 /// The default is GRPC_DEFAULT_MAX_RECV_MESSAGE_LENGTH.
187 ServerBuilder& SetMaxReceiveMessageSize(int max_receive_message_size) {
188 max_receive_message_size_ = max_receive_message_size;
189 return *this;
190 }
191
192 /// Set max send message size in bytes.
193 /// The default is GRPC_DEFAULT_MAX_SEND_MESSAGE_LENGTH.
194 ServerBuilder& SetMaxSendMessageSize(int max_send_message_size) {
195 max_send_message_size_ = max_send_message_size;
196 return *this;
197 }
198
199 /// \deprecated For backward compatibility.
200 ServerBuilder& SetMaxMessageSize(int max_message_size) {
201 return SetMaxReceiveMessageSize(max_message_size);
202 }
203
204 /// Set the support status for compression algorithms. All algorithms are
205 /// enabled by default.
206 ///
207 /// Incoming calls compressed with an unsupported algorithm will fail with
208 /// \a GRPC_STATUS_UNIMPLEMENTED.
209 ServerBuilder& SetCompressionAlgorithmSupportStatus(
210 grpc_compression_algorithm algorithm, bool enabled);
211
212 /// The default compression level to use for all channel calls in the
213 /// absence of a call-specific level.
214 ServerBuilder& SetDefaultCompressionLevel(grpc_compression_level level);
215
216 /// The default compression algorithm to use for all channel calls in the
217 /// absence of a call-specific level. Note that it overrides any compression
218 /// level set by \a SetDefaultCompressionLevel.
219 ServerBuilder& SetDefaultCompressionAlgorithm(
220 grpc_compression_algorithm algorithm);
221
222 /// Set the attached buffer pool for this server
223 ServerBuilder& SetResourceQuota(const grpc::ResourceQuota& resource_quota);
224
225 ServerBuilder& SetOption(std::unique_ptr<grpc::ServerBuilderOption> option);
226
227 /// Options for synchronous servers.
228 enum SyncServerOption {
229 NUM_CQS, ///< Number of completion queues.
230 MIN_POLLERS, ///< Minimum number of polling threads.
231 MAX_POLLERS, ///< Maximum number of polling threads.
232 CQ_TIMEOUT_MSEC ///< Completion queue timeout in milliseconds.
233 };
234
235 /// Only useful if this is a Synchronous server.
236 ServerBuilder& SetSyncServerOption(SyncServerOption option, int value);
237
238 /// Add a channel argument (an escape hatch to tuning core library parameters
239 /// directly)
240 template <class T>
241 ServerBuilder& AddChannelArgument(const std::string& arg, const T& value) {
242 return SetOption(grpc::MakeChannelArgumentOption(arg, value));
243 }
244
245 /// For internal use only: Register a ServerBuilderPlugin factory function.
246 static void InternalAddPluginFactory(
247 std::unique_ptr<grpc::ServerBuilderPlugin> (*CreatePlugin)());
248
249 /// Enable a server workaround. Do not use unless you know what the workaround
250 /// does. For explanation and detailed descriptions of workarounds, see
251 /// doc/workarounds.md.
252 ServerBuilder& EnableWorkaround(grpc_workaround_list id);
253
254 /// NOTE: class experimental_type is not part of the public API of this class.
255 /// TODO(yashykt): Integrate into public API when this is no longer
256 /// experimental.
257 class experimental_type {
258 public:
259 explicit experimental_type(ServerBuilder* builder) : builder_(builder) {}
260
261 void SetInterceptorCreators(
262 std::vector<std::unique_ptr<
263 grpc::experimental::ServerInterceptorFactoryInterface>>
264 interceptor_creators) {
265 builder_->interceptor_creators_ = std::move(interceptor_creators);
266 }
267
268 enum class ExternalConnectionType {
269 FROM_FD = 0 // in the form of a file descriptor
270 };
271
272 /// Register an acceptor to handle the externally accepted connection in
273 /// grpc server. The returned acceptor can be used to pass the connection
274 /// to grpc server, where a channel will be created with the provided
275 /// server credentials.
276 std::unique_ptr<grpc::experimental::ExternalConnectionAcceptor>
277 AddExternalConnectionAcceptor(ExternalConnectionType type,
278 std::shared_ptr<ServerCredentials> creds);
279
280 /// Sets server authorization policy provider in
281 /// GRPC_ARG_AUTHORIZATION_POLICY_PROVIDER channel argument.
282 void SetAuthorizationPolicyProvider(
283 std::shared_ptr<experimental::AuthorizationPolicyProviderInterface>
284 provider);
285
286 private:
287 ServerBuilder* builder_;
288 };
289
290 /// Set the allocator for creating and releasing callback server context.
291 /// Takes the owndership of the allocator.
292 ServerBuilder& SetContextAllocator(
293 std::unique_ptr<grpc::ContextAllocator> context_allocator);
294
295 /// Register a generic service that uses the callback API.
296 /// Matches requests with any :authority
297 /// This is mostly useful for writing generic gRPC Proxies where the exact
298 /// serialization format is unknown
299 ServerBuilder& RegisterCallbackGenericService(
300 grpc::CallbackGenericService* service);
301
302 /// NOTE: The function experimental() is not stable public API. It is a view
303 /// to the experimental components of this class. It may be changed or removed
304 /// at any time.
305 experimental_type experimental() { return experimental_type(this); }
306
307 protected:
308 /// Experimental, to be deprecated
309 struct Port {
310 std::string addr;
311 std::shared_ptr<ServerCredentials> creds;
312 int* selected_port;
313 };
314
315 /// Experimental, to be deprecated
316 typedef std::unique_ptr<std::string> HostString;
317 struct NamedService {
318 explicit NamedService(grpc::Service* s) : service(s) {}
319 NamedService(const std::string& h, grpc::Service* s)
320 : host(new std::string(h)), service(s) {}
321 HostString host;
322 grpc::Service* service;
323 };
324
325 /// Experimental, to be deprecated
326 std::vector<Port> ports() { return ports_; }
327
328 /// Experimental, to be deprecated
329 std::vector<NamedService*> services() {
330 std::vector<NamedService*> service_refs;
331 service_refs.reserve(n: services_.size());
332 for (auto& ptr : services_) {
333 service_refs.push_back(x: ptr.get());
334 }
335 return service_refs;
336 }
337
338 /// Experimental, to be deprecated
339 std::vector<grpc::ServerBuilderOption*> options() {
340 std::vector<grpc::ServerBuilderOption*> option_refs;
341 option_refs.reserve(n: options_.size());
342 for (auto& ptr : options_) {
343 option_refs.push_back(x: ptr.get());
344 }
345 return option_refs;
346 }
347
348 /// Experimental API, subject to change.
349 void set_fetcher(grpc_server_config_fetcher* server_config_fetcher) {
350 server_config_fetcher_ = server_config_fetcher;
351 }
352
353 /// Experimental API, subject to change.
354 virtual ChannelArguments BuildChannelArgs();
355
356 private:
357 friend class grpc::testing::ServerBuilderPluginTest;
358 friend class grpc::experimental::OrcaServerInterceptorFactory;
359
360 struct SyncServerSettings {
361 SyncServerSettings()
362 : num_cqs(1), min_pollers(1), max_pollers(2), cq_timeout_msec(10000) {}
363
364 /// Number of server completion queues to create to listen to incoming RPCs.
365 int num_cqs;
366
367 /// Minimum number of threads per completion queue that should be listening
368 /// to incoming RPCs.
369 int min_pollers;
370
371 /// Maximum number of threads per completion queue that can be listening to
372 /// incoming RPCs.
373 int max_pollers;
374
375 /// The timeout for server completion queue's AsyncNext call.
376 int cq_timeout_msec;
377 };
378
379 int max_receive_message_size_;
380 int max_send_message_size_;
381 std::vector<std::unique_ptr<grpc::ServerBuilderOption>> options_;
382 std::vector<std::unique_ptr<NamedService>> services_;
383 std::vector<Port> ports_;
384
385 SyncServerSettings sync_server_settings_;
386
387 /// List of completion queues added via \a AddCompletionQueue method.
388 std::vector<grpc::ServerCompletionQueue*> cqs_;
389
390 std::shared_ptr<grpc::ServerCredentials> creds_;
391 std::vector<std::unique_ptr<grpc::ServerBuilderPlugin>> plugins_;
392 grpc_resource_quota* resource_quota_;
393 grpc::AsyncGenericService* generic_service_{nullptr};
394 std::unique_ptr<ContextAllocator> context_allocator_;
395 grpc::CallbackGenericService* callback_generic_service_{nullptr};
396
397 struct {
398 bool is_set;
399 grpc_compression_level level;
400 } maybe_default_compression_level_;
401 struct {
402 bool is_set;
403 grpc_compression_algorithm algorithm;
404 } maybe_default_compression_algorithm_;
405 uint32_t enabled_compression_algorithms_bitset_;
406 std::vector<
407 std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>>
408 interceptor_creators_;
409 std::vector<
410 std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>>
411 internal_interceptor_creators_;
412 std::vector<std::shared_ptr<grpc::internal::ExternalConnectionAcceptorImpl>>
413 acceptors_;
414 grpc_server_config_fetcher* server_config_fetcher_ = nullptr;
415 std::shared_ptr<experimental::AuthorizationPolicyProviderInterface>
416 authorization_provider_;
417};
418
419} // namespace grpc
420
421#endif // GRPCPP_SERVER_BUILDER_H
422

source code of include/grpcpp/server_builder.h