18cfbb26c75cc7b9e2758f15782d386d2c31eb37
[platform/upstream/grpc.git] / include / grpcpp / server_builder.h
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 <climits>
23 #include <map>
24 #include <memory>
25 #include <vector>
26
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>
35
36 struct grpc_resource_quota;
37
38 namespace grpc {
39
40 class AsyncGenericService;
41 class ResourceQuota;
42 class CompletionQueue;
43 class Server;
44 class ServerCompletionQueue;
45 class ServerCredentials;
46 class Service;
47
48 namespace testing {
49 class ServerBuilderPluginTest;
50 }  // namespace testing
51
52 namespace experimental {
53 class CallbackGenericService;
54 }  // namespace experimental
55
56 /// A builder class for the creation and startup of \a grpc::Server instances.
57 class ServerBuilder {
58  public:
59   ServerBuilder();
60   virtual ~ServerBuilder();
61
62   //////////////////////////////////////////////////////////////////////////////
63   // Primary API's
64
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();
74
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);
80
81   /// Enlists an endpoint \a addr (port with an optional IP address) to
82   /// bind the \a grpc::Server object to be created to.
83   ///
84   /// It can be invoked multiple times.
85   ///
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);
99
100   /// Add a completion queue for handling asynchronous services.
101   ///
102   /// Best performance is typically obtained by using one thread per polling
103   /// completion queue.
104   ///
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:
108   ///
109   /// // While building the server:
110   /// ServerBuilder builder;
111   /// ...
112   /// cq_ = builder.AddCompletionQueue();
113   /// server_ = builder.BuildAndStart();
114   ///
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;
120   /// bool ignored_ok;
121   /// while (cq_->Next(&ignored_tag, &ignored_ok)) { }
122   ///
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
129   /// use cases.
130   std::unique_ptr<ServerCompletionQueue> AddCompletionQueue(
131       bool is_frequently_polled = true);
132
133   //////////////////////////////////////////////////////////////////////////////
134   // Less commonly used RegisterService variants
135
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);
141
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);
147
148   //////////////////////////////////////////////////////////////////////////////
149   // Fine control knobs
150
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;
155     return *this;
156   }
157
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;
162     return *this;
163   }
164
165   /// \deprecated For backward compatibility.
166   ServerBuilder& SetMaxMessageSize(int max_message_size) {
167     return SetMaxReceiveMessageSize(max_message_size);
168   }
169
170   /// Set the support status for compression algorithms. All algorithms are
171   /// enabled by default.
172   ///
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);
177
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);
181
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);
187
188   /// Set the attached buffer pool for this server
189   ServerBuilder& SetResourceQuota(const ResourceQuota& resource_quota);
190
191   ServerBuilder& SetOption(std::unique_ptr<ServerBuilderOption> option);
192
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.
199   };
200
201   /// Only useful if this is a Synchronous server.
202   ServerBuilder& SetSyncServerOption(SyncServerOption option, int value);
203
204   /// Add a channel argument (an escape hatch to tuning core library parameters
205   /// directly)
206   template <class T>
207   ServerBuilder& AddChannelArgument(const grpc::string& arg, const T& value) {
208     return SetOption(MakeChannelArgumentOption(arg, value));
209   }
210
211   /// For internal use only: Register a ServerBuilderPlugin factory function.
212   static void InternalAddPluginFactory(
213       std::unique_ptr<ServerBuilderPlugin> (*CreatePlugin)());
214
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);
219
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
222   /// experimental.
223   class experimental_type {
224    public:
225     explicit experimental_type(ServerBuilder* builder) : builder_(builder) {}
226
227     void SetInterceptorCreators(
228         std::vector<
229             std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
230             interceptor_creators) {
231       builder_->interceptor_creators_ = std::move(interceptor_creators);
232     }
233
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);
240
241    private:
242     ServerBuilder* builder_;
243   };
244
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
247   /// at any time.
248   experimental_type experimental() { return experimental_type(this); }
249
250  protected:
251   /// Experimental, to be deprecated
252   struct Port {
253     grpc::string addr;
254     std::shared_ptr<ServerCredentials> creds;
255     int* selected_port;
256   };
257
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) {}
264     HostString host;
265     Service* service;
266   };
267
268   /// Experimental, to be deprecated
269   std::vector<Port> ports() { return ports_; }
270
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());
276     }
277     return service_refs;
278   }
279
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());
285     }
286     return option_refs;
287   }
288
289  private:
290   friend class ::grpc::testing::ServerBuilderPluginTest;
291
292   struct SyncServerSettings {
293     SyncServerSettings()
294         : num_cqs(1), min_pollers(1), max_pollers(2), cq_timeout_msec(10000) {}
295
296     /// Number of server completion queues to create to listen to incoming RPCs.
297     int num_cqs;
298
299     /// Minimum number of threads per completion queue that should be listening
300     /// to incoming RPCs.
301     int min_pollers;
302
303     /// Maximum number of threads per completion queue that can be listening to
304     /// incoming RPCs.
305     int max_pollers;
306
307     /// The timeout for server completion queue's AsyncNext call.
308     int cq_timeout_msec;
309   };
310
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_;
316
317   SyncServerSettings sync_server_settings_;
318
319   /// List of completion queues added via \a AddCompletionQueue method.
320   std::vector<ServerCompletionQueue*> cqs_;
321
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};
327   struct {
328     bool is_set;
329     grpc_compression_level level;
330   } maybe_default_compression_level_;
331   struct {
332     bool is_set;
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_;
338 };
339
340 }  // namespace grpc
341
342 #endif  // GRPCPP_SERVER_BUILDER_H