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