• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/server_builder_option.h>
32 #include <grpcpp/impl/server_builder_plugin.h>
33 #include <grpcpp/support/config.h>
34 
35 struct grpc_resource_quota;
36 
37 namespace grpc {
38 
39 class AsyncGenericService;
40 class ResourceQuota;
41 class CompletionQueue;
42 class Server;
43 class ServerCompletionQueue;
44 class ServerCredentials;
45 class Service;
46 
47 namespace testing {
48 class ServerBuilderPluginTest;
49 }  // namespace testing
50 
51 /// A builder class for the creation and startup of \a grpc::Server instances.
52 class ServerBuilder {
53  public:
54   ServerBuilder();
55   virtual ~ServerBuilder();
56 
57   //////////////////////////////////////////////////////////////////////////////
58   // Primary API's
59 
60   /// Return a running server which is ready for processing calls.
61   /// Before calling, one typically needs to ensure that:
62   ///  1. a service is registered - so that the server knows what to serve
63   ///     (via RegisterService, or RegisterAsyncGenericService)
64   ///  2. a listening port has been added - so the server knows where to receive
65   ///     traffic (via AddListeningPort)
66   ///  3. [for async api only] completion queues have been added via
67   ///     AddCompletionQueue
68   virtual std::unique_ptr<Server> BuildAndStart();
69 
70   /// Register a service. This call does not take ownership of the service.
71   /// The service must exist for the lifetime of the \a Server instance returned
72   /// by \a BuildAndStart().
73   /// Matches requests with any :authority
74   ServerBuilder& RegisterService(Service* service);
75 
76   /// Enlists an endpoint \a addr (port with an optional IP address) to
77   /// bind the \a grpc::Server object to be created to.
78   ///
79   /// It can be invoked multiple times.
80   ///
81   /// \param addr_uri The address to try to bind to the server in URI form. If
82   /// the scheme name is omitted, "dns:///" is assumed. To bind to any address,
83   /// please use IPv6 any, i.e., [::]:<port>, which also accepts IPv4
84   /// connections.  Valid values include dns:///localhost:1234, /
85   /// 192.168.1.1:31416, dns:///[::1]:27182, etc.).
86   /// \param creds The credentials associated with the server.
87   /// \param selected_port[out] If not `nullptr`, gets populated with the port
88   /// number bound to the \a grpc::Server for the corresponding endpoint after
89   /// it is successfully bound by BuildAndStart(), 0 otherwise. AddListeningPort
90   /// does not modify this pointer.
91   ServerBuilder& AddListeningPort(const grpc::string& addr_uri,
92                                   std::shared_ptr<ServerCredentials> creds,
93                                   int* selected_port = nullptr);
94 
95   /// Add a completion queue for handling asynchronous services.
96   ///
97   /// Best performance is typically obtained by using one thread per polling
98   /// completion queue.
99   ///
100   /// Caller is required to shutdown the server prior to shutting down the
101   /// returned completion queue. Caller is also required to drain the
102   /// completion queue after shutting it down. A typical usage scenario:
103   ///
104   /// // While building the server:
105   /// ServerBuilder builder;
106   /// ...
107   /// cq_ = builder.AddCompletionQueue();
108   /// server_ = builder.BuildAndStart();
109   ///
110   /// // While shutting down the server;
111   /// server_->Shutdown();
112   /// cq_->Shutdown();  // Always *after* the associated server's Shutdown()!
113   /// // Drain the cq_ that was created
114   /// void* ignored_tag;
115   /// bool ignored_ok;
116   /// while (cq_->Next(&ignored_tag, &ignored_ok)) { }
117   ///
118   /// \param is_frequently_polled This is an optional parameter to inform gRPC
119   /// library about whether this completion queue would be frequently polled
120   /// (i.e. by calling \a Next() or \a AsyncNext()). The default value is
121   /// 'true' and is the recommended setting. Setting this to 'false' (i.e.
122   /// not polling the completion queue frequently) will have a significantly
123   /// negative performance impact and hence should not be used in production
124   /// use cases.
125   std::unique_ptr<ServerCompletionQueue> AddCompletionQueue(
126       bool is_frequently_polled = true);
127 
128   //////////////////////////////////////////////////////////////////////////////
129   // Less commonly used RegisterService variants
130 
131   /// Register a service. This call does not take ownership of the service.
132   /// The service must exist for the lifetime of the \a Server instance returned
133   /// by \a BuildAndStart().
134   /// Only matches requests with :authority \a host
135   ServerBuilder& RegisterService(const grpc::string& host, Service* service);
136 
137   /// Register a generic service.
138   /// Matches requests with any :authority
139   /// This is mostly useful for writing generic gRPC Proxies where the exact
140   /// serialization format is unknown
141   ServerBuilder& RegisterAsyncGenericService(AsyncGenericService* service);
142 
143   //////////////////////////////////////////////////////////////////////////////
144   // Fine control knobs
145 
146   /// Set max receive message size in bytes.
147   /// The default is GRPC_DEFAULT_MAX_RECV_MESSAGE_LENGTH.
SetMaxReceiveMessageSize(int max_receive_message_size)148   ServerBuilder& SetMaxReceiveMessageSize(int max_receive_message_size) {
149     max_receive_message_size_ = max_receive_message_size;
150     return *this;
151   }
152 
153   /// Set max send message size in bytes.
154   /// The default is GRPC_DEFAULT_MAX_SEND_MESSAGE_LENGTH.
SetMaxSendMessageSize(int max_send_message_size)155   ServerBuilder& SetMaxSendMessageSize(int max_send_message_size) {
156     max_send_message_size_ = max_send_message_size;
157     return *this;
158   }
159 
160   /// \deprecated For backward compatibility.
SetMaxMessageSize(int max_message_size)161   ServerBuilder& SetMaxMessageSize(int max_message_size) {
162     return SetMaxReceiveMessageSize(max_message_size);
163   }
164 
165   /// Set the support status for compression algorithms. All algorithms are
166   /// enabled by default.
167   ///
168   /// Incoming calls compressed with an unsupported algorithm will fail with
169   /// \a GRPC_STATUS_UNIMPLEMENTED.
170   ServerBuilder& SetCompressionAlgorithmSupportStatus(
171       grpc_compression_algorithm algorithm, bool enabled);
172 
173   /// The default compression level to use for all channel calls in the
174   /// absence of a call-specific level.
175   ServerBuilder& SetDefaultCompressionLevel(grpc_compression_level level);
176 
177   /// The default compression algorithm to use for all channel calls in the
178   /// absence of a call-specific level. Note that it overrides any compression
179   /// level set by \a SetDefaultCompressionLevel.
180   ServerBuilder& SetDefaultCompressionAlgorithm(
181       grpc_compression_algorithm algorithm);
182 
183   /// Set the attached buffer pool for this server
184   ServerBuilder& SetResourceQuota(const ResourceQuota& resource_quota);
185 
186   ServerBuilder& SetOption(std::unique_ptr<ServerBuilderOption> option);
187 
188   /// Options for synchronous servers.
189   enum SyncServerOption {
190     NUM_CQS,         ///< Number of completion queues.
191     MIN_POLLERS,     ///< Minimum number of polling threads.
192     MAX_POLLERS,     ///< Maximum number of polling threads.
193     CQ_TIMEOUT_MSEC  ///< Completion queue timeout in milliseconds.
194   };
195 
196   /// Only useful if this is a Synchronous server.
197   ServerBuilder& SetSyncServerOption(SyncServerOption option, int value);
198 
199   /// Add a channel argument (an escape hatch to tuning core library parameters
200   /// directly)
201   template <class T>
AddChannelArgument(const grpc::string & arg,const T & value)202   ServerBuilder& AddChannelArgument(const grpc::string& arg, const T& value) {
203     return SetOption(MakeChannelArgumentOption(arg, value));
204   }
205 
206   /// For internal use only: Register a ServerBuilderPlugin factory function.
207   static void InternalAddPluginFactory(
208       std::unique_ptr<ServerBuilderPlugin> (*CreatePlugin)());
209 
210   /// Enable a server workaround. Do not use unless you know what the workaround
211   /// does. For explanation and detailed descriptions of workarounds, see
212   /// doc/workarounds.md.
213   ServerBuilder& EnableWorkaround(grpc_workaround_list id);
214 
215  protected:
216   /// Experimental, to be deprecated
217   struct Port {
218     grpc::string addr;
219     std::shared_ptr<ServerCredentials> creds;
220     int* selected_port;
221   };
222 
223   /// Experimental, to be deprecated
224   typedef std::unique_ptr<grpc::string> HostString;
225   struct NamedService {
NamedServiceNamedService226     explicit NamedService(Service* s) : service(s) {}
NamedServiceNamedService227     NamedService(const grpc::string& h, Service* s)
228         : host(new grpc::string(h)), service(s) {}
229     HostString host;
230     Service* service;
231   };
232 
233   /// Experimental, to be deprecated
ports()234   std::vector<Port> ports() { return ports_; }
235 
236   /// Experimental, to be deprecated
services()237   std::vector<NamedService*> services() {
238     std::vector<NamedService*> service_refs;
239     for (auto& ptr : services_) {
240       service_refs.push_back(ptr.get());
241     }
242     return service_refs;
243   }
244 
245   /// Experimental, to be deprecated
options()246   std::vector<ServerBuilderOption*> options() {
247     std::vector<ServerBuilderOption*> option_refs;
248     for (auto& ptr : options_) {
249       option_refs.push_back(ptr.get());
250     }
251     return option_refs;
252   }
253 
254  private:
255   friend class ::grpc::testing::ServerBuilderPluginTest;
256 
257   struct SyncServerSettings {
SyncServerSettingsSyncServerSettings258     SyncServerSettings()
259         : num_cqs(1), min_pollers(1), max_pollers(2), cq_timeout_msec(10000) {}
260 
261     /// Number of server completion queues to create to listen to incoming RPCs.
262     int num_cqs;
263 
264     /// Minimum number of threads per completion queue that should be listening
265     /// to incoming RPCs.
266     int min_pollers;
267 
268     /// Maximum number of threads per completion queue that can be listening to
269     /// incoming RPCs.
270     int max_pollers;
271 
272     /// The timeout for server completion queue's AsyncNext call.
273     int cq_timeout_msec;
274   };
275 
276   int max_receive_message_size_;
277   int max_send_message_size_;
278   std::vector<std::unique_ptr<ServerBuilderOption>> options_;
279   std::vector<std::unique_ptr<NamedService>> services_;
280   std::vector<Port> ports_;
281 
282   SyncServerSettings sync_server_settings_;
283 
284   /// List of completion queues added via \a AddCompletionQueue method.
285   std::vector<ServerCompletionQueue*> cqs_;
286 
287   std::shared_ptr<ServerCredentials> creds_;
288   std::vector<std::unique_ptr<ServerBuilderPlugin>> plugins_;
289   grpc_resource_quota* resource_quota_;
290   AsyncGenericService* generic_service_;
291   struct {
292     bool is_set;
293     grpc_compression_level level;
294   } maybe_default_compression_level_;
295   struct {
296     bool is_set;
297     grpc_compression_algorithm algorithm;
298   } maybe_default_compression_algorithm_;
299   uint32_t enabled_compression_algorithms_bitset_;
300 };
301 
302 }  // namespace grpc
303 
304 #endif  // GRPCPP_SERVER_BUILDER_H
305