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 #include <grpcpp/server_builder.h>
20
21 #include <grpc/support/cpu.h>
22 #include <grpc/support/log.h>
23 #include <grpcpp/impl/service_type.h>
24 #include <grpcpp/resource_quota.h>
25 #include <grpcpp/server.h>
26
27 #include <utility>
28
29 #include "src/core/lib/channel/channel_args.h"
30 #include "src/core/lib/gpr/string.h"
31 #include "src/core/lib/gpr/useful.h"
32 #include "src/cpp/server/external_connection_acceptor_impl.h"
33 #include "src/cpp/server/thread_pool_interface.h"
34
35 namespace grpc {
36
37 static std::vector<std::unique_ptr<ServerBuilderPlugin> (*)()>*
38 g_plugin_factory_list;
39 static gpr_once once_init_plugin_list = GPR_ONCE_INIT;
40
do_plugin_list_init(void)41 static void do_plugin_list_init(void) {
42 g_plugin_factory_list =
43 new std::vector<std::unique_ptr<ServerBuilderPlugin> (*)()>();
44 }
45
ServerBuilder()46 ServerBuilder::ServerBuilder()
47 : max_receive_message_size_(INT_MIN),
48 max_send_message_size_(INT_MIN),
49 sync_server_settings_(SyncServerSettings()),
50 resource_quota_(nullptr) {
51 gpr_once_init(&once_init_plugin_list, do_plugin_list_init);
52 for (const auto& value : *g_plugin_factory_list) {
53 plugins_.emplace_back(value());
54 }
55
56 // all compression algorithms enabled by default.
57 enabled_compression_algorithms_bitset_ =
58 (1u << GRPC_COMPRESS_ALGORITHMS_COUNT) - 1;
59 memset(&maybe_default_compression_level_, 0,
60 sizeof(maybe_default_compression_level_));
61 memset(&maybe_default_compression_algorithm_, 0,
62 sizeof(maybe_default_compression_algorithm_));
63 }
64
~ServerBuilder()65 ServerBuilder::~ServerBuilder() {
66 if (resource_quota_ != nullptr) {
67 grpc_resource_quota_unref(resource_quota_);
68 }
69 }
70
AddCompletionQueue(bool is_frequently_polled)71 std::unique_ptr<grpc::ServerCompletionQueue> ServerBuilder::AddCompletionQueue(
72 bool is_frequently_polled) {
73 grpc::ServerCompletionQueue* cq = new grpc::ServerCompletionQueue(
74 GRPC_CQ_NEXT,
75 is_frequently_polled ? GRPC_CQ_DEFAULT_POLLING : GRPC_CQ_NON_LISTENING,
76 nullptr);
77 cqs_.push_back(cq);
78 return std::unique_ptr<grpc::ServerCompletionQueue>(cq);
79 }
80
RegisterService(Service * service)81 ServerBuilder& ServerBuilder::RegisterService(Service* service) {
82 services_.emplace_back(new NamedService(service));
83 return *this;
84 }
85
RegisterService(const std::string & host,Service * service)86 ServerBuilder& ServerBuilder::RegisterService(const std::string& host,
87 Service* service) {
88 services_.emplace_back(new NamedService(host, service));
89 return *this;
90 }
91
RegisterAsyncGenericService(AsyncGenericService * service)92 ServerBuilder& ServerBuilder::RegisterAsyncGenericService(
93 AsyncGenericService* service) {
94 if (generic_service_ || callback_generic_service_) {
95 gpr_log(GPR_ERROR,
96 "Adding multiple generic services is unsupported for now. "
97 "Dropping the service %p",
98 service);
99 } else {
100 generic_service_ = service;
101 }
102 return *this;
103 }
104
105 #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
RegisterCallbackGenericService(CallbackGenericService * service)106 ServerBuilder& ServerBuilder::RegisterCallbackGenericService(
107 CallbackGenericService* service) {
108 if (generic_service_ || callback_generic_service_) {
109 gpr_log(GPR_ERROR,
110 "Adding multiple generic services is unsupported for now. "
111 "Dropping the service %p",
112 (void*)service);
113 } else {
114 callback_generic_service_ = service;
115 }
116 return *this;
117 }
118 #else
RegisterCallbackGenericService(experimental::CallbackGenericService * service)119 ServerBuilder& ServerBuilder::experimental_type::RegisterCallbackGenericService(
120 experimental::CallbackGenericService* service) {
121 if (builder_->generic_service_ || builder_->callback_generic_service_) {
122 gpr_log(GPR_ERROR,
123 "Adding multiple generic services is unsupported for now. "
124 "Dropping the service %p",
125 service);
126 } else {
127 builder_->callback_generic_service_ = service;
128 }
129 return *builder_;
130 }
131 #endif
132
SetContextAllocator(std::unique_ptr<grpc::ContextAllocator> context_allocator)133 ServerBuilder& ServerBuilder::experimental_type::SetContextAllocator(
134 std::unique_ptr<grpc::ContextAllocator> context_allocator) {
135 builder_->context_allocator_ = std::move(context_allocator);
136 return *builder_;
137 }
138
139 std::unique_ptr<grpc::experimental::ExternalConnectionAcceptor>
AddExternalConnectionAcceptor(experimental_type::ExternalConnectionType type,std::shared_ptr<ServerCredentials> creds)140 ServerBuilder::experimental_type::AddExternalConnectionAcceptor(
141 experimental_type::ExternalConnectionType type,
142 std::shared_ptr<ServerCredentials> creds) {
143 std::string name_prefix("external:");
144 char count_str[GPR_LTOA_MIN_BUFSIZE];
145 gpr_ltoa(static_cast<long>(builder_->acceptors_.size()), count_str);
146 builder_->acceptors_.emplace_back(
147 std::make_shared<grpc::internal::ExternalConnectionAcceptorImpl>(
148 name_prefix.append(count_str), type, creds));
149 return builder_->acceptors_.back()->GetAcceptor();
150 }
151
SetOption(std::unique_ptr<ServerBuilderOption> option)152 ServerBuilder& ServerBuilder::SetOption(
153 std::unique_ptr<ServerBuilderOption> option) {
154 options_.push_back(std::move(option));
155 return *this;
156 }
157
SetSyncServerOption(ServerBuilder::SyncServerOption option,int val)158 ServerBuilder& ServerBuilder::SetSyncServerOption(
159 ServerBuilder::SyncServerOption option, int val) {
160 switch (option) {
161 case NUM_CQS:
162 sync_server_settings_.num_cqs = val;
163 break;
164 case MIN_POLLERS:
165 sync_server_settings_.min_pollers = val;
166 break;
167 case MAX_POLLERS:
168 sync_server_settings_.max_pollers = val;
169 break;
170 case CQ_TIMEOUT_MSEC:
171 sync_server_settings_.cq_timeout_msec = val;
172 break;
173 }
174 return *this;
175 }
176
SetCompressionAlgorithmSupportStatus(grpc_compression_algorithm algorithm,bool enabled)177 ServerBuilder& ServerBuilder::SetCompressionAlgorithmSupportStatus(
178 grpc_compression_algorithm algorithm, bool enabled) {
179 if (enabled) {
180 GPR_BITSET(&enabled_compression_algorithms_bitset_, algorithm);
181 } else {
182 GPR_BITCLEAR(&enabled_compression_algorithms_bitset_, algorithm);
183 }
184 return *this;
185 }
186
SetDefaultCompressionLevel(grpc_compression_level level)187 ServerBuilder& ServerBuilder::SetDefaultCompressionLevel(
188 grpc_compression_level level) {
189 maybe_default_compression_level_.is_set = true;
190 maybe_default_compression_level_.level = level;
191 return *this;
192 }
193
SetDefaultCompressionAlgorithm(grpc_compression_algorithm algorithm)194 ServerBuilder& ServerBuilder::SetDefaultCompressionAlgorithm(
195 grpc_compression_algorithm algorithm) {
196 maybe_default_compression_algorithm_.is_set = true;
197 maybe_default_compression_algorithm_.algorithm = algorithm;
198 return *this;
199 }
200
SetResourceQuota(const grpc::ResourceQuota & resource_quota)201 ServerBuilder& ServerBuilder::SetResourceQuota(
202 const grpc::ResourceQuota& resource_quota) {
203 if (resource_quota_ != nullptr) {
204 grpc_resource_quota_unref(resource_quota_);
205 }
206 resource_quota_ = resource_quota.c_resource_quota();
207 grpc_resource_quota_ref(resource_quota_);
208 return *this;
209 }
210
AddListeningPort(const std::string & addr_uri,std::shared_ptr<ServerCredentials> creds,int * selected_port)211 ServerBuilder& ServerBuilder::AddListeningPort(
212 const std::string& addr_uri, std::shared_ptr<ServerCredentials> creds,
213 int* selected_port) {
214 const std::string uri_scheme = "dns:";
215 std::string addr = addr_uri;
216 if (addr_uri.compare(0, uri_scheme.size(), uri_scheme) == 0) {
217 size_t pos = uri_scheme.size();
218 while (addr_uri[pos] == '/') ++pos; // Skip slashes.
219 addr = addr_uri.substr(pos);
220 }
221 Port port = {addr, std::move(creds), selected_port};
222 ports_.push_back(port);
223 return *this;
224 }
225
BuildAndStart()226 std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() {
227 grpc::ChannelArguments args;
228 if (max_receive_message_size_ >= -1) {
229 args.SetInt(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH, max_receive_message_size_);
230 }
231 if (max_send_message_size_ >= -1) {
232 args.SetInt(GRPC_ARG_MAX_SEND_MESSAGE_LENGTH, max_send_message_size_);
233 }
234 for (const auto& option : options_) {
235 option->UpdateArguments(&args);
236 option->UpdatePlugins(&plugins_);
237 }
238 args.SetInt(GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET,
239 enabled_compression_algorithms_bitset_);
240 if (maybe_default_compression_level_.is_set) {
241 args.SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_LEVEL,
242 maybe_default_compression_level_.level);
243 }
244 if (maybe_default_compression_algorithm_.is_set) {
245 args.SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM,
246 maybe_default_compression_algorithm_.algorithm);
247 }
248
249 if (resource_quota_ != nullptr) {
250 args.SetPointerWithVtable(GRPC_ARG_RESOURCE_QUOTA, resource_quota_,
251 grpc_resource_quota_arg_vtable());
252 }
253
254 for (const auto& plugin : plugins_) {
255 plugin->UpdateServerBuilder(this);
256 plugin->UpdateChannelArguments(&args);
257 }
258
259 // == Determine if the server has any syncrhonous methods ==
260 bool has_sync_methods = false;
261 for (const auto& value : services_) {
262 if (value->service->has_synchronous_methods()) {
263 has_sync_methods = true;
264 break;
265 }
266 }
267
268 if (!has_sync_methods) {
269 for (const auto& value : plugins_) {
270 if (value->has_sync_methods()) {
271 has_sync_methods = true;
272 break;
273 }
274 }
275 }
276
277 // If this is a Sync server, i.e a server expositing sync API, then the server
278 // needs to create some completion queues to listen for incoming requests.
279 // 'sync_server_cqs' are those internal completion queues.
280 //
281 // This is different from the completion queues added to the server via
282 // ServerBuilder's AddCompletionQueue() method (those completion queues
283 // are in 'cqs_' member variable of ServerBuilder object)
284 std::shared_ptr<std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>>
285 sync_server_cqs(
286 std::make_shared<
287 std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>>());
288
289 bool has_frequently_polled_cqs = false;
290 for (const auto& cq : cqs_) {
291 if (cq->IsFrequentlyPolled()) {
292 has_frequently_polled_cqs = true;
293 break;
294 }
295 }
296
297 // == Determine if the server has any callback methods ==
298 bool has_callback_methods = false;
299 for (const auto& service : services_) {
300 if (service->service->has_callback_methods()) {
301 has_callback_methods = true;
302 has_frequently_polled_cqs = true;
303 break;
304 }
305 }
306
307 const bool is_hybrid_server = has_sync_methods && has_frequently_polled_cqs;
308
309 if (has_sync_methods) {
310 grpc_cq_polling_type polling_type =
311 is_hybrid_server ? GRPC_CQ_NON_POLLING : GRPC_CQ_DEFAULT_POLLING;
312
313 // Create completion queues to listen to incoming rpc requests
314 for (int i = 0; i < sync_server_settings_.num_cqs; i++) {
315 sync_server_cqs->emplace_back(
316 new grpc::ServerCompletionQueue(GRPC_CQ_NEXT, polling_type, nullptr));
317 }
318 }
319
320 // TODO(vjpai): Add a section here for plugins once they can support callback
321 // methods
322
323 if (has_sync_methods) {
324 // This is a Sync server
325 gpr_log(GPR_INFO,
326 "Synchronous server. Num CQs: %d, Min pollers: %d, Max Pollers: "
327 "%d, CQ timeout (msec): %d",
328 sync_server_settings_.num_cqs, sync_server_settings_.min_pollers,
329 sync_server_settings_.max_pollers,
330 sync_server_settings_.cq_timeout_msec);
331 }
332
333 if (has_callback_methods) {
334 gpr_log(GPR_INFO, "Callback server.");
335 }
336
337 std::unique_ptr<grpc::Server> server(new grpc::Server(
338 &args, sync_server_cqs, sync_server_settings_.min_pollers,
339 sync_server_settings_.max_pollers, sync_server_settings_.cq_timeout_msec,
340 std::move(acceptors_), server_config_fetcher_, resource_quota_,
341 std::move(interceptor_creators_)));
342
343 ServerInitializer* initializer = server->initializer();
344
345 // Register all the completion queues with the server. i.e
346 // 1. sync_server_cqs: internal completion queues created IF this is a sync
347 // server
348 // 2. cqs_: Completion queues added via AddCompletionQueue() call
349
350 for (const auto& cq : *sync_server_cqs) {
351 grpc_server_register_completion_queue(server->server_, cq->cq(), nullptr);
352 has_frequently_polled_cqs = true;
353 }
354
355 if (has_callback_methods || callback_generic_service_ != nullptr) {
356 auto* cq = server->CallbackCQ();
357 grpc_server_register_completion_queue(server->server_, cq->cq(), nullptr);
358 }
359
360 // cqs_ contains the completion queue added by calling the ServerBuilder's
361 // AddCompletionQueue() API. Some of them may not be frequently polled (i.e by
362 // calling Next() or AsyncNext()) and hence are not safe to be used for
363 // listening to incoming channels. Such completion queues must be registered
364 // as non-listening queues. In debug mode, these should have their server list
365 // tracked since these are provided the user and must be Shutdown by the user
366 // after the server is shutdown.
367 for (const auto& cq : cqs_) {
368 grpc_server_register_completion_queue(server->server_, cq->cq(), nullptr);
369 cq->RegisterServer(server.get());
370 }
371
372 if (!has_frequently_polled_cqs) {
373 gpr_log(GPR_ERROR,
374 "At least one of the completion queues must be frequently polled");
375 return nullptr;
376 }
377
378 #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
379 server->RegisterContextAllocator(std::move(context_allocator_));
380 #else
381 server->experimental_registration()->RegisterContextAllocator(
382 std::move(context_allocator_));
383 #endif
384
385 for (const auto& value : services_) {
386 if (!server->RegisterService(value->host.get(), value->service)) {
387 return nullptr;
388 }
389 }
390
391 for (const auto& value : plugins_) {
392 value->InitServer(initializer);
393 }
394
395 if (generic_service_) {
396 server->RegisterAsyncGenericService(generic_service_);
397 } else if (callback_generic_service_) {
398 server->RegisterCallbackGenericService(callback_generic_service_);
399 } else {
400 for (const auto& value : services_) {
401 if (value->service->has_generic_methods()) {
402 gpr_log(GPR_ERROR,
403 "Some methods were marked generic but there is no "
404 "generic service registered.");
405 return nullptr;
406 }
407 }
408 }
409
410 bool added_port = false;
411 for (auto& port : ports_) {
412 int r = server->AddListeningPort(port.addr, port.creds.get());
413 if (!r) {
414 if (added_port) server->Shutdown();
415 return nullptr;
416 }
417 added_port = true;
418 if (port.selected_port != nullptr) {
419 *port.selected_port = r;
420 }
421 }
422
423 auto cqs_data = cqs_.empty() ? nullptr : &cqs_[0];
424 server->Start(cqs_data, cqs_.size());
425
426 for (const auto& value : plugins_) {
427 value->Finish(initializer);
428 }
429
430 return server;
431 }
432
InternalAddPluginFactory(std::unique_ptr<ServerBuilderPlugin> (* CreatePlugin)())433 void ServerBuilder::InternalAddPluginFactory(
434 std::unique_ptr<ServerBuilderPlugin> (*CreatePlugin)()) {
435 gpr_once_init(&once_init_plugin_list, do_plugin_list_init);
436 (*g_plugin_factory_list).push_back(CreatePlugin);
437 }
438
EnableWorkaround(grpc_workaround_list id)439 ServerBuilder& ServerBuilder::EnableWorkaround(grpc_workaround_list id) {
440 switch (id) {
441 case GRPC_WORKAROUND_ID_CRONET_COMPRESSION:
442 return AddChannelArgument(GRPC_ARG_WORKAROUND_CRONET_COMPRESSION, 1);
443 default:
444 gpr_log(GPR_ERROR, "Workaround %u does not exist or is obsolete.", id);
445 return *this;
446 }
447 }
448
449 } // namespace grpc
450