diff options
author | akastornov <akastornov@yandex-team.ru> | 2022-02-10 16:46:03 +0300 |
---|---|---|
committer | Daniil Cherednik <dcherednik@yandex-team.ru> | 2022-02-10 16:46:03 +0300 |
commit | 3a2de774d91ca8d7325aaf81c200b1d2047725e6 (patch) | |
tree | 5674a780ce03a8bbd794733a19c7a70d587e4a14 /contrib/libs/grpc/src/cpp | |
parent | 7bd11ff35e97544d119e43447e3e865f2588ee7f (diff) | |
download | ydb-3a2de774d91ca8d7325aaf81c200b1d2047725e6.tar.gz |
Restoring authorship annotation for <akastornov@yandex-team.ru>. Commit 1 of 2.
Diffstat (limited to 'contrib/libs/grpc/src/cpp')
48 files changed, 3136 insertions, 3136 deletions
diff --git a/contrib/libs/grpc/src/cpp/README.md b/contrib/libs/grpc/src/cpp/README.md index 967a0a43b7..464427e34e 100755 --- a/contrib/libs/grpc/src/cpp/README.md +++ b/contrib/libs/grpc/src/cpp/README.md @@ -1,14 +1,14 @@ # gRPC C++ - + This directory contains the C++ implementation of gRPC. - + # To start using gRPC C++ - + This section describes how to add gRPC as a dependency to your C++ project. In the C++ world, there's no universally accepted standard for managing project dependencies. Therefore, gRPC supports several major build systems, which should satisfy most users. - + ## Bazel Bazel is the primary build system used by the core gRPC development team. Bazel @@ -159,22 +159,22 @@ The gRPC port in vcpkg is kept up to date by Microsoft team members and communit ## Examples & Additional Documentation -You can find out how to build and run our simplest gRPC C++ example in our -[C++ quick start](../../examples/cpp). - -For more detailed documentation on using gRPC in C++ , see our main +You can find out how to build and run our simplest gRPC C++ example in our +[C++ quick start](../../examples/cpp). + +For more detailed documentation on using gRPC in C++ , see our main documentation site at [grpc.io](https://grpc.io), specifically: - + * [Overview](https://grpc.io/docs): An introduction to gRPC with a simple - Hello World example in all our supported languages, including C++. + Hello World example in all our supported languages, including C++. * [gRPC Basics - C++](https://grpc.io/docs/languages/cpp/basics): - A tutorial that steps you through creating a simple gRPC C++ example - application. + A tutorial that steps you through creating a simple gRPC C++ example + application. * [Asynchronous Basics - C++](https://grpc.io/docs/languages/cpp/async): - A tutorial that shows you how to use gRPC C++'s asynchronous/non-blocking - APIs. - - + A tutorial that shows you how to use gRPC C++'s asynchronous/non-blocking + APIs. + + # To start developing gRPC C++ - + For instructions on how to build gRPC C++ from source, follow the [Building gRPC C++](../../BUILDING.md) instructions. diff --git a/contrib/libs/grpc/src/cpp/client/channel_cc.cc b/contrib/libs/grpc/src/cpp/client/channel_cc.cc index ac95c29efc..282a694888 100644 --- a/contrib/libs/grpc/src/cpp/client/channel_cc.cc +++ b/contrib/libs/grpc/src/cpp/client/channel_cc.cc @@ -1,30 +1,30 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/channel.h> - + #include <cstring> -#include <memory> - -#include <grpc/grpc.h> -#include <grpc/slice.h> -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> +#include <memory> + +#include <grpc/grpc.h> +#include <grpc/slice.h> +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> #include <grpc/support/sync.h> #include <grpc/support/time.h> #include <grpcpp/client_context.h> @@ -40,28 +40,28 @@ #include <grpcpp/support/status.h> #include "src/core/lib/gpr/string.h" #include "src/core/lib/surface/completion_queue.h" - + namespace grpc { - + static ::grpc::internal::GrpcLibraryInitializer g_gli_initializer; Channel::Channel(const TString& host, grpc_channel* channel, std::vector<std::unique_ptr< ::grpc::experimental::ClientInterceptorFactoryInterface>> interceptor_creators) - : host_(host), c_channel_(channel) { + : host_(host), c_channel_(channel) { interceptor_creators_ = std::move(interceptor_creators); - g_gli_initializer.summon(); -} - + g_gli_initializer.summon(); +} + Channel::~Channel() { grpc_channel_destroy(c_channel_); if (callback_cq_ != nullptr) { callback_cq_->Shutdown(); } } - -namespace { - + +namespace { + inline grpc_slice SliceFromArray(const char* arr, size_t len) { return g_core_codegen_interface->grpc_slice_from_copied_buffer(arr, len); } @@ -70,29 +70,29 @@ TString GetChannelInfoField(grpc_channel* channel, grpc_channel_info* channel_info, char*** channel_info_field) { char* value = nullptr; - memset(channel_info, 0, sizeof(*channel_info)); - *channel_info_field = &value; - grpc_channel_get_info(channel, channel_info); + memset(channel_info, 0, sizeof(*channel_info)); + *channel_info_field = &value; + grpc_channel_get_info(channel, channel_info); if (value == nullptr) return ""; TString result = value; - gpr_free(value); - return result; -} - -} // namespace - + gpr_free(value); + return result; +} + +} // namespace + TString Channel::GetLoadBalancingPolicyName() const { - grpc_channel_info channel_info; - return GetChannelInfoField(c_channel_, &channel_info, - &channel_info.lb_policy_name); -} - + grpc_channel_info channel_info; + return GetChannelInfoField(c_channel_, &channel_info, + &channel_info.lb_policy_name); +} + TString Channel::GetServiceConfigJSON() const { - grpc_channel_info channel_info; - return GetChannelInfoField(c_channel_, &channel_info, - &channel_info.service_config_json); -} - + grpc_channel_info channel_info; + return GetChannelInfoField(c_channel_, &channel_info, + &channel_info.service_config_json); +} + namespace experimental { void ChannelResetConnectionBackoff(Channel* channel) { @@ -104,20 +104,20 @@ void ChannelResetConnectionBackoff(Channel* channel) { ::grpc::internal::Call Channel::CreateCallInternal( const ::grpc::internal::RpcMethod& method, ::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, size_t interceptor_pos) { - const bool kRegistered = method.channel_tag() && context->authority().empty(); + const bool kRegistered = method.channel_tag() && context->authority().empty(); grpc_call* c_call = nullptr; - if (kRegistered) { - c_call = grpc_channel_create_registered_call( - c_channel_, context->propagate_from_call_, - context->propagation_options_.c_bitmask(), cq->cq(), - method.channel_tag(), context->raw_deadline(), nullptr); - } else { + if (kRegistered) { + c_call = grpc_channel_create_registered_call( + c_channel_, context->propagate_from_call_, + context->propagation_options_.c_bitmask(), cq->cq(), + method.channel_tag(), context->raw_deadline(), nullptr); + } else { const ::TString* host_str = nullptr; if (!context->authority_.empty()) { host_str = &context->authority_; - } else if (!host_.empty()) { + } else if (!host_.empty()) { host_str = &host_; - } + } grpc_slice method_slice = SliceFromArray(method.name(), strlen(method.name())); grpc_slice host_slice; @@ -133,8 +133,8 @@ void ChannelResetConnectionBackoff(Channel* channel) { if (host_str != nullptr) { grpc_slice_unref(host_slice); } - } - grpc_census_call_set_context(c_call, context->census_context()); + } + grpc_census_call_set_context(c_call, context->census_context()); // ClientRpcInfo should be set before call because set_call also checks // whether the call has been cancelled, and if the call was cancelled, we @@ -142,11 +142,11 @@ void ChannelResetConnectionBackoff(Channel* channel) { auto* info = context->set_client_rpc_info(method.name(), method.method_type(), this, interceptor_creators_, interceptor_pos); - context->set_call(c_call, shared_from_this()); + context->set_call(c_call, shared_from_this()); return ::grpc::internal::Call(c_call, this, cq, info); -} - +} + ::grpc::internal::Call Channel::CreateCall( const ::grpc::internal::RpcMethod& method, ::grpc::ClientContext* context, CompletionQueue* cq) { @@ -157,54 +157,54 @@ void Channel::PerformOpsOnCall(::grpc::internal::CallOpSetInterface* ops, ::grpc::internal::Call* call) { ops->FillOps( call); // Make a copy of call. It's fine since Call just has pointers -} - -void* Channel::RegisterMethod(const char* method) { - return grpc_channel_register_call( +} + +void* Channel::RegisterMethod(const char* method) { + return grpc_channel_register_call( c_channel_, method, host_.empty() ? nullptr : host_.c_str(), nullptr); -} - -grpc_connectivity_state Channel::GetState(bool try_to_connect) { - return grpc_channel_check_connectivity_state(c_channel_, try_to_connect); -} - -namespace { +} + +grpc_connectivity_state Channel::GetState(bool try_to_connect) { + return grpc_channel_check_connectivity_state(c_channel_, try_to_connect); +} + +namespace { class TagSaver final : public ::grpc::internal::CompletionQueueTag { - public: - explicit TagSaver(void* tag) : tag_(tag) {} - ~TagSaver() override {} + public: + explicit TagSaver(void* tag) : tag_(tag) {} + ~TagSaver() override {} bool FinalizeResult(void** tag, bool* /*status*/) override { - *tag = tag_; - delete this; - return true; - } - - private: - void* tag_; -}; - -} // namespace - -void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed, - gpr_timespec deadline, + *tag = tag_; + delete this; + return true; + } + + private: + void* tag_; +}; + +} // namespace + +void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed, + gpr_timespec deadline, ::grpc::CompletionQueue* cq, void* tag) { - TagSaver* tag_saver = new TagSaver(tag); - grpc_channel_watch_connectivity_state(c_channel_, last_observed, deadline, - cq->cq(), tag_saver); -} - -bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed, - gpr_timespec deadline) { + TagSaver* tag_saver = new TagSaver(tag); + grpc_channel_watch_connectivity_state(c_channel_, last_observed, deadline, + cq->cq(), tag_saver); +} + +bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed, + gpr_timespec deadline) { ::grpc::CompletionQueue cq; - bool ok = false; + bool ok = false; void* tag = nullptr; NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr); - cq.Next(&tag, &ok); + cq.Next(&tag, &ok); GPR_ASSERT(tag == nullptr); - return ok; -} - + return ok; +} + namespace { class ShutdownCallback : public grpc_experimental_completion_queue_functor { public: diff --git a/contrib/libs/grpc/src/cpp/client/client_context.cc b/contrib/libs/grpc/src/cpp/client/client_context.cc index b75343d089..458965186c 100644 --- a/contrib/libs/grpc/src/cpp/client/client_context.cc +++ b/contrib/libs/grpc/src/cpp/client/client_context.cc @@ -1,77 +1,77 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/client_context.h> - -#include <grpc/compression.h> -#include <grpc/grpc.h> -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/string_util.h> - + +#include <grpc/compression.h> +#include <grpc/grpc.h> +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/string_util.h> + #include <grpcpp/impl/codegen/interceptor_common.h> #include <grpcpp/impl/codegen/sync.h> #include <grpcpp/impl/grpc_library.h> #include <grpcpp/security/credentials.h> #include <grpcpp/server_context.h> #include <grpcpp/support/time.h> - + namespace grpc { - + class Channel; -class DefaultGlobalClientCallbacks final - : public ClientContext::GlobalCallbacks { - public: - ~DefaultGlobalClientCallbacks() override {} +class DefaultGlobalClientCallbacks final + : public ClientContext::GlobalCallbacks { + public: + ~DefaultGlobalClientCallbacks() override {} void DefaultConstructor(ClientContext* /*context*/) override {} void Destructor(ClientContext* /*context*/) override {} -}; - +}; + static internal::GrpcLibraryInitializer g_gli_initializer; static DefaultGlobalClientCallbacks* g_default_client_callbacks = new DefaultGlobalClientCallbacks(); -static ClientContext::GlobalCallbacks* g_client_callbacks = +static ClientContext::GlobalCallbacks* g_client_callbacks = g_default_client_callbacks; - -ClientContext::ClientContext() - : initial_metadata_received_(false), - wait_for_ready_(false), - wait_for_ready_explicitly_set_(false), - idempotent_(false), - cacheable_(false), - call_(nullptr), - call_canceled_(false), - deadline_(gpr_inf_future(GPR_CLOCK_REALTIME)), - census_context_(nullptr), + +ClientContext::ClientContext() + : initial_metadata_received_(false), + wait_for_ready_(false), + wait_for_ready_explicitly_set_(false), + idempotent_(false), + cacheable_(false), + call_(nullptr), + call_canceled_(false), + deadline_(gpr_inf_future(GPR_CLOCK_REALTIME)), + census_context_(nullptr), propagate_from_call_(nullptr), compression_algorithm_(GRPC_COMPRESS_NONE), initial_metadata_corked_(false) { - g_client_callbacks->DefaultConstructor(this); -} - -ClientContext::~ClientContext() { - if (call_) { + g_client_callbacks->DefaultConstructor(this); +} + +ClientContext::~ClientContext() { + if (call_) { grpc_call_unref(call_); - } - g_client_callbacks->Destructor(this); -} - + } + g_client_callbacks->Destructor(this); +} + void ClientContext::set_credentials( const std::shared_ptr<CallCredentials>& creds) { creds_ = creds; @@ -90,12 +90,12 @@ void ClientContext::set_credentials( std::unique_ptr<ClientContext> ClientContext::FromInternalServerContext( const grpc::ServerContextBase& context, PropagationOptions options) { - std::unique_ptr<ClientContext> ctx(new ClientContext); + std::unique_ptr<ClientContext> ctx(new ClientContext); ctx->propagate_from_call_ = context.call_.call; - ctx->propagation_options_ = options; - return ctx; -} - + ctx->propagation_options_ = options; + return ctx; +} + std::unique_ptr<ClientContext> ClientContext::FromServerContext( const grpc::ServerContext& server_context, PropagationOptions options) { return FromInternalServerContext(server_context, options); @@ -109,50 +109,50 @@ std::unique_ptr<ClientContext> ClientContext::FromCallbackServerContext( void ClientContext::AddMetadata(const TString& meta_key, const TString& meta_value) { - send_initial_metadata_.insert(std::make_pair(meta_key, meta_value)); -} - + send_initial_metadata_.insert(std::make_pair(meta_key, meta_value)); +} + void ClientContext::set_call(grpc_call* call, const std::shared_ptr<Channel>& channel) { internal::MutexLock lock(&mu_); - GPR_ASSERT(call_ == nullptr); - call_ = call; - channel_ = channel; - if (creds_ && !creds_->ApplyToCall(call_)) { + GPR_ASSERT(call_ == nullptr); + call_ = call; + channel_ = channel; + if (creds_ && !creds_->ApplyToCall(call_)) { // TODO(yashykt): should interceptors also see this status? SendCancelToInterceptors(); - grpc_call_cancel_with_status(call, GRPC_STATUS_CANCELLED, - "Failed to set credentials to rpc.", nullptr); - } - if (call_canceled_) { + grpc_call_cancel_with_status(call, GRPC_STATUS_CANCELLED, + "Failed to set credentials to rpc.", nullptr); + } + if (call_canceled_) { SendCancelToInterceptors(); - grpc_call_cancel(call_, nullptr); - } -} - -void ClientContext::set_compression_algorithm( - grpc_compression_algorithm algorithm) { + grpc_call_cancel(call_, nullptr); + } +} + +void ClientContext::set_compression_algorithm( + grpc_compression_algorithm algorithm) { compression_algorithm_ = algorithm; const char* algorithm_name = nullptr; - if (!grpc_compression_algorithm_name(algorithm, &algorithm_name)) { - gpr_log(GPR_ERROR, "Name for compression algorithm '%d' unknown.", - algorithm); - abort(); - } - GPR_ASSERT(algorithm_name != nullptr); - AddMetadata(GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY, algorithm_name); -} - -void ClientContext::TryCancel() { + if (!grpc_compression_algorithm_name(algorithm, &algorithm_name)) { + gpr_log(GPR_ERROR, "Name for compression algorithm '%d' unknown.", + algorithm); + abort(); + } + GPR_ASSERT(algorithm_name != nullptr); + AddMetadata(GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY, algorithm_name); +} + +void ClientContext::TryCancel() { internal::MutexLock lock(&mu_); - if (call_) { + if (call_) { SendCancelToInterceptors(); - grpc_call_cancel(call_, nullptr); - } else { - call_canceled_ = true; - } -} - + grpc_call_cancel(call_, nullptr); + } else { + call_canceled_ = true; + } +} + void ClientContext::SendCancelToInterceptors() { internal::CancelInterceptorBatchMethods cancel_methods; for (size_t i = 0; i < rpc_info_.interceptors_.size(); i++) { @@ -162,19 +162,19 @@ void ClientContext::SendCancelToInterceptors() { TString ClientContext::peer() const { TString peer; - if (call_) { - char* c_peer = grpc_call_get_peer(call_); - peer = c_peer; - gpr_free(c_peer); - } - return peer; -} - -void ClientContext::SetGlobalCallbacks(GlobalCallbacks* client_callbacks) { + if (call_) { + char* c_peer = grpc_call_get_peer(call_); + peer = c_peer; + gpr_free(c_peer); + } + return peer; +} + +void ClientContext::SetGlobalCallbacks(GlobalCallbacks* client_callbacks) { GPR_ASSERT(g_client_callbacks == g_default_client_callbacks); GPR_ASSERT(client_callbacks != nullptr); GPR_ASSERT(client_callbacks != g_default_client_callbacks); - g_client_callbacks = client_callbacks; -} - + g_client_callbacks = client_callbacks; +} + } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/client/create_channel.cc b/contrib/libs/grpc/src/cpp/client/create_channel.cc index 97327490ed..9958d317c6 100644 --- a/contrib/libs/grpc/src/cpp/client/create_channel.cc +++ b/contrib/libs/grpc/src/cpp/client/create_channel.cc @@ -1,40 +1,40 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#include <memory> - + * + */ + +#include <memory> + #include <grpcpp/channel.h> #include <grpcpp/create_channel.h> #include <grpcpp/impl/grpc_library.h> #include <grpcpp/security/credentials.h> #include <grpcpp/support/channel_arguments.h> - -#include "src/cpp/client/create_channel_internal.h" - + +#include "src/cpp/client/create_channel_internal.h" + namespace grpc { std::shared_ptr<grpc::Channel> CreateChannel( - const grpc::string& target, + const grpc::string& target, const std::shared_ptr<grpc::ChannelCredentials>& creds) { return CreateCustomChannel(target, creds, grpc::ChannelArguments()); -} - +} + std::shared_ptr<grpc::Channel> CreateCustomChannel( - const grpc::string& target, + const grpc::string& target, const std::shared_ptr<grpc::ChannelCredentials>& creds, const grpc::ChannelArguments& args) { grpc::GrpcLibraryCodegen @@ -48,8 +48,8 @@ std::shared_ptr<grpc::Channel> CreateCustomChannel( std::vector<std::unique_ptr< grpc::experimental:: ClientInterceptorFactoryInterface>>()); -} - +} + namespace experimental { /// Create a new \em custom \a Channel pointing to \a target with \a /// interceptors being invoked per call. diff --git a/contrib/libs/grpc/src/cpp/client/create_channel_internal.cc b/contrib/libs/grpc/src/cpp/client/create_channel_internal.cc index da2a878a22..ff961afc78 100644 --- a/contrib/libs/grpc/src/cpp/client/create_channel_internal.cc +++ b/contrib/libs/grpc/src/cpp/client/create_channel_internal.cc @@ -1,29 +1,29 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#include <memory> - + * + */ + +#include <memory> + #include <grpcpp/channel.h> - -struct grpc_channel; - -namespace grpc { - + +struct grpc_channel; + +namespace grpc { + std::shared_ptr<Channel> CreateChannelInternal( const TString& host, grpc_channel* c_channel, std::vector<std::unique_ptr< @@ -31,6 +31,6 @@ std::shared_ptr<Channel> CreateChannelInternal( interceptor_creators) { return std::shared_ptr<Channel>( new Channel(host, c_channel, std::move(interceptor_creators))); -} +} -} // namespace grpc +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/client/create_channel_internal.h b/contrib/libs/grpc/src/cpp/client/create_channel_internal.h index 09d4e56b02..e944622298 100644 --- a/contrib/libs/grpc/src/cpp/client/create_channel_internal.h +++ b/contrib/libs/grpc/src/cpp/client/create_channel_internal.h @@ -1,40 +1,40 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#ifndef GRPC_INTERNAL_CPP_CLIENT_CREATE_CHANNEL_INTERNAL_H -#define GRPC_INTERNAL_CPP_CLIENT_CREATE_CHANNEL_INTERNAL_H - -#include <memory> - + * + */ + +#ifndef GRPC_INTERNAL_CPP_CLIENT_CREATE_CHANNEL_INTERNAL_H +#define GRPC_INTERNAL_CPP_CLIENT_CREATE_CHANNEL_INTERNAL_H + +#include <memory> + #include <grpcpp/channel.h> #include <grpcpp/impl/codegen/client_interceptor.h> #include <grpcpp/support/config.h> - -struct grpc_channel; - -namespace grpc { - + +struct grpc_channel; + +namespace grpc { + std::shared_ptr<Channel> CreateChannelInternal( const TString& host, grpc_channel* c_channel, std::vector<std::unique_ptr< ::grpc::experimental::ClientInterceptorFactoryInterface>> interceptor_creators); - -} // namespace grpc - -#endif // GRPC_INTERNAL_CPP_CLIENT_CREATE_CHANNEL_INTERNAL_H + +} // namespace grpc + +#endif // GRPC_INTERNAL_CPP_CLIENT_CREATE_CHANNEL_INTERNAL_H diff --git a/contrib/libs/grpc/src/cpp/client/create_channel_posix.cc b/contrib/libs/grpc/src/cpp/client/create_channel_posix.cc index db09eda8a6..9a84e105f4 100644 --- a/contrib/libs/grpc/src/cpp/client/create_channel_posix.cc +++ b/contrib/libs/grpc/src/cpp/client/create_channel_posix.cc @@ -1,58 +1,58 @@ -/* - * +/* + * * Copyright 2016 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#include <grpc/grpc.h> -#include <grpc/grpc_posix.h> + * + */ + +#include <grpc/grpc.h> +#include <grpc/grpc_posix.h> #include <grpcpp/channel.h> #include <grpcpp/impl/grpc_library.h> #include <grpcpp/support/channel_arguments.h> - -#include "src/cpp/client/create_channel_internal.h" - + +#include "src/cpp/client/create_channel_internal.h" + namespace grpc { - + class ChannelArguments; -#ifdef GPR_SUPPORT_CHANNELS_FROM_FD - +#ifdef GPR_SUPPORT_CHANNELS_FROM_FD + std::shared_ptr<Channel> CreateInsecureChannelFromFd(const TString& target, int fd) { grpc::internal::GrpcLibrary init_lib; - init_lib.init(); + init_lib.init(); return CreateChannelInternal( "", grpc_insecure_channel_create_from_fd(target.c_str(), fd, nullptr), std::vector< std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>()); -} - +} + std::shared_ptr<Channel> CreateCustomInsecureChannelFromFd( const TString& target, int fd, const grpc::ChannelArguments& args) { internal::GrpcLibrary init_lib; - init_lib.init(); - grpc_channel_args channel_args; - args.SetChannelArgs(&channel_args); + init_lib.init(); + grpc_channel_args channel_args; + args.SetChannelArgs(&channel_args); return CreateChannelInternal( "", grpc_insecure_channel_create_from_fd(target.c_str(), fd, &channel_args), std::vector< std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>()); -} - +} + namespace experimental { std::shared_ptr<Channel> CreateCustomInsecureChannelWithInterceptorsFromFd( @@ -72,6 +72,6 @@ std::shared_ptr<Channel> CreateCustomInsecureChannelWithInterceptorsFromFd( } // namespace experimental -#endif // GPR_SUPPORT_CHANNELS_FROM_FD - +#endif // GPR_SUPPORT_CHANNELS_FROM_FD + } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/client/credentials_cc.cc b/contrib/libs/grpc/src/cpp/client/credentials_cc.cc index 9dfb2f491c..5c673c2f5b 100644 --- a/contrib/libs/grpc/src/cpp/client/credentials_cc.cc +++ b/contrib/libs/grpc/src/cpp/client/credentials_cc.cc @@ -1,33 +1,33 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/impl/grpc_library.h> #include <grpcpp/security/credentials.h> - + namespace grpc { - + static grpc::internal::GrpcLibraryInitializer g_gli_initializer; -ChannelCredentials::ChannelCredentials() { g_gli_initializer.summon(); } - -ChannelCredentials::~ChannelCredentials() {} - -CallCredentials::CallCredentials() { g_gli_initializer.summon(); } - -CallCredentials::~CallCredentials() {} - +ChannelCredentials::ChannelCredentials() { g_gli_initializer.summon(); } + +ChannelCredentials::~ChannelCredentials() {} + +CallCredentials::CallCredentials() { g_gli_initializer.summon(); } + +CallCredentials::~CallCredentials() {} + } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/client/insecure_credentials.cc b/contrib/libs/grpc/src/cpp/client/insecure_credentials.cc index e5bafff70a..9d9586fcb1 100644 --- a/contrib/libs/grpc/src/cpp/client/insecure_credentials.cc +++ b/contrib/libs/grpc/src/cpp/client/insecure_credentials.cc @@ -1,34 +1,34 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ + * + */ #include <grpcpp/security/credentials.h> - -#include <grpc/grpc.h> -#include <grpc/support/log.h> + +#include <grpc/grpc.h> +#include <grpc/support/log.h> #include <grpcpp/channel.h> #include <grpcpp/support/channel_arguments.h> #include <grpcpp/support/config.h> -#include "src/cpp/client/create_channel_internal.h" - +#include "src/cpp/client/create_channel_internal.h" + namespace grpc { - -namespace { -class InsecureChannelCredentialsImpl final : public ChannelCredentials { - public: + +namespace { +class InsecureChannelCredentialsImpl final : public ChannelCredentials { + public: std::shared_ptr<Channel> CreateChannelImpl( const TString& target, const ChannelArguments& args) override { return CreateChannelWithInterceptors( @@ -42,21 +42,21 @@ class InsecureChannelCredentialsImpl final : public ChannelCredentials { std::vector<std::unique_ptr< grpc::experimental::ClientInterceptorFactoryInterface>> interceptor_creators) override { - grpc_channel_args channel_args; - args.SetChannelArgs(&channel_args); + grpc_channel_args channel_args; + args.SetChannelArgs(&channel_args); return ::grpc::CreateChannelInternal( - "", + "", grpc_insecure_channel_create(target.c_str(), &channel_args, nullptr), std::move(interceptor_creators)); - } - - SecureChannelCredentials* AsSecureCredentials() override { return nullptr; } -}; -} // namespace - -std::shared_ptr<ChannelCredentials> InsecureChannelCredentials() { - return std::shared_ptr<ChannelCredentials>( - new InsecureChannelCredentialsImpl()); -} - + } + + SecureChannelCredentials* AsSecureCredentials() override { return nullptr; } +}; +} // namespace + +std::shared_ptr<ChannelCredentials> InsecureChannelCredentials() { + return std::shared_ptr<ChannelCredentials>( + new InsecureChannelCredentialsImpl()); +} + } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/client/secure_credentials.cc b/contrib/libs/grpc/src/cpp/client/secure_credentials.cc index 0f6db3caa5..882d66ee17 100644 --- a/contrib/libs/grpc/src/cpp/client/secure_credentials.cc +++ b/contrib/libs/grpc/src/cpp/client/secure_credentials.cc @@ -1,27 +1,27 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#include "src/cpp/client/secure_credentials.h" + * + */ + +#include "src/cpp/client/secure_credentials.h" #include <grpc/impl/codegen/slice.h> #include <grpc/slice.h> #include <grpc/support/alloc.h> -#include <grpc/support/log.h> +#include <grpc/support/log.h> #include <grpc/support/string_util.h> #include <grpcpp/channel.h> #include <grpcpp/impl/codegen/status.h> @@ -35,18 +35,18 @@ #include "src/core/lib/json/json.h" #include "src/core/lib/security/transport/auth_filters.h" #include "src/core/lib/security/util/json_util.h" -#include "src/cpp/client/create_channel_internal.h" -#include "src/cpp/common/secure_auth_context.h" - +#include "src/cpp/client/create_channel_internal.h" +#include "src/cpp/common/secure_auth_context.h" + namespace grpc { - + static grpc::internal::GrpcLibraryInitializer g_gli_initializer; -SecureChannelCredentials::SecureChannelCredentials( - grpc_channel_credentials* c_creds) - : c_creds_(c_creds) { - g_gli_initializer.summon(); -} - +SecureChannelCredentials::SecureChannelCredentials( + grpc_channel_credentials* c_creds) + : c_creds_(c_creds) { + g_gli_initializer.summon(); +} + std::shared_ptr<Channel> SecureChannelCredentials::CreateChannelImpl( const TString& target, const ChannelArguments& args) { return CreateChannelWithInterceptors( @@ -61,60 +61,60 @@ SecureChannelCredentials::CreateChannelWithInterceptors( std::vector< std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>> interceptor_creators) { - grpc_channel_args channel_args; - args.SetChannelArgs(&channel_args); + grpc_channel_args channel_args; + args.SetChannelArgs(&channel_args); return ::grpc::CreateChannelInternal( - args.GetSslTargetNameOverride(), - grpc_secure_channel_create(c_creds_, target.c_str(), &channel_args, + args.GetSslTargetNameOverride(), + grpc_secure_channel_create(c_creds_, target.c_str(), &channel_args, nullptr), std::move(interceptor_creators)); -} - -SecureCallCredentials::SecureCallCredentials(grpc_call_credentials* c_creds) - : c_creds_(c_creds) { - g_gli_initializer.summon(); -} - -bool SecureCallCredentials::ApplyToCall(grpc_call* call) { - return grpc_call_set_credentials(call, c_creds_) == GRPC_CALL_OK; -} - -namespace { -std::shared_ptr<ChannelCredentials> WrapChannelCredentials( - grpc_channel_credentials* creds) { +} + +SecureCallCredentials::SecureCallCredentials(grpc_call_credentials* c_creds) + : c_creds_(c_creds) { + g_gli_initializer.summon(); +} + +bool SecureCallCredentials::ApplyToCall(grpc_call* call) { + return grpc_call_set_credentials(call, c_creds_) == GRPC_CALL_OK; +} + +namespace { +std::shared_ptr<ChannelCredentials> WrapChannelCredentials( + grpc_channel_credentials* creds) { return creds == nullptr ? nullptr : std::shared_ptr<ChannelCredentials>( new SecureChannelCredentials(creds)); -} - -std::shared_ptr<CallCredentials> WrapCallCredentials( - grpc_call_credentials* creds) { +} + +std::shared_ptr<CallCredentials> WrapCallCredentials( + grpc_call_credentials* creds) { return creds == nullptr ? nullptr : std::shared_ptr<CallCredentials>( new SecureCallCredentials(creds)); -} -} // namespace - -std::shared_ptr<ChannelCredentials> GoogleDefaultCredentials() { +} +} // namespace + +std::shared_ptr<ChannelCredentials> GoogleDefaultCredentials() { grpc::GrpcLibraryCodegen init; // To call grpc_init(). return WrapChannelCredentials( grpc_google_default_credentials_create(nullptr)); -} - -// Builds SSL Credentials given SSL specific options -std::shared_ptr<ChannelCredentials> SslCredentials( - const SslCredentialsOptions& options) { +} + +// Builds SSL Credentials given SSL specific options +std::shared_ptr<ChannelCredentials> SslCredentials( + const SslCredentialsOptions& options) { grpc::GrpcLibraryCodegen init; // To call grpc_init(). - grpc_ssl_pem_key_cert_pair pem_key_cert_pair = { - options.pem_private_key.c_str(), options.pem_cert_chain.c_str()}; - - grpc_channel_credentials* c_creds = grpc_ssl_credentials_create( - options.pem_root_certs.empty() ? nullptr : options.pem_root_certs.c_str(), + grpc_ssl_pem_key_cert_pair pem_key_cert_pair = { + options.pem_private_key.c_str(), options.pem_cert_chain.c_str()}; + + grpc_channel_credentials* c_creds = grpc_ssl_credentials_create( + options.pem_root_certs.empty() ? nullptr : options.pem_root_certs.c_str(), options.pem_private_key.empty() ? nullptr : &pem_key_cert_pair, nullptr, nullptr); - return WrapChannelCredentials(c_creds); -} - + return WrapChannelCredentials(c_creds); +} + namespace experimental { namespace { @@ -296,72 +296,72 @@ std::shared_ptr<ChannelCredentials> TlsCredentials( } // namespace experimental -// Builds credentials for use when running in GCE -std::shared_ptr<CallCredentials> GoogleComputeEngineCredentials() { +// Builds credentials for use when running in GCE +std::shared_ptr<CallCredentials> GoogleComputeEngineCredentials() { grpc::GrpcLibraryCodegen init; // To call grpc_init(). - return WrapCallCredentials( - grpc_google_compute_engine_credentials_create(nullptr)); -} - -// Builds JWT credentials. -std::shared_ptr<CallCredentials> ServiceAccountJWTAccessCredentials( + return WrapCallCredentials( + grpc_google_compute_engine_credentials_create(nullptr)); +} + +// Builds JWT credentials. +std::shared_ptr<CallCredentials> ServiceAccountJWTAccessCredentials( const TString& json_key, long token_lifetime_seconds) { grpc::GrpcLibraryCodegen init; // To call grpc_init(). - if (token_lifetime_seconds <= 0) { - gpr_log(GPR_ERROR, - "Trying to create JWTCredentials with non-positive lifetime"); - return WrapCallCredentials(nullptr); - } - gpr_timespec lifetime = - gpr_time_from_seconds(token_lifetime_seconds, GPR_TIMESPAN); - return WrapCallCredentials(grpc_service_account_jwt_access_credentials_create( - json_key.c_str(), lifetime, nullptr)); -} - -// Builds refresh token credentials. -std::shared_ptr<CallCredentials> GoogleRefreshTokenCredentials( + if (token_lifetime_seconds <= 0) { + gpr_log(GPR_ERROR, + "Trying to create JWTCredentials with non-positive lifetime"); + return WrapCallCredentials(nullptr); + } + gpr_timespec lifetime = + gpr_time_from_seconds(token_lifetime_seconds, GPR_TIMESPAN); + return WrapCallCredentials(grpc_service_account_jwt_access_credentials_create( + json_key.c_str(), lifetime, nullptr)); +} + +// Builds refresh token credentials. +std::shared_ptr<CallCredentials> GoogleRefreshTokenCredentials( const TString& json_refresh_token) { grpc::GrpcLibraryCodegen init; // To call grpc_init(). - return WrapCallCredentials(grpc_google_refresh_token_credentials_create( - json_refresh_token.c_str(), nullptr)); -} - -// Builds access token credentials. -std::shared_ptr<CallCredentials> AccessTokenCredentials( + return WrapCallCredentials(grpc_google_refresh_token_credentials_create( + json_refresh_token.c_str(), nullptr)); +} + +// Builds access token credentials. +std::shared_ptr<CallCredentials> AccessTokenCredentials( const TString& access_token) { grpc::GrpcLibraryCodegen init; // To call grpc_init(). - return WrapCallCredentials( - grpc_access_token_credentials_create(access_token.c_str(), nullptr)); -} - -// Builds IAM credentials. -std::shared_ptr<CallCredentials> GoogleIAMCredentials( + return WrapCallCredentials( + grpc_access_token_credentials_create(access_token.c_str(), nullptr)); +} + +// Builds IAM credentials. +std::shared_ptr<CallCredentials> GoogleIAMCredentials( const TString& authorization_token, const TString& authority_selector) { grpc::GrpcLibraryCodegen init; // To call grpc_init(). - return WrapCallCredentials(grpc_google_iam_credentials_create( - authorization_token.c_str(), authority_selector.c_str(), nullptr)); -} - -// Combines one channel credentials and one call credentials into a channel -// composite credentials. -std::shared_ptr<ChannelCredentials> CompositeChannelCredentials( - const std::shared_ptr<ChannelCredentials>& channel_creds, - const std::shared_ptr<CallCredentials>& call_creds) { - // Note that we are not saving shared_ptrs to the two credentials passed in - // here. This is OK because the underlying C objects (i.e., channel_creds and - // call_creds) into grpc_composite_credentials_create will see their refcounts - // incremented. - SecureChannelCredentials* s_channel_creds = - channel_creds->AsSecureCredentials(); - SecureCallCredentials* s_call_creds = call_creds->AsSecureCredentials(); - if (s_channel_creds && s_call_creds) { - return WrapChannelCredentials(grpc_composite_channel_credentials_create( - s_channel_creds->GetRawCreds(), s_call_creds->GetRawCreds(), nullptr)); - } - return nullptr; -} - + return WrapCallCredentials(grpc_google_iam_credentials_create( + authorization_token.c_str(), authority_selector.c_str(), nullptr)); +} + +// Combines one channel credentials and one call credentials into a channel +// composite credentials. +std::shared_ptr<ChannelCredentials> CompositeChannelCredentials( + const std::shared_ptr<ChannelCredentials>& channel_creds, + const std::shared_ptr<CallCredentials>& call_creds) { + // Note that we are not saving shared_ptrs to the two credentials passed in + // here. This is OK because the underlying C objects (i.e., channel_creds and + // call_creds) into grpc_composite_credentials_create will see their refcounts + // incremented. + SecureChannelCredentials* s_channel_creds = + channel_creds->AsSecureCredentials(); + SecureCallCredentials* s_call_creds = call_creds->AsSecureCredentials(); + if (s_channel_creds && s_call_creds) { + return WrapChannelCredentials(grpc_composite_channel_credentials_create( + s_channel_creds->GetRawCreds(), s_call_creds->GetRawCreds(), nullptr)); + } + return nullptr; +} + std::shared_ptr<CallCredentials> CompositeCallCredentials( const std::shared_ptr<CallCredentials>& creds1, const std::shared_ptr<CallCredentials>& creds2) { @@ -390,12 +390,12 @@ std::shared_ptr<CallCredentials> MetadataCredentialsFromPlugin( namespace { void DeleteWrapper(void* wrapper, grpc_error* /*ignored*/) { - MetadataCredentialsPluginWrapper* w = + MetadataCredentialsPluginWrapper* w = static_cast<MetadataCredentialsPluginWrapper*>(wrapper); - delete w; -} + delete w; +} } // namespace - + char* MetadataCredentialsPluginWrapper::DebugString(void* wrapper) { GPR_ASSERT(wrapper); MetadataCredentialsPluginWrapper* w = @@ -412,21 +412,21 @@ void MetadataCredentialsPluginWrapper::Destroy(void* wrapper) { } int MetadataCredentialsPluginWrapper::GetMetadata( - void* wrapper, grpc_auth_metadata_context context, + void* wrapper, grpc_auth_metadata_context context, grpc_credentials_plugin_metadata_cb cb, void* user_data, grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], size_t* num_creds_md, grpc_status_code* status, const char** error_details) { - GPR_ASSERT(wrapper); - MetadataCredentialsPluginWrapper* w = + GPR_ASSERT(wrapper); + MetadataCredentialsPluginWrapper* w = static_cast<MetadataCredentialsPluginWrapper*>(wrapper); - if (!w->plugin_) { + if (!w->plugin_) { *num_creds_md = 0; *status = GRPC_STATUS_OK; *error_details = nullptr; return 1; - } - if (w->plugin_->IsBlocking()) { + } + if (w->plugin_->IsBlocking()) { // The internals of context may be destroyed if GetMetadata is cancelled. // Make a copy for InvokePlugin. grpc_auth_metadata_context context_copy = grpc_auth_metadata_context(); @@ -438,14 +438,14 @@ int MetadataCredentialsPluginWrapper::GetMetadata( grpc_auth_metadata_context_reset(&context_copy); }); return 0; - } else { + } else { // Synchronous return. w->InvokePlugin(context, cb, user_data, creds_md, num_creds_md, status, error_details); return 1; - } -} - + } +} + namespace { void UnrefMetadata(const std::vector<grpc_metadata>& md) { @@ -457,27 +457,27 @@ void UnrefMetadata(const std::vector<grpc_metadata>& md) { } // namespace -void MetadataCredentialsPluginWrapper::InvokePlugin( - grpc_auth_metadata_context context, grpc_credentials_plugin_metadata_cb cb, +void MetadataCredentialsPluginWrapper::InvokePlugin( + grpc_auth_metadata_context context, grpc_credentials_plugin_metadata_cb cb, void* user_data, grpc_metadata creds_md[4], size_t* num_creds_md, grpc_status_code* status_code, const char** error_details) { std::multimap<TString, TString> metadata; - + // const_cast is safe since the SecureAuthContext only inc/dec the refcount // and the object is passed as a const ref to plugin_->GetMetadata. - SecureAuthContext cpp_channel_auth_context( + SecureAuthContext cpp_channel_auth_context( const_cast<grpc_auth_context*>(context.channel_auth_context)); - - Status status = plugin_->GetMetadata(context.service_url, context.method_name, - cpp_channel_auth_context, &metadata); - std::vector<grpc_metadata> md; + + Status status = plugin_->GetMetadata(context.service_url, context.method_name, + cpp_channel_auth_context, &metadata); + std::vector<grpc_metadata> md; for (auto& metadatum : metadata) { - grpc_metadata md_entry; + grpc_metadata md_entry; md_entry.key = SliceFromCopiedString(metadatum.first); md_entry.value = SliceFromCopiedString(metadatum.second); - md_entry.flags = 0; - md.push_back(md_entry); - } + md_entry.flags = 0; + md.push_back(md_entry); + } if (creds_md != nullptr) { // Synchronous return. if (md.size() > GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX) { @@ -504,10 +504,10 @@ void MetadataCredentialsPluginWrapper::InvokePlugin( status.error_message().c_str()); UnrefMetadata(md); } -} - -MetadataCredentialsPluginWrapper::MetadataCredentialsPluginWrapper( - std::unique_ptr<MetadataCredentialsPlugin> plugin) - : thread_pool_(CreateDefaultThreadPool()), plugin_(std::move(plugin)) {} - -} // namespace grpc +} + +MetadataCredentialsPluginWrapper::MetadataCredentialsPluginWrapper( + std::unique_ptr<MetadataCredentialsPlugin> plugin) + : thread_pool_(CreateDefaultThreadPool()), plugin_(std::move(plugin)) {} + +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/client/secure_credentials.h b/contrib/libs/grpc/src/cpp/client/secure_credentials.h index 4fc79346bf..3b7fbaaf02 100644 --- a/contrib/libs/grpc/src/cpp/client/secure_credentials.h +++ b/contrib/libs/grpc/src/cpp/client/secure_credentials.h @@ -1,79 +1,79 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#ifndef GRPC_INTERNAL_CPP_CLIENT_SECURE_CREDENTIALS_H -#define GRPC_INTERNAL_CPP_CLIENT_SECURE_CREDENTIALS_H - -#include <grpc/grpc_security.h> - + * + */ + +#ifndef GRPC_INTERNAL_CPP_CLIENT_SECURE_CREDENTIALS_H +#define GRPC_INTERNAL_CPP_CLIENT_SECURE_CREDENTIALS_H + +#include <grpc/grpc_security.h> + #include <grpcpp/security/credentials.h> #include <grpcpp/security/tls_credentials_options.h> #include <grpcpp/support/config.h> - + #include "y_absl/strings/str_cat.h" #include "src/core/lib/security/credentials/credentials.h" -#include "src/cpp/server/thread_pool_interface.h" - +#include "src/cpp/server/thread_pool_interface.h" + namespace grpc { - + class Channel; -class SecureChannelCredentials final : public ChannelCredentials { - public: - explicit SecureChannelCredentials(grpc_channel_credentials* c_creds); +class SecureChannelCredentials final : public ChannelCredentials { + public: + explicit SecureChannelCredentials(grpc_channel_credentials* c_creds); ~SecureChannelCredentials() { if (c_creds_ != nullptr) c_creds_->Unref(); } - grpc_channel_credentials* GetRawCreds() { return c_creds_; } - + grpc_channel_credentials* GetRawCreds() { return c_creds_; } + std::shared_ptr<Channel> CreateChannelImpl( const TString& target, const ChannelArguments& args) override; - SecureChannelCredentials* AsSecureCredentials() override { return this; } - - private: + SecureChannelCredentials* AsSecureCredentials() override { return this; } + + private: std::shared_ptr<Channel> CreateChannelWithInterceptors( const TString& target, const ChannelArguments& args, std::vector<std::unique_ptr< ::grpc::experimental::ClientInterceptorFactoryInterface>> interceptor_creators) override; - grpc_channel_credentials* const c_creds_; -}; - -class SecureCallCredentials final : public CallCredentials { - public: - explicit SecureCallCredentials(grpc_call_credentials* c_creds); + grpc_channel_credentials* const c_creds_; +}; + +class SecureCallCredentials final : public CallCredentials { + public: + explicit SecureCallCredentials(grpc_call_credentials* c_creds); ~SecureCallCredentials() { if (c_creds_ != nullptr) c_creds_->Unref(); } - grpc_call_credentials* GetRawCreds() { return c_creds_; } - - bool ApplyToCall(grpc_call* call) override; - SecureCallCredentials* AsSecureCredentials() override { return this; } + grpc_call_credentials* GetRawCreds() { return c_creds_; } + + bool ApplyToCall(grpc_call* call) override; + SecureCallCredentials* AsSecureCredentials() override { return this; } TString DebugString() override { return y_absl::StrCat("SecureCallCredentials{", TString(c_creds_->debug_string()), "}"); } - - private: - grpc_call_credentials* const c_creds_; -}; - + + private: + grpc_call_credentials* const c_creds_; +}; + namespace experimental { // Transforms C++ STS Credentials options to core options. The pointers of the @@ -85,8 +85,8 @@ grpc_sts_credentials_options StsCredentialsCppToCoreOptions( } // namespace experimental class MetadataCredentialsPluginWrapper final : private GrpcLibraryCodegen { - public: - static void Destroy(void* wrapper); + public: + static void Destroy(void* wrapper); static int GetMetadata( void* wrapper, grpc_auth_metadata_context context, grpc_credentials_plugin_metadata_cb cb, void* user_data, @@ -94,21 +94,21 @@ class MetadataCredentialsPluginWrapper final : private GrpcLibraryCodegen { size_t* num_creds_md, grpc_status_code* status, const char** error_details); static char* DebugString(void* wrapper); - - explicit MetadataCredentialsPluginWrapper( - std::unique_ptr<MetadataCredentialsPlugin> plugin); - - private: + + explicit MetadataCredentialsPluginWrapper( + std::unique_ptr<MetadataCredentialsPlugin> plugin); + + private: void InvokePlugin( grpc_auth_metadata_context context, grpc_credentials_plugin_metadata_cb cb, void* user_data, grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], size_t* num_creds_md, grpc_status_code* status_code, const char** error_details); - std::unique_ptr<ThreadPoolInterface> thread_pool_; - std::unique_ptr<MetadataCredentialsPlugin> plugin_; -}; - -} // namespace grpc - -#endif // GRPC_INTERNAL_CPP_CLIENT_SECURE_CREDENTIALS_H + std::unique_ptr<ThreadPoolInterface> thread_pool_; + std::unique_ptr<MetadataCredentialsPlugin> plugin_; +}; + +} // namespace grpc + +#endif // GRPC_INTERNAL_CPP_CLIENT_SECURE_CREDENTIALS_H diff --git a/contrib/libs/grpc/src/cpp/codegen/codegen_init.cc b/contrib/libs/grpc/src/cpp/codegen/codegen_init.cc index e1e47cbb17..5a0375c065 100644 --- a/contrib/libs/grpc/src/cpp/codegen/codegen_init.cc +++ b/contrib/libs/grpc/src/cpp/codegen/codegen_init.cc @@ -1,30 +1,30 @@ -/* - * +/* + * * Copyright 2016 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/impl/codegen/core_codegen_interface.h> #include <grpcpp/impl/codegen/grpc_library.h> - -/// Null-initializes the global gRPC variables for the codegen library. These + +/// Null-initializes the global gRPC variables for the codegen library. These /// stay null in the absence of grpc++ library. In this case, no gRPC -/// features such as the ability to perform calls will be available. Trying to -/// perform them would result in a segmentation fault when trying to deference -/// the following nulled globals. These should be associated with actual -/// as part of the instantiation of a \a grpc::GrpcLibraryInitializer variable. - -grpc::CoreCodegenInterface* grpc::g_core_codegen_interface; -grpc::GrpcLibraryInterface* grpc::g_glip; +/// features such as the ability to perform calls will be available. Trying to +/// perform them would result in a segmentation fault when trying to deference +/// the following nulled globals. These should be associated with actual +/// as part of the instantiation of a \a grpc::GrpcLibraryInitializer variable. + +grpc::CoreCodegenInterface* grpc::g_core_codegen_interface; +grpc::GrpcLibraryInterface* grpc::g_glip; diff --git a/contrib/libs/grpc/src/cpp/common/auth_property_iterator.cc b/contrib/libs/grpc/src/cpp/common/auth_property_iterator.cc index fbb18e9915..1184b500ea 100644 --- a/contrib/libs/grpc/src/cpp/common/auth_property_iterator.cc +++ b/contrib/libs/grpc/src/cpp/common/auth_property_iterator.cc @@ -1,70 +1,70 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/security/auth_context.h> - -#include <grpc/grpc_security.h> - -namespace grpc { - -AuthPropertyIterator::AuthPropertyIterator() - : property_(nullptr), ctx_(nullptr), index_(0), name_(nullptr) {} - -AuthPropertyIterator::AuthPropertyIterator( - const grpc_auth_property* property, const grpc_auth_property_iterator* iter) - : property_(property), - ctx_(iter->ctx), - index_(iter->index), - name_(iter->name) {} - -AuthPropertyIterator::~AuthPropertyIterator() {} - -AuthPropertyIterator& AuthPropertyIterator::operator++() { - grpc_auth_property_iterator iter = {ctx_, index_, name_}; - property_ = grpc_auth_property_iterator_next(&iter); - ctx_ = iter.ctx; - index_ = iter.index; - name_ = iter.name; - return *this; -} - -AuthPropertyIterator AuthPropertyIterator::operator++(int) { - AuthPropertyIterator tmp(*this); - operator++(); - return tmp; -} - -bool AuthPropertyIterator::operator==(const AuthPropertyIterator& rhs) const { - if (property_ == nullptr || rhs.property_ == nullptr) { - return property_ == rhs.property_; - } else { - return index_ == rhs.index_; - } -} - -bool AuthPropertyIterator::operator!=(const AuthPropertyIterator& rhs) const { - return !operator==(rhs); -} - -const AuthProperty AuthPropertyIterator::operator*() { - return std::pair<grpc::string_ref, grpc::string_ref>( - property_->name, - grpc::string_ref(property_->value, property_->value_length)); -} - -} // namespace grpc + +#include <grpc/grpc_security.h> + +namespace grpc { + +AuthPropertyIterator::AuthPropertyIterator() + : property_(nullptr), ctx_(nullptr), index_(0), name_(nullptr) {} + +AuthPropertyIterator::AuthPropertyIterator( + const grpc_auth_property* property, const grpc_auth_property_iterator* iter) + : property_(property), + ctx_(iter->ctx), + index_(iter->index), + name_(iter->name) {} + +AuthPropertyIterator::~AuthPropertyIterator() {} + +AuthPropertyIterator& AuthPropertyIterator::operator++() { + grpc_auth_property_iterator iter = {ctx_, index_, name_}; + property_ = grpc_auth_property_iterator_next(&iter); + ctx_ = iter.ctx; + index_ = iter.index; + name_ = iter.name; + return *this; +} + +AuthPropertyIterator AuthPropertyIterator::operator++(int) { + AuthPropertyIterator tmp(*this); + operator++(); + return tmp; +} + +bool AuthPropertyIterator::operator==(const AuthPropertyIterator& rhs) const { + if (property_ == nullptr || rhs.property_ == nullptr) { + return property_ == rhs.property_; + } else { + return index_ == rhs.index_; + } +} + +bool AuthPropertyIterator::operator!=(const AuthPropertyIterator& rhs) const { + return !operator==(rhs); +} + +const AuthProperty AuthPropertyIterator::operator*() { + return std::pair<grpc::string_ref, grpc::string_ref>( + property_->name, + grpc::string_ref(property_->value, property_->value_length)); +} + +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/common/channel_arguments.cc b/contrib/libs/grpc/src/cpp/common/channel_arguments.cc index 5a5dd91b5e..0a045b999d 100644 --- a/contrib/libs/grpc/src/cpp/common/channel_arguments.cc +++ b/contrib/libs/grpc/src/cpp/common/channel_arguments.cc @@ -1,70 +1,70 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ + * + */ #include <grpcpp/support/channel_arguments.h> - -#include <sstream> - -#include <grpc/impl/codegen/grpc_types.h> -#include <grpc/support/log.h> + +#include <sstream> + +#include <grpc/impl/codegen/grpc_types.h> +#include <grpc/support/log.h> #include <grpcpp/grpcpp.h> #include <grpcpp/resource_quota.h> -#include "src/core/lib/channel/channel_args.h" -#include "src/core/lib/iomgr/exec_ctx.h" -#include "src/core/lib/iomgr/socket_mutator.h" +#include "src/core/lib/channel/channel_args.h" +#include "src/core/lib/iomgr/exec_ctx.h" +#include "src/core/lib/iomgr/socket_mutator.h" namespace grpc { - -ChannelArguments::ChannelArguments() { - // This will be ignored if used on the server side. + +ChannelArguments::ChannelArguments() { + // This will be ignored if used on the server side. SetString(GRPC_ARG_PRIMARY_USER_AGENT_STRING, "grpc-c++/" + grpc::Version()); -} - -ChannelArguments::ChannelArguments(const ChannelArguments& other) - : strings_(other.strings_) { - args_.reserve(other.args_.size()); - auto list_it_dst = strings_.begin(); - auto list_it_src = other.strings_.begin(); +} + +ChannelArguments::ChannelArguments(const ChannelArguments& other) + : strings_(other.strings_) { + args_.reserve(other.args_.size()); + auto list_it_dst = strings_.begin(); + auto list_it_src = other.strings_.begin(); for (const auto& a : other.args_) { - grpc_arg ap; + grpc_arg ap; ap.type = a.type; GPR_ASSERT(list_it_src->c_str() == a.key); - ap.key = const_cast<char*>(list_it_dst->c_str()); - ++list_it_src; - ++list_it_dst; + ap.key = const_cast<char*>(list_it_dst->c_str()); + ++list_it_src; + ++list_it_dst; switch (a.type) { - case GRPC_ARG_INTEGER: + case GRPC_ARG_INTEGER: ap.value.integer = a.value.integer; - break; - case GRPC_ARG_STRING: + break; + case GRPC_ARG_STRING: GPR_ASSERT(list_it_src->c_str() == a.value.string); - ap.value.string = const_cast<char*>(list_it_dst->c_str()); - ++list_it_src; - ++list_it_dst; - break; - case GRPC_ARG_POINTER: + ap.value.string = const_cast<char*>(list_it_dst->c_str()); + ++list_it_src; + ++list_it_dst; + break; + case GRPC_ARG_POINTER: ap.value.pointer = a.value.pointer; ap.value.pointer.p = a.value.pointer.vtable->copy(ap.value.pointer.p); - break; - } - args_.push_back(ap); - } -} - + break; + } + args_.push_back(ap); + } +} + ChannelArguments::~ChannelArguments() { grpc_core::ExecCtx exec_ctx; for (auto& arg : args_) { @@ -74,26 +74,26 @@ ChannelArguments::~ChannelArguments() { } } -void ChannelArguments::Swap(ChannelArguments& other) { - args_.swap(other.args_); - strings_.swap(other.strings_); -} - -void ChannelArguments::SetCompressionAlgorithm( - grpc_compression_algorithm algorithm) { - SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM, algorithm); -} - +void ChannelArguments::Swap(ChannelArguments& other) { + args_.swap(other.args_); + strings_.swap(other.strings_); +} + +void ChannelArguments::SetCompressionAlgorithm( + grpc_compression_algorithm algorithm) { + SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM, algorithm); +} + void ChannelArguments::SetGrpclbFallbackTimeout(int fallback_timeout) { SetInt(GRPC_ARG_GRPCLB_FALLBACK_TIMEOUT_MS, fallback_timeout); } -void ChannelArguments::SetSocketMutator(grpc_socket_mutator* mutator) { - if (!mutator) { - return; - } - grpc_arg mutator_arg = grpc_socket_mutator_to_arg(mutator); - bool replaced = false; +void ChannelArguments::SetSocketMutator(grpc_socket_mutator* mutator) { + if (!mutator) { + return; + } + grpc_arg mutator_arg = grpc_socket_mutator_to_arg(mutator); + bool replaced = false; grpc_core::ExecCtx exec_ctx; for (auto& arg : args_) { if (arg.type == mutator_arg.type && @@ -102,26 +102,26 @@ void ChannelArguments::SetSocketMutator(grpc_socket_mutator* mutator) { arg.value.pointer.vtable->destroy(arg.value.pointer.p); arg.value.pointer = mutator_arg.value.pointer; replaced = true; - } - } + } + } - if (!replaced) { + if (!replaced) { strings_.push_back(TString(mutator_arg.key)); - args_.push_back(mutator_arg); + args_.push_back(mutator_arg); args_.back().key = const_cast<char*>(strings_.back().c_str()); - } -} - -// Note: a second call to this will add in front the result of the first call. -// An example is calling this on a copy of ChannelArguments which already has a -// prefix. The user can build up a prefix string by calling this multiple times, -// each with more significant identifier. -void ChannelArguments::SetUserAgentPrefix( + } +} + +// Note: a second call to this will add in front the result of the first call. +// An example is calling this on a copy of ChannelArguments which already has a +// prefix. The user can build up a prefix string by calling this multiple times, +// each with more significant identifier. +void ChannelArguments::SetUserAgentPrefix( const TString& user_agent_prefix) { - if (user_agent_prefix.empty()) { - return; - } - bool replaced = false; + if (user_agent_prefix.empty()) { + return; + } + bool replaced = false; auto strings_it = strings_.begin(); for (auto& arg : args_) { ++strings_it; @@ -134,84 +134,84 @@ void ChannelArguments::SetUserAgentPrefix( break; } ++strings_it; - } - } - if (!replaced) { - SetString(GRPC_ARG_PRIMARY_USER_AGENT_STRING, user_agent_prefix); - } -} - -void ChannelArguments::SetResourceQuota( + } + } + if (!replaced) { + SetString(GRPC_ARG_PRIMARY_USER_AGENT_STRING, user_agent_prefix); + } +} + +void ChannelArguments::SetResourceQuota( const grpc::ResourceQuota& resource_quota) { - SetPointerWithVtable(GRPC_ARG_RESOURCE_QUOTA, - resource_quota.c_resource_quota(), - grpc_resource_quota_arg_vtable()); -} - -void ChannelArguments::SetMaxReceiveMessageSize(int size) { - SetInt(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH, size); -} - -void ChannelArguments::SetMaxSendMessageSize(int size) { - SetInt(GRPC_ARG_MAX_SEND_MESSAGE_LENGTH, size); -} - -void ChannelArguments::SetLoadBalancingPolicyName( + SetPointerWithVtable(GRPC_ARG_RESOURCE_QUOTA, + resource_quota.c_resource_quota(), + grpc_resource_quota_arg_vtable()); +} + +void ChannelArguments::SetMaxReceiveMessageSize(int size) { + SetInt(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH, size); +} + +void ChannelArguments::SetMaxSendMessageSize(int size) { + SetInt(GRPC_ARG_MAX_SEND_MESSAGE_LENGTH, size); +} + +void ChannelArguments::SetLoadBalancingPolicyName( const TString& lb_policy_name) { - SetString(GRPC_ARG_LB_POLICY_NAME, lb_policy_name); -} - -void ChannelArguments::SetServiceConfigJSON( + SetString(GRPC_ARG_LB_POLICY_NAME, lb_policy_name); +} + +void ChannelArguments::SetServiceConfigJSON( const TString& service_config_json) { - SetString(GRPC_ARG_SERVICE_CONFIG, service_config_json); -} - + SetString(GRPC_ARG_SERVICE_CONFIG, service_config_json); +} + void ChannelArguments::SetInt(const TString& key, int value) { - grpc_arg arg; - arg.type = GRPC_ARG_INTEGER; - strings_.push_back(key); - arg.key = const_cast<char*>(strings_.back().c_str()); - arg.value.integer = value; - - args_.push_back(arg); -} - + grpc_arg arg; + arg.type = GRPC_ARG_INTEGER; + strings_.push_back(key); + arg.key = const_cast<char*>(strings_.back().c_str()); + arg.value.integer = value; + + args_.push_back(arg); +} + void ChannelArguments::SetPointer(const TString& key, void* value) { - static const grpc_arg_pointer_vtable vtable = { - &PointerVtableMembers::Copy, &PointerVtableMembers::Destroy, - &PointerVtableMembers::Compare}; - SetPointerWithVtable(key, value, &vtable); -} - -void ChannelArguments::SetPointerWithVtable( + static const grpc_arg_pointer_vtable vtable = { + &PointerVtableMembers::Copy, &PointerVtableMembers::Destroy, + &PointerVtableMembers::Compare}; + SetPointerWithVtable(key, value, &vtable); +} + +void ChannelArguments::SetPointerWithVtable( const TString& key, void* value, - const grpc_arg_pointer_vtable* vtable) { - grpc_arg arg; - arg.type = GRPC_ARG_POINTER; - strings_.push_back(key); - arg.key = const_cast<char*>(strings_.back().c_str()); + const grpc_arg_pointer_vtable* vtable) { + grpc_arg arg; + arg.type = GRPC_ARG_POINTER; + strings_.push_back(key); + arg.key = const_cast<char*>(strings_.back().c_str()); arg.value.pointer.p = vtable->copy(value); - arg.value.pointer.vtable = vtable; - args_.push_back(arg); -} - + arg.value.pointer.vtable = vtable; + args_.push_back(arg); +} + void ChannelArguments::SetString(const TString& key, const TString& value) { - grpc_arg arg; - arg.type = GRPC_ARG_STRING; - strings_.push_back(key); - arg.key = const_cast<char*>(strings_.back().c_str()); - strings_.push_back(value); - arg.value.string = const_cast<char*>(strings_.back().c_str()); - - args_.push_back(arg); -} - -void ChannelArguments::SetChannelArgs(grpc_channel_args* channel_args) const { - channel_args->num_args = args_.size(); - if (channel_args->num_args > 0) { - channel_args->args = const_cast<grpc_arg*>(&args_[0]); - } -} - + grpc_arg arg; + arg.type = GRPC_ARG_STRING; + strings_.push_back(key); + arg.key = const_cast<char*>(strings_.back().c_str()); + strings_.push_back(value); + arg.value.string = const_cast<char*>(strings_.back().c_str()); + + args_.push_back(arg); +} + +void ChannelArguments::SetChannelArgs(grpc_channel_args* channel_args) const { + channel_args->num_args = args_.size(); + if (channel_args->num_args > 0) { + channel_args->args = const_cast<grpc_arg*>(&args_[0]); + } +} + } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/common/channel_filter.cc b/contrib/libs/grpc/src/cpp/common/channel_filter.cc index 8df6c7b98f..7b2a08cca0 100644 --- a/contrib/libs/grpc/src/cpp/common/channel_filter.cc +++ b/contrib/libs/grpc/src/cpp/common/channel_filter.cc @@ -1,32 +1,32 @@ -/* - * +/* + * * Copyright 2016 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#include <string.h> - -#include "src/core/lib/channel/channel_stack.h" -#include "src/cpp/common/channel_filter.h" - + * + */ + +#include <string.h> + +#include "src/core/lib/channel/channel_stack.h" +#include "src/cpp/common/channel_filter.h" + #include <grpcpp/impl/codegen/slice.h> -namespace grpc { - -// MetadataBatch - +namespace grpc { + +// MetadataBatch + grpc_linked_mdelem* MetadataBatch::AddMetadata(const string& key, const string& value) { grpc_linked_mdelem* storage = new grpc_linked_mdelem; @@ -34,65 +34,65 @@ grpc_linked_mdelem* MetadataBatch::AddMetadata(const string& key, SliceFromCopiedString(value)); GRPC_LOG_IF_ERROR("MetadataBatch::AddMetadata", grpc_metadata_batch_link_head(batch_, storage)); - return storage; -} - -// ChannelData - + return storage; +} + +// ChannelData + void ChannelData::StartTransportOp(grpc_channel_element* elem, TransportOp* op) { grpc_channel_next_op(elem, op->op()); -} - +} + void ChannelData::GetInfo(grpc_channel_element* elem, const grpc_channel_info* channel_info) { grpc_channel_next_get_info(elem, channel_info); -} - -// CallData - +} + +// CallData + void CallData::StartTransportStreamOpBatch(grpc_call_element* elem, TransportStreamOpBatch* op) { grpc_call_next_op(elem, op->op()); -} - +} + void CallData::SetPollsetOrPollsetSet(grpc_call_element* elem, grpc_polling_entity* pollent) { grpc_call_stack_ignore_set_pollset_or_pollset_set(elem, pollent); -} - -// internal code used by RegisterChannelFilter() - -namespace internal { - -// Note: Implicitly initialized to nullptr due to static lifetime. +} + +// internal code used by RegisterChannelFilter() + +namespace internal { + +// Note: Implicitly initialized to nullptr due to static lifetime. std::vector<FilterRecord>* channel_filters; - -namespace { - + +namespace { + bool MaybeAddFilter(grpc_channel_stack_builder* builder, void* arg) { const FilterRecord& filter = *static_cast<FilterRecord*>(arg); - if (filter.include_filter) { + if (filter.include_filter) { const grpc_channel_args* args = - grpc_channel_stack_builder_get_channel_arguments(builder); - if (!filter.include_filter(*args)) return true; - } - return grpc_channel_stack_builder_prepend_filter(builder, &filter.filter, - nullptr, nullptr); -} - -} // namespace - -void ChannelFilterPluginInit() { - for (size_t i = 0; i < channel_filters->size(); ++i) { + grpc_channel_stack_builder_get_channel_arguments(builder); + if (!filter.include_filter(*args)) return true; + } + return grpc_channel_stack_builder_prepend_filter(builder, &filter.filter, + nullptr, nullptr); +} + +} // namespace + +void ChannelFilterPluginInit() { + for (size_t i = 0; i < channel_filters->size(); ++i) { FilterRecord& filter = (*channel_filters)[i]; - grpc_channel_init_register_stage(filter.stack_type, filter.priority, + grpc_channel_init_register_stage(filter.stack_type, filter.priority, MaybeAddFilter, (void*)&filter); - } -} - -void ChannelFilterPluginShutdown() {} - -} // namespace internal - -} // namespace grpc + } +} + +void ChannelFilterPluginShutdown() {} + +} // namespace internal + +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/common/channel_filter.h b/contrib/libs/grpc/src/cpp/common/channel_filter.h index 5ce720b307..9bb3e5c7f7 100644 --- a/contrib/libs/grpc/src/cpp/common/channel_filter.h +++ b/contrib/libs/grpc/src/cpp/common/channel_filter.h @@ -1,137 +1,137 @@ -/* - * +/* + * * Copyright 2016 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#ifndef GRPCXX_CHANNEL_FILTER_H -#define GRPCXX_CHANNEL_FILTER_H - -#include <grpc/grpc.h> -#include <grpc/support/alloc.h> + * + */ + +#ifndef GRPCXX_CHANNEL_FILTER_H +#define GRPCXX_CHANNEL_FILTER_H + +#include <grpc/grpc.h> +#include <grpc/support/alloc.h> #include <grpcpp/impl/codegen/config.h> - -#include <functional> -#include <vector> - -#include "src/core/lib/channel/channel_stack.h" -#include "src/core/lib/surface/channel_init.h" -#include "src/core/lib/transport/metadata_batch.h" - -/// An interface to define filters. -/// -/// To define a filter, implement a subclass of each of \c CallData and -/// \c ChannelData. Then register the filter using something like this: -/// \code{.cpp} -/// RegisterChannelFilter<MyChannelDataSubclass, MyCallDataSubclass>( -/// "name-of-filter", GRPC_SERVER_CHANNEL, INT_MAX, nullptr); -/// \endcode - -namespace grpc { - -/// A C++ wrapper for the \c grpc_metadata_batch struct. -class MetadataBatch { - public: - /// Borrows a pointer to \a batch, but does NOT take ownership. - /// The caller must ensure that \a batch continues to exist for as - /// long as the MetadataBatch object does. + +#include <functional> +#include <vector> + +#include "src/core/lib/channel/channel_stack.h" +#include "src/core/lib/surface/channel_init.h" +#include "src/core/lib/transport/metadata_batch.h" + +/// An interface to define filters. +/// +/// To define a filter, implement a subclass of each of \c CallData and +/// \c ChannelData. Then register the filter using something like this: +/// \code{.cpp} +/// RegisterChannelFilter<MyChannelDataSubclass, MyCallDataSubclass>( +/// "name-of-filter", GRPC_SERVER_CHANNEL, INT_MAX, nullptr); +/// \endcode + +namespace grpc { + +/// A C++ wrapper for the \c grpc_metadata_batch struct. +class MetadataBatch { + public: + /// Borrows a pointer to \a batch, but does NOT take ownership. + /// The caller must ensure that \a batch continues to exist for as + /// long as the MetadataBatch object does. explicit MetadataBatch(grpc_metadata_batch* batch) : batch_(batch) {} - + grpc_metadata_batch* batch() const { return batch_; } - - /// Adds metadata and returns the newly allocated storage. - /// The caller takes ownership of the result, which must exist for the - /// lifetime of the gRPC call. + + /// Adds metadata and returns the newly allocated storage. + /// The caller takes ownership of the result, which must exist for the + /// lifetime of the gRPC call. grpc_linked_mdelem* AddMetadata(const string& key, const string& value); - - class const_iterator : public std::iterator<std::bidirectional_iterator_tag, - const grpc_mdelem> { - public: + + class const_iterator : public std::iterator<std::bidirectional_iterator_tag, + const grpc_mdelem> { + public: const grpc_mdelem& operator*() const { return elem_->md; } const grpc_mdelem operator->() const { return elem_->md; } - + const_iterator& operator++() { - elem_ = elem_->next; - return *this; - } - const_iterator operator++(int) { - const_iterator tmp(*this); - operator++(); - return tmp; - } + elem_ = elem_->next; + return *this; + } + const_iterator operator++(int) { + const_iterator tmp(*this); + operator++(); + return tmp; + } const_iterator& operator--() { - elem_ = elem_->prev; - return *this; - } - const_iterator operator--(int) { - const_iterator tmp(*this); - operator--(); - return tmp; - } - + elem_ = elem_->prev; + return *this; + } + const_iterator operator--(int) { + const_iterator tmp(*this); + operator--(); + return tmp; + } + bool operator==(const const_iterator& other) const { - return elem_ == other.elem_; - } + return elem_ == other.elem_; + } bool operator!=(const const_iterator& other) const { - return elem_ != other.elem_; - } - - private: - friend class MetadataBatch; + return elem_ != other.elem_; + } + + private: + friend class MetadataBatch; explicit const_iterator(grpc_linked_mdelem* elem) : elem_(elem) {} - + grpc_linked_mdelem* elem_; - }; - - const_iterator begin() const { return const_iterator(batch_->list.head); } - const_iterator end() const { return const_iterator(nullptr); } - - private: + }; + + const_iterator begin() const { return const_iterator(batch_->list.head); } + const_iterator end() const { return const_iterator(nullptr); } + + private: grpc_metadata_batch* batch_; // Not owned. -}; - -/// A C++ wrapper for the \c grpc_transport_op struct. -class TransportOp { - public: - /// Borrows a pointer to \a op, but does NOT take ownership. - /// The caller must ensure that \a op continues to exist for as - /// long as the TransportOp object does. +}; + +/// A C++ wrapper for the \c grpc_transport_op struct. +class TransportOp { + public: + /// Borrows a pointer to \a op, but does NOT take ownership. + /// The caller must ensure that \a op continues to exist for as + /// long as the TransportOp object does. explicit TransportOp(grpc_transport_op* op) : op_(op) {} - + grpc_transport_op* op() const { return op_; } - - // TODO(roth): Add a C++ wrapper for grpc_error? + + // TODO(roth): Add a C++ wrapper for grpc_error? grpc_error* disconnect_with_error() const { - return op_->disconnect_with_error; - } + return op_->disconnect_with_error; + } bool send_goaway() const { return op_->goaway_error != GRPC_ERROR_NONE; } - - // TODO(roth): Add methods for additional fields as needed. - - private: + + // TODO(roth): Add methods for additional fields as needed. + + private: grpc_transport_op* op_; // Not owned. -}; - +}; + /// A C++ wrapper for the \c grpc_transport_stream_op_batch struct. class TransportStreamOpBatch { - public: - /// Borrows a pointer to \a op, but does NOT take ownership. - /// The caller must ensure that \a op continues to exist for as + public: + /// Borrows a pointer to \a op, but does NOT take ownership. + /// The caller must ensure that \a op continues to exist for as /// long as the TransportStreamOpBatch object does. explicit TransportStreamOpBatch(grpc_transport_stream_op_batch* op) - : op_(op), + : op_(op), send_initial_metadata_( op->send_initial_metadata ? op->payload->send_initial_metadata.send_initial_metadata @@ -148,65 +148,65 @@ class TransportStreamOpBatch { op->recv_trailing_metadata ? op->payload->recv_trailing_metadata.recv_trailing_metadata : nullptr) {} - + grpc_transport_stream_op_batch* op() const { return op_; } - + grpc_closure* on_complete() const { return op_->on_complete; } void set_on_complete(grpc_closure* closure) { op_->on_complete = closure; } - + MetadataBatch* send_initial_metadata() { return op_->send_initial_metadata ? &send_initial_metadata_ : nullptr; - } + } MetadataBatch* send_trailing_metadata() { return op_->send_trailing_metadata ? &send_trailing_metadata_ : nullptr; - } + } MetadataBatch* recv_initial_metadata() { return op_->recv_initial_metadata ? &recv_initial_metadata_ : nullptr; - } + } MetadataBatch* recv_trailing_metadata() { return op_->recv_trailing_metadata ? &recv_trailing_metadata_ : nullptr; - } - + } + uint32_t* send_initial_metadata_flags() const { return op_->send_initial_metadata ? &op_->payload->send_initial_metadata .send_initial_metadata_flags : nullptr; - } - + } + grpc_closure* recv_initial_metadata_ready() const { return op_->recv_initial_metadata ? op_->payload->recv_initial_metadata.recv_initial_metadata_ready : nullptr; - } + } void set_recv_initial_metadata_ready(grpc_closure* closure) { op_->payload->recv_initial_metadata.recv_initial_metadata_ready = closure; - } - + } + grpc_core::OrphanablePtr<grpc_core::ByteStream>* send_message() const { return op_->send_message ? &op_->payload->send_message.send_message : nullptr; - } + } void set_send_message( grpc_core::OrphanablePtr<grpc_core::ByteStream> send_message) { op_->send_message = true; op_->payload->send_message.send_message = std::move(send_message); } - + grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message() const { return op_->recv_message ? op_->payload->recv_message.recv_message : nullptr; - } + } void set_recv_message( grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message) { op_->recv_message = true; op_->payload->recv_message.recv_message = recv_message; - } - + } + census_context* get_census_context() const { return static_cast<census_context*>( op_->payload->context[GRPC_CONTEXT_TRACING].value); - } - + } + const gpr_atm* get_peer_string() const { if (op_->send_initial_metadata && op_->payload->send_initial_metadata.peer_string != nullptr) { @@ -219,184 +219,184 @@ class TransportStreamOpBatch { } } - private: + private: grpc_transport_stream_op_batch* op_; // Not owned. - MetadataBatch send_initial_metadata_; - MetadataBatch send_trailing_metadata_; - MetadataBatch recv_initial_metadata_; - MetadataBatch recv_trailing_metadata_; -}; - -/// Represents channel data. -class ChannelData { - public: + MetadataBatch send_initial_metadata_; + MetadataBatch send_trailing_metadata_; + MetadataBatch recv_initial_metadata_; + MetadataBatch recv_trailing_metadata_; +}; + +/// Represents channel data. +class ChannelData { + public: ChannelData() {} - virtual ~ChannelData() {} - + virtual ~ChannelData() {} + // TODO(roth): Come up with a more C++-like API for the channel element. /// Initializes the channel data. virtual grpc_error* Init(grpc_channel_element* /*elem*/, grpc_channel_element_args* /*args*/) { - return GRPC_ERROR_NONE; - } - + return GRPC_ERROR_NONE; + } + // Called before destruction. virtual void Destroy(grpc_channel_element* /*elem*/) {} - + virtual void StartTransportOp(grpc_channel_element* elem, TransportOp* op); - + virtual void GetInfo(grpc_channel_element* elem, const grpc_channel_info* channel_info); -}; - -/// Represents call data. -class CallData { - public: +}; + +/// Represents call data. +class CallData { + public: CallData() {} - virtual ~CallData() {} - + virtual ~CallData() {} + // TODO(roth): Come up with a more C++-like API for the call element. - /// Initializes the call data. + /// Initializes the call data. virtual grpc_error* Init(grpc_call_element* /*elem*/, const grpc_call_element_args* /*args*/) { - return GRPC_ERROR_NONE; - } - + return GRPC_ERROR_NONE; + } + // Called before destruction. virtual void Destroy(grpc_call_element* /*elem*/, const grpc_call_final_info* /*final_info*/, grpc_closure* /*then_call_closure*/) {} - - /// Starts a new stream operation. + + /// Starts a new stream operation. virtual void StartTransportStreamOpBatch(grpc_call_element* elem, TransportStreamOpBatch* op); - - /// Sets a pollset or pollset set. + + /// Sets a pollset or pollset set. virtual void SetPollsetOrPollsetSet(grpc_call_element* elem, grpc_polling_entity* pollent); -}; - -namespace internal { - -// Defines static members for passing to C core. -// Members of this class correspond to the members of the C -// grpc_channel_filter struct. -template <typename ChannelDataType, typename CallDataType> -class ChannelFilter final { - public: - static const size_t channel_data_size = sizeof(ChannelDataType); - +}; + +namespace internal { + +// Defines static members for passing to C core. +// Members of this class correspond to the members of the C +// grpc_channel_filter struct. +template <typename ChannelDataType, typename CallDataType> +class ChannelFilter final { + public: + static const size_t channel_data_size = sizeof(ChannelDataType); + static grpc_error* InitChannelElement(grpc_channel_element* elem, grpc_channel_element_args* args) { // Construct the object in the already-allocated memory. ChannelDataType* channel_data = new (elem->channel_data) ChannelDataType(); return channel_data->Init(elem, args); - } - + } + static void DestroyChannelElement(grpc_channel_element* elem) { ChannelDataType* channel_data = static_cast<ChannelDataType*>(elem->channel_data); channel_data->Destroy(elem); channel_data->~ChannelDataType(); - } - + } + static void StartTransportOp(grpc_channel_element* elem, grpc_transport_op* op) { ChannelDataType* channel_data = static_cast<ChannelDataType*>(elem->channel_data); - TransportOp op_wrapper(op); + TransportOp op_wrapper(op); channel_data->StartTransportOp(elem, &op_wrapper); - } - + } + static void GetChannelInfo(grpc_channel_element* elem, const grpc_channel_info* channel_info) { ChannelDataType* channel_data = static_cast<ChannelDataType*>(elem->channel_data); channel_data->GetInfo(elem, channel_info); - } - - static const size_t call_data_size = sizeof(CallDataType); - + } + + static const size_t call_data_size = sizeof(CallDataType); + static grpc_error* InitCallElement(grpc_call_element* elem, const grpc_call_element_args* args) { - // Construct the object in the already-allocated memory. + // Construct the object in the already-allocated memory. CallDataType* call_data = new (elem->call_data) CallDataType(); return call_data->Init(elem, args); - } - + } + static void DestroyCallElement(grpc_call_element* elem, const grpc_call_final_info* final_info, grpc_closure* then_call_closure) { CallDataType* call_data = static_cast<CallDataType*>(elem->call_data); call_data->Destroy(elem, final_info, then_call_closure); call_data->~CallDataType(); - } - + } + static void StartTransportStreamOpBatch(grpc_call_element* elem, grpc_transport_stream_op_batch* op) { CallDataType* call_data = static_cast<CallDataType*>(elem->call_data); TransportStreamOpBatch op_wrapper(op); call_data->StartTransportStreamOpBatch(elem, &op_wrapper); - } - + } + static void SetPollsetOrPollsetSet(grpc_call_element* elem, grpc_polling_entity* pollent) { CallDataType* call_data = static_cast<CallDataType*>(elem->call_data); call_data->SetPollsetOrPollsetSet(elem, pollent); - } -}; - -struct FilterRecord { - grpc_channel_stack_type stack_type; - int priority; + } +}; + +struct FilterRecord { + grpc_channel_stack_type stack_type; + int priority; std::function<bool(const grpc_channel_args&)> include_filter; - grpc_channel_filter filter; -}; + grpc_channel_filter filter; +}; extern std::vector<FilterRecord>* channel_filters; - -void ChannelFilterPluginInit(); -void ChannelFilterPluginShutdown(); - -} // namespace internal - -/// Registers a new filter. -/// Must be called by only one thread at a time. -/// The \a include_filter argument specifies a function that will be called -/// to determine at run-time whether or not to add the filter. If the -/// value is nullptr, the filter will be added unconditionally. + +void ChannelFilterPluginInit(); +void ChannelFilterPluginShutdown(); + +} // namespace internal + +/// Registers a new filter. +/// Must be called by only one thread at a time. +/// The \a include_filter argument specifies a function that will be called +/// to determine at run-time whether or not to add the filter. If the +/// value is nullptr, the filter will be added unconditionally. /// If the channel stack type is GRPC_CLIENT_SUBCHANNEL, the caller should /// ensure that subchannels with different filter lists will always have /// different channel args. This requires setting a channel arg in case the /// registration function relies on some condition other than channel args to /// decide whether to add a filter or not. -template <typename ChannelDataType, typename CallDataType> -void RegisterChannelFilter( +template <typename ChannelDataType, typename CallDataType> +void RegisterChannelFilter( const char* name, grpc_channel_stack_type stack_type, int priority, std::function<bool(const grpc_channel_args&)> include_filter) { - // If we haven't been called before, initialize channel_filters and - // call grpc_register_plugin(). - if (internal::channel_filters == nullptr) { - grpc_register_plugin(internal::ChannelFilterPluginInit, - internal::ChannelFilterPluginShutdown); - internal::channel_filters = new std::vector<internal::FilterRecord>(); - } - // Add an entry to channel_filters. The filter will be added when the - // C-core initialization code calls ChannelFilterPluginInit(). - typedef internal::ChannelFilter<ChannelDataType, CallDataType> FilterType; - internal::FilterRecord filter_record = { - stack_type, - priority, - include_filter, + // If we haven't been called before, initialize channel_filters and + // call grpc_register_plugin(). + if (internal::channel_filters == nullptr) { + grpc_register_plugin(internal::ChannelFilterPluginInit, + internal::ChannelFilterPluginShutdown); + internal::channel_filters = new std::vector<internal::FilterRecord>(); + } + // Add an entry to channel_filters. The filter will be added when the + // C-core initialization code calls ChannelFilterPluginInit(). + typedef internal::ChannelFilter<ChannelDataType, CallDataType> FilterType; + internal::FilterRecord filter_record = { + stack_type, + priority, + include_filter, {FilterType::StartTransportStreamOpBatch, FilterType::StartTransportOp, - FilterType::call_data_size, FilterType::InitCallElement, - FilterType::SetPollsetOrPollsetSet, FilterType::DestroyCallElement, - FilterType::channel_data_size, FilterType::InitChannelElement, + FilterType::call_data_size, FilterType::InitCallElement, + FilterType::SetPollsetOrPollsetSet, FilterType::DestroyCallElement, + FilterType::channel_data_size, FilterType::InitChannelElement, FilterType::DestroyChannelElement, FilterType::GetChannelInfo, name}}; - internal::channel_filters->push_back(filter_record); -} - -} // namespace grpc - -#endif // GRPCXX_CHANNEL_FILTER_H + internal::channel_filters->push_back(filter_record); +} + +} // namespace grpc + +#endif // GRPCXX_CHANNEL_FILTER_H diff --git a/contrib/libs/grpc/src/cpp/common/completion_queue_cc.cc b/contrib/libs/grpc/src/cpp/common/completion_queue_cc.cc index 96a7105eaf..f0ad7dc8b1 100644 --- a/contrib/libs/grpc/src/cpp/common/completion_queue_cc.cc +++ b/contrib/libs/grpc/src/cpp/common/completion_queue_cc.cc @@ -1,75 +1,75 @@ -/* +/* * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/completion_queue.h> - -#include <memory> - -#include <grpc/grpc.h> -#include <grpc/support/log.h> + +#include <memory> + +#include <grpc/grpc.h> +#include <grpc/support/log.h> #include <grpcpp/impl/grpc_library.h> #include <grpcpp/support/time.h> - + namespace grpc { - + static internal::GrpcLibraryInitializer g_gli_initializer; - + // 'CompletionQueue' constructor can safely call GrpcLibraryCodegen(false) here // i.e not have GrpcLibraryCodegen call grpc_init(). This is because, to create // a 'grpc_completion_queue' instance (which is being passed as the input to // this constructor), one must have already called grpc_init(). CompletionQueue::CompletionQueue(grpc_completion_queue* take) : GrpcLibraryCodegen(false), cq_(take) { - InitialAvalanching(); -} - -void CompletionQueue::Shutdown() { - g_gli_initializer.summon(); + InitialAvalanching(); +} + +void CompletionQueue::Shutdown() { + g_gli_initializer.summon(); #ifndef NDEBUG if (!ServerListEmpty()) { gpr_log(GPR_ERROR, "CompletionQueue shutdown being shutdown before its server."); } #endif - CompleteAvalanching(); -} - -CompletionQueue::NextStatus CompletionQueue::AsyncNextInternal( - void** tag, bool* ok, gpr_timespec deadline) { - for (;;) { - auto ev = grpc_completion_queue_next(cq_, deadline, nullptr); - switch (ev.type) { - case GRPC_QUEUE_TIMEOUT: - return TIMEOUT; - case GRPC_QUEUE_SHUTDOWN: - return SHUTDOWN; - case GRPC_OP_COMPLETE: + CompleteAvalanching(); +} + +CompletionQueue::NextStatus CompletionQueue::AsyncNextInternal( + void** tag, bool* ok, gpr_timespec deadline) { + for (;;) { + auto ev = grpc_completion_queue_next(cq_, deadline, nullptr); + switch (ev.type) { + case GRPC_QUEUE_TIMEOUT: + return TIMEOUT; + case GRPC_QUEUE_SHUTDOWN: + return SHUTDOWN; + case GRPC_OP_COMPLETE: auto core_cq_tag = static_cast<::grpc::internal::CompletionQueueTag*>(ev.tag); - *ok = ev.success != 0; + *ok = ev.success != 0; *tag = core_cq_tag; if (core_cq_tag->FinalizeResult(tag, ok)) { - return GOT_EVENT; - } - break; - } - } -} - + return GOT_EVENT; + } + break; + } + } +} + CompletionQueue::CompletionQueueTLSCache::CompletionQueueTLSCache( CompletionQueue* cq) : cq_(cq), flushed_(false) { diff --git a/contrib/libs/grpc/src/cpp/common/core_codegen.cc b/contrib/libs/grpc/src/cpp/common/core_codegen.cc index 75383ed511..fdd353f9f2 100644 --- a/contrib/libs/grpc/src/cpp/common/core_codegen.cc +++ b/contrib/libs/grpc/src/cpp/common/core_codegen.cc @@ -1,59 +1,59 @@ -/* - * +/* + * * Copyright 2016 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/impl/codegen/core_codegen.h> - -#include <stdlib.h> - -#include <grpc/byte_buffer.h> -#include <grpc/byte_buffer_reader.h> -#include <grpc/grpc.h> -#include <grpc/slice.h> -#include <grpc/slice_buffer.h> -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/port_platform.h> -#include <grpc/support/sync.h> + +#include <stdlib.h> + +#include <grpc/byte_buffer.h> +#include <grpc/byte_buffer_reader.h> +#include <grpc/grpc.h> +#include <grpc/slice.h> +#include <grpc/slice_buffer.h> +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/port_platform.h> +#include <grpc/support/sync.h> #include <grpcpp/support/config.h> - -#include "src/core/lib/profiling/timers.h" - -struct grpc_byte_buffer; - -namespace grpc { - + +#include "src/core/lib/profiling/timers.h" + +struct grpc_byte_buffer; + +namespace grpc { + const grpc_completion_queue_factory* CoreCodegen::grpc_completion_queue_factory_lookup( const grpc_completion_queue_attributes* attributes) { return ::grpc_completion_queue_factory_lookup(attributes); } -grpc_completion_queue* CoreCodegen::grpc_completion_queue_create( +grpc_completion_queue* CoreCodegen::grpc_completion_queue_create( const grpc_completion_queue_factory* factory, const grpc_completion_queue_attributes* attributes, void* reserved) { return ::grpc_completion_queue_create(factory, attributes, reserved); } grpc_completion_queue* CoreCodegen::grpc_completion_queue_create_for_next( - void* reserved) { + void* reserved) { return ::grpc_completion_queue_create_for_next(reserved); -} - +} + grpc_completion_queue* CoreCodegen::grpc_completion_queue_create_for_pluck( void* reserved) { return ::grpc_completion_queue_create_for_pluck(reserved); @@ -63,45 +63,45 @@ void CoreCodegen::grpc_completion_queue_shutdown(grpc_completion_queue* cq) { ::grpc_completion_queue_shutdown(cq); } -void CoreCodegen::grpc_completion_queue_destroy(grpc_completion_queue* cq) { - ::grpc_completion_queue_destroy(cq); -} - -grpc_event CoreCodegen::grpc_completion_queue_pluck(grpc_completion_queue* cq, - void* tag, - gpr_timespec deadline, - void* reserved) { - return ::grpc_completion_queue_pluck(cq, tag, deadline, reserved); -} - -void* CoreCodegen::gpr_malloc(size_t size) { return ::gpr_malloc(size); } - -void CoreCodegen::gpr_free(void* p) { return ::gpr_free(p); } - +void CoreCodegen::grpc_completion_queue_destroy(grpc_completion_queue* cq) { + ::grpc_completion_queue_destroy(cq); +} + +grpc_event CoreCodegen::grpc_completion_queue_pluck(grpc_completion_queue* cq, + void* tag, + gpr_timespec deadline, + void* reserved) { + return ::grpc_completion_queue_pluck(cq, tag, deadline, reserved); +} + +void* CoreCodegen::gpr_malloc(size_t size) { return ::gpr_malloc(size); } + +void CoreCodegen::gpr_free(void* p) { return ::gpr_free(p); } + void CoreCodegen::grpc_init() { ::grpc_init(); } void CoreCodegen::grpc_shutdown() { ::grpc_shutdown(); } void CoreCodegen::gpr_mu_init(gpr_mu* mu) { ::gpr_mu_init(mu); } -void CoreCodegen::gpr_mu_destroy(gpr_mu* mu) { ::gpr_mu_destroy(mu); } -void CoreCodegen::gpr_mu_lock(gpr_mu* mu) { ::gpr_mu_lock(mu); } -void CoreCodegen::gpr_mu_unlock(gpr_mu* mu) { ::gpr_mu_unlock(mu); } -void CoreCodegen::gpr_cv_init(gpr_cv* cv) { ::gpr_cv_init(cv); } -void CoreCodegen::gpr_cv_destroy(gpr_cv* cv) { ::gpr_cv_destroy(cv); } -int CoreCodegen::gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, - gpr_timespec abs_deadline) { - return ::gpr_cv_wait(cv, mu, abs_deadline); -} -void CoreCodegen::gpr_cv_signal(gpr_cv* cv) { ::gpr_cv_signal(cv); } -void CoreCodegen::gpr_cv_broadcast(gpr_cv* cv) { ::gpr_cv_broadcast(cv); } - +void CoreCodegen::gpr_mu_destroy(gpr_mu* mu) { ::gpr_mu_destroy(mu); } +void CoreCodegen::gpr_mu_lock(gpr_mu* mu) { ::gpr_mu_lock(mu); } +void CoreCodegen::gpr_mu_unlock(gpr_mu* mu) { ::gpr_mu_unlock(mu); } +void CoreCodegen::gpr_cv_init(gpr_cv* cv) { ::gpr_cv_init(cv); } +void CoreCodegen::gpr_cv_destroy(gpr_cv* cv) { ::gpr_cv_destroy(cv); } +int CoreCodegen::gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, + gpr_timespec abs_deadline) { + return ::gpr_cv_wait(cv, mu, abs_deadline); +} +void CoreCodegen::gpr_cv_signal(gpr_cv* cv) { ::gpr_cv_signal(cv); } +void CoreCodegen::gpr_cv_broadcast(gpr_cv* cv) { ::gpr_cv_broadcast(cv); } + grpc_byte_buffer* CoreCodegen::grpc_byte_buffer_copy(grpc_byte_buffer* bb) { return ::grpc_byte_buffer_copy(bb); } -void CoreCodegen::grpc_byte_buffer_destroy(grpc_byte_buffer* bb) { - ::grpc_byte_buffer_destroy(bb); -} - +void CoreCodegen::grpc_byte_buffer_destroy(grpc_byte_buffer* bb) { + ::grpc_byte_buffer_destroy(bb); +} + size_t CoreCodegen::grpc_byte_buffer_length(grpc_byte_buffer* bb) { return ::grpc_byte_buffer_length(bb); } @@ -127,31 +127,31 @@ const char* CoreCodegen::grpc_call_error_to_string(grpc_call_error error) { return ::grpc_call_error_to_string(error); } -int CoreCodegen::grpc_byte_buffer_reader_init(grpc_byte_buffer_reader* reader, - grpc_byte_buffer* buffer) { - return ::grpc_byte_buffer_reader_init(reader, buffer); -} - -void CoreCodegen::grpc_byte_buffer_reader_destroy( - grpc_byte_buffer_reader* reader) { - ::grpc_byte_buffer_reader_destroy(reader); -} - -int CoreCodegen::grpc_byte_buffer_reader_next(grpc_byte_buffer_reader* reader, - grpc_slice* slice) { - return ::grpc_byte_buffer_reader_next(reader, slice); -} - +int CoreCodegen::grpc_byte_buffer_reader_init(grpc_byte_buffer_reader* reader, + grpc_byte_buffer* buffer) { + return ::grpc_byte_buffer_reader_init(reader, buffer); +} + +void CoreCodegen::grpc_byte_buffer_reader_destroy( + grpc_byte_buffer_reader* reader) { + ::grpc_byte_buffer_reader_destroy(reader); +} + +int CoreCodegen::grpc_byte_buffer_reader_next(grpc_byte_buffer_reader* reader, + grpc_slice* slice) { + return ::grpc_byte_buffer_reader_next(reader, slice); +} + int CoreCodegen::grpc_byte_buffer_reader_peek(grpc_byte_buffer_reader* reader, grpc_slice** slice) { return ::grpc_byte_buffer_reader_peek(reader, slice); } -grpc_byte_buffer* CoreCodegen::grpc_raw_byte_buffer_create(grpc_slice* slice, - size_t nslices) { - return ::grpc_raw_byte_buffer_create(slice, nslices); -} - +grpc_byte_buffer* CoreCodegen::grpc_raw_byte_buffer_create(grpc_slice* slice, + size_t nslices) { + return ::grpc_raw_byte_buffer_create(slice, nslices); +} + grpc_slice CoreCodegen::grpc_slice_new_with_user_data(void* p, size_t len, void (*destroy)(void*), void* user_data) { @@ -166,22 +166,22 @@ grpc_slice CoreCodegen::grpc_slice_new_with_len(void* p, size_t len, grpc_slice CoreCodegen::grpc_empty_slice() { return ::grpc_empty_slice(); } -grpc_slice CoreCodegen::grpc_slice_malloc(size_t length) { - return ::grpc_slice_malloc(length); -} - -void CoreCodegen::grpc_slice_unref(grpc_slice slice) { - ::grpc_slice_unref(slice); -} - +grpc_slice CoreCodegen::grpc_slice_malloc(size_t length) { + return ::grpc_slice_malloc(length); +} + +void CoreCodegen::grpc_slice_unref(grpc_slice slice) { + ::grpc_slice_unref(slice); +} + grpc_slice CoreCodegen::grpc_slice_ref(grpc_slice slice) { return ::grpc_slice_ref(slice); } -grpc_slice CoreCodegen::grpc_slice_split_tail(grpc_slice* s, size_t split) { - return ::grpc_slice_split_tail(s, split); -} - +grpc_slice CoreCodegen::grpc_slice_split_tail(grpc_slice* s, size_t split) { + return ::grpc_slice_split_tail(s, split); +} + grpc_slice CoreCodegen::grpc_slice_split_head(grpc_slice* s, size_t split) { return ::grpc_slice_split_head(s, split); } @@ -201,40 +201,40 @@ grpc_slice CoreCodegen::grpc_slice_from_copied_buffer(const void* buffer, length); } -void CoreCodegen::grpc_slice_buffer_add(grpc_slice_buffer* sb, - grpc_slice slice) { - ::grpc_slice_buffer_add(sb, slice); -} - -void CoreCodegen::grpc_slice_buffer_pop(grpc_slice_buffer* sb) { - ::grpc_slice_buffer_pop(sb); -} - -void CoreCodegen::grpc_metadata_array_init(grpc_metadata_array* array) { - ::grpc_metadata_array_init(array); -} - -void CoreCodegen::grpc_metadata_array_destroy(grpc_metadata_array* array) { - ::grpc_metadata_array_destroy(array); -} - -const Status& CoreCodegen::ok() { return grpc::Status::OK; } - -const Status& CoreCodegen::cancelled() { return grpc::Status::CANCELLED; } - -gpr_timespec CoreCodegen::gpr_inf_future(gpr_clock_type type) { - return ::gpr_inf_future(type); -} - -gpr_timespec CoreCodegen::gpr_time_0(gpr_clock_type type) { - return ::gpr_time_0(type); -} - +void CoreCodegen::grpc_slice_buffer_add(grpc_slice_buffer* sb, + grpc_slice slice) { + ::grpc_slice_buffer_add(sb, slice); +} + +void CoreCodegen::grpc_slice_buffer_pop(grpc_slice_buffer* sb) { + ::grpc_slice_buffer_pop(sb); +} + +void CoreCodegen::grpc_metadata_array_init(grpc_metadata_array* array) { + ::grpc_metadata_array_init(array); +} + +void CoreCodegen::grpc_metadata_array_destroy(grpc_metadata_array* array) { + ::grpc_metadata_array_destroy(array); +} + +const Status& CoreCodegen::ok() { return grpc::Status::OK; } + +const Status& CoreCodegen::cancelled() { return grpc::Status::CANCELLED; } + +gpr_timespec CoreCodegen::gpr_inf_future(gpr_clock_type type) { + return ::gpr_inf_future(type); +} + +gpr_timespec CoreCodegen::gpr_time_0(gpr_clock_type type) { + return ::gpr_time_0(type); +} + void CoreCodegen::assert_fail(const char* failed_assertion, const char* file, int line) { gpr_log(file, line, GPR_LOG_SEVERITY_ERROR, "assertion failed: %s", failed_assertion); - abort(); -} - -} // namespace grpc + abort(); +} + +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/common/insecure_create_auth_context.cc b/contrib/libs/grpc/src/cpp/common/insecure_create_auth_context.cc index 4e5cbd0372..9610078682 100644 --- a/contrib/libs/grpc/src/cpp/common/insecure_create_auth_context.cc +++ b/contrib/libs/grpc/src/cpp/common/insecure_create_auth_context.cc @@ -1,30 +1,30 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ -#include <memory> - -#include <grpc/grpc.h> + * + */ +#include <memory> + +#include <grpc/grpc.h> #include <grpcpp/security/auth_context.h> - -namespace grpc { - -std::shared_ptr<const AuthContext> CreateAuthContext(grpc_call* call) { - (void)call; - return std::shared_ptr<const AuthContext>(); -} - -} // namespace grpc + +namespace grpc { + +std::shared_ptr<const AuthContext> CreateAuthContext(grpc_call* call) { + (void)call; + return std::shared_ptr<const AuthContext>(); +} + +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/common/resource_quota_cc.cc b/contrib/libs/grpc/src/cpp/common/resource_quota_cc.cc index 64abff9633..adc70dda33 100644 --- a/contrib/libs/grpc/src/cpp/common/resource_quota_cc.cc +++ b/contrib/libs/grpc/src/cpp/common/resource_quota_cc.cc @@ -1,38 +1,38 @@ -/* - * +/* + * * Copyright 2016 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#include <grpc/grpc.h> + * + */ + +#include <grpc/grpc.h> #include <grpcpp/resource_quota.h> - + namespace grpc { - -ResourceQuota::ResourceQuota() : impl_(grpc_resource_quota_create(nullptr)) {} - + +ResourceQuota::ResourceQuota() : impl_(grpc_resource_quota_create(nullptr)) {} + ResourceQuota::ResourceQuota(const TString& name) - : impl_(grpc_resource_quota_create(name.c_str())) {} - -ResourceQuota::~ResourceQuota() { grpc_resource_quota_unref(impl_); } - -ResourceQuota& ResourceQuota::Resize(size_t new_size) { - grpc_resource_quota_resize(impl_, new_size); - return *this; -} - + : impl_(grpc_resource_quota_create(name.c_str())) {} + +ResourceQuota::~ResourceQuota() { grpc_resource_quota_unref(impl_); } + +ResourceQuota& ResourceQuota::Resize(size_t new_size) { + grpc_resource_quota_resize(impl_, new_size); + return *this; +} + ResourceQuota& ResourceQuota::SetMaxThreads(int new_max_threads) { grpc_resource_quota_set_max_threads(impl_, new_max_threads); return *this; diff --git a/contrib/libs/grpc/src/cpp/common/rpc_method.cc b/contrib/libs/grpc/src/cpp/common/rpc_method.cc index a47dd3e444..1f70617fe0 100644 --- a/contrib/libs/grpc/src/cpp/common/rpc_method.cc +++ b/contrib/libs/grpc/src/cpp/common/rpc_method.cc @@ -1,21 +1,21 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/impl/rpc_method.h> - -namespace grpc {} // namespace grpc + +namespace grpc {} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/common/secure_auth_context.cc b/contrib/libs/grpc/src/cpp/common/secure_auth_context.cc index e1f97889c8..65254c11df 100644 --- a/contrib/libs/grpc/src/cpp/common/secure_auth_context.cc +++ b/contrib/libs/grpc/src/cpp/common/secure_auth_context.cc @@ -1,97 +1,97 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#include "src/cpp/common/secure_auth_context.h" - -#include <grpc/grpc_security.h> - -namespace grpc { - -std::vector<grpc::string_ref> SecureAuthContext::GetPeerIdentity() const { + * + */ + +#include "src/cpp/common/secure_auth_context.h" + +#include <grpc/grpc_security.h> + +namespace grpc { + +std::vector<grpc::string_ref> SecureAuthContext::GetPeerIdentity() const { if (ctx_ == nullptr) { - return std::vector<grpc::string_ref>(); - } + return std::vector<grpc::string_ref>(); + } grpc_auth_property_iterator iter = grpc_auth_context_peer_identity(ctx_.get()); - std::vector<grpc::string_ref> identity; - const grpc_auth_property* property = nullptr; - while ((property = grpc_auth_property_iterator_next(&iter))) { - identity.push_back( - grpc::string_ref(property->value, property->value_length)); - } - return identity; -} - + std::vector<grpc::string_ref> identity; + const grpc_auth_property* property = nullptr; + while ((property = grpc_auth_property_iterator_next(&iter))) { + identity.push_back( + grpc::string_ref(property->value, property->value_length)); + } + return identity; +} + TString SecureAuthContext::GetPeerIdentityPropertyName() const { if (ctx_ == nullptr) { - return ""; - } + return ""; + } const char* name = grpc_auth_context_peer_identity_property_name(ctx_.get()); - return name == nullptr ? "" : name; -} - -std::vector<grpc::string_ref> SecureAuthContext::FindPropertyValues( + return name == nullptr ? "" : name; +} + +std::vector<grpc::string_ref> SecureAuthContext::FindPropertyValues( const TString& name) const { if (ctx_ == nullptr) { - return std::vector<grpc::string_ref>(); - } - grpc_auth_property_iterator iter = + return std::vector<grpc::string_ref>(); + } + grpc_auth_property_iterator iter = grpc_auth_context_find_properties_by_name(ctx_.get(), name.c_str()); - const grpc_auth_property* property = nullptr; - std::vector<grpc::string_ref> values; - while ((property = grpc_auth_property_iterator_next(&iter))) { - values.push_back(grpc::string_ref(property->value, property->value_length)); - } - return values; -} - -AuthPropertyIterator SecureAuthContext::begin() const { + const grpc_auth_property* property = nullptr; + std::vector<grpc::string_ref> values; + while ((property = grpc_auth_property_iterator_next(&iter))) { + values.push_back(grpc::string_ref(property->value, property->value_length)); + } + return values; +} + +AuthPropertyIterator SecureAuthContext::begin() const { if (ctx_ != nullptr) { - grpc_auth_property_iterator iter = + grpc_auth_property_iterator iter = grpc_auth_context_property_iterator(ctx_.get()); - const grpc_auth_property* property = - grpc_auth_property_iterator_next(&iter); - return AuthPropertyIterator(property, &iter); - } else { - return end(); - } -} - -AuthPropertyIterator SecureAuthContext::end() const { - return AuthPropertyIterator(); -} - + const grpc_auth_property* property = + grpc_auth_property_iterator_next(&iter); + return AuthPropertyIterator(property, &iter); + } else { + return end(); + } +} + +AuthPropertyIterator SecureAuthContext::end() const { + return AuthPropertyIterator(); +} + void SecureAuthContext::AddProperty(const TString& key, - const grpc::string_ref& value) { + const grpc::string_ref& value) { if (ctx_ == nullptr) return; grpc_auth_context_add_property(ctx_.get(), key.c_str(), value.data(), value.size()); -} - +} + bool SecureAuthContext::SetPeerIdentityPropertyName(const TString& name) { if (ctx_ == nullptr) return false; return grpc_auth_context_set_peer_identity_property_name(ctx_.get(), - name.c_str()) != 0; -} - -bool SecureAuthContext::IsPeerAuthenticated() const { + name.c_str()) != 0; +} + +bool SecureAuthContext::IsPeerAuthenticated() const { if (ctx_ == nullptr) return false; return grpc_auth_context_peer_is_authenticated(ctx_.get()) != 0; -} - -} // namespace grpc +} + +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/common/secure_auth_context.h b/contrib/libs/grpc/src/cpp/common/secure_auth_context.h index 51013efac7..8e1d0ee7b1 100644 --- a/contrib/libs/grpc/src/cpp/common/secure_auth_context.h +++ b/contrib/libs/grpc/src/cpp/common/secure_auth_context.h @@ -1,60 +1,60 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#ifndef GRPC_INTERNAL_CPP_COMMON_SECURE_AUTH_CONTEXT_H -#define GRPC_INTERNAL_CPP_COMMON_SECURE_AUTH_CONTEXT_H - + * + */ + +#ifndef GRPC_INTERNAL_CPP_COMMON_SECURE_AUTH_CONTEXT_H +#define GRPC_INTERNAL_CPP_COMMON_SECURE_AUTH_CONTEXT_H + #include <grpcpp/security/auth_context.h> - + #include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/security/context/security_context.h" - -namespace grpc { - -class SecureAuthContext final : public AuthContext { - public: + +namespace grpc { + +class SecureAuthContext final : public AuthContext { + public: explicit SecureAuthContext(grpc_auth_context* ctx) : ctx_(ctx != nullptr ? ctx->Ref() : nullptr) {} - + ~SecureAuthContext() override = default; - - bool IsPeerAuthenticated() const override; - - std::vector<grpc::string_ref> GetPeerIdentity() const override; - + + bool IsPeerAuthenticated() const override; + + std::vector<grpc::string_ref> GetPeerIdentity() const override; + TString GetPeerIdentityPropertyName() const override; - - std::vector<grpc::string_ref> FindPropertyValues( + + std::vector<grpc::string_ref> FindPropertyValues( const TString& name) const override; - - AuthPropertyIterator begin() const override; - - AuthPropertyIterator end() const override; - + + AuthPropertyIterator begin() const override; + + AuthPropertyIterator end() const override; + void AddProperty(const TString& key, - const grpc::string_ref& value) override; - + const grpc::string_ref& value) override; + virtual bool SetPeerIdentityPropertyName(const TString& name) override; - - private: + + private: grpc_core::RefCountedPtr<grpc_auth_context> ctx_; -}; - -} // namespace grpc - -#endif // GRPC_INTERNAL_CPP_COMMON_SECURE_AUTH_CONTEXT_H +}; + +} // namespace grpc + +#endif // GRPC_INTERNAL_CPP_COMMON_SECURE_AUTH_CONTEXT_H diff --git a/contrib/libs/grpc/src/cpp/common/secure_channel_arguments.cc b/contrib/libs/grpc/src/cpp/common/secure_channel_arguments.cc index 844bc627ab..9504bfa8df 100644 --- a/contrib/libs/grpc/src/cpp/common/secure_channel_arguments.cc +++ b/contrib/libs/grpc/src/cpp/common/secure_channel_arguments.cc @@ -1,39 +1,39 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/support/channel_arguments.h> - -#include <grpc/grpc_security.h> -#include "src/core/lib/channel/channel_args.h" - + +#include <grpc/grpc_security.h> +#include "src/core/lib/channel/channel_args.h" + namespace grpc { - + void ChannelArguments::SetSslTargetNameOverride(const TString& name) { - SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG, name); -} - + SetString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG, name); +} + TString ChannelArguments::GetSslTargetNameOverride() const { - for (unsigned int i = 0; i < args_.size(); i++) { + for (unsigned int i = 0; i < args_.size(); i++) { if (TString(GRPC_SSL_TARGET_NAME_OVERRIDE_ARG) == args_[i].key) { - return args_[i].value.string; - } - } - return ""; -} - + return args_[i].value.string; + } + } + return ""; +} + } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/common/secure_create_auth_context.cc b/contrib/libs/grpc/src/cpp/common/secure_create_auth_context.cc index 908c46629e..33d6f14cbe 100644 --- a/contrib/libs/grpc/src/cpp/common/secure_create_auth_context.cc +++ b/contrib/libs/grpc/src/cpp/common/secure_create_auth_context.cc @@ -1,36 +1,36 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ -#include <memory> - -#include <grpc/grpc.h> -#include <grpc/grpc_security.h> + * + */ +#include <memory> + +#include <grpc/grpc.h> +#include <grpc/grpc_security.h> #include <grpcpp/security/auth_context.h> #include "src/core/lib/gprpp/ref_counted_ptr.h" -#include "src/cpp/common/secure_auth_context.h" - -namespace grpc { - -std::shared_ptr<const AuthContext> CreateAuthContext(grpc_call* call) { - if (call == nullptr) { - return std::shared_ptr<const AuthContext>(); - } +#include "src/cpp/common/secure_auth_context.h" + +namespace grpc { + +std::shared_ptr<const AuthContext> CreateAuthContext(grpc_call* call) { + if (call == nullptr) { + return std::shared_ptr<const AuthContext>(); + } grpc_core::RefCountedPtr<grpc_auth_context> ctx(grpc_call_auth_context(call)); return std::make_shared<SecureAuthContext>(ctx.get()); -} - -} // namespace grpc +} + +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/common/version_cc.cc b/contrib/libs/grpc/src/cpp/common/version_cc.cc index 7f4228346a..0e58eb6c0b 100644 --- a/contrib/libs/grpc/src/cpp/common/version_cc.cc +++ b/contrib/libs/grpc/src/cpp/common/version_cc.cc @@ -1,26 +1,26 @@ -/* - * +/* + * * Copyright 2016 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -/* This file is autogenerated from: - templates/src/core/surface/version.c.template */ - + * + */ + +/* This file is autogenerated from: + templates/src/core/surface/version.c.template */ + #include <grpcpp/grpcpp.h> - -namespace grpc { + +namespace grpc { TString Version() { return "1.33.2"; } } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.cc b/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.cc index 1b388210c0..2daec87a4c 100644 --- a/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.cc +++ b/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.cc @@ -1,212 +1,212 @@ -/* - * +/* + * * Copyright 2016 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#include <unordered_set> -#include <vector> - + * + */ + +#include <unordered_set> +#include <vector> + #include <grpcpp/grpcpp.h> - -#include "src/cpp/ext/proto_server_reflection.h" - -using grpc::Status; -using grpc::StatusCode; + +#include "src/cpp/ext/proto_server_reflection.h" + +using grpc::Status; +using grpc::StatusCode; using grpc::reflection::v1alpha::ErrorResponse; using grpc::reflection::v1alpha::ExtensionNumberResponse; using grpc::reflection::v1alpha::ExtensionRequest; using grpc::reflection::v1alpha::FileDescriptorResponse; using grpc::reflection::v1alpha::ListServiceResponse; -using grpc::reflection::v1alpha::ServerReflectionRequest; -using grpc::reflection::v1alpha::ServerReflectionResponse; -using grpc::reflection::v1alpha::ServiceResponse; - -namespace grpc { - -ProtoServerReflection::ProtoServerReflection() - : descriptor_pool_(protobuf::DescriptorPool::generated_pool()) {} - -void ProtoServerReflection::SetServiceList( +using grpc::reflection::v1alpha::ServerReflectionRequest; +using grpc::reflection::v1alpha::ServerReflectionResponse; +using grpc::reflection::v1alpha::ServiceResponse; + +namespace grpc { + +ProtoServerReflection::ProtoServerReflection() + : descriptor_pool_(protobuf::DescriptorPool::generated_pool()) {} + +void ProtoServerReflection::SetServiceList( const std::vector<TString>* services) { - services_ = services; -} - -Status ProtoServerReflection::ServerReflectionInfo( - ServerContext* context, - ServerReaderWriter<ServerReflectionResponse, ServerReflectionRequest>* - stream) { - ServerReflectionRequest request; - ServerReflectionResponse response; - Status status; - while (stream->Read(&request)) { - switch (request.message_request_case()) { - case ServerReflectionRequest::MessageRequestCase::kFileByFilename: - status = GetFileByName(context, request.file_by_filename(), &response); - break; - case ServerReflectionRequest::MessageRequestCase::kFileContainingSymbol: - status = GetFileContainingSymbol( - context, request.file_containing_symbol(), &response); - break; - case ServerReflectionRequest::MessageRequestCase:: - kFileContainingExtension: - status = GetFileContainingExtension( - context, &request.file_containing_extension(), &response); - break; - case ServerReflectionRequest::MessageRequestCase:: - kAllExtensionNumbersOfType: - status = GetAllExtensionNumbers( - context, request.all_extension_numbers_of_type(), - response.mutable_all_extension_numbers_response()); - break; - case ServerReflectionRequest::MessageRequestCase::kListServices: - status = - ListService(context, response.mutable_list_services_response()); - break; - default: - status = Status(StatusCode::UNIMPLEMENTED, ""); - } - - if (!status.ok()) { - FillErrorResponse(status, response.mutable_error_response()); - } - response.set_valid_host(request.host()); - response.set_allocated_original_request( - new ServerReflectionRequest(request)); - stream->Write(response); - } - - return Status::OK; -} - -void ProtoServerReflection::FillErrorResponse(const Status& status, - ErrorResponse* error_response) { - error_response->set_error_code(status.error_code()); + services_ = services; +} + +Status ProtoServerReflection::ServerReflectionInfo( + ServerContext* context, + ServerReaderWriter<ServerReflectionResponse, ServerReflectionRequest>* + stream) { + ServerReflectionRequest request; + ServerReflectionResponse response; + Status status; + while (stream->Read(&request)) { + switch (request.message_request_case()) { + case ServerReflectionRequest::MessageRequestCase::kFileByFilename: + status = GetFileByName(context, request.file_by_filename(), &response); + break; + case ServerReflectionRequest::MessageRequestCase::kFileContainingSymbol: + status = GetFileContainingSymbol( + context, request.file_containing_symbol(), &response); + break; + case ServerReflectionRequest::MessageRequestCase:: + kFileContainingExtension: + status = GetFileContainingExtension( + context, &request.file_containing_extension(), &response); + break; + case ServerReflectionRequest::MessageRequestCase:: + kAllExtensionNumbersOfType: + status = GetAllExtensionNumbers( + context, request.all_extension_numbers_of_type(), + response.mutable_all_extension_numbers_response()); + break; + case ServerReflectionRequest::MessageRequestCase::kListServices: + status = + ListService(context, response.mutable_list_services_response()); + break; + default: + status = Status(StatusCode::UNIMPLEMENTED, ""); + } + + if (!status.ok()) { + FillErrorResponse(status, response.mutable_error_response()); + } + response.set_valid_host(request.host()); + response.set_allocated_original_request( + new ServerReflectionRequest(request)); + stream->Write(response); + } + + return Status::OK; +} + +void ProtoServerReflection::FillErrorResponse(const Status& status, + ErrorResponse* error_response) { + error_response->set_error_code(status.error_code()); error_response->set_error_message(TProtoStringType(status.error_message())); -} - +} + Status ProtoServerReflection::ListService(ServerContext* /*context*/, - ListServiceResponse* response) { - if (services_ == nullptr) { - return Status(StatusCode::NOT_FOUND, "Services not found."); - } + ListServiceResponse* response) { + if (services_ == nullptr) { + return Status(StatusCode::NOT_FOUND, "Services not found."); + } for (const auto& value : *services_) { - ServiceResponse* service_response = response->add_service(); + ServiceResponse* service_response = response->add_service(); service_response->set_name(TProtoStringType(value)); - } - return Status::OK; -} - -Status ProtoServerReflection::GetFileByName( + } + return Status::OK; +} + +Status ProtoServerReflection::GetFileByName( ServerContext* /*context*/, const TString& filename, - ServerReflectionResponse* response) { - if (descriptor_pool_ == nullptr) { - return Status::CANCELLED; - } - - const protobuf::FileDescriptor* file_desc = + ServerReflectionResponse* response) { + if (descriptor_pool_ == nullptr) { + return Status::CANCELLED; + } + + const protobuf::FileDescriptor* file_desc = descriptor_pool_->FindFileByName(TProtoStringType(filename)); - if (file_desc == nullptr) { - return Status(StatusCode::NOT_FOUND, "File not found."); - } + if (file_desc == nullptr) { + return Status(StatusCode::NOT_FOUND, "File not found."); + } std::unordered_set<TString> seen_files; - FillFileDescriptorResponse(file_desc, response, &seen_files); - return Status::OK; -} - -Status ProtoServerReflection::GetFileContainingSymbol( + FillFileDescriptorResponse(file_desc, response, &seen_files); + return Status::OK; +} + +Status ProtoServerReflection::GetFileContainingSymbol( ServerContext* /*context*/, const TString& symbol, - ServerReflectionResponse* response) { - if (descriptor_pool_ == nullptr) { - return Status::CANCELLED; - } - - const protobuf::FileDescriptor* file_desc = + ServerReflectionResponse* response) { + if (descriptor_pool_ == nullptr) { + return Status::CANCELLED; + } + + const protobuf::FileDescriptor* file_desc = descriptor_pool_->FindFileContainingSymbol(TProtoStringType(symbol)); - if (file_desc == nullptr) { - return Status(StatusCode::NOT_FOUND, "Symbol not found."); - } + if (file_desc == nullptr) { + return Status(StatusCode::NOT_FOUND, "Symbol not found."); + } std::unordered_set<TString> seen_files; - FillFileDescriptorResponse(file_desc, response, &seen_files); - return Status::OK; -} - -Status ProtoServerReflection::GetFileContainingExtension( + FillFileDescriptorResponse(file_desc, response, &seen_files); + return Status::OK; +} + +Status ProtoServerReflection::GetFileContainingExtension( ServerContext* /*context*/, const ExtensionRequest* request, - ServerReflectionResponse* response) { - if (descriptor_pool_ == nullptr) { - return Status::CANCELLED; - } - - const protobuf::Descriptor* desc = - descriptor_pool_->FindMessageTypeByName(request->containing_type()); - if (desc == nullptr) { - return Status(StatusCode::NOT_FOUND, "Type not found."); - } - - const protobuf::FieldDescriptor* field_desc = - descriptor_pool_->FindExtensionByNumber(desc, - request->extension_number()); - if (field_desc == nullptr) { - return Status(StatusCode::NOT_FOUND, "Extension not found."); - } + ServerReflectionResponse* response) { + if (descriptor_pool_ == nullptr) { + return Status::CANCELLED; + } + + const protobuf::Descriptor* desc = + descriptor_pool_->FindMessageTypeByName(request->containing_type()); + if (desc == nullptr) { + return Status(StatusCode::NOT_FOUND, "Type not found."); + } + + const protobuf::FieldDescriptor* field_desc = + descriptor_pool_->FindExtensionByNumber(desc, + request->extension_number()); + if (field_desc == nullptr) { + return Status(StatusCode::NOT_FOUND, "Extension not found."); + } std::unordered_set<TString> seen_files; - FillFileDescriptorResponse(field_desc->file(), response, &seen_files); - return Status::OK; -} - -Status ProtoServerReflection::GetAllExtensionNumbers( + FillFileDescriptorResponse(field_desc->file(), response, &seen_files); + return Status::OK; +} + +Status ProtoServerReflection::GetAllExtensionNumbers( ServerContext* /*context*/, const TString& type, - ExtensionNumberResponse* response) { - if (descriptor_pool_ == nullptr) { - return Status::CANCELLED; - } - - const protobuf::Descriptor* desc = + ExtensionNumberResponse* response) { + if (descriptor_pool_ == nullptr) { + return Status::CANCELLED; + } + + const protobuf::Descriptor* desc = descriptor_pool_->FindMessageTypeByName(TProtoStringType(type)); - if (desc == nullptr) { - return Status(StatusCode::NOT_FOUND, "Type not found."); - } - - std::vector<const protobuf::FieldDescriptor*> extensions; - descriptor_pool_->FindAllExtensions(desc, &extensions); + if (desc == nullptr) { + return Status(StatusCode::NOT_FOUND, "Type not found."); + } + + std::vector<const protobuf::FieldDescriptor*> extensions; + descriptor_pool_->FindAllExtensions(desc, &extensions); for (const auto& value : extensions) { response->add_extension_number(value->number()); - } + } response->set_base_type_name(TProtoStringType(type)); - return Status::OK; -} - -void ProtoServerReflection::FillFileDescriptorResponse( - const protobuf::FileDescriptor* file_desc, - ServerReflectionResponse* response, + return Status::OK; +} + +void ProtoServerReflection::FillFileDescriptorResponse( + const protobuf::FileDescriptor* file_desc, + ServerReflectionResponse* response, std::unordered_set<TString>* seen_files) { - if (seen_files->find(file_desc->name()) != seen_files->end()) { - return; - } - seen_files->insert(file_desc->name()); - - protobuf::FileDescriptorProto file_desc_proto; + if (seen_files->find(file_desc->name()) != seen_files->end()) { + return; + } + seen_files->insert(file_desc->name()); + + protobuf::FileDescriptorProto file_desc_proto; TProtoStringType data; - file_desc->CopyTo(&file_desc_proto); - file_desc_proto.SerializeToString(&data); - response->mutable_file_descriptor_response()->add_file_descriptor_proto(data); - - for (int i = 0; i < file_desc->dependency_count(); ++i) { - FillFileDescriptorResponse(file_desc->dependency(i), response, seen_files); - } -} - -} // namespace grpc + file_desc->CopyTo(&file_desc_proto); + file_desc_proto.SerializeToString(&data); + response->mutable_file_descriptor_response()->add_file_descriptor_proto(data); + + for (int i = 0; i < file_desc->dependency_count(); ++i) { + FillFileDescriptorResponse(file_desc->dependency(i), response, seen_files); + } +} + +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.h b/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.h index 2d17eed95a..8bd562dda1 100644 --- a/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.h +++ b/contrib/libs/grpc/src/cpp/ext/proto_server_reflection.h @@ -1,80 +1,80 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#ifndef GRPC_INTERNAL_CPP_EXT_PROTO_SERVER_REFLECTION_H -#define GRPC_INTERNAL_CPP_EXT_PROTO_SERVER_REFLECTION_H - -#include <unordered_set> -#include <vector> - + * + */ + +#ifndef GRPC_INTERNAL_CPP_EXT_PROTO_SERVER_REFLECTION_H +#define GRPC_INTERNAL_CPP_EXT_PROTO_SERVER_REFLECTION_H + +#include <unordered_set> +#include <vector> + #include <grpcpp/grpcpp.h> -#include "src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.h" - -namespace grpc { - -class ProtoServerReflection final - : public reflection::v1alpha::ServerReflection::Service { - public: - ProtoServerReflection(); - - // Add the full names of registered services +#include "src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.h" + +namespace grpc { + +class ProtoServerReflection final + : public reflection::v1alpha::ServerReflection::Service { + public: + ProtoServerReflection(); + + // Add the full names of registered services void SetServiceList(const std::vector<TString>* services); - - // implementation of ServerReflectionInfo(stream ServerReflectionRequest) rpc - // in ServerReflection service - Status ServerReflectionInfo( - ServerContext* context, - ServerReaderWriter<reflection::v1alpha::ServerReflectionResponse, - reflection::v1alpha::ServerReflectionRequest>* stream) - override; - - private: - Status ListService(ServerContext* context, - reflection::v1alpha::ListServiceResponse* response); - + + // implementation of ServerReflectionInfo(stream ServerReflectionRequest) rpc + // in ServerReflection service + Status ServerReflectionInfo( + ServerContext* context, + ServerReaderWriter<reflection::v1alpha::ServerReflectionResponse, + reflection::v1alpha::ServerReflectionRequest>* stream) + override; + + private: + Status ListService(ServerContext* context, + reflection::v1alpha::ListServiceResponse* response); + Status GetFileByName(ServerContext* context, const TString& file_name, - reflection::v1alpha::ServerReflectionResponse* response); - - Status GetFileContainingSymbol( + reflection::v1alpha::ServerReflectionResponse* response); + + Status GetFileContainingSymbol( ServerContext* context, const TString& symbol, - reflection::v1alpha::ServerReflectionResponse* response); - - Status GetFileContainingExtension( - ServerContext* context, - const reflection::v1alpha::ExtensionRequest* request, - reflection::v1alpha::ServerReflectionResponse* response); - - Status GetAllExtensionNumbers( + reflection::v1alpha::ServerReflectionResponse* response); + + Status GetFileContainingExtension( + ServerContext* context, + const reflection::v1alpha::ExtensionRequest* request, + reflection::v1alpha::ServerReflectionResponse* response); + + Status GetAllExtensionNumbers( ServerContext* context, const TString& type, - reflection::v1alpha::ExtensionNumberResponse* response); - - void FillFileDescriptorResponse( - const protobuf::FileDescriptor* file_desc, - reflection::v1alpha::ServerReflectionResponse* response, + reflection::v1alpha::ExtensionNumberResponse* response); + + void FillFileDescriptorResponse( + const protobuf::FileDescriptor* file_desc, + reflection::v1alpha::ServerReflectionResponse* response, std::unordered_set<TString>* seen_files); - - void FillErrorResponse(const Status& status, - reflection::v1alpha::ErrorResponse* error_response); - - const protobuf::DescriptorPool* descriptor_pool_; - const std::vector<string>* services_; -}; - -} // namespace grpc - -#endif // GRPC_INTERNAL_CPP_EXT_PROTO_SERVER_REFLECTION_H + + void FillErrorResponse(const Status& status, + reflection::v1alpha::ErrorResponse* error_response); + + const protobuf::DescriptorPool* descriptor_pool_; + const std::vector<string>* services_; +}; + +} // namespace grpc + +#endif // GRPC_INTERNAL_CPP_EXT_PROTO_SERVER_REFLECTION_H diff --git a/contrib/libs/grpc/src/cpp/ext/proto_server_reflection_plugin.cc b/contrib/libs/grpc/src/cpp/ext/proto_server_reflection_plugin.cc index 007193d7f7..6e468ba1fd 100644 --- a/contrib/libs/grpc/src/cpp/ext/proto_server_reflection_plugin.cc +++ b/contrib/libs/grpc/src/cpp/ext/proto_server_reflection_plugin.cc @@ -1,83 +1,83 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/ext/proto_server_reflection_plugin.h> #include <grpcpp/impl/server_builder_plugin.h> #include <grpcpp/impl/server_initializer.h> #include <grpcpp/server.h> - -#include "src/cpp/ext/proto_server_reflection.h" - + +#include "src/cpp/ext/proto_server_reflection.h" + namespace grpc { -namespace reflection { - -ProtoServerReflectionPlugin::ProtoServerReflectionPlugin() - : reflection_service_(new grpc::ProtoServerReflection()) {} - +namespace reflection { + +ProtoServerReflectionPlugin::ProtoServerReflectionPlugin() + : reflection_service_(new grpc::ProtoServerReflection()) {} + TString ProtoServerReflectionPlugin::name() { - return "proto_server_reflection"; -} - -void ProtoServerReflectionPlugin::InitServer(grpc::ServerInitializer* si) { - si->RegisterService(reflection_service_); -} - -void ProtoServerReflectionPlugin::Finish(grpc::ServerInitializer* si) { - reflection_service_->SetServiceList(si->GetServiceList()); -} - + return "proto_server_reflection"; +} + +void ProtoServerReflectionPlugin::InitServer(grpc::ServerInitializer* si) { + si->RegisterService(reflection_service_); +} + +void ProtoServerReflectionPlugin::Finish(grpc::ServerInitializer* si) { + reflection_service_->SetServiceList(si->GetServiceList()); +} + void ProtoServerReflectionPlugin::ChangeArguments(const TString& /*name*/, void* /*value*/) {} - -bool ProtoServerReflectionPlugin::has_sync_methods() const { - if (reflection_service_) { - return reflection_service_->has_synchronous_methods(); - } - return false; -} - -bool ProtoServerReflectionPlugin::has_async_methods() const { - if (reflection_service_) { - return reflection_service_->has_async_methods(); - } - return false; -} - -static std::unique_ptr< ::grpc::ServerBuilderPlugin> CreateProtoReflection() { - return std::unique_ptr< ::grpc::ServerBuilderPlugin>( - new ProtoServerReflectionPlugin()); -} - -void InitProtoReflectionServerBuilderPlugin() { + +bool ProtoServerReflectionPlugin::has_sync_methods() const { + if (reflection_service_) { + return reflection_service_->has_synchronous_methods(); + } + return false; +} + +bool ProtoServerReflectionPlugin::has_async_methods() const { + if (reflection_service_) { + return reflection_service_->has_async_methods(); + } + return false; +} + +static std::unique_ptr< ::grpc::ServerBuilderPlugin> CreateProtoReflection() { + return std::unique_ptr< ::grpc::ServerBuilderPlugin>( + new ProtoServerReflectionPlugin()); +} + +void InitProtoReflectionServerBuilderPlugin() { static struct Initialize { Initialize() { ::grpc::ServerBuilder::InternalAddPluginFactory(&CreateProtoReflection); } } initializer; -} - -// Force InitProtoReflectionServerBuilderPlugin() to be called at static -// initialization time. -struct StaticProtoReflectionPluginInitializer { - StaticProtoReflectionPluginInitializer() { - InitProtoReflectionServerBuilderPlugin(); - } -} static_proto_reflection_plugin_initializer; - -} // namespace reflection +} + +// Force InitProtoReflectionServerBuilderPlugin() to be called at static +// initialization time. +struct StaticProtoReflectionPluginInitializer { + StaticProtoReflectionPluginInitializer() { + InitProtoReflectionServerBuilderPlugin(); + } +} static_proto_reflection_plugin_initializer; + +} // namespace reflection } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/server/async_generic_service.cc b/contrib/libs/grpc/src/cpp/server/async_generic_service.cc index 07697a52d1..a6c901d83c 100644 --- a/contrib/libs/grpc/src/cpp/server/async_generic_service.cc +++ b/contrib/libs/grpc/src/cpp/server/async_generic_service.cc @@ -1,33 +1,33 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/generic/async_generic_service.h> - + #include <grpcpp/server.h> - -namespace grpc { - -void AsyncGenericService::RequestCall( - GenericServerContext* ctx, GenericServerAsyncReaderWriter* reader_writer, + +namespace grpc { + +void AsyncGenericService::RequestCall( + GenericServerContext* ctx, GenericServerAsyncReaderWriter* reader_writer, ::grpc::CompletionQueue* call_cq, ::grpc::ServerCompletionQueue* notification_cq, void* tag) { - server_->RequestAsyncGenericCall(ctx, reader_writer, call_cq, notification_cq, - tag); -} - -} // namespace grpc + server_->RequestAsyncGenericCall(ctx, reader_writer, call_cq, notification_cq, + tag); +} + +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/server/create_default_thread_pool.cc b/contrib/libs/grpc/src/cpp/server/create_default_thread_pool.cc index 8ca3e32c2f..b682af211f 100644 --- a/contrib/libs/grpc/src/cpp/server/create_default_thread_pool.cc +++ b/contrib/libs/grpc/src/cpp/server/create_default_thread_pool.cc @@ -1,36 +1,36 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#include <grpc/support/cpu.h> - -#include "src/cpp/server/dynamic_thread_pool.h" - -#ifndef GRPC_CUSTOM_DEFAULT_THREAD_POOL - -namespace grpc { + * + */ + +#include <grpc/support/cpu.h> + +#include "src/cpp/server/dynamic_thread_pool.h" + +#ifndef GRPC_CUSTOM_DEFAULT_THREAD_POOL + +namespace grpc { namespace { - + ThreadPoolInterface* CreateDefaultThreadPoolImpl() { - int cores = gpr_cpu_num_cores(); - if (!cores) cores = 4; - return new DynamicThreadPool(cores); -} - + int cores = gpr_cpu_num_cores(); + if (!cores) cores = 4; + return new DynamicThreadPool(cores); +} + CreateThreadPoolFunc g_ctp_impl = CreateDefaultThreadPoolImpl; } // namespace @@ -39,6 +39,6 @@ ThreadPoolInterface* CreateDefaultThreadPool() { return g_ctp_impl(); } void SetCreateThreadPool(CreateThreadPoolFunc func) { g_ctp_impl = func; } -} // namespace grpc - -#endif // !GRPC_CUSTOM_DEFAULT_THREAD_POOL +} // namespace grpc + +#endif // !GRPC_CUSTOM_DEFAULT_THREAD_POOL diff --git a/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.cc b/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.cc index 77c5d6a263..ffb232c847 100644 --- a/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.cc +++ b/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.cc @@ -1,124 +1,124 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include "src/cpp/server/dynamic_thread_pool.h" #include <grpc/support/log.h> #include <grpcpp/impl/codegen/sync.h> - + #include "src/core/lib/gprpp/thd.h" -namespace grpc { +namespace grpc { -DynamicThreadPool::DynamicThread::DynamicThread(DynamicThreadPool* pool) - : pool_(pool), +DynamicThreadPool::DynamicThread::DynamicThread(DynamicThreadPool* pool) + : pool_(pool), thd_("grpcpp_dynamic_pool", [](void* th) { static_cast<DynamicThreadPool::DynamicThread*>(th)->ThreadFunc(); }, this) { thd_.Start(); -} +} DynamicThreadPool::DynamicThread::~DynamicThread() { thd_.Join(); } - -void DynamicThreadPool::DynamicThread::ThreadFunc() { - pool_->ThreadFunc(); - // Now that we have killed ourselves, we should reduce the thread count + +void DynamicThreadPool::DynamicThread::ThreadFunc() { + pool_->ThreadFunc(); + // Now that we have killed ourselves, we should reduce the thread count grpc_core::MutexLock lock(&pool_->mu_); - pool_->nthreads_--; - // Move ourselves to dead list - pool_->dead_threads_.push_back(this); - - if ((pool_->shutdown_) && (pool_->nthreads_ == 0)) { + pool_->nthreads_--; + // Move ourselves to dead list + pool_->dead_threads_.push_back(this); + + if ((pool_->shutdown_) && (pool_->nthreads_ == 0)) { pool_->shutdown_cv_.Signal(); - } -} - -void DynamicThreadPool::ThreadFunc() { - for (;;) { - // Wait until work is available or we are shutting down. + } +} + +void DynamicThreadPool::ThreadFunc() { + for (;;) { + // Wait until work is available or we are shutting down. grpc_core::ReleasableMutexLock lock(&mu_); - if (!shutdown_ && callbacks_.empty()) { - // If there are too many threads waiting, then quit this thread - if (threads_waiting_ >= reserve_threads_) { - break; - } - threads_waiting_++; + if (!shutdown_ && callbacks_.empty()) { + // If there are too many threads waiting, then quit this thread + if (threads_waiting_ >= reserve_threads_) { + break; + } + threads_waiting_++; cv_.Wait(&mu_); - threads_waiting_--; - } - // Drain callbacks before considering shutdown to ensure all work - // gets completed. - if (!callbacks_.empty()) { - auto cb = callbacks_.front(); - callbacks_.pop(); + threads_waiting_--; + } + // Drain callbacks before considering shutdown to ensure all work + // gets completed. + if (!callbacks_.empty()) { + auto cb = callbacks_.front(); + callbacks_.pop(); lock.Unlock(); - cb(); - } else if (shutdown_) { - break; - } - } -} - -DynamicThreadPool::DynamicThreadPool(int reserve_threads) - : shutdown_(false), - reserve_threads_(reserve_threads), - nthreads_(0), - threads_waiting_(0) { - for (int i = 0; i < reserve_threads_; i++) { + cb(); + } else if (shutdown_) { + break; + } + } +} + +DynamicThreadPool::DynamicThreadPool(int reserve_threads) + : shutdown_(false), + reserve_threads_(reserve_threads), + nthreads_(0), + threads_waiting_(0) { + for (int i = 0; i < reserve_threads_; i++) { grpc_core::MutexLock lock(&mu_); - nthreads_++; - new DynamicThread(this); - } -} - -void DynamicThreadPool::ReapThreads(std::list<DynamicThread*>* tlist) { - for (auto t = tlist->begin(); t != tlist->end(); t = tlist->erase(t)) { - delete *t; - } -} - -DynamicThreadPool::~DynamicThreadPool() { + nthreads_++; + new DynamicThread(this); + } +} + +void DynamicThreadPool::ReapThreads(std::list<DynamicThread*>* tlist) { + for (auto t = tlist->begin(); t != tlist->end(); t = tlist->erase(t)) { + delete *t; + } +} + +DynamicThreadPool::~DynamicThreadPool() { grpc_core::MutexLock lock(&mu_); - shutdown_ = true; + shutdown_ = true; cv_.Broadcast(); - while (nthreads_ != 0) { + while (nthreads_ != 0) { shutdown_cv_.Wait(&mu_); - } - ReapThreads(&dead_threads_); -} - -void DynamicThreadPool::Add(const std::function<void()>& callback) { + } + ReapThreads(&dead_threads_); +} + +void DynamicThreadPool::Add(const std::function<void()>& callback) { grpc_core::MutexLock lock(&mu_); - // Add works to the callbacks list - callbacks_.push(callback); - // Increase pool size or notify as needed - if (threads_waiting_ == 0) { - // Kick off a new thread - nthreads_++; - new DynamicThread(this); - } else { + // Add works to the callbacks list + callbacks_.push(callback); + // Increase pool size or notify as needed + if (threads_waiting_ == 0) { + // Kick off a new thread + nthreads_++; + new DynamicThread(this); + } else { cv_.Signal(); - } - // Also use this chance to harvest dead threads - if (!dead_threads_.empty()) { - ReapThreads(&dead_threads_); - } -} - -} // namespace grpc + } + // Also use this chance to harvest dead threads + if (!dead_threads_.empty()) { + ReapThreads(&dead_threads_); + } +} + +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.h b/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.h index 6f9f943bc3..edf0c56c22 100644 --- a/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.h +++ b/contrib/libs/grpc/src/cpp/server/dynamic_thread_pool.h @@ -1,68 +1,68 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#ifndef GRPC_INTERNAL_CPP_DYNAMIC_THREAD_POOL_H -#define GRPC_INTERNAL_CPP_DYNAMIC_THREAD_POOL_H - -#include <list> -#include <memory> -#include <queue> - + * + */ + +#ifndef GRPC_INTERNAL_CPP_DYNAMIC_THREAD_POOL_H +#define GRPC_INTERNAL_CPP_DYNAMIC_THREAD_POOL_H + +#include <list> +#include <memory> +#include <queue> + #include <grpcpp/support/config.h> - + #include "src/core/lib/gprpp/sync.h" #include "src/core/lib/gprpp/thd.h" -#include "src/cpp/server/thread_pool_interface.h" - -namespace grpc { - -class DynamicThreadPool final : public ThreadPoolInterface { - public: - explicit DynamicThreadPool(int reserve_threads); - ~DynamicThreadPool(); - - void Add(const std::function<void()>& callback) override; - - private: - class DynamicThread { - public: - DynamicThread(DynamicThreadPool* pool); - ~DynamicThread(); - - private: - DynamicThreadPool* pool_; +#include "src/cpp/server/thread_pool_interface.h" + +namespace grpc { + +class DynamicThreadPool final : public ThreadPoolInterface { + public: + explicit DynamicThreadPool(int reserve_threads); + ~DynamicThreadPool(); + + void Add(const std::function<void()>& callback) override; + + private: + class DynamicThread { + public: + DynamicThread(DynamicThreadPool* pool); + ~DynamicThread(); + + private: + DynamicThreadPool* pool_; grpc_core::Thread thd_; - void ThreadFunc(); - }; + void ThreadFunc(); + }; grpc_core::Mutex mu_; grpc_core::CondVar cv_; grpc_core::CondVar shutdown_cv_; - bool shutdown_; - std::queue<std::function<void()>> callbacks_; - int reserve_threads_; - int nthreads_; - int threads_waiting_; - std::list<DynamicThread*> dead_threads_; - - void ThreadFunc(); - static void ReapThreads(std::list<DynamicThread*>* tlist); -}; - -} // namespace grpc - -#endif // GRPC_INTERNAL_CPP_DYNAMIC_THREAD_POOL_H + bool shutdown_; + std::queue<std::function<void()>> callbacks_; + int reserve_threads_; + int nthreads_; + int threads_waiting_; + std::list<DynamicThread*> dead_threads_; + + void ThreadFunc(); + static void ReapThreads(std::list<DynamicThread*>* tlist); +}; + +} // namespace grpc + +#endif // GRPC_INTERNAL_CPP_DYNAMIC_THREAD_POOL_H diff --git a/contrib/libs/grpc/src/cpp/server/insecure_server_credentials.cc b/contrib/libs/grpc/src/cpp/server/insecure_server_credentials.cc index 3f33f4e045..c592066372 100644 --- a/contrib/libs/grpc/src/cpp/server/insecure_server_credentials.cc +++ b/contrib/libs/grpc/src/cpp/server/insecure_server_credentials.cc @@ -1,44 +1,44 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/security/server_credentials.h> - -#include <grpc/grpc.h> -#include <grpc/support/log.h> - + +#include <grpc/grpc.h> +#include <grpc/support/log.h> + namespace grpc { -namespace { -class InsecureServerCredentialsImpl final : public ServerCredentials { - public: +namespace { +class InsecureServerCredentialsImpl final : public ServerCredentials { + public: int AddPortToServer(const TString& addr, grpc_server* server) override { - return grpc_server_add_insecure_http2_port(server, addr.c_str()); - } - void SetAuthMetadataProcessor( + return grpc_server_add_insecure_http2_port(server, addr.c_str()); + } + void SetAuthMetadataProcessor( const std::shared_ptr<grpc::AuthMetadataProcessor>& processor) override { - (void)processor; - GPR_ASSERT(0); // Should not be called on InsecureServerCredentials. - } -}; -} // namespace - -std::shared_ptr<ServerCredentials> InsecureServerCredentials() { - return std::shared_ptr<ServerCredentials>( - new InsecureServerCredentialsImpl()); -} - + (void)processor; + GPR_ASSERT(0); // Should not be called on InsecureServerCredentials. + } +}; +} // namespace + +std::shared_ptr<ServerCredentials> InsecureServerCredentials() { + return std::shared_ptr<ServerCredentials>( + new InsecureServerCredentialsImpl()); +} + } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/server/secure_server_credentials.cc b/contrib/libs/grpc/src/cpp/server/secure_server_credentials.cc index 732602bcb7..143773a062 100644 --- a/contrib/libs/grpc/src/cpp/server/secure_server_credentials.cc +++ b/contrib/libs/grpc/src/cpp/server/secure_server_credentials.cc @@ -1,130 +1,130 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#include <functional> -#include <map> -#include <memory> - + * + */ + +#include <functional> +#include <map> +#include <memory> + #include <grpcpp/impl/codegen/slice.h> #include <grpcpp/impl/grpc_library.h> #include <grpcpp/security/auth_metadata_processor.h> -#include "src/cpp/common/secure_auth_context.h" -#include "src/cpp/server/secure_server_credentials.h" - -namespace grpc { - -void AuthMetadataProcessorAyncWrapper::Destroy(void* wrapper) { +#include "src/cpp/common/secure_auth_context.h" +#include "src/cpp/server/secure_server_credentials.h" + +namespace grpc { + +void AuthMetadataProcessorAyncWrapper::Destroy(void* wrapper) { auto* w = static_cast<AuthMetadataProcessorAyncWrapper*>(wrapper); - delete w; -} - -void AuthMetadataProcessorAyncWrapper::Process( - void* wrapper, grpc_auth_context* context, const grpc_metadata* md, - size_t num_md, grpc_process_auth_metadata_done_cb cb, void* user_data) { + delete w; +} + +void AuthMetadataProcessorAyncWrapper::Process( + void* wrapper, grpc_auth_context* context, const grpc_metadata* md, + size_t num_md, grpc_process_auth_metadata_done_cb cb, void* user_data) { auto* w = static_cast<AuthMetadataProcessorAyncWrapper*>(wrapper); - if (!w->processor_) { - // Early exit. - cb(user_data, nullptr, 0, nullptr, 0, GRPC_STATUS_OK, nullptr); - return; - } - if (w->processor_->IsBlocking()) { + if (!w->processor_) { + // Early exit. + cb(user_data, nullptr, 0, nullptr, 0, GRPC_STATUS_OK, nullptr); + return; + } + if (w->processor_->IsBlocking()) { w->thread_pool_->Add([w, context, md, num_md, cb, user_data] { w->AuthMetadataProcessorAyncWrapper::InvokeProcessor(context, md, num_md, cb, user_data); }); - } else { - // invoke directly. - w->InvokeProcessor(context, md, num_md, cb, user_data); - } -} - -void AuthMetadataProcessorAyncWrapper::InvokeProcessor( - grpc_auth_context* ctx, const grpc_metadata* md, size_t num_md, - grpc_process_auth_metadata_done_cb cb, void* user_data) { - AuthMetadataProcessor::InputMetadata metadata; - for (size_t i = 0; i < num_md; i++) { + } else { + // invoke directly. + w->InvokeProcessor(context, md, num_md, cb, user_data); + } +} + +void AuthMetadataProcessorAyncWrapper::InvokeProcessor( + grpc_auth_context* ctx, const grpc_metadata* md, size_t num_md, + grpc_process_auth_metadata_done_cb cb, void* user_data) { + AuthMetadataProcessor::InputMetadata metadata; + for (size_t i = 0; i < num_md; i++) { metadata.insert(std::make_pair(StringRefFromSlice(&md[i].key), StringRefFromSlice(&md[i].value))); - } + } SecureAuthContext context(ctx); - AuthMetadataProcessor::OutputMetadata consumed_metadata; - AuthMetadataProcessor::OutputMetadata response_metadata; - - Status status = processor_->Process(metadata, &context, &consumed_metadata, - &response_metadata); - - std::vector<grpc_metadata> consumed_md; + AuthMetadataProcessor::OutputMetadata consumed_metadata; + AuthMetadataProcessor::OutputMetadata response_metadata; + + Status status = processor_->Process(metadata, &context, &consumed_metadata, + &response_metadata); + + std::vector<grpc_metadata> consumed_md; for (const auto& consumed : consumed_metadata) { - grpc_metadata md_entry; + grpc_metadata md_entry; md_entry.key = SliceReferencingString(consumed.first); md_entry.value = SliceReferencingString(consumed.second); - md_entry.flags = 0; - consumed_md.push_back(md_entry); - } - std::vector<grpc_metadata> response_md; + md_entry.flags = 0; + consumed_md.push_back(md_entry); + } + std::vector<grpc_metadata> response_md; for (const auto& response : response_metadata) { - grpc_metadata md_entry; + grpc_metadata md_entry; md_entry.key = SliceReferencingString(response.first); md_entry.value = SliceReferencingString(response.second); - md_entry.flags = 0; - response_md.push_back(md_entry); - } - auto consumed_md_data = consumed_md.empty() ? nullptr : &consumed_md[0]; - auto response_md_data = response_md.empty() ? nullptr : &response_md[0]; - cb(user_data, consumed_md_data, consumed_md.size(), response_md_data, - response_md.size(), static_cast<grpc_status_code>(status.error_code()), - status.error_message().c_str()); -} - + md_entry.flags = 0; + response_md.push_back(md_entry); + } + auto consumed_md_data = consumed_md.empty() ? nullptr : &consumed_md[0]; + auto response_md_data = response_md.empty() ? nullptr : &response_md[0]; + cb(user_data, consumed_md_data, consumed_md.size(), response_md_data, + response_md.size(), static_cast<grpc_status_code>(status.error_code()), + status.error_message().c_str()); +} + int SecureServerCredentials::AddPortToServer(const TString& addr, - grpc_server* server) { - return grpc_server_add_secure_http2_port(server, addr.c_str(), creds_); -} - -void SecureServerCredentials::SetAuthMetadataProcessor( + grpc_server* server) { + return grpc_server_add_secure_http2_port(server, addr.c_str(), creds_); +} + +void SecureServerCredentials::SetAuthMetadataProcessor( const std::shared_ptr<grpc::AuthMetadataProcessor>& processor) { auto* wrapper = new grpc::AuthMetadataProcessorAyncWrapper(processor); - grpc_server_credentials_set_auth_metadata_processor( + grpc_server_credentials_set_auth_metadata_processor( creds_, {grpc::AuthMetadataProcessorAyncWrapper::Process, grpc::AuthMetadataProcessorAyncWrapper::Destroy, wrapper}); -} - -std::shared_ptr<ServerCredentials> SslServerCredentials( +} + +std::shared_ptr<ServerCredentials> SslServerCredentials( const grpc::SslServerCredentialsOptions& options) { - std::vector<grpc_ssl_pem_key_cert_pair> pem_key_cert_pairs; + std::vector<grpc_ssl_pem_key_cert_pair> pem_key_cert_pairs; for (const auto& key_cert_pair : options.pem_key_cert_pairs) { grpc_ssl_pem_key_cert_pair p = {key_cert_pair.private_key.c_str(), key_cert_pair.cert_chain.c_str()}; - pem_key_cert_pairs.push_back(p); - } - grpc_server_credentials* c_creds = grpc_ssl_server_credentials_create_ex( - options.pem_root_certs.empty() ? nullptr : options.pem_root_certs.c_str(), - pem_key_cert_pairs.empty() ? nullptr : &pem_key_cert_pairs[0], - pem_key_cert_pairs.size(), - options.force_client_auth - ? GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY - : options.client_certificate_request, - nullptr); - return std::shared_ptr<ServerCredentials>( - new SecureServerCredentials(c_creds)); -} - + pem_key_cert_pairs.push_back(p); + } + grpc_server_credentials* c_creds = grpc_ssl_server_credentials_create_ex( + options.pem_root_certs.empty() ? nullptr : options.pem_root_certs.c_str(), + pem_key_cert_pairs.empty() ? nullptr : &pem_key_cert_pairs[0], + pem_key_cert_pairs.size(), + options.force_client_auth + ? GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY + : options.client_certificate_request, + nullptr); + return std::shared_ptr<ServerCredentials>( + new SecureServerCredentials(c_creds)); +} + namespace experimental { std::shared_ptr<ServerCredentials> AltsServerCredentials( diff --git a/contrib/libs/grpc/src/cpp/server/secure_server_credentials.h b/contrib/libs/grpc/src/cpp/server/secure_server_credentials.h index 9e3fb3f9eb..1970f6b65e 100644 --- a/contrib/libs/grpc/src/cpp/server/secure_server_credentials.h +++ b/contrib/libs/grpc/src/cpp/server/secure_server_credentials.h @@ -1,79 +1,79 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#ifndef GRPC_INTERNAL_CPP_SERVER_SECURE_SERVER_CREDENTIALS_H -#define GRPC_INTERNAL_CPP_SERVER_SECURE_SERVER_CREDENTIALS_H - -#include <memory> - + * + */ + +#ifndef GRPC_INTERNAL_CPP_SERVER_SECURE_SERVER_CREDENTIALS_H +#define GRPC_INTERNAL_CPP_SERVER_SECURE_SERVER_CREDENTIALS_H + +#include <memory> + #include <grpcpp/security/server_credentials.h> #include <grpcpp/security/tls_credentials_options.h> - -#include <grpc/grpc_security.h> - -#include "src/cpp/server/thread_pool_interface.h" - + +#include <grpc/grpc_security.h> + +#include "src/cpp/server/thread_pool_interface.h" + namespace grpc { class SecureServerCredentials; -class AuthMetadataProcessorAyncWrapper final { - public: - static void Destroy(void* wrapper); - - static void Process(void* wrapper, grpc_auth_context* context, - const grpc_metadata* md, size_t num_md, - grpc_process_auth_metadata_done_cb cb, void* user_data); - - AuthMetadataProcessorAyncWrapper( - const std::shared_ptr<AuthMetadataProcessor>& processor) +class AuthMetadataProcessorAyncWrapper final { + public: + static void Destroy(void* wrapper); + + static void Process(void* wrapper, grpc_auth_context* context, + const grpc_metadata* md, size_t num_md, + grpc_process_auth_metadata_done_cb cb, void* user_data); + + AuthMetadataProcessorAyncWrapper( + const std::shared_ptr<AuthMetadataProcessor>& processor) : processor_(processor) { if (processor && processor->IsBlocking()) { thread_pool_.reset(CreateDefaultThreadPool()); } } - - private: - void InvokeProcessor(grpc_auth_context* context, const grpc_metadata* md, - size_t num_md, grpc_process_auth_metadata_done_cb cb, - void* user_data); - std::unique_ptr<ThreadPoolInterface> thread_pool_; - std::shared_ptr<AuthMetadataProcessor> processor_; -}; - -class SecureServerCredentials final : public ServerCredentials { - public: - explicit SecureServerCredentials(grpc_server_credentials* creds) - : creds_(creds) {} - ~SecureServerCredentials() override { - grpc_server_credentials_release(creds_); - } - + + private: + void InvokeProcessor(grpc_auth_context* context, const grpc_metadata* md, + size_t num_md, grpc_process_auth_metadata_done_cb cb, + void* user_data); + std::unique_ptr<ThreadPoolInterface> thread_pool_; + std::shared_ptr<AuthMetadataProcessor> processor_; +}; + +class SecureServerCredentials final : public ServerCredentials { + public: + explicit SecureServerCredentials(grpc_server_credentials* creds) + : creds_(creds) {} + ~SecureServerCredentials() override { + grpc_server_credentials_release(creds_); + } + int AddPortToServer(const TString& addr, grpc_server* server) override; - - void SetAuthMetadataProcessor( + + void SetAuthMetadataProcessor( const std::shared_ptr<grpc::AuthMetadataProcessor>& processor) override; - - private: - grpc_server_credentials* creds_; + + private: + grpc_server_credentials* creds_; std::unique_ptr<grpc::AuthMetadataProcessorAyncWrapper> processor_; -}; - +}; + } // namespace grpc - -#endif // GRPC_INTERNAL_CPP_SERVER_SECURE_SERVER_CREDENTIALS_H + +#endif // GRPC_INTERNAL_CPP_SERVER_SECURE_SERVER_CREDENTIALS_H diff --git a/contrib/libs/grpc/src/cpp/server/server_builder.cc b/contrib/libs/grpc/src/cpp/server/server_builder.cc index 0cc00b365f..842fb7e366 100644 --- a/contrib/libs/grpc/src/cpp/server/server_builder.cc +++ b/contrib/libs/grpc/src/cpp/server/server_builder.cc @@ -1,107 +1,107 @@ -/* - * +/* + * * Copyright 2015-2016 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/server_builder.h> - -#include <grpc/support/cpu.h> -#include <grpc/support/log.h> + +#include <grpc/support/cpu.h> +#include <grpc/support/log.h> #include <grpcpp/impl/service_type.h> #include <grpcpp/resource_quota.h> #include <grpcpp/server.h> - + #include <utility> #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gpr/useful.h" #include "src/cpp/server/external_connection_acceptor_impl.h" -#include "src/cpp/server/thread_pool_interface.h" - +#include "src/cpp/server/thread_pool_interface.h" + namespace grpc { - + static std::vector<std::unique_ptr<ServerBuilderPlugin> (*)()>* - g_plugin_factory_list; -static gpr_once once_init_plugin_list = GPR_ONCE_INIT; - -static void do_plugin_list_init(void) { - g_plugin_factory_list = + g_plugin_factory_list; +static gpr_once once_init_plugin_list = GPR_ONCE_INIT; + +static void do_plugin_list_init(void) { + g_plugin_factory_list = new std::vector<std::unique_ptr<ServerBuilderPlugin> (*)()>(); -} - -ServerBuilder::ServerBuilder() +} + +ServerBuilder::ServerBuilder() : max_receive_message_size_(INT_MIN), max_send_message_size_(INT_MIN), - sync_server_settings_(SyncServerSettings()), + sync_server_settings_(SyncServerSettings()), resource_quota_(nullptr) { - gpr_once_init(&once_init_plugin_list, do_plugin_list_init); + gpr_once_init(&once_init_plugin_list, do_plugin_list_init); for (const auto& value : *g_plugin_factory_list) { plugins_.emplace_back(value()); - } - - // all compression algorithms enabled by default. - enabled_compression_algorithms_bitset_ = - (1u << GRPC_COMPRESS_ALGORITHMS_COUNT) - 1; - memset(&maybe_default_compression_level_, 0, - sizeof(maybe_default_compression_level_)); - memset(&maybe_default_compression_algorithm_, 0, - sizeof(maybe_default_compression_algorithm_)); -} - -ServerBuilder::~ServerBuilder() { - if (resource_quota_ != nullptr) { - grpc_resource_quota_unref(resource_quota_); - } -} - + } + + // all compression algorithms enabled by default. + enabled_compression_algorithms_bitset_ = + (1u << GRPC_COMPRESS_ALGORITHMS_COUNT) - 1; + memset(&maybe_default_compression_level_, 0, + sizeof(maybe_default_compression_level_)); + memset(&maybe_default_compression_algorithm_, 0, + sizeof(maybe_default_compression_algorithm_)); +} + +ServerBuilder::~ServerBuilder() { + if (resource_quota_ != nullptr) { + grpc_resource_quota_unref(resource_quota_); + } +} + std::unique_ptr<grpc::ServerCompletionQueue> ServerBuilder::AddCompletionQueue( - bool is_frequently_polled) { + bool is_frequently_polled) { grpc::ServerCompletionQueue* cq = new grpc::ServerCompletionQueue( GRPC_CQ_NEXT, is_frequently_polled ? GRPC_CQ_DEFAULT_POLLING : GRPC_CQ_NON_LISTENING, nullptr); - cqs_.push_back(cq); + cqs_.push_back(cq); return std::unique_ptr<grpc::ServerCompletionQueue>(cq); -} - +} + ServerBuilder& ServerBuilder::RegisterService(Service* service) { - services_.emplace_back(new NamedService(service)); - return *this; -} - + services_.emplace_back(new NamedService(service)); + return *this; +} + ServerBuilder& ServerBuilder::RegisterService(const TString& addr, Service* service) { - services_.emplace_back(new NamedService(addr, service)); - return *this; -} - -ServerBuilder& ServerBuilder::RegisterAsyncGenericService( + services_.emplace_back(new NamedService(addr, service)); + return *this; +} + +ServerBuilder& ServerBuilder::RegisterAsyncGenericService( AsyncGenericService* service) { if (generic_service_ || callback_generic_service_) { - gpr_log(GPR_ERROR, + gpr_log(GPR_ERROR, "Adding multiple generic services is unsupported for now. " - "Dropping the service %p", - (void*)service); - } else { - generic_service_ = service; - } - return *this; -} - + "Dropping the service %p", + (void*)service); + } else { + generic_service_ = service; + } + return *this; +} + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL ServerBuilder& ServerBuilder::RegisterCallbackGenericService( CallbackGenericService* service) { @@ -143,66 +143,66 @@ ServerBuilder::experimental_type::AddExternalConnectionAcceptor( return builder_->acceptors_.back()->GetAcceptor(); } -ServerBuilder& ServerBuilder::SetOption( +ServerBuilder& ServerBuilder::SetOption( std::unique_ptr<ServerBuilderOption> option) { - options_.push_back(std::move(option)); - return *this; -} - -ServerBuilder& ServerBuilder::SetSyncServerOption( - ServerBuilder::SyncServerOption option, int val) { - switch (option) { - case NUM_CQS: - sync_server_settings_.num_cqs = val; - break; - case MIN_POLLERS: - sync_server_settings_.min_pollers = val; - break; - case MAX_POLLERS: - sync_server_settings_.max_pollers = val; - break; - case CQ_TIMEOUT_MSEC: - sync_server_settings_.cq_timeout_msec = val; - break; - } - return *this; -} - -ServerBuilder& ServerBuilder::SetCompressionAlgorithmSupportStatus( - grpc_compression_algorithm algorithm, bool enabled) { - if (enabled) { - GPR_BITSET(&enabled_compression_algorithms_bitset_, algorithm); - } else { - GPR_BITCLEAR(&enabled_compression_algorithms_bitset_, algorithm); - } - return *this; -} - -ServerBuilder& ServerBuilder::SetDefaultCompressionLevel( - grpc_compression_level level) { + options_.push_back(std::move(option)); + return *this; +} + +ServerBuilder& ServerBuilder::SetSyncServerOption( + ServerBuilder::SyncServerOption option, int val) { + switch (option) { + case NUM_CQS: + sync_server_settings_.num_cqs = val; + break; + case MIN_POLLERS: + sync_server_settings_.min_pollers = val; + break; + case MAX_POLLERS: + sync_server_settings_.max_pollers = val; + break; + case CQ_TIMEOUT_MSEC: + sync_server_settings_.cq_timeout_msec = val; + break; + } + return *this; +} + +ServerBuilder& ServerBuilder::SetCompressionAlgorithmSupportStatus( + grpc_compression_algorithm algorithm, bool enabled) { + if (enabled) { + GPR_BITSET(&enabled_compression_algorithms_bitset_, algorithm); + } else { + GPR_BITCLEAR(&enabled_compression_algorithms_bitset_, algorithm); + } + return *this; +} + +ServerBuilder& ServerBuilder::SetDefaultCompressionLevel( + grpc_compression_level level) { maybe_default_compression_level_.is_set = true; - maybe_default_compression_level_.level = level; - return *this; -} - -ServerBuilder& ServerBuilder::SetDefaultCompressionAlgorithm( - grpc_compression_algorithm algorithm) { - maybe_default_compression_algorithm_.is_set = true; - maybe_default_compression_algorithm_.algorithm = algorithm; - return *this; -} - -ServerBuilder& ServerBuilder::SetResourceQuota( + maybe_default_compression_level_.level = level; + return *this; +} + +ServerBuilder& ServerBuilder::SetDefaultCompressionAlgorithm( + grpc_compression_algorithm algorithm) { + maybe_default_compression_algorithm_.is_set = true; + maybe_default_compression_algorithm_.algorithm = algorithm; + return *this; +} + +ServerBuilder& ServerBuilder::SetResourceQuota( const grpc::ResourceQuota& resource_quota) { - if (resource_quota_ != nullptr) { - grpc_resource_quota_unref(resource_quota_); - } - resource_quota_ = resource_quota.c_resource_quota(); - grpc_resource_quota_ref(resource_quota_); - return *this; -} - -ServerBuilder& ServerBuilder::AddListeningPort( + if (resource_quota_ != nullptr) { + grpc_resource_quota_unref(resource_quota_); + } + resource_quota_ = resource_quota.c_resource_quota(); + grpc_resource_quota_ref(resource_quota_); + return *this; +} + +ServerBuilder& ServerBuilder::AddListeningPort( const TString& addr_uri, std::shared_ptr<ServerCredentials> creds, int* selected_port) { const TString uri_scheme = "dns:"; @@ -213,73 +213,73 @@ ServerBuilder& ServerBuilder::AddListeningPort( addr = addr_uri.substr(pos); } Port port = {addr, std::move(creds), selected_port}; - ports_.push_back(port); - return *this; -} - + ports_.push_back(port); + return *this; +} + std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() { grpc::ChannelArguments args; if (max_receive_message_size_ >= -1) { - args.SetInt(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH, max_receive_message_size_); - } + args.SetInt(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH, max_receive_message_size_); + } if (max_send_message_size_ >= -1) { - args.SetInt(GRPC_ARG_MAX_SEND_MESSAGE_LENGTH, max_send_message_size_); - } + args.SetInt(GRPC_ARG_MAX_SEND_MESSAGE_LENGTH, max_send_message_size_); + } for (const auto& option : options_) { option->UpdateArguments(&args); option->UpdatePlugins(&plugins_); } - args.SetInt(GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET, - enabled_compression_algorithms_bitset_); - if (maybe_default_compression_level_.is_set) { - args.SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_LEVEL, - maybe_default_compression_level_.level); - } - if (maybe_default_compression_algorithm_.is_set) { - args.SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM, - maybe_default_compression_algorithm_.algorithm); - } - - if (resource_quota_ != nullptr) { - args.SetPointerWithVtable(GRPC_ARG_RESOURCE_QUOTA, resource_quota_, - grpc_resource_quota_arg_vtable()); - } - + args.SetInt(GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET, + enabled_compression_algorithms_bitset_); + if (maybe_default_compression_level_.is_set) { + args.SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_LEVEL, + maybe_default_compression_level_.level); + } + if (maybe_default_compression_algorithm_.is_set) { + args.SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM, + maybe_default_compression_algorithm_.algorithm); + } + + if (resource_quota_ != nullptr) { + args.SetPointerWithVtable(GRPC_ARG_RESOURCE_QUOTA, resource_quota_, + grpc_resource_quota_arg_vtable()); + } + for (const auto& plugin : plugins_) { plugin->UpdateServerBuilder(this); plugin->UpdateChannelArguments(&args); } - // == Determine if the server has any syncrhonous methods == - bool has_sync_methods = false; + // == Determine if the server has any syncrhonous methods == + bool has_sync_methods = false; for (const auto& value : services_) { if (value->service->has_synchronous_methods()) { - has_sync_methods = true; - break; - } - } - - if (!has_sync_methods) { + has_sync_methods = true; + break; + } + } + + if (!has_sync_methods) { for (const auto& value : plugins_) { if (value->has_sync_methods()) { - has_sync_methods = true; - break; - } - } - } - - // If this is a Sync server, i.e a server expositing sync API, then the server - // needs to create some completion queues to listen for incoming requests. - // 'sync_server_cqs' are those internal completion queues. - // - // This is different from the completion queues added to the server via - // ServerBuilder's AddCompletionQueue() method (those completion queues - // are in 'cqs_' member variable of ServerBuilder object) + has_sync_methods = true; + break; + } + } + } + + // If this is a Sync server, i.e a server expositing sync API, then the server + // needs to create some completion queues to listen for incoming requests. + // 'sync_server_cqs' are those internal completion queues. + // + // This is different from the completion queues added to the server via + // ServerBuilder's AddCompletionQueue() method (those completion queues + // are in 'cqs_' member variable of ServerBuilder object) std::shared_ptr<std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>> sync_server_cqs( std::make_shared< std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>>()); - + bool has_frequently_polled_cqs = false; for (const auto& cq : cqs_) { if (cq->IsFrequentlyPolled()) { @@ -300,17 +300,17 @@ std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() { const bool is_hybrid_server = has_sync_methods && has_frequently_polled_cqs; - if (has_sync_methods) { + if (has_sync_methods) { grpc_cq_polling_type polling_type = is_hybrid_server ? GRPC_CQ_NON_POLLING : GRPC_CQ_DEFAULT_POLLING; - - // Create completion queues to listen to incoming rpc requests - for (int i = 0; i < sync_server_settings_.num_cqs; i++) { + + // Create completion queues to listen to incoming rpc requests + for (int i = 0; i < sync_server_settings_.num_cqs; i++) { sync_server_cqs->emplace_back( new grpc::ServerCompletionQueue(GRPC_CQ_NEXT, polling_type, nullptr)); - } - } - + } + } + // TODO(vjpai): Add a section here for plugins once they can support callback // methods @@ -335,65 +335,65 @@ std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() { std::move(interceptor_creators_))); ServerInitializer* initializer = server->initializer(); - - // Register all the completion queues with the server. i.e - // 1. sync_server_cqs: internal completion queues created IF this is a sync - // server - // 2. cqs_: Completion queues added via AddCompletionQueue() call - + + // Register all the completion queues with the server. i.e + // 1. sync_server_cqs: internal completion queues created IF this is a sync + // server + // 2. cqs_: Completion queues added via AddCompletionQueue() call + for (const auto& cq : *sync_server_cqs) { grpc_server_register_completion_queue(server->server_, cq->cq(), nullptr); has_frequently_polled_cqs = true; - } - + } + if (has_callback_methods || callback_generic_service_ != nullptr) { auto* cq = server->CallbackCQ(); grpc_server_register_completion_queue(server->server_, cq->cq(), nullptr); } - // cqs_ contains the completion queue added by calling the ServerBuilder's - // AddCompletionQueue() API. Some of them may not be frequently polled (i.e by - // calling Next() or AsyncNext()) and hence are not safe to be used for - // listening to incoming channels. Such completion queues must be registered + // cqs_ contains the completion queue added by calling the ServerBuilder's + // AddCompletionQueue() API. Some of them may not be frequently polled (i.e by + // calling Next() or AsyncNext()) and hence are not safe to be used for + // listening to incoming channels. Such completion queues must be registered // as non-listening queues. In debug mode, these should have their server list // tracked since these are provided the user and must be Shutdown by the user // after the server is shutdown. for (const auto& cq : cqs_) { grpc_server_register_completion_queue(server->server_, cq->cq(), nullptr); cq->RegisterServer(server.get()); - } - + } + if (!has_frequently_polled_cqs) { - gpr_log(GPR_ERROR, - "At least one of the completion queues must be frequently polled"); - return nullptr; - } - + gpr_log(GPR_ERROR, + "At least one of the completion queues must be frequently polled"); + return nullptr; + } + for (const auto& value : services_) { if (!server->RegisterService(value->host.get(), value->service)) { - return nullptr; - } - } - + return nullptr; + } + } + for (const auto& value : plugins_) { value->InitServer(initializer); - } - - if (generic_service_) { - server->RegisterAsyncGenericService(generic_service_); + } + + if (generic_service_) { + server->RegisterAsyncGenericService(generic_service_); } else if (callback_generic_service_) { server->RegisterCallbackGenericService(callback_generic_service_); - } else { + } else { for (const auto& value : services_) { if (value->service->has_generic_methods()) { - gpr_log(GPR_ERROR, - "Some methods were marked generic but there is no " - "generic service registered."); - return nullptr; - } - } - } - + gpr_log(GPR_ERROR, + "Some methods were marked generic but there is no " + "generic service registered."); + return nullptr; + } + } + } + for (auto& port : ports_) { int r = server->AddListeningPort(port.addr, port.creds.get()); if (!r) { @@ -402,25 +402,25 @@ std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() { } if (port.selected_port != nullptr) { *port.selected_port = r; - } - } - - auto cqs_data = cqs_.empty() ? nullptr : &cqs_[0]; + } + } + + auto cqs_data = cqs_.empty() ? nullptr : &cqs_[0]; server->Start(cqs_data, cqs_.size()); - + for (const auto& value : plugins_) { value->Finish(initializer); - } - - return server; -} - -void ServerBuilder::InternalAddPluginFactory( + } + + return server; +} + +void ServerBuilder::InternalAddPluginFactory( std::unique_ptr<ServerBuilderPlugin> (*CreatePlugin)()) { - gpr_once_init(&once_init_plugin_list, do_plugin_list_init); - (*g_plugin_factory_list).push_back(CreatePlugin); -} - + gpr_once_init(&once_init_plugin_list, do_plugin_list_init); + (*g_plugin_factory_list).push_back(CreatePlugin); +} + ServerBuilder& ServerBuilder::EnableWorkaround(grpc_workaround_list id) { switch (id) { case GRPC_WORKAROUND_ID_CRONET_COMPRESSION: diff --git a/contrib/libs/grpc/src/cpp/server/server_cc.cc b/contrib/libs/grpc/src/cpp/server/server_cc.cc index c2a911c7f7..fbd12437e4 100644 --- a/contrib/libs/grpc/src/cpp/server/server_cc.cc +++ b/contrib/libs/grpc/src/cpp/server/server_cc.cc @@ -1,31 +1,31 @@ -/* +/* * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/server.h> - + #include <cstdlib> -#include <sstream> +#include <sstream> #include <type_traits> -#include <utility> - -#include <grpc/grpc.h> +#include <utility> + +#include <grpc/grpc.h> #include <grpc/impl/codegen/grpc_types.h> -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> #include <grpcpp/completion_queue.h> #include <grpcpp/generic/async_generic_service.h> #include <grpcpp/impl/codegen/async_unary_call.h> @@ -41,23 +41,23 @@ #include <grpcpp/security/server_credentials.h> #include <grpcpp/server_context.h> #include <grpcpp/support/time.h> - + #include "src/core/ext/transport/inproc/inproc_transport.h" #include "src/core/lib/iomgr/exec_ctx.h" -#include "src/core/lib/profiling/timers.h" +#include "src/core/lib/profiling/timers.h" #include "src/core/lib/surface/call.h" #include "src/core/lib/surface/completion_queue.h" #include "src/core/lib/surface/server.h" #include "src/cpp/client/create_channel_internal.h" #include "src/cpp/server/external_connection_acceptor_impl.h" #include "src/cpp/server/health/default_health_check_service.h" -#include "src/cpp/thread_manager/thread_manager.h" - +#include "src/cpp/thread_manager/thread_manager.h" + #include <util/stream/str.h> -namespace grpc { +namespace grpc { namespace { - + // The default value for maximum number of threads that can be created in the // sync server. This value of INT_MAX is chosen to match the default behavior if // no ResourceQuota is set. To modify the max number of threads in a sync @@ -65,22 +65,22 @@ namespace { // max-threads set) to the server builder. #define DEFAULT_MAX_SYNC_SERVER_THREADS INT_MAX -class DefaultGlobalCallbacks final : public Server::GlobalCallbacks { - public: - ~DefaultGlobalCallbacks() override {} +class DefaultGlobalCallbacks final : public Server::GlobalCallbacks { + public: + ~DefaultGlobalCallbacks() override {} void PreSynchronousRequest(ServerContext* /*context*/) override {} void PostSynchronousRequest(ServerContext* /*context*/) override {} -}; - +}; + std::shared_ptr<Server::GlobalCallbacks> g_callbacks = nullptr; gpr_once g_once_init_callbacks = GPR_ONCE_INIT; - + void InitGlobalCallbacks() { - if (!g_callbacks) { - g_callbacks.reset(new DefaultGlobalCallbacks()); - } -} - + if (!g_callbacks) { + g_callbacks.reset(new DefaultGlobalCallbacks()); + } +} + class ShutdownTag : public internal::CompletionQueueTag { public: bool FinalizeResult(void** /*tag*/, bool* /*status*/) { return false; } @@ -92,13 +92,13 @@ class DummyTag : public internal::CompletionQueueTag { }; class UnimplementedAsyncRequestContext { - protected: - UnimplementedAsyncRequestContext() : generic_stream_(&server_context_) {} - - GenericServerContext server_context_; - GenericServerAsyncReaderWriter generic_stream_; -}; - + protected: + UnimplementedAsyncRequestContext() : generic_stream_(&server_context_) {} + + GenericServerContext server_context_; + GenericServerAsyncReaderWriter generic_stream_; +}; + // TODO(vjpai): Just for this file, use some contents of the experimental // namespace here to make the code easier to read below. Remove this when // de-experimentalized fully. @@ -289,32 +289,32 @@ class ShutdownCallback : public grpc_experimental_completion_queue_functor { /// of construction, since the public base class should be constructed after the /// elements belonging to the private base class are constructed. This is not /// possible using true composition. -class Server::UnimplementedAsyncRequest final +class Server::UnimplementedAsyncRequest final : private grpc::UnimplementedAsyncRequestContext, - public GenericAsyncRequest { - public: + public GenericAsyncRequest { + public: UnimplementedAsyncRequest(ServerInterface* server, grpc::ServerCompletionQueue* cq) - : GenericAsyncRequest(server, &server_context_, &generic_stream_, cq, cq, + : GenericAsyncRequest(server, &server_context_, &generic_stream_, cq, cq, nullptr, false) {} - - bool FinalizeResult(void** tag, bool* status) override; - + + bool FinalizeResult(void** tag, bool* status) override; + grpc::ServerContext* context() { return &server_context_; } grpc::GenericServerAsyncReaderWriter* stream() { return &generic_stream_; } -}; - +}; + /// UnimplementedAsyncResponse should not post user-visible completions to the /// C++ completion queue, but is generated as a CQ event by the core -class Server::UnimplementedAsyncResponse final +class Server::UnimplementedAsyncResponse final : public grpc::internal::CallOpSet< grpc::internal::CallOpSendInitialMetadata, grpc::internal::CallOpServerSendStatus> { - public: - UnimplementedAsyncResponse(UnimplementedAsyncRequest* request); - ~UnimplementedAsyncResponse() { delete request_; } - - bool FinalizeResult(void** tag, bool* status) override { + public: + UnimplementedAsyncResponse(UnimplementedAsyncRequest* request); + ~UnimplementedAsyncResponse() { delete request_; } + + bool FinalizeResult(void** tag, bool* status) override { if (grpc::internal::CallOpSet< grpc::internal::CallOpSendInitialMetadata, grpc::internal::CallOpServerSendStatus>::FinalizeResult(tag, @@ -324,44 +324,44 @@ class Server::UnimplementedAsyncResponse final // The tag was swallowed due to interception. We will see it again. } return false; - } - - private: - UnimplementedAsyncRequest* const request_; -}; - + } + + private: + UnimplementedAsyncRequest* const request_; +}; + class Server::SyncRequest final : public grpc::internal::CompletionQueueTag { - public: + public: SyncRequest(grpc::internal::RpcServiceMethod* method, void* method_tag) - : method_(method), + : method_(method), method_tag_(method_tag), - in_flight_(false), + in_flight_(false), has_request_payload_(method->method_type() == grpc::internal::RpcMethod::NORMAL_RPC || method->method_type() == grpc::internal::RpcMethod::SERVER_STREAMING), - call_details_(nullptr), - cq_(nullptr) { - grpc_metadata_array_init(&request_metadata_); - } - - ~SyncRequest() { - if (call_details_) { - delete call_details_; - } - grpc_metadata_array_destroy(&request_metadata_); - } - + call_details_(nullptr), + cq_(nullptr) { + grpc_metadata_array_init(&request_metadata_); + } + + ~SyncRequest() { + if (call_details_) { + delete call_details_; + } + grpc_metadata_array_destroy(&request_metadata_); + } + void SetupRequest() { cq_ = grpc_completion_queue_create_for_pluck(nullptr); } - - void TeardownRequest() { - grpc_completion_queue_destroy(cq_); - cq_ = nullptr; - } - - void Request(grpc_server* server, grpc_completion_queue* notify_cq) { - GPR_ASSERT(cq_ && !in_flight_); - in_flight_ = true; + + void TeardownRequest() { + grpc_completion_queue_destroy(cq_); + cq_ = nullptr; + } + + void Request(grpc_server* server, grpc_completion_queue* notify_cq) { + GPR_ASSERT(cq_ && !in_flight_); + in_flight_ = true; if (method_tag_) { if (grpc_server_request_registered_call( server, method_tag_, &call_, &deadline_, &request_metadata_, @@ -370,20 +370,20 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag { TeardownRequest(); return; } - } else { - if (!call_details_) { - call_details_ = new grpc_call_details; - grpc_call_details_init(call_details_); - } + } else { + if (!call_details_) { + call_details_ = new grpc_call_details; + grpc_call_details_init(call_details_); + } if (grpc_server_request_call(server, &call_, call_details_, &request_metadata_, cq_, notify_cq, this) != GRPC_CALL_OK) { TeardownRequest(); return; } - } - } - + } + } + void PostShutdownCleanup() { if (call_) { grpc_call_unref(call_); @@ -396,27 +396,27 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag { } bool FinalizeResult(void** /*tag*/, bool* status) override { - if (!*status) { - grpc_completion_queue_destroy(cq_); + if (!*status) { + grpc_completion_queue_destroy(cq_); cq_ = nullptr; - } - if (call_details_) { - deadline_ = call_details_->deadline; - grpc_call_details_destroy(call_details_); - grpc_call_details_init(call_details_); - } - return true; - } - + } + if (call_details_) { + deadline_ = call_details_->deadline; + grpc_call_details_destroy(call_details_); + grpc_call_details_init(call_details_); + } + return true; + } + // The CallData class represents a call that is "active" as opposed // to just being requested. It wraps and takes ownership of the cq from // the call request - class CallData final { - public: - explicit CallData(Server* server, SyncRequest* mrd) - : cq_(mrd->cq_), + class CallData final { + public: + explicit CallData(Server* server, SyncRequest* mrd) + : cq_(mrd->cq_), ctx_(mrd->deadline_, &mrd->request_metadata_), - has_request_payload_(mrd->has_request_payload_), + has_request_payload_(mrd->has_request_payload_), request_payload_(has_request_payload_ ? mrd->request_payload_ : nullptr), request_(nullptr), @@ -428,19 +428,19 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag { server_(server), global_callbacks_(nullptr), resources_(false) { - ctx_.set_call(mrd->call_); - ctx_.cq_ = &cq_; - GPR_ASSERT(mrd->in_flight_); - mrd->in_flight_ = false; - mrd->request_metadata_.count = 0; - } - - ~CallData() { - if (has_request_payload_ && request_payload_) { - grpc_byte_buffer_destroy(request_payload_); - } - } - + ctx_.set_call(mrd->call_); + ctx_.cq_ = &cq_; + GPR_ASSERT(mrd->in_flight_); + mrd->in_flight_ = false; + mrd->request_metadata_.count = 0; + } + + ~CallData() { + if (has_request_payload_ && request_payload_) { + grpc_byte_buffer_destroy(request_payload_); + } + } + void Run(const std::shared_ptr<GlobalCallbacks>& global_callbacks, bool resources) { global_callbacks_ = global_callbacks; @@ -474,8 +474,8 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag { // There were interceptors to be run, so ContinueRunAfterInterception // will be run when interceptors are done. } - } - + } + void ContinueRunAfterInterception() { { ctx_.BeginCompletionOp(&call_, nullptr, nullptr); @@ -499,11 +499,11 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag { delete this; } - private: + private: grpc::CompletionQueue cq_; grpc::ServerContext ctx_; - const bool has_request_payload_; - grpc_byte_buffer* request_payload_; + const bool has_request_payload_; + grpc_byte_buffer* request_payload_; void* request_; grpc::Status request_status_; grpc::internal::RpcServiceMethod* const method_; @@ -512,21 +512,21 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag { std::shared_ptr<GlobalCallbacks> global_callbacks_; bool resources_; grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_; - }; - - private: + }; + + private: grpc::internal::RpcServiceMethod* const method_; void* const method_tag_; - bool in_flight_; - const bool has_request_payload_; - grpc_call* call_; - grpc_call_details* call_details_; - gpr_timespec deadline_; - grpc_metadata_array request_metadata_; - grpc_byte_buffer* request_payload_; - grpc_completion_queue* cq_; -}; - + bool in_flight_; + const bool has_request_payload_; + grpc_call* call_; + grpc_call_details* call_details_; + gpr_timespec deadline_; + grpc_metadata_array request_metadata_; + grpc_byte_buffer* request_payload_; + grpc_completion_queue* cq_; +}; + template <class ServerContextType> class Server::CallbackRequest final : public grpc::internal::CompletionQueueTag { @@ -743,52 +743,52 @@ const char* Server::CallbackRequest< return ctx_.method().c_str(); } -// Implementation of ThreadManager. Each instance of SyncRequestThreadManager -// manages a pool of threads that poll for incoming Sync RPCs and call the -// appropriate RPC handlers +// Implementation of ThreadManager. Each instance of SyncRequestThreadManager +// manages a pool of threads that poll for incoming Sync RPCs and call the +// appropriate RPC handlers class Server::SyncRequestThreadManager : public grpc::ThreadManager { - public: + public: SyncRequestThreadManager(Server* server, grpc::CompletionQueue* server_cq, - std::shared_ptr<GlobalCallbacks> global_callbacks, + std::shared_ptr<GlobalCallbacks> global_callbacks, grpc_resource_quota* rq, int min_pollers, int max_pollers, int cq_timeout_msec) : ThreadManager("SyncServer", rq, min_pollers, max_pollers), - server_(server), - server_cq_(server_cq), - cq_timeout_msec_(cq_timeout_msec), + server_(server), + server_cq_(server_cq), + cq_timeout_msec_(cq_timeout_msec), global_callbacks_(std::move(global_callbacks)) {} - - WorkStatus PollForWork(void** tag, bool* ok) override { - *tag = nullptr; + + WorkStatus PollForWork(void** tag, bool* ok) override { + *tag = nullptr; // TODO(ctiller): workaround for GPR_TIMESPAN based deadlines not working // right now - gpr_timespec deadline = + gpr_timespec deadline = gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC), gpr_time_from_millis(cq_timeout_msec_, GPR_TIMESPAN)); - - switch (server_cq_->AsyncNext(tag, ok, deadline)) { + + switch (server_cq_->AsyncNext(tag, ok, deadline)) { case grpc::CompletionQueue::TIMEOUT: - return TIMEOUT; + return TIMEOUT; case grpc::CompletionQueue::SHUTDOWN: - return SHUTDOWN; + return SHUTDOWN; case grpc::CompletionQueue::GOT_EVENT: - return WORK_FOUND; - } - - GPR_UNREACHABLE_CODE(return TIMEOUT); - } - + return WORK_FOUND; + } + + GPR_UNREACHABLE_CODE(return TIMEOUT); + } + void DoWork(void* tag, bool ok, bool resources) override { - SyncRequest* sync_req = static_cast<SyncRequest*>(tag); - - if (!sync_req) { - // No tag. Nothing to work on. This is an unlikley scenario and possibly a - // bug in RPC Manager implementation. - gpr_log(GPR_ERROR, "Sync server. DoWork() was called with NULL tag"); - return; - } - - if (ok) { + SyncRequest* sync_req = static_cast<SyncRequest*>(tag); + + if (!sync_req) { + // No tag. Nothing to work on. This is an unlikley scenario and possibly a + // bug in RPC Manager implementation. + gpr_log(GPR_ERROR, "Sync server. DoWork() was called with NULL tag"); + return; + } + + if (ok) { // Calldata takes ownership of the completion queue and interceptors // inside sync_req auto* cd = new SyncRequest::CallData(server_, sync_req); @@ -796,41 +796,41 @@ class Server::SyncRequestThreadManager : public grpc::ThreadManager { if (!IsShutdown()) { sync_req->SetupRequest(); // Create new completion queue for sync_req sync_req->Request(server_->c_server(), server_cq_->cq()); - } - - GPR_TIMER_SCOPE("cd.Run()", 0); + } + + GPR_TIMER_SCOPE("cd.Run()", 0); cd->Run(global_callbacks_, resources); - } - // TODO (sreek) If ok is false here (which it isn't in case of - // grpc_request_registered_call), we should still re-queue the request - // object - } - + } + // TODO (sreek) If ok is false here (which it isn't in case of + // grpc_request_registered_call), we should still re-queue the request + // object + } + void AddSyncMethod(grpc::internal::RpcServiceMethod* method, void* tag) { - sync_requests_.emplace_back(new SyncRequest(method, tag)); - } - - void AddUnknownSyncMethod() { - if (!sync_requests_.empty()) { + sync_requests_.emplace_back(new SyncRequest(method, tag)); + } + + void AddUnknownSyncMethod() { + if (!sync_requests_.empty()) { unknown_method_.reset(new grpc::internal::RpcServiceMethod( "unknown", grpc::internal::RpcMethod::BIDI_STREAMING, new grpc::internal::UnknownMethodHandler)); - sync_requests_.emplace_back( - new SyncRequest(unknown_method_.get(), nullptr)); - } - } - + sync_requests_.emplace_back( + new SyncRequest(unknown_method_.get(), nullptr)); + } + } + void Shutdown() override { ThreadManager::Shutdown(); - server_cq_->Shutdown(); + server_cq_->Shutdown(); } - + void Wait() override { ThreadManager::Wait(); - // Drain any pending items from the queue - void* tag; - bool ok; - while (server_cq_->Next(&tag, &ok)) { + // Drain any pending items from the queue + void* tag; + bool ok; + while (server_cq_->Next(&tag, &ok)) { if (ok) { // If a request was pulled off the queue, it means that the thread // handling the request added it to the completion queue after shutdown @@ -842,34 +842,34 @@ class Server::SyncRequestThreadManager : public grpc::ThreadManager { SyncRequest* sync_req = static_cast<SyncRequest*>(tag); sync_req->PostShutdownCleanup(); } - } - } - - void Start() { - if (!sync_requests_.empty()) { + } + } + + void Start() { + if (!sync_requests_.empty()) { for (const auto& value : sync_requests_) { value->SetupRequest(); value->Request(server_->c_server(), server_cq_->cq()); - } - - Initialize(); // ThreadManager's Initialize() - } - } - - private: - Server* server_; + } + + Initialize(); // ThreadManager's Initialize() + } + } + + private: + Server* server_; grpc::CompletionQueue* server_cq_; - int cq_timeout_msec_; - std::vector<std::unique_ptr<SyncRequest>> sync_requests_; + int cq_timeout_msec_; + std::vector<std::unique_ptr<SyncRequest>> sync_requests_; std::unique_ptr<grpc::internal::RpcServiceMethod> unknown_method_; - std::shared_ptr<Server::GlobalCallbacks> global_callbacks_; -}; - + std::shared_ptr<Server::GlobalCallbacks> global_callbacks_; +}; + static grpc::internal::GrpcLibraryInitializer g_gli_initializer; -Server::Server( +Server::Server( grpc::ChannelArguments* args, std::shared_ptr<std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>> - sync_server_cqs, + sync_server_cqs, int min_pollers, int max_pollers, int sync_cq_timeout_msec, std::vector<std::shared_ptr<grpc::internal::ExternalConnectionAcceptorImpl>> acceptors, @@ -881,17 +881,17 @@ Server::Server( interceptor_creators_(std::move(interceptor_creators)), max_receive_message_size_(INT_MIN), sync_server_cqs_(std::move(sync_server_cqs)), - started_(false), - shutdown_(false), - shutdown_notified_(false), - server_(nullptr), + started_(false), + shutdown_(false), + shutdown_notified_(false), + server_(nullptr), server_initializer_(new ServerInitializer(this)), health_check_service_disabled_(false) { - g_gli_initializer.summon(); + g_gli_initializer.summon(); gpr_once_init(&grpc::g_once_init_callbacks, grpc::InitGlobalCallbacks); global_callbacks_ = grpc::g_callbacks; - global_callbacks_->UpdateArguments(args); - + global_callbacks_->UpdateArguments(args); + if (sync_server_cqs_ != nullptr) { bool default_rq_created = false; if (server_rq == nullptr) { @@ -910,15 +910,15 @@ Server::Server( if (default_rq_created) { grpc_resource_quota_unref(server_rq); } - } - + } + for (auto& acceptor : acceptors_) { acceptor->SetToChannelArgs(args); } - grpc_channel_args channel_args; - args->SetChannelArgs(&channel_args); - + grpc_channel_args channel_args; + args->SetChannelArgs(&channel_args); + for (size_t i = 0; i < channel_args.num_args; i++) { if (0 == strcmp(channel_args.args[i].key, grpc::kHealthCheckServiceInterfaceArg)) { @@ -935,41 +935,41 @@ Server::Server( max_receive_message_size_ = channel_args.args[i].value.integer; } } - server_ = grpc_server_create(&channel_args, nullptr); -} - -Server::~Server() { - { + server_ = grpc_server_create(&channel_args, nullptr); +} + +Server::~Server() { + { grpc::internal::ReleasableMutexLock lock(&mu_); - if (started_ && !shutdown_) { + if (started_ && !shutdown_) { lock.Unlock(); - Shutdown(); - } else if (!started_) { - // Shutdown the completion queues + Shutdown(); + } else if (!started_) { + // Shutdown the completion queues for (const auto& value : sync_req_mgrs_) { value->Shutdown(); - } + } if (callback_cq_ != nullptr) { callback_cq_->Shutdown(); callback_cq_ = nullptr; } - } - } + } + } // Destroy health check service before we destroy the C server so that // it does not call grpc_server_request_registered_call() after the C // server has been destroyed. health_check_service_.reset(); - grpc_server_destroy(server_); -} - -void Server::SetGlobalCallbacks(GlobalCallbacks* callbacks) { + grpc_server_destroy(server_); +} + +void Server::SetGlobalCallbacks(GlobalCallbacks* callbacks) { GPR_ASSERT(!grpc::g_callbacks); - GPR_ASSERT(callbacks); + GPR_ASSERT(callbacks); grpc::g_callbacks.reset(callbacks); -} - -grpc_server* Server::c_server() { return server_; } - +} + +grpc_server* Server::c_server() { return server_; } + std::shared_ptr<grpc::Channel> Server::InProcessChannel( const grpc::ChannelArguments& args) { grpc_channel_args channel_args = args.c_channel_args(); @@ -992,50 +992,50 @@ Server::experimental_type::InProcessChannelWithInterceptors( std::move(interceptor_creators)); } -static grpc_server_register_method_payload_handling PayloadHandlingForMethod( +static grpc_server_register_method_payload_handling PayloadHandlingForMethod( grpc::internal::RpcServiceMethod* method) { - switch (method->method_type()) { + switch (method->method_type()) { case grpc::internal::RpcMethod::NORMAL_RPC: case grpc::internal::RpcMethod::SERVER_STREAMING: - return GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER; + return GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER; case grpc::internal::RpcMethod::CLIENT_STREAMING: case grpc::internal::RpcMethod::BIDI_STREAMING: - return GRPC_SRM_PAYLOAD_NONE; - } - GPR_UNREACHABLE_CODE(return GRPC_SRM_PAYLOAD_NONE;); -} - + return GRPC_SRM_PAYLOAD_NONE; + } + GPR_UNREACHABLE_CODE(return GRPC_SRM_PAYLOAD_NONE;); +} + bool Server::RegisterService(const TString* host, grpc::Service* service) { - bool has_async_methods = service->has_async_methods(); - if (has_async_methods) { - GPR_ASSERT(service->server_ == nullptr && - "Can only register an asynchronous service against one server."); - service->server_ = this; - } - - const char* method_name = nullptr; + bool has_async_methods = service->has_async_methods(); + if (has_async_methods) { + GPR_ASSERT(service->server_ == nullptr && + "Can only register an asynchronous service against one server."); + service->server_ = this; + } + + const char* method_name = nullptr; for (const auto& method : service->methods_) { if (method.get() == nullptr) { // Handled by generic service if any. - continue; - } - + continue; + } + void* method_registration_tag = grpc_server_register_method( - server_, method->name(), host ? host->c_str() : nullptr, + server_, method->name(), host ? host->c_str() : nullptr, PayloadHandlingForMethod(method.get()), 0); if (method_registration_tag == nullptr) { - gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", - method->name()); - return false; - } - + gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", + method->name()); + return false; + } + if (method->handler() == nullptr) { // Async method without handler method->set_server_tag(method_registration_tag); } else if (method->api_type() == grpc::internal::RpcServiceMethod::ApiType::SYNC) { for (const auto& value : sync_req_mgrs_) { value->AddSyncMethod(method.get(), method_registration_tag); - } + } } else { has_callback_methods_ = true; grpc::internal::RpcServiceMethod* method_value = method.get(); @@ -1047,30 +1047,30 @@ bool Server::RegisterService(const TString* host, grpc::Service* service) { cq, &result); return result; }); - } - - method_name = method->name(); - } - - // Parse service name. - if (method_name != nullptr) { - std::stringstream ss(method_name); + } + + method_name = method->name(); + } + + // Parse service name. + if (method_name != nullptr) { + std::stringstream ss(method_name); std::string service_name; - if (std::getline(ss, service_name, '/') && - std::getline(ss, service_name, '/')) { + if (std::getline(ss, service_name, '/') && + std::getline(ss, service_name, '/')) { services_.push_back(service_name.c_str()); - } - } - return true; -} - + } + } + return true; +} + void Server::RegisterAsyncGenericService(grpc::AsyncGenericService* service) { - GPR_ASSERT(service->server_ == nullptr && - "Can only register an async generic service against one server."); - service->server_ = this; + GPR_ASSERT(service->server_ == nullptr && + "Can only register an async generic service against one server."); + service->server_ = this; has_async_generic_service_ = true; -} - +} + void Server::RegisterCallbackGenericService( grpc::CallbackGenericService* service) { GPR_ASSERT( @@ -1090,12 +1090,12 @@ void Server::RegisterCallbackGenericService( int Server::AddListeningPort(const TString& addr, grpc::ServerCredentials* creds) { - GPR_ASSERT(!started_); + GPR_ASSERT(!started_); int port = creds->AddPortToServer(addr, server_); global_callbacks_->AddPort(this, addr, creds, port); return port; -} - +} + void Server::Ref() { shutdown_refs_outstanding_.fetch_add(1, std::memory_order_relaxed); } @@ -1122,9 +1122,9 @@ void Server::UnrefAndWaitLocked() { } void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) { - GPR_ASSERT(!started_); + GPR_ASSERT(!started_); global_callbacks_->PreServerStart(this); - started_ = true; + started_ = true; // Only create default health check service when user did not provide an // explicit one. @@ -1167,23 +1167,23 @@ void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) { } #endif - grpc_server_start(server_); - + grpc_server_start(server_); + if (!has_async_generic_service_ && !has_callback_generic_service_) { for (const auto& value : sync_req_mgrs_) { value->AddUnknownSyncMethod(); - } - - for (size_t i = 0; i < num_cqs; i++) { - if (cqs[i]->IsFrequentlyPolled()) { - new UnimplementedAsyncRequest(this, cqs[i]); - } - } + } + + for (size_t i = 0; i < num_cqs; i++) { + if (cqs[i]->IsFrequentlyPolled()) { + new UnimplementedAsyncRequest(this, cqs[i]); + } + } if (health_check_cq != nullptr) { new UnimplementedAsyncRequest(this, health_check_cq); } - } - + } + // If this server has any support for synchronous methods (has any sync // server CQs), make sure that we have a ResourceExhausted handler // to deal with the case of thread exhaustion @@ -1194,7 +1194,7 @@ void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) { for (const auto& value : sync_req_mgrs_) { value->Start(); - } + } if (default_health_check_service_impl != nullptr) { default_health_check_service_impl->StartServingThread(); @@ -1203,16 +1203,16 @@ void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) { for (auto& acceptor : acceptors_) { acceptor->Start(); } -} - -void Server::ShutdownInternal(gpr_timespec deadline) { +} + +void Server::ShutdownInternal(gpr_timespec deadline) { grpc::internal::MutexLock lock(&mu_); if (shutdown_) { return; } - + shutdown_ = true; - + for (auto& acceptor : acceptors_) { acceptor->Shutdown(); } @@ -1221,14 +1221,14 @@ void Server::ShutdownInternal(gpr_timespec deadline) { grpc::CompletionQueue shutdown_cq; grpc::ShutdownTag shutdown_tag; // Dummy shutdown tag grpc_server_shutdown_and_notify(server_, shutdown_cq.cq(), &shutdown_tag); - + shutdown_cq.Shutdown(); - + void* tag; bool ok; grpc::CompletionQueue::NextStatus status = shutdown_cq.AsyncNext(&tag, &ok, deadline); - + // If this timed out, it means we are done with the grace period for a clean // shutdown. We should force a shutdown now by cancelling all inflight calls if (status == grpc::CompletionQueue::NextStatus::TIMEOUT) { @@ -1236,18 +1236,18 @@ void Server::ShutdownInternal(gpr_timespec deadline) { } // Else in case of SHUTDOWN or GOT_EVENT, it means that the server has // successfully shutdown - + // Shutdown all ThreadManagers. This will try to gracefully stop all the // threads in the ThreadManagers (once they process any inflight requests) for (const auto& value : sync_req_mgrs_) { value->Shutdown(); // ThreadManager's Shutdown() } - + // Wait for threads in all ThreadManagers to terminate for (const auto& value : sync_req_mgrs_) { value->Wait(); } - + // Drop the shutdown ref and wait for all other refs to drop as well. UnrefAndWaitLocked(); @@ -1275,22 +1275,22 @@ void Server::ShutdownInternal(gpr_timespec deadline) { } cq_list_.clear(); #endif -} - -void Server::Wait() { +} + +void Server::Wait() { grpc::internal::MutexLock lock(&mu_); - while (started_ && !shutdown_notified_) { + while (started_ && !shutdown_notified_) { shutdown_cv_.Wait(&mu_); - } -} - + } +} + void Server::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops, grpc::internal::Call* call) { ops->FillOps(call); -} - -bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag, - bool* status) { +} + +bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag, + bool* status) { if (GenericAsyncRequest::FinalizeResult(tag, status)) { // We either had no interceptors run or we are done intercepting if (*status) { @@ -1301,24 +1301,24 @@ bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag, } else { delete this; } - } else { + } else { // The tag was swallowed due to interception. We will see it again. - } - return false; -} - -Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse( - UnimplementedAsyncRequest* request) - : request_(request) { + } + return false; +} + +Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse( + UnimplementedAsyncRequest* request) + : request_(request) { grpc::Status status(grpc::StatusCode::UNIMPLEMENTED, ""); grpc::internal::UnknownMethodHandler::FillOps(request_->context(), this); - request_->stream()->call_.PerformOps(this); -} - + request_->stream()->call_.PerformOps(this); +} + grpc::ServerInitializer* Server::initializer() { return server_initializer_.get(); } - + grpc::CompletionQueue* Server::CallbackCQ() { // TODO(vjpai): Consider using a single global CQ for the default CQ // if there is no explicit per-server CQ registered diff --git a/contrib/libs/grpc/src/cpp/server/server_context.cc b/contrib/libs/grpc/src/cpp/server/server_context.cc index 458ac20d87..60ba0f46b3 100644 --- a/contrib/libs/grpc/src/cpp/server/server_context.cc +++ b/contrib/libs/grpc/src/cpp/server/server_context.cc @@ -1,61 +1,61 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/impl/codegen/server_context.h> - + #include <algorithm> #include <utility> - -#include <grpc/compression.h> -#include <grpc/grpc.h> + +#include <grpc/compression.h> +#include <grpc/grpc.h> #include <grpc/load_reporting.h> -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> #include <grpcpp/impl/call.h> #include <grpcpp/impl/codegen/completion_queue.h> #include <grpcpp/support/server_callback.h> #include <grpcpp/support/time.h> - + #include "src/core/lib/gprpp/ref_counted.h" #include "src/core/lib/gprpp/sync.h" -#include "src/core/lib/surface/call.h" - +#include "src/core/lib/surface/call.h" + namespace grpc { - -// CompletionOp - + +// CompletionOp + class ServerContextBase::CompletionOp final : public internal::CallOpSetInterface { - public: - // initial refs: one in the server context, one in the cq + public: + // initial refs: one in the server context, one in the cq // must ref the call before calling constructor and after deleting this CompletionOp(internal::Call* call, ::grpc::internal::ServerCallbackCall* callback_controller) : call_(*call), callback_controller_(callback_controller), has_tag_(false), - tag_(nullptr), + tag_(nullptr), core_cq_tag_(this), - refs_(2), - finalized_(false), + refs_(2), + finalized_(false), cancelled_(0), done_intercepting_(false) {} - + // CompletionOp isn't copyable or movable CompletionOp(const CompletionOp&) = delete; CompletionOp& operator=(const CompletionOp&) = delete; @@ -87,25 +87,25 @@ class ServerContextBase::CompletionOp final // there are no tests catching the compiler warning. static void operator delete(void*, void*) { assert(0); } - bool FinalizeResult(void** tag, bool* status) override; - - bool CheckCancelled(CompletionQueue* cq) { - cq->TryPluck(this); - return CheckCancelledNoPluck(); - } - bool CheckCancelledAsync() { return CheckCancelledNoPluck(); } - - void set_tag(void* tag) { - has_tag_ = true; - tag_ = tag; - } - + bool FinalizeResult(void** tag, bool* status) override; + + bool CheckCancelled(CompletionQueue* cq) { + cq->TryPluck(this); + return CheckCancelledNoPluck(); + } + bool CheckCancelledAsync() { return CheckCancelledNoPluck(); } + + void set_tag(void* tag) { + has_tag_ = true; + tag_ = tag; + } + void set_core_cq_tag(void* core_cq_tag) { core_cq_tag_ = core_cq_tag; } void* core_cq_tag() override { return core_cq_tag_; } - void Unref(); - + void Unref(); + // This will be called while interceptors are run if the RPC is a hijacked // RPC. This should set hijacking state for each of the ops. void SetHijackingState() override { @@ -130,33 +130,33 @@ class ServerContextBase::CompletionOp final nullptr) == GRPC_CALL_OK); } - private: - bool CheckCancelledNoPluck() { + private: + bool CheckCancelledNoPluck() { grpc_core::MutexLock lock(&mu_); - return finalized_ ? (cancelled_ != 0) : false; - } - + return finalized_ ? (cancelled_ != 0) : false; + } + internal::Call call_; ::grpc::internal::ServerCallbackCall* const callback_controller_; - bool has_tag_; - void* tag_; + bool has_tag_; + void* tag_; void* core_cq_tag_; grpc_core::RefCount refs_; grpc_core::Mutex mu_; - bool finalized_; + bool finalized_; int cancelled_; // This is an int (not bool) because it is passed to core bool done_intercepting_; internal::InterceptorBatchMethodsImpl interceptor_methods_; -}; - +}; + void ServerContextBase::CompletionOp::Unref() { if (refs_.Unref()) { grpc_call* call = call_.call(); - delete this; + delete this; grpc_call_unref(call); - } -} - + } +} + void ServerContextBase::CompletionOp::FillOps(internal::Call* call) { grpc_op ops; ops.op = GRPC_OP_RECV_CLOSE_ON_SERVER; @@ -171,8 +171,8 @@ void ServerContextBase::CompletionOp::FillOps(internal::Call* call) { GPR_ASSERT(grpc_call_start_batch(call->call(), &ops, 1, core_cq_tag_, nullptr) == GRPC_CALL_OK); /* No interceptors to run here */ -} - +} + bool ServerContextBase::CompletionOp::FinalizeResult(void** tag, bool* status) { // Decide whether to call the cancel callback within the lock bool call_cancel; @@ -199,11 +199,11 @@ bool ServerContextBase::CompletionOp::FinalizeResult(void** tag, bool* status) { call_cancel = (cancelled_ != 0); // Release the lock since we may call a callback and interceptors. - } + } if (call_cancel && callback_controller_ != nullptr) { callback_controller_->MaybeCallOnCancel(); - } + } /* Add interception point and run through interceptors */ interceptor_methods_.AddInterceptionHookPoint( experimental::InterceptionHookPoints::POST_RECV_CLOSE); @@ -218,19 +218,19 @@ bool ServerContextBase::CompletionOp::FinalizeResult(void** tag, bool* status) { } // There are interceptors to be run. Return false for now. return false; -} - +} + // ServerContextBase body - + ServerContextBase::ServerContextBase() : deadline_(gpr_inf_future(GPR_CLOCK_REALTIME)) {} - + ServerContextBase::ServerContextBase(gpr_timespec deadline, grpc_metadata_array* arr) : deadline_(deadline) { std::swap(*client_metadata_.arr(), *arr); -} - +} + void ServerContextBase::BindDeadlineAndMetadata(gpr_timespec deadline, grpc_metadata_array* arr) { deadline_ = deadline; @@ -238,17 +238,17 @@ void ServerContextBase::BindDeadlineAndMetadata(gpr_timespec deadline, } ServerContextBase::~ServerContextBase() { - if (completion_op_) { - completion_op_->Unref(); - } + if (completion_op_) { + completion_op_->Unref(); + } if (rpc_info_) { rpc_info_->Unref(); } if (default_reactor_used_.load(std::memory_order_relaxed)) { reinterpret_cast<Reactor*>(&default_reactor_)->~Reactor(); } -} - +} + ServerContextBase::CallWrapper::~CallWrapper() { if (call) { // If the ServerContext is part of the call's arena, this could free the @@ -260,7 +260,7 @@ ServerContextBase::CallWrapper::~CallWrapper() { void ServerContextBase::BeginCompletionOp( internal::Call* call, std::function<void(bool)> callback, ::grpc::internal::ServerCallbackCall* callback_controller) { - GPR_ASSERT(!completion_op_); + GPR_ASSERT(!completion_op_); if (rpc_info_) { rpc_info_->Ref(); } @@ -274,25 +274,25 @@ void ServerContextBase::BeginCompletionOp( completion_op_->set_core_cq_tag(&completion_tag_); completion_op_->set_tag(completion_op_); } else if (has_notify_when_done_tag_) { - completion_op_->set_tag(async_notify_when_done_tag_); - } - call->PerformOps(completion_op_); -} - + completion_op_->set_tag(async_notify_when_done_tag_); + } + call->PerformOps(completion_op_); +} + internal::CompletionQueueTag* ServerContextBase::GetCompletionOpTag() { return static_cast<internal::CompletionQueueTag*>(completion_op_); } void ServerContextBase::AddInitialMetadata(const TString& key, const TString& value) { - initial_metadata_.insert(std::make_pair(key, value)); -} - + initial_metadata_.insert(std::make_pair(key, value)); +} + void ServerContextBase::AddTrailingMetadata(const TString& key, const TString& value) { - trailing_metadata_.insert(std::make_pair(key, value)); -} - + trailing_metadata_.insert(std::make_pair(key, value)); +} + void ServerContextBase::TryCancel() const { internal::CancelInterceptorBatchMethods cancel_methods; if (rpc_info_) { @@ -303,53 +303,53 @@ void ServerContextBase::TryCancel() const { grpc_call_error err = grpc_call_cancel_with_status(call_.call, GRPC_STATUS_CANCELLED, "Cancelled on the server side", nullptr); - if (err != GRPC_CALL_OK) { - gpr_log(GPR_ERROR, "TryCancel failed with: %d", err); - } -} - + if (err != GRPC_CALL_OK) { + gpr_log(GPR_ERROR, "TryCancel failed with: %d", err); + } +} + bool ServerContextBase::IsCancelled() const { if (completion_tag_) { // When using callback API, this result is always valid. return completion_op_->CheckCancelledAsync(); } else if (has_notify_when_done_tag_) { // When using async API, the result is only valid - // if the tag has already been delivered at the completion queue - return completion_op_ && completion_op_->CheckCancelledAsync(); - } else { + // if the tag has already been delivered at the completion queue + return completion_op_ && completion_op_->CheckCancelledAsync(); + } else { // when using sync API, the result is always valid - return completion_op_ && completion_op_->CheckCancelled(cq_); - } -} - + return completion_op_ && completion_op_->CheckCancelled(cq_); + } +} + void ServerContextBase::set_compression_algorithm( - grpc_compression_algorithm algorithm) { + grpc_compression_algorithm algorithm) { compression_algorithm_ = algorithm; const char* algorithm_name = nullptr; - if (!grpc_compression_algorithm_name(algorithm, &algorithm_name)) { - gpr_log(GPR_ERROR, "Name for compression algorithm '%d' unknown.", - algorithm); - abort(); - } + if (!grpc_compression_algorithm_name(algorithm, &algorithm_name)) { + gpr_log(GPR_ERROR, "Name for compression algorithm '%d' unknown.", + algorithm); + abort(); + } GPR_ASSERT(algorithm_name != nullptr); - AddInitialMetadata(GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY, algorithm_name); -} - + AddInitialMetadata(GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY, algorithm_name); +} + TString ServerContextBase::peer() const { TString peer; if (call_.call) { char* c_peer = grpc_call_get_peer(call_.call); - peer = c_peer; - gpr_free(c_peer); - } - return peer; -} - + peer = c_peer; + gpr_free(c_peer); + } + return peer; +} + const struct census_context* ServerContextBase::census_context() const { return call_.call == nullptr ? nullptr : grpc_census_call_get_context(call_.call); -} - +} + void ServerContextBase::SetLoadReportingCosts( const std::vector<TString>& cost_data) { if (call_.call == nullptr) return; diff --git a/contrib/libs/grpc/src/cpp/server/server_credentials.cc b/contrib/libs/grpc/src/cpp/server/server_credentials.cc index c3b3a8b379..a0f7c48999 100644 --- a/contrib/libs/grpc/src/cpp/server/server_credentials.cc +++ b/contrib/libs/grpc/src/cpp/server/server_credentials.cc @@ -1,25 +1,25 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/security/server_credentials.h> - + namespace grpc { - -ServerCredentials::~ServerCredentials() {} - + +ServerCredentials::~ServerCredentials() {} + } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/server/server_posix.cc b/contrib/libs/grpc/src/cpp/server/server_posix.cc index c3d40d4fa2..99bc6a1606 100644 --- a/contrib/libs/grpc/src/cpp/server/server_posix.cc +++ b/contrib/libs/grpc/src/cpp/server/server_posix.cc @@ -1,33 +1,33 @@ -/* - * +/* + * * Copyright 2016 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/server_posix.h> - -#include <grpc/grpc_posix.h> - + +#include <grpc/grpc_posix.h> + namespace grpc { - -#ifdef GPR_SUPPORT_CHANNELS_FROM_FD - + +#ifdef GPR_SUPPORT_CHANNELS_FROM_FD + void AddInsecureChannelFromFd(grpc::Server* server, int fd) { grpc_server_add_insecure_channel_from_fd(server->c_server(), nullptr, fd); -} - -#endif // GPR_SUPPORT_CHANNELS_FROM_FD - +} + +#endif // GPR_SUPPORT_CHANNELS_FROM_FD + } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/server/thread_pool_interface.h b/contrib/libs/grpc/src/cpp/server/thread_pool_interface.h index 028842a776..4bc12345dd 100644 --- a/contrib/libs/grpc/src/cpp/server/thread_pool_interface.h +++ b/contrib/libs/grpc/src/cpp/server/thread_pool_interface.h @@ -1,43 +1,43 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#ifndef GRPC_INTERNAL_CPP_THREAD_POOL_INTERFACE_H -#define GRPC_INTERNAL_CPP_THREAD_POOL_INTERFACE_H - -#include <functional> - -namespace grpc { - -// A thread pool interface for running callbacks. -class ThreadPoolInterface { - public: - virtual ~ThreadPoolInterface() {} - - // Schedule the given callback for execution. - virtual void Add(const std::function<void()>& callback) = 0; -}; - + * + */ + +#ifndef GRPC_INTERNAL_CPP_THREAD_POOL_INTERFACE_H +#define GRPC_INTERNAL_CPP_THREAD_POOL_INTERFACE_H + +#include <functional> + +namespace grpc { + +// A thread pool interface for running callbacks. +class ThreadPoolInterface { + public: + virtual ~ThreadPoolInterface() {} + + // Schedule the given callback for execution. + virtual void Add(const std::function<void()>& callback) = 0; +}; + // Allows different codebases to use their own thread pool impls typedef ThreadPoolInterface* (*CreateThreadPoolFunc)(void); void SetCreateThreadPool(CreateThreadPoolFunc func); -ThreadPoolInterface* CreateDefaultThreadPool(); - -} // namespace grpc - -#endif // GRPC_INTERNAL_CPP_THREAD_POOL_INTERFACE_H +ThreadPoolInterface* CreateDefaultThreadPool(); + +} // namespace grpc + +#endif // GRPC_INTERNAL_CPP_THREAD_POOL_INTERFACE_H diff --git a/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.cc b/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.cc index c8560aa81d..29113e48f4 100644 --- a/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.cc +++ b/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.cc @@ -1,32 +1,32 @@ -/* - * +/* + * * Copyright 2016 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#include "src/cpp/thread_manager/thread_manager.h" - -#include <climits> - -#include <grpc/support/log.h> + * + */ + +#include "src/cpp/thread_manager/thread_manager.h" + +#include <climits> + +#include <grpc/support/log.h> #include "src/core/lib/gprpp/thd.h" #include "src/core/lib/iomgr/exec_ctx.h" -namespace grpc { - -ThreadManager::WorkerThread::WorkerThread(ThreadManager* thd_mgr) +namespace grpc { + +ThreadManager::WorkerThread::WorkerThread(ThreadManager* thd_mgr) : thd_mgr_(thd_mgr) { // Make thread creation exclusive with respect to its join happening in // ~WorkerThread(). @@ -38,92 +38,92 @@ ThreadManager::WorkerThread::WorkerThread(ThreadManager* thd_mgr) gpr_log(GPR_ERROR, "Could not create grpc_sync_server worker-thread"); } } - -void ThreadManager::WorkerThread::Run() { - thd_mgr_->MainWorkLoop(); - thd_mgr_->MarkAsCompleted(this); -} - + +void ThreadManager::WorkerThread::Run() { + thd_mgr_->MainWorkLoop(); + thd_mgr_->MarkAsCompleted(this); +} + ThreadManager::WorkerThread::~WorkerThread() { // Don't join until the thread is fully constructed. thd_.Join(); } - + ThreadManager::ThreadManager(const char* name, grpc_resource_quota* resource_quota, int min_pollers, int max_pollers) - : shutdown_(false), - num_pollers_(0), - min_pollers_(min_pollers), - max_pollers_(max_pollers == -1 ? INT_MAX : max_pollers), + : shutdown_(false), + num_pollers_(0), + min_pollers_(min_pollers), + max_pollers_(max_pollers == -1 ? INT_MAX : max_pollers), num_threads_(0), max_active_threads_sofar_(0) { resource_user_ = grpc_resource_user_create(resource_quota, name); } - -ThreadManager::~ThreadManager() { - { + +ThreadManager::~ThreadManager() { + { grpc_core::MutexLock lock(&mu_); - GPR_ASSERT(num_threads_ == 0); - } - + GPR_ASSERT(num_threads_ == 0); + } + grpc_core::ExecCtx exec_ctx; // grpc_resource_user_unref needs an exec_ctx grpc_resource_user_unref(resource_user_); - CleanupCompletedThreads(); -} - -void ThreadManager::Wait() { + CleanupCompletedThreads(); +} + +void ThreadManager::Wait() { grpc_core::MutexLock lock(&mu_); - while (num_threads_ != 0) { + while (num_threads_ != 0) { shutdown_cv_.Wait(&mu_); - } -} - -void ThreadManager::Shutdown() { + } +} + +void ThreadManager::Shutdown() { grpc_core::MutexLock lock(&mu_); - shutdown_ = true; -} - -bool ThreadManager::IsShutdown() { + shutdown_ = true; +} + +bool ThreadManager::IsShutdown() { grpc_core::MutexLock lock(&mu_); - return shutdown_; -} - + return shutdown_; +} + int ThreadManager::GetMaxActiveThreadsSoFar() { grpc_core::MutexLock list_lock(&list_mu_); return max_active_threads_sofar_; } -void ThreadManager::MarkAsCompleted(WorkerThread* thd) { - { +void ThreadManager::MarkAsCompleted(WorkerThread* thd) { + { grpc_core::MutexLock list_lock(&list_mu_); - completed_threads_.push_back(thd); - } - + completed_threads_.push_back(thd); + } + { grpc_core::MutexLock lock(&mu_); num_threads_--; if (num_threads_ == 0) { shutdown_cv_.Signal(); } - } + } // Give a thread back to the resource quota grpc_resource_user_free_threads(resource_user_, 1); -} - -void ThreadManager::CleanupCompletedThreads() { +} + +void ThreadManager::CleanupCompletedThreads() { std::list<WorkerThread*> completed_threads; { // swap out the completed threads list: allows other threads to clean up // more quickly grpc_core::MutexLock lock(&list_mu_); completed_threads.swap(completed_threads_); - } + } for (auto thd : completed_threads) delete thd; -} - -void ThreadManager::Initialize() { +} + +void ThreadManager::Initialize() { if (!grpc_resource_user_allocate_threads(resource_user_, min_pollers_)) { gpr_log(GPR_ERROR, "No thread quota available to even create the minimum required " @@ -137,21 +137,21 @@ void ThreadManager::Initialize() { num_pollers_ = min_pollers_; num_threads_ = min_pollers_; max_active_threads_sofar_ = min_pollers_; - } - + } + for (int i = 0; i < min_pollers_; i++) { WorkerThread* worker = new WorkerThread(this); GPR_ASSERT(worker->created()); // Must be able to create the minimum worker->Start(); - } -} - -void ThreadManager::MainWorkLoop() { + } +} + +void ThreadManager::MainWorkLoop() { while (true) { void* tag; bool ok; - WorkStatus work_status = PollForWork(&tag, &ok); - + WorkStatus work_status = PollForWork(&tag, &ok); + grpc_core::ReleasableMutexLock lock(&mu_); // Reduce the number of pollers by 1 and check what happened with the poll num_pollers_--; @@ -161,7 +161,7 @@ void ThreadManager::MainWorkLoop() { // If we timed out and we have more pollers than we need (or we are // shutdown), finish this thread if (shutdown_ || num_pollers_ > max_pollers_) done = true; - break; + break; case SHUTDOWN: // If the thread manager is shutdown, finish this thread done = true; @@ -216,10 +216,10 @@ void ThreadManager::MainWorkLoop() { // If we're shutdown, we should finish at this point. if (shutdown_) done = true; break; - } + } // If we decided to finish the thread, break out of the while loop if (done) break; - + // Otherwise go back to polling as long as it doesn't exceed max_pollers_ // // **WARNING**: @@ -251,15 +251,15 @@ void ThreadManager::MainWorkLoop() { num_pollers_++; } else { break; - } + } }; - + // This thread is exiting. Do some cleanup work i.e delete already completed // worker threads - CleanupCompletedThreads(); - - // If we are here, either ThreadManager is shutting down or it already has - // enough threads. -} - -} // namespace grpc + CleanupCompletedThreads(); + + // If we are here, either ThreadManager is shutting down or it already has + // enough threads. +} + +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.h b/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.h index 43f1fd5585..32592a7280 100644 --- a/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.h +++ b/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.h @@ -1,104 +1,104 @@ -/* - * +/* + * * Copyright 2016 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#ifndef GRPC_INTERNAL_CPP_THREAD_MANAGER_H -#define GRPC_INTERNAL_CPP_THREAD_MANAGER_H - -#include <list> -#include <memory> - + * + */ + +#ifndef GRPC_INTERNAL_CPP_THREAD_MANAGER_H +#define GRPC_INTERNAL_CPP_THREAD_MANAGER_H + +#include <list> +#include <memory> + #include <grpcpp/support/config.h> - + #include "src/core/lib/gprpp/sync.h" #include "src/core/lib/gprpp/thd.h" #include "src/core/lib/iomgr/resource_quota.h" -namespace grpc { - -class ThreadManager { - public: +namespace grpc { + +class ThreadManager { + public: explicit ThreadManager(const char* name, grpc_resource_quota* resource_quota, int min_pollers, int max_pollers); - virtual ~ThreadManager(); - - // Initializes and Starts the Rpc Manager threads - void Initialize(); - - // The return type of PollForWork() function - enum WorkStatus { WORK_FOUND, SHUTDOWN, TIMEOUT }; - - // "Polls" for new work. - // If the return value is WORK_FOUND: - // - The implementaion of PollForWork() MAY set some opaque identifier to - // (identify the work item found) via the '*tag' parameter - // - The implementaion MUST set the value of 'ok' to 'true' or 'false'. A - // value of 'false' indicates some implemenation specific error (that is - // neither SHUTDOWN nor TIMEOUT) - // - ThreadManager does not interpret the values of 'tag' and 'ok' - // - ThreadManager WILL call DoWork() and pass '*tag' and 'ok' as input to - // DoWork() - // - // If the return value is SHUTDOWN:, + virtual ~ThreadManager(); + + // Initializes and Starts the Rpc Manager threads + void Initialize(); + + // The return type of PollForWork() function + enum WorkStatus { WORK_FOUND, SHUTDOWN, TIMEOUT }; + + // "Polls" for new work. + // If the return value is WORK_FOUND: + // - The implementaion of PollForWork() MAY set some opaque identifier to + // (identify the work item found) via the '*tag' parameter + // - The implementaion MUST set the value of 'ok' to 'true' or 'false'. A + // value of 'false' indicates some implemenation specific error (that is + // neither SHUTDOWN nor TIMEOUT) + // - ThreadManager does not interpret the values of 'tag' and 'ok' + // - ThreadManager WILL call DoWork() and pass '*tag' and 'ok' as input to + // DoWork() + // + // If the return value is SHUTDOWN:, // - ThreadManager WILL NOT call DoWork() and terminates the thread - // - // If the return value is TIMEOUT:, - // - ThreadManager WILL NOT call DoWork() - // - ThreadManager MAY terminate the thread depending on the current number - // of active poller threads and mix_pollers/max_pollers settings - // - Also, the value of timeout is specific to the derived class - // implementation - virtual WorkStatus PollForWork(void** tag, bool* ok) = 0; - - // The implementation of DoWork() is supposed to perform the work found by - // PollForWork(). The tag and ok parameters are the same as returned by + // + // If the return value is TIMEOUT:, + // - ThreadManager WILL NOT call DoWork() + // - ThreadManager MAY terminate the thread depending on the current number + // of active poller threads and mix_pollers/max_pollers settings + // - Also, the value of timeout is specific to the derived class + // implementation + virtual WorkStatus PollForWork(void** tag, bool* ok) = 0; + + // The implementation of DoWork() is supposed to perform the work found by + // PollForWork(). The tag and ok parameters are the same as returned by // PollForWork(). The resources parameter indicates that the call actually // has the resources available for performing the RPC's work. If it doesn't, // the implementation should fail it appropriately. - // - // The implementation of DoWork() should also do any setup needed to ensure - // that the next call to PollForWork() (not necessarily by the current thread) - // actually finds some work + // + // The implementation of DoWork() should also do any setup needed to ensure + // that the next call to PollForWork() (not necessarily by the current thread) + // actually finds some work virtual void DoWork(void* tag, bool ok, bool resources) = 0; - - // Mark the ThreadManager as shutdown and begin draining the work. This is a - // non-blocking call and the caller should call Wait(), a blocking call which - // returns only once the shutdown is complete + + // Mark the ThreadManager as shutdown and begin draining the work. This is a + // non-blocking call and the caller should call Wait(), a blocking call which + // returns only once the shutdown is complete virtual void Shutdown(); - - // Has Shutdown() been called - bool IsShutdown(); - - // A blocking call that returns only after the ThreadManager has shutdown and - // all the threads have drained all the outstanding work + + // Has Shutdown() been called + bool IsShutdown(); + + // A blocking call that returns only after the ThreadManager has shutdown and + // all the threads have drained all the outstanding work virtual void Wait(); - + // Max number of concurrent threads that were ever active in this thread // manager so far. This is useful for debugging purposes (and in unit tests) // to check if resource_quota is properly being enforced. int GetMaxActiveThreadsSoFar(); - private: + private: // Helper wrapper class around grpc_core::Thread. Takes a ThreadManager object // and starts a new grpc_core::Thread to calls the Run() function. - // - // The Run() function calls ThreadManager::MainWorkLoop() function and once - // that completes, it marks the WorkerThread completed by calling - // ThreadManager::MarkAsCompleted() + // + // The Run() function calls ThreadManager::MainWorkLoop() function and once + // that completes, it marks the WorkerThread completed by calling + // ThreadManager::MarkAsCompleted() // // WHY IS THIS NEEDED?: // When a thread terminates, some other thread *must* call Join() on that @@ -117,37 +117,37 @@ class ThreadManager { // // TODO(sreek): Consider creating the threads 'detached' so that Join() need // not be called (and the need for this WorkerThread class is eliminated) - class WorkerThread { - public: - WorkerThread(ThreadManager* thd_mgr); - ~WorkerThread(); - + class WorkerThread { + public: + WorkerThread(ThreadManager* thd_mgr); + ~WorkerThread(); + bool created() const { return created_; } void Start() { thd_.Start(); } - private: - // Calls thd_mgr_->MainWorkLoop() and once that completes, calls - // thd_mgr_>MarkAsCompleted(this) to mark the thread as completed - void Run(); - + private: + // Calls thd_mgr_->MainWorkLoop() and once that completes, calls + // thd_mgr_>MarkAsCompleted(this) to mark the thread as completed + void Run(); + ThreadManager* const thd_mgr_; grpc_core::Thread thd_; bool created_; - }; - + }; + // The main function in ThreadManager - void MainWorkLoop(); - - void MarkAsCompleted(WorkerThread* thd); - void CleanupCompletedThreads(); - + void MainWorkLoop(); + + void MarkAsCompleted(WorkerThread* thd); + void CleanupCompletedThreads(); + // Protects shutdown_, num_pollers_, num_threads_ and // max_active_threads_sofar_ grpc_core::Mutex mu_; - - bool shutdown_; + + bool shutdown_; grpc_core::CondVar shutdown_cv_; - + // The resource user object to use when requesting quota to create threads // // Note: The user of this ThreadManager object must create grpc_resource_quota @@ -156,26 +156,26 @@ class ThreadManager { // created grpc_resource_user* resource_user_; - // Number of threads doing polling - int num_pollers_; - - // The minimum and maximum number of threads that should be doing polling - int min_pollers_; - int max_pollers_; - + // Number of threads doing polling + int num_pollers_; + + // The minimum and maximum number of threads that should be doing polling + int min_pollers_; + int max_pollers_; + // The total number of threads currently active (includes threads includes the // threads that are currently polling i.e num_pollers_) - int num_threads_; - + int num_threads_; + // See GetMaxActiveThreadsSoFar()'s description. // To be more specific, this variable tracks the max value num_threads_ was // ever set so far int max_active_threads_sofar_; grpc_core::Mutex list_mu_; - std::list<WorkerThread*> completed_threads_; -}; - -} // namespace grpc - -#endif // GRPC_INTERNAL_CPP_THREAD_MANAGER_H + std::list<WorkerThread*> completed_threads_; +}; + +} // namespace grpc + +#endif // GRPC_INTERNAL_CPP_THREAD_MANAGER_H diff --git a/contrib/libs/grpc/src/cpp/util/byte_buffer_cc.cc b/contrib/libs/grpc/src/cpp/util/byte_buffer_cc.cc index fb70590645..8ac84b83ce 100644 --- a/contrib/libs/grpc/src/cpp/util/byte_buffer_cc.cc +++ b/contrib/libs/grpc/src/cpp/util/byte_buffer_cc.cc @@ -1,46 +1,46 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpc/byte_buffer.h> -#include <grpc/byte_buffer_reader.h> +#include <grpc/byte_buffer_reader.h> #include <grpcpp/impl/grpc_library.h> #include <grpcpp/support/byte_buffer.h> - -namespace grpc { - + +namespace grpc { + static internal::GrpcLibraryInitializer g_gli_initializer; - -Status ByteBuffer::Dump(std::vector<Slice>* slices) const { - slices->clear(); - if (!buffer_) { - return Status(StatusCode::FAILED_PRECONDITION, "Buffer not initialized"); - } - grpc_byte_buffer_reader reader; - if (!grpc_byte_buffer_reader_init(&reader, buffer_)) { - return Status(StatusCode::INTERNAL, - "Couldn't initialize byte buffer reader"); - } - grpc_slice s; - while (grpc_byte_buffer_reader_next(&reader, &s)) { - slices->push_back(Slice(s, Slice::STEAL_REF)); - } - grpc_byte_buffer_reader_destroy(&reader); - return Status::OK; -} - -} // namespace grpc + +Status ByteBuffer::Dump(std::vector<Slice>* slices) const { + slices->clear(); + if (!buffer_) { + return Status(StatusCode::FAILED_PRECONDITION, "Buffer not initialized"); + } + grpc_byte_buffer_reader reader; + if (!grpc_byte_buffer_reader_init(&reader, buffer_)) { + return Status(StatusCode::INTERNAL, + "Couldn't initialize byte buffer reader"); + } + grpc_slice s; + while (grpc_byte_buffer_reader_next(&reader, &s)) { + slices->push_back(Slice(s, Slice::STEAL_REF)); + } + grpc_byte_buffer_reader_destroy(&reader); + return Status::OK; +} + +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/util/status.cc b/contrib/libs/grpc/src/cpp/util/status.cc index 93696d8126..47c381400d 100644 --- a/contrib/libs/grpc/src/cpp/util/status.cc +++ b/contrib/libs/grpc/src/cpp/util/status.cc @@ -1,26 +1,26 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/support/status.h> - -namespace grpc { - -const Status& Status::OK = Status(); -const Status& Status::CANCELLED = Status(StatusCode::CANCELLED, ""); - -} // namespace grpc + +namespace grpc { + +const Status& Status::OK = Status(); +const Status& Status::CANCELLED = Status(StatusCode::CANCELLED, ""); + +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/util/string_ref.cc b/contrib/libs/grpc/src/cpp/util/string_ref.cc index 8b09a82a63..64882969ae 100644 --- a/contrib/libs/grpc/src/cpp/util/string_ref.cc +++ b/contrib/libs/grpc/src/cpp/util/string_ref.cc @@ -1,25 +1,25 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - + * + */ + #include <grpcpp/support/string_ref.h> - -namespace grpc { - -const size_t string_ref::npos = size_t(-1); - -} // namespace grpc + +namespace grpc { + +const size_t string_ref::npos = size_t(-1); + +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/util/time_cc.cc b/contrib/libs/grpc/src/cpp/util/time_cc.cc index 6c9c228d7c..5401bf0da5 100644 --- a/contrib/libs/grpc/src/cpp/util/time_cc.cc +++ b/contrib/libs/grpc/src/cpp/util/time_cc.cc @@ -1,75 +1,75 @@ -/* - * +/* + * * Copyright 2015 gRPC authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - */ - -#include <grpc/support/time.h> + * + */ + +#include <grpc/support/time.h> #include <grpcpp/support/config.h> #include <grpcpp/support/time.h> - -using std::chrono::duration_cast; + +using std::chrono::duration_cast; using std::chrono::high_resolution_clock; -using std::chrono::nanoseconds; -using std::chrono::seconds; -using std::chrono::system_clock; - -namespace grpc { - -void Timepoint2Timespec(const system_clock::time_point& from, - gpr_timespec* to) { - system_clock::duration deadline = from.time_since_epoch(); - seconds secs = duration_cast<seconds>(deadline); - if (from == system_clock::time_point::max() || - secs.count() >= gpr_inf_future(GPR_CLOCK_REALTIME).tv_sec || - secs.count() < 0) { - *to = gpr_inf_future(GPR_CLOCK_REALTIME); - return; - } - nanoseconds nsecs = duration_cast<nanoseconds>(deadline - secs); +using std::chrono::nanoseconds; +using std::chrono::seconds; +using std::chrono::system_clock; + +namespace grpc { + +void Timepoint2Timespec(const system_clock::time_point& from, + gpr_timespec* to) { + system_clock::duration deadline = from.time_since_epoch(); + seconds secs = duration_cast<seconds>(deadline); + if (from == system_clock::time_point::max() || + secs.count() >= gpr_inf_future(GPR_CLOCK_REALTIME).tv_sec || + secs.count() < 0) { + *to = gpr_inf_future(GPR_CLOCK_REALTIME); + return; + } + nanoseconds nsecs = duration_cast<nanoseconds>(deadline - secs); to->tv_sec = static_cast<int64_t>(secs.count()); to->tv_nsec = static_cast<int32_t>(nsecs.count()); - to->clock_type = GPR_CLOCK_REALTIME; -} - -void TimepointHR2Timespec(const high_resolution_clock::time_point& from, - gpr_timespec* to) { - high_resolution_clock::duration deadline = from.time_since_epoch(); - seconds secs = duration_cast<seconds>(deadline); - if (from == high_resolution_clock::time_point::max() || - secs.count() >= gpr_inf_future(GPR_CLOCK_REALTIME).tv_sec || - secs.count() < 0) { - *to = gpr_inf_future(GPR_CLOCK_REALTIME); - return; - } - nanoseconds nsecs = duration_cast<nanoseconds>(deadline - secs); + to->clock_type = GPR_CLOCK_REALTIME; +} + +void TimepointHR2Timespec(const high_resolution_clock::time_point& from, + gpr_timespec* to) { + high_resolution_clock::duration deadline = from.time_since_epoch(); + seconds secs = duration_cast<seconds>(deadline); + if (from == high_resolution_clock::time_point::max() || + secs.count() >= gpr_inf_future(GPR_CLOCK_REALTIME).tv_sec || + secs.count() < 0) { + *to = gpr_inf_future(GPR_CLOCK_REALTIME); + return; + } + nanoseconds nsecs = duration_cast<nanoseconds>(deadline - secs); to->tv_sec = static_cast<int64_t>(secs.count()); to->tv_nsec = static_cast<int32_t>(nsecs.count()); - to->clock_type = GPR_CLOCK_REALTIME; -} - -system_clock::time_point Timespec2Timepoint(gpr_timespec t) { - if (gpr_time_cmp(t, gpr_inf_future(t.clock_type)) == 0) { - return system_clock::time_point::max(); - } - t = gpr_convert_clock_type(t, GPR_CLOCK_REALTIME); - system_clock::time_point tp; - tp += duration_cast<system_clock::time_point::duration>(seconds(t.tv_sec)); - tp += - duration_cast<system_clock::time_point::duration>(nanoseconds(t.tv_nsec)); - return tp; -} - -} // namespace grpc + to->clock_type = GPR_CLOCK_REALTIME; +} + +system_clock::time_point Timespec2Timepoint(gpr_timespec t) { + if (gpr_time_cmp(t, gpr_inf_future(t.clock_type)) == 0) { + return system_clock::time_point::max(); + } + t = gpr_convert_clock_type(t, GPR_CLOCK_REALTIME); + system_clock::time_point tp; + tp += duration_cast<system_clock::time_point::duration>(seconds(t.tv_sec)); + tp += + duration_cast<system_clock::time_point::duration>(nanoseconds(t.tv_nsec)); + return tp; +} + +} // namespace grpc |