| 1 |
/* |
| 2 |
* Copyright 2015 gRPC authors. |
| 3 |
* |
| 4 |
* Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
* you may not use this file except in compliance with the License. |
| 6 |
* You may obtain a copy of the License at |
| 7 |
* |
| 8 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
* |
| 10 |
* Unless required by applicable law or agreed to in writing, software |
| 11 |
* distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
* See the License for the specific language governing permissions and |
| 14 |
* limitations under the License. |
| 15 |
* |
| 16 |
*/ |
| 17 |
|
| 18 |
#include <limits.h> |
| 19 |
#include <string.h> |
| 20 |
|
| 21 |
#include <algorithm> |
| 22 |
#include <atomic> |
| 23 |
#include <cstdlib> |
| 24 |
#include <memory> |
| 25 |
#include <new> |
| 26 |
#include <sstream> |
| 27 |
#include <string> |
| 28 |
#include <utility> |
| 29 |
#include <vector> |
| 30 |
|
| 31 |
#include "absl/status/status.h" |
| 32 |
|
| 33 |
#include <grpc/byte_buffer.h> |
| 34 |
#include <grpc/grpc.h> |
| 35 |
#include <grpc/impl/codegen/gpr_types.h> |
| 36 |
#include <grpc/impl/codegen/grpc_types.h> |
| 37 |
#include <grpc/slice.h> |
| 38 |
#include <grpc/support/log.h> |
| 39 |
#include <grpc/support/sync.h> |
| 40 |
#include <grpc/support/time.h> |
| 41 |
#include <grpcpp/channel.h> |
| 42 |
#include <grpcpp/completion_queue.h> |
| 43 |
#include <grpcpp/generic/async_generic_service.h> |
| 44 |
#include <grpcpp/health_check_service_interface.h> |
| 45 |
#include <grpcpp/impl/call.h> |
| 46 |
#include <grpcpp/impl/call_op_set.h> |
| 47 |
#include <grpcpp/impl/call_op_set_interface.h> |
| 48 |
#include <grpcpp/impl/codegen/completion_queue_tag.h> |
| 49 |
#include <grpcpp/impl/codegen/interceptor_common.h> |
| 50 |
#include <grpcpp/impl/codegen/metadata_map.h> |
| 51 |
#include <grpcpp/impl/codegen/server_callback_handlers.h> |
| 52 |
#include <grpcpp/impl/codegen/server_interface.h> |
| 53 |
#include <grpcpp/impl/codegen/sync.h> |
| 54 |
#include <grpcpp/impl/grpc_library.h> |
| 55 |
#include <grpcpp/impl/rpc_method.h> |
| 56 |
#include <grpcpp/impl/rpc_service_method.h> |
| 57 |
#include <grpcpp/impl/server_initializer.h> |
| 58 |
#include <grpcpp/impl/service_type.h> |
| 59 |
#include <grpcpp/security/server_credentials.h> |
| 60 |
#include <grpcpp/server.h> |
| 61 |
#include <grpcpp/server_context.h> |
| 62 |
#include <grpcpp/support/channel_arguments.h> |
| 63 |
#include <grpcpp/support/client_interceptor.h> |
| 64 |
#include <grpcpp/support/interceptor.h> |
| 65 |
#include <grpcpp/support/method_handler.h> |
| 66 |
#include <grpcpp/support/server_interceptor.h> |
| 67 |
#include <grpcpp/support/slice.h> |
| 68 |
#include <grpcpp/support/status.h> |
| 69 |
|
| 70 |
#include "src/core/ext/transport/inproc/inproc_transport.h" |
| 71 |
#include "src/core/lib/gprpp/manual_constructor.h" |
| 72 |
#include "src/core/lib/iomgr/exec_ctx.h" |
| 73 |
#include "src/core/lib/iomgr/iomgr.h" |
| 74 |
#include "src/core/lib/resource_quota/api.h" |
| 75 |
#include "src/core/lib/surface/completion_queue.h" |
| 76 |
#include "src/core/lib/surface/server.h" |
| 77 |
#include "src/cpp/client/create_channel_internal.h" |
| 78 |
#include "src/cpp/server/external_connection_acceptor_impl.h" |
| 79 |
#include "src/cpp/server/health/default_health_check_service.h" |
| 80 |
#include "src/cpp/thread_manager/thread_manager.h" |
| 81 |
|
| 82 |
namespace grpc { |
| 83 |
namespace { |
| 84 |
|
| 85 |
// The default value for maximum number of threads that can be created in the |
| 86 |
// sync server. This value of INT_MAX is chosen to match the default behavior if |
| 87 |
// no ResourceQuota is set. To modify the max number of threads in a sync |
| 88 |
// server, pass a custom ResourceQuota object (with the desired number of |
| 89 |
// max-threads set) to the server builder. |
| 90 |
#define DEFAULT_MAX_SYNC_SERVER_THREADS INT_MAX |
| 91 |
|
| 92 |
// Give a useful status error message if the resource is exhausted specifically |
| 93 |
// because the server threadpool is full. |
| 94 |
const char* kServerThreadpoolExhausted = "Server Threadpool Exhausted"; |
| 95 |
|
| 96 |
// Although we might like to give a useful status error message on unimplemented |
| 97 |
// RPCs, it's not always possible since that also would need to be added across |
| 98 |
// languages and isn't actually required by the spec. |
| 99 |
const char* kUnknownRpcMethod = ""; |
| 100 |
|
| 101 |
class DefaultGlobalCallbacks final : public Server::GlobalCallbacks { |
| 102 |
public: |
| 103 |
~DefaultGlobalCallbacks() override {} |
| 104 |
void PreSynchronousRequest(ServerContext* /*context*/) override {} |
| 105 |
void PostSynchronousRequest(ServerContext* /*context*/) override {} |
| 106 |
}; |
| 107 |
|
| 108 |
std::shared_ptr<Server::GlobalCallbacks> g_callbacks = nullptr; |
| 109 |
gpr_once g_once_init_callbacks = GPR_ONCE_INIT; |
| 110 |
|
| 111 |
void InitGlobalCallbacks() { |
| 112 |
if (!g_callbacks) { |
| 113 |
g_callbacks.reset(new DefaultGlobalCallbacks()); |
| 114 |
} |
| 115 |
} |
| 116 |
|
| 117 |
class ShutdownTag : public internal::CompletionQueueTag { |
| 118 |
public: |
| 119 |
bool FinalizeResult(void** /*tag*/, bool* /*status*/) override { |
| 120 |
return false; |
| 121 |
} |
| 122 |
}; |
| 123 |
|
| 124 |
class PhonyTag : public internal::CompletionQueueTag { |
| 125 |
public: |
| 126 |
bool FinalizeResult(void** /*tag*/, bool* /*status*/) override { |
| 127 |
return true; |
| 128 |
} |
| 129 |
}; |
| 130 |
|
| 131 |
class UnimplementedAsyncRequestContext { |
| 132 |
protected: |
| 133 |
UnimplementedAsyncRequestContext() : generic_stream_(&server_context_) {} |
| 134 |
|
| 135 |
GenericServerContext server_context_; |
| 136 |
GenericServerAsyncReaderWriter generic_stream_; |
| 137 |
}; |
| 138 |
|
| 139 |
} // namespace |
| 140 |
|
| 141 |
ServerInterface::BaseAsyncRequest::BaseAsyncRequest( |
| 142 |
ServerInterface* server, ServerContext* context, |
| 143 |
internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, |
| 144 |
ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize) |
| 145 |
: server_(server), |
| 146 |
context_(context), |
| 147 |
stream_(stream), |
| 148 |
call_cq_(call_cq), |
| 149 |
notification_cq_(notification_cq), |
| 150 |
tag_(tag), |
| 151 |
delete_on_finalize_(delete_on_finalize), |
| 152 |
call_(nullptr), |
| 153 |
done_intercepting_(false) { |
| 154 |
/* Set up interception state partially for the receive ops. call_wrapper_ is |
| 155 |
* not filled at this point, but it will be filled before the interceptors are |
| 156 |
* run. */ |
| 157 |
interceptor_methods_.SetCall(&call_wrapper_); |
| 158 |
interceptor_methods_.SetReverse(); |
| 159 |
call_cq_->RegisterAvalanching(); // This op will trigger more ops |
| 160 |
} |
| 161 |
|
| 162 |
ServerInterface::BaseAsyncRequest::~BaseAsyncRequest() { |
| 163 |
call_cq_->CompleteAvalanching(); |
| 164 |
} |
| 165 |
|
| 166 |
bool ServerInterface::BaseAsyncRequest::FinalizeResult(void** tag, |
| 167 |
bool* status) { |
| 168 |
if (done_intercepting_) { |
| 169 |
*tag = tag_; |
| 170 |
if (delete_on_finalize_) { |
| 171 |
delete this; |
| 172 |
} |
| 173 |
return true; |
| 174 |
} |
| 175 |
context_->set_call(call_); |
| 176 |
context_->cq_ = call_cq_; |
| 177 |
if (call_wrapper_.call() == nullptr) { |
| 178 |
// Fill it since it is empty. |
| 179 |
call_wrapper_ = internal::Call( |
| 180 |
call_, server_, call_cq_, server_->max_receive_message_size(), nullptr); |
| 181 |
} |
| 182 |
|
| 183 |
// just the pointers inside call are copied here |
| 184 |
stream_->BindCall(&call_wrapper_); |
| 185 |
|
| 186 |
if (*status && call_ && call_wrapper_.server_rpc_info()) { |
| 187 |
done_intercepting_ = true; |
| 188 |
// Set interception point for RECV INITIAL METADATA |
| 189 |
interceptor_methods_.AddInterceptionHookPoint( |
| 190 |
experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA); |
| 191 |
interceptor_methods_.SetRecvInitialMetadata(&context_->client_metadata_); |
| 192 |
if (interceptor_methods_.RunInterceptors( |
| 193 |
[this]() { ContinueFinalizeResultAfterInterception(); })) { |
| 194 |
// There are no interceptors to run. Continue |
| 195 |
} else { |
| 196 |
// There were interceptors to be run, so |
| 197 |
// ContinueFinalizeResultAfterInterception will be run when interceptors |
| 198 |
// are done. |
| 199 |
return false; |
| 200 |
} |
| 201 |
} |
| 202 |
if (*status && call_) { |
| 203 |
context_->BeginCompletionOp(&call_wrapper_, nullptr, nullptr); |
| 204 |
} |
| 205 |
*tag = tag_; |
| 206 |
if (delete_on_finalize_) { |
| 207 |
delete this; |
| 208 |
} |
| 209 |
return true; |
| 210 |
} |
| 211 |
|
| 212 |
void ServerInterface::BaseAsyncRequest:: |
| 213 |
ContinueFinalizeResultAfterInterception() { |
| 214 |
context_->BeginCompletionOp(&call_wrapper_, nullptr, nullptr); |
| 215 |
// Queue a tag which will be returned immediately |
| 216 |
grpc_core::ExecCtx exec_ctx; |
| 217 |
grpc_cq_begin_op(notification_cq_->cq(), this); |
| 218 |
grpc_cq_end_op( |
| 219 |
notification_cq_->cq(), this, absl::OkStatus(), |
| 220 |
[](void* /*arg*/, grpc_cq_completion* completion) { delete completion; }, |
| 221 |
nullptr, new grpc_cq_completion()); |
| 222 |
} |
| 223 |
|
| 224 |
ServerInterface::RegisteredAsyncRequest::RegisteredAsyncRequest( |
| 225 |
ServerInterface* server, ServerContext* context, |
| 226 |
internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, |
| 227 |
ServerCompletionQueue* notification_cq, void* tag, const char* name, |
| 228 |
internal::RpcMethod::RpcType type) |
| 229 |
: BaseAsyncRequest(server, context, stream, call_cq, notification_cq, tag, |
| 230 |
true), |
| 231 |
name_(name), |
| 232 |
type_(type) {} |
| 233 |
|
| 234 |
void ServerInterface::RegisteredAsyncRequest::IssueRequest( |
| 235 |
void* registered_method, grpc_byte_buffer** payload, |
| 236 |
ServerCompletionQueue* notification_cq) { |
| 237 |
// The following call_start_batch is internally-generated so no need for an |
| 238 |
// explanatory log on failure. |
| 239 |
GPR_ASSERT(grpc_server_request_registered_call( |
| 240 |
server_->server(), registered_method, &call_, |
| 241 |
&context_->deadline_, context_->client_metadata_.arr(), |
| 242 |
payload, call_cq_->cq(), notification_cq->cq(), |
| 243 |
this) == GRPC_CALL_OK); |
| 244 |
} |
| 245 |
|
| 246 |
ServerInterface::GenericAsyncRequest::GenericAsyncRequest( |
| 247 |
ServerInterface* server, GenericServerContext* context, |
| 248 |
internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, |
| 249 |
ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize) |
| 250 |
: BaseAsyncRequest(server, context, stream, call_cq, notification_cq, tag, |
| 251 |
delete_on_finalize) { |
| 252 |
grpc_call_details_init(&call_details_); |
| 253 |
GPR_ASSERT(notification_cq); |
| 254 |
GPR_ASSERT(call_cq); |
| 255 |
// The following call_start_batch is internally-generated so no need for an |
| 256 |
// explanatory log on failure. |
| 257 |
GPR_ASSERT(grpc_server_request_call(server->server(), &call_, &call_details_, |
| 258 |
context->client_metadata_.arr(), |
| 259 |
call_cq->cq(), notification_cq->cq(), |
| 260 |
this) == GRPC_CALL_OK); |
| 261 |
} |
| 262 |
|
| 263 |
bool ServerInterface::GenericAsyncRequest::FinalizeResult(void** tag, |
| 264 |
bool* status) { |
| 265 |
// If we are done intercepting, there is nothing more for us to do |
| 266 |
if (done_intercepting_) { |
| 267 |
return BaseAsyncRequest::FinalizeResult(tag, status); |
| 268 |
} |
| 269 |
// TODO(yangg) remove the copy here. |
| 270 |
if (*status) { |
| 271 |
static_cast<GenericServerContext*>(context_)->method_ = |
| 272 |
StringFromCopiedSlice(call_details_.method); |
| 273 |
static_cast<GenericServerContext*>(context_)->host_ = |
| 274 |
StringFromCopiedSlice(call_details_.host); |
| 275 |
context_->deadline_ = call_details_.deadline; |
| 276 |
} |
| 277 |
grpc_slice_unref(call_details_.method); |
| 278 |
grpc_slice_unref(call_details_.host); |
| 279 |
call_wrapper_ = internal::Call( |
| 280 |
call_, server_, call_cq_, server_->max_receive_message_size(), |
| 281 |
context_->set_server_rpc_info( |
| 282 |
static_cast<GenericServerContext*>(context_)->method_.c_str(), |
| 283 |
internal::RpcMethod::BIDI_STREAMING, |
| 284 |
*server_->interceptor_creators())); |
| 285 |
return BaseAsyncRequest::FinalizeResult(tag, status); |
| 286 |
} |
| 287 |
|
| 288 |
namespace { |
| 289 |
class ShutdownCallback : public grpc_completion_queue_functor { |
| 290 |
public: |
| 291 |
ShutdownCallback() { |
| 292 |
functor_run = &ShutdownCallback::Run; |
| 293 |
// Set inlineable to true since this callback is trivial and thus does not |
| 294 |
// need to be run from the executor (triggering a thread hop). This should |
| 295 |
// only be used by internal callbacks like this and not by user application |
| 296 |
// code. |
| 297 |
inlineable = true; |
| 298 |
} |
| 299 |
// TakeCQ takes ownership of the cq into the shutdown callback |
| 300 |
// so that the shutdown callback will be responsible for destroying it |
| 301 |
void TakeCQ(CompletionQueue* cq) { cq_ = cq; } |
| 302 |
|
| 303 |
// The Run function will get invoked by the completion queue library |
| 304 |
// when the shutdown is actually complete |
| 305 |
static void Run(grpc_completion_queue_functor* cb, int) { |
| 306 |
auto* callback = static_cast<ShutdownCallback*>(cb); |
| 307 |
delete callback->cq_; |
| 308 |
delete callback; |
| 309 |
} |
| 310 |
|
| 311 |
private: |
| 312 |
CompletionQueue* cq_ = nullptr; |
| 313 |
}; |
| 314 |
} // namespace |
| 315 |
|
| 316 |
/// Use private inheritance rather than composition only to establish order |
| 317 |
/// of construction, since the public base class should be constructed after the |
| 318 |
/// elements belonging to the private base class are constructed. This is not |
| 319 |
/// possible using true composition. |
| 320 |
class Server::UnimplementedAsyncRequest final |
| 321 |
: private grpc::UnimplementedAsyncRequestContext, |
| 322 |
public GenericAsyncRequest { |
| 323 |
public: |
| 324 |
UnimplementedAsyncRequest(ServerInterface* server, |
| 325 |
grpc::ServerCompletionQueue* cq) |
| 326 |
: GenericAsyncRequest(server, &server_context_, &generic_stream_, cq, cq, |
| 327 |
nullptr, false) {} |
| 328 |
|
| 329 |
bool FinalizeResult(void** tag, bool* status) override; |
| 330 |
|
| 331 |
grpc::ServerContext* context() { return &server_context_; } |
| 332 |
grpc::GenericServerAsyncReaderWriter* stream() { return &generic_stream_; } |
| 333 |
}; |
| 334 |
|
| 335 |
/// UnimplementedAsyncResponse should not post user-visible completions to the |
| 336 |
/// C++ completion queue, but is generated as a CQ event by the core |
| 337 |
class Server::UnimplementedAsyncResponse final |
| 338 |
: public grpc::internal::CallOpSet< |
| 339 |
grpc::internal::CallOpSendInitialMetadata, |
| 340 |
grpc::internal::CallOpServerSendStatus> { |
| 341 |
public: |
| 342 |
explicit UnimplementedAsyncResponse(UnimplementedAsyncRequest* request); |
| 343 |
~UnimplementedAsyncResponse() override { delete request_; } |
| 344 |
|
| 345 |
bool FinalizeResult(void** tag, bool* status) override { |
| 346 |
if (grpc::internal::CallOpSet< |
| 347 |
grpc::internal::CallOpSendInitialMetadata, |
| 348 |
grpc::internal::CallOpServerSendStatus>::FinalizeResult(tag, |
| 349 |
status)) { |
| 350 |
delete this; |
| 351 |
} else { |
| 352 |
// The tag was swallowed due to interception. We will see it again. |
| 353 |
} |
| 354 |
return false; |
| 355 |
} |
| 356 |
|
| 357 |
private: |
| 358 |
UnimplementedAsyncRequest* const request_; |
| 359 |
}; |
| 360 |
|
| 361 |
class Server::SyncRequest final : public grpc::internal::CompletionQueueTag { |
| 362 |
public: |
| 363 |
SyncRequest(Server* server, grpc::internal::RpcServiceMethod* method, |
| 364 |
grpc_core::Server::RegisteredCallAllocation* data) |
| 365 |
: SyncRequest(server, method) { |
| 366 |
CommonSetup(data); |
| 367 |
data->deadline = &deadline_; |
| 368 |
data->optional_payload = has_request_payload_ ? &request_payload_ : nullptr; |
| 369 |
} |
| 370 |
|
| 371 |
SyncRequest(Server* server, grpc::internal::RpcServiceMethod* method, |
| 372 |
grpc_core::Server::BatchCallAllocation* data) |
| 373 |
: SyncRequest(server, method) { |
| 374 |
CommonSetup(data); |
| 375 |
call_details_ = new grpc_call_details; |
| 376 |
grpc_call_details_init(call_details_); |
| 377 |
data->details = call_details_; |
| 378 |
} |
| 379 |
|
| 380 |
~SyncRequest() override { |
| 381 |
// The destructor should only cleanup those objects created in the |
| 382 |
// constructor, since some paths may or may not actually go through the |
| 383 |
// Run stage where other objects are allocated. |
| 384 |
if (has_request_payload_ && request_payload_) { |
| 385 |
grpc_byte_buffer_destroy(request_payload_); |
| 386 |
} |
| 387 |
if (call_details_ != nullptr) { |
| 388 |
grpc_call_details_destroy(call_details_); |
| 389 |
delete call_details_; |
| 390 |
} |
| 391 |
grpc_metadata_array_destroy(&request_metadata_); |
| 392 |
server_->UnrefWithPossibleNotify(); |
| 393 |
} |
| 394 |
|
| 395 |
bool FinalizeResult(void** /*tag*/, bool* status) override { |
| 396 |
if (!*status) { |
| 397 |
delete this; |
| 398 |
return false; |
| 399 |
} |
| 400 |
if (call_details_) { |
| 401 |
deadline_ = call_details_->deadline; |
| 402 |
} |
| 403 |
return true; |
| 404 |
} |
| 405 |
|
| 406 |
void Run(const std::shared_ptr<GlobalCallbacks>& global_callbacks, |
| 407 |
bool resources) { |
| 408 |
ctx_.Init(deadline_, &request_metadata_); |
| 409 |
wrapped_call_.Init( |
| 410 |
call_, server_, &cq_, server_->max_receive_message_size(), |
| 411 |
ctx_->ctx.set_server_rpc_info(method_->name(), method_->method_type(), |
| 412 |
server_->interceptor_creators_)); |
| 413 |
ctx_->ctx.set_call(call_); |
| 414 |
ctx_->ctx.cq_ = &cq_; |
| 415 |
request_metadata_.count = 0; |
| 416 |
|
| 417 |
global_callbacks_ = global_callbacks; |
| 418 |
resources_ = resources; |
| 419 |
|
| 420 |
interceptor_methods_.SetCall(&*wrapped_call_); |
| 421 |
interceptor_methods_.SetReverse(); |
| 422 |
// Set interception point for RECV INITIAL METADATA |
| 423 |
interceptor_methods_.AddInterceptionHookPoint( |
| 424 |
grpc::experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA); |
| 425 |
interceptor_methods_.SetRecvInitialMetadata(&ctx_->ctx.client_metadata_); |
| 426 |
|
| 427 |
if (has_request_payload_) { |
| 428 |
// Set interception point for RECV MESSAGE |
| 429 |
auto* handler = resources_ ? method_->handler() |
| 430 |
: server_->resource_exhausted_handler_.get(); |
| 431 |
deserialized_request_ = handler->Deserialize(call_, request_payload_, |
| 432 |
&request_status_, nullptr); |
| 433 |
if (!request_status_.ok()) { |
| 434 |
gpr_log(GPR_DEBUG, "Failed to deserialize message."); |
| 435 |
} |
| 436 |
request_payload_ = nullptr; |
| 437 |
interceptor_methods_.AddInterceptionHookPoint( |
| 438 |
grpc::experimental::InterceptionHookPoints::POST_RECV_MESSAGE); |
| 439 |
interceptor_methods_.SetRecvMessage(deserialized_request_, nullptr); |
| 440 |
} |
| 441 |
|
| 442 |
if (interceptor_methods_.RunInterceptors( |
| 443 |
[this]() { ContinueRunAfterInterception(); })) { |
| 444 |
ContinueRunAfterInterception(); |
| 445 |
} else { |
| 446 |
// There were interceptors to be run, so ContinueRunAfterInterception |
| 447 |
// will be run when interceptors are done. |
| 448 |
} |
| 449 |
} |
| 450 |
|
| 451 |
void ContinueRunAfterInterception() { |
| 452 |
ctx_->ctx.BeginCompletionOp(&*wrapped_call_, nullptr, nullptr); |
| 453 |
global_callbacks_->PreSynchronousRequest(&ctx_->ctx); |
| 454 |
auto* handler = resources_ ? method_->handler() |
| 455 |
: server_->resource_exhausted_handler_.get(); |
| 456 |
handler->RunHandler(grpc::internal::MethodHandler::HandlerParameter( |
| 457 |
&*wrapped_call_, &ctx_->ctx, deserialized_request_, request_status_, |
| 458 |
nullptr, nullptr)); |
| 459 |
global_callbacks_->PostSynchronousRequest(&ctx_->ctx); |
| 460 |
|
| 461 |
cq_.Shutdown(); |
| 462 |
|
| 463 |
grpc::internal::CompletionQueueTag* op_tag = ctx_->ctx.GetCompletionOpTag(); |
| 464 |
cq_.TryPluck(op_tag, gpr_inf_future(GPR_CLOCK_REALTIME)); |
| 465 |
|
| 466 |
// Ensure the cq_ is shutdown |
| 467 |
grpc::PhonyTag ignored_tag; |
| 468 |
GPR_ASSERT(cq_.Pluck(&ignored_tag) == false); |
| 469 |
|
| 470 |
// Cleanup structures allocated during Run/ContinueRunAfterInterception |
| 471 |
wrapped_call_.Destroy(); |
| 472 |
ctx_.Destroy(); |
| 473 |
|
| 474 |
delete this; |
| 475 |
} |
| 476 |
|
| 477 |
// For requests that must be only cleaned up but not actually Run |
| 478 |
void Cleanup() { |
| 479 |
cq_.Shutdown(); |
| 480 |
grpc_call_unref(call_); |
| 481 |
delete this; |
| 482 |
} |
| 483 |
|
| 484 |
private: |
| 485 |
SyncRequest(Server* server, grpc::internal::RpcServiceMethod* method) |
| 486 |
: server_(server), |
| 487 |
method_(method), |
| 488 |
has_request_payload_(method->method_type() == |
| 489 |
grpc::internal::RpcMethod::NORMAL_RPC || |
| 490 |
method->method_type() == |
| 491 |
grpc::internal::RpcMethod::SERVER_STREAMING), |
| 492 |
cq_(grpc_completion_queue_create_for_pluck(nullptr)) {} |
| 493 |
|
| 494 |
template <class CallAllocation> |
| 495 |
void CommonSetup(CallAllocation* data) { |
| 496 |
server_->Ref(); |
| 497 |
grpc_metadata_array_init(&request_metadata_); |
| 498 |
data->tag = static_cast<void*>(this); |
| 499 |
data->call = &call_; |
| 500 |
data->initial_metadata = &request_metadata_; |
| 501 |
data->cq = cq_.cq(); |
| 502 |
} |
| 503 |
|
| 504 |
Server* const server_; |
| 505 |
grpc::internal::RpcServiceMethod* const method_; |
| 506 |
const bool has_request_payload_; |
| 507 |
grpc_call* call_; |
| 508 |
grpc_call_details* call_details_ = nullptr; |
| 509 |
gpr_timespec deadline_; |
| 510 |
grpc_metadata_array request_metadata_; |
| 511 |
grpc_byte_buffer* request_payload_ = nullptr; |
| 512 |
grpc::CompletionQueue cq_; |
| 513 |
grpc::Status request_status_; |
| 514 |
std::shared_ptr<GlobalCallbacks> global_callbacks_; |
| 515 |
bool resources_; |
| 516 |
void* deserialized_request_ = nullptr; |
| 517 |
grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_; |
| 518 |
|
| 519 |
// ServerContextWrapper allows ManualConstructor while using a private |
| 520 |
// contructor of ServerContext via this friend class. |
| 521 |
struct ServerContextWrapper { |
| 522 |
ServerContext ctx; |
| 523 |
|
| 524 |
ServerContextWrapper(gpr_timespec deadline, grpc_metadata_array* arr) |
| 525 |
: ctx(deadline, arr) {} |
| 526 |
}; |
| 527 |
|
| 528 |
grpc_core::ManualConstructor<ServerContextWrapper> ctx_; |
| 529 |
grpc_core::ManualConstructor<internal::Call> wrapped_call_; |
| 530 |
}; |
| 531 |
|
| 532 |
template <class ServerContextType> |
| 533 |
class Server::CallbackRequest final |
| 534 |
: public grpc::internal::CompletionQueueTag { |
| 535 |
public: |
| 536 |
static_assert( |
| 537 |
std::is_base_of<grpc::CallbackServerContext, ServerContextType>::value, |
| 538 |
"ServerContextType must be derived from CallbackServerContext"); |
| 539 |
|
| 540 |
// For codegen services, the value of method represents the defined |
| 541 |
// characteristics of the method being requested. For generic services, method |
| 542 |
// is nullptr since these services don't have pre-defined methods. |
| 543 |
CallbackRequest(Server* server, grpc::internal::RpcServiceMethod* method, |
| 544 |
grpc::CompletionQueue* cq, |
| 545 |
grpc_core::Server::RegisteredCallAllocation* data) |
| 546 |
: server_(server), |
| 547 |
method_(method), |
| 548 |
has_request_payload_(method->method_type() == |
| 549 |
grpc::internal::RpcMethod::NORMAL_RPC || |
| 550 |
method->method_type() == |
| 551 |
grpc::internal::RpcMethod::SERVER_STREAMING), |
| 552 |
cq_(cq), |
| 553 |
tag_(this), |
| 554 |
ctx_(server_->context_allocator() != nullptr |
| 555 |
? server_->context_allocator()->NewCallbackServerContext() |
| 556 |
: nullptr) { |
| 557 |
CommonSetup(server, data); |
| 558 |
data->deadline = &deadline_; |
| 559 |
data->optional_payload = has_request_payload_ ? &request_payload_ : nullptr; |
| 560 |
} |
| 561 |
|
| 562 |
// For generic services, method is nullptr since these services don't have |
| 563 |
// pre-defined methods. |
| 564 |
CallbackRequest(Server* server, grpc::CompletionQueue* cq, |
| 565 |
grpc_core::Server::BatchCallAllocation* data) |
| 566 |
: server_(server), |
| 567 |
method_(nullptr), |
| 568 |
has_request_payload_(false), |
| 569 |
call_details_(new grpc_call_details), |
| 570 |
cq_(cq), |
| 571 |
tag_(this), |
| 572 |
ctx_(server_->context_allocator() != nullptr |
| 573 |
? server_->context_allocator() |
| 574 |
->NewGenericCallbackServerContext() |
| 575 |
: nullptr) { |
| 576 |
CommonSetup(server, data); |
| 577 |
grpc_call_details_init(call_details_); |
| 578 |
data->details = call_details_; |
| 579 |
} |
| 580 |
|
| 581 |
~CallbackRequest() override { |
| 582 |
delete call_details_; |
| 583 |
grpc_metadata_array_destroy(&request_metadata_); |
| 584 |
if (has_request_payload_ && request_payload_) { |
| 585 |
grpc_byte_buffer_destroy(request_payload_); |
| 586 |
} |
| 587 |
if (ctx_alloc_by_default_ || server_->context_allocator() == nullptr) { |
| 588 |
default_ctx_.Destroy(); |
| 589 |
} |
| 590 |
server_->UnrefWithPossibleNotify(); |
| 591 |
} |
| 592 |
|
| 593 |
// Needs specialization to account for different processing of metadata |
| 594 |
// in generic API |
| 595 |
bool FinalizeResult(void** tag, bool* status) override; |
| 596 |
|
| 597 |
private: |
| 598 |
// method_name needs to be specialized between named method and generic |
| 599 |
const char* method_name() const; |
| 600 |
|
| 601 |
class CallbackCallTag : public grpc_completion_queue_functor { |
| 602 |
public: |
| 603 |
explicit CallbackCallTag(Server::CallbackRequest<ServerContextType>* req) |
| 604 |
: req_(req) { |
| 605 |
functor_run = &CallbackCallTag::StaticRun; |
| 606 |
// Set inlineable to true since this callback is internally-controlled |
| 607 |
// without taking any locks, and thus does not need to be run from the |
| 608 |
// executor (which triggers a thread hop). This should only be used by |
| 609 |
// internal callbacks like this and not by user application code. The work |
| 610 |
// here is actually non-trivial, but there is no chance of having user |
| 611 |
// locks conflict with each other so it's ok to run inlined. |
| 612 |
inlineable = true; |
| 613 |
} |
| 614 |
|
| 615 |
// force_run can not be performed on a tag if operations using this tag |
| 616 |
// have been sent to PerformOpsOnCall. It is intended for error conditions |
| 617 |
// that are detected before the operations are internally processed. |
| 618 |
void force_run(bool ok) { Run(ok); } |
| 619 |
|
| 620 |
private: |
| 621 |
Server::CallbackRequest<ServerContextType>* req_; |
| 622 |
grpc::internal::Call* call_; |
| 623 |
|
| 624 |
static void StaticRun(grpc_completion_queue_functor* cb, int ok) { |
| 625 |
static_cast<CallbackCallTag*>(cb)->Run(static_cast<bool>(ok)); |
| 626 |
} |
| 627 |
void Run(bool ok) { |
| 628 |
void* ignored = req_; |
| 629 |
bool new_ok = ok; |
| 630 |
GPR_ASSERT(!req_->FinalizeResult(&ignored, &new_ok)); |
| 631 |
GPR_ASSERT(ignored == req_); |
| 632 |
|
| 633 |
if (!ok) { |
| 634 |
// The call has been shutdown. |
| 635 |
// Delete its contents to free up the request. |
| 636 |
delete req_; |
| 637 |
return; |
| 638 |
} |
| 639 |
|
| 640 |
// Bind the call, deadline, and metadata from what we got |
| 641 |
req_->ctx_->set_call(req_->call_); |
| 642 |
req_->ctx_->cq_ = req_->cq_; |
| 643 |
req_->ctx_->BindDeadlineAndMetadata(req_->deadline_, |
| 644 |
&req_->request_metadata_); |
| 645 |
req_->request_metadata_.count = 0; |
| 646 |
|
| 647 |
// Create a C++ Call to control the underlying core call |
| 648 |
call_ = |
| 649 |
new (grpc_call_arena_alloc(req_->call_, sizeof(grpc::internal::Call))) |
| 650 |
grpc::internal::Call( |
| 651 |
req_->call_, req_->server_, req_->cq_, |
| 652 |
req_->server_->max_receive_message_size(), |
| 653 |
req_->ctx_->set_server_rpc_info( |
| 654 |
req_->method_name(), |
| 655 |
(req_->method_ != nullptr) |
| 656 |
? req_->method_->method_type() |
| 657 |
: grpc::internal::RpcMethod::BIDI_STREAMING, |
| 658 |
req_->server_->interceptor_creators_)); |
| 659 |
|
| 660 |
req_->interceptor_methods_.SetCall(call_); |
| 661 |
req_->interceptor_methods_.SetReverse(); |
| 662 |
// Set interception point for RECV INITIAL METADATA |
| 663 |
req_->interceptor_methods_.AddInterceptionHookPoint( |
| 664 |
grpc::experimental::InterceptionHookPoints:: |
| 665 |
POST_RECV_INITIAL_METADATA); |
| 666 |
req_->interceptor_methods_.SetRecvInitialMetadata( |
| 667 |
&req_->ctx_->client_metadata_); |
| 668 |
|
| 669 |
if (req_->has_request_payload_) { |
| 670 |
// Set interception point for RECV MESSAGE |
| 671 |
req_->request_ = req_->method_->handler()->Deserialize( |
| 672 |
req_->call_, req_->request_payload_, &req_->request_status_, |
| 673 |
&req_->handler_data_); |
| 674 |
if (!(req_->request_status_.ok())) { |
| 675 |
gpr_log(GPR_DEBUG, "Failed to deserialize message."); |
| 676 |
} |
| 677 |
req_->request_payload_ = nullptr; |
| 678 |
req_->interceptor_methods_.AddInterceptionHookPoint( |
| 679 |
grpc::experimental::InterceptionHookPoints::POST_RECV_MESSAGE); |
| 680 |
req_->interceptor_methods_.SetRecvMessage(req_->request_, nullptr); |
| 681 |
} |
| 682 |
|
| 683 |
if (req_->interceptor_methods_.RunInterceptors( |
| 684 |
[this] { ContinueRunAfterInterception(); })) { |
| 685 |
ContinueRunAfterInterception(); |
| 686 |
} else { |
| 687 |
// There were interceptors to be run, so ContinueRunAfterInterception |
| 688 |
// will be run when interceptors are done. |
| 689 |
} |
| 690 |
} |
| 691 |
void ContinueRunAfterInterception() { |
| 692 |
auto* handler = (req_->method_ != nullptr) |
| 693 |
? req_->method_->handler() |
| 694 |
: req_->server_->generic_handler_.get(); |
| 695 |
handler->RunHandler(grpc::internal::MethodHandler::HandlerParameter( |
| 696 |
call_, req_->ctx_, req_->request_, req_->request_status_, |
| 697 |
req_->handler_data_, [this] { delete req_; })); |
| 698 |
} |
| 699 |
}; |
| 700 |
|
| 701 |
template <class CallAllocation> |
| 702 |
void CommonSetup(Server* server, CallAllocation* data) { |
| 703 |
server->Ref(); |
| 704 |
grpc_metadata_array_init(&request_metadata_); |
| 705 |
data->tag = static_cast<void*>(&tag_); |
| 706 |
data->call = &call_; |
| 707 |
data->initial_metadata = &request_metadata_; |
| 708 |
if (ctx_ == nullptr) { |
| 709 |
default_ctx_.Init(); |
| 710 |
ctx_ = &*default_ctx_; |
| 711 |
ctx_alloc_by_default_ = true; |
| 712 |
} |
| 713 |
ctx_->set_context_allocator(server->context_allocator()); |
| 714 |
data->cq = cq_->cq(); |
| 715 |
} |
| 716 |
|
| 717 |
Server* const server_; |
| 718 |
grpc::internal::RpcServiceMethod* const method_; |
| 719 |
const bool has_request_payload_; |
| 720 |
grpc_byte_buffer* request_payload_ = nullptr; |
| 721 |
void* request_ = nullptr; |
| 722 |
void* handler_data_ = nullptr; |
| 723 |
grpc::Status request_status_; |
| 724 |
grpc_call_details* const call_details_ = nullptr; |
| 725 |
grpc_call* call_; |
| 726 |
gpr_timespec deadline_; |
| 727 |
grpc_metadata_array request_metadata_; |
| 728 |
grpc::CompletionQueue* const cq_; |
| 729 |
bool ctx_alloc_by_default_ = false; |
| 730 |
CallbackCallTag tag_; |
| 731 |
ServerContextType* ctx_ = nullptr; |
| 732 |
grpc_core::ManualConstructor<ServerContextType> default_ctx_; |
| 733 |
grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_; |
| 734 |
}; |
| 735 |
|
| 736 |
template <> |
| 737 |
bool Server::CallbackRequest<grpc::CallbackServerContext>::FinalizeResult( |
| 738 |
void** /*tag*/, bool* /*status*/) { |
| 739 |
return false; |
| 740 |
} |
| 741 |
|
| 742 |
template <> |
| 743 |
bool Server::CallbackRequest< |
| 744 |
grpc::GenericCallbackServerContext>::FinalizeResult(void** /*tag*/, |
| 745 |
bool* status) { |
| 746 |
if (*status) { |
| 747 |
deadline_ = call_details_->deadline; |
| 748 |
// TODO(yangg) remove the copy here |
| 749 |
ctx_->method_ = grpc::StringFromCopiedSlice(call_details_->method); |
| 750 |
ctx_->host_ = grpc::StringFromCopiedSlice(call_details_->host); |
| 751 |
} |
| 752 |
grpc_slice_unref(call_details_->method); |
| 753 |
grpc_slice_unref(call_details_->host); |
| 754 |
return false; |
| 755 |
} |
| 756 |
|
| 757 |
template <> |
| 758 |
const char* Server::CallbackRequest<grpc::CallbackServerContext>::method_name() |
| 759 |
const { |
| 760 |
return method_->name(); |
| 761 |
} |
| 762 |
|
| 763 |
template <> |
| 764 |
const char* Server::CallbackRequest< |
| 765 |
grpc::GenericCallbackServerContext>::method_name() const { |
| 766 |
return ctx_->method().c_str(); |
| 767 |
} |
| 768 |
|
| 769 |
// Implementation of ThreadManager. Each instance of SyncRequestThreadManager |
| 770 |
// manages a pool of threads that poll for incoming Sync RPCs and call the |
| 771 |
// appropriate RPC handlers |
| 772 |
class Server::SyncRequestThreadManager : public grpc::ThreadManager { |
| 773 |
public: |
| 774 |
SyncRequestThreadManager(Server* server, grpc::CompletionQueue* server_cq, |
| 775 |
std::shared_ptr<GlobalCallbacks> global_callbacks, |
| 776 |
grpc_resource_quota* rq, int min_pollers, |
| 777 |
int max_pollers, int cq_timeout_msec) |
| 778 |
: ThreadManager("SyncServer", rq, min_pollers, max_pollers), |
| 779 |
server_(server), |
| 780 |
server_cq_(server_cq), |
| 781 |
cq_timeout_msec_(cq_timeout_msec), |
| 782 |
global_callbacks_(std::move(global_callbacks)) {} |
| 783 |
|
| 784 |
WorkStatus PollForWork(void** tag, bool* ok) override { |
| 785 |
*tag = nullptr; |
| 786 |
// TODO(ctiller): workaround for GPR_TIMESPAN based deadlines not working |
| 787 |
// right now |
| 788 |
gpr_timespec deadline = |
| 789 |
gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC), |
| 790 |
gpr_time_from_millis(cq_timeout_msec_, GPR_TIMESPAN)); |
| 791 |
|
| 792 |
switch (server_cq_->AsyncNext(tag, ok, deadline)) { |
| 793 |
case grpc::CompletionQueue::TIMEOUT: |
| 794 |
return TIMEOUT; |
| 795 |
case grpc::CompletionQueue::SHUTDOWN: |
| 796 |
return SHUTDOWN; |
| 797 |
case grpc::CompletionQueue::GOT_EVENT: |
| 798 |
return WORK_FOUND; |
| 799 |
} |
| 800 |
|
| 801 |
GPR_UNREACHABLE_CODE(return TIMEOUT); |
| 802 |
} |
| 803 |
|
| 804 |
void DoWork(void* tag, bool ok, bool resources) override { |
| 805 |
(void)ok; |
| 806 |
SyncRequest* sync_req = static_cast<SyncRequest*>(tag); |
| 807 |
|
| 808 |
// Under the AllocatingRequestMatcher model we will never see an invalid tag |
| 809 |
// here. |
| 810 |
GPR_DEBUG_ASSERT(sync_req != nullptr); |
| 811 |
GPR_DEBUG_ASSERT(ok); |
| 812 |
|
| 813 |
sync_req->Run(global_callbacks_, resources); |
| 814 |
} |
| 815 |
|
| 816 |
void AddSyncMethod(grpc::internal::RpcServiceMethod* method, void* tag) { |
| 817 |
grpc_core::Server::FromC(server_->server()) |
| 818 |
->SetRegisteredMethodAllocator(server_cq_->cq(), tag, [this, method] { |
| 819 |
grpc_core::Server::RegisteredCallAllocation result; |
| 820 |
new SyncRequest(server_, method, &result); |
| 821 |
return result; |
| 822 |
}); |
| 823 |
has_sync_method_ = true; |
| 824 |
} |
| 825 |
|
| 826 |
void AddUnknownSyncMethod() { |
| 827 |
if (has_sync_method_) { |
| 828 |
unknown_method_ = std::make_unique<grpc::internal::RpcServiceMethod>( |
| 829 |
"unknown", grpc::internal::RpcMethod::BIDI_STREAMING, |
| 830 |
new grpc::internal::UnknownMethodHandler(kUnknownRpcMethod)); |
| 831 |
grpc_core::Server::FromC(server_->server()) |
| 832 |
->SetBatchMethodAllocator(server_cq_->cq(), [this] { |
| 833 |
grpc_core::Server::BatchCallAllocation result; |
| 834 |
new SyncRequest(server_, unknown_method_.get(), &result); |
| 835 |
return result; |
| 836 |
}); |
| 837 |
} |
| 838 |
} |
| 839 |
|
| 840 |
void Shutdown() override { |
| 841 |
ThreadManager::Shutdown(); |
| 842 |
server_cq_->Shutdown(); |
| 843 |
} |
| 844 |
|
| 845 |
void Wait() override { |
| 846 |
ThreadManager::Wait(); |
| 847 |
// Drain any pending items from the queue |
| 848 |
void* tag; |
| 849 |
bool ok; |
| 850 |
while (server_cq_->Next(&tag, &ok)) { |
| 851 |
// This problem can arise if the server CQ gets a request queued to it |
| 852 |
// before it gets shutdown but then pulls it after shutdown. |
| 853 |
static_cast<SyncRequest*>(tag)->Cleanup(); |
| 854 |
} |
| 855 |
} |
| 856 |
|
| 857 |
void Start() { |
| 858 |
if (has_sync_method_) { |
| 859 |
Initialize(); // ThreadManager's Initialize() |
| 860 |
} |
| 861 |
} |
| 862 |
|
| 863 |
private: |
| 864 |
Server* server_; |
| 865 |
grpc::CompletionQueue* server_cq_; |
| 866 |
int cq_timeout_msec_; |
| 867 |
bool has_sync_method_ = false; |
| 868 |
std::unique_ptr<grpc::internal::RpcServiceMethod> unknown_method_; |
| 869 |
std::shared_ptr<Server::GlobalCallbacks> global_callbacks_; |
| 870 |
}; |
| 871 |
|
| 872 |
static grpc::internal::GrpcLibraryInitializer g_gli_initializer; |
| 873 |
Server::Server( |
| 874 |
grpc::ChannelArguments* args, |
| 875 |
std::shared_ptr<std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>> |
| 876 |
sync_server_cqs, |
| 877 |
int min_pollers, int max_pollers, int sync_cq_timeout_msec, |
| 878 |
std::vector<std::shared_ptr<grpc::internal::ExternalConnectionAcceptorImpl>> |
| 879 |
acceptors, |
| 880 |
grpc_server_config_fetcher* server_config_fetcher, |
| 881 |
grpc_resource_quota* server_rq, |
| 882 |
std::vector< |
| 883 |
std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>> |
| 884 |
interceptor_creators) |
| 885 |
: acceptors_(std::move(acceptors)), |
| 886 |
interceptor_creators_(std::move(interceptor_creators)), |
| 887 |
max_receive_message_size_(INT_MIN), |
| 888 |
sync_server_cqs_(std::move(sync_server_cqs)), |
| 889 |
started_(false), |
| 890 |
shutdown_(false), |
| 891 |
shutdown_notified_(false), |
| 892 |
server_(nullptr), |
| 893 |
server_initializer_(new ServerInitializer(this)), |
| 894 |
health_check_service_disabled_(false) { |
| 895 |
g_gli_initializer.summon(); |
| 896 |
gpr_once_init(&grpc::g_once_init_callbacks, grpc::InitGlobalCallbacks); |
| 897 |
global_callbacks_ = grpc::g_callbacks; |
| 898 |
global_callbacks_->UpdateArguments(args); |
| 899 |
|
| 900 |
if (sync_server_cqs_ != nullptr) { |
| 901 |
bool default_rq_created = false; |
| 902 |
if (server_rq == nullptr) { |
| 903 |
server_rq = grpc_resource_quota_create("SyncServer-default-rq"); |
| 904 |
grpc_resource_quota_set_max_threads(server_rq, |
| 905 |
DEFAULT_MAX_SYNC_SERVER_THREADS); |
| 906 |
default_rq_created = true; |
| 907 |
} |
| 908 |
|
| 909 |
for (const auto& it : *sync_server_cqs_) { |
| 910 |
sync_req_mgrs_.emplace_back(new SyncRequestThreadManager( |
| 911 |
this, it.get(), global_callbacks_, server_rq, min_pollers, |
| 912 |
max_pollers, sync_cq_timeout_msec)); |
| 913 |
} |
| 914 |
|
| 915 |
if (default_rq_created) { |
| 916 |
grpc_resource_quota_unref(server_rq); |
| 917 |
} |
| 918 |
} |
| 919 |
|
| 920 |
for (auto& acceptor : acceptors_) { |
| 921 |
acceptor->SetToChannelArgs(args); |
| 922 |
} |
| 923 |
|
| 924 |
grpc_channel_args channel_args; |
| 925 |
args->SetChannelArgs(&channel_args); |
| 926 |
|
| 927 |
for (size_t i = 0; i < channel_args.num_args; i++) { |
| 928 |
if (0 == strcmp(channel_args.args[i].key, |
| 929 |
grpc::kHealthCheckServiceInterfaceArg)) { |
| 930 |
if (channel_args.args[i].value.pointer.p == nullptr) { |
| 931 |
health_check_service_disabled_ = true; |
| 932 |
} else { |
| 933 |
health_check_service_.reset( |
| 934 |
static_cast<grpc::HealthCheckServiceInterface*>( |
| 935 |
channel_args.args[i].value.pointer.p)); |
| 936 |
} |
| 937 |
} |
| 938 |
if (0 == |
| 939 |
strcmp(channel_args.args[i].key, GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH)) { |
| 940 |
max_receive_message_size_ = channel_args.args[i].value.integer; |
| 941 |
} |
| 942 |
} |
| 943 |
server_ = grpc_server_create(&channel_args, nullptr); |
| 944 |
grpc_server_set_config_fetcher(server_, server_config_fetcher); |
| 945 |
} |
| 946 |
|
| 947 |
Server::~Server() { |
| 948 |
{ |
| 949 |
grpc::internal::ReleasableMutexLock lock(&mu_); |
| 950 |
if (started_ && !shutdown_) { |
| 951 |
lock.Release(); |
| 952 |
Shutdown(); |
| 953 |
} else if (!started_) { |
| 954 |
// Shutdown the completion queues |
| 955 |
for (const auto& value : sync_req_mgrs_) { |
| 956 |
value->Shutdown(); |
| 957 |
} |
| 958 |
CompletionQueue* callback_cq = |
| 959 |
callback_cq_.load(std::memory_order_relaxed); |
| 960 |
if (callback_cq != nullptr) { |
| 961 |
if (grpc_iomgr_run_in_background()) { |
| 962 |
// gRPC-core provides the backing needed for the preferred CQ type |
| 963 |
callback_cq->Shutdown(); |
| 964 |
} else { |
| 965 |
CompletionQueue::ReleaseCallbackAlternativeCQ(callback_cq); |
| 966 |
} |
| 967 |
callback_cq_.store(nullptr, std::memory_order_release); |
| 968 |
} |
| 969 |
} |
| 970 |
} |
| 971 |
// Destroy health check service before we destroy the C server so that |
| 972 |
// it does not call grpc_server_request_registered_call() after the C |
| 973 |
// server has been destroyed. |
| 974 |
health_check_service_.reset(); |
| 975 |
grpc_server_destroy(server_); |
| 976 |
} |
| 977 |
|
| 978 |
void Server::SetGlobalCallbacks(GlobalCallbacks* callbacks) { |
| 979 |
GPR_ASSERT(!grpc::g_callbacks); |
| 980 |
GPR_ASSERT(callbacks); |
| 981 |
grpc::g_callbacks.reset(callbacks); |
| 982 |
} |
| 983 |
|
| 984 |
grpc_server* Server::c_server() { return server_; } |
| 985 |
|
| 986 |
std::shared_ptr<grpc::Channel> Server::InProcessChannel( |
| 987 |
const grpc::ChannelArguments& args) { |
| 988 |
grpc_channel_args channel_args = args.c_channel_args(); |
| 989 |
return grpc::CreateChannelInternal( |
| 990 |
"inproc", grpc_inproc_channel_create(server_, &channel_args, nullptr), |
| 991 |
std::vector<std::unique_ptr< |
| 992 |
grpc::experimental::ClientInterceptorFactoryInterface>>()); |
| 993 |
} |
| 994 |
|
| 995 |
std::shared_ptr<grpc::Channel> |
| 996 |
Server::experimental_type::InProcessChannelWithInterceptors( |
| 997 |
const grpc::ChannelArguments& args, |
| 998 |
std::vector< |
| 999 |
std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>> |
| 1000 |
interceptor_creators) { |
| 1001 |
grpc_channel_args channel_args = args.c_channel_args(); |
| 1002 |
return grpc::CreateChannelInternal( |
| 1003 |
"inproc", |
| 1004 |
grpc_inproc_channel_create(server_->server_, &channel_args, nullptr), |
| 1005 |
std::move(interceptor_creators)); |
| 1006 |
} |
| 1007 |
|
| 1008 |
static grpc_server_register_method_payload_handling PayloadHandlingForMethod( |
| 1009 |
grpc::internal::RpcServiceMethod* method) { |
| 1010 |
switch (method->method_type()) { |
| 1011 |
case grpc::internal::RpcMethod::NORMAL_RPC: |
| 1012 |
case grpc::internal::RpcMethod::SERVER_STREAMING: |
| 1013 |
return GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER; |
| 1014 |
case grpc::internal::RpcMethod::CLIENT_STREAMING: |
| 1015 |
case grpc::internal::RpcMethod::BIDI_STREAMING: |
| 1016 |
return GRPC_SRM_PAYLOAD_NONE; |
| 1017 |
} |
| 1018 |
GPR_UNREACHABLE_CODE(return GRPC_SRM_PAYLOAD_NONE;); |
| 1019 |
} |
| 1020 |
|
| 1021 |
bool Server::RegisterService(const std::string* addr, grpc::Service* service) { |
| 1022 |
bool has_async_methods = service->has_async_methods(); |
| 1023 |
if (has_async_methods) { |
| 1024 |
GPR_ASSERT(service->server_ == nullptr && |
| 1025 |
"Can only register an asynchronous service against one server."); |
| 1026 |
service->server_ = this; |
| 1027 |
} |
| 1028 |
|
| 1029 |
const char* method_name = nullptr; |
| 1030 |
|
| 1031 |
for (const auto& method : service->methods_) { |
| 1032 |
if (method == nullptr) { // Handled by generic service if any. |
| 1033 |
continue; |
| 1034 |
} |
| 1035 |
|
| 1036 |
void* method_registration_tag = grpc_server_register_method( |
| 1037 |
server_, method->name(), addr ? addr->c_str() : nullptr, |
| 1038 |
PayloadHandlingForMethod(method.get()), 0); |
| 1039 |
if (method_registration_tag == nullptr) { |
| 1040 |
gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", |
| 1041 |
method->name()); |
| 1042 |
return false; |
| 1043 |
} |
| 1044 |
|
| 1045 |
if (method->handler() == nullptr) { // Async method without handler |
| 1046 |
method->set_server_tag(method_registration_tag); |
| 1047 |
} else if (method->api_type() == |
| 1048 |
grpc::internal::RpcServiceMethod::ApiType::SYNC) { |
| 1049 |
for (const auto& value : sync_req_mgrs_) { |
| 1050 |
value->AddSyncMethod(method.get(), method_registration_tag); |
| 1051 |
} |
| 1052 |
} else { |
| 1053 |
has_callback_methods_ = true; |
| 1054 |
grpc::internal::RpcServiceMethod* method_value = method.get(); |
| 1055 |
grpc::CompletionQueue* cq = CallbackCQ(); |
| 1056 |
grpc_server_register_completion_queue(server_, cq->cq(), nullptr); |
| 1057 |
grpc_core::Server::FromC(server_)->SetRegisteredMethodAllocator( |
| 1058 |
cq->cq(), method_registration_tag, [this, cq, method_value] { |
| 1059 |
grpc_core::Server::RegisteredCallAllocation result; |
| 1060 |
new CallbackRequest<grpc::CallbackServerContext>(this, method_value, |
| 1061 |
cq, &result); |
| 1062 |
return result; |
| 1063 |
}); |
| 1064 |
} |
| 1065 |
|
| 1066 |
method_name = method->name(); |
| 1067 |
} |
| 1068 |
|
| 1069 |
// Parse service name. |
| 1070 |
if (method_name != nullptr) { |
| 1071 |
std::stringstream ss(method_name); |
| 1072 |
std::string service_name; |
| 1073 |
if (std::getline(ss, service_name, '/') && |
| 1074 |
std::getline(ss, service_name, '/')) { |
| 1075 |
services_.push_back(service_name); |
| 1076 |
} |
| 1077 |
} |
| 1078 |
return true; |
| 1079 |
} |
| 1080 |
|
| 1081 |
void Server::RegisterAsyncGenericService(grpc::AsyncGenericService* service) { |
| 1082 |
GPR_ASSERT(service->server_ == nullptr && |
| 1083 |
"Can only register an async generic service against one server."); |
| 1084 |
service->server_ = this; |
| 1085 |
has_async_generic_service_ = true; |
| 1086 |
} |
| 1087 |
|
| 1088 |
void Server::RegisterCallbackGenericService( |
| 1089 |
grpc::CallbackGenericService* service) { |
| 1090 |
GPR_ASSERT( |
| 1091 |
service->server_ == nullptr && |
| 1092 |
"Can only register a callback generic service against one server."); |
| 1093 |
service->server_ = this; |
| 1094 |
has_callback_generic_service_ = true; |
| 1095 |
generic_handler_.reset(service->Handler()); |
| 1096 |
|
| 1097 |
grpc::CompletionQueue* cq = CallbackCQ(); |
| 1098 |
grpc_core::Server::FromC(server_)->SetBatchMethodAllocator(cq->cq(), [this, |
| 1099 |
cq] { |
| 1100 |
grpc_core::Server::BatchCallAllocation result; |
| 1101 |
new CallbackRequest<grpc::GenericCallbackServerContext>(this, cq, &result); |
| 1102 |
return result; |
| 1103 |
}); |
| 1104 |
} |
| 1105 |
|
| 1106 |
int Server::AddListeningPort(const std::string& addr, |
| 1107 |
grpc::ServerCredentials* creds) { |
| 1108 |
GPR_ASSERT(!started_); |
| 1109 |
int port = creds->AddPortToServer(addr, server_); |
| 1110 |
global_callbacks_->AddPort(this, addr, creds, port); |
| 1111 |
return port; |
| 1112 |
} |
| 1113 |
|
| 1114 |
void Server::Ref() { |
| 1115 |
shutdown_refs_outstanding_.fetch_add(1, std::memory_order_relaxed); |
| 1116 |
} |
| 1117 |
|
| 1118 |
void Server::UnrefWithPossibleNotify() { |
| 1119 |
if (GPR_UNLIKELY(shutdown_refs_outstanding_.fetch_sub( |
| 1120 |
1, std::memory_order_acq_rel) == 1)) { |
| 1121 |
// No refs outstanding means that shutdown has been initiated and no more |
| 1122 |
// callback requests are outstanding. |
| 1123 |
grpc::internal::MutexLock lock(&mu_); |
| 1124 |
GPR_ASSERT(shutdown_); |
| 1125 |
shutdown_done_ = true; |
| 1126 |
shutdown_done_cv_.Signal(); |
| 1127 |
} |
| 1128 |
} |
| 1129 |
|
| 1130 |
void Server::UnrefAndWaitLocked() { |
| 1131 |
if (GPR_UNLIKELY(shutdown_refs_outstanding_.fetch_sub( |
| 1132 |
1, std::memory_order_acq_rel) == 1)) { |
| 1133 |
shutdown_done_ = true; |
| 1134 |
return; // no need to wait on CV since done condition already set |
| 1135 |
} |
| 1136 |
while (!shutdown_done_) { |
| 1137 |
shutdown_done_cv_.Wait(&mu_); |
| 1138 |
} |
| 1139 |
} |
| 1140 |
|
| 1141 |
void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) { |
| 1142 |
GPR_ASSERT(!started_); |
| 1143 |
global_callbacks_->PreServerStart(this); |
| 1144 |
started_ = true; |
| 1145 |
|
| 1146 |
// Only create default health check service when user did not provide an |
| 1147 |
// explicit one. |
| 1148 |
if (health_check_service_ == nullptr && !health_check_service_disabled_ && |
| 1149 |
grpc::DefaultHealthCheckServiceEnabled()) { |
| 1150 |
auto default_hc_service = std::make_unique<DefaultHealthCheckService>(); |
| 1151 |
auto* hc_service_impl = default_hc_service->GetHealthCheckService(); |
| 1152 |
health_check_service_ = std::move(default_hc_service); |
| 1153 |
RegisterService(nullptr, hc_service_impl); |
| 1154 |
} |
| 1155 |
|
| 1156 |
for (auto& acceptor : acceptors_) { |
| 1157 |
acceptor->GetCredentials()->AddPortToServer(acceptor->name(), server_); |
| 1158 |
} |
| 1159 |
|
| 1160 |
#ifndef NDEBUG |
| 1161 |
for (size_t i = 0; i < num_cqs; i++) { |
| 1162 |
cq_list_.push_back(cqs[i]); |
| 1163 |
} |
| 1164 |
#endif |
| 1165 |
|
| 1166 |
// We must have exactly one generic service to handle requests for |
| 1167 |
// unmatched method names (i.e., to return UNIMPLEMENTED for any RPC |
| 1168 |
// method for which we don't have a registered implementation). This |
| 1169 |
// service comes from one of the following places (first match wins): |
| 1170 |
// - If the application supplied a generic service via either the async |
| 1171 |
// or callback APIs, we use that. |
| 1172 |
// - If there are callback methods, register a callback generic service. |
| 1173 |
// - If there are sync methods, register a sync generic service. |
| 1174 |
// (This must be done before server start to initialize an |
| 1175 |
// AllocatingRequestMatcher.) |
| 1176 |
// - Otherwise (we have only async methods), we wait until the server |
| 1177 |
// is started and then start an UnimplementedAsyncRequest on each |
| 1178 |
// async CQ, so that the requests will be moved along by polling |
| 1179 |
// done in application threads. |
| 1180 |
bool unknown_rpc_needed = |
| 1181 |
!has_async_generic_service_ && !has_callback_generic_service_; |
| 1182 |
if (unknown_rpc_needed && has_callback_methods_) { |
| 1183 |
unimplemented_service_ = std::make_unique<grpc::CallbackGenericService>(); |
| 1184 |
RegisterCallbackGenericService(unimplemented_service_.get()); |
| 1185 |
unknown_rpc_needed = false; |
| 1186 |
} |
| 1187 |
if (unknown_rpc_needed && !sync_req_mgrs_.empty()) { |
| 1188 |
sync_req_mgrs_[0]->AddUnknownSyncMethod(); |
| 1189 |
unknown_rpc_needed = false; |
| 1190 |
} |
| 1191 |
|
| 1192 |
grpc_server_start(server_); |
| 1193 |
|
| 1194 |
if (unknown_rpc_needed) { |
| 1195 |
for (size_t i = 0; i < num_cqs; i++) { |
| 1196 |
if (cqs[i]->IsFrequentlyPolled()) { |
| 1197 |
new UnimplementedAsyncRequest(this, cqs[i]); |
| 1198 |
} |
| 1199 |
} |
| 1200 |
unknown_rpc_needed = false; |
| 1201 |
} |
| 1202 |
|
| 1203 |
// If this server has any support for synchronous methods (has any sync |
| 1204 |
// server CQs), make sure that we have a ResourceExhausted handler |
| 1205 |
// to deal with the case of thread exhaustion |
| 1206 |
if (sync_server_cqs_ != nullptr && !sync_server_cqs_->empty()) { |
| 1207 |
resource_exhausted_handler_ = |
| 1208 |
std::make_unique<grpc::internal::ResourceExhaustedHandler>( |
| 1209 |
kServerThreadpoolExhausted); |
| 1210 |
} |
| 1211 |
|
| 1212 |
for (const auto& value : sync_req_mgrs_) { |
| 1213 |
value->Start(); |
| 1214 |
} |
| 1215 |
|
| 1216 |
for (auto& acceptor : acceptors_) { |
| 1217 |
acceptor->Start(); |
| 1218 |
} |
| 1219 |
} |
| 1220 |
|
| 1221 |
void Server::ShutdownInternal(gpr_timespec deadline) { |
| 1222 |
grpc::internal::MutexLock lock(&mu_); |
| 1223 |
if (shutdown_) { |
| 1224 |
return; |
| 1225 |
} |
| 1226 |
|
| 1227 |
shutdown_ = true; |
| 1228 |
|
| 1229 |
for (auto& acceptor : acceptors_) { |
| 1230 |
acceptor->Shutdown(); |
| 1231 |
} |
| 1232 |
|
| 1233 |
/// The completion queue to use for server shutdown completion notification |
| 1234 |
grpc::CompletionQueue shutdown_cq; |
| 1235 |
grpc::ShutdownTag shutdown_tag; // Phony shutdown tag |
| 1236 |
grpc_server_shutdown_and_notify(server_, shutdown_cq.cq(), &shutdown_tag); |
| 1237 |
|
| 1238 |
shutdown_cq.Shutdown(); |
| 1239 |
|
| 1240 |
void* tag; |
| 1241 |
bool ok; |
| 1242 |
grpc::CompletionQueue::NextStatus status = |
| 1243 |
shutdown_cq.AsyncNext(&tag, &ok, deadline); |
| 1244 |
|
| 1245 |
// If this timed out, it means we are done with the grace period for a clean |
| 1246 |
// shutdown. We should force a shutdown now by cancelling all inflight calls |
| 1247 |
if (status == grpc::CompletionQueue::NextStatus::TIMEOUT) { |
| 1248 |
grpc_server_cancel_all_calls(server_); |
| 1249 |
} |
| 1250 |
// Else in case of SHUTDOWN or GOT_EVENT, it means that the server has |
| 1251 |
// successfully shutdown |
| 1252 |
|
| 1253 |
// Drop the shutdown ref and wait for all other refs to drop as well. |
| 1254 |
UnrefAndWaitLocked(); |
| 1255 |
|
| 1256 |
// Shutdown all ThreadManagers. This will try to gracefully stop all the |
| 1257 |
// threads in the ThreadManagers (once they process any inflight requests) |
| 1258 |
for (const auto& value : sync_req_mgrs_) { |
| 1259 |
value->Shutdown(); // ThreadManager's Shutdown() |
| 1260 |
} |
| 1261 |
|
| 1262 |
// Wait for threads in all ThreadManagers to terminate |
| 1263 |
for (const auto& value : sync_req_mgrs_) { |
| 1264 |
value->Wait(); |
| 1265 |
} |
| 1266 |
|
| 1267 |
// Shutdown the callback CQ. The CQ is owned by its own shutdown tag, so it |
| 1268 |
// will delete itself at true shutdown. |
| 1269 |
CompletionQueue* callback_cq = callback_cq_.load(std::memory_order_relaxed); |
| 1270 |
if (callback_cq != nullptr) { |
| 1271 |
if (grpc_iomgr_run_in_background()) { |
| 1272 |
// gRPC-core provides the backing needed for the preferred CQ type |
| 1273 |
callback_cq->Shutdown(); |
| 1274 |
} else { |
| 1275 |
CompletionQueue::ReleaseCallbackAlternativeCQ(callback_cq); |
| 1276 |
} |
| 1277 |
callback_cq_.store(nullptr, std::memory_order_release); |
| 1278 |
} |
| 1279 |
|
| 1280 |
// Drain the shutdown queue (if the previous call to AsyncNext() timed out |
| 1281 |
// and we didn't remove the tag from the queue yet) |
| 1282 |
while (shutdown_cq.Next(&tag, &ok)) { |
| 1283 |
// Nothing to be done here. Just ignore ok and tag values |
| 1284 |
} |
| 1285 |
|
| 1286 |
shutdown_notified_ = true; |
| 1287 |
shutdown_cv_.SignalAll(); |
| 1288 |
|
| 1289 |
#ifndef NDEBUG |
| 1290 |
// Unregister this server with the CQs passed into it by the user so that |
| 1291 |
// those can be checked for properly-ordered shutdown. |
| 1292 |
for (auto* cq : cq_list_) { |
| 1293 |
cq->UnregisterServer(this); |
| 1294 |
} |
| 1295 |
cq_list_.clear(); |
| 1296 |
#endif |
| 1297 |
} |
| 1298 |
|
| 1299 |
void Server::Wait() { |
| 1300 |
grpc::internal::MutexLock lock(&mu_); |
| 1301 |
while (started_ && !shutdown_notified_) { |
| 1302 |
shutdown_cv_.Wait(&mu_); |
| 1303 |
} |
| 1304 |
} |
| 1305 |
|
| 1306 |
void Server::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops, |
| 1307 |
grpc::internal::Call* call) { |
| 1308 |
ops->FillOps(call); |
| 1309 |
} |
| 1310 |
|
| 1311 |
bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag, |
| 1312 |
bool* status) { |
| 1313 |
if (GenericAsyncRequest::FinalizeResult(tag, status)) { |
| 1314 |
// We either had no interceptors run or we are done intercepting |
| 1315 |
if (*status) { |
| 1316 |
// Create a new request/response pair using the server and CQ values |
| 1317 |
// stored in this object's base class. |
| 1318 |
new UnimplementedAsyncRequest(server_, notification_cq_); |
| 1319 |
new UnimplementedAsyncResponse(this); |
| 1320 |
} else { |
| 1321 |
delete this; |
| 1322 |
} |
| 1323 |
} else { |
| 1324 |
// The tag was swallowed due to interception. We will see it again. |
| 1325 |
} |
| 1326 |
return false; |
| 1327 |
} |
| 1328 |
|
| 1329 |
Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse( |
| 1330 |
UnimplementedAsyncRequest* request) |
| 1331 |
: request_(request) { |
| 1332 |
grpc::Status status(grpc::StatusCode::UNIMPLEMENTED, kUnknownRpcMethod); |
| 1333 |
grpc::internal::UnknownMethodHandler::FillOps(request_->context(), |
| 1334 |
kUnknownRpcMethod, this); |
| 1335 |
request_->stream()->call_.PerformOps(this); |
| 1336 |
} |
| 1337 |
|
| 1338 |
grpc::ServerInitializer* Server::initializer() { |
| 1339 |
return server_initializer_.get(); |
| 1340 |
} |
| 1341 |
|
| 1342 |
grpc::CompletionQueue* Server::CallbackCQ() { |
| 1343 |
// TODO(vjpai): Consider using a single global CQ for the default CQ |
| 1344 |
// if there is no explicit per-server CQ registered |
| 1345 |
CompletionQueue* callback_cq = callback_cq_.load(std::memory_order_acquire); |
| 1346 |
if (callback_cq != nullptr) { |
| 1347 |
return callback_cq; |
| 1348 |
} |
| 1349 |
// The callback_cq_ wasn't already set, so grab a lock and set it up exactly |
| 1350 |
// once for this server. |
| 1351 |
grpc::internal::MutexLock l(&mu_); |
| 1352 |
callback_cq = callback_cq_.load(std::memory_order_relaxed); |
| 1353 |
if (callback_cq != nullptr) { |
| 1354 |
return callback_cq; |
| 1355 |
} |
| 1356 |
if (grpc_iomgr_run_in_background()) { |
| 1357 |
// gRPC-core provides the backing needed for the preferred CQ type |
| 1358 |
auto* shutdown_callback = new grpc::ShutdownCallback; |
| 1359 |
callback_cq = new grpc::CompletionQueue(grpc_completion_queue_attributes{ |
| 1360 |
GRPC_CQ_CURRENT_VERSION, GRPC_CQ_CALLBACK, GRPC_CQ_DEFAULT_POLLING, |
| 1361 |
shutdown_callback}); |
| 1362 |
|
| 1363 |
// Transfer ownership of the new cq to its own shutdown callback |
| 1364 |
shutdown_callback->TakeCQ(callback_cq); |
| 1365 |
} else { |
| 1366 |
// Otherwise we need to use the alternative CQ variant |
| 1367 |
callback_cq = CompletionQueue::CallbackAlternativeCQ(); |
| 1368 |
} |
| 1369 |
|
| 1370 |
callback_cq_.store(callback_cq, std::memory_order_release); |
| 1371 |
return callback_cq; |
| 1372 |
} |
| 1373 |
|
| 1374 |
} // namespace grpc |