From 7a6e30e61c29eeab8c9cae6577d92ff59c1f64f6 Mon Sep 17 00:00:00 2001 From: Nathaniel Manista Date: Sat, 20 Aug 2016 15:34:13 +0000 Subject: Python grpc.secure_channel doc string correction --- src/python/grpcio/grpc/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/python/grpcio/grpc/__init__.py b/src/python/grpcio/grpc/__init__.py index 513839df7d..1cbe93cddd 100644 --- a/src/python/grpcio/grpc/__init__.py +++ b/src/python/grpcio/grpc/__init__.py @@ -1193,7 +1193,7 @@ def insecure_channel(target, options=None): def secure_channel(target, credentials, options=None): - """Creates an insecure Channel to a server. + """Creates a secure Channel to a server. Args: target: The target to which to connect. -- cgit v1.2.3 From 102fa966b67c2aca6dbfb9ff4833505615adab0a Mon Sep 17 00:00:00 2001 From: Craig Tiller Date: Mon, 22 Aug 2016 13:56:36 -0700 Subject: Rename some files to avoid conflicting .obj files on Windows --- BUILD | 28 +- CMakeLists.txt | 28 +- Makefile | 32 +- build.yaml | 16 +- src/cpp/client/channel.cc | 144 ----- src/cpp/client/channel_cc.cc | 144 +++++ src/cpp/client/credentials.cc | 48 -- src/cpp/client/credentials_cc.cc | 48 ++ src/cpp/common/completion_queue.cc | 74 --- src/cpp/common/completion_queue_cc.cc | 74 +++ src/cpp/server/server.cc | 633 --------------------- src/cpp/server/server_cc.cc | 633 +++++++++++++++++++++ src/cpp/util/byte_buffer.cc | 98 ---- src/cpp/util/byte_buffer_cc.cc | 98 ++++ src/cpp/util/slice.cc | 48 -- src/cpp/util/slice_cc.cc | 48 ++ src/cpp/util/time.cc | 95 ---- src/cpp/util/time_cc.cc | 95 ++++ test/cpp/util/test_config.cc | 52 -- test/cpp/util/test_config_cc.cc | 52 ++ tools/doxygen/Doxyfile.c++.internal | 14 +- .../run_tests/sanity/check_sources_and_headers.py | 5 +- tools/run_tests/sources_and_headers.json | 18 +- vsprojects/vcxproj/grpc++/grpc++.vcxproj | 16 +- vsprojects/vcxproj/grpc++/grpc++.vcxproj.filters | 16 +- .../grpc++_test_config/grpc++_test_config.vcxproj | 2 +- .../grpc++_test_config.vcxproj.filters | 2 +- .../grpc++_unsecure/grpc++_unsecure.vcxproj | 16 +- .../grpc++_unsecure.vcxproj.filters | 16 +- 29 files changed, 1297 insertions(+), 1296 deletions(-) delete mode 100644 src/cpp/client/channel.cc create mode 100644 src/cpp/client/channel_cc.cc delete mode 100644 src/cpp/client/credentials.cc create mode 100644 src/cpp/client/credentials_cc.cc delete mode 100644 src/cpp/common/completion_queue.cc create mode 100644 src/cpp/common/completion_queue_cc.cc delete mode 100644 src/cpp/server/server.cc create mode 100644 src/cpp/server/server_cc.cc delete mode 100644 src/cpp/util/byte_buffer.cc create mode 100644 src/cpp/util/byte_buffer_cc.cc delete mode 100644 src/cpp/util/slice.cc create mode 100644 src/cpp/util/slice_cc.cc delete mode 100644 src/cpp/util/time.cc create mode 100644 src/cpp/util/time_cc.cc delete mode 100644 test/cpp/util/test_config.cc create mode 100644 test/cpp/util/test_config_cc.cc (limited to 'src') diff --git a/BUILD b/BUILD index 6e1289d8c0..385afc48d9 100644 --- a/BUILD +++ b/BUILD @@ -1320,32 +1320,32 @@ cc_library( "src/cpp/common/secure_channel_arguments.cc", "src/cpp/common/secure_create_auth_context.cc", "src/cpp/server/secure_server_credentials.cc", - "src/cpp/client/channel.cc", + "src/cpp/client/channel_cc.cc", "src/cpp/client/client_context.cc", "src/cpp/client/create_channel.cc", "src/cpp/client/create_channel_internal.cc", "src/cpp/client/create_channel_posix.cc", - "src/cpp/client/credentials.cc", + "src/cpp/client/credentials_cc.cc", "src/cpp/client/generic_stub.cc", "src/cpp/client/insecure_credentials.cc", "src/cpp/common/channel_arguments.cc", - "src/cpp/common/completion_queue.cc", + "src/cpp/common/completion_queue_cc.cc", "src/cpp/common/core_codegen.cc", "src/cpp/common/rpc_method.cc", "src/cpp/server/async_generic_service.cc", "src/cpp/server/create_default_thread_pool.cc", "src/cpp/server/dynamic_thread_pool.cc", "src/cpp/server/insecure_server_credentials.cc", - "src/cpp/server/server.cc", "src/cpp/server/server_builder.cc", + "src/cpp/server/server_cc.cc", "src/cpp/server/server_context.cc", "src/cpp/server/server_credentials.cc", "src/cpp/server/server_posix.cc", - "src/cpp/util/byte_buffer.cc", - "src/cpp/util/slice.cc", + "src/cpp/util/byte_buffer_cc.cc", + "src/cpp/util/slice_cc.cc", "src/cpp/util/status.cc", "src/cpp/util/string_ref.cc", - "src/cpp/util/time.cc", + "src/cpp/util/time_cc.cc", "src/core/lib/channel/channel_args.c", "src/core/lib/channel/channel_stack.c", "src/core/lib/channel/channel_stack_builder.c", @@ -1719,32 +1719,32 @@ cc_library( "src/core/lib/transport/transport.h", "src/core/lib/transport/transport_impl.h", "src/cpp/common/insecure_create_auth_context.cc", - "src/cpp/client/channel.cc", + "src/cpp/client/channel_cc.cc", "src/cpp/client/client_context.cc", "src/cpp/client/create_channel.cc", "src/cpp/client/create_channel_internal.cc", "src/cpp/client/create_channel_posix.cc", - "src/cpp/client/credentials.cc", + "src/cpp/client/credentials_cc.cc", "src/cpp/client/generic_stub.cc", "src/cpp/client/insecure_credentials.cc", "src/cpp/common/channel_arguments.cc", - "src/cpp/common/completion_queue.cc", + "src/cpp/common/completion_queue_cc.cc", "src/cpp/common/core_codegen.cc", "src/cpp/common/rpc_method.cc", "src/cpp/server/async_generic_service.cc", "src/cpp/server/create_default_thread_pool.cc", "src/cpp/server/dynamic_thread_pool.cc", "src/cpp/server/insecure_server_credentials.cc", - "src/cpp/server/server.cc", "src/cpp/server/server_builder.cc", + "src/cpp/server/server_cc.cc", "src/cpp/server/server_context.cc", "src/cpp/server/server_credentials.cc", "src/cpp/server/server_posix.cc", - "src/cpp/util/byte_buffer.cc", - "src/cpp/util/slice.cc", + "src/cpp/util/byte_buffer_cc.cc", + "src/cpp/util/slice_cc.cc", "src/cpp/util/status.cc", "src/cpp/util/string_ref.cc", - "src/cpp/util/time.cc", + "src/cpp/util/time_cc.cc", "src/core/lib/channel/channel_args.c", "src/core/lib/channel/channel_stack.c", "src/core/lib/channel/channel_stack_builder.c", diff --git a/CMakeLists.txt b/CMakeLists.txt index 44e90720a5..0dbf3f67fa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -699,32 +699,32 @@ add_library(grpc++ src/cpp/common/secure_channel_arguments.cc src/cpp/common/secure_create_auth_context.cc src/cpp/server/secure_server_credentials.cc - src/cpp/client/channel.cc + src/cpp/client/channel_cc.cc src/cpp/client/client_context.cc src/cpp/client/create_channel.cc src/cpp/client/create_channel_internal.cc src/cpp/client/create_channel_posix.cc - src/cpp/client/credentials.cc + src/cpp/client/credentials_cc.cc src/cpp/client/generic_stub.cc src/cpp/client/insecure_credentials.cc src/cpp/common/channel_arguments.cc - src/cpp/common/completion_queue.cc + src/cpp/common/completion_queue_cc.cc src/cpp/common/core_codegen.cc src/cpp/common/rpc_method.cc src/cpp/server/async_generic_service.cc src/cpp/server/create_default_thread_pool.cc src/cpp/server/dynamic_thread_pool.cc src/cpp/server/insecure_server_credentials.cc - src/cpp/server/server.cc src/cpp/server/server_builder.cc + src/cpp/server/server_cc.cc src/cpp/server/server_context.cc src/cpp/server/server_credentials.cc src/cpp/server/server_posix.cc - src/cpp/util/byte_buffer.cc - src/cpp/util/slice.cc + src/cpp/util/byte_buffer_cc.cc + src/cpp/util/slice_cc.cc src/cpp/util/status.cc src/cpp/util/string_ref.cc - src/cpp/util/time.cc + src/cpp/util/time_cc.cc src/core/lib/channel/channel_args.c src/core/lib/channel/channel_stack.c src/core/lib/channel/channel_stack_builder.c @@ -855,32 +855,32 @@ target_link_libraries(grpc++_reflection add_library(grpc++_unsecure src/cpp/common/insecure_create_auth_context.cc - src/cpp/client/channel.cc + src/cpp/client/channel_cc.cc src/cpp/client/client_context.cc src/cpp/client/create_channel.cc src/cpp/client/create_channel_internal.cc src/cpp/client/create_channel_posix.cc - src/cpp/client/credentials.cc + src/cpp/client/credentials_cc.cc src/cpp/client/generic_stub.cc src/cpp/client/insecure_credentials.cc src/cpp/common/channel_arguments.cc - src/cpp/common/completion_queue.cc + src/cpp/common/completion_queue_cc.cc src/cpp/common/core_codegen.cc src/cpp/common/rpc_method.cc src/cpp/server/async_generic_service.cc src/cpp/server/create_default_thread_pool.cc src/cpp/server/dynamic_thread_pool.cc src/cpp/server/insecure_server_credentials.cc - src/cpp/server/server.cc src/cpp/server/server_builder.cc + src/cpp/server/server_cc.cc src/cpp/server/server_context.cc src/cpp/server/server_credentials.cc src/cpp/server/server_posix.cc - src/cpp/util/byte_buffer.cc - src/cpp/util/slice.cc + src/cpp/util/byte_buffer_cc.cc + src/cpp/util/slice_cc.cc src/cpp/util/status.cc src/cpp/util/string_ref.cc - src/cpp/util/time.cc + src/cpp/util/time_cc.cc src/core/lib/channel/channel_args.c src/core/lib/channel/channel_stack.c src/core/lib/channel/channel_stack_builder.c diff --git a/Makefile b/Makefile index da53211281..e6c35328a9 100644 --- a/Makefile +++ b/Makefile @@ -3363,32 +3363,32 @@ LIBGRPC++_SRC = \ src/cpp/common/secure_channel_arguments.cc \ src/cpp/common/secure_create_auth_context.cc \ src/cpp/server/secure_server_credentials.cc \ - src/cpp/client/channel.cc \ + src/cpp/client/channel_cc.cc \ src/cpp/client/client_context.cc \ src/cpp/client/create_channel.cc \ src/cpp/client/create_channel_internal.cc \ src/cpp/client/create_channel_posix.cc \ - src/cpp/client/credentials.cc \ + src/cpp/client/credentials_cc.cc \ src/cpp/client/generic_stub.cc \ src/cpp/client/insecure_credentials.cc \ src/cpp/common/channel_arguments.cc \ - src/cpp/common/completion_queue.cc \ + src/cpp/common/completion_queue_cc.cc \ src/cpp/common/core_codegen.cc \ src/cpp/common/rpc_method.cc \ src/cpp/server/async_generic_service.cc \ src/cpp/server/create_default_thread_pool.cc \ src/cpp/server/dynamic_thread_pool.cc \ src/cpp/server/insecure_server_credentials.cc \ - src/cpp/server/server.cc \ src/cpp/server/server_builder.cc \ + src/cpp/server/server_cc.cc \ src/cpp/server/server_context.cc \ src/cpp/server/server_credentials.cc \ src/cpp/server/server_posix.cc \ - src/cpp/util/byte_buffer.cc \ - src/cpp/util/slice.cc \ + src/cpp/util/byte_buffer_cc.cc \ + src/cpp/util/slice_cc.cc \ src/cpp/util/status.cc \ src/cpp/util/string_ref.cc \ - src/cpp/util/time.cc \ + src/cpp/util/time_cc.cc \ src/core/lib/channel/channel_args.c \ src/core/lib/channel/channel_stack.c \ src/core/lib/channel/channel_stack_builder.c \ @@ -3776,7 +3776,7 @@ endif LIBGRPC++_TEST_CONFIG_SRC = \ - test/cpp/util/test_config.cc \ + test/cpp/util/test_config_cc.cc \ PUBLIC_HEADERS_CXX += \ @@ -3944,32 +3944,32 @@ $(OBJDIR)/$(CONFIG)/src/cpp/codegen/codegen_init.o: $(GENDIR)/src/proto/grpc/tes LIBGRPC++_UNSECURE_SRC = \ src/cpp/common/insecure_create_auth_context.cc \ - src/cpp/client/channel.cc \ + src/cpp/client/channel_cc.cc \ src/cpp/client/client_context.cc \ src/cpp/client/create_channel.cc \ src/cpp/client/create_channel_internal.cc \ src/cpp/client/create_channel_posix.cc \ - src/cpp/client/credentials.cc \ + src/cpp/client/credentials_cc.cc \ src/cpp/client/generic_stub.cc \ src/cpp/client/insecure_credentials.cc \ src/cpp/common/channel_arguments.cc \ - src/cpp/common/completion_queue.cc \ + src/cpp/common/completion_queue_cc.cc \ src/cpp/common/core_codegen.cc \ src/cpp/common/rpc_method.cc \ src/cpp/server/async_generic_service.cc \ src/cpp/server/create_default_thread_pool.cc \ src/cpp/server/dynamic_thread_pool.cc \ src/cpp/server/insecure_server_credentials.cc \ - src/cpp/server/server.cc \ src/cpp/server/server_builder.cc \ + src/cpp/server/server_cc.cc \ src/cpp/server/server_context.cc \ src/cpp/server/server_credentials.cc \ src/cpp/server/server_posix.cc \ - src/cpp/util/byte_buffer.cc \ - src/cpp/util/slice.cc \ + src/cpp/util/byte_buffer_cc.cc \ + src/cpp/util/slice_cc.cc \ src/cpp/util/status.cc \ src/cpp/util/string_ref.cc \ - src/cpp/util/time.cc \ + src/cpp/util/time_cc.cc \ src/core/lib/channel/channel_args.c \ src/core/lib/channel/channel_stack.c \ src/core/lib/channel/channel_stack_builder.c \ @@ -15050,7 +15050,7 @@ test/cpp/util/create_test_channel.cc: $(OPENSSL_DEP) test/cpp/util/proto_file_parser.cc: $(OPENSSL_DEP) test/cpp/util/string_ref_helper.cc: $(OPENSSL_DEP) test/cpp/util/subprocess.cc: $(OPENSSL_DEP) -test/cpp/util/test_config.cc: $(OPENSSL_DEP) +test/cpp/util/test_config_cc.cc: $(OPENSSL_DEP) test/cpp/util/test_credentials_provider.cc: $(OPENSSL_DEP) endif diff --git a/build.yaml b/build.yaml index 8377c65545..63933c67d9 100644 --- a/build.yaml +++ b/build.yaml @@ -686,32 +686,32 @@ filegroups: - src/cpp/server/dynamic_thread_pool.h - src/cpp/server/thread_pool_interface.h src: - - src/cpp/client/channel.cc + - src/cpp/client/channel_cc.cc - src/cpp/client/client_context.cc - src/cpp/client/create_channel.cc - src/cpp/client/create_channel_internal.cc - src/cpp/client/create_channel_posix.cc - - src/cpp/client/credentials.cc + - src/cpp/client/credentials_cc.cc - src/cpp/client/generic_stub.cc - src/cpp/client/insecure_credentials.cc - src/cpp/common/channel_arguments.cc - - src/cpp/common/completion_queue.cc + - src/cpp/common/completion_queue_cc.cc - src/cpp/common/core_codegen.cc - src/cpp/common/rpc_method.cc - src/cpp/server/async_generic_service.cc - src/cpp/server/create_default_thread_pool.cc - src/cpp/server/dynamic_thread_pool.cc - src/cpp/server/insecure_server_credentials.cc - - src/cpp/server/server.cc - src/cpp/server/server_builder.cc + - src/cpp/server/server_cc.cc - src/cpp/server/server_context.cc - src/cpp/server/server_credentials.cc - src/cpp/server/server_posix.cc - - src/cpp/util/byte_buffer.cc - - src/cpp/util/slice.cc + - src/cpp/util/byte_buffer_cc.cc + - src/cpp/util/slice_cc.cc - src/cpp/util/status.cc - src/cpp/util/string_ref.cc - - src/cpp/util/time.cc + - src/cpp/util/time_cc.cc uses: - grpc_base - grpc++_codegen_base @@ -978,7 +978,7 @@ libs: headers: - test/cpp/util/test_config.h src: - - test/cpp/util/test_config.cc + - test/cpp/util/test_config_cc.cc - name: grpc++_test_util build: private language: c++ diff --git a/src/cpp/client/channel.cc b/src/cpp/client/channel.cc deleted file mode 100644 index 43b3875cb3..0000000000 --- a/src/cpp/client/channel.cc +++ /dev/null @@ -1,144 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "src/core/lib/profiling/timers.h" - -namespace grpc { - -static internal::GrpcLibraryInitializer g_gli_initializer; -Channel::Channel(const grpc::string& host, grpc_channel* channel) - : host_(host), c_channel_(channel) { - g_gli_initializer.summon(); -} - -Channel::~Channel() { grpc_channel_destroy(c_channel_); } - -Call Channel::CreateCall(const RpcMethod& method, ClientContext* context, - CompletionQueue* cq) { - const bool kRegistered = method.channel_tag() && context->authority().empty(); - grpc_call* c_call = NULL; - 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 char* host_str = NULL; - if (!context->authority().empty()) { - host_str = context->authority_.c_str(); - } else if (!host_.empty()) { - host_str = host_.c_str(); - } - c_call = grpc_channel_create_call(c_channel_, context->propagate_from_call_, - context->propagation_options_.c_bitmask(), - cq->cq(), method.name(), host_str, - context->raw_deadline(), nullptr); - } - grpc_census_call_set_context(c_call, context->census_context()); - context->set_call(c_call, shared_from_this()); - return Call(c_call, this, cq); -} - -void Channel::PerformOpsOnCall(CallOpSetInterface* ops, Call* call) { - static const size_t MAX_OPS = 8; - size_t nops = 0; - grpc_op cops[MAX_OPS]; - ops->FillOps(cops, &nops); - GPR_ASSERT(GRPC_CALL_OK == - grpc_call_start_batch(call->call(), cops, nops, ops, nullptr)); -} - -void* Channel::RegisterMethod(const char* method) { - return grpc_channel_register_call( - c_channel_, method, host_.empty() ? NULL : 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 { -class TagSaver GRPC_FINAL : public CompletionQueueTag { - public: - explicit TagSaver(void* tag) : tag_(tag) {} - ~TagSaver() GRPC_OVERRIDE {} - bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { - *tag = tag_; - delete this; - return true; - } - - private: - void* tag_; -}; - -} // namespace - -void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed, - gpr_timespec deadline, - 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) { - CompletionQueue cq; - bool ok = false; - void* tag = NULL; - NotifyOnStateChangeImpl(last_observed, deadline, &cq, NULL); - cq.Next(&tag, &ok); - GPR_ASSERT(tag == NULL); - return ok; -} - -} // namespace grpc diff --git a/src/cpp/client/channel_cc.cc b/src/cpp/client/channel_cc.cc new file mode 100644 index 0000000000..43b3875cb3 --- /dev/null +++ b/src/cpp/client/channel_cc.cc @@ -0,0 +1,144 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "src/core/lib/profiling/timers.h" + +namespace grpc { + +static internal::GrpcLibraryInitializer g_gli_initializer; +Channel::Channel(const grpc::string& host, grpc_channel* channel) + : host_(host), c_channel_(channel) { + g_gli_initializer.summon(); +} + +Channel::~Channel() { grpc_channel_destroy(c_channel_); } + +Call Channel::CreateCall(const RpcMethod& method, ClientContext* context, + CompletionQueue* cq) { + const bool kRegistered = method.channel_tag() && context->authority().empty(); + grpc_call* c_call = NULL; + 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 char* host_str = NULL; + if (!context->authority().empty()) { + host_str = context->authority_.c_str(); + } else if (!host_.empty()) { + host_str = host_.c_str(); + } + c_call = grpc_channel_create_call(c_channel_, context->propagate_from_call_, + context->propagation_options_.c_bitmask(), + cq->cq(), method.name(), host_str, + context->raw_deadline(), nullptr); + } + grpc_census_call_set_context(c_call, context->census_context()); + context->set_call(c_call, shared_from_this()); + return Call(c_call, this, cq); +} + +void Channel::PerformOpsOnCall(CallOpSetInterface* ops, Call* call) { + static const size_t MAX_OPS = 8; + size_t nops = 0; + grpc_op cops[MAX_OPS]; + ops->FillOps(cops, &nops); + GPR_ASSERT(GRPC_CALL_OK == + grpc_call_start_batch(call->call(), cops, nops, ops, nullptr)); +} + +void* Channel::RegisterMethod(const char* method) { + return grpc_channel_register_call( + c_channel_, method, host_.empty() ? NULL : 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 { +class TagSaver GRPC_FINAL : public CompletionQueueTag { + public: + explicit TagSaver(void* tag) : tag_(tag) {} + ~TagSaver() GRPC_OVERRIDE {} + bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { + *tag = tag_; + delete this; + return true; + } + + private: + void* tag_; +}; + +} // namespace + +void Channel::NotifyOnStateChangeImpl(grpc_connectivity_state last_observed, + gpr_timespec deadline, + 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) { + CompletionQueue cq; + bool ok = false; + void* tag = NULL; + NotifyOnStateChangeImpl(last_observed, deadline, &cq, NULL); + cq.Next(&tag, &ok); + GPR_ASSERT(tag == NULL); + return ok; +} + +} // namespace grpc diff --git a/src/cpp/client/credentials.cc b/src/cpp/client/credentials.cc deleted file mode 100644 index e6a4f81b0d..0000000000 --- a/src/cpp/client/credentials.cc +++ /dev/null @@ -1,48 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#include -#include - -namespace grpc { - -static internal::GrpcLibraryInitializer g_gli_initializer; -ChannelCredentials::ChannelCredentials() { g_gli_initializer.summon(); } - -ChannelCredentials::~ChannelCredentials() {} - -CallCredentials::CallCredentials() { g_gli_initializer.summon(); } - -CallCredentials::~CallCredentials() {} - -} // namespace grpc diff --git a/src/cpp/client/credentials_cc.cc b/src/cpp/client/credentials_cc.cc new file mode 100644 index 0000000000..e6a4f81b0d --- /dev/null +++ b/src/cpp/client/credentials_cc.cc @@ -0,0 +1,48 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include +#include + +namespace grpc { + +static internal::GrpcLibraryInitializer g_gli_initializer; +ChannelCredentials::ChannelCredentials() { g_gli_initializer.summon(); } + +ChannelCredentials::~ChannelCredentials() {} + +CallCredentials::CallCredentials() { g_gli_initializer.summon(); } + +CallCredentials::~CallCredentials() {} + +} // namespace grpc diff --git a/src/cpp/common/completion_queue.cc b/src/cpp/common/completion_queue.cc deleted file mode 100644 index 00cc102f92..0000000000 --- a/src/cpp/common/completion_queue.cc +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#include - -#include - -#include -#include -#include -#include - -namespace grpc { - -static internal::GrpcLibraryInitializer g_gli_initializer; - -CompletionQueue::CompletionQueue(grpc_completion_queue* take) : cq_(take) {} - -void CompletionQueue::Shutdown() { - g_gli_initializer.summon(); - grpc_completion_queue_shutdown(cq_); -} - -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 cq_tag = static_cast(ev.tag); - *ok = ev.success != 0; - *tag = cq_tag; - if (cq_tag->FinalizeResult(tag, ok)) { - return GOT_EVENT; - } - break; - } - } -} - -} // namespace grpc diff --git a/src/cpp/common/completion_queue_cc.cc b/src/cpp/common/completion_queue_cc.cc new file mode 100644 index 0000000000..00cc102f92 --- /dev/null +++ b/src/cpp/common/completion_queue_cc.cc @@ -0,0 +1,74 @@ +/* + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include + +#include + +#include +#include +#include +#include + +namespace grpc { + +static internal::GrpcLibraryInitializer g_gli_initializer; + +CompletionQueue::CompletionQueue(grpc_completion_queue* take) : cq_(take) {} + +void CompletionQueue::Shutdown() { + g_gli_initializer.summon(); + grpc_completion_queue_shutdown(cq_); +} + +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 cq_tag = static_cast(ev.tag); + *ok = ev.success != 0; + *tag = cq_tag; + if (cq_tag->FinalizeResult(tag, ok)) { + return GOT_EVENT; + } + break; + } + } +} + +} // namespace grpc diff --git a/src/cpp/server/server.cc b/src/cpp/server/server.cc deleted file mode 100644 index af04fd4ca6..0000000000 --- a/src/cpp/server/server.cc +++ /dev/null @@ -1,633 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "src/core/lib/profiling/timers.h" -#include "src/cpp/server/thread_pool_interface.h" - -namespace grpc { - -class DefaultGlobalCallbacks GRPC_FINAL : public Server::GlobalCallbacks { - public: - ~DefaultGlobalCallbacks() GRPC_OVERRIDE {} - void PreSynchronousRequest(ServerContext* context) GRPC_OVERRIDE {} - void PostSynchronousRequest(ServerContext* context) GRPC_OVERRIDE {} -}; - -static std::shared_ptr g_callbacks = nullptr; -static gpr_once g_once_init_callbacks = GPR_ONCE_INIT; - -static void InitGlobalCallbacks() { - if (!g_callbacks) { - g_callbacks.reset(new DefaultGlobalCallbacks()); - } -} - -class Server::UnimplementedAsyncRequestContext { - protected: - UnimplementedAsyncRequestContext() : generic_stream_(&server_context_) {} - - GenericServerContext server_context_; - GenericServerAsyncReaderWriter generic_stream_; -}; - -class Server::UnimplementedAsyncRequest GRPC_FINAL - : public UnimplementedAsyncRequestContext, - public GenericAsyncRequest { - public: - UnimplementedAsyncRequest(Server* server, ServerCompletionQueue* cq) - : GenericAsyncRequest(server, &server_context_, &generic_stream_, cq, cq, - NULL, false), - server_(server), - cq_(cq) {} - - bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE; - - ServerContext* context() { return &server_context_; } - GenericServerAsyncReaderWriter* stream() { return &generic_stream_; } - - private: - Server* const server_; - ServerCompletionQueue* const cq_; -}; - -typedef SneakyCallOpSet - UnimplementedAsyncResponseOp; -class Server::UnimplementedAsyncResponse GRPC_FINAL - : public UnimplementedAsyncResponseOp { - public: - UnimplementedAsyncResponse(UnimplementedAsyncRequest* request); - ~UnimplementedAsyncResponse() { delete request_; } - - bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { - bool r = UnimplementedAsyncResponseOp::FinalizeResult(tag, status); - delete this; - return r; - } - - private: - UnimplementedAsyncRequest* const request_; -}; - -class Server::ShutdownRequest GRPC_FINAL : public CompletionQueueTag { - public: - bool FinalizeResult(void** tag, bool* status) { - delete this; - return false; - } -}; - -class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag { - public: - SyncRequest(RpcServiceMethod* method, void* tag) - : method_(method), - tag_(tag), - in_flight_(false), - has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC || - method->method_type() == - 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_); - } - - static SyncRequest* Wait(CompletionQueue* cq, bool* ok) { - void* tag = nullptr; - *ok = false; - if (!cq->Next(&tag, ok)) { - return nullptr; - } - auto* mrd = static_cast(tag); - GPR_ASSERT(mrd->in_flight_); - return mrd; - } - - static bool AsyncWait(CompletionQueue* cq, SyncRequest** req, bool* ok, - gpr_timespec deadline) { - void* tag = nullptr; - *ok = false; - switch (cq->AsyncNext(&tag, ok, deadline)) { - case CompletionQueue::TIMEOUT: - *req = nullptr; - return true; - case CompletionQueue::SHUTDOWN: - *req = nullptr; - return false; - case CompletionQueue::GOT_EVENT: - *req = static_cast(tag); - GPR_ASSERT((*req)->in_flight_); - return true; - } - GPR_UNREACHABLE_CODE(return false); - } - - void SetupRequest() { cq_ = grpc_completion_queue_create(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; - if (tag_) { - GPR_ASSERT(GRPC_CALL_OK == - grpc_server_request_registered_call( - server, tag_, &call_, &deadline_, &request_metadata_, - has_request_payload_ ? &request_payload_ : nullptr, cq_, - notify_cq, this)); - } else { - if (!call_details_) { - call_details_ = new grpc_call_details; - grpc_call_details_init(call_details_); - } - GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call( - server, &call_, call_details_, - &request_metadata_, cq_, notify_cq, this)); - } - } - - bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { - if (!*status) { - grpc_completion_queue_destroy(cq_); - } - if (call_details_) { - deadline_ = call_details_->deadline; - grpc_call_details_destroy(call_details_); - grpc_call_details_init(call_details_); - } - return true; - } - - class CallData GRPC_FINAL { - public: - explicit CallData(Server* server, SyncRequest* mrd) - : cq_(mrd->cq_), - call_(mrd->call_, server, &cq_, server->max_message_size_), - ctx_(mrd->deadline_, mrd->request_metadata_.metadata, - mrd->request_metadata_.count), - has_request_payload_(mrd->has_request_payload_), - request_payload_(mrd->request_payload_), - method_(mrd->method_) { - 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(std::shared_ptr global_callbacks) { - ctx_.BeginCompletionOp(&call_); - global_callbacks->PreSynchronousRequest(&ctx_); - method_->handler()->RunHandler(MethodHandler::HandlerParameter( - &call_, &ctx_, request_payload_, call_.max_message_size())); - global_callbacks->PostSynchronousRequest(&ctx_); - request_payload_ = nullptr; - void* ignored_tag; - bool ignored_ok; - cq_.Shutdown(); - GPR_ASSERT(cq_.Next(&ignored_tag, &ignored_ok) == false); - } - - private: - CompletionQueue cq_; - Call call_; - ServerContext ctx_; - const bool has_request_payload_; - grpc_byte_buffer* request_payload_; - RpcServiceMethod* const method_; - }; - - private: - RpcServiceMethod* const method_; - void* const tag_; - bool in_flight_; - const bool has_request_payload_; - uint32_t incoming_flags_; - 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_; -}; - -static internal::GrpcLibraryInitializer g_gli_initializer; -Server::Server(ThreadPoolInterface* thread_pool, bool thread_pool_owned, - int max_message_size, ChannelArguments* args) - : max_message_size_(max_message_size), - started_(false), - shutdown_(false), - shutdown_notified_(false), - num_running_cb_(0), - sync_methods_(new std::list), - has_generic_service_(false), - server_(nullptr), - thread_pool_(thread_pool), - thread_pool_owned_(thread_pool_owned), - server_initializer_(new ServerInitializer(this)) { - g_gli_initializer.summon(); - gpr_once_init(&g_once_init_callbacks, InitGlobalCallbacks); - global_callbacks_ = g_callbacks; - global_callbacks_->UpdateArguments(args); - grpc_channel_args channel_args; - args->SetChannelArgs(&channel_args); - server_ = grpc_server_create(&channel_args, nullptr); - if (thread_pool_ == nullptr) { - grpc_server_register_non_listening_completion_queue(server_, cq_.cq(), - nullptr); - } else { - grpc_server_register_completion_queue(server_, cq_.cq(), nullptr); - } -} - -Server::~Server() { - { - grpc::unique_lock lock(mu_); - if (started_ && !shutdown_) { - lock.unlock(); - Shutdown(); - } else if (!started_) { - cq_.Shutdown(); - } - } - void* got_tag; - bool ok; - GPR_ASSERT(!cq_.Next(&got_tag, &ok)); - grpc_server_destroy(server_); - if (thread_pool_owned_) { - delete thread_pool_; - } - delete sync_methods_; -} - -void Server::SetGlobalCallbacks(GlobalCallbacks* callbacks) { - GPR_ASSERT(!g_callbacks); - GPR_ASSERT(callbacks); - g_callbacks.reset(callbacks); -} - -grpc_server* Server::c_server() { return server_; } - -CompletionQueue* Server::completion_queue() { return &cq_; } - -static grpc_server_register_method_payload_handling PayloadHandlingForMethod( - RpcServiceMethod* method) { - switch (method->method_type()) { - case RpcMethod::NORMAL_RPC: - case RpcMethod::SERVER_STREAMING: - return GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER; - case RpcMethod::CLIENT_STREAMING: - case RpcMethod::BIDI_STREAMING: - return GRPC_SRM_PAYLOAD_NONE; - } - GPR_UNREACHABLE_CODE(return GRPC_SRM_PAYLOAD_NONE;); -} - -bool Server::RegisterService(const grpc::string* host, 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; - for (auto it = service->methods_.begin(); it != service->methods_.end(); - ++it) { - if (it->get() == nullptr) { // Handled by generic service if any. - continue; - } - RpcServiceMethod* method = it->get(); - void* tag = grpc_server_register_method( - server_, method->name(), host ? host->c_str() : nullptr, - PayloadHandlingForMethod(method), 0); - if (tag == nullptr) { - gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", - method->name()); - return false; - } - if (method->handler() == nullptr) { - method->set_server_tag(tag); - } else { - sync_methods_->emplace_back(method, tag); - } - method_name = method->name(); - } - - // Parse service name. - if (method_name != nullptr) { - std::stringstream ss(method_name); - grpc::string service_name; - if (std::getline(ss, service_name, '/') && - std::getline(ss, service_name, '/')) { - services_.push_back(service_name); - } - } - return true; -} - -void Server::RegisterAsyncGenericService(AsyncGenericService* service) { - GPR_ASSERT(service->server_ == nullptr && - "Can only register an async generic service against one server."); - service->server_ = this; - has_generic_service_ = true; -} - -int Server::AddListeningPort(const grpc::string& addr, - ServerCredentials* creds) { - GPR_ASSERT(!started_); - return creds->AddPortToServer(addr, server_); -} - -bool Server::Start(ServerCompletionQueue** cqs, size_t num_cqs) { - GPR_ASSERT(!started_); - started_ = true; - grpc_server_start(server_); - - if (!has_generic_service_) { - if (!sync_methods_->empty()) { - unknown_method_.reset(new RpcServiceMethod( - "unknown", RpcMethod::BIDI_STREAMING, new UnknownMethodHandler)); - // Use of emplace_back with just constructor arguments is not accepted - // here by gcc-4.4 because it can't match the anonymous nullptr with a - // proper constructor implicitly. Construct the object and use push_back. - sync_methods_->push_back(SyncRequest(unknown_method_.get(), nullptr)); - } - for (size_t i = 0; i < num_cqs; i++) { - if (cqs[i]->IsFrequentlyPolled()) { - new UnimplementedAsyncRequest(this, cqs[i]); - } - } - } - // Start processing rpcs. - if (!sync_methods_->empty()) { - for (auto m = sync_methods_->begin(); m != sync_methods_->end(); m++) { - m->SetupRequest(); - m->Request(server_, cq_.cq()); - } - - ScheduleCallback(); - } - - return true; -} - -void Server::ShutdownInternal(gpr_timespec deadline) { - grpc::unique_lock lock(mu_); - if (started_ && !shutdown_) { - shutdown_ = true; - grpc_server_shutdown_and_notify(server_, cq_.cq(), new ShutdownRequest()); - cq_.Shutdown(); - lock.unlock(); - // Spin, eating requests until the completion queue is completely shutdown. - // If the deadline expires then cancel anything that's pending and keep - // spinning forever until the work is actually drained. - // Since nothing else needs to touch state guarded by mu_, holding it - // through this loop is fine. - SyncRequest* request; - bool ok; - while (SyncRequest::AsyncWait(&cq_, &request, &ok, deadline)) { - if (request == NULL) { // deadline expired - grpc_server_cancel_all_calls(server_); - deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC); - } else if (ok) { - SyncRequest::CallData call_data(this, request); - } - } - lock.lock(); - - // Wait for running callbacks to finish. - while (num_running_cb_ != 0) { - callback_cv_.wait(lock); - } - - shutdown_notified_ = true; - shutdown_cv_.notify_all(); - } -} - -void Server::Wait() { - grpc::unique_lock lock(mu_); - while (started_ && !shutdown_notified_) { - shutdown_cv_.wait(lock); - } -} - -void Server::PerformOpsOnCall(CallOpSetInterface* ops, Call* call) { - static const size_t MAX_OPS = 8; - size_t nops = 0; - grpc_op cops[MAX_OPS]; - ops->FillOps(cops, &nops); - auto result = grpc_call_start_batch(call->call(), cops, nops, ops, nullptr); - GPR_ASSERT(GRPC_CALL_OK == result); -} - -ServerInterface::BaseAsyncRequest::BaseAsyncRequest( - ServerInterface* server, ServerContext* context, - ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag, - bool delete_on_finalize) - : server_(server), - context_(context), - stream_(stream), - call_cq_(call_cq), - tag_(tag), - delete_on_finalize_(delete_on_finalize), - call_(nullptr) { - memset(&initial_metadata_array_, 0, sizeof(initial_metadata_array_)); -} - -bool ServerInterface::BaseAsyncRequest::FinalizeResult(void** tag, - bool* status) { - if (*status) { - for (size_t i = 0; i < initial_metadata_array_.count; i++) { - context_->client_metadata_.insert( - std::pair( - initial_metadata_array_.metadata[i].key, - grpc::string_ref( - initial_metadata_array_.metadata[i].value, - initial_metadata_array_.metadata[i].value_length))); - } - } - grpc_metadata_array_destroy(&initial_metadata_array_); - context_->set_call(call_); - context_->cq_ = call_cq_; - Call call(call_, server_, call_cq_, server_->max_message_size()); - if (*status && call_) { - context_->BeginCompletionOp(&call); - } - // just the pointers inside call are copied here - stream_->BindCall(&call); - *tag = tag_; - if (delete_on_finalize_) { - delete this; - } - return true; -} - -ServerInterface::RegisteredAsyncRequest::RegisteredAsyncRequest( - ServerInterface* server, ServerContext* context, - ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag) - : BaseAsyncRequest(server, context, stream, call_cq, tag, true) {} - -void ServerInterface::RegisteredAsyncRequest::IssueRequest( - void* registered_method, grpc_byte_buffer** payload, - ServerCompletionQueue* notification_cq) { - grpc_server_request_registered_call( - server_->server(), registered_method, &call_, &context_->deadline_, - &initial_metadata_array_, payload, call_cq_->cq(), notification_cq->cq(), - this); -} - -ServerInterface::GenericAsyncRequest::GenericAsyncRequest( - ServerInterface* server, GenericServerContext* context, - ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, - ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize) - : BaseAsyncRequest(server, context, stream, call_cq, tag, - delete_on_finalize) { - grpc_call_details_init(&call_details_); - GPR_ASSERT(notification_cq); - GPR_ASSERT(call_cq); - grpc_server_request_call(server->server(), &call_, &call_details_, - &initial_metadata_array_, call_cq->cq(), - notification_cq->cq(), this); -} - -bool ServerInterface::GenericAsyncRequest::FinalizeResult(void** tag, - bool* status) { - // TODO(yangg) remove the copy here. - if (*status) { - static_cast(context_)->method_ = - call_details_.method; - static_cast(context_)->host_ = call_details_.host; - } - gpr_free(call_details_.method); - gpr_free(call_details_.host); - return BaseAsyncRequest::FinalizeResult(tag, status); -} - -bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag, - bool* status) { - if (GenericAsyncRequest::FinalizeResult(tag, status) && *status) { - new UnimplementedAsyncRequest(server_, cq_); - new UnimplementedAsyncResponse(this); - } else { - delete this; - } - return false; -} - -Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse( - UnimplementedAsyncRequest* request) - : request_(request) { - Status status(StatusCode::UNIMPLEMENTED, ""); - UnknownMethodHandler::FillOps(request_->context(), this); - request_->stream()->call_.PerformOps(this); -} - -void Server::ScheduleCallback() { - { - grpc::unique_lock lock(mu_); - num_running_cb_++; - } - thread_pool_->Add(std::bind(&Server::RunRpc, this)); -} - -void Server::RunRpc() { - // Wait for one more incoming rpc. - bool ok; - GPR_TIMER_SCOPE("Server::RunRpc", 0); - auto* mrd = SyncRequest::Wait(&cq_, &ok); - if (mrd) { - ScheduleCallback(); - if (ok) { - SyncRequest::CallData cd(this, mrd); - { - mrd->SetupRequest(); - grpc::unique_lock lock(mu_); - if (!shutdown_) { - mrd->Request(server_, cq_.cq()); - } else { - // destroy the structure that was created - mrd->TeardownRequest(); - } - } - GPR_TIMER_SCOPE("cd.Run()", 0); - cd.Run(global_callbacks_); - } - } - - { - grpc::unique_lock lock(mu_); - num_running_cb_--; - if (shutdown_) { - callback_cv_.notify_all(); - } - } -} - -ServerInitializer* Server::initializer() { return server_initializer_.get(); } - -} // namespace grpc diff --git a/src/cpp/server/server_cc.cc b/src/cpp/server/server_cc.cc new file mode 100644 index 0000000000..af04fd4ca6 --- /dev/null +++ b/src/cpp/server/server_cc.cc @@ -0,0 +1,633 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "src/core/lib/profiling/timers.h" +#include "src/cpp/server/thread_pool_interface.h" + +namespace grpc { + +class DefaultGlobalCallbacks GRPC_FINAL : public Server::GlobalCallbacks { + public: + ~DefaultGlobalCallbacks() GRPC_OVERRIDE {} + void PreSynchronousRequest(ServerContext* context) GRPC_OVERRIDE {} + void PostSynchronousRequest(ServerContext* context) GRPC_OVERRIDE {} +}; + +static std::shared_ptr g_callbacks = nullptr; +static gpr_once g_once_init_callbacks = GPR_ONCE_INIT; + +static void InitGlobalCallbacks() { + if (!g_callbacks) { + g_callbacks.reset(new DefaultGlobalCallbacks()); + } +} + +class Server::UnimplementedAsyncRequestContext { + protected: + UnimplementedAsyncRequestContext() : generic_stream_(&server_context_) {} + + GenericServerContext server_context_; + GenericServerAsyncReaderWriter generic_stream_; +}; + +class Server::UnimplementedAsyncRequest GRPC_FINAL + : public UnimplementedAsyncRequestContext, + public GenericAsyncRequest { + public: + UnimplementedAsyncRequest(Server* server, ServerCompletionQueue* cq) + : GenericAsyncRequest(server, &server_context_, &generic_stream_, cq, cq, + NULL, false), + server_(server), + cq_(cq) {} + + bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE; + + ServerContext* context() { return &server_context_; } + GenericServerAsyncReaderWriter* stream() { return &generic_stream_; } + + private: + Server* const server_; + ServerCompletionQueue* const cq_; +}; + +typedef SneakyCallOpSet + UnimplementedAsyncResponseOp; +class Server::UnimplementedAsyncResponse GRPC_FINAL + : public UnimplementedAsyncResponseOp { + public: + UnimplementedAsyncResponse(UnimplementedAsyncRequest* request); + ~UnimplementedAsyncResponse() { delete request_; } + + bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { + bool r = UnimplementedAsyncResponseOp::FinalizeResult(tag, status); + delete this; + return r; + } + + private: + UnimplementedAsyncRequest* const request_; +}; + +class Server::ShutdownRequest GRPC_FINAL : public CompletionQueueTag { + public: + bool FinalizeResult(void** tag, bool* status) { + delete this; + return false; + } +}; + +class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag { + public: + SyncRequest(RpcServiceMethod* method, void* tag) + : method_(method), + tag_(tag), + in_flight_(false), + has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC || + method->method_type() == + 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_); + } + + static SyncRequest* Wait(CompletionQueue* cq, bool* ok) { + void* tag = nullptr; + *ok = false; + if (!cq->Next(&tag, ok)) { + return nullptr; + } + auto* mrd = static_cast(tag); + GPR_ASSERT(mrd->in_flight_); + return mrd; + } + + static bool AsyncWait(CompletionQueue* cq, SyncRequest** req, bool* ok, + gpr_timespec deadline) { + void* tag = nullptr; + *ok = false; + switch (cq->AsyncNext(&tag, ok, deadline)) { + case CompletionQueue::TIMEOUT: + *req = nullptr; + return true; + case CompletionQueue::SHUTDOWN: + *req = nullptr; + return false; + case CompletionQueue::GOT_EVENT: + *req = static_cast(tag); + GPR_ASSERT((*req)->in_flight_); + return true; + } + GPR_UNREACHABLE_CODE(return false); + } + + void SetupRequest() { cq_ = grpc_completion_queue_create(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; + if (tag_) { + GPR_ASSERT(GRPC_CALL_OK == + grpc_server_request_registered_call( + server, tag_, &call_, &deadline_, &request_metadata_, + has_request_payload_ ? &request_payload_ : nullptr, cq_, + notify_cq, this)); + } else { + if (!call_details_) { + call_details_ = new grpc_call_details; + grpc_call_details_init(call_details_); + } + GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call( + server, &call_, call_details_, + &request_metadata_, cq_, notify_cq, this)); + } + } + + bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { + if (!*status) { + grpc_completion_queue_destroy(cq_); + } + if (call_details_) { + deadline_ = call_details_->deadline; + grpc_call_details_destroy(call_details_); + grpc_call_details_init(call_details_); + } + return true; + } + + class CallData GRPC_FINAL { + public: + explicit CallData(Server* server, SyncRequest* mrd) + : cq_(mrd->cq_), + call_(mrd->call_, server, &cq_, server->max_message_size_), + ctx_(mrd->deadline_, mrd->request_metadata_.metadata, + mrd->request_metadata_.count), + has_request_payload_(mrd->has_request_payload_), + request_payload_(mrd->request_payload_), + method_(mrd->method_) { + 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(std::shared_ptr global_callbacks) { + ctx_.BeginCompletionOp(&call_); + global_callbacks->PreSynchronousRequest(&ctx_); + method_->handler()->RunHandler(MethodHandler::HandlerParameter( + &call_, &ctx_, request_payload_, call_.max_message_size())); + global_callbacks->PostSynchronousRequest(&ctx_); + request_payload_ = nullptr; + void* ignored_tag; + bool ignored_ok; + cq_.Shutdown(); + GPR_ASSERT(cq_.Next(&ignored_tag, &ignored_ok) == false); + } + + private: + CompletionQueue cq_; + Call call_; + ServerContext ctx_; + const bool has_request_payload_; + grpc_byte_buffer* request_payload_; + RpcServiceMethod* const method_; + }; + + private: + RpcServiceMethod* const method_; + void* const tag_; + bool in_flight_; + const bool has_request_payload_; + uint32_t incoming_flags_; + 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_; +}; + +static internal::GrpcLibraryInitializer g_gli_initializer; +Server::Server(ThreadPoolInterface* thread_pool, bool thread_pool_owned, + int max_message_size, ChannelArguments* args) + : max_message_size_(max_message_size), + started_(false), + shutdown_(false), + shutdown_notified_(false), + num_running_cb_(0), + sync_methods_(new std::list), + has_generic_service_(false), + server_(nullptr), + thread_pool_(thread_pool), + thread_pool_owned_(thread_pool_owned), + server_initializer_(new ServerInitializer(this)) { + g_gli_initializer.summon(); + gpr_once_init(&g_once_init_callbacks, InitGlobalCallbacks); + global_callbacks_ = g_callbacks; + global_callbacks_->UpdateArguments(args); + grpc_channel_args channel_args; + args->SetChannelArgs(&channel_args); + server_ = grpc_server_create(&channel_args, nullptr); + if (thread_pool_ == nullptr) { + grpc_server_register_non_listening_completion_queue(server_, cq_.cq(), + nullptr); + } else { + grpc_server_register_completion_queue(server_, cq_.cq(), nullptr); + } +} + +Server::~Server() { + { + grpc::unique_lock lock(mu_); + if (started_ && !shutdown_) { + lock.unlock(); + Shutdown(); + } else if (!started_) { + cq_.Shutdown(); + } + } + void* got_tag; + bool ok; + GPR_ASSERT(!cq_.Next(&got_tag, &ok)); + grpc_server_destroy(server_); + if (thread_pool_owned_) { + delete thread_pool_; + } + delete sync_methods_; +} + +void Server::SetGlobalCallbacks(GlobalCallbacks* callbacks) { + GPR_ASSERT(!g_callbacks); + GPR_ASSERT(callbacks); + g_callbacks.reset(callbacks); +} + +grpc_server* Server::c_server() { return server_; } + +CompletionQueue* Server::completion_queue() { return &cq_; } + +static grpc_server_register_method_payload_handling PayloadHandlingForMethod( + RpcServiceMethod* method) { + switch (method->method_type()) { + case RpcMethod::NORMAL_RPC: + case RpcMethod::SERVER_STREAMING: + return GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER; + case RpcMethod::CLIENT_STREAMING: + case RpcMethod::BIDI_STREAMING: + return GRPC_SRM_PAYLOAD_NONE; + } + GPR_UNREACHABLE_CODE(return GRPC_SRM_PAYLOAD_NONE;); +} + +bool Server::RegisterService(const grpc::string* host, 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; + for (auto it = service->methods_.begin(); it != service->methods_.end(); + ++it) { + if (it->get() == nullptr) { // Handled by generic service if any. + continue; + } + RpcServiceMethod* method = it->get(); + void* tag = grpc_server_register_method( + server_, method->name(), host ? host->c_str() : nullptr, + PayloadHandlingForMethod(method), 0); + if (tag == nullptr) { + gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", + method->name()); + return false; + } + if (method->handler() == nullptr) { + method->set_server_tag(tag); + } else { + sync_methods_->emplace_back(method, tag); + } + method_name = method->name(); + } + + // Parse service name. + if (method_name != nullptr) { + std::stringstream ss(method_name); + grpc::string service_name; + if (std::getline(ss, service_name, '/') && + std::getline(ss, service_name, '/')) { + services_.push_back(service_name); + } + } + return true; +} + +void Server::RegisterAsyncGenericService(AsyncGenericService* service) { + GPR_ASSERT(service->server_ == nullptr && + "Can only register an async generic service against one server."); + service->server_ = this; + has_generic_service_ = true; +} + +int Server::AddListeningPort(const grpc::string& addr, + ServerCredentials* creds) { + GPR_ASSERT(!started_); + return creds->AddPortToServer(addr, server_); +} + +bool Server::Start(ServerCompletionQueue** cqs, size_t num_cqs) { + GPR_ASSERT(!started_); + started_ = true; + grpc_server_start(server_); + + if (!has_generic_service_) { + if (!sync_methods_->empty()) { + unknown_method_.reset(new RpcServiceMethod( + "unknown", RpcMethod::BIDI_STREAMING, new UnknownMethodHandler)); + // Use of emplace_back with just constructor arguments is not accepted + // here by gcc-4.4 because it can't match the anonymous nullptr with a + // proper constructor implicitly. Construct the object and use push_back. + sync_methods_->push_back(SyncRequest(unknown_method_.get(), nullptr)); + } + for (size_t i = 0; i < num_cqs; i++) { + if (cqs[i]->IsFrequentlyPolled()) { + new UnimplementedAsyncRequest(this, cqs[i]); + } + } + } + // Start processing rpcs. + if (!sync_methods_->empty()) { + for (auto m = sync_methods_->begin(); m != sync_methods_->end(); m++) { + m->SetupRequest(); + m->Request(server_, cq_.cq()); + } + + ScheduleCallback(); + } + + return true; +} + +void Server::ShutdownInternal(gpr_timespec deadline) { + grpc::unique_lock lock(mu_); + if (started_ && !shutdown_) { + shutdown_ = true; + grpc_server_shutdown_and_notify(server_, cq_.cq(), new ShutdownRequest()); + cq_.Shutdown(); + lock.unlock(); + // Spin, eating requests until the completion queue is completely shutdown. + // If the deadline expires then cancel anything that's pending and keep + // spinning forever until the work is actually drained. + // Since nothing else needs to touch state guarded by mu_, holding it + // through this loop is fine. + SyncRequest* request; + bool ok; + while (SyncRequest::AsyncWait(&cq_, &request, &ok, deadline)) { + if (request == NULL) { // deadline expired + grpc_server_cancel_all_calls(server_); + deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC); + } else if (ok) { + SyncRequest::CallData call_data(this, request); + } + } + lock.lock(); + + // Wait for running callbacks to finish. + while (num_running_cb_ != 0) { + callback_cv_.wait(lock); + } + + shutdown_notified_ = true; + shutdown_cv_.notify_all(); + } +} + +void Server::Wait() { + grpc::unique_lock lock(mu_); + while (started_ && !shutdown_notified_) { + shutdown_cv_.wait(lock); + } +} + +void Server::PerformOpsOnCall(CallOpSetInterface* ops, Call* call) { + static const size_t MAX_OPS = 8; + size_t nops = 0; + grpc_op cops[MAX_OPS]; + ops->FillOps(cops, &nops); + auto result = grpc_call_start_batch(call->call(), cops, nops, ops, nullptr); + GPR_ASSERT(GRPC_CALL_OK == result); +} + +ServerInterface::BaseAsyncRequest::BaseAsyncRequest( + ServerInterface* server, ServerContext* context, + ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag, + bool delete_on_finalize) + : server_(server), + context_(context), + stream_(stream), + call_cq_(call_cq), + tag_(tag), + delete_on_finalize_(delete_on_finalize), + call_(nullptr) { + memset(&initial_metadata_array_, 0, sizeof(initial_metadata_array_)); +} + +bool ServerInterface::BaseAsyncRequest::FinalizeResult(void** tag, + bool* status) { + if (*status) { + for (size_t i = 0; i < initial_metadata_array_.count; i++) { + context_->client_metadata_.insert( + std::pair( + initial_metadata_array_.metadata[i].key, + grpc::string_ref( + initial_metadata_array_.metadata[i].value, + initial_metadata_array_.metadata[i].value_length))); + } + } + grpc_metadata_array_destroy(&initial_metadata_array_); + context_->set_call(call_); + context_->cq_ = call_cq_; + Call call(call_, server_, call_cq_, server_->max_message_size()); + if (*status && call_) { + context_->BeginCompletionOp(&call); + } + // just the pointers inside call are copied here + stream_->BindCall(&call); + *tag = tag_; + if (delete_on_finalize_) { + delete this; + } + return true; +} + +ServerInterface::RegisteredAsyncRequest::RegisteredAsyncRequest( + ServerInterface* server, ServerContext* context, + ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag) + : BaseAsyncRequest(server, context, stream, call_cq, tag, true) {} + +void ServerInterface::RegisteredAsyncRequest::IssueRequest( + void* registered_method, grpc_byte_buffer** payload, + ServerCompletionQueue* notification_cq) { + grpc_server_request_registered_call( + server_->server(), registered_method, &call_, &context_->deadline_, + &initial_metadata_array_, payload, call_cq_->cq(), notification_cq->cq(), + this); +} + +ServerInterface::GenericAsyncRequest::GenericAsyncRequest( + ServerInterface* server, GenericServerContext* context, + ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, + ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize) + : BaseAsyncRequest(server, context, stream, call_cq, tag, + delete_on_finalize) { + grpc_call_details_init(&call_details_); + GPR_ASSERT(notification_cq); + GPR_ASSERT(call_cq); + grpc_server_request_call(server->server(), &call_, &call_details_, + &initial_metadata_array_, call_cq->cq(), + notification_cq->cq(), this); +} + +bool ServerInterface::GenericAsyncRequest::FinalizeResult(void** tag, + bool* status) { + // TODO(yangg) remove the copy here. + if (*status) { + static_cast(context_)->method_ = + call_details_.method; + static_cast(context_)->host_ = call_details_.host; + } + gpr_free(call_details_.method); + gpr_free(call_details_.host); + return BaseAsyncRequest::FinalizeResult(tag, status); +} + +bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag, + bool* status) { + if (GenericAsyncRequest::FinalizeResult(tag, status) && *status) { + new UnimplementedAsyncRequest(server_, cq_); + new UnimplementedAsyncResponse(this); + } else { + delete this; + } + return false; +} + +Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse( + UnimplementedAsyncRequest* request) + : request_(request) { + Status status(StatusCode::UNIMPLEMENTED, ""); + UnknownMethodHandler::FillOps(request_->context(), this); + request_->stream()->call_.PerformOps(this); +} + +void Server::ScheduleCallback() { + { + grpc::unique_lock lock(mu_); + num_running_cb_++; + } + thread_pool_->Add(std::bind(&Server::RunRpc, this)); +} + +void Server::RunRpc() { + // Wait for one more incoming rpc. + bool ok; + GPR_TIMER_SCOPE("Server::RunRpc", 0); + auto* mrd = SyncRequest::Wait(&cq_, &ok); + if (mrd) { + ScheduleCallback(); + if (ok) { + SyncRequest::CallData cd(this, mrd); + { + mrd->SetupRequest(); + grpc::unique_lock lock(mu_); + if (!shutdown_) { + mrd->Request(server_, cq_.cq()); + } else { + // destroy the structure that was created + mrd->TeardownRequest(); + } + } + GPR_TIMER_SCOPE("cd.Run()", 0); + cd.Run(global_callbacks_); + } + } + + { + grpc::unique_lock lock(mu_); + num_running_cb_--; + if (shutdown_) { + callback_cv_.notify_all(); + } + } +} + +ServerInitializer* Server::initializer() { return server_initializer_.get(); } + +} // namespace grpc diff --git a/src/cpp/util/byte_buffer.cc b/src/cpp/util/byte_buffer.cc deleted file mode 100644 index c2cd20ee07..0000000000 --- a/src/cpp/util/byte_buffer.cc +++ /dev/null @@ -1,98 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#include -#include - -namespace grpc { - -ByteBuffer::ByteBuffer(const Slice* slices, size_t nslices) { - // TODO(yangg) maybe expose some core API to simplify this - std::vector c_slices(nslices); - for (size_t i = 0; i < nslices; i++) { - c_slices[i] = slices[i].slice_; - } - buffer_ = grpc_raw_byte_buffer_create(c_slices.data(), nslices); -} - -ByteBuffer::~ByteBuffer() { - if (buffer_) { - grpc_byte_buffer_destroy(buffer_); - } -} - -void ByteBuffer::Clear() { - if (buffer_) { - grpc_byte_buffer_destroy(buffer_); - buffer_ = nullptr; - } -} - -Status ByteBuffer::Dump(std::vector* 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"); - } - gpr_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; -} - -size_t ByteBuffer::Length() const { - if (buffer_) { - return grpc_byte_buffer_length(buffer_); - } else { - return 0; - } -} - -ByteBuffer::ByteBuffer(const ByteBuffer& buf) - : buffer_(grpc_byte_buffer_copy(buf.buffer_)) {} - -ByteBuffer& ByteBuffer::operator=(const ByteBuffer& buf) { - Clear(); // first remove existing data - if (buf.buffer_) { - buffer_ = grpc_byte_buffer_copy(buf.buffer_); // then copy - } - return *this; -} - -} // namespace grpc diff --git a/src/cpp/util/byte_buffer_cc.cc b/src/cpp/util/byte_buffer_cc.cc new file mode 100644 index 0000000000..c2cd20ee07 --- /dev/null +++ b/src/cpp/util/byte_buffer_cc.cc @@ -0,0 +1,98 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include +#include + +namespace grpc { + +ByteBuffer::ByteBuffer(const Slice* slices, size_t nslices) { + // TODO(yangg) maybe expose some core API to simplify this + std::vector c_slices(nslices); + for (size_t i = 0; i < nslices; i++) { + c_slices[i] = slices[i].slice_; + } + buffer_ = grpc_raw_byte_buffer_create(c_slices.data(), nslices); +} + +ByteBuffer::~ByteBuffer() { + if (buffer_) { + grpc_byte_buffer_destroy(buffer_); + } +} + +void ByteBuffer::Clear() { + if (buffer_) { + grpc_byte_buffer_destroy(buffer_); + buffer_ = nullptr; + } +} + +Status ByteBuffer::Dump(std::vector* 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"); + } + gpr_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; +} + +size_t ByteBuffer::Length() const { + if (buffer_) { + return grpc_byte_buffer_length(buffer_); + } else { + return 0; + } +} + +ByteBuffer::ByteBuffer(const ByteBuffer& buf) + : buffer_(grpc_byte_buffer_copy(buf.buffer_)) {} + +ByteBuffer& ByteBuffer::operator=(const ByteBuffer& buf) { + Clear(); // first remove existing data + if (buf.buffer_) { + buffer_ = grpc_byte_buffer_copy(buf.buffer_); // then copy + } + return *this; +} + +} // namespace grpc diff --git a/src/cpp/util/slice.cc b/src/cpp/util/slice.cc deleted file mode 100644 index 7e88423b6c..0000000000 --- a/src/cpp/util/slice.cc +++ /dev/null @@ -1,48 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#include - -namespace grpc { - -Slice::Slice() : slice_(gpr_empty_slice()) {} - -Slice::~Slice() { gpr_slice_unref(slice_); } - -Slice::Slice(gpr_slice slice, AddRef) : slice_(gpr_slice_ref(slice)) {} - -Slice::Slice(gpr_slice slice, StealRef) : slice_(slice) {} - -Slice::Slice(const Slice& other) : slice_(gpr_slice_ref(other.slice_)) {} - -} // namespace grpc diff --git a/src/cpp/util/slice_cc.cc b/src/cpp/util/slice_cc.cc new file mode 100644 index 0000000000..7e88423b6c --- /dev/null +++ b/src/cpp/util/slice_cc.cc @@ -0,0 +1,48 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include + +namespace grpc { + +Slice::Slice() : slice_(gpr_empty_slice()) {} + +Slice::~Slice() { gpr_slice_unref(slice_); } + +Slice::Slice(gpr_slice slice, AddRef) : slice_(gpr_slice_ref(slice)) {} + +Slice::Slice(gpr_slice slice, StealRef) : slice_(slice) {} + +Slice::Slice(const Slice& other) : slice_(gpr_slice_ref(other.slice_)) {} + +} // namespace grpc diff --git a/src/cpp/util/time.cc b/src/cpp/util/time.cc deleted file mode 100644 index c43d848cc6..0000000000 --- a/src/cpp/util/time.cc +++ /dev/null @@ -1,95 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#include - -#ifndef GRPC_CXX0X_NO_CHRONO - -#include -#include - -using std::chrono::duration_cast; -using std::chrono::nanoseconds; -using std::chrono::seconds; -using std::chrono::system_clock; -using std::chrono::high_resolution_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(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(deadline - secs); - to->tv_sec = (int64_t)secs.count(); - to->tv_nsec = (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(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(deadline - secs); - to->tv_sec = (int64_t)secs.count(); - to->tv_nsec = (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(seconds(t.tv_sec)); - tp += - duration_cast(nanoseconds(t.tv_nsec)); - return tp; -} - -} // namespace grpc - -#endif // !GRPC_CXX0X_NO_CHRONO diff --git a/src/cpp/util/time_cc.cc b/src/cpp/util/time_cc.cc new file mode 100644 index 0000000000..c43d848cc6 --- /dev/null +++ b/src/cpp/util/time_cc.cc @@ -0,0 +1,95 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include + +#ifndef GRPC_CXX0X_NO_CHRONO + +#include +#include + +using std::chrono::duration_cast; +using std::chrono::nanoseconds; +using std::chrono::seconds; +using std::chrono::system_clock; +using std::chrono::high_resolution_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(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(deadline - secs); + to->tv_sec = (int64_t)secs.count(); + to->tv_nsec = (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(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(deadline - secs); + to->tv_sec = (int64_t)secs.count(); + to->tv_nsec = (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(seconds(t.tv_sec)); + tp += + duration_cast(nanoseconds(t.tv_nsec)); + return tp; +} + +} // namespace grpc + +#endif // !GRPC_CXX0X_NO_CHRONO diff --git a/test/cpp/util/test_config.cc b/test/cpp/util/test_config.cc deleted file mode 100644 index 8711746129..0000000000 --- a/test/cpp/util/test_config.cc +++ /dev/null @@ -1,52 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#include "test/cpp/util/test_config.h" -#include - -// In some distros, gflags is in the namespace google, and in some others, -// in gflags. This hack is enabling us to find both. -namespace google {} -namespace gflags {} -using namespace google; -using namespace gflags; - -namespace grpc { -namespace testing { - -void InitTest(int* argc, char*** argv, bool remove_flags) { - ParseCommandLineFlags(argc, argv, remove_flags); -} - -} // namespace testing -} // namespace grpc diff --git a/test/cpp/util/test_config_cc.cc b/test/cpp/util/test_config_cc.cc new file mode 100644 index 0000000000..8711746129 --- /dev/null +++ b/test/cpp/util/test_config_cc.cc @@ -0,0 +1,52 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "test/cpp/util/test_config.h" +#include + +// In some distros, gflags is in the namespace google, and in some others, +// in gflags. This hack is enabling us to find both. +namespace google {} +namespace gflags {} +using namespace google; +using namespace gflags; + +namespace grpc { +namespace testing { + +void InitTest(int* argc, char*** argv, bool remove_flags) { + ParseCommandLineFlags(argc, argv, remove_flags); +} + +} // namespace testing +} // namespace grpc diff --git a/tools/doxygen/Doxyfile.c++.internal b/tools/doxygen/Doxyfile.c++.internal index 8d38d9a36f..67312d7ad4 100644 --- a/tools/doxygen/Doxyfile.c++.internal +++ b/tools/doxygen/Doxyfile.c++.internal @@ -956,32 +956,32 @@ src/cpp/common/secure_auth_context.cc \ src/cpp/common/secure_channel_arguments.cc \ src/cpp/common/secure_create_auth_context.cc \ src/cpp/server/secure_server_credentials.cc \ -src/cpp/client/channel.cc \ +src/cpp/client/channel_cc.cc \ src/cpp/client/client_context.cc \ src/cpp/client/create_channel.cc \ src/cpp/client/create_channel_internal.cc \ src/cpp/client/create_channel_posix.cc \ -src/cpp/client/credentials.cc \ +src/cpp/client/credentials_cc.cc \ src/cpp/client/generic_stub.cc \ src/cpp/client/insecure_credentials.cc \ src/cpp/common/channel_arguments.cc \ -src/cpp/common/completion_queue.cc \ +src/cpp/common/completion_queue_cc.cc \ src/cpp/common/core_codegen.cc \ src/cpp/common/rpc_method.cc \ src/cpp/server/async_generic_service.cc \ src/cpp/server/create_default_thread_pool.cc \ src/cpp/server/dynamic_thread_pool.cc \ src/cpp/server/insecure_server_credentials.cc \ -src/cpp/server/server.cc \ src/cpp/server/server_builder.cc \ +src/cpp/server/server_cc.cc \ src/cpp/server/server_context.cc \ src/cpp/server/server_credentials.cc \ src/cpp/server/server_posix.cc \ -src/cpp/util/byte_buffer.cc \ -src/cpp/util/slice.cc \ +src/cpp/util/byte_buffer_cc.cc \ +src/cpp/util/slice_cc.cc \ src/cpp/util/status.cc \ src/cpp/util/string_ref.cc \ -src/cpp/util/time.cc \ +src/cpp/util/time_cc.cc \ src/core/lib/channel/channel_args.c \ src/core/lib/channel/channel_stack.c \ src/core/lib/channel/channel_stack_builder.c \ diff --git a/tools/run_tests/sanity/check_sources_and_headers.py b/tools/run_tests/sanity/check_sources_and_headers.py index c028499ca6..524640942e 100755 --- a/tools/run_tests/sanity/check_sources_and_headers.py +++ b/tools/run_tests/sanity/check_sources_and_headers.py @@ -62,7 +62,8 @@ def target_has_header(target, name): def produces_object(name): return os.path.splitext(name)[1] in ['.c', '.cc'] -obj_producer_to_source = {'c': {}, 'c++': {}, 'csharp': {}} +c_ish = {} +obj_producer_to_source = {'c': c_ish, 'c++': c_ish, 'csharp': {}} errors = 0 for target in js: @@ -85,7 +86,7 @@ for target in js: 'target %s (%s) does not name header %s as a dependency' % ( target['name'], fn, m.group(1))) errors += 1 - if target['type'] == 'lib': + if target['type'] in ['lib', 'filegroup']: for fn in target['src']: language = target['language'] if produces_object(fn): diff --git a/tools/run_tests/sources_and_headers.json b/tools/run_tests/sources_and_headers.json index cd1757acec..9295a2a88e 100644 --- a/tools/run_tests/sources_and_headers.json +++ b/tools/run_tests/sources_and_headers.json @@ -4392,8 +4392,8 @@ "language": "c++", "name": "grpc++_test_config", "src": [ - "test/cpp/util/test_config.cc", - "test/cpp/util/test_config.h" + "test/cpp/util/test_config.h", + "test/cpp/util/test_config_cc.cc" ], "third_party": false, "type": "lib" @@ -6605,17 +6605,17 @@ "include/grpc++/support/stub_options.h", "include/grpc++/support/sync_stream.h", "include/grpc++/support/time.h", - "src/cpp/client/channel.cc", + "src/cpp/client/channel_cc.cc", "src/cpp/client/client_context.cc", "src/cpp/client/create_channel.cc", "src/cpp/client/create_channel_internal.cc", "src/cpp/client/create_channel_internal.h", "src/cpp/client/create_channel_posix.cc", - "src/cpp/client/credentials.cc", + "src/cpp/client/credentials_cc.cc", "src/cpp/client/generic_stub.cc", "src/cpp/client/insecure_credentials.cc", "src/cpp/common/channel_arguments.cc", - "src/cpp/common/completion_queue.cc", + "src/cpp/common/completion_queue_cc.cc", "src/cpp/common/core_codegen.cc", "src/cpp/common/rpc_method.cc", "src/cpp/server/async_generic_service.cc", @@ -6623,17 +6623,17 @@ "src/cpp/server/dynamic_thread_pool.cc", "src/cpp/server/dynamic_thread_pool.h", "src/cpp/server/insecure_server_credentials.cc", - "src/cpp/server/server.cc", "src/cpp/server/server_builder.cc", + "src/cpp/server/server_cc.cc", "src/cpp/server/server_context.cc", "src/cpp/server/server_credentials.cc", "src/cpp/server/server_posix.cc", "src/cpp/server/thread_pool_interface.h", - "src/cpp/util/byte_buffer.cc", - "src/cpp/util/slice.cc", + "src/cpp/util/byte_buffer_cc.cc", + "src/cpp/util/slice_cc.cc", "src/cpp/util/status.cc", "src/cpp/util/string_ref.cc", - "src/cpp/util/time.cc" + "src/cpp/util/time_cc.cc" ], "third_party": false, "type": "filegroup" diff --git a/vsprojects/vcxproj/grpc++/grpc++.vcxproj b/vsprojects/vcxproj/grpc++/grpc++.vcxproj index c50fc4a86d..cd459ae194 100644 --- a/vsprojects/vcxproj/grpc++/grpc++.vcxproj +++ b/vsprojects/vcxproj/grpc++/grpc++.vcxproj @@ -464,7 +464,7 @@ - + @@ -474,7 +474,7 @@ - + @@ -482,7 +482,7 @@ - + @@ -496,25 +496,25 @@ - - + + - + - + - + diff --git a/vsprojects/vcxproj/grpc++/grpc++.vcxproj.filters b/vsprojects/vcxproj/grpc++/grpc++.vcxproj.filters index a68ac33157..30ad03941f 100644 --- a/vsprojects/vcxproj/grpc++/grpc++.vcxproj.filters +++ b/vsprojects/vcxproj/grpc++/grpc++.vcxproj.filters @@ -19,7 +19,7 @@ src\cpp\server - + src\cpp\client @@ -34,7 +34,7 @@ src\cpp\client - + src\cpp\client @@ -46,7 +46,7 @@ src\cpp\common - + src\cpp\common @@ -67,10 +67,10 @@ src\cpp\server - + src\cpp\server - + src\cpp\server @@ -82,10 +82,10 @@ src\cpp\server - + src\cpp\util - + src\cpp\util @@ -94,7 +94,7 @@ src\cpp\util - + src\cpp\util diff --git a/vsprojects/vcxproj/grpc++_test_config/grpc++_test_config.vcxproj b/vsprojects/vcxproj/grpc++_test_config/grpc++_test_config.vcxproj index 5eab788e4c..cf07e21da4 100644 --- a/vsprojects/vcxproj/grpc++_test_config/grpc++_test_config.vcxproj +++ b/vsprojects/vcxproj/grpc++_test_config/grpc++_test_config.vcxproj @@ -150,7 +150,7 @@ - + diff --git a/vsprojects/vcxproj/grpc++_test_config/grpc++_test_config.vcxproj.filters b/vsprojects/vcxproj/grpc++_test_config/grpc++_test_config.vcxproj.filters index b4d4134b05..73e36148f2 100644 --- a/vsprojects/vcxproj/grpc++_test_config/grpc++_test_config.vcxproj.filters +++ b/vsprojects/vcxproj/grpc++_test_config/grpc++_test_config.vcxproj.filters @@ -1,7 +1,7 @@ - + test\cpp\util diff --git a/vsprojects/vcxproj/grpc++_unsecure/grpc++_unsecure.vcxproj b/vsprojects/vcxproj/grpc++_unsecure/grpc++_unsecure.vcxproj index 3a4aa13527..527c5c6918 100644 --- a/vsprojects/vcxproj/grpc++_unsecure/grpc++_unsecure.vcxproj +++ b/vsprojects/vcxproj/grpc++_unsecure/grpc++_unsecure.vcxproj @@ -450,7 +450,7 @@ - + @@ -460,7 +460,7 @@ - + @@ -468,7 +468,7 @@ - + @@ -482,25 +482,25 @@ - - + + - + - + - + diff --git a/vsprojects/vcxproj/grpc++_unsecure/grpc++_unsecure.vcxproj.filters b/vsprojects/vcxproj/grpc++_unsecure/grpc++_unsecure.vcxproj.filters index 56b434433b..6b9ca058c5 100644 --- a/vsprojects/vcxproj/grpc++_unsecure/grpc++_unsecure.vcxproj.filters +++ b/vsprojects/vcxproj/grpc++_unsecure/grpc++_unsecure.vcxproj.filters @@ -4,7 +4,7 @@ src\cpp\common - + src\cpp\client @@ -19,7 +19,7 @@ src\cpp\client - + src\cpp\client @@ -31,7 +31,7 @@ src\cpp\common - + src\cpp\common @@ -52,10 +52,10 @@ src\cpp\server - + src\cpp\server - + src\cpp\server @@ -67,10 +67,10 @@ src\cpp\server - + src\cpp\util - + src\cpp\util @@ -79,7 +79,7 @@ src\cpp\util - + src\cpp\util -- cgit v1.2.3 From 7603d64982ea5de924218d600a851d6c8a4e6415 Mon Sep 17 00:00:00 2001 From: Jorge Canizales Date: Wed, 24 Aug 2016 18:23:24 -0700 Subject: Let tracing be enabled before starting an RPC by calling grpc_init on [GRPCCall load], instead of lazily. --- src/objective-c/GRPCClient/GRPCCall.m | 5 +++++ src/objective-c/GRPCClient/private/GRPCWrappedCall.m | 5 ----- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/objective-c/GRPCClient/GRPCCall.m b/src/objective-c/GRPCClient/GRPCCall.m index da9473f9a2..b5d8309787 100644 --- a/src/objective-c/GRPCClient/GRPCCall.m +++ b/src/objective-c/GRPCClient/GRPCCall.m @@ -103,6 +103,11 @@ NSString * const kGRPCTrailersKey = @"io.grpc.TrailersKey"; @synthesize state = _state; +// TODO(jcanizales): If grpc_init is idempotent, this should be changed from load to initialize. ++ (void)load { + grpc_init(); +} + - (instancetype)init { return [self initWithHost:nil path:nil requestsWriter:nil]; } diff --git a/src/objective-c/GRPCClient/private/GRPCWrappedCall.m b/src/objective-c/GRPCClient/private/GRPCWrappedCall.m index 97f6b89340..1339429660 100644 --- a/src/objective-c/GRPCClient/private/GRPCWrappedCall.m +++ b/src/objective-c/GRPCClient/private/GRPCWrappedCall.m @@ -245,11 +245,6 @@ } if (self = [super init]) { - static dispatch_once_t initialization; - dispatch_once(&initialization, ^{ - grpc_init(); - }); - // Each completion queue consumes one thread. There's a trade to be made between creating and // consuming too many threads and having contention of multiple calls in a single completion // queue. Currently we use a singleton queue. -- cgit v1.2.3 From b15811e36d5b1885293413219fb546f6d93ebf0f Mon Sep 17 00:00:00 2001 From: Stanley Cheung Date: Fri, 26 Aug 2016 15:23:28 -0700 Subject: php: fix per_rpc_creds capital auth header key --- src/php/tests/interop/interop_client.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/php/tests/interop/interop_client.php b/src/php/tests/interop/interop_client.php index bf40549a04..7f8354e236 100755 --- a/src/php/tests/interop/interop_client.php +++ b/src/php/tests/interop/interop_client.php @@ -197,7 +197,12 @@ function updateAuthMetadataCallback($context) $methodName = $context->method_name; $auth_credentials = ApplicationDefaultCredentials::getCredentials(); - return $auth_credentials->updateMetadata($metadata = [], $authUri); + $metadata = []; + $result = $auth_credentials->updateMetadata([], $authUri); + foreach ($result as $key => $value) { + $metadata[strtolower($key)] = $value; + } + return $metadata; } /** -- cgit v1.2.3 From 14e2a566c9a36c884c9d92be6bc506a8959254f3 Mon Sep 17 00:00:00 2001 From: Stanley Cheung Date: Fri, 26 Aug 2016 19:52:35 -0700 Subject: php: error out if metadata key is not legal --- package.xml | 4 +- src/php/ext/grpc/call.c | 3 + src/php/ext/grpc/call_credentials.c | 20 +--- src/php/tests/interop/interop_client.php | 30 ++--- src/php/tests/unit_tests/CallCredentials2Test.php | 65 +++++++++++ src/php/tests/unit_tests/CallCredentials3Test.php | 135 ---------------------- src/php/tests/unit_tests/CallTest.php | 24 +++- templates/package.xml.template | 4 +- 8 files changed, 118 insertions(+), 167 deletions(-) delete mode 100644 src/php/tests/unit_tests/CallCredentials3Test.php (limited to 'src') diff --git a/package.xml b/package.xml index 6e3aab7a76..7da3d48a07 100644 --- a/package.xml +++ b/package.xml @@ -22,7 +22,7 @@ BSD -- TBD +- Reject metadata keys which are not legal #7881 @@ -1173,7 +1173,7 @@ Update to wrap gRPC C Core version 0.10.0 2016-08-22 BSD -- TBD +- Reject metadata keys which are not legal #7881 diff --git a/src/php/ext/grpc/call.c b/src/php/ext/grpc/call.c index 66ca1513ed..31c59fe5ad 100644 --- a/src/php/ext/grpc/call.c +++ b/src/php/ext/grpc/call.c @@ -164,6 +164,9 @@ bool create_metadata_array(zval *array, grpc_metadata_array *metadata) { if (key_type1 != HASH_KEY_IS_STRING) { return false; } + if (!grpc_header_key_is_legal(key1, strlen(key1))) { + return false; + } inner_array_hash = Z_ARRVAL_P(inner_array); PHP_GRPC_HASH_FOREACH_VAL_START(inner_array_hash, value) if (Z_TYPE_P(value) != IS_STRING) { diff --git a/src/php/ext/grpc/call_credentials.c b/src/php/ext/grpc/call_credentials.c index 6921a5df17..25c92c91fe 100644 --- a/src/php/ext/grpc/call_credentials.c +++ b/src/php/ext/grpc/call_credentials.c @@ -192,24 +192,16 @@ void plugin_get_metadata(void *ptr, grpc_auth_metadata_context context, /* call the user callback function */ zend_call_function(state->fci, state->fci_cache TSRMLS_CC); - if (Z_TYPE_P(retval) != IS_ARRAY) { - zend_throw_exception(spl_ce_InvalidArgumentException, - "plugin callback must return metadata array", - 1 TSRMLS_CC); - return; - } - + grpc_status_code code = GRPC_STATUS_OK; grpc_metadata_array metadata; - if (!create_metadata_array(retval, &metadata)) { - zend_throw_exception(spl_ce_InvalidArgumentException, - "invalid metadata", 1 TSRMLS_CC); + + if (Z_TYPE_P(retval) != IS_ARRAY) { + code = GRPC_STATUS_INVALID_ARGUMENT; + } else if (!create_metadata_array(retval, &metadata)) { grpc_metadata_array_destroy(&metadata); - return; + code = GRPC_STATUS_INVALID_ARGUMENT; } - /* TODO: handle error */ - grpc_status_code code = GRPC_STATUS_OK; - /* Pass control back to core */ cb(user_data, metadata.metadata, metadata.count, code, NULL); } diff --git a/src/php/tests/interop/interop_client.php b/src/php/tests/interop/interop_client.php index 7f8354e236..c94ba61296 100755 --- a/src/php/tests/interop/interop_client.php +++ b/src/php/tests/interop/interop_client.php @@ -54,6 +54,15 @@ function hardAssert($value, $error_message) } } +function hardAssertIfStatusOk($status) +{ + if ($status->code !== Grpc\STATUS_OK) { + echo "Call did not complete successfully. Status object:\n"; + var_dump($status); + exit(1); + } +} + /** * Run the empty_unary test. * @@ -62,7 +71,7 @@ function hardAssert($value, $error_message) function emptyUnary($stub) { list($result, $status) = $stub->EmptyCall(new grpc\testing\EmptyMessage())->wait(); - hardAssert($status->code === Grpc\STATUS_OK, 'Call did not complete successfully'); + hardAssertIfStatusOk($status); hardAssert($result !== null, 'Call completed with a null response'); } @@ -105,7 +114,7 @@ function performLargeUnary($stub, $fillUsername = false, $fillOauthScope = false } list($result, $status) = $stub->UnaryCall($request, [], $options)->wait(); - hardAssert($status->code === Grpc\STATUS_OK, 'Call did not complete successfully'); + hardAssertIfStatusOk($status); hardAssert($result !== null, 'Call returned a null response'); $payload = $result->getPayload(); hardAssert($payload->getType() === grpc\testing\PayloadType::COMPRESSABLE, @@ -247,7 +256,7 @@ function clientStreaming($stub) $call->write($request); } list($result, $status) = $call->wait(); - hardAssert($status->code === Grpc\STATUS_OK, 'Call did not complete successfully'); + hardAssertIfStatusOk($status); hardAssert($result->getAggregatedPayloadSize() === 74922, 'aggregated_payload_size was incorrect'); } @@ -280,8 +289,7 @@ function serverStreaming($stub) 'Response '.$i.' had the wrong length'); $i += 1; } - hardAssert($call->getStatus()->code === Grpc\STATUS_OK, - 'Call did not complete successfully'); + hardAssertIfStatusOk($call->getStatus()); } /** @@ -317,8 +325,7 @@ function pingPong($stub) } $call->writesDone(); hardAssert($call->read() === null, 'Server returned too many responses'); - hardAssert($call->getStatus()->code === Grpc\STATUS_OK, - 'Call did not complete successfully'); + hardAssertIfStatusOk($call->getStatus()); } /** @@ -331,8 +338,7 @@ function emptyStream($stub) $call = $stub->FullDuplexCall(); $call->writesDone(); hardAssert($call->read() === null, 'Server returned too many responses'); - hardAssert($call->getStatus()->code === Grpc\STATUS_OK, - 'Call did not complete successfully'); + hardAssertIfStatusOk($call->getStatus()); } /** @@ -424,8 +430,7 @@ function customMetadata($stub) 'Incorrect initial metadata value'); list($result, $status) = $call->wait(); - hardAssert($status->code === Grpc\STATUS_OK, - 'Call did not complete successfully'); + hardAssertIfStatusOk($status); $trailing_metadata = $call->getTrailingMetadata(); hardAssert(array_key_exists($ECHO_TRAILING_KEY, $trailing_metadata), @@ -440,8 +445,7 @@ function customMetadata($stub) $streaming_call->write($streaming_request); $streaming_call->writesDone(); - hardAssert($streaming_call->getStatus()->code === Grpc\STATUS_OK, - 'Call did not complete successfully'); + hardAssertIfStatusOk($streaming_call->getStatus()); $streaming_trailing_metadata = $streaming_call->getTrailingMetadata(); hardAssert(array_key_exists($ECHO_TRAILING_KEY, diff --git a/src/php/tests/unit_tests/CallCredentials2Test.php b/src/php/tests/unit_tests/CallCredentials2Test.php index a57e2b9b4e..b3b98a22ca 100644 --- a/src/php/tests/unit_tests/CallCredentials2Test.php +++ b/src/php/tests/unit_tests/CallCredentials2Test.php @@ -132,4 +132,69 @@ class CallCredentials2Test extends PHPUnit_Framework_TestCase unset($call); unset($server_call); } + + public function invalidKeyCallbackFunc($context) + { + $this->assertTrue(is_string($context->service_url)); + $this->assertTrue(is_string($context->method_name)); + + return ['K1' => ['v1']]; + } + + public function testCallbackWithInvalidKey() + { + $deadline = Grpc\Timeval::infFuture(); + $status_text = 'xyz'; + $call = new Grpc\Call($this->channel, + '/abc/dummy_method', + $deadline, + $this->host_override); + + $call_credentials = Grpc\CallCredentials::createFromPlugin( + array($this, 'invalidKeyCallbackFunc')); + $call->setCredentials($call_credentials); + + $event = $call->startBatch([ + Grpc\OP_SEND_INITIAL_METADATA => [], + Grpc\OP_SEND_CLOSE_FROM_CLIENT => true, + Grpc\OP_RECV_STATUS_ON_CLIENT => true, + ]); + + $this->assertTrue($event->send_metadata); + $this->assertTrue($event->send_close); + $this->assertTrue($event->status->code == Grpc\STATUS_UNAUTHENTICATED); + } + + public function invalidReturnCallbackFunc($context) + { + $this->assertTrue(is_string($context->service_url)); + $this->assertTrue(is_string($context->method_name)); + + return "a string"; + } + + public function testCallbackWithInvalidReturnValue() + { + $deadline = Grpc\Timeval::infFuture(); + $status_text = 'xyz'; + $call = new Grpc\Call($this->channel, + '/abc/dummy_method', + $deadline, + $this->host_override); + + $call_credentials = Grpc\CallCredentials::createFromPlugin( + array($this, 'invalidReturnCallbackFunc')); + $call->setCredentials($call_credentials); + + $event = $call->startBatch([ + Grpc\OP_SEND_INITIAL_METADATA => [], + Grpc\OP_SEND_CLOSE_FROM_CLIENT => true, + Grpc\OP_RECV_STATUS_ON_CLIENT => true, + ]); + + $this->assertTrue($event->send_metadata); + $this->assertTrue($event->send_close); + $this->assertTrue($event->status->code == Grpc\STATUS_UNAUTHENTICATED); + } + } diff --git a/src/php/tests/unit_tests/CallCredentials3Test.php b/src/php/tests/unit_tests/CallCredentials3Test.php deleted file mode 100644 index 8f5e109bf5..0000000000 --- a/src/php/tests/unit_tests/CallCredentials3Test.php +++ /dev/null @@ -1,135 +0,0 @@ -credentials = Grpc\ChannelCredentials::createSsl( - file_get_contents(dirname(__FILE__).'/../data/ca.pem')); - $server_credentials = Grpc\ServerCredentials::createSsl( - null, - file_get_contents(dirname(__FILE__).'/../data/server1.key'), - file_get_contents(dirname(__FILE__).'/../data/server1.pem')); - $this->server = new Grpc\Server(); - $this->port = $this->server->addSecureHttp2Port('0.0.0.0:0', - $server_credentials); - $this->server->start(); - $this->host_override = 'foo.test.google.fr'; - $this->channel = new Grpc\Channel( - 'localhost:'.$this->port, - [ - 'grpc.ssl_target_name_override' => $this->host_override, - 'grpc.default_authority' => $this->host_override, - 'credentials' => $this->credentials, - ] - ); - } - - public function tearDown() - { - unset($this->channel); - unset($this->server); - } - - public function callbackFunc($context) - { - $this->assertTrue(is_string($context->service_url)); - $this->assertTrue(is_string($context->method_name)); - - return ['k1' => ['v1'], 'k2' => ['v2']]; - } - - public function testCreateFromPlugin() - { - $deadline = Grpc\Timeval::infFuture(); - $status_text = 'xyz'; - $call = new Grpc\Call($this->channel, - '/abc/dummy_method', - $deadline, - $this->host_override); - - $call_credentials = Grpc\CallCredentials::createFromPlugin( - [$this, 'callbackFunc']); - $call->setCredentials($call_credentials); - - $event = $call->startBatch([ - Grpc\OP_SEND_INITIAL_METADATA => [], - Grpc\OP_SEND_CLOSE_FROM_CLIENT => true, - ]); - - $this->assertTrue($event->send_metadata); - $this->assertTrue($event->send_close); - - $event = $this->server->requestCall(); - - $this->assertTrue(is_array($event->metadata)); - $metadata = $event->metadata; - $this->assertTrue(array_key_exists('k1', $metadata)); - $this->assertTrue(array_key_exists('k2', $metadata)); - $this->assertSame($metadata['k1'], ['v1']); - $this->assertSame($metadata['k2'], ['v2']); - - $this->assertSame('/abc/dummy_method', $event->method); - $server_call = $event->call; - - $event = $server_call->startBatch([ - Grpc\OP_SEND_INITIAL_METADATA => [], - Grpc\OP_SEND_STATUS_FROM_SERVER => [ - 'metadata' => [], - 'code' => Grpc\STATUS_OK, - 'details' => $status_text, - ], - Grpc\OP_RECV_CLOSE_ON_SERVER => true, - ]); - - $this->assertTrue($event->send_metadata); - $this->assertTrue($event->send_status); - $this->assertFalse($event->cancelled); - - $event = $call->startBatch([ - Grpc\OP_RECV_INITIAL_METADATA => true, - Grpc\OP_RECV_STATUS_ON_CLIENT => true, - ]); - - $this->assertSame([], $event->metadata); - $status = $event->status; - $this->assertSame([], $status->metadata); - $this->assertSame(Grpc\STATUS_OK, $status->code); - $this->assertSame($status_text, $status->details); - - unset($call); - unset($server_call); - } -} diff --git a/src/php/tests/unit_tests/CallTest.php b/src/php/tests/unit_tests/CallTest.php index d736f51546..1205f0cd8e 100644 --- a/src/php/tests/unit_tests/CallTest.php +++ b/src/php/tests/unit_tests/CallTest.php @@ -113,7 +113,7 @@ class CallTest extends PHPUnit_Framework_TestCase /** * @expectedException InvalidArgumentException */ - public function testInvalidMetadataKey() + public function testInvalidStartBatchKey() { $batch = [ 'invalid' => ['key1' => 'value1'], @@ -121,6 +121,28 @@ class CallTest extends PHPUnit_Framework_TestCase $result = $this->call->startBatch($batch); } + /** + * @expectedException InvalidArgumentException + */ + public function testInvalidMetadataStrKey() + { + $batch = [ + Grpc\OP_SEND_INITIAL_METADATA => ['Key' => ['value1', 'value2']], + ]; + $result = $this->call->startBatch($batch); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testInvalidMetadataIntKey() + { + $batch = [ + Grpc\OP_SEND_INITIAL_METADATA => [1 => ['value1', 'value2']], + ]; + $result = $this->call->startBatch($batch); + } + /** * @expectedException InvalidArgumentException */ diff --git a/templates/package.xml.template b/templates/package.xml.template index 65fef1892f..32ed3b633e 100644 --- a/templates/package.xml.template +++ b/templates/package.xml.template @@ -24,7 +24,7 @@ BSD - - TBD + - Reject metadata keys which are not legal #7881 @@ -291,7 +291,7 @@ 2016-08-22 BSD - - TBD + - Reject metadata keys which are not legal #7881 -- cgit v1.2.3 From 79cf53c992575308526a346d39011f83bbf2f2c9 Mon Sep 17 00:00:00 2001 From: Nathaniel Manista Date: Mon, 29 Aug 2016 16:56:43 +0000 Subject: Lower-case example "Authorization" header name The HTTP/2 specification requires header names to be lower case. --- src/python/grpcio/grpc/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/python/grpcio/grpc/__init__.py b/src/python/grpcio/grpc/__init__.py index 513839df7d..fb3900decc 100644 --- a/src/python/grpcio/grpc/__init__.py +++ b/src/python/grpcio/grpc/__init__.py @@ -1078,7 +1078,7 @@ def access_token_call_credentials(access_token): Args: access_token: A string to place directly in the http request - authorization header, ie "Authorization: Bearer ". + authorization header, ie "authorization: Bearer ". Returns: A CallCredentials. -- cgit v1.2.3 From 38ba85ce48f450d4022547687e55cddbddafd8ab Mon Sep 17 00:00:00 2001 From: Alexander Polcyn Date: Mon, 29 Aug 2016 16:59:23 -0700 Subject: allow choosing config of ruby package builds from environment variable --- Rakefile | 6 ++++-- src/ruby/ext/grpc/extconf.rb | 4 ++++ 2 files changed, 8 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/Rakefile b/Rakefile index 5b6f101d8f..cfd4181d7e 100755 --- a/Rakefile +++ b/Rakefile @@ -100,13 +100,15 @@ desc 'Build the native gem file under rake_compiler_dock' task 'gem:native' do verbose = ENV['V'] || '0' + grpc_config = ENV['GRPC_CONFIG'] || 'opt' + if RUBY_PLATFORM =~ /darwin/ FileUtils.touch 'grpc_c.32.ruby' FileUtils.touch 'grpc_c.64.ruby' - system "rake cross native gem RUBY_CC_VERSION=2.3.0:2.2.2:2.1.5:2.0.0 V=#{verbose}" + system "rake cross native gem RUBY_CC_VERSION=2.3.0:2.2.2:2.1.5:2.0.0 V=#{verbose} GRPC_CONFIG=#{grpc_config}" else Rake::Task['dlls'].execute - docker_for_windows "bundle && rake cross native gem RUBY_CC_VERSION=2.3.0:2.2.2:2.1.5:2.0.0 V=#{verbose}" + docker_for_windows "bundle && rake cross native gem RUBY_CC_VERSION=2.3.0:2.2.2:2.1.5:2.0.0 V=#{verbose} GRPC_CONFIG=#{grpc_config}" end end diff --git a/src/ruby/ext/grpc/extconf.rb b/src/ruby/ext/grpc/extconf.rb index 6d65db8306..66c54aa3e0 100644 --- a/src/ruby/ext/grpc/extconf.rb +++ b/src/ruby/ext/grpc/extconf.rb @@ -91,6 +91,10 @@ if grpc_config == 'gcov' $LDFLAGS << ' -fprofile-arcs -ftest-coverage -rdynamic' end +if grpc_config == 'dbg' + $CFLAGS << ' -O0' +end + $LDFLAGS << ' -Wl,-wrap,memcpy' if RUBY_PLATFORM =~ /linux/ $LDFLAGS << ' -static' if windows -- cgit v1.2.3 From 7c5befd86b56a1eb4d6ed8312d5e722547f39e2d Mon Sep 17 00:00:00 2001 From: murgatroid99 Date: Thu, 1 Sep 2016 17:09:47 -0700 Subject: Change UnimplementedService to UnimplementedEchoService in echo.proto --- src/proto/grpc/testing/echo.proto | 2 +- test/cpp/end2end/async_end2end_test.cc | 4 ++-- test/cpp/end2end/end2end_test.cc | 4 ++-- test/cpp/end2end/hybrid_end2end_test.cc | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/proto/grpc/testing/echo.proto b/src/proto/grpc/testing/echo.proto index c596aabfcc..ca60a41b4f 100644 --- a/src/proto/grpc/testing/echo.proto +++ b/src/proto/grpc/testing/echo.proto @@ -42,7 +42,7 @@ service EchoTestService { rpc Unimplemented(EchoRequest) returns (EchoResponse); } -service UnimplementedService { +service UnimplementedEchoService { rpc Unimplemented(EchoRequest) returns (EchoResponse); } diff --git a/test/cpp/end2end/async_end2end_test.cc b/test/cpp/end2end/async_end2end_test.cc index 4a8936d281..27673c4ea1 100644 --- a/test/cpp/end2end/async_end2end_test.cc +++ b/test/cpp/end2end/async_end2end_test.cc @@ -898,8 +898,8 @@ TEST_P(AsyncEnd2endTest, UnimplementedRpc) { GetChannelCredentials(GetParam().credentials_type, &args); std::shared_ptr channel = CreateCustomChannel(server_address_.str(), channel_creds, args); - std::unique_ptr stub; - stub = grpc::testing::UnimplementedService::NewStub(channel); + std::unique_ptr stub; + stub = grpc::testing::UnimplementedEchoService::NewStub(channel); EchoRequest send_request; EchoResponse recv_response; Status recv_status; diff --git a/test/cpp/end2end/end2end_test.cc b/test/cpp/end2end/end2end_test.cc index 0f87ae3e44..683a71583a 100644 --- a/test/cpp/end2end/end2end_test.cc +++ b/test/cpp/end2end/end2end_test.cc @@ -967,8 +967,8 @@ TEST_P(End2endTest, ChannelStateTimeout) { // Talking to a non-existing service. TEST_P(End2endTest, NonExistingService) { ResetChannel(); - std::unique_ptr stub; - stub = grpc::testing::UnimplementedService::NewStub(channel_); + std::unique_ptr stub; + stub = grpc::testing::UnimplementedEchoService::NewStub(channel_); EchoRequest request; EchoResponse response; diff --git a/test/cpp/end2end/hybrid_end2end_test.cc b/test/cpp/end2end/hybrid_end2end_test.cc index 7e0c0e8a7c..77b0e1f40e 100644 --- a/test/cpp/end2end/hybrid_end2end_test.cc +++ b/test/cpp/end2end/hybrid_end2end_test.cc @@ -346,7 +346,7 @@ class HybridEnd2endTest : public ::testing::Test { EXPECT_TRUE(s.ok()); } - grpc::testing::UnimplementedService::Service unimplemented_service_; + grpc::testing::UnimplementedEchoService::Service unimplemented_service_; std::vector> cqs_; std::unique_ptr stub_; std::unique_ptr server_; -- cgit v1.2.3 From 676565326c061597e5a0f15f5e43db7ddf37fd54 Mon Sep 17 00:00:00 2001 From: Alexander Polcyn Date: Thu, 1 Sep 2016 18:50:13 -0700 Subject: destroy byte buffer reader after use --- src/csharp/ext/grpc_csharp_ext.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/csharp/ext/grpc_csharp_ext.c b/src/csharp/ext/grpc_csharp_ext.c index 3d0947c03d..068bf709b8 100644 --- a/src/csharp/ext/grpc_csharp_ext.c +++ b/src/csharp/ext/grpc_csharp_ext.c @@ -255,8 +255,10 @@ GPR_EXPORT intptr_t GPR_CALLTYPE grpcsharp_batch_context_recv_message_length( } GPR_ASSERT(grpc_byte_buffer_reader_init(&reader, ctx->recv_message)); + intptr_t result = (intptr_t)grpc_byte_buffer_length(reader.buffer_out); + grpc_byte_buffer_reader_destroy(&reader); - return (intptr_t)grpc_byte_buffer_length(reader.buffer_out); + return result; } /* @@ -279,6 +281,8 @@ GPR_EXPORT void GPR_CALLTYPE grpcsharp_batch_context_recv_message_to_buffer( offset += len; gpr_slice_unref(slice); } + + grpc_byte_buffer_reader_destroy(&reader); } GPR_EXPORT grpc_status_code GPR_CALLTYPE -- cgit v1.2.3