Merge branch 'master' into bmchttp2fix

pull/20460/head
Yash Tibrewal 5 years ago
commit a59acd2f4b
  1. 8
      .gitmodules
  2. 9
      BUILD
  3. 4
      BUILD.gn
  4. 42
      CMakeLists.txt
  5. 94
      Makefile
  6. 20
      bazel/grpc_build_system.bzl
  7. 9
      bazel/grpc_deps.bzl
  8. 47
      build.yaml
  9. 47
      doc/core/moving-to-c++.md
  10. 2
      doc/interop-test-descriptions.md
  11. 2
      examples/csharp/HelloworldXamarin/iOS/AppDelegate.cs
  12. 86
      examples/php/echo/README.md
  13. 49
      examples/php/echo/apache.Dockerfile
  14. 38
      examples/php/echo/base.Dockerfile
  15. 52
      examples/php/echo/cli.Dockerfile
  16. 45
      examples/php/echo/client.php
  17. 12
      examples/php/echo/composer.json
  18. 100
      examples/php/echo/echo.proto
  19. 49
      examples/php/echo/fpm.Dockerfile
  20. 23
      examples/php/echo/nginx.conf
  21. 2
      examples/python/cancellation/README.md
  22. 2
      examples/python/cancellation/hash_name.proto
  23. 2
      examples/python/data_transmission/README.en.md
  24. 2
      gRPC-C++.podspec
  25. 4
      gRPC-Core.podspec
  26. 2
      grpc.gemspec
  27. 26
      grpc.gyp
  28. 8
      include/grpc/impl/codegen/port_platform.h
  29. 30
      include/grpcpp/impl/codegen/call_op_set.h
  30. 2
      package.xml
  31. 23
      setup.py
  32. 2
      src/compiler/ruby_generator_string-inl.h
  33. 4
      src/core/ext/filters/client_channel/backend_metric.cc
  34. 151
      src/core/ext/filters/client_channel/client_channel.cc
  35. 30
      src/core/ext/filters/client_channel/client_channel.h
  36. 6
      src/core/ext/filters/client_channel/client_channel_factory.h
  37. 63
      src/core/ext/filters/client_channel/health/health_check_client.cc
  38. 18
      src/core/ext/filters/client_channel/health/health_check_client.h
  39. 2
      src/core/ext/filters/client_channel/http_connect_handshaker.cc
  40. 78
      src/core/ext/filters/client_channel/lb_policy.h
  41. 10
      src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc
  42. 31
      src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc
  43. 17
      src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc
  44. 7
      src/core/ext/filters/client_channel/lb_policy/subchannel_list.h
  45. 150
      src/core/ext/filters/client_channel/lb_policy/xds/xds.cc
  46. 4
      src/core/ext/filters/client_channel/lb_policy/xds/xds_client_stats.cc
  47. 14
      src/core/ext/filters/client_channel/lb_policy/xds/xds_client_stats.h
  48. 17
      src/core/ext/filters/client_channel/lb_policy/xds/xds_load_balancer_api.cc
  49. 2
      src/core/ext/filters/client_channel/lb_policy/xds/xds_load_balancer_api.h
  50. 9
      src/core/ext/filters/client_channel/lb_policy_factory.h
  51. 13
      src/core/ext/filters/client_channel/resolver.h
  52. 5
      src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc
  53. 23
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h
  54. 2
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc
  55. 2
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc
  56. 3
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc
  57. 8
      src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc
  58. 5
      src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc
  59. 13
      src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc
  60. 5
      src/core/ext/filters/client_channel/resolver/xds/xds_resolver.cc
  61. 10
      src/core/ext/filters/client_channel/resolver_factory.h
  62. 17
      src/core/ext/filters/client_channel/resolver_result_parsing.cc
  63. 9
      src/core/ext/filters/client_channel/resolving_lb_policy.cc
  64. 4
      src/core/ext/filters/client_channel/service_config.h
  65. 46
      src/core/ext/filters/client_channel/subchannel.cc
  66. 16
      src/core/ext/filters/client_channel/subchannel.h
  67. 22
      src/core/ext/filters/client_channel/subchannel_interface.h
  68. 9
      src/core/ext/filters/client_channel/subchannel_pool_interface.h
  69. 8
      src/core/ext/filters/message_size/message_size_filter.cc
  70. 739
      src/core/ext/transport/chttp2/transport/chttp2_transport.cc
  71. 5
      src/core/ext/transport/chttp2/transport/flow_control.h
  72. 23
      src/core/ext/transport/chttp2/transport/hpack_parser.cc
  73. 31
      src/core/ext/transport/chttp2/transport/internal.h
  74. 4
      src/core/ext/transport/chttp2/transport/writing.cc
  75. 8
      src/core/lib/channel/channelz.cc
  76. 10
      src/core/lib/channel/channelz.h
  77. 2
      src/core/lib/channel/channelz_registry.h
  78. 7
      src/core/lib/channel/handshaker.h
  79. 4
      src/core/lib/channel/handshaker_factory.h
  80. 47
      src/core/lib/gprpp/abstract.h
  81. 6
      src/core/lib/gprpp/arena.cc
  82. 5
      src/core/lib/gprpp/arena.h
  83. 501
      src/core/lib/gprpp/map.h
  84. 33
      src/core/lib/gprpp/memory.h
  85. 15
      src/core/lib/gprpp/orphanable.h
  86. 38
      src/core/lib/gprpp/pair.h
  87. 9
      src/core/lib/gprpp/ref_counted.h
  88. 6
      src/core/lib/gprpp/thd.h
  89. 39
      src/core/lib/iomgr/closure.h
  90. 13
      src/core/lib/iomgr/executor.cc
  91. 9
      src/core/lib/iomgr/executor/mpmcqueue.h
  92. 13
      src/core/lib/iomgr/executor/threadpool.h
  93. 8
      src/core/lib/iomgr/python_util.h
  94. 5
      src/core/lib/iomgr/tcp_server.h
  95. 16
      src/core/lib/iomgr/udp_server.h
  96. 12
      src/core/lib/security/credentials/credentials.cc
  97. 30
      src/core/lib/security/credentials/credentials.h
  98. 4
      src/core/lib/security/credentials/oauth2/oauth2_credentials.h
  99. 26
      src/core/lib/security/security_connector/security_connector.h
  100. 3
      src/core/lib/security/security_connector/ssl/ssl_security_connector.cc
  101. Some files were not shown because too many files have changed in this diff Show More

8
.gitmodules vendored

@ -34,14 +34,6 @@
[submodule "third_party/abseil-cpp"]
path = third_party/abseil-cpp
url = https://github.com/abseil/abseil-cpp
[submodule "third_party/libcxxabi"]
path = third_party/libcxxabi
url = https://github.com/llvm-mirror/libcxxabi.git
branch = release_60
[submodule "third_party/libcxx"]
path = third_party/libcxx
url = https://github.com/llvm-mirror/libcxx.git
branch = release_60
[submodule "third_party/envoy-api"]
path = third_party/envoy-api
url = https://github.com/envoyproxy/data-plane-api.git

@ -69,11 +69,6 @@ config_setting(
values = {"cpu": "darwin"},
)
config_setting(
name = "grpc_use_cpp_std_lib",
values = {"define": "GRPC_USE_CPP_STD_LIB=1"},
)
python_config_settings()
# This should be updated along with build.yaml
@ -514,7 +509,6 @@ grpc_cc_library(
"src/core/lib/gpr/tls_pthread.h",
"src/core/lib/gpr/tmpfile.h",
"src/core/lib/gpr/useful.h",
"src/core/lib/gprpp/abstract.h",
"src/core/lib/gprpp/arena.h",
"src/core/lib/gprpp/atomic.h",
"src/core/lib/gprpp/fork.h",
@ -527,7 +521,6 @@ grpc_cc_library(
"src/core/lib/gprpp/map.h",
"src/core/lib/gprpp/memory.h",
"src/core/lib/gprpp/mpscq.h",
"src/core/lib/gprpp/pair.h",
"src/core/lib/gprpp/string_view.h",
"src/core/lib/gprpp/sync.h",
"src/core/lib/gprpp/thd.h",
@ -855,7 +848,7 @@ grpc_cc_library(
"src/core/lib/iomgr/executor/mpmcqueue.h",
"src/core/lib/iomgr/executor/threadpool.h",
"src/core/lib/iomgr/gethostname.h",
"src/core/lib/iomgr/gevent_util.h",
"src/core/lib/iomgr/python_util.h",
"src/core/lib/iomgr/grpc_if_nametoindex.h",
"src/core/lib/iomgr/internal_errqueue.h",
"src/core/lib/iomgr/iocp_windows.h",

@ -132,7 +132,6 @@ config("grpc_config") {
"src/core/lib/gpr/tmpfile_windows.cc",
"src/core/lib/gpr/useful.h",
"src/core/lib/gpr/wrap_memcpy.cc",
"src/core/lib/gprpp/abstract.h",
"src/core/lib/gprpp/arena.cc",
"src/core/lib/gprpp/arena.h",
"src/core/lib/gprpp/atomic.h",
@ -150,7 +149,6 @@ config("grpc_config") {
"src/core/lib/gprpp/memory.h",
"src/core/lib/gprpp/mpscq.cc",
"src/core/lib/gprpp/mpscq.h",
"src/core/lib/gprpp/pair.h",
"src/core/lib/gprpp/sync.h",
"src/core/lib/gprpp/thd.h",
"src/core/lib/gprpp/thd_posix.cc",
@ -1237,7 +1235,6 @@ config("grpc_config") {
"src/core/lib/gpr/tls_pthread.h",
"src/core/lib/gpr/tmpfile.h",
"src/core/lib/gpr/useful.h",
"src/core/lib/gprpp/abstract.h",
"src/core/lib/gprpp/arena.h",
"src/core/lib/gprpp/atomic.h",
"src/core/lib/gprpp/debug_location.h",
@ -1254,7 +1251,6 @@ config("grpc_config") {
"src/core/lib/gprpp/mpscq.h",
"src/core/lib/gprpp/optional.h",
"src/core/lib/gprpp/orphanable.h",
"src/core/lib/gprpp/pair.h",
"src/core/lib/gprpp/ref_counted.h",
"src/core/lib/gprpp/ref_counted_ptr.h",
"src/core/lib/gprpp/string_view.h",

@ -631,7 +631,6 @@ add_dependencies(buildtests_cxx golden_file_test)
add_dependencies(buildtests_cxx gprpp_mpscq_test)
add_dependencies(buildtests_cxx grpc_alts_credentials_options_test)
add_dependencies(buildtests_cxx grpc_cli)
add_dependencies(buildtests_cxx grpc_core_map_test)
add_dependencies(buildtests_cxx grpc_fetch_oauth2)
add_dependencies(buildtests_cxx grpc_linux_system_roots_test)
add_dependencies(buildtests_cxx grpc_spiffe_security_connector_test)
@ -13408,47 +13407,6 @@ target_link_libraries(grpc_cli
)
endif (gRPC_BUILD_TESTS)
if (gRPC_BUILD_TESTS)
add_executable(grpc_core_map_test
test/core/gprpp/map_test.cc
third_party/googletest/googletest/src/gtest-all.cc
third_party/googletest/googlemock/src/gmock-all.cc
)
target_include_directories(grpc_core_map_test
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include
PRIVATE ${_gRPC_ADDRESS_SORTING_INCLUDE_DIR}
PRIVATE ${_gRPC_BENCHMARK_INCLUDE_DIR}
PRIVATE ${_gRPC_CARES_INCLUDE_DIR}
PRIVATE ${_gRPC_GFLAGS_INCLUDE_DIR}
PRIVATE ${_gRPC_PROTOBUF_INCLUDE_DIR}
PRIVATE ${_gRPC_SSL_INCLUDE_DIR}
PRIVATE ${_gRPC_UPB_GENERATED_DIR}
PRIVATE ${_gRPC_UPB_GRPC_GENERATED_DIR}
PRIVATE ${_gRPC_UPB_INCLUDE_DIR}
PRIVATE ${_gRPC_ZLIB_INCLUDE_DIR}
PRIVATE third_party/googletest/googletest/include
PRIVATE third_party/googletest/googletest
PRIVATE third_party/googletest/googlemock/include
PRIVATE third_party/googletest/googlemock
PRIVATE ${_gRPC_PROTO_GENS_DIR}
)
target_link_libraries(grpc_core_map_test
${_gRPC_PROTOBUF_LIBRARIES}
${_gRPC_ALLTARGETS_LIBRARIES}
grpc_test_util
grpc++
grpc
gpr
${_gRPC_GFLAGS_LIBRARIES}
)
endif (gRPC_BUILD_TESTS)
if (gRPC_BUILD_CODEGEN)

@ -1220,7 +1220,6 @@ golden_file_test: $(BINDIR)/$(CONFIG)/golden_file_test
gprpp_mpscq_test: $(BINDIR)/$(CONFIG)/gprpp_mpscq_test
grpc_alts_credentials_options_test: $(BINDIR)/$(CONFIG)/grpc_alts_credentials_options_test
grpc_cli: $(BINDIR)/$(CONFIG)/grpc_cli
grpc_core_map_test: $(BINDIR)/$(CONFIG)/grpc_core_map_test
grpc_cpp_plugin: $(BINDIR)/$(CONFIG)/grpc_cpp_plugin
grpc_csharp_plugin: $(BINDIR)/$(CONFIG)/grpc_csharp_plugin
grpc_fetch_oauth2: $(BINDIR)/$(CONFIG)/grpc_fetch_oauth2
@ -1417,7 +1416,7 @@ plugins: $(PROTOC_PLUGINS)
privatelibs: privatelibs_c privatelibs_cxx
privatelibs_c: $(LIBDIR)/$(CONFIG)/libalts_test_util.a $(LIBDIR)/$(CONFIG)/libcxxabi.a $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc_test_util_unsecure.a $(LIBDIR)/$(CONFIG)/libreconnect_server.a $(LIBDIR)/$(CONFIG)/libtest_tcp_server.a $(LIBDIR)/$(CONFIG)/libz.a $(LIBDIR)/$(CONFIG)/libares.a $(LIBDIR)/$(CONFIG)/libbad_ssl_test_server.a $(LIBDIR)/$(CONFIG)/libend2end_tests.a $(LIBDIR)/$(CONFIG)/libend2end_nosec_tests.a
privatelibs_c: $(LIBDIR)/$(CONFIG)/libalts_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc_test_util_unsecure.a $(LIBDIR)/$(CONFIG)/libreconnect_server.a $(LIBDIR)/$(CONFIG)/libtest_tcp_server.a $(LIBDIR)/$(CONFIG)/libz.a $(LIBDIR)/$(CONFIG)/libares.a $(LIBDIR)/$(CONFIG)/libbad_ssl_test_server.a $(LIBDIR)/$(CONFIG)/libend2end_tests.a $(LIBDIR)/$(CONFIG)/libend2end_nosec_tests.a
pc_c: $(LIBDIR)/$(CONFIG)/pkgconfig/grpc.pc $(LIBDIR)/$(CONFIG)/pkgconfig/gpr.pc
pc_c_unsecure: $(LIBDIR)/$(CONFIG)/pkgconfig/grpc_unsecure.pc $(LIBDIR)/$(CONFIG)/pkgconfig/gpr.pc
@ -1699,7 +1698,6 @@ buildtests_cxx: privatelibs_cxx \
$(BINDIR)/$(CONFIG)/gprpp_mpscq_test \
$(BINDIR)/$(CONFIG)/grpc_alts_credentials_options_test \
$(BINDIR)/$(CONFIG)/grpc_cli \
$(BINDIR)/$(CONFIG)/grpc_core_map_test \
$(BINDIR)/$(CONFIG)/grpc_fetch_oauth2 \
$(BINDIR)/$(CONFIG)/grpc_linux_system_roots_test \
$(BINDIR)/$(CONFIG)/grpc_spiffe_security_connector_test \
@ -1870,7 +1868,6 @@ buildtests_cxx: privatelibs_cxx \
$(BINDIR)/$(CONFIG)/gprpp_mpscq_test \
$(BINDIR)/$(CONFIG)/grpc_alts_credentials_options_test \
$(BINDIR)/$(CONFIG)/grpc_cli \
$(BINDIR)/$(CONFIG)/grpc_core_map_test \
$(BINDIR)/$(CONFIG)/grpc_fetch_oauth2 \
$(BINDIR)/$(CONFIG)/grpc_linux_system_roots_test \
$(BINDIR)/$(CONFIG)/grpc_spiffe_security_connector_test \
@ -2378,8 +2375,6 @@ test_cxx: buildtests_cxx
$(Q) $(BINDIR)/$(CONFIG)/gprpp_mpscq_test || ( echo test gprpp_mpscq_test failed ; exit 1 )
$(E) "[RUN] Testing grpc_alts_credentials_options_test"
$(Q) $(BINDIR)/$(CONFIG)/grpc_alts_credentials_options_test || ( echo test grpc_alts_credentials_options_test failed ; exit 1 )
$(E) "[RUN] Testing grpc_core_map_test"
$(Q) $(BINDIR)/$(CONFIG)/grpc_core_map_test || ( echo test grpc_core_map_test failed ; exit 1 )
$(E) "[RUN] Testing grpc_linux_system_roots_test"
$(Q) $(BINDIR)/$(CONFIG)/grpc_linux_system_roots_test || ( echo test grpc_linux_system_roots_test failed ; exit 1 )
$(E) "[RUN] Testing grpc_spiffe_security_connector_test"
@ -3400,50 +3395,6 @@ endif
endif
LIBCXXABI_SRC = \
third_party/libcxxabi/src/abort_message.cpp \
third_party/libcxxabi/src/cxa_aux_runtime.cpp \
third_party/libcxxabi/src/cxa_default_handlers.cpp \
third_party/libcxxabi/src/cxa_demangle.cpp \
third_party/libcxxabi/src/cxa_exception_storage.cpp \
third_party/libcxxabi/src/cxa_guard.cpp \
third_party/libcxxabi/src/cxa_handlers.cpp \
third_party/libcxxabi/src/cxa_noexception.cpp \
third_party/libcxxabi/src/cxa_thread_atexit.cpp \
third_party/libcxxabi/src/cxa_unexpected.cpp \
third_party/libcxxabi/src/cxa_vector.cpp \
third_party/libcxxabi/src/cxa_virtual.cpp \
third_party/libcxxabi/src/fallback_malloc.cpp \
third_party/libcxxabi/src/private_typeinfo.cpp \
third_party/libcxxabi/src/stdlib_exception.cpp \
third_party/libcxxabi/src/stdlib_new_delete.cpp \
third_party/libcxxabi/src/stdlib_stdexcept.cpp \
third_party/libcxxabi/src/stdlib_typeinfo.cpp \
PUBLIC_HEADERS_C += \
LIBCXXABI_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(LIBCXXABI_SRC))))
$(LIBCXXABI_OBJS): CPPFLAGS += -D_LIBCPP_DISABLE_EXTERN_TEMPLATE -D_LIBCXXABI_BUILDING_LIBRARY -D_LIBCXXABI_NO_EXCEPTIONS -Ithird_party/libcxxabi/include -nostdinc++ -Ithird_party/libcxx/include $(W_NO_UNUSED_BUT_SET_VARIABLE) $(W_NO_MAYBE_UNINITIALIZED) -fvisibility=hidden
$(LIBCXXABI_OBJS): CXXFLAGS += $(W_NO_CXX14_COMPAT)
$(LIBDIR)/$(CONFIG)/libcxxabi.a: $(ZLIB_DEP) $(CARES_DEP) $(ADDRESS_SORTING_DEP) $(LIBCXXABI_OBJS)
$(E) "[AR] Creating $@"
$(Q) mkdir -p `dirname $@`
$(Q) rm -f $(LIBDIR)/$(CONFIG)/libcxxabi.a
$(Q) $(AR) $(AROPTS) $(LIBDIR)/$(CONFIG)/libcxxabi.a $(LIBCXXABI_OBJS)
ifeq ($(SYSTEM),Darwin)
$(Q) ranlib -no_warning_for_no_symbols $(LIBDIR)/$(CONFIG)/libcxxabi.a
endif
ifneq ($(NO_DEPS),true)
-include $(LIBCXXABI_OBJS:.o=.dep)
endif
LIBGPR_SRC = \
src/core/lib/gpr/alloc.cc \
src/core/lib/gpr/atm.cc \
@ -16803,49 +16754,6 @@ endif
endif
GRPC_CORE_MAP_TEST_SRC = \
test/core/gprpp/map_test.cc \
GRPC_CORE_MAP_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_CORE_MAP_TEST_SRC))))
ifeq ($(NO_SECURE),true)
# You can't build secure targets if you don't have OpenSSL.
$(BINDIR)/$(CONFIG)/grpc_core_map_test: openssl_dep_error
else
ifeq ($(NO_PROTOBUF),true)
# You can't build the protoc plugins or protobuf-enabled targets if you don't have protobuf 3.5.0+.
$(BINDIR)/$(CONFIG)/grpc_core_map_test: protobuf_dep_error
else
$(BINDIR)/$(CONFIG)/grpc_core_map_test: $(PROTOBUF_DEP) $(GRPC_CORE_MAP_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr.a
$(E) "[LD] Linking $@"
$(Q) mkdir -p `dirname $@`
$(Q) $(LDXX) $(LDFLAGS) $(GRPC_CORE_MAP_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LDLIBSXX) $(LDLIBS_PROTOBUF) $(LDLIBS) $(LDLIBS_SECURE) $(GTEST_LIB) -o $(BINDIR)/$(CONFIG)/grpc_core_map_test
endif
endif
$(OBJDIR)/$(CONFIG)/test/core/gprpp/map_test.o: $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr.a
deps_grpc_core_map_test: $(GRPC_CORE_MAP_TEST_OBJS:.o=.dep)
ifneq ($(NO_SECURE),true)
ifneq ($(NO_DEPS),true)
-include $(GRPC_CORE_MAP_TEST_OBJS:.o=.dep)
endif
endif
GRPC_CPP_PLUGIN_SRC = \
src/compiler/cpp_plugin.cc \

@ -98,9 +98,6 @@ def grpc_cc_library(
"//:grpc_allow_exceptions": ["GRPC_ALLOW_EXCEPTIONS=1"],
"//:grpc_disallow_exceptions": ["GRPC_ALLOW_EXCEPTIONS=0"],
"//conditions:default": [],
}) + select({
"//:grpc_use_cpp_std_lib": ["GRPC_USE_CPP_STD_LIB=1"],
"//conditions:default": [],
}),
hdrs = hdrs + public_hdrs,
deps = deps + _get_external_deps(external_deps),
@ -184,17 +181,17 @@ def grpc_cc_test(name, srcs = [], deps = [], external_deps = [], args = [], data
"exec_compatible_with": exec_compatible_with,
}
if uses_polling:
# Only run targets with pollers for non-MSVC
# TODO(yfen): Enable MSVC for poller-enabled targets without pollers
# the vanilla version of the test should run on platforms that only
# support a single poller
native.cc_test(
name = name,
testonly = True,
tags = [
"manual",
"no_windows",
],
tags = (tags + [
"no_linux", # linux supports multiple pollers
]),
**args
)
# on linux we run the same test multiple times, once for each poller
for poller in POLLERS:
native.sh_test(
name = name + "@poller=" + poller,
@ -208,11 +205,12 @@ def grpc_cc_test(name, srcs = [], deps = [], external_deps = [], args = [], data
poller,
"$(location %s)" % name,
] + args["args"],
tags = (tags + ["no_windows"]),
tags = (tags + ["no_windows", "no_mac"]),
exec_compatible_with = exec_compatible_with,
)
else:
native.cc_test(tags = tags, **args)
# the test behavior doesn't depend on polling, just generate the test
native.cc_test(name = name, tags = tags, **args)
ios_cc_test(
name = name,
tags = tags,

@ -174,13 +174,14 @@ def grpc_deps():
)
if "bazel_toolchains" not in native.existing_rules():
# list of releases is at https://releases.bazel.build/bazel-toolchains.html
http_archive(
name = "bazel_toolchains",
sha256 = "872955b658113924eb1a3594b04d43238da47f4f90c17b76e8785709490dc041",
strip_prefix = "bazel-toolchains-1083686fde6032378d52b4c98044922cebde364e",
sha256 = "22ca5b8115c8673ecb627a02b606529e813961e447933863fccdf325cc5f999f",
strip_prefix = "bazel-toolchains-0.29.5",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/bazel-toolchains/archive/1083686fde6032378d52b4c98044922cebde364e.tar.gz",
"https://github.com/bazelbuild/bazel-toolchains/archive/1083686fde6032378d52b4c98044922cebde364e.tar.gz",
"https://github.com/bazelbuild/bazel-toolchains/releases/download/0.29.5/bazel-toolchains-0.29.5.tar.gz",
"https://mirror.bazel.build/github.com/bazelbuild/bazel-toolchains/archive/0.29.5.tar.gz",
],
)

@ -279,7 +279,6 @@ filegroups:
- src/core/lib/gpr/tls_pthread.h
- src/core/lib/gpr/tmpfile.h
- src/core/lib/gpr/useful.h
- src/core/lib/gprpp/abstract.h
- src/core/lib/gprpp/arena.h
- src/core/lib/gprpp/atomic.h
- src/core/lib/gprpp/fork.h
@ -292,7 +291,6 @@ filegroups:
- src/core/lib/gprpp/map.h
- src/core/lib/gprpp/memory.h
- src/core/lib/gprpp/mpscq.h
- src/core/lib/gprpp/pair.h
- src/core/lib/gprpp/sync.h
- src/core/lib/gprpp/thd.h
- src/core/lib/profiling/timers.h
@ -1627,32 +1625,6 @@ libs:
deps:
- grpc
secure: true
- name: cxxabi
build: private
language: c
src:
- third_party/libcxxabi/src/abort_message.cpp
- third_party/libcxxabi/src/cxa_aux_runtime.cpp
- third_party/libcxxabi/src/cxa_default_handlers.cpp
- third_party/libcxxabi/src/cxa_demangle.cpp
- third_party/libcxxabi/src/cxa_exception_storage.cpp
- third_party/libcxxabi/src/cxa_guard.cpp
- third_party/libcxxabi/src/cxa_handlers.cpp
- third_party/libcxxabi/src/cxa_noexception.cpp
- third_party/libcxxabi/src/cxa_thread_atexit.cpp
- third_party/libcxxabi/src/cxa_unexpected.cpp
- third_party/libcxxabi/src/cxa_vector.cpp
- third_party/libcxxabi/src/cxa_virtual.cpp
- third_party/libcxxabi/src/fallback_malloc.cpp
- third_party/libcxxabi/src/private_typeinfo.cpp
- third_party/libcxxabi/src/stdlib_exception.cpp
- third_party/libcxxabi/src/stdlib_new_delete.cpp
- third_party/libcxxabi/src/stdlib_stdexcept.cpp
- third_party/libcxxabi/src/stdlib_typeinfo.cpp
build_system:
- Makefile
defaults: cxxabi
secure: false
- name: gpr
build: all
language: c
@ -5016,20 +4988,6 @@ targets:
- grpc
- gpr
- grpc++_test_config
- name: grpc_core_map_test
gtest: true
build: test
language: c++
headers:
- test/core/gprpp/map_tester.h
src:
- test/core/gprpp/map_test.cc
deps:
- grpc_test_util
- grpc++
- grpc
- gpr
uses_polling: false
- name: grpc_cpp_plugin
build: protoc
language: c++
@ -6207,11 +6165,6 @@ defaults:
CPPFLAGS: -Ithird_party/boringssl/include -fvisibility=hidden -DOPENSSL_NO_ASM
-D_GNU_SOURCE -DWIN32_LEAN_AND_MEAN -D_HAS_EXCEPTIONS=0 -DNOMINMAX
CXXFLAGS: -fno-rtti -fno-exceptions
cxxabi:
CPPFLAGS: -D_LIBCPP_DISABLE_EXTERN_TEMPLATE -D_LIBCXXABI_BUILDING_LIBRARY -D_LIBCXXABI_NO_EXCEPTIONS
-Ithird_party/libcxxabi/include -nostdinc++ -Ithird_party/libcxx/include $(W_NO_UNUSED_BUT_SET_VARIABLE)
$(W_NO_MAYBE_UNINITIALIZED) -fvisibility=hidden
CXXFLAGS: $(W_NO_CXX14_COMPAT)
global:
CFLAGS: -g
COREFLAGS: -fno-rtti -fno-exceptions

@ -1,8 +1,8 @@
# Moving gRPC core to C++
October 2017
Originally written by ctiller, markdroth, and vjpai in October 2017
ctiller, markdroth, vjpai
Revised by veblush in October 2019
## Background and Goal
@ -10,10 +10,14 @@ gRPC core was originally written in C89 for several reasons
(possibility of kernel integration, ease of wrapping, compiler
support, etc). Over time, this was changed to C99 as all relevant
compilers in active use came to support C99 effectively.
[Now, gRPC core is C++](https://github.com/grpc/proposal/blob/master/L6-allow-c%2B%2B-in-grpc-core.md)
(although the code is still idiomatically C code) with C linkage for
public functions. Throughout all of these transitions, the public
header files are committed to remain in C89.
gRPC started allowing to use C++ with a couple of exceptions not to
have C++ library linked such as `libstdc++.so`.
(For more detail, see the [proposal](https://github.com/grpc/proposal/blob/master/L6-core-allow-cpp.md))
Finally gRPC became ready to use full C++11 with the standard library by the [proposal](https://github.com[/grpc/proposal/blob/master/L59-core-allow-cppstdlib.md).
Throughout all of these transitions, the public header files are committed to remain in C89.
The goal now is to make the gRPC core implementation true idiomatic
C++ compatible with
@ -21,24 +25,16 @@ C++ compatible with
## Constraints
- No use of standard library if it requires link-time dependency
- Standard library makes wrapping difficult/impossible and also reduces platform portability
- This takes precedence over using C++ style guide
- Limited use of standard library if it does not require link-time dependency
- We can use things from `std::` as long as they are header-only implementations.
- Since the standard library API does not specify whether any given part of the API is implemented header-only, the only way to know is to try using something and see if our tests fail.
- Since there is no guarantee that some header-only implementation in the standard library will remain header-only in the future, we should define our own API in lib/gprpp that is an alias for the thing we want to use in `std::` and use the gprpp API in core. That way, if we later need to stop using the thing from `std::`, we can replace the alias with our own implementation.
- But lambdas are ok
- As are third-party libraries that meet our build requirements (such as many parts of abseil)
- There will be some C++ features that don't work
- `new` and `delete`
- pure virtual functions are not allowed because the message that prints out "Pure Virtual Function called" is part of the standard library
- Make a `#define GRPC_ABSTRACT {GPR_ASSERT(false);}` instead of `= 0;`
- The sanity for making sure that we don't depend on libstdc++ is that at least some tests should explicitly not include it
- Most tests can migrate to use gtest
- There are tremendous # of code paths that can now be exposed to unit tests because of the use of gtest and C++
- But at least some tests should not use gtest
- Most of features available in C++11 are allowed to use but there are some exceptions
because gRPC should support old systems.
- Should be built with gcc 4.8, clang 3.3, and Visual C++ 2015.
- Should be run on Linux system with libstdc++ 6.0.9 to support
[manylinux1](https://www.python.org/dev/peps/pep-0513).
- This would limit us not to use modern C++11 standard library such as `filesystem`.
You can easily see whether PR is free from this issue by checking the result of
`Artifact Build Linux` test.
- `thread_local` is not allowed to use on Apple's products because their old OSes
(e.g. ios < 9.0) don't support `thread_local`.
## Roadmap
@ -59,6 +55,3 @@ C++ compatible with
ByteBuffer, ...)
- The C++ API implementation might directly start using
`grpc_transport_stream_op_batch` rather than the core surface `grpc_op`.
- Can we get wrapped languages to a point where we can statically link C++? This will take a year in probability but that would allow the use of `std::`
- Are there other environments that don't support std library, like maybe Android NDK?
- Probably, that might push things out to 18 months

@ -1121,7 +1121,7 @@ for the `SimpleRequest.response_type`. If the server does not support the
Server gets the default SimpleRequest proto as the request. The content of the
request is ignored. It returns the SimpleResponse proto with the payload set
to current timestamp. The timestamp is an integer representing current time
with nanosecond resolution. This integer is formated as ASCII decimal in the
with nanosecond resolution. This integer is formatted as ASCII decimal in the
response. The format is not really important as long as the response payload
is different for each request. In addition it adds
1. cache control headers such that the response can be cached by proxies in

@ -58,7 +58,7 @@ namespace HelloworldXamarin.iOS
public override void WillEnterForeground(UIApplication application)
{
// Called as part of the transiton from background to active state.
// Called as part of the transition from background to active state.
// Here you can undo many of the changes made on entering the background.
}

@ -0,0 +1,86 @@
# gRPC PHP End-to-End Examples
This page shows a number of ways to create a PHP gRPC client and connect with
a gRPC backend service.
## Run the Server
For all the following examples, we use a simple gRPC server, written in Node.
```sh
$ git clone https://github.com/grpc/grpc-web
$ cd grpc-web
$ docker-compose build common node-server
$ docker run -d -p 9090:9090 --name node-server grpcweb/node-server
```
## Install the gRPC PECL extension
All the following commands are assumed to be run from this current directory.
```sh
$ cd grpc/examples/php/echo
```
In order to build a PHP gRPC client, we need to install the `grpc` extension
first.
```sh
$ docker build -t grpc-php/base -f ./base.Dockerfile .
```
## CLI
Let's first build a simple CLI gRPC client:
```sh
$ docker build -t grpc-php/echo-client -f ./cli.Dockerfile .
$ docker run -it --rm --link node-server:node-server grpc-php/echo-client
$ php client.php
```
## Apache
Now let's see how the gRPC PHP client can run with Apache:
```sh
$ docker build -t grpc-php/apache -f ./apache.Dockerfile .
$ docker run -it --rm --link node-server:node-server -p 80:80 grpc-php/apache
```
Open the browser to `http://localhost`.
## Nginx + FPM
We can also try running PHP-FPM and put Nginx in front of it.
The PHP-FPM part:
```sh
$ docker build -t grpc-php/fpm -f ./fpm.Dockerfile .
$ docker run -it --rm --link node-server:node-server -p 9000:9000 \
--name fpm grpc-php/fpm
```
The Nginx part:
```sh
$ docker run -it --rm -v $(pwd)/nginx.conf:/etc/nginx/conf.d/default.conf:ro \
--link fpm:fpm -p 80:80 nginx:1.17.4
```
Open the browser to `http://localhost`.

@ -0,0 +1,49 @@
# Copyright 2019 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
FROM composer:1.8.6 as composer
FROM grpc-php/base as grpc-base
FROM php:7.2-apache-stretch
RUN apt-get -qq update && apt-get -qq install -y git
COPY --from=composer /usr/bin/composer /usr/bin/composer
COPY --from=grpc-base /usr/local/bin/protoc /usr/local/bin/protoc
COPY --from=grpc-base /github/grpc/bins/opt/grpc_php_plugin \
/usr/local/bin/protoc-gen-grpc
COPY --from=grpc-base \
/usr/local/lib/php/extensions/no-debug-non-zts-20170718/grpc.so \
/usr/local/lib/php/extensions/no-debug-non-zts-20170718/grpc.so
RUN docker-php-ext-enable grpc
WORKDIR /var/www/html
COPY client.php ./index.php
COPY composer.json .
COPY echo.proto .
RUN protoc -I=. echo.proto --php_out=. --grpc_out=.
RUN composer install

@ -0,0 +1,38 @@
# Copyright 2019 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
FROM php:7.2-stretch
RUN apt-get -qq update && apt-get -qq install -y \
autoconf automake curl git libtool \
pkg-config unzip zlib1g-dev
WORKDIR /tmp
RUN curl -sSL https://github.com/protocolbuffers/protobuf/releases/download/v3.8.0/\
protoc-3.8.0-linux-x86_64.zip -o /tmp/protoc.zip && \
unzip -qq protoc.zip && \
cp /tmp/bin/protoc /usr/local/bin/protoc
WORKDIR /github/grpc
RUN git clone https://github.com/grpc/grpc . && \
git submodule update --init && \
cd third_party/protobuf && git submodule update --init
RUN make grpc_php_plugin
RUN pecl install grpc

@ -0,0 +1,52 @@
# Copyright 2019 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
FROM composer:1.8.6 as composer
FROM grpc-php/base as grpc-base
FROM php:7.2-stretch
RUN apt-get -qq update && apt-get -qq install -y git
COPY --from=composer /usr/bin/composer /usr/bin/composer
COPY --from=grpc-base /usr/local/bin/protoc /usr/local/bin/protoc
COPY --from=grpc-base /github/grpc/bins/opt/grpc_php_plugin \
/usr/local/bin/protoc-gen-grpc
COPY --from=grpc-base \
/usr/local/lib/php/extensions/no-debug-non-zts-20170718/grpc.so \
/usr/local/lib/php/extensions/no-debug-non-zts-20170718/grpc.so
RUN docker-php-ext-enable grpc
WORKDIR /github/grpc-php/examples/echo
COPY client.php .
COPY composer.json .
COPY echo.proto .
RUN protoc -I=. echo.proto --php_out=. --grpc_out=.
RUN composer install
CMD ["/bin/bash"]

@ -0,0 +1,45 @@
<?php
/*
*
* Copyright 2018 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
require dirname(__FILE__).'/vendor/autoload.php';
$client = new Grpc\Gateway\Testing\EchoServiceClient('node-server:9090', [
'credentials' => Grpc\ChannelCredentials::createInsecure(),
]);
// unary call
$request = new Grpc\Gateway\Testing\EchoRequest();
$request->setMessage("Hello World!");
list($response, $status) = $client->Echo($request)->wait();
echo $response->getMessage()."\n";
// server streaming call
$stream_request = new Grpc\Gateway\Testing\ServerStreamingEchoRequest();
$stream_request->setMessage("stream message");
$stream_request->setMessageCount(5);
$responses = $client->ServerStreamingEcho($stream_request)->responses();
foreach ($responses as $response) {
echo $response->getMessage()."\n";
}

@ -0,0 +1,12 @@
{
"name": "grpc-php/echo-example",
"require": {
"grpc/grpc": "^v1.22.0",
"google/protobuf": "^3.7.0"
},
"autoload": {
"psr-4": {
"": "./"
}
}
}

@ -0,0 +1,100 @@
// Copyright 2019 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
syntax = "proto3";
package grpc.gateway.testing;
message Empty {}
message EchoRequest {
string message = 1;
}
message EchoResponse {
string message = 1;
int32 message_count = 2;
}
// Request type for server side streaming echo.
message ServerStreamingEchoRequest {
// Message string for server streaming request.
string message = 1;
// The total number of messages to be generated before the server
// closes the stream; default is 10.
int32 message_count = 2;
// The interval (ms) between two server messages. The server implementation
// may enforce some minimum interval (e.g. 100ms) to avoid message overflow.
int32 message_interval = 3;
}
// Response type for server streaming response.
message ServerStreamingEchoResponse {
// Response message.
string message = 1;
}
// Request type for client side streaming echo.
message ClientStreamingEchoRequest {
// A special value "" indicates that there's no further messages.
string message = 1;
}
// Response type for client side streaming echo.
message ClientStreamingEchoResponse {
// Total number of client messages that have been received.
int32 message_count = 1;
}
// A simple echo service.
service EchoService {
// One request followed by one response
// The server returns the client message as-is.
rpc Echo(EchoRequest) returns (EchoResponse);
// Sends back abort status.
rpc EchoAbort(EchoRequest) returns (EchoResponse) {}
// One empty request, ZERO processing, followed by one empty response
// (minimum effort to do message serialization).
rpc NoOp(Empty) returns (Empty);
// One request followed by a sequence of responses (streamed download).
// The server will return the same client message repeatedly.
rpc ServerStreamingEcho(ServerStreamingEchoRequest)
returns (stream ServerStreamingEchoResponse);
// One request followed by a sequence of responses (streamed download).
// The server abort directly.
rpc ServerStreamingEchoAbort(ServerStreamingEchoRequest)
returns (stream ServerStreamingEchoResponse) {}
// A sequence of requests followed by one response (streamed upload).
// The server returns the total number of messages as the result.
rpc ClientStreamingEcho(stream ClientStreamingEchoRequest)
returns (ClientStreamingEchoResponse);
// A sequence of requests with each message echoed by the server immediately.
// The server returns the same client messages in order.
// E.g. this is how the speech API works.
rpc FullDuplexEcho(stream EchoRequest) returns (stream EchoResponse);
// A sequence of requests followed by a sequence of responses.
// The server buffers all the client messages and then returns the same
// client messages one by one after the client half-closes the stream.
// This is how an image recognition API may work.
rpc HalfDuplexEcho(stream EchoRequest) returns (stream EchoResponse);
}

@ -0,0 +1,49 @@
# Copyright 2019 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
FROM composer:1.8.6 as composer
FROM grpc-php/base as grpc-base
FROM php:7.2-fpm-stretch
RUN apt-get -qq update && apt-get -qq install -y git
COPY --from=composer /usr/bin/composer /usr/bin/composer
COPY --from=grpc-base /usr/local/bin/protoc /usr/local/bin/protoc
COPY --from=grpc-base /github/grpc/bins/opt/grpc_php_plugin \
/usr/local/bin/protoc-gen-grpc
COPY --from=grpc-base \
/usr/local/lib/php/extensions/no-debug-non-zts-20170718/grpc.so \
/usr/local/lib/php/extensions/no-debug-non-zts-20170718/grpc.so
RUN docker-php-ext-enable grpc
WORKDIR /var/www/html
COPY client.php ./index.php
COPY composer.json .
COPY echo.proto .
RUN protoc -I=. echo.proto --php_out=. --grpc_out=.
RUN composer install

@ -0,0 +1,23 @@
server {
listen 80;
server_name localhost;
root /var/www/html;
index index.php;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ [^/]\.php(/|$) {
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
fastcgi_pass fpm:9000;
fastcgi_index index.php;
}
}

@ -76,7 +76,7 @@ catch the `RpcError` raised by the for loop upon cancellation.
#### Cancellation on the Server Side
A server is reponsible for cancellation in two ways. It must respond in some way
A server is responsible for cancellation in two ways. It must respond in some way
when a client initiates a cancellation, otherwise long-running computations
could continue indefinitely.

@ -21,7 +21,7 @@ message HashNameRequest {
// The string that is desired in the secret's hash.
string desired_name = 1;
// The ideal Hamming distance betwen desired_name and the secret that will
// The ideal Hamming distance between desired_name and the secret that will
// be searched for.
int32 ideal_hamming_distance = 2;

@ -1,6 +1,6 @@
## Data transmission demo for using gRPC in Python
Four ways of data transmission when gRPC is used in Python. [Offical Guide](<https://grpc.io/docs/guides/concepts/#unary-rpc>)
Four ways of data transmission when gRPC is used in Python. [Official Guide](<https://grpc.io/docs/guides/concepts/#unary-rpc>)
- #### unary-unary

@ -299,7 +299,6 @@ Pod::Spec.new do |s|
'src/core/lib/gpr/tls_pthread.h',
'src/core/lib/gpr/tmpfile.h',
'src/core/lib/gpr/useful.h',
'src/core/lib/gprpp/abstract.h',
'src/core/lib/gprpp/arena.h',
'src/core/lib/gprpp/atomic.h',
'src/core/lib/gprpp/fork.h',
@ -312,7 +311,6 @@ Pod::Spec.new do |s|
'src/core/lib/gprpp/map.h',
'src/core/lib/gprpp/memory.h',
'src/core/lib/gprpp/mpscq.h',
'src/core/lib/gprpp/pair.h',
'src/core/lib/gprpp/sync.h',
'src/core/lib/gprpp/thd.h',
'src/core/lib/profiling/timers.h',

@ -202,7 +202,6 @@ Pod::Spec.new do |s|
'src/core/lib/gpr/tls_pthread.h',
'src/core/lib/gpr/tmpfile.h',
'src/core/lib/gpr/useful.h',
'src/core/lib/gprpp/abstract.h',
'src/core/lib/gprpp/arena.h',
'src/core/lib/gprpp/atomic.h',
'src/core/lib/gprpp/fork.h',
@ -215,7 +214,6 @@ Pod::Spec.new do |s|
'src/core/lib/gprpp/map.h',
'src/core/lib/gprpp/memory.h',
'src/core/lib/gprpp/mpscq.h',
'src/core/lib/gprpp/pair.h',
'src/core/lib/gprpp/sync.h',
'src/core/lib/gprpp/thd.h',
'src/core/lib/profiling/timers.h',
@ -978,7 +976,6 @@ Pod::Spec.new do |s|
'src/core/lib/gpr/tls_pthread.h',
'src/core/lib/gpr/tmpfile.h',
'src/core/lib/gpr/useful.h',
'src/core/lib/gprpp/abstract.h',
'src/core/lib/gprpp/arena.h',
'src/core/lib/gprpp/atomic.h',
'src/core/lib/gprpp/fork.h',
@ -991,7 +988,6 @@ Pod::Spec.new do |s|
'src/core/lib/gprpp/map.h',
'src/core/lib/gprpp/memory.h',
'src/core/lib/gprpp/mpscq.h',
'src/core/lib/gprpp/pair.h',
'src/core/lib/gprpp/sync.h',
'src/core/lib/gprpp/thd.h',
'src/core/lib/profiling/timers.h',

@ -96,7 +96,6 @@ Gem::Specification.new do |s|
s.files += %w( src/core/lib/gpr/tls_pthread.h )
s.files += %w( src/core/lib/gpr/tmpfile.h )
s.files += %w( src/core/lib/gpr/useful.h )
s.files += %w( src/core/lib/gprpp/abstract.h )
s.files += %w( src/core/lib/gprpp/arena.h )
s.files += %w( src/core/lib/gprpp/atomic.h )
s.files += %w( src/core/lib/gprpp/fork.h )
@ -109,7 +108,6 @@ Gem::Specification.new do |s|
s.files += %w( src/core/lib/gprpp/map.h )
s.files += %w( src/core/lib/gprpp/memory.h )
s.files += %w( src/core/lib/gprpp/mpscq.h )
s.files += %w( src/core/lib/gprpp/pair.h )
s.files += %w( src/core/lib/gprpp/sync.h )
s.files += %w( src/core/lib/gprpp/thd.h )
s.files += %w( src/core/lib/profiling/timers.h )

@ -172,32 +172,6 @@
'test/core/tsi/alts/handshaker/alts_handshaker_service_api_test_lib.cc',
],
},
{
'target_name': 'cxxabi',
'type': 'static_library',
'dependencies': [
],
'sources': [
'third_party/libcxxabi/src/abort_message.cpp',
'third_party/libcxxabi/src/cxa_aux_runtime.cpp',
'third_party/libcxxabi/src/cxa_default_handlers.cpp',
'third_party/libcxxabi/src/cxa_demangle.cpp',
'third_party/libcxxabi/src/cxa_exception_storage.cpp',
'third_party/libcxxabi/src/cxa_guard.cpp',
'third_party/libcxxabi/src/cxa_handlers.cpp',
'third_party/libcxxabi/src/cxa_noexception.cpp',
'third_party/libcxxabi/src/cxa_thread_atexit.cpp',
'third_party/libcxxabi/src/cxa_unexpected.cpp',
'third_party/libcxxabi/src/cxa_vector.cpp',
'third_party/libcxxabi/src/cxa_virtual.cpp',
'third_party/libcxxabi/src/fallback_malloc.cpp',
'third_party/libcxxabi/src/private_typeinfo.cpp',
'third_party/libcxxabi/src/stdlib_exception.cpp',
'third_party/libcxxabi/src/stdlib_new_delete.cpp',
'third_party/libcxxabi/src/stdlib_stdexcept.cpp',
'third_party/libcxxabi/src/stdlib_typeinfo.cpp',
],
},
{
'target_name': 'gpr',
'type': 'static_library',

@ -27,14 +27,6 @@
* - some syscalls to be made directly
*/
/*
* Defines GRPC_USE_CPP_STD_LIB to use standard C++ library instead of
* in-house library if possible. (e.g. std::map)
*/
#ifndef GRPC_USE_CPP_STD_LIB
#define GRPC_USE_CPP_STD_LIB 1
#endif
/* Get windows.h included everywhere (we need it) */
#if defined(_WIN64) || defined(WIN64) || defined(_WIN32) || defined(WIN32)
#ifndef WIN32_LEAN_AND_MEAN

@ -772,19 +772,23 @@ class CallOpClientRecvStatus {
void FinishOp(bool* /*status*/) {
if (recv_status_ == nullptr || hijacked_) return;
grpc::string binary_error_details = metadata_map_->GetBinaryErrorDetails();
*recv_status_ =
Status(static_cast<StatusCode>(status_code_),
GRPC_SLICE_IS_EMPTY(error_message_)
? grpc::string()
: grpc::string(GRPC_SLICE_START_PTR(error_message_),
GRPC_SLICE_END_PTR(error_message_)),
binary_error_details);
client_context_->set_debug_error_string(
debug_error_string_ != nullptr ? debug_error_string_ : "");
g_core_codegen_interface->grpc_slice_unref(error_message_);
if (debug_error_string_ != nullptr) {
g_core_codegen_interface->gpr_free((void*)debug_error_string_);
if (status_code_ == StatusCode::OK) {
*recv_status_ = Status();
GPR_CODEGEN_DEBUG_ASSERT(GRPC_SLICE_IS_EMPTY(error_message_));
GPR_CODEGEN_DEBUG_ASSERT(debug_error_string_ == nullptr);
} else {
*recv_status_ =
Status(static_cast<StatusCode>(status_code_),
GRPC_SLICE_IS_EMPTY(error_message_)
? grpc::string()
: grpc::string(GRPC_SLICE_START_PTR(error_message_),
GRPC_SLICE_END_PTR(error_message_)),
metadata_map_->GetBinaryErrorDetails());
g_core_codegen_interface->grpc_slice_unref(error_message_);
if (debug_error_string_ != nullptr) {
client_context_->set_debug_error_string(debug_error_string_);
g_core_codegen_interface->gpr_free((void*)debug_error_string_);
}
}
}

@ -101,7 +101,6 @@
<file baseinstalldir="/" name="src/core/lib/gpr/tls_pthread.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gpr/tmpfile.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gpr/useful.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/abstract.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/arena.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/atomic.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/fork.h" role="src" />
@ -114,7 +113,6 @@
<file baseinstalldir="/" name="src/core/lib/gprpp/map.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/memory.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/mpscq.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/pair.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/sync.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/thd.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/profiling/timers.h" role="src" />

@ -147,16 +147,21 @@ EXTRA_ENV_COMPILE_ARGS = os.environ.get('GRPC_PYTHON_CFLAGS', None)
EXTRA_ENV_LINK_ARGS = os.environ.get('GRPC_PYTHON_LDFLAGS', None)
if EXTRA_ENV_COMPILE_ARGS is None:
EXTRA_ENV_COMPILE_ARGS = ' -std=c++11'
if 'win32' in sys.platform and sys.version_info < (3, 5):
EXTRA_ENV_COMPILE_ARGS += ' -D_hypot=hypot'
# We use define flags here and don't directly add to DEFINE_MACROS below to
# ensure that the expert user/builder has a way of turning it off (via the
# envvars) without adding yet more GRPC-specific envvars.
# See https://sourceforge.net/p/mingw-w64/bugs/363/
if '32' in platform.architecture()[0]:
EXTRA_ENV_COMPILE_ARGS += ' -D_ftime=_ftime32 -D_timeb=__timeb32 -D_ftime_s=_ftime32_s'
if 'win32' in sys.platform:
if sys.version_info < (3, 5):
EXTRA_ENV_COMPILE_ARGS += ' -D_hypot=hypot'
# We use define flags here and don't directly add to DEFINE_MACROS below to
# ensure that the expert user/builder has a way of turning it off (via the
# envvars) without adding yet more GRPC-specific envvars.
# See https://sourceforge.net/p/mingw-w64/bugs/363/
if '32' in platform.architecture()[0]:
EXTRA_ENV_COMPILE_ARGS += ' -D_ftime=_ftime32 -D_timeb=__timeb32 -D_ftime_s=_ftime32_s'
else:
EXTRA_ENV_COMPILE_ARGS += ' -D_ftime=_ftime64 -D_timeb=__timeb64'
else:
EXTRA_ENV_COMPILE_ARGS += ' -D_ftime=_ftime64 -D_timeb=__timeb64'
# We need to statically link the C++ Runtime, only the C runtime is
# available dynamically
EXTRA_ENV_COMPILE_ARGS += ' /MT'
elif "linux" in sys.platform:
EXTRA_ENV_COMPILE_ARGS += ' -std=gnu99 -fvisibility=hidden -fno-wrapv -fno-exceptions'
elif "darwin" in sys.platform:

@ -106,7 +106,7 @@ inline grpc::string RubyPackage(const grpc::protobuf::FileDescriptor* file) {
if (file->options().has_ruby_package()) {
package_name = file->options().ruby_package();
// If :: is in the package convert the Ruby formated name
// If :: is in the package convert the Ruby formatted name
// -> A::B::C
// to use the dot seperator notation
// -> A.B.C

@ -26,12 +26,12 @@ namespace grpc_core {
namespace {
template <typename EntryType>
Map<StringView, double, StringLess> ParseMap(
std::map<StringView, double, StringLess> ParseMap(
udpa_data_orca_v1_OrcaLoadReport* msg,
EntryType** (*entry_func)(udpa_data_orca_v1_OrcaLoadReport*, size_t*),
upb_strview (*key_func)(const EntryType*),
double (*value_func)(const EntryType*), Arena* arena) {
Map<StringView, double, StringLess> result;
std::map<StringView, double, StringLess> result;
size_t size;
const auto* const* entries = entry_func(msg, &size);
for (size_t i = 0; i < size; ++i) {

@ -26,6 +26,9 @@
#include <stdio.h>
#include <string.h>
#include <map>
#include <set>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
@ -179,9 +182,17 @@ class ChannelData {
return static_cast<int>(external_watchers_.size());
}
void AddConnectivityWatcher(
grpc_connectivity_state initial_state,
OrphanablePtr<AsyncConnectivityStateWatcherInterface> watcher);
void RemoveConnectivityWatcher(
AsyncConnectivityStateWatcherInterface* watcher);
private:
class SubchannelWrapper;
class ClientChannelControlHelper;
class ConnectivityWatcherAdder;
class ConnectivityWatcherRemover;
// Represents a pending connectivity callback from an external caller
// via grpc_client_channel_watch_connectivity_state().
@ -282,18 +293,16 @@ class ChannelData {
RefCountedPtr<ServiceConfig> saved_service_config_;
bool received_first_resolver_result_ = false;
// The number of SubchannelWrapper instances referencing a given Subchannel.
Map<Subchannel*, int> subchannel_refcount_map_;
std::map<Subchannel*, int> subchannel_refcount_map_;
// The set of SubchannelWrappers that currently exist.
// No need to hold a ref, since the map is updated in the control-plane
// combiner when the SubchannelWrappers are created and destroyed.
// TODO(roth): We really want to use a set here, not a map. Since we don't
// currently have a set implementation, we use a map and ignore the value.
Map<SubchannelWrapper*, bool> subchannel_wrappers_;
std::set<SubchannelWrapper*> subchannel_wrappers_;
// Pending ConnectedSubchannel updates for each SubchannelWrapper.
// Updates are queued here in the control plane combiner and then applied
// in the data plane mutex when the picker is updated.
Map<RefCountedPtr<SubchannelWrapper>, RefCountedPtr<ConnectedSubchannel>,
RefCountedPtrLess<SubchannelWrapper>>
std::map<RefCountedPtr<SubchannelWrapper>, RefCountedPtr<ConnectedSubchannel>,
RefCountedPtrLess<SubchannelWrapper>>
pending_subchannel_updates_;
//
@ -314,7 +323,7 @@ class ChannelData {
// synchronously via grpc_channel_num_external_connectivity_watchers().
//
mutable Mutex external_watchers_mu_;
Map<grpc_closure*, ExternalConnectivityWatcher*> external_watchers_;
std::map<grpc_closure*, ExternalConnectivityWatcher*> external_watchers_;
};
//
@ -753,11 +762,9 @@ class CallData {
LbCallState lb_call_state_;
const LoadBalancingPolicy::BackendMetricData* backend_metric_data_ = nullptr;
RefCountedPtr<ConnectedSubchannel> connected_subchannel_;
void (*lb_recv_trailing_metadata_ready_)(
void* user_data, grpc_error* error,
LoadBalancingPolicy::MetadataInterface* recv_trailing_metadata,
LoadBalancingPolicy::CallState* call_state) = nullptr;
void* lb_recv_trailing_metadata_ready_user_data_ = nullptr;
std::function<void(grpc_error*, LoadBalancingPolicy::MetadataInterface*,
LoadBalancingPolicy::CallState*)>
lb_recv_trailing_metadata_ready_;
grpc_closure pick_closure_;
// For intercepting recv_trailing_metadata_ready for the LB policy.
@ -852,7 +859,7 @@ class ChannelData::SubchannelWrapper : public SubchannelInterface {
}
++it->second;
}
chand_->subchannel_wrappers_[this] = true;
chand_->subchannel_wrappers_.insert(this);
}
~SubchannelWrapper() {
@ -1107,7 +1114,7 @@ class ChannelData::SubchannelWrapper : public SubchannelInterface {
// subchannel. This is needed so that when the LB policy calls
// CancelConnectivityStateWatch() with its watcher, we know the
// corresponding WrapperWatcher to cancel on the underlying subchannel.
Map<ConnectivityStateWatcherInterface*, WatcherWrapper*> watcher_map_;
std::map<ConnectivityStateWatcherInterface*, WatcherWrapper*> watcher_map_;
// To be accessed only in the control plane combiner.
RefCountedPtr<ConnectedSubchannel> connected_subchannel_;
// To be accessed only in the data plane mutex.
@ -1151,11 +1158,11 @@ void ChannelData::ExternalConnectivityWatcher::Notify(
MemoryOrder::RELAXED)) {
return; // Already done.
}
// Remove external watcher.
chand_->RemoveExternalConnectivityWatcher(on_complete_, /*cancel=*/false);
// Report new state to the user.
*state_ = state;
GRPC_CLOSURE_SCHED(on_complete_, GRPC_ERROR_NONE);
// Remove external watcher.
chand_->RemoveExternalConnectivityWatcher(on_complete_, /*cancel=*/false);
// Hop back into the combiner to clean up.
// Not needed in state SHUTDOWN, because the tracker will
// automatically remove all watchers in that case.
@ -1201,6 +1208,72 @@ void ChannelData::ExternalConnectivityWatcher::RemoveWatcherLocked(
self->chand_->state_tracker_.RemoveWatcher(self);
}
//
// ChannelData::ConnectivityWatcherAdder
//
class ChannelData::ConnectivityWatcherAdder {
public:
ConnectivityWatcherAdder(
ChannelData* chand, grpc_connectivity_state initial_state,
OrphanablePtr<AsyncConnectivityStateWatcherInterface> watcher)
: chand_(chand),
initial_state_(initial_state),
watcher_(std::move(watcher)) {
GRPC_CHANNEL_STACK_REF(chand_->owning_stack_, "ConnectivityWatcherAdder");
GRPC_CLOSURE_INIT(&closure_, &ConnectivityWatcherAdder::AddWatcherLocked,
this, grpc_combiner_scheduler(chand_->combiner_));
GRPC_CLOSURE_SCHED(&closure_, GRPC_ERROR_NONE);
}
private:
static void AddWatcherLocked(void* arg, grpc_error* error) {
ConnectivityWatcherAdder* self =
static_cast<ConnectivityWatcherAdder*>(arg);
self->chand_->state_tracker_.AddWatcher(self->initial_state_,
std::move(self->watcher_));
GRPC_CHANNEL_STACK_UNREF(self->chand_->owning_stack_,
"ConnectivityWatcherAdder");
Delete(self);
}
ChannelData* chand_;
grpc_connectivity_state initial_state_;
OrphanablePtr<AsyncConnectivityStateWatcherInterface> watcher_;
grpc_closure closure_;
};
//
// ChannelData::ConnectivityWatcherRemover
//
class ChannelData::ConnectivityWatcherRemover {
public:
ConnectivityWatcherRemover(ChannelData* chand,
AsyncConnectivityStateWatcherInterface* watcher)
: chand_(chand), watcher_(watcher) {
GRPC_CHANNEL_STACK_REF(chand_->owning_stack_, "ConnectivityWatcherRemover");
GRPC_CLOSURE_INIT(&closure_,
&ConnectivityWatcherRemover::RemoveWatcherLocked, this,
grpc_combiner_scheduler(chand_->combiner_));
GRPC_CLOSURE_SCHED(&closure_, GRPC_ERROR_NONE);
}
private:
static void RemoveWatcherLocked(void* arg, grpc_error* error) {
ConnectivityWatcherRemover* self =
static_cast<ConnectivityWatcherRemover*>(arg);
self->chand_->state_tracker_.RemoveWatcher(self->watcher_);
GRPC_CHANNEL_STACK_UNREF(self->chand_->owning_stack_,
"ConnectivityWatcherRemover");
Delete(self);
}
ChannelData* chand_;
AsyncConnectivityStateWatcherInterface* watcher_;
grpc_closure closure_;
};
//
// ChannelData::ClientChannelControlHelper
//
@ -1515,9 +1588,7 @@ void ChannelData::CreateResolvingLoadBalancingPolicyLocked() {
// Instantiate resolving LB policy.
LoadBalancingPolicy::Args lb_args;
lb_args.combiner = combiner_;
lb_args.channel_control_helper =
UniquePtr<LoadBalancingPolicy::ChannelControlHelper>(
New<ClientChannelControlHelper>(this));
lb_args.channel_control_helper = MakeUnique<ClientChannelControlHelper>(this);
lb_args.args = channel_args_;
UniquePtr<char> target_uri(gpr_strdup(target_uri_.get()));
resolving_lb_policy_.reset(New<ResolvingLoadBalancingPolicy>(
@ -1670,8 +1741,8 @@ bool ChannelData::ProcessResolverResultLocked(
chand->health_check_service_name_.reset();
}
// Update health check service name used by existing subchannel wrappers.
for (const auto& p : chand->subchannel_wrappers_) {
p.first->UpdateHealthCheckServiceName(
for (auto* subchannel_wrapper : chand->subchannel_wrappers_) {
subchannel_wrapper->UpdateHealthCheckServiceName(
UniquePtr<char>(gpr_strdup(chand->health_check_service_name_.get())));
}
// Save service config.
@ -1791,9 +1862,8 @@ void ChannelData::StartTransportOpLocked(void* arg, grpc_error* ignored) {
MemoryOrder::RELEASE);
chand->UpdateStateAndPickerLocked(
GRPC_CHANNEL_SHUTDOWN, "shutdown from API",
UniquePtr<LoadBalancingPolicy::SubchannelPicker>(
New<LoadBalancingPolicy::TransientFailurePicker>(
GRPC_ERROR_REF(op->disconnect_with_error))));
MakeUnique<LoadBalancingPolicy::TransientFailurePicker>(
GRPC_ERROR_REF(op->disconnect_with_error)));
}
}
GRPC_CHANNEL_STACK_UNREF(chand->owning_stack_, "start_transport_op");
@ -1888,6 +1958,17 @@ grpc_connectivity_state ChannelData::CheckConnectivityState(
return out;
}
void ChannelData::AddConnectivityWatcher(
grpc_connectivity_state initial_state,
OrphanablePtr<AsyncConnectivityStateWatcherInterface> watcher) {
New<ConnectivityWatcherAdder>(this, initial_state, std::move(watcher));
}
void ChannelData::RemoveConnectivityWatcher(
AsyncConnectivityStateWatcherInterface* watcher) {
New<ConnectivityWatcherRemover>(this, watcher);
}
//
// CallData implementation
//
@ -2179,9 +2260,8 @@ void CallData::RecvTrailingMetadataReadyForLoadBalancingPolicy(
CallData* calld = static_cast<CallData*>(arg);
// Invoke callback to LB policy.
Metadata trailing_metadata(calld, calld->recv_trailing_metadata_);
calld->lb_recv_trailing_metadata_ready_(
calld->lb_recv_trailing_metadata_ready_user_data_, error,
&trailing_metadata, &calld->lb_call_state_);
calld->lb_recv_trailing_metadata_ready_(error, &trailing_metadata,
&calld->lb_call_state_);
// Chain to original callback.
GRPC_CLOSURE_RUN(calld->original_recv_trailing_metadata_ready_,
GRPC_ERROR_REF(error));
@ -3880,8 +3960,6 @@ bool CallData::PickSubchannelLocked(grpc_call_element* elem,
GPR_ASSERT(connected_subchannel_ != nullptr);
}
lb_recv_trailing_metadata_ready_ = result.recv_trailing_metadata_ready;
lb_recv_trailing_metadata_ready_user_data_ =
result.recv_trailing_metadata_ready_user_data;
*error = result.error;
return true;
}
@ -3939,6 +4017,21 @@ void grpc_client_channel_watch_connectivity_state(
watcher_timer_init);
}
void grpc_client_channel_start_connectivity_watch(
grpc_channel_element* elem, grpc_connectivity_state initial_state,
grpc_core::OrphanablePtr<grpc_core::AsyncConnectivityStateWatcherInterface>
watcher) {
auto* chand = static_cast<ChannelData*>(elem->channel_data);
chand->AddConnectivityWatcher(initial_state, std::move(watcher));
}
void grpc_client_channel_stop_connectivity_watch(
grpc_channel_element* elem,
grpc_core::AsyncConnectivityStateWatcherInterface* watcher) {
auto* chand = static_cast<ChannelData*>(elem->channel_data);
chand->RemoveConnectivityWatcher(watcher);
}
grpc_core::RefCountedPtr<grpc_core::SubchannelCall>
grpc_client_channel_get_subchannel_call(grpc_call_element* elem) {
auto* calld = static_cast<CallData*>(elem->call_data);

@ -46,17 +46,35 @@ grpc_connectivity_state grpc_client_channel_check_connectivity_state(
int grpc_client_channel_num_external_connectivity_watchers(
grpc_channel_element* elem);
// TODO(roth): This function is used both when handling external
// connectivity watchers and for LB policies like grpclb and xds that
// contain nested channels. In the latter case, we ideally want
// something closer to the normal connectivity state tracker API.
// When we have time, consider refactoring this somehow to allow each
// use-case to be handled more cleanly.
// Starts a one-time connectivity state watch. When the channel's state
// becomes different from *state, sets *state to the new state and
// schedules on_complete. The watcher_timer_init callback is invoked as
// soon as the watch is actually started (i.e., after hopping into the
// client channel combiner). I/O will be serviced via pollent.
//
// This is intended to be used when starting a watch from outside of C-core
// via grpc_channel_watch_connectivity_state(). It should not be used
// by other callers.
void grpc_client_channel_watch_connectivity_state(
grpc_channel_element* elem, grpc_polling_entity pollent,
grpc_connectivity_state* state, grpc_closure* on_complete,
grpc_closure* watcher_timer_init);
// Starts and stops a connectivity watch. The watcher will be initially
// notified as soon as the state changes from initial_state and then on
// every subsequent state change until either the watch is stopped or
// it is notified that the state has changed to SHUTDOWN.
//
// This is intended to be used when starting watches from code inside of
// C-core (e.g., for a nested control plane channel for things like xds).
void grpc_client_channel_start_connectivity_watch(
grpc_channel_element* elem, grpc_connectivity_state initial_state,
grpc_core::OrphanablePtr<grpc_core::AsyncConnectivityStateWatcherInterface>
watcher);
void grpc_client_channel_stop_connectivity_watch(
grpc_channel_element* elem,
grpc_core::AsyncConnectivityStateWatcherInterface* watcher);
/* Debug helper: pull the subchannel call from a call stack element */
grpc_core::RefCountedPtr<grpc_core::SubchannelCall>
grpc_client_channel_get_subchannel_call(grpc_call_element* elem);

@ -24,7 +24,6 @@
#include <grpc/impl/codegen/grpc_types.h>
#include "src/core/ext/filters/client_channel/subchannel.h"
#include "src/core/lib/gprpp/abstract.h"
namespace grpc_core {
@ -33,8 +32,7 @@ class ClientChannelFactory {
virtual ~ClientChannelFactory() = default;
// Creates a subchannel with the specified args.
virtual Subchannel* CreateSubchannel(const grpc_channel_args* args)
GRPC_ABSTRACT;
virtual Subchannel* CreateSubchannel(const grpc_channel_args* args) = 0;
// Returns a channel arg containing the specified factory.
static grpc_arg CreateChannelArg(ClientChannelFactory* factory);
@ -42,8 +40,6 @@ class ClientChannelFactory {
// Returns the factory from args, or null if not found.
static ClientChannelFactory* GetFromChannelArgs(
const grpc_channel_args* args);
GRPC_ABSTRACT_BASE_CLASS
};
} // namespace grpc_core

@ -47,12 +47,14 @@ HealthCheckClient::HealthCheckClient(
const char* service_name,
RefCountedPtr<ConnectedSubchannel> connected_subchannel,
grpc_pollset_set* interested_parties,
RefCountedPtr<channelz::SubchannelNode> channelz_node)
RefCountedPtr<channelz::SubchannelNode> channelz_node,
RefCountedPtr<ConnectivityStateWatcherInterface> watcher)
: InternallyRefCounted<HealthCheckClient>(&grpc_health_check_client_trace),
service_name_(service_name),
connected_subchannel_(std::move(connected_subchannel)),
interested_parties_(interested_parties),
channelz_node_(std::move(channelz_node)),
watcher_(std::move(watcher)),
retry_backoff_(
BackOff::Options()
.set_initial_backoff(
@ -73,43 +75,21 @@ HealthCheckClient::~HealthCheckClient() {
if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
gpr_log(GPR_INFO, "destroying HealthCheckClient %p", this);
}
GRPC_ERROR_UNREF(error_);
}
void HealthCheckClient::NotifyOnHealthChange(grpc_connectivity_state* state,
grpc_closure* closure) {
MutexLock lock(&mu_);
GPR_ASSERT(notify_state_ == nullptr);
if (*state != state_) {
*state = state_;
GRPC_CLOSURE_SCHED(closure, GRPC_ERROR_REF(error_));
return;
}
notify_state_ = state;
on_health_changed_ = closure;
}
void HealthCheckClient::SetHealthStatus(grpc_connectivity_state state,
grpc_error* error) {
const char* reason) {
MutexLock lock(&mu_);
SetHealthStatusLocked(state, error);
SetHealthStatusLocked(state, reason);
}
void HealthCheckClient::SetHealthStatusLocked(grpc_connectivity_state state,
grpc_error* error) {
const char* reason) {
if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
gpr_log(GPR_INFO, "HealthCheckClient %p: setting state=%d error=%s", this,
state, grpc_error_string(error));
}
if (notify_state_ != nullptr && *notify_state_ != state) {
*notify_state_ = state;
notify_state_ = nullptr;
GRPC_CLOSURE_SCHED(on_health_changed_, GRPC_ERROR_REF(error));
on_health_changed_ = nullptr;
gpr_log(GPR_INFO, "HealthCheckClient %p: setting state=%s reason=%s", this,
ConnectivityStateName(state), reason);
}
state_ = state;
GRPC_ERROR_UNREF(error_);
error_ = error;
if (watcher_ != nullptr) watcher_->Notify(state);
}
void HealthCheckClient::Orphan() {
@ -118,13 +98,8 @@ void HealthCheckClient::Orphan() {
}
{
MutexLock lock(&mu_);
if (on_health_changed_ != nullptr) {
*notify_state_ = GRPC_CHANNEL_SHUTDOWN;
notify_state_ = nullptr;
GRPC_CLOSURE_SCHED(on_health_changed_, GRPC_ERROR_NONE);
on_health_changed_ = nullptr;
}
shutting_down_ = true;
watcher_.reset();
call_state_.reset();
if (retry_timer_callback_pending_) {
grpc_timer_cancel(&retry_timer_);
@ -141,7 +116,7 @@ void HealthCheckClient::StartCall() {
void HealthCheckClient::StartCallLocked() {
if (shutting_down_) return;
GPR_ASSERT(call_state_ == nullptr);
SetHealthStatusLocked(GRPC_CHANNEL_CONNECTING, GRPC_ERROR_NONE);
SetHealthStatusLocked(GRPC_CHANNEL_CONNECTING, "starting health watch");
call_state_ = MakeOrphanable<CallState>(Ref(), interested_parties_);
if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
gpr_log(GPR_INFO, "HealthCheckClient %p: created CallState %p", this,
@ -152,10 +127,8 @@ void HealthCheckClient::StartCallLocked() {
void HealthCheckClient::StartRetryTimer() {
MutexLock lock(&mu_);
SetHealthStatusLocked(
GRPC_CHANNEL_TRANSIENT_FAILURE,
GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"health check call failed; will retry after backoff"));
SetHealthStatusLocked(GRPC_CHANNEL_TRANSIENT_FAILURE,
"health check call failed; will retry after backoff");
grpc_millis next_try = retry_backoff_.NextAttemptTime();
if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) {
gpr_log(GPR_INFO, "HealthCheckClient %p: health check call lost...", this);
@ -489,10 +462,10 @@ void HealthCheckClient::CallState::DoneReadingRecvMessage(grpc_error* error) {
const bool healthy = DecodeResponse(&recv_message_buffer_, &error);
const grpc_connectivity_state state =
healthy ? GRPC_CHANNEL_READY : GRPC_CHANNEL_TRANSIENT_FAILURE;
if (error == GRPC_ERROR_NONE && !healthy) {
error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("backend unhealthy");
}
health_check_client_->SetHealthStatus(state, error);
const char* reason = error == GRPC_ERROR_NONE && !healthy
? "backend unhealthy"
: grpc_error_string(error);
health_check_client_->SetHealthStatus(state, reason);
seen_response_.Store(true, MemoryOrder::RELEASE);
grpc_slice_buffer_destroy_internal(&recv_message_buffer_);
// Start another recv_message batch.
@ -603,7 +576,7 @@ void HealthCheckClient::CallState::RecvTrailingMetadataReady(
grpc_slice_from_static_string(kErrorMessage));
}
self->health_check_client_->SetHealthStatus(GRPC_CHANNEL_READY,
GRPC_ERROR_NONE);
kErrorMessage);
retry = false;
}
self->CallEnded(retry);

@ -47,16 +47,11 @@ class HealthCheckClient : public InternallyRefCounted<HealthCheckClient> {
HealthCheckClient(const char* service_name,
RefCountedPtr<ConnectedSubchannel> connected_subchannel,
grpc_pollset_set* interested_parties,
RefCountedPtr<channelz::SubchannelNode> channelz_node);
RefCountedPtr<channelz::SubchannelNode> channelz_node,
RefCountedPtr<ConnectivityStateWatcherInterface> watcher);
~HealthCheckClient();
// When the health state changes from *state, sets *state to the new
// value and schedules closure.
// Only one closure can be outstanding at a time.
void NotifyOnHealthChange(grpc_connectivity_state* state,
grpc_closure* closure);
void Orphan() override;
private:
@ -151,9 +146,9 @@ class HealthCheckClient : public InternallyRefCounted<HealthCheckClient> {
void StartRetryTimer();
static void OnRetryTimer(void* arg, grpc_error* error);
void SetHealthStatus(grpc_connectivity_state state, grpc_error* error);
void SetHealthStatus(grpc_connectivity_state state, const char* reason);
void SetHealthStatusLocked(grpc_connectivity_state state,
grpc_error* error); // Requires holding mu_.
const char* reason); // Requires holding mu_.
const char* service_name_; // Do not own.
RefCountedPtr<ConnectedSubchannel> connected_subchannel_;
@ -161,10 +156,7 @@ class HealthCheckClient : public InternallyRefCounted<HealthCheckClient> {
RefCountedPtr<channelz::SubchannelNode> channelz_node_;
Mutex mu_;
grpc_connectivity_state state_ = GRPC_CHANNEL_CONNECTING;
grpc_error* error_ = GRPC_ERROR_NONE;
grpc_connectivity_state* notify_state_ = nullptr;
grpc_closure* on_health_changed_ = nullptr;
RefCountedPtr<ConnectivityStateWatcherInterface> watcher_;
bool shutting_down_ = false;
// The data associated with the current health check call. It holds a ref

@ -356,5 +356,5 @@ void grpc_http_connect_register_handshaker_factory() {
using namespace grpc_core;
HandshakerRegistry::RegisterHandshakerFactory(
true /* at_start */, HANDSHAKER_CLIENT,
UniquePtr<HandshakerFactory>(New<HttpConnectHandshakerFactory>()));
MakeUnique<HttpConnectHandshakerFactory>());
}

@ -24,7 +24,6 @@
#include "src/core/ext/filters/client_channel/server_address.h"
#include "src/core/ext/filters/client_channel/service_config.h"
#include "src/core/ext/filters/client_channel/subchannel_interface.h"
#include "src/core/lib/gprpp/abstract.h"
#include "src/core/lib/gprpp/map.h"
#include "src/core/lib/gprpp/orphanable.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
@ -91,11 +90,11 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
/// Application-specific requests cost metrics. Metric names are
/// determined by the application. Each value is an absolute cost
/// (e.g. 3487 bytes of storage) associated with the request.
Map<StringView, double, StringLess> request_cost;
std::map<StringView, double, StringLess> request_cost;
/// Application-specific resource utilization metrics. Metric names
/// are determined by the application. Each value is expressed as a
/// fraction of total resources available.
Map<StringView, double, StringLess> utilization;
std::map<StringView, double, StringLess> utilization;
};
/// Interface for accessing per-call state.
@ -109,13 +108,11 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
/// automatically freed when the call is complete.
/// It is more efficient to use this than to allocate memory directly
/// for allocations that need to be made on a per-call basis.
virtual void* Alloc(size_t size) GRPC_ABSTRACT;
virtual void* Alloc(size_t size) = 0;
/// Returns the backend metric data returned by the server for the call,
/// or null if no backend metric data was returned.
virtual const BackendMetricData* GetBackendMetricData() GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS
virtual const BackendMetricData* GetBackendMetricData() = 0;
};
/// Interface for accessing metadata.
@ -134,20 +131,18 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
/// Implementations must ensure that the key and value remain alive
/// until the call ends. If desired, they may be allocated via
/// CallState::Alloc().
virtual void Add(StringView key, StringView value) GRPC_ABSTRACT;
virtual void Add(StringView key, StringView value) = 0;
/// Iteration interface.
virtual Iterator Begin() const GRPC_ABSTRACT;
virtual bool IsEnd(Iterator it) const GRPC_ABSTRACT;
virtual void Next(Iterator* it) const GRPC_ABSTRACT;
virtual StringView Key(Iterator it) const GRPC_ABSTRACT;
virtual StringView Value(Iterator it) const GRPC_ABSTRACT;
virtual Iterator Begin() const = 0;
virtual bool IsEnd(Iterator it) const = 0;
virtual void Next(Iterator* it) const = 0;
virtual StringView Key(Iterator it) const = 0;
virtual StringView Value(Iterator it) const = 0;
/// Removes the element pointed to by \a it, which is modified to
/// point to the next element.
virtual void Erase(Iterator* it) GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS
virtual void Erase(Iterator* it) = 0;
};
/// Arguments used when picking a subchannel for a call.
@ -194,20 +189,14 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
/// Used only if type is PICK_COMPLETE.
/// Callback set by LB policy to be notified of trailing metadata.
/// The user_data argument will be set to the
/// recv_trailing_metadata_ready_user_data field.
/// recv_trailing_metadata will be set to the metadata, which may be
/// modified by the callback. The callback does not take ownership,
/// however, so any data that needs to be used after returning must
/// be copied.
/// call_state can be used to obtain backend metric data.
// TODO(roth): Replace grpc_error with something better before we allow
// people outside of gRPC team to use this API.
void (*recv_trailing_metadata_ready)(
void* user_data, grpc_error* error,
MetadataInterface* recv_trailing_metadata,
CallState* call_state) = nullptr;
void* recv_trailing_metadata_ready_user_data = nullptr;
/// If set by LB policy, the client channel will invoke the callback
/// when trailing metadata is returned.
/// The metadata may be modified by the callback. However, the callback
/// does not take ownership, so any data that needs to be used after
/// returning must be copied.
/// The call state can be used to obtain backend metric data.
std::function<void(grpc_error*, MetadataInterface*, CallState*)>
recv_trailing_metadata_ready;
};
/// A subchannel picker is the object used to pick the subchannel to
@ -229,9 +218,7 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
SubchannelPicker() = default;
virtual ~SubchannelPicker() = default;
virtual PickResult Pick(PickArgs args) GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS
virtual PickResult Pick(PickArgs args) = 0;
};
/// A proxy object implemented by the client channel and used by the
@ -246,22 +233,19 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
/// Creates a new subchannel with the specified channel args.
virtual RefCountedPtr<SubchannelInterface> CreateSubchannel(
const grpc_channel_args& args) GRPC_ABSTRACT;
const grpc_channel_args& args) = 0;
/// Sets the connectivity state and returns a new picker to be used
/// by the client channel.
virtual void UpdateState(grpc_connectivity_state state,
UniquePtr<SubchannelPicker>) GRPC_ABSTRACT;
UniquePtr<SubchannelPicker>) = 0;
/// Requests that the resolver re-resolve.
virtual void RequestReresolution() GRPC_ABSTRACT;
virtual void RequestReresolution() = 0;
/// Adds a trace message associated with the channel.
enum TraceSeverity { TRACE_INFO, TRACE_WARNING, TRACE_ERROR };
virtual void AddTraceEvent(TraceSeverity severity,
StringView message) GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS
virtual void AddTraceEvent(TraceSeverity severity, StringView message) = 0;
};
/// Interface for configuration data used by an LB policy implementation.
@ -272,9 +256,7 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
virtual ~Config() = default;
// Returns the load balancing policy name
virtual const char* name() const GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS
virtual const char* name() const = 0;
};
/// Data passed to the UpdateLocked() method when new addresses and
@ -319,12 +301,12 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
LoadBalancingPolicy& operator=(const LoadBalancingPolicy&) = delete;
/// Returns the name of the LB policy.
virtual const char* name() const GRPC_ABSTRACT;
virtual const char* name() const = 0;
/// Updates the policy with new data from the resolver. Will be invoked
/// immediately after LB policy is constructed, and then again whenever
/// the resolver returns a new result.
virtual void UpdateLocked(UpdateArgs) GRPC_ABSTRACT; // NOLINT
virtual void UpdateLocked(UpdateArgs) = 0; // NOLINT
/// Tries to enter a READY connectivity state.
/// This is a no-op by default, since most LB policies never go into
@ -332,7 +314,7 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
virtual void ExitIdleLocked() {}
/// Resets connection backoff.
virtual void ResetBackoffLocked() GRPC_ABSTRACT;
virtual void ResetBackoffLocked() = 0;
grpc_pollset_set* interested_parties() const { return interested_parties_; }
@ -370,8 +352,6 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
grpc_error* error_;
};
GRPC_ABSTRACT_BASE_CLASS
protected:
grpc_combiner* combiner() const { return combiner_; }
@ -382,7 +362,7 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> {
}
/// Shuts down the policy.
virtual void ShutdownLocked() GRPC_ABSTRACT;
virtual void ShutdownLocked() = 0;
private:
/// Combiner under which LB policy actions take place.

@ -716,9 +716,8 @@ void GrpcLb::Helper::UpdateState(grpc_connectivity_state state,
client_stats = parent_->lb_calld_->client_stats()->Ref();
}
parent_->channel_control_helper()->UpdateState(
state, UniquePtr<SubchannelPicker>(
New<Picker>(parent_.get(), parent_->serverlist_,
std::move(picker), std::move(client_stats))));
state, MakeUnique<Picker>(parent_.get(), parent_->serverlist_,
std::move(picker), std::move(client_stats)));
}
void GrpcLb::Helper::RequestReresolution() {
@ -1794,7 +1793,7 @@ class GrpcLbFactory : public LoadBalancingPolicyFactory {
public:
OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
LoadBalancingPolicy::Args args) const override {
return OrphanablePtr<LoadBalancingPolicy>(New<GrpcLb>(std::move(args)));
return MakeOrphanable<GrpcLb>(std::move(args));
}
const char* name() const override { return kGrpclb; }
@ -1869,8 +1868,7 @@ bool maybe_add_client_load_reporting_filter(grpc_channel_stack_builder* builder,
void grpc_lb_policy_grpclb_init() {
grpc_core::LoadBalancingPolicyRegistry::Builder::
RegisterLoadBalancingPolicyFactory(
grpc_core::UniquePtr<grpc_core::LoadBalancingPolicyFactory>(
grpc_core::New<grpc_core::GrpcLbFactory>()));
grpc_core::MakeUnique<grpc_core::GrpcLbFactory>());
grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
maybe_add_client_load_reporting_filter,

@ -201,7 +201,7 @@ void PickFirst::AttemptToConnectUsingLatestUpdateArgsLocked() {
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
channel_control_helper()->UpdateState(
GRPC_CHANNEL_TRANSIENT_FAILURE,
UniquePtr<SubchannelPicker>(New<TransientFailurePicker>(error)));
MakeUnique<TransientFailurePicker>(error));
return;
}
// If one of the subchannels in the new list is already in state
@ -319,12 +319,11 @@ void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked(
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_TRANSIENT_FAILURE,
UniquePtr<SubchannelPicker>(New<TransientFailurePicker>(error)));
MakeUnique<TransientFailurePicker>(error));
} else {
p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_CONNECTING,
UniquePtr<SubchannelPicker>(
New<QueuePicker>(p->Ref(DEBUG_LOCATION, "QueuePicker"))));
MakeUnique<QueuePicker>(p->Ref(DEBUG_LOCATION, "QueuePicker")));
}
} else {
if (connectivity_state == GRPC_CHANNEL_TRANSIENT_FAILURE) {
@ -339,20 +338,19 @@ void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked(
p->selected_ = nullptr;
p->subchannel_list_.reset();
p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_IDLE, UniquePtr<SubchannelPicker>(New<QueuePicker>(
p->Ref(DEBUG_LOCATION, "QueuePicker"))));
GRPC_CHANNEL_IDLE,
MakeUnique<QueuePicker>(p->Ref(DEBUG_LOCATION, "QueuePicker")));
} else {
// This is unlikely but can happen when a subchannel has been asked
// to reconnect by a different channel and this channel has dropped
// some connectivity state notifications.
if (connectivity_state == GRPC_CHANNEL_READY) {
p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_READY,
UniquePtr<SubchannelPicker>(New<Picker>(subchannel()->Ref())));
GRPC_CHANNEL_READY, MakeUnique<Picker>(subchannel()->Ref()));
} else { // CONNECTING
p->channel_control_helper()->UpdateState(
connectivity_state, UniquePtr<SubchannelPicker>(New<QueuePicker>(
p->Ref(DEBUG_LOCATION, "QueuePicker"))));
connectivity_state,
MakeUnique<QueuePicker>(p->Ref(DEBUG_LOCATION, "QueuePicker")));
}
}
}
@ -396,7 +394,7 @@ void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked(
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_TRANSIENT_FAILURE,
UniquePtr<SubchannelPicker>(New<TransientFailurePicker>(error)));
MakeUnique<TransientFailurePicker>(error));
}
}
sd->CheckConnectivityStateAndStartWatchingLocked();
@ -408,8 +406,7 @@ void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked(
if (subchannel_list() == p->subchannel_list_.get()) {
p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_CONNECTING,
UniquePtr<SubchannelPicker>(
New<QueuePicker>(p->Ref(DEBUG_LOCATION, "QueuePicker"))));
MakeUnique<QueuePicker>(p->Ref(DEBUG_LOCATION, "QueuePicker")));
}
break;
}
@ -448,8 +445,7 @@ void PickFirst::PickFirstSubchannelData::ProcessUnselectedReadyLocked() {
}
p->selected_ = this;
p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_READY,
UniquePtr<SubchannelPicker>(New<Picker>(subchannel()->Ref())));
GRPC_CHANNEL_READY, MakeUnique<Picker>(subchannel()->Ref()));
for (size_t i = 0; i < subchannel_list()->num_subchannels(); ++i) {
if (i != Index()) {
subchannel_list()->subchannel(i)->ShutdownLocked();
@ -488,7 +484,7 @@ class PickFirstFactory : public LoadBalancingPolicyFactory {
public:
OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
LoadBalancingPolicy::Args args) const override {
return OrphanablePtr<LoadBalancingPolicy>(New<PickFirst>(std::move(args)));
return MakeOrphanable<PickFirst>(std::move(args));
}
const char* name() const override { return kPickFirst; }
@ -510,8 +506,7 @@ class PickFirstFactory : public LoadBalancingPolicyFactory {
void grpc_lb_policy_pick_first_init() {
grpc_core::LoadBalancingPolicyRegistry::Builder::
RegisterLoadBalancingPolicyFactory(
grpc_core::UniquePtr<grpc_core::LoadBalancingPolicyFactory>(
grpc_core::New<grpc_core::PickFirstFactory>()));
grpc_core::MakeUnique<grpc_core::PickFirstFactory>());
}
void grpc_lb_policy_pick_first_shutdown() {}

@ -321,13 +321,13 @@ void RoundRobin::RoundRobinSubchannelList::
*/
if (num_ready_ > 0) {
/* 1) READY */
p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_READY, UniquePtr<SubchannelPicker>(New<Picker>(p, this)));
p->channel_control_helper()->UpdateState(GRPC_CHANNEL_READY,
MakeUnique<Picker>(p, this));
} else if (num_connecting_ > 0) {
/* 2) CONNECTING */
p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_CONNECTING, UniquePtr<SubchannelPicker>(New<QueuePicker>(
p->Ref(DEBUG_LOCATION, "QueuePicker"))));
GRPC_CHANNEL_CONNECTING,
MakeUnique<QueuePicker>(p->Ref(DEBUG_LOCATION, "QueuePicker")));
} else if (num_transient_failure_ == num_subchannels()) {
/* 3) TRANSIENT_FAILURE */
grpc_error* error =
@ -336,7 +336,7 @@ void RoundRobin::RoundRobinSubchannelList::
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
p->channel_control_helper()->UpdateState(
GRPC_CHANNEL_TRANSIENT_FAILURE,
UniquePtr<SubchannelPicker>(New<TransientFailurePicker>(error)));
MakeUnique<TransientFailurePicker>(error));
}
}
@ -453,7 +453,7 @@ void RoundRobin::UpdateLocked(UpdateArgs args) {
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
channel_control_helper()->UpdateState(
GRPC_CHANNEL_TRANSIENT_FAILURE,
UniquePtr<SubchannelPicker>(New<TransientFailurePicker>(error)));
MakeUnique<TransientFailurePicker>(error));
subchannel_list_ = std::move(latest_pending_subchannel_list_);
} else if (subchannel_list_ == nullptr) {
// If there is no current list, immediately promote the new list to
@ -480,7 +480,7 @@ class RoundRobinFactory : public LoadBalancingPolicyFactory {
public:
OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
LoadBalancingPolicy::Args args) const override {
return OrphanablePtr<LoadBalancingPolicy>(New<RoundRobin>(std::move(args)));
return MakeOrphanable<RoundRobin>(std::move(args));
}
const char* name() const override { return kRoundRobin; }
@ -502,8 +502,7 @@ class RoundRobinFactory : public LoadBalancingPolicyFactory {
void grpc_lb_policy_round_robin_init() {
grpc_core::LoadBalancingPolicyRegistry::Builder::
RegisterLoadBalancingPolicyFactory(
grpc_core::UniquePtr<grpc_core::LoadBalancingPolicyFactory>(
grpc_core::New<grpc_core::RoundRobinFactory>()));
grpc_core::MakeUnique<grpc_core::RoundRobinFactory>());
}
void grpc_lb_policy_round_robin_shutdown() {}

@ -33,7 +33,6 @@
#include "src/core/ext/filters/client_channel/subchannel_interface.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gprpp/abstract.h"
#include "src/core/lib/gprpp/inlined_vector.h"
#include "src/core/lib/gprpp/orphanable.h"
#include "src/core/lib/gprpp/ref_counted.h"
@ -117,8 +116,6 @@ class SubchannelData {
// Cancels any pending connectivity watch and unrefs the subchannel.
void ShutdownLocked();
GRPC_ABSTRACT_BASE_CLASS
protected:
SubchannelData(
SubchannelList<SubchannelListType, SubchannelDataType>* subchannel_list,
@ -131,7 +128,7 @@ class SubchannelData {
// invoked whenever the subchannel's connectivity state changes.
// To stop watching, use CancelConnectivityWatchLocked().
virtual void ProcessConnectivityChangeLocked(
grpc_connectivity_state connectivity_state) GRPC_ABSTRACT;
grpc_connectivity_state connectivity_state) = 0;
private:
// Watcher for subchannel connectivity state.
@ -200,8 +197,6 @@ class SubchannelList : public InternallyRefCounted<SubchannelListType> {
InternallyRefCounted<SubchannelListType>::Unref(DEBUG_LOCATION, "shutdown");
}
GRPC_ABSTRACT_BASE_CLASS
protected:
SubchannelList(LoadBalancingPolicy* policy, TraceFlag* tracer,
const ServerAddressList& addresses,

@ -355,17 +355,17 @@ class XdsLb : public LoadBalancingPolicy {
void StartConnectivityWatchLocked();
void CancelConnectivityWatchLocked();
static void OnConnectivityChangedLocked(void* arg, grpc_error* error);
private:
class StateWatcher;
// The owning LB policy.
RefCountedPtr<XdsLb> xdslb_policy_;
// The channel and its status.
grpc_channel* channel_;
bool shutting_down_ = false;
grpc_connectivity_state connectivity_ = GRPC_CHANNEL_IDLE;
grpc_closure on_connectivity_changed_;
StateWatcher* watcher_ = nullptr;
// The retryable XDS calls to the LB server.
OrphanablePtr<RetryableLbCall<EdsCallState>> eds_calld_;
@ -389,11 +389,6 @@ class XdsLb : public LoadBalancingPolicy {
PickResult Pick(PickArgs args);
private:
static void RecordCallCompletion(
void* arg, grpc_error* error,
LoadBalancingPolicy::MetadataInterface* recv_trailing_metadata,
LoadBalancingPolicy::CallState* call_state);
UniquePtr<SubchannelPicker> picker_;
RefCountedPtr<XdsClientStats::LocalityStats> locality_stats_;
};
@ -407,7 +402,7 @@ class XdsLb : public LoadBalancingPolicy {
// proportional to the locality's weight. The start of the range is the
// previous value in the vector and is 0 for the first element.
using PickerList =
InlinedVector<Pair<uint32_t, RefCountedPtr<PickerWrapper>>, 1>;
InlinedVector<std::pair<uint32_t, RefCountedPtr<PickerWrapper>>, 1>;
Picker(RefCountedPtr<XdsLb> xds_policy, PickerList pickers)
: xds_policy_(std::move(xds_policy)),
pickers_(std::move(pickers)),
@ -576,8 +571,8 @@ class XdsLb : public LoadBalancingPolicy {
RefCountedPtr<XdsLb> xds_policy_;
Map<RefCountedPtr<XdsLocalityName>, OrphanablePtr<Locality>,
XdsLocalityName::Less>
std::map<RefCountedPtr<XdsLocalityName>, OrphanablePtr<Locality>,
XdsLocalityName::Less>
localities_;
const uint32_t priority_;
grpc_connectivity_state connectivity_state_ = GRPC_CHANNEL_IDLE;
@ -728,25 +723,20 @@ LoadBalancingPolicy::PickResult XdsLb::PickerWrapper::Pick(
// Record a call started.
locality_stats_->AddCallStarted();
// Intercept the recv_trailing_metadata op to record call completion.
result.recv_trailing_metadata_ready = RecordCallCompletion;
result.recv_trailing_metadata_ready_user_data =
XdsClientStats::LocalityStats* locality_stats =
locality_stats_->Ref(DEBUG_LOCATION, "LocalityStats+call").release();
result.recv_trailing_metadata_ready =
// Note: This callback does not run in either the control plane
// combiner or in the data plane mutex.
[locality_stats](grpc_error* error, MetadataInterface* metadata,
CallState* call_state) {
const bool call_failed = error != GRPC_ERROR_NONE;
locality_stats->AddCallFinished(call_failed);
locality_stats->Unref(DEBUG_LOCATION, "LocalityStats+call");
};
return result;
}
// Note that the following callback does not run in either the control plane
// combiner or the data plane combiner.
void XdsLb::PickerWrapper::RecordCallCompletion(
void* arg, grpc_error* error,
LoadBalancingPolicy::MetadataInterface* recv_trailing_metadata,
LoadBalancingPolicy::CallState* call_state) {
XdsClientStats::LocalityStats* locality_stats =
static_cast<XdsClientStats::LocalityStats*>(arg);
const bool call_failed = error != GRPC_ERROR_NONE;
locality_stats->AddCallFinished(call_failed);
locality_stats->Unref(DEBUG_LOCATION, "LocalityStats+call");
}
//
// XdsLb::Picker
//
@ -862,6 +852,39 @@ void XdsLb::FallbackHelper::AddTraceEvent(TraceSeverity severity,
parent_->channel_control_helper()->AddTraceEvent(severity, message);
}
//
// XdsLb::LbChannelState::StateWatcher
//
class XdsLb::LbChannelState::StateWatcher
: public AsyncConnectivityStateWatcherInterface {
public:
explicit StateWatcher(RefCountedPtr<LbChannelState> parent)
: AsyncConnectivityStateWatcherInterface(
grpc_combiner_scheduler(parent->xdslb_policy_->combiner())),
parent_(std::move(parent)) {}
private:
void OnConnectivityStateChange(grpc_connectivity_state new_state) override {
if (!parent_->shutting_down_ &&
parent_->xdslb_policy_->fallback_at_startup_checks_pending_ &&
new_state == GRPC_CHANNEL_TRANSIENT_FAILURE) {
// In TRANSIENT_FAILURE. Cancel the fallback timer and go into
// fallback mode immediately.
gpr_log(GPR_INFO,
"[xdslb %p] Balancer channel in state TRANSIENT_FAILURE; "
"entering fallback mode",
parent_->xdslb_policy_.get());
parent_->xdslb_policy_->fallback_at_startup_checks_pending_ = false;
grpc_timer_cancel(&parent_->xdslb_policy_->lb_fallback_timer_);
parent_->xdslb_policy_->UpdateFallbackPolicyLocked();
parent_->CancelConnectivityWatchLocked();
}
}
RefCountedPtr<LbChannelState> parent_;
};
//
// XdsLb::LbChannelState
//
@ -871,8 +894,6 @@ XdsLb::LbChannelState::LbChannelState(RefCountedPtr<XdsLb> xdslb_policy,
const grpc_channel_args& args)
: InternallyRefCounted<LbChannelState>(&grpc_lb_xds_trace),
xdslb_policy_(std::move(xdslb_policy)) {
GRPC_CLOSURE_INIT(&on_connectivity_changed_, OnConnectivityChangedLocked,
this, grpc_combiner_scheduler(xdslb_policy_->combiner()));
channel_ = CreateXdsBalancerChannel(balancer_name, args);
GPR_ASSERT(channel_ != nullptr);
eds_calld_.reset(New<RetryableLbCall<EdsCallState>>(
@ -900,56 +921,17 @@ void XdsLb::LbChannelState::StartConnectivityWatchLocked() {
grpc_channel_element* client_channel_elem =
grpc_channel_stack_last_element(grpc_channel_get_channel_stack(channel_));
GPR_ASSERT(client_channel_elem->filter == &grpc_client_channel_filter);
// Ref held by callback.
Ref(DEBUG_LOCATION, "LbChannelState+start_watch").release();
grpc_client_channel_watch_connectivity_state(
client_channel_elem,
grpc_polling_entity_create_from_pollset_set(
xdslb_policy_->interested_parties()),
&connectivity_, &on_connectivity_changed_, nullptr);
auto watcher = MakeOrphanable<StateWatcher>(Ref());
watcher_ = watcher.get();
grpc_client_channel_start_connectivity_watch(
client_channel_elem, GRPC_CHANNEL_IDLE, std::move(watcher));
}
void XdsLb::LbChannelState::CancelConnectivityWatchLocked() {
grpc_channel_element* client_channel_elem =
grpc_channel_stack_last_element(grpc_channel_get_channel_stack(channel_));
GPR_ASSERT(client_channel_elem->filter == &grpc_client_channel_filter);
grpc_client_channel_watch_connectivity_state(
client_channel_elem,
grpc_polling_entity_create_from_pollset_set(
xdslb_policy_->interested_parties()),
nullptr, &on_connectivity_changed_, nullptr);
}
void XdsLb::LbChannelState::OnConnectivityChangedLocked(void* arg,
grpc_error* error) {
LbChannelState* self = static_cast<LbChannelState*>(arg);
if (!self->shutting_down_ &&
self->xdslb_policy_->fallback_at_startup_checks_pending_) {
if (self->connectivity_ != GRPC_CHANNEL_TRANSIENT_FAILURE) {
// Not in TRANSIENT_FAILURE. Renew connectivity watch.
grpc_channel_element* client_channel_elem =
grpc_channel_stack_last_element(
grpc_channel_get_channel_stack(self->channel_));
GPR_ASSERT(client_channel_elem->filter == &grpc_client_channel_filter);
grpc_client_channel_watch_connectivity_state(
client_channel_elem,
grpc_polling_entity_create_from_pollset_set(
self->xdslb_policy_->interested_parties()),
&self->connectivity_, &self->on_connectivity_changed_, nullptr);
return; // Early out so we don't drop the ref below.
}
// In TRANSIENT_FAILURE. Cancel the fallback timer and go into
// fallback mode immediately.
gpr_log(GPR_INFO,
"[xdslb %p] Balancer channel in state TRANSIENT_FAILURE; "
"entering fallback mode",
self);
self->xdslb_policy_->fallback_at_startup_checks_pending_ = false;
grpc_timer_cancel(&self->xdslb_policy_->lb_fallback_timer_);
self->xdslb_policy_->UpdateFallbackPolicyLocked();
}
// Done watching connectivity state, so drop ref.
self->Unref(DEBUG_LOCATION, "LbChannelState+watch_done");
grpc_client_channel_stop_connectivity_watch(client_channel_elem, watcher_);
}
//
@ -1843,9 +1825,7 @@ void XdsLb::ShutdownLocked() {
gpr_log(GPR_INFO, "[xdslb %p] shutting down", this);
}
shutting_down_ = true;
if (fallback_at_startup_checks_pending_) {
grpc_timer_cancel(&lb_fallback_timer_);
}
MaybeCancelFallbackAtStartupChecks();
priority_list_.ShutdownLocked();
if (fallback_policy_ != nullptr) {
grpc_pollset_set_del_pollset_set(fallback_policy_->interested_parties(),
@ -2179,7 +2159,7 @@ void XdsLb::PriorityList::UpdateXdsPickerLocked() {
GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE);
xds_policy_->channel_control_helper()->UpdateState(
GRPC_CHANNEL_TRANSIENT_FAILURE,
UniquePtr<SubchannelPicker>(New<TransientFailurePicker>(error)));
MakeUnique<TransientFailurePicker>(error));
return;
}
priorities_[current_priority_]->UpdateXdsPickerLocked();
@ -2272,9 +2252,8 @@ XdsLb::PriorityList::LocalityMap::LocalityMap(RefCountedPtr<XdsLb> xds_policy,
// This is the first locality map ever created, report CONNECTING.
if (priority_ == 0) {
xds_policy_->channel_control_helper()->UpdateState(
GRPC_CHANNEL_CONNECTING,
UniquePtr<SubchannelPicker>(
New<QueuePicker>(xds_policy_->Ref(DEBUG_LOCATION, "QueuePicker"))));
GRPC_CHANNEL_CONNECTING, MakeUnique<QueuePicker>(xds_policy_->Ref(
DEBUG_LOCATION, "QueuePicker")));
}
}
@ -2344,12 +2323,12 @@ void XdsLb::PriorityList::LocalityMap::UpdateXdsPickerLocked() {
if (!locality_map_update()->Contains(locality_name)) continue;
if (locality->connectivity_state() != GRPC_CHANNEL_READY) continue;
end += locality->weight();
picker_list.push_back(MakePair(end, locality->picker_wrapper()));
picker_list.push_back(std::make_pair(end, locality->picker_wrapper()));
}
xds_policy()->channel_control_helper()->UpdateState(
GRPC_CHANNEL_READY, UniquePtr<SubchannelPicker>(New<Picker>(
xds_policy_->Ref(DEBUG_LOCATION, "XdsLb+Picker"),
std::move(picker_list))));
GRPC_CHANNEL_READY,
MakeUnique<Picker>(xds_policy_->Ref(DEBUG_LOCATION, "XdsLb+Picker"),
std::move(picker_list)));
}
OrphanablePtr<XdsLb::PriorityList::LocalityMap::Locality>
@ -2898,7 +2877,7 @@ class XdsFactory : public LoadBalancingPolicyFactory {
public:
OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
LoadBalancingPolicy::Args args) const override {
return OrphanablePtr<LoadBalancingPolicy>(New<XdsLb>(std::move(args)));
return MakeOrphanable<XdsLb>(std::move(args));
}
const char* name() const override { return kXds; }
@ -2982,8 +2961,7 @@ class XdsFactory : public LoadBalancingPolicyFactory {
void grpc_lb_policy_xds_init() {
grpc_core::LoadBalancingPolicyRegistry::Builder::
RegisterLoadBalancingPolicyFactory(
grpc_core::UniquePtr<grpc_core::LoadBalancingPolicyFactory>(
grpc_core::New<grpc_core::XdsFactory>()));
grpc_core::MakeUnique<grpc_core::XdsFactory>());
}
void grpc_lb_policy_xds_shutdown() {}

@ -143,15 +143,11 @@ XdsClientStats::Snapshot XdsClientStats::GetSnapshotAndReset() {
}
{
MutexLock lock(&dropped_requests_mu_);
#if GRPC_USE_CPP_STD_LIB
// This is a workaround for the case where some compilers cannot build
// move-assignment of map with non-copyable but movable key.
// https://stackoverflow.com/questions/36475497
std::swap(snapshot.dropped_requests, dropped_requests_);
dropped_requests_.clear();
#else
snapshot.dropped_requests = std::move(dropped_requests_);
#endif
}
return snapshot;
}

@ -111,9 +111,9 @@ class XdsClientStats {
double total_metric_value_{0};
};
using LoadMetricMap = Map<UniquePtr<char>, LoadMetric, StringLess>;
using LoadMetricMap = std::map<UniquePtr<char>, LoadMetric, StringLess>;
using LoadMetricSnapshotMap =
Map<UniquePtr<char>, LoadMetric::Snapshot, StringLess>;
std::map<UniquePtr<char>, LoadMetric::Snapshot, StringLess>;
struct Snapshot {
// TODO(juanlishen): Change this to const method when const_iterator is
@ -180,12 +180,12 @@ class XdsClientStats {
// UniquePtr<>. We should remove this wrapper if the value type of Map<>
// doesn't have to be movable.
using LocalityStatsMap =
Map<RefCountedPtr<XdsLocalityName>, RefCountedPtr<LocalityStats>,
XdsLocalityName::Less>;
std::map<RefCountedPtr<XdsLocalityName>, RefCountedPtr<LocalityStats>,
XdsLocalityName::Less>;
using LocalityStatsSnapshotMap =
Map<RefCountedPtr<XdsLocalityName>, LocalityStats::Snapshot,
XdsLocalityName::Less>;
using DroppedRequestsMap = Map<UniquePtr<char>, uint64_t, StringLess>;
std::map<RefCountedPtr<XdsLocalityName>, LocalityStats::Snapshot,
XdsLocalityName::Less>;
using DroppedRequestsMap = std::map<UniquePtr<char>, uint64_t, StringLess>;
using DroppedRequestsSnapshotMap = DroppedRequestsMap;
struct Snapshot {

@ -345,18 +345,11 @@ grpc_slice XdsLrsRequestCreateAndEncode(const char* server_name) {
namespace {
void LocalityStatsPopulate(envoy_api_v2_endpoint_UpstreamLocalityStats* output,
#if GRPC_USE_CPP_STD_LIB
// TODO(veblush): Clean up this
// This is to address the difference between
// std::map and Map. #else block will be gone
// once using stdlib is enabled by default.
Pair<const RefCountedPtr<XdsLocalityName>,
#else
Pair<RefCountedPtr<XdsLocalityName>,
#endif
XdsClientStats::LocalityStats::Snapshot>& input,
upb_arena* arena) {
void LocalityStatsPopulate(
envoy_api_v2_endpoint_UpstreamLocalityStats* output,
std::pair<const RefCountedPtr<XdsLocalityName>,
XdsClientStats::LocalityStats::Snapshot>& input,
upb_arena* arena) {
// Set sub_zone.
envoy_api_v2_core_Locality* locality =
envoy_api_v2_endpoint_UpstreamLocalityStats_mutable_locality(output,

@ -57,7 +57,7 @@ class XdsPriorityListUpdate {
size_t size() const { return localities.size(); }
Map<RefCountedPtr<XdsLocalityName>, Locality, XdsLocalityName::Less>
std::map<RefCountedPtr<XdsLocalityName>, Locality, XdsLocalityName::Less>
localities;
};

@ -22,7 +22,6 @@
#include <grpc/support/port_platform.h>
#include "src/core/ext/filters/client_channel/lb_policy.h"
#include "src/core/lib/gprpp/abstract.h"
#include "src/core/lib/gprpp/orphanable.h"
namespace grpc_core {
@ -31,18 +30,16 @@ class LoadBalancingPolicyFactory {
public:
/// Returns a new LB policy instance.
virtual OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy(
LoadBalancingPolicy::Args) const GRPC_ABSTRACT;
LoadBalancingPolicy::Args) const = 0;
/// Returns the LB policy name that this factory provides.
/// Caller does NOT take ownership of result.
virtual const char* name() const GRPC_ABSTRACT;
virtual const char* name() const = 0;
virtual RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig(
const grpc_json* json, grpc_error** error) const GRPC_ABSTRACT;
const grpc_json* json, grpc_error** error) const = 0;
virtual ~LoadBalancingPolicyFactory() {}
GRPC_ABSTRACT_BASE_CLASS;
};
} // namespace grpc_core

@ -25,7 +25,6 @@
#include "src/core/ext/filters/client_channel/server_address.h"
#include "src/core/ext/filters/client_channel/service_config.h"
#include "src/core/lib/gprpp/abstract.h"
#include "src/core/lib/gprpp/orphanable.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/combiner.h"
@ -74,17 +73,15 @@ class Resolver : public InternallyRefCounted<Resolver> {
/// Returns a result to the channel.
/// Takes ownership of \a result.args.
virtual void ReturnResult(Result result) GRPC_ABSTRACT; // NOLINT
virtual void ReturnResult(Result result) = 0; // NOLINT
/// Returns a transient error to the channel.
/// If the resolver does not set the GRPC_ERROR_INT_GRPC_STATUS
/// attribute on the error, calls will be failed with status UNKNOWN.
virtual void ReturnError(grpc_error* error) GRPC_ABSTRACT;
virtual void ReturnError(grpc_error* error) = 0;
// TODO(yashkt): As part of the service config error handling
// changes, add a method to parse the service config JSON string.
GRPC_ABSTRACT_BASE_CLASS
};
// Not copyable nor movable.
@ -92,7 +89,7 @@ class Resolver : public InternallyRefCounted<Resolver> {
Resolver& operator=(const Resolver&) = delete;
/// Starts resolving.
virtual void StartLocked() GRPC_ABSTRACT;
virtual void StartLocked() = 0;
/// Asks the resolver to obtain an updated resolver result, if
/// applicable.
@ -123,8 +120,6 @@ class Resolver : public InternallyRefCounted<Resolver> {
Unref();
}
GRPC_ABSTRACT_BASE_CLASS
protected:
GRPC_ALLOW_CLASS_TO_USE_NON_PUBLIC_DELETE
@ -138,7 +133,7 @@ class Resolver : public InternallyRefCounted<Resolver> {
virtual ~Resolver();
/// Shuts down the resolver.
virtual void ShutdownLocked() GRPC_ABSTRACT;
virtual void ShutdownLocked() = 0;
grpc_combiner* combiner() const { return combiner_; }

@ -436,7 +436,7 @@ class AresDnsResolverFactory : public ResolverFactory {
bool IsValidUri(const grpc_uri* uri) const override { return true; }
OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
return OrphanablePtr<Resolver>(New<AresDnsResolver>(std::move(args)));
return MakeOrphanable<AresDnsResolver>(std::move(args));
}
const char* scheme() const override { return "dns"; }
@ -494,8 +494,7 @@ void grpc_resolver_dns_ares_init() {
}
grpc_set_resolver_impl(&ares_resolver);
grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
grpc_core::UniquePtr<grpc_core::ResolverFactory>(
grpc_core::New<grpc_core::AresDnsResolverFactory>()));
grpc_core::MakeUnique<grpc_core::AresDnsResolverFactory>());
} else {
g_use_ares_dns_resolver = false;
}

@ -23,7 +23,6 @@
#include <ares.h>
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
#include "src/core/lib/gprpp/abstract.h"
#include "src/core/lib/iomgr/pollset_set.h"
typedef struct grpc_ares_ev_driver grpc_ares_ev_driver;
@ -67,22 +66,18 @@ class GrpcPolledFd {
public:
virtual ~GrpcPolledFd() {}
/* Called when c-ares library is interested and there's no pending callback */
virtual void RegisterForOnReadableLocked(grpc_closure* read_closure)
GRPC_ABSTRACT;
virtual void RegisterForOnReadableLocked(grpc_closure* read_closure) = 0;
/* Called when c-ares library is interested and there's no pending callback */
virtual void RegisterForOnWriteableLocked(grpc_closure* write_closure)
GRPC_ABSTRACT;
virtual void RegisterForOnWriteableLocked(grpc_closure* write_closure) = 0;
/* Indicates if there is data left even after just being read from */
virtual bool IsFdStillReadableLocked() GRPC_ABSTRACT;
virtual bool IsFdStillReadableLocked() = 0;
/* Called once and only once. Must cause cancellation of any pending
* read/write callbacks. */
virtual void ShutdownLocked(grpc_error* error) GRPC_ABSTRACT;
virtual void ShutdownLocked(grpc_error* error) = 0;
/* Get the underlying ares_socket_t that this was created from */
virtual ares_socket_t GetWrappedAresSocketLocked() GRPC_ABSTRACT;
virtual ares_socket_t GetWrappedAresSocketLocked() = 0;
/* A unique name, for logging */
virtual const char* GetName() GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS
virtual const char* GetName() = 0;
};
/* A GrpcPolledFdFactory is 1-to-1 with and owned by the
@ -95,11 +90,9 @@ class GrpcPolledFdFactory {
/* Creates a new wrapped fd for the current platform */
virtual GrpcPolledFd* NewGrpcPolledFdLocked(
ares_socket_t as, grpc_pollset_set* driver_pollset_set,
grpc_combiner* combiner) GRPC_ABSTRACT;
grpc_combiner* combiner) = 0;
/* Optionally configures the ares channel after creation */
virtual void ConfigureAresChannelLocked(ares_channel channel) GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS
virtual void ConfigureAresChannelLocked(ares_channel channel) = 0;
};
UniquePtr<GrpcPolledFdFactory> NewGrpcPolledFdFactory(grpc_combiner* combiner);

@ -171,7 +171,7 @@ class GrpcPolledFdFactoryLibuv : public GrpcPolledFdFactory {
};
UniquePtr<GrpcPolledFdFactory> NewGrpcPolledFdFactory(grpc_combiner* combiner) {
return UniquePtr<GrpcPolledFdFactory>(New<GrpcPolledFdFactoryLibuv>());
return MakeUnique<GrpcPolledFdFactoryLibuv>();
}
} // namespace grpc_core

@ -98,7 +98,7 @@ class GrpcPolledFdFactoryPosix : public GrpcPolledFdFactory {
};
UniquePtr<GrpcPolledFdFactory> NewGrpcPolledFdFactory(grpc_combiner* combiner) {
return UniquePtr<GrpcPolledFdFactory>(New<GrpcPolledFdFactoryPosix>());
return MakeUnique<GrpcPolledFdFactoryPosix>();
}
} // namespace grpc_core

@ -904,8 +904,7 @@ class GrpcPolledFdFactoryWindows : public GrpcPolledFdFactory {
};
UniquePtr<GrpcPolledFdFactory> NewGrpcPolledFdFactory(grpc_combiner* combiner) {
return UniquePtr<GrpcPolledFdFactory>(
New<GrpcPolledFdFactoryWindows>(combiner));
return MakeUnique<GrpcPolledFdFactoryWindows>(combiner);
}
} // namespace grpc_core

@ -268,7 +268,7 @@ class NativeDnsResolverFactory : public ResolverFactory {
OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
if (!IsValidUri(args.uri)) return nullptr;
return OrphanablePtr<Resolver>(New<NativeDnsResolver>(std::move(args)));
return MakeOrphanable<NativeDnsResolver>(std::move(args));
}
const char* scheme() const override { return "dns"; }
@ -284,8 +284,7 @@ void grpc_resolver_dns_native_init() {
if (gpr_stricmp(resolver.get(), "native") == 0) {
gpr_log(GPR_DEBUG, "Using native dns resolver");
grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
grpc_core::UniquePtr<grpc_core::ResolverFactory>(
grpc_core::New<grpc_core::NativeDnsResolverFactory>()));
grpc_core::MakeUnique<grpc_core::NativeDnsResolverFactory>());
} else {
grpc_core::ResolverRegistry::Builder::InitRegistry();
grpc_core::ResolverFactory* existing_factory =
@ -293,8 +292,7 @@ void grpc_resolver_dns_native_init() {
if (existing_factory == nullptr) {
gpr_log(GPR_DEBUG, "Using native dns resolver");
grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
grpc_core::UniquePtr<grpc_core::ResolverFactory>(
grpc_core::New<grpc_core::NativeDnsResolverFactory>()));
grpc_core::MakeUnique<grpc_core::NativeDnsResolverFactory>());
}
}
}

@ -382,7 +382,7 @@ class FakeResolverFactory : public ResolverFactory {
bool IsValidUri(const grpc_uri* uri) const override { return true; }
OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
return OrphanablePtr<Resolver>(New<FakeResolver>(std::move(args)));
return MakeOrphanable<FakeResolver>(std::move(args));
}
const char* scheme() const override { return "fake"; }
@ -394,8 +394,7 @@ class FakeResolverFactory : public ResolverFactory {
void grpc_resolver_fake_init() {
grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
grpc_core::UniquePtr<grpc_core::ResolverFactory>(
grpc_core::New<grpc_core::FakeResolverFactory>()));
grpc_core::MakeUnique<grpc_core::FakeResolverFactory>());
}
void grpc_resolver_fake_shutdown() {}

@ -119,8 +119,8 @@ OrphanablePtr<Resolver> CreateSockaddrResolver(
ServerAddressList addresses;
if (!ParseUri(args.uri, parse, &addresses)) return nullptr;
// Instantiate resolver.
return OrphanablePtr<Resolver>(
New<SockaddrResolver>(std::move(addresses), std::move(args)));
return MakeOrphanable<SockaddrResolver>(std::move(addresses),
std::move(args));
}
class IPv4ResolverFactory : public ResolverFactory {
@ -174,15 +174,12 @@ class UnixResolverFactory : public ResolverFactory {
void grpc_resolver_sockaddr_init() {
grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
grpc_core::UniquePtr<grpc_core::ResolverFactory>(
grpc_core::New<grpc_core::IPv4ResolverFactory>()));
grpc_core::MakeUnique<grpc_core::IPv4ResolverFactory>());
grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
grpc_core::UniquePtr<grpc_core::ResolverFactory>(
grpc_core::New<grpc_core::IPv6ResolverFactory>()));
grpc_core::MakeUnique<grpc_core::IPv6ResolverFactory>());
#ifdef GRPC_HAVE_UNIX_SOCKET
grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
grpc_core::UniquePtr<grpc_core::ResolverFactory>(
grpc_core::New<grpc_core::UnixResolverFactory>()));
grpc_core::MakeUnique<grpc_core::UnixResolverFactory>());
#endif
}

@ -70,7 +70,7 @@ class XdsResolverFactory : public ResolverFactory {
OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override {
if (!IsValidUri(args.uri)) return nullptr;
return OrphanablePtr<Resolver>(New<XdsResolver>(std::move(args)));
return MakeOrphanable<XdsResolver>(std::move(args));
}
const char* scheme() const override { return "xds-experimental"; }
@ -82,8 +82,7 @@ class XdsResolverFactory : public ResolverFactory {
void grpc_resolver_xds_init() {
grpc_core::ResolverRegistry::Builder::RegisterResolverFactory(
grpc_core::UniquePtr<grpc_core::ResolverFactory>(
grpc_core::New<grpc_core::XdsResolverFactory>()));
grpc_core::MakeUnique<grpc_core::XdsResolverFactory>());
}
void grpc_resolver_xds_shutdown() {}

@ -24,7 +24,6 @@
#include <grpc/support/string_util.h>
#include "src/core/ext/filters/client_channel/resolver.h"
#include "src/core/lib/gprpp/abstract.h"
#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/gprpp/orphanable.h"
#include "src/core/lib/iomgr/pollset_set.h"
@ -49,11 +48,10 @@ class ResolverFactory {
public:
/// Returns a bool indicating whether the input uri is valid to create a
/// resolver.
virtual bool IsValidUri(const grpc_uri* uri) const GRPC_ABSTRACT;
virtual bool IsValidUri(const grpc_uri* uri) const = 0;
/// Returns a new resolver instance.
virtual OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const
GRPC_ABSTRACT;
virtual OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const = 0;
/// Returns a string representing the default authority to use for this
/// scheme.
@ -65,11 +63,9 @@ class ResolverFactory {
/// Returns the URI scheme that this factory implements.
/// Caller does NOT take ownership of result.
virtual const char* scheme() const GRPC_ABSTRACT;
virtual const char* scheme() const = 0;
virtual ~ResolverFactory() {}
GRPC_ABSTRACT_BASE_CLASS
};
} // namespace grpc_core

@ -53,9 +53,8 @@ size_t ClientChannelServiceConfigParser::ParserIndex() {
}
void ClientChannelServiceConfigParser::Register() {
g_client_channel_service_config_parser_index =
ServiceConfig::RegisterParser(UniquePtr<ServiceConfig::Parser>(
New<ClientChannelServiceConfigParser>()));
g_client_channel_service_config_parser_index = ServiceConfig::RegisterParser(
MakeUnique<ClientChannelServiceConfigParser>());
}
namespace {
@ -439,10 +438,9 @@ ClientChannelServiceConfigParser::ParseGlobalParams(const grpc_json* json,
*error = GRPC_ERROR_CREATE_FROM_VECTOR("Client channel global parser",
&error_list);
if (*error == GRPC_ERROR_NONE) {
return UniquePtr<ServiceConfig::ParsedConfig>(
New<ClientChannelGlobalParsedConfig>(
std::move(parsed_lb_config), std::move(lb_policy_name),
retry_throttling, health_check_service_name));
return MakeUnique<ClientChannelGlobalParsedConfig>(
std::move(parsed_lb_config), std::move(lb_policy_name),
retry_throttling, health_check_service_name);
}
return nullptr;
}
@ -493,9 +491,8 @@ ClientChannelServiceConfigParser::ParsePerMethodParams(const grpc_json* json,
}
*error = GRPC_ERROR_CREATE_FROM_VECTOR("Client channel parser", &error_list);
if (*error == GRPC_ERROR_NONE) {
return UniquePtr<ServiceConfig::ParsedConfig>(
New<ClientChannelMethodParsedConfig>(timeout, wait_for_ready,
std::move(retry_policy)));
return MakeUnique<ClientChannelMethodParsedConfig>(timeout, wait_for_ready,
std::move(retry_policy));
}
return nullptr;
}

@ -187,16 +187,15 @@ ResolvingLoadBalancingPolicy::ResolvingLoadBalancingPolicy(
GPR_ASSERT(process_resolver_result != nullptr);
resolver_ = ResolverRegistry::CreateResolver(
target_uri_.get(), args.args, interested_parties(), combiner(),
UniquePtr<Resolver::ResultHandler>(New<ResolverResultHandler>(Ref())));
MakeUnique<ResolverResultHandler>(Ref()));
// Since the validity of args has been checked when create the channel,
// CreateResolver() must return a non-null result.
GPR_ASSERT(resolver_ != nullptr);
if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) {
gpr_log(GPR_INFO, "resolving_lb=%p: starting name resolution", this);
}
channel_control_helper()->UpdateState(
GRPC_CHANNEL_CONNECTING,
UniquePtr<SubchannelPicker>(New<QueuePicker>(Ref())));
channel_control_helper()->UpdateState(GRPC_CHANNEL_CONNECTING,
MakeUnique<QueuePicker>(Ref()));
resolver_->StartLocked();
}
@ -262,7 +261,7 @@ void ResolvingLoadBalancingPolicy::OnResolverError(grpc_error* error) {
"Resolver transient failure", &error, 1);
channel_control_helper()->UpdateState(
GRPC_CHANNEL_TRANSIENT_FAILURE,
UniquePtr<SubchannelPicker>(New<TransientFailurePicker>(state_error)));
MakeUnique<TransientFailurePicker>(state_error));
}
GRPC_ERROR_UNREF(error);
}

@ -62,8 +62,6 @@ class ServiceConfig : public RefCounted<ServiceConfig> {
class ParsedConfig {
public:
virtual ~ParsedConfig() = default;
GRPC_ABSTRACT_BASE_CLASS;
};
/// This is the base class that all service config parsers should derive from.
@ -82,8 +80,6 @@ class ServiceConfig : public RefCounted<ServiceConfig> {
GPR_DEBUG_ASSERT(error != nullptr);
return nullptr;
}
GRPC_ABSTRACT_BASE_CLASS;
};
static constexpr int kNumPreallocatedParsers = 4;

@ -367,7 +367,7 @@ class Subchannel::ConnectedSubchannelStateWatcher
void Subchannel::ConnectivityStateWatcherList::AddWatcherLocked(
OrphanablePtr<ConnectivityStateWatcherInterface> watcher) {
watchers_.insert(MakePair(watcher.get(), std::move(watcher)));
watchers_.insert(std::make_pair(watcher.get(), std::move(watcher)));
}
void Subchannel::ConnectivityStateWatcherList::RemoveWatcherLocked(
@ -401,7 +401,7 @@ void Subchannel::ConnectivityStateWatcherList::NotifyLocked(
// State needed for tracking the connectivity state with a particular
// health check service name.
class Subchannel::HealthWatcherMap::HealthWatcher
: public InternallyRefCounted<HealthWatcher> {
: public AsyncConnectivityStateWatcherInterface {
public:
HealthWatcher(Subchannel* c, UniquePtr<char> health_check_service_name,
grpc_connectivity_state subchannel_state)
@ -410,8 +410,6 @@ class Subchannel::HealthWatcherMap::HealthWatcher
state_(subchannel_state == GRPC_CHANNEL_READY ? GRPC_CHANNEL_CONNECTING
: subchannel_state) {
GRPC_SUBCHANNEL_WEAK_REF(subchannel_, "health_watcher");
GRPC_CLOSURE_INIT(&on_health_changed_, OnHealthChanged, this,
grpc_schedule_on_exec_ctx);
// If the subchannel is already connected, start health checking.
if (subchannel_state == GRPC_CHANNEL_READY) StartHealthCheckingLocked();
}
@ -428,7 +426,7 @@ class Subchannel::HealthWatcherMap::HealthWatcher
void AddWatcherLocked(
grpc_connectivity_state initial_state,
OrphanablePtr<ConnectivityStateWatcherInterface> watcher) {
OrphanablePtr<Subchannel::ConnectivityStateWatcherInterface> watcher) {
if (state_ != initial_state) {
RefCountedPtr<ConnectedSubchannel> connected_subchannel;
if (state_ == GRPC_CHANNEL_READY) {
@ -440,7 +438,8 @@ class Subchannel::HealthWatcherMap::HealthWatcher
watcher_list_.AddWatcherLocked(std::move(watcher));
}
void RemoveWatcherLocked(ConnectivityStateWatcherInterface* watcher) {
void RemoveWatcherLocked(
Subchannel::ConnectivityStateWatcherInterface* watcher) {
watcher_list_.RemoveWatcherLocked(watcher);
}
@ -473,38 +472,24 @@ class Subchannel::HealthWatcherMap::HealthWatcher
}
private:
void OnConnectivityStateChange(grpc_connectivity_state new_state) override {
MutexLock lock(&subchannel_->mu_);
if (new_state != GRPC_CHANNEL_SHUTDOWN && health_check_client_ != nullptr) {
state_ = new_state;
watcher_list_.NotifyLocked(subchannel_, new_state);
}
}
void StartHealthCheckingLocked() {
GPR_ASSERT(health_check_client_ == nullptr);
health_check_client_ = MakeOrphanable<HealthCheckClient>(
health_check_service_name_.get(), subchannel_->connected_subchannel_,
subchannel_->pollset_set_, subchannel_->channelz_node_);
Ref().release(); // Ref for health callback tracked manually.
health_check_client_->NotifyOnHealthChange(&state_, &on_health_changed_);
}
static void OnHealthChanged(void* arg, grpc_error* error) {
auto* self = static_cast<HealthWatcher*>(arg);
Subchannel* c = self->subchannel_;
{
MutexLock lock(&c->mu_);
if (self->state_ != GRPC_CHANNEL_SHUTDOWN &&
self->health_check_client_ != nullptr) {
self->watcher_list_.NotifyLocked(c, self->state_);
// Renew watch.
self->health_check_client_->NotifyOnHealthChange(
&self->state_, &self->on_health_changed_);
return; // So we don't unref below.
}
}
// Don't unref until we've released the lock, because this might
// cause the subchannel (which contains the lock) to be destroyed.
self->Unref();
subchannel_->pollset_set_, subchannel_->channelz_node_, Ref());
}
Subchannel* subchannel_;
UniquePtr<char> health_check_service_name_;
OrphanablePtr<HealthCheckClient> health_check_client_;
grpc_closure on_health_changed_;
grpc_connectivity_state state_;
ConnectivityStateWatcherList watcher_list_;
};
@ -1071,8 +1056,7 @@ bool Subchannel::PublishTransportLocked() {
}
// Start watching connected subchannel.
connected_subchannel_->StartWatch(
pollset_set_, OrphanablePtr<grpc_core::ConnectivityStateWatcherInterface>(
New<ConnectedSubchannelStateWatcher>(this)));
pollset_set_, MakeOrphanable<ConnectedSubchannelStateWatcher>(this));
// Report initial state.
SetConnectivityStateLocked(GRPC_CHANNEL_READY);
return true;

@ -192,11 +192,9 @@ class Subchannel {
virtual void OnConnectivityStateChange(
grpc_connectivity_state new_state,
RefCountedPtr<ConnectedSubchannel> connected_subchannel) // NOLINT
GRPC_ABSTRACT;
= 0;
virtual grpc_pollset_set* interested_parties() GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS
virtual grpc_pollset_set* interested_parties() = 0;
};
// The ctor and dtor are not intended to use directly.
@ -294,10 +292,10 @@ class Subchannel {
bool empty() const { return watchers_.empty(); }
private:
// TODO(roth): This could be a set instead of a map if we had a set
// implementation.
Map<ConnectivityStateWatcherInterface*,
OrphanablePtr<ConnectivityStateWatcherInterface>>
// TODO(roth): Once we can use C++-14 heterogenous lookups, this can
// be a set instead of a map.
std::map<ConnectivityStateWatcherInterface*,
OrphanablePtr<ConnectivityStateWatcherInterface>>
watchers_;
};
@ -330,7 +328,7 @@ class Subchannel {
private:
class HealthWatcher;
Map<const char*, OrphanablePtr<HealthWatcher>, StringLess> map_;
std::map<const char*, OrphanablePtr<HealthWatcher>, StringLess> map_;
};
class ConnectedSubchannelStateWatcher;

@ -36,14 +36,12 @@ class SubchannelInterface : public RefCounted<SubchannelInterface> {
// Will be invoked whenever the subchannel's connectivity state
// changes. There will be only one invocation of this method on a
// given watcher instance at any given time.
virtual void OnConnectivityStateChange(grpc_connectivity_state new_state)
GRPC_ABSTRACT;
virtual void OnConnectivityStateChange(
grpc_connectivity_state new_state) = 0;
// TODO(roth): Remove this as soon as we move to EventManager-based
// polling.
virtual grpc_pollset_set* interested_parties() GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS
virtual grpc_pollset_set* interested_parties() = 0;
};
template <typename TraceFlagT = TraceFlag>
@ -53,7 +51,7 @@ class SubchannelInterface : public RefCounted<SubchannelInterface> {
virtual ~SubchannelInterface() = default;
// Returns the current connectivity state of the subchannel.
virtual grpc_connectivity_state CheckConnectivityState() GRPC_ABSTRACT;
virtual grpc_connectivity_state CheckConnectivityState() = 0;
// Starts watching the subchannel's connectivity state.
// The first callback to the watcher will be delivered when the
@ -68,29 +66,27 @@ class SubchannelInterface : public RefCounted<SubchannelInterface> {
// the previous watcher using CancelConnectivityStateWatch().
virtual void WatchConnectivityState(
grpc_connectivity_state initial_state,
UniquePtr<ConnectivityStateWatcherInterface> watcher) GRPC_ABSTRACT;
UniquePtr<ConnectivityStateWatcherInterface> watcher) = 0;
// Cancels a connectivity state watch.
// If the watcher has already been destroyed, this is a no-op.
virtual void CancelConnectivityStateWatch(
ConnectivityStateWatcherInterface* watcher) GRPC_ABSTRACT;
ConnectivityStateWatcherInterface* watcher) = 0;
// Attempt to connect to the backend. Has no effect if already connected.
// If the subchannel is currently in backoff delay due to a previously
// failed attempt, the new connection attempt will not start until the
// backoff delay has elapsed.
virtual void AttemptToConnect() GRPC_ABSTRACT;
virtual void AttemptToConnect() = 0;
// Resets the subchannel's connection backoff state. If AttemptToConnect()
// has been called since the subchannel entered TRANSIENT_FAILURE state,
// starts a new connection attempt immediately; otherwise, a new connection
// attempt will be started as soon as AttemptToConnect() is called.
virtual void ResetBackoff() GRPC_ABSTRACT;
virtual void ResetBackoff() = 0;
// TODO(roth): Need a better non-grpc-specific abstraction here.
virtual const grpc_channel_args* channel_args() GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS
virtual const grpc_channel_args* channel_args() = 0;
};
} // namespace grpc_core

@ -23,7 +23,6 @@
#include "src/core/lib/avl/avl.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/gprpp/abstract.h"
#include "src/core/lib/gprpp/ref_counted.h"
namespace grpc_core {
@ -70,14 +69,14 @@ class SubchannelPoolInterface : public RefCounted<SubchannelPoolInterface> {
// with \a key, which may be different from \a constructed because we reuse
// (instead of update) any existing subchannel already registered with \a key.
virtual Subchannel* RegisterSubchannel(SubchannelKey* key,
Subchannel* constructed) GRPC_ABSTRACT;
Subchannel* constructed) = 0;
// Removes the registered subchannel found by \a key.
virtual void UnregisterSubchannel(SubchannelKey* key) GRPC_ABSTRACT;
virtual void UnregisterSubchannel(SubchannelKey* key) = 0;
// Finds the subchannel registered for the given subchannel key. Returns NULL
// if no such channel exists. Thread-safe.
virtual Subchannel* FindSubchannel(SubchannelKey* key) GRPC_ABSTRACT;
virtual Subchannel* FindSubchannel(SubchannelKey* key) = 0;
// Creates a channel arg from \a subchannel pool.
static grpc_arg CreateChannelArg(SubchannelPoolInterface* subchannel_pool);
@ -85,8 +84,6 @@ class SubchannelPoolInterface : public RefCounted<SubchannelPoolInterface> {
// Gets the subchannel pool from the channel args.
static SubchannelPoolInterface* GetSubchannelPoolFromChannelArgs(
const grpc_channel_args* args);
GRPC_ABSTRACT_BASE_CLASS
};
} // namespace grpc_core

@ -88,13 +88,13 @@ UniquePtr<ServiceConfig::ParsedConfig> MessageSizeParser::ParsePerMethodParams(
*error = GRPC_ERROR_CREATE_FROM_VECTOR("Message size parser", &error_list);
return nullptr;
}
return UniquePtr<ServiceConfig::ParsedConfig>(New<MessageSizeParsedConfig>(
max_request_message_bytes, max_response_message_bytes));
return MakeUnique<MessageSizeParsedConfig>(max_request_message_bytes,
max_response_message_bytes);
}
void MessageSizeParser::Register() {
g_message_size_parser_index = ServiceConfig::RegisterParser(
UniquePtr<ServiceConfig::Parser>(New<MessageSizeParser>()));
g_message_size_parser_index =
ServiceConfig::RegisterParser(MakeUnique<MessageSizeParser>());
}
size_t MessageSizeParser::ParserIndex() { return g_message_size_parser_index; }

File diff suppressed because it is too large Load Diff

@ -25,7 +25,6 @@
#include "src/core/ext/transport/chttp2/transport/http2_settings.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/abstract.h"
#include "src/core/lib/gprpp/manual_constructor.h"
#include "src/core/lib/transport/bdp_estimator.h"
#include "src/core/lib/transport/pid_controller.h"
@ -189,8 +188,6 @@ class TransportFlowControlBase {
// factor
virtual void TestOnlyForceHugeWindow() {}
GRPC_ABSTRACT_BASE_CLASS
protected:
friend class ::grpc::testing::TrickledCHTTP2;
int64_t remote_window_ = kDefaultWindow;
@ -385,8 +382,6 @@ class StreamFlowControlBase {
int64_t local_window_delta() { return local_window_delta_; }
int64_t announced_window_delta() { return announced_window_delta_; }
GRPC_ABSTRACT_BASE_CLASS
protected:
friend class ::grpc::testing::TrickledCHTTP2;
int64_t remote_window_delta_ = 0;

@ -1669,15 +1669,11 @@ static const maybe_complete_func_type maybe_complete_funcs[] = {
static void force_client_rst_stream(void* sp, grpc_error* error) {
grpc_chttp2_stream* s = static_cast<grpc_chttp2_stream*>(sp);
grpc_chttp2_transport* t = s->t;
{
grpc_core::MutexLock lock(&t->mu);
if (!s->write_closed) {
grpc_chttp2_add_rst_stream_to_next_write(t, s->id, GRPC_HTTP2_NO_ERROR,
&s->stats.outgoing);
grpc_chttp2_initiate_write(t,
GRPC_CHTTP2_INITIATE_WRITE_FORCE_RST_STREAM);
grpc_chttp2_mark_stream_closed(t, s, true, true, GRPC_ERROR_NONE);
}
if (!s->write_closed) {
grpc_chttp2_add_rst_stream_to_next_write(t, s->id, GRPC_HTTP2_NO_ERROR,
&s->stats.outgoing);
grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_FORCE_RST_STREAM);
grpc_chttp2_mark_stream_closed(t, s, true, true, GRPC_ERROR_NONE);
}
GRPC_CHTTP2_STREAM_UNREF(s, "final_rst");
}
@ -1744,12 +1740,11 @@ grpc_error* grpc_chttp2_header_parser_parse(void* hpack_parser,
the stream. Wait until the combiner lock is ready to be released
however -- it might be that we receive a RST_STREAM following this
and can avoid the extra write */
// TODO(yashykt) : When we were using combiners, we were using the
// finally version. Maybe do something similar?
GRPC_CHTTP2_STREAM_REF(s, "final_rst");
GRPC_CLOSURE_SCHED(GRPC_CLOSURE_CREATE(force_client_rst_stream, s,
grpc_schedule_on_exec_ctx),
GRPC_ERROR_NONE);
GRPC_CLOSURE_SCHED(
GRPC_CLOSURE_CREATE(force_client_rst_stream, s,
grpc_combiner_finally_scheduler(t->combiner)),
GRPC_ERROR_NONE);
}
grpc_chttp2_mark_stream_closed(t, s, true, false, GRPC_ERROR_NONE);
}

@ -39,7 +39,6 @@
#include "src/core/lib/channel/channelz.h"
#include "src/core/lib/compression/stream_compression.h"
#include "src/core/lib/gprpp/manual_constructor.h"
#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/combiner.h"
#include "src/core/lib/iomgr/endpoint.h"
#include "src/core/lib/iomgr/timer.h"
@ -254,6 +253,7 @@ class Chttp2IncomingByteStream : public ByteStream {
private:
static void NextLocked(void* arg, grpc_error* error_ignored);
static void OrphanLocked(void* arg, grpc_error* error_ignored);
void MaybeCreateStreamDecompressionCtx();
@ -275,6 +275,7 @@ class Chttp2IncomingByteStream : public ByteStream {
size_t max_size_hint;
grpc_closure* on_complete;
} next_action_;
grpc_closure destroy_action_;
};
} // namespace grpc_core
@ -293,13 +294,14 @@ struct grpc_chttp2_transport {
~grpc_chttp2_transport();
grpc_transport base; /* must be first */
grpc_core::Mutex mu;
grpc_core::RefCount refs;
grpc_endpoint* ep;
char* peer_string;
grpc_resource_user* resource_user;
grpc_combiner* combiner;
grpc_closure* notify_on_receive_settings = nullptr;
/** write execution state of the transport */
@ -325,11 +327,11 @@ struct grpc_chttp2_transport {
/** maps stream id to grpc_chttp2_stream objects */
grpc_chttp2_stream_map stream_map;
grpc_closure write_action_begin;
grpc_closure write_action_begin_locked;
grpc_closure write_action;
grpc_closure write_action_end;
grpc_closure write_action_end_locked;
grpc_closure read_action;
grpc_closure read_action_locked;
/** incoming read bytes */
grpc_slice_buffer read_buffer;
@ -390,7 +392,7 @@ struct grpc_chttp2_transport {
grpc_chttp2_repeated_ping_policy ping_policy;
grpc_chttp2_repeated_ping_state ping_state;
uint64_t ping_ctr = 0; /* unique id for pings */
grpc_closure retry_initiate_ping;
grpc_closure retry_initiate_ping_locked;
/** ping acks */
size_t ping_ack_count = 0;
@ -440,9 +442,9 @@ struct grpc_chttp2_transport {
grpc_chttp2_write_cb* write_cb_pool = nullptr;
/* bdp estimator */
grpc_closure next_bdp_ping_timer_expired;
grpc_closure next_bdp_ping_timer_expired_locked;
grpc_closure start_bdp_ping_locked;
grpc_closure finish_bdp_ping;
grpc_closure finish_bdp_ping_locked;
/* if non-NULL, close the transport with this error when writes are finished
*/
@ -457,9 +459,9 @@ struct grpc_chttp2_transport {
/** have we scheduled a destructive cleanup? */
bool destructive_reclaimer_registered = false;
/** benign cleanup closure */
grpc_closure benign_reclaimer;
grpc_closure benign_reclaimer_locked;
/** destructive cleanup closure */
grpc_closure destructive_reclaimer;
grpc_closure destructive_reclaimer_locked;
/* next bdp ping timer */
bool have_next_bdp_ping_timer = false;
@ -467,13 +469,13 @@ struct grpc_chttp2_transport {
/* keep-alive ping support */
/** Closure to initialize a keepalive ping */
grpc_closure init_keepalive_ping;
grpc_closure init_keepalive_ping_locked;
/** Closure to run when the keepalive ping is sent */
grpc_closure start_keepalive_ping_locked;
/** Cousure to run when the keepalive ping ack is received */
grpc_closure finish_keepalive_ping;
grpc_closure finish_keepalive_ping_locked;
/** Closrue to run when the keepalive ping timeouts */
grpc_closure keepalive_watchdog_fired;
grpc_closure keepalive_watchdog_fired_locked;
/** timer to initiate ping events */
grpc_timer keepalive_ping_timer;
/** watchdog to kill the transport when waiting for the keepalive ping */
@ -520,6 +522,7 @@ struct grpc_chttp2_stream {
explicit Reffer(grpc_chttp2_stream* s);
} reffer;
grpc_closure destroy_stream;
grpc_closure* destroy_stream_arg;
grpc_chttp2_stream_link links[STREAM_LIST_COUNT];
@ -540,7 +543,7 @@ struct grpc_chttp2_stream {
int64_t next_message_end_offset;
int64_t flow_controlled_bytes_written = 0;
int64_t flow_controlled_bytes_flowed = 0;
grpc_closure complete_fetch;
grpc_closure complete_fetch_locked;
grpc_closure* fetching_send_message_finished = nullptr;
grpc_metadata_batch* recv_initial_metadata;

@ -97,14 +97,14 @@ static void maybe_initiate_ping(grpc_chttp2_transport* t) {
t->ping_state.is_delayed_ping_timer_set = true;
GRPC_CHTTP2_REF_TRANSPORT(t, "retry_initiate_ping_locked");
grpc_timer_init(&t->ping_state.delayed_ping_timer, next_allowed_ping,
&t->retry_initiate_ping);
&t->retry_initiate_ping_locked);
}
return;
}
pq->inflight_id = t->ping_ctr;
t->ping_ctr++;
GRPC_CLOSURE_LIST_RUN(&pq->lists[GRPC_CHTTP2_PCL_INITIATE]);
GRPC_CLOSURE_LIST_SCHED(&pq->lists[GRPC_CHTTP2_PCL_INITIATE]);
grpc_closure_list_move(&pq->lists[GRPC_CHTTP2_PCL_NEXT],
&pq->lists[GRPC_CHTTP2_PCL_INFLIGHT]);
grpc_slice_buffer_add(&t->outbuf,

@ -293,7 +293,7 @@ void ChannelNode::SetConnectivityState(grpc_connectivity_state state) {
void ChannelNode::AddChildChannel(intptr_t child_uuid) {
MutexLock lock(&child_mu_);
child_channels_.insert(MakePair(child_uuid, true));
child_channels_.insert(std::make_pair(child_uuid, true));
}
void ChannelNode::RemoveChildChannel(intptr_t child_uuid) {
@ -303,7 +303,7 @@ void ChannelNode::RemoveChildChannel(intptr_t child_uuid) {
void ChannelNode::AddChildSubchannel(intptr_t child_uuid) {
MutexLock lock(&child_mu_);
child_subchannels_.insert(MakePair(child_uuid, true));
child_subchannels_.insert(std::make_pair(child_uuid, true));
}
void ChannelNode::RemoveChildSubchannel(intptr_t child_uuid) {
@ -323,7 +323,7 @@ ServerNode::~ServerNode() {}
void ServerNode::AddChildSocket(RefCountedPtr<SocketNode> node) {
MutexLock lock(&child_mu_);
child_sockets_.insert(MakePair(node->uuid(), std::move(node)));
child_sockets_.insert(std::make_pair(node->uuid(), std::move(node)));
}
void ServerNode::RemoveChildSocket(intptr_t child_uuid) {
@ -333,7 +333,7 @@ void ServerNode::RemoveChildSocket(intptr_t child_uuid) {
void ServerNode::AddChildListenSocket(RefCountedPtr<ListenSocketNode> node) {
MutexLock lock(&child_mu_);
child_listen_sockets_.insert(MakePair(node->uuid(), std::move(node)));
child_listen_sockets_.insert(std::make_pair(node->uuid(), std::move(node)));
}
void ServerNode::RemoveChildListenSocket(intptr_t child_uuid) {

@ -88,7 +88,7 @@ class BaseNode : public RefCounted<BaseNode> {
virtual ~BaseNode();
// All children must implement this function.
virtual grpc_json* RenderJson() GRPC_ABSTRACT;
virtual grpc_json* RenderJson() = 0;
// Renders the json and returns allocated string that must be freed by the
// caller.
@ -221,8 +221,8 @@ class ChannelNode : public BaseNode {
// TODO(roth): We don't actually use the values here, only the keys, so
// these should be sets instead of maps, but we don't currently have a set
// implementation. Change this if/when we have one.
Map<intptr_t, bool> child_channels_;
Map<intptr_t, bool> child_subchannels_;
std::map<intptr_t, bool> child_channels_;
std::map<intptr_t, bool> child_subchannels_;
};
// Handles channelz bookkeeping for servers
@ -262,8 +262,8 @@ class ServerNode : public BaseNode {
CallCountingHelper call_counter_;
ChannelTrace trace_;
Mutex child_mu_; // Guards child maps below.
Map<intptr_t, RefCountedPtr<SocketNode>> child_sockets_;
Map<intptr_t, RefCountedPtr<ListenSocketNode>> child_listen_sockets_;
std::map<intptr_t, RefCountedPtr<SocketNode>> child_sockets_;
std::map<intptr_t, RefCountedPtr<ListenSocketNode>> child_listen_sockets_;
};
// Handles channelz bookkeeping for sockets

@ -87,7 +87,7 @@ class ChannelzRegistry {
// protects members
Mutex mu_;
Map<intptr_t, BaseNode*> node_map_;
std::map<intptr_t, BaseNode*> node_map_;
intptr_t uuid_generator_ = 0;
};

@ -77,12 +77,11 @@ struct HandshakerArgs {
class Handshaker : public RefCounted<Handshaker> {
public:
virtual ~Handshaker() = default;
virtual void Shutdown(grpc_error* why) GRPC_ABSTRACT;
virtual void Shutdown(grpc_error* why) = 0;
virtual void DoHandshake(grpc_tcp_server_acceptor* acceptor,
grpc_closure* on_handshake_done,
HandshakerArgs* args) GRPC_ABSTRACT;
virtual const char* name() const GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS
HandshakerArgs* args) = 0;
virtual const char* name() const = 0;
};
//

@ -33,10 +33,8 @@ class HandshakerFactory {
public:
virtual void AddHandshakers(const grpc_channel_args* args,
grpc_pollset_set* interested_parties,
HandshakeManager* handshake_mgr) GRPC_ABSTRACT;
HandshakeManager* handshake_mgr) = 0;
virtual ~HandshakerFactory() = default;
GRPC_ABSTRACT_BASE_CLASS
};
} // namespace grpc_core

@ -1,47 +0,0 @@
/*
*
* Copyright 2017 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef GRPC_CORE_LIB_GPRPP_ABSTRACT_H
#define GRPC_CORE_LIB_GPRPP_ABSTRACT_H
#if GRPC_USE_CPP_STD_LIB
#define GRPC_ABSTRACT_BASE_CLASS
#define GRPC_ABSTRACT = 0
#else
// This is needed to support abstract base classes in the c core. Since gRPC
// doesn't have a c++ runtime, it will hit a linker error on delete unless
// we define a virtual operator delete. See this blog for more info:
// https://eli.thegreenplace.net/2015/c-deleting-destructors-and-virtual-operator-delete/
#define GRPC_ABSTRACT_BASE_CLASS \
static void operator delete(void* p) { abort(); }
// gRPC currently can't depend on libstdc++, so we can't use "= 0" for
// pure virtual methods. Instead, we use this macro.
#define GRPC_ABSTRACT \
{ \
gpr_log(GPR_ERROR, "Function marked GRPC_ABSTRACT was not implemented"); \
GPR_ASSERT(false); \
}
#endif // GRPC_USE_CPP_STD_LIB
#endif /* GRPC_CORE_LIB_GPRPP_ABSTRACT_H */

@ -64,14 +64,14 @@ Arena* Arena::Create(size_t initial_size) {
return new (ArenaStorage(initial_size)) Arena(initial_size);
}
Pair<Arena*, void*> Arena::CreateWithAlloc(size_t initial_size,
size_t alloc_size) {
std::pair<Arena*, void*> Arena::CreateWithAlloc(size_t initial_size,
size_t alloc_size) {
static constexpr size_t base_size =
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(Arena));
auto* new_arena =
new (ArenaStorage(initial_size)) Arena(initial_size, alloc_size);
void* first_alloc = reinterpret_cast<char*>(new_arena) + base_size;
return MakePair(new_arena, first_alloc);
return std::make_pair(new_arena, first_alloc);
}
size_t Arena::Destroy() {

@ -36,7 +36,6 @@
#include "src/core/lib/gpr/alloc.h"
#include "src/core/lib/gpr/spinlock.h"
#include "src/core/lib/gprpp/atomic.h"
#include "src/core/lib/gprpp/pair.h"
#include <stddef.h>
@ -50,8 +49,8 @@ class Arena {
// Create an arena, with \a initial_size bytes in the first allocated buffer,
// and return both a void pointer to the returned arena and a void* with the
// first allocation.
static Pair<Arena*, void*> CreateWithAlloc(size_t initial_size,
size_t alloc_size);
static std::pair<Arena*, void*> CreateWithAlloc(size_t initial_size,
size_t alloc_size);
// Destroy an arena, returning the total number of bytes allocated.
size_t Destroy();

@ -26,14 +26,10 @@
#include <algorithm>
#include <functional>
#include <iterator>
#if GRPC_USE_CPP_STD_LIB
#include <map>
#endif
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/gprpp/pair.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/gprpp/string_view.h"
@ -62,503 +58,6 @@ struct RefCountedPtrLess {
}
};
#if GRPC_USE_CPP_STD_LIB
template <class Key, class T, class Compare = std::less<Key>>
using Map = std::map<Key, T, Compare>;
#else // GRPC_USE_CPP_STD_LIB
namespace testing {
class MapTest;
}
// Alternative map implementation for grpc_core
template <class Key, class T, class Compare = std::less<Key>>
class Map {
public:
typedef Key key_type;
typedef T mapped_type;
typedef Pair<key_type, mapped_type> value_type;
typedef Compare key_compare;
class iterator;
class const_iterator;
Map() = default;
~Map() { clear(); }
// Movable.
Map(Map&& other) : root_(other.root_), size_(other.size_) {
other.root_ = nullptr;
other.size_ = 0;
}
Map& operator=(Map&& other) {
if (this != &other) {
clear();
root_ = other.root_;
size_ = other.size_;
other.root_ = nullptr;
other.size_ = 0;
}
return *this;
}
// Copyable.
Map(const Map& other) {
for (const auto& p : other) {
emplace(p);
}
}
Map& operator=(const Map& other) {
if (this != &other) {
clear();
for (const auto& p : other) {
emplace(p);
}
}
return *this;
}
T& operator[](key_type&& key);
T& operator[](const key_type& key);
iterator find(const key_type& k);
size_t erase(const key_type& key);
// Removes the current entry and points to the next one
iterator erase(iterator iter);
size_t size() const { return size_; }
template <class... Args>
Pair<iterator, bool> emplace(Args&&... args);
Pair<iterator, bool> insert(value_type&& pair) {
return emplace(std::move(pair));
}
Pair<iterator, bool> insert(const value_type& pair) { return emplace(pair); }
bool empty() const { return root_ == nullptr; }
void clear() {
auto iter = begin();
while (!empty()) {
iter = erase(iter);
}
}
iterator begin() {
Entry* curr = GetMinEntry(root_);
return iterator(this, curr);
}
iterator end() { return iterator(this, nullptr); }
const_iterator begin() const {
Entry* curr = GetMinEntry(root_);
return const_iterator(this, curr);
}
const_iterator end() const { return const_iterator(this, nullptr); }
iterator lower_bound(const Key& k) {
// This is a workaround for "const key_compare compare;"
// because some versions of compilers cannot build this by requiring
// a user-provided constructor. (ref: https://stackoverflow.com/q/7411515)
key_compare compare_tmp;
const key_compare& compare = compare_tmp;
return std::find_if(begin(), end(), [&k, &compare](const value_type& v) {
return !compare(v.first, k);
});
}
private:
friend class testing::MapTest;
struct Entry {
explicit Entry(value_type&& pair) : pair(std::move(pair)) {}
value_type pair;
Entry* left = nullptr;
Entry* right = nullptr;
int32_t height = 1;
};
static int32_t EntryHeight(const Entry* e) {
return e == nullptr ? 0 : e->height;
}
static Entry* GetMinEntry(Entry* e);
Entry* InOrderSuccessor(const Entry* e) const;
static Entry* RotateLeft(Entry* e);
static Entry* RotateRight(Entry* e);
static Entry* RebalanceTreeAfterInsertion(Entry* root, const key_type& k);
static Entry* RebalanceTreeAfterDeletion(Entry* root);
// Returns a pair with the first value being an iterator pointing to the
// inserted entry and the second value being the new root of the subtree
// after a rebalance
Pair<iterator, Entry*> InsertRecursive(Entry* root, value_type&& p);
// Returns a pair with the first value being an iterator pointing to the
// successor of the deleted entry and the second value being the new root of
// the subtree after a rebalance
Pair<iterator, Entry*> RemoveRecursive(Entry* root, const key_type& k);
// Return 0 if lhs = rhs
// 1 if lhs > rhs
// -1 if lhs < rhs
static int CompareKeys(const Key& lhs, const Key& rhs);
Entry* root_ = nullptr;
size_t size_ = 0;
};
template <class Key, class T, class Compare>
class Map<Key, T, Compare>::iterator
: public std::iterator<std::input_iterator_tag, Pair<Key, T>, int32_t,
Pair<Key, T>*, Pair<Key, T>&> {
public:
iterator(const iterator& iter) : curr_(iter.curr_), map_(iter.map_) {}
bool operator==(const iterator& rhs) const { return (curr_ == rhs.curr_); }
bool operator!=(const iterator& rhs) const { return (curr_ != rhs.curr_); }
iterator& operator++() {
curr_ = map_->InOrderSuccessor(curr_);
return *this;
}
iterator operator++(int) {
Entry* prev = curr_;
curr_ = map_->InOrderSuccessor(curr_);
return iterator(map_, prev);
}
iterator& operator=(const iterator& other) {
if (this != &other) {
this->curr_ = other.curr_;
this->map_ = other.map_;
}
return *this;
}
// operator*()
value_type& operator*() { return curr_->pair; }
const value_type& operator*() const { return curr_->pair; }
// operator->()
value_type* operator->() { return &curr_->pair; }
value_type const* operator->() const { return &curr_->pair; }
private:
friend class Map<key_type, mapped_type, key_compare>;
using GrpcMap = typename ::grpc_core::Map<Key, T, Compare>;
iterator(GrpcMap* map, Entry* curr) : curr_(curr), map_(map) {}
Entry* curr_;
GrpcMap* map_;
};
template <class Key, class T, class Compare>
class Map<Key, T, Compare>::const_iterator
: public std::iterator<std::input_iterator_tag, Pair<Key, T>, int32_t,
Pair<Key, T>*, Pair<Key, T>&> {
public:
const_iterator(const const_iterator& iter)
: curr_(iter.curr_), map_(iter.map_) {}
bool operator==(const const_iterator& rhs) const {
return (curr_ == rhs.curr_);
}
bool operator!=(const const_iterator& rhs) const {
return (curr_ != rhs.curr_);
}
const_iterator& operator++() {
curr_ = map_->InOrderSuccessor(curr_);
return *this;
}
const_iterator operator++(int) {
Entry* prev = curr_;
curr_ = map_->InOrderSuccessor(curr_);
return const_iterator(map_, prev);
}
const_iterator& operator=(const const_iterator& other) {
if (this != &other) {
this->curr_ = other.curr_;
this->map_ = other.map_;
}
return *this;
}
// operator*()
const value_type& operator*() const { return curr_->pair; }
// operator->()
const value_type* operator->() const { return &curr_->pair; }
private:
friend class Map<key_type, mapped_type, key_compare>;
using GrpcMap = typename ::grpc_core::Map<Key, T, Compare>;
const_iterator(const GrpcMap* map, Entry* curr) : curr_(curr), map_(map) {}
Entry* curr_;
const GrpcMap* map_;
};
template <class Key, class T, class Compare>
T& Map<Key, T, Compare>::operator[](key_type&& key) {
auto iter = find(key);
if (iter == end()) {
return emplace(std::move(key), T()).first->second;
}
return iter->second;
}
template <class Key, class T, class Compare>
T& Map<Key, T, Compare>::operator[](const key_type& key) {
auto iter = find(key);
if (iter == end()) {
return emplace(key, T()).first->second;
}
return iter->second;
}
template <class Key, class T, class Compare>
typename Map<Key, T, Compare>::iterator Map<Key, T, Compare>::find(
const key_type& k) {
Entry* iter = root_;
while (iter != nullptr) {
int comp = CompareKeys(iter->pair.first, k);
if (comp == 0) {
return iterator(this, iter);
} else if (comp < 0) {
iter = iter->right;
} else {
iter = iter->left;
}
}
return end();
}
template <class Key, class T, class Compare>
template <class... Args>
typename ::grpc_core::Pair<typename Map<Key, T, Compare>::iterator, bool>
Map<Key, T, Compare>::emplace(Args&&... args) {
Pair<key_type, mapped_type> pair(std::forward<Args>(args)...);
iterator ret = find(pair.first);
bool insertion = false;
if (ret == end()) {
Pair<iterator, Entry*> p = InsertRecursive(root_, std::move(pair));
root_ = p.second;
ret = p.first;
insertion = true;
size_++;
}
return MakePair(ret, insertion);
}
template <class Key, class T, class Compare>
size_t Map<Key, T, Compare>::erase(const key_type& key) {
iterator it = find(key);
if (it == end()) return 0;
erase(it);
return 1;
}
// TODO(mhaidry): Modify erase to use the iterator location
// to create an efficient erase method
template <class Key, class T, class Compare>
typename Map<Key, T, Compare>::iterator Map<Key, T, Compare>::erase(
iterator iter) {
if (iter == end()) return iter;
key_type& del_key = iter->first;
Pair<iterator, Entry*> ret = RemoveRecursive(root_, del_key);
root_ = ret.second;
size_--;
return ret.first;
}
template <class Key, class T, class Compare>
typename Map<Key, T, Compare>::Entry* Map<Key, T, Compare>::InOrderSuccessor(
const Entry* e) const {
if (e->right != nullptr) {
return GetMinEntry(e->right);
}
Entry* successor = nullptr;
Entry* iter = root_;
while (iter != nullptr) {
int comp = CompareKeys(iter->pair.first, e->pair.first);
if (comp > 0) {
successor = iter;
iter = iter->left;
} else if (comp < 0) {
iter = iter->right;
} else
break;
}
return successor;
}
// Returns a pair with the first value being an iterator pointing to the
// inserted entry and the second value being the new root of the subtree
// after a rebalance
template <class Key, class T, class Compare>
typename ::grpc_core::Pair<typename Map<Key, T, Compare>::iterator,
typename Map<Key, T, Compare>::Entry*>
Map<Key, T, Compare>::InsertRecursive(Entry* root, value_type&& p) {
if (root == nullptr) {
Entry* e = New<Entry>(std::move(p));
return MakePair(iterator(this, e), e);
}
int comp = CompareKeys(root->pair.first, p.first);
if (comp > 0) {
Pair<iterator, Entry*> ret = InsertRecursive(root->left, std::move(p));
root->left = ret.second;
ret.second = RebalanceTreeAfterInsertion(root, ret.first->first);
return ret;
} else if (comp < 0) {
Pair<iterator, Entry*> ret = InsertRecursive(root->right, std::move(p));
root->right = ret.second;
ret.second = RebalanceTreeAfterInsertion(root, ret.first->first);
return ret;
} else {
root->pair = std::move(p);
return MakePair(iterator(this, root), root);
}
}
template <class Key, class T, class Compare>
typename Map<Key, T, Compare>::Entry* Map<Key, T, Compare>::GetMinEntry(
Entry* e) {
if (e != nullptr) {
while (e->left != nullptr) {
e = e->left;
}
}
return e;
}
template <class Key, class T, class Compare>
typename Map<Key, T, Compare>::Entry* Map<Key, T, Compare>::RotateLeft(
Entry* e) {
Entry* rightChild = e->right;
Entry* rightLeftChild = rightChild->left;
rightChild->left = e;
e->right = rightLeftChild;
e->height = 1 + GPR_MAX(EntryHeight(e->left), EntryHeight(e->right));
rightChild->height = 1 + GPR_MAX(EntryHeight(rightChild->left),
EntryHeight(rightChild->right));
return rightChild;
}
template <class Key, class T, class Compare>
typename Map<Key, T, Compare>::Entry* Map<Key, T, Compare>::RotateRight(
Entry* e) {
Entry* leftChild = e->left;
Entry* leftRightChild = leftChild->right;
leftChild->right = e;
e->left = leftRightChild;
e->height = 1 + GPR_MAX(EntryHeight(e->left), EntryHeight(e->right));
leftChild->height =
1 + GPR_MAX(EntryHeight(leftChild->left), EntryHeight(leftChild->right));
return leftChild;
}
template <class Key, class T, class Compare>
typename Map<Key, T, Compare>::Entry*
Map<Key, T, Compare>::RebalanceTreeAfterInsertion(Entry* root,
const key_type& k) {
root->height = 1 + GPR_MAX(EntryHeight(root->left), EntryHeight(root->right));
int32_t heightDifference = EntryHeight(root->left) - EntryHeight(root->right);
if (heightDifference > 1 && CompareKeys(root->left->pair.first, k) > 0) {
return RotateRight(root);
}
if (heightDifference < -1 && CompareKeys(root->right->pair.first, k) < 0) {
return RotateLeft(root);
}
if (heightDifference > 1 && CompareKeys(root->left->pair.first, k) < 0) {
root->left = RotateLeft(root->left);
return RotateRight(root);
}
if (heightDifference < -1 && CompareKeys(root->right->pair.first, k) > 0) {
root->right = RotateRight(root->right);
return RotateLeft(root);
}
return root;
}
template <class Key, class T, class Compare>
typename Map<Key, T, Compare>::Entry*
Map<Key, T, Compare>::RebalanceTreeAfterDeletion(Entry* root) {
root->height = 1 + GPR_MAX(EntryHeight(root->left), EntryHeight(root->right));
int32_t heightDifference = EntryHeight(root->left) - EntryHeight(root->right);
if (heightDifference > 1) {
int leftHeightDifference =
EntryHeight(root->left->left) - EntryHeight(root->left->right);
if (leftHeightDifference < 0) {
root->left = RotateLeft(root->left);
}
return RotateRight(root);
}
if (heightDifference < -1) {
int rightHeightDifference =
EntryHeight(root->right->left) - EntryHeight(root->right->right);
if (rightHeightDifference > 0) {
root->right = RotateRight(root->right);
}
return RotateLeft(root);
}
return root;
}
template <class Key, class T, class Compare>
typename ::grpc_core::Pair<typename Map<Key, T, Compare>::iterator,
typename Map<Key, T, Compare>::Entry*>
Map<Key, T, Compare>::RemoveRecursive(Entry* root, const key_type& k) {
Pair<iterator, Entry*> ret = MakePair(end(), root);
if (root == nullptr) return ret;
int comp = CompareKeys(root->pair.first, k);
if (comp > 0) {
ret = RemoveRecursive(root->left, k);
root->left = ret.second;
} else if (comp < 0) {
ret = RemoveRecursive(root->right, k);
root->right = ret.second;
} else {
Entry* entry;
Entry* successor = InOrderSuccessor(root);
if (root->left == nullptr) {
entry = root->right;
Delete(root);
return MakePair(iterator(this, successor), entry);
} else if (root->right == nullptr) {
entry = root->left;
Delete(root);
return MakePair(iterator(this, successor), entry);
} else {
entry = successor;
root->pair.swap(entry->pair);
ret = RemoveRecursive(root->right, entry->pair.first);
root->right = ret.second;
ret.first = iterator(this, root);
}
}
return MakePair(ret.first, RebalanceTreeAfterDeletion(root));
}
template <class Key, class T, class Compare>
int Map<Key, T, Compare>::CompareKeys(const key_type& lhs,
const key_type& rhs) {
// This is a workaround for "const key_compare compare;"
// because some versions of compilers cannot build this by requiring
// a user-provided constructor. (ref: https://stackoverflow.com/q/7411515)
key_compare compare_tmp;
const key_compare& compare = compare_tmp;
bool left_comparison = compare(lhs, rhs);
bool right_comparison = compare(rhs, lhs);
// Both values are equal
if (!left_comparison && !right_comparison) {
return 0;
}
return left_comparison ? -1 : 1;
}
#endif // GRPC_USE_CPP_STD_LIB
} // namespace grpc_core
#endif /* GRPC_CORE_LIB_GPRPP_MAP_H */

@ -33,10 +33,8 @@
// Should not be used in new code.
// TODO(juanlishen): Remove this macro, and instead comment that the public dtor
// should not be used directly.
#define GRPC_ALLOW_CLASS_TO_USE_NON_PUBLIC_DELETE \
template <typename _Delete_T, bool _Delete_can_be_null> \
friend void ::grpc_core::Delete(_Delete_T*); \
template <typename _Delete_T> \
#define GRPC_ALLOW_CLASS_TO_USE_NON_PUBLIC_DELETE \
template <typename _Delete_T> \
friend void ::grpc_core::Delete(_Delete_T*);
// Add this to a class that want to use New(), but has a private or
@ -58,33 +56,28 @@ inline T* New(Args&&... args) {
}
// Alternative to delete, since we cannot use it (for fear of libstdc++)
// We cannot add a default value for can_be_null, because they are used as
// as friend template methods where we cannot define a default value.
// Instead we simply define two variants, one with and one without the boolean
// argument.
template <typename T, bool can_be_null>
template <typename T>
inline void Delete(T* p) {
GPR_DEBUG_ASSERT(can_be_null || p != nullptr);
if (can_be_null && p == nullptr) return;
if (p == nullptr) return;
p->~T();
gpr_free(p);
}
template <typename T>
inline void Delete(T* p) {
Delete<T, /*can_be_null=*/true>(p);
}
template <typename T>
class DefaultDelete {
public:
template <typename T>
void operator()(T* p) {
// std::unique_ptr is gauranteed not to call the deleter
// if the pointer is nullptr.
Delete<T, /*can_be_null=*/false>(p);
// Delete() checks whether the value is null, but std::unique_ptr<> is
// gauranteed not to call the deleter if the pointer is nullptr
// (i.e., it already does this check for us), and we don't want to
// do the check twice. So, instead of calling Delete() here, we
// manually call the object's dtor and free it.
p->~T();
gpr_free(p);
}
};
template <typename T, typename Deleter = DefaultDelete<T>>
template <typename T, typename Deleter = DefaultDelete>
using UniquePtr = std::unique_ptr<T, Deleter>;
template <typename T, typename... Args>

@ -28,7 +28,6 @@
#include <memory>
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gprpp/abstract.h"
#include "src/core/lib/gprpp/debug_location.h"
#include "src/core/lib/gprpp/memory.h"
#include "src/core/lib/gprpp/ref_counted.h"
@ -46,26 +45,26 @@ class Orphanable {
// Gives up ownership of the object. The implementation must arrange
// to eventually destroy the object without further interaction from the
// caller.
virtual void Orphan() GRPC_ABSTRACT;
virtual void Orphan() = 0;
// Not copyable or movable.
Orphanable(const Orphanable&) = delete;
Orphanable& operator=(const Orphanable&) = delete;
GRPC_ABSTRACT_BASE_CLASS
protected:
Orphanable() {}
virtual ~Orphanable() {}
};
template <typename T>
class OrphanableDelete {
public:
void operator()(T* p) { p->Orphan(); }
template <typename T>
void operator()(T* p) {
p->Orphan();
}
};
template <typename T, typename Deleter = OrphanableDelete<T>>
template <typename T, typename Deleter = OrphanableDelete>
using OrphanablePtr = std::unique_ptr<T, Deleter>;
template <typename T, typename... Args>
@ -81,8 +80,6 @@ class InternallyRefCounted : public Orphanable {
InternallyRefCounted(const InternallyRefCounted&) = delete;
InternallyRefCounted& operator=(const InternallyRefCounted&) = delete;
GRPC_ABSTRACT_BASE_CLASS
protected:
GRPC_ALLOW_CLASS_TO_USE_NON_PUBLIC_DELETE

@ -1,38 +0,0 @@
/*
*
* Copyright 2017 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef GRPC_CORE_LIB_GPRPP_PAIR_H
#define GRPC_CORE_LIB_GPRPP_PAIR_H
#include <grpc/support/port_platform.h>
#include <utility>
namespace grpc_core {
template <class T1, class T2>
using Pair = std::pair<T1, T2>;
template <class T1, class T2>
inline Pair<typename std::decay<T1>::type, typename std::decay<T2>::type>
MakePair(T1&& u, T2&& v) {
typedef typename std::decay<T1>::type V1;
typedef typename std::decay<T2>::type V2;
return Pair<V1, V2>(std::forward<T1>(u), std::forward<T2>(v));
}
} // namespace grpc_core
#endif /* GRPC_CORE_LIB_GPRPP_PAIR_H */

@ -30,7 +30,6 @@
#include <cinttypes>
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gprpp/abstract.h"
#include "src/core/lib/gprpp/atomic.h"
#include "src/core/lib/gprpp/debug_location.h"
#include "src/core/lib/gprpp/memory.h"
@ -40,9 +39,6 @@ namespace grpc_core {
// PolymorphicRefCount enforces polymorphic destruction of RefCounted.
class PolymorphicRefCount {
public:
GRPC_ABSTRACT_BASE_CLASS
protected:
GRPC_ALLOW_CLASS_TO_USE_NON_PUBLIC_DELETE
@ -53,9 +49,6 @@ class PolymorphicRefCount {
// RefCounted. Please refer to grpc_core::RefCounted for more details, and
// when in doubt use PolymorphicRefCount.
class NonPolymorphicRefCount {
public:
GRPC_ABSTRACT_BASE_CLASS
protected:
GRPC_ALLOW_CLASS_TO_USE_NON_PUBLIC_DELETE
@ -272,8 +265,6 @@ class RefCounted : public Impl {
RefCounted(const RefCounted&) = delete;
RefCounted& operator=(const RefCounted&) = delete;
GRPC_ABSTRACT_BASE_CLASS
protected:
GRPC_ALLOW_CLASS_TO_USE_NON_PUBLIC_DELETE

@ -28,7 +28,6 @@
#include <grpc/support/thd_id.h>
#include <grpc/support/time.h>
#include "src/core/lib/gprpp/abstract.h"
#include "src/core/lib/gprpp/memory.h"
namespace grpc_core {
@ -38,9 +37,8 @@ namespace internal {
class ThreadInternalsInterface {
public:
virtual ~ThreadInternalsInterface() {}
virtual void Start() GRPC_ABSTRACT;
virtual void Join() GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS
virtual void Start() = 0;
virtual void Join() = 0;
};
} // namespace internal

@ -355,43 +355,4 @@ inline void grpc_closure_list_sched(grpc_closure_list* list) {
grpc_closure_list_sched(closure_list)
#endif
#ifndef NDEBUG
inline void grpc_closure_list_run(const char* file, int line,
grpc_closure_list* list) {
#else
inline void grpc_closure_list_run(grpc_closure_list* list) {
#endif
grpc_closure* c = list->head;
while (c != nullptr) {
grpc_closure* next = c->next_data.next;
#ifndef NDEBUG
if (c->scheduled) {
gpr_log(GPR_ERROR,
"Closure already scheduled. (closure: %p, created: [%s:%d], "
"previously scheduled at: [%s: %d] run?: %s",
c, c->file_created, c->line_created, c->file_initiated,
c->line_initiated, c->run ? "true" : "false");
abort();
}
c->scheduled = true;
c->file_initiated = file;
c->line_initiated = line;
c->run = false;
GPR_ASSERT(c->cb != nullptr);
#endif
c->scheduler->vtable->run(c, c->error_data.error);
c = next;
}
list->head = list->tail = nullptr;
}
/** Schedule all closures in a list to be run. Does not need to be run from a
* safe point. */
#ifndef NDEBUG
#define GRPC_CLOSURE_LIST_RUN(closure_list) \
grpc_closure_list_run(__FILE__, __LINE__, closure_list)
#else
#define GRPC_CLOSURE_LIST_RUN(closure_list) grpc_closure_list_run(closure_list)
#endif
#endif /* GRPC_CORE_LIB_IOMGR_CLOSURE_H */

@ -264,6 +264,15 @@ void Executor::ThreadMain(void* arg) {
grpc_core::ExecCtx::Get()->InvalidateNow();
subtract_depth = RunClosures(ts->name, closures);
}
// We have an issue with Apple platforms where applying gpr_tls_set here
// leads to an EAGAIN error while performing a gpr_tls_get, so we are
// skipping this cleanup for Apple platforms. See PR #19978
// TODO(mhaidry) : Fix this by switching to using thread_local once we have
// support for it in Xcode (PR #20413)or whatever else it takes
#if !defined(__APPLE__)
gpr_tls_set(&g_this_thread_state, reinterpret_cast<intptr_t>(nullptr));
#endif // !__APPLE__
}
void Executor::Enqueue(grpc_closure* closure, grpc_error* error,
@ -465,10 +474,6 @@ void Executor::ShutdownAll() {
bool Executor::IsThreaded(ExecutorType executor_type) {
GPR_ASSERT(executor_type < ExecutorType::NUM_EXECUTORS);
Executor* executor = executors[static_cast<size_t>(executor_type)];
if (executor == nullptr) {
return false;
}
return executors[static_cast<size_t>(executor_type)]->IsThreaded();
}

@ -22,7 +22,6 @@
#include <grpc/support/port_platform.h>
#include "src/core/lib/debug/stats.h"
#include "src/core/lib/gprpp/abstract.h"
#include "src/core/lib/gprpp/atomic.h"
#include "src/core/lib/gprpp/sync.h"
@ -38,17 +37,15 @@ class MPMCQueueInterface {
// Puts elem into queue immediately at the end of queue.
// This might cause to block on full queue depending on implementation.
virtual void Put(void* elem) GRPC_ABSTRACT;
virtual void Put(void* elem) = 0;
// Removes the oldest element from the queue and return it.
// This might cause to block on empty queue depending on implementation.
// Optional argument for collecting stats purpose.
virtual void* Get(gpr_timespec* wait_time = nullptr) GRPC_ABSTRACT;
virtual void* Get(gpr_timespec* wait_time = nullptr) = 0;
// Returns number of elements in the queue currently
virtual int count() const GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS
virtual int count() const = 0;
};
class InfLenFIFOQueue : public MPMCQueueInterface {

@ -43,22 +43,19 @@ class ThreadPoolInterface {
// current thread to be blocked (in case of unable to schedule).
// Closure should contain a function pointer and arguments it will take, more
// details for closure struct at /grpc/include/grpc/impl/codegen/grpc_types.h
virtual void Add(grpc_experimental_completion_queue_functor* closure)
GRPC_ABSTRACT;
virtual void Add(grpc_experimental_completion_queue_functor* closure) = 0;
// Returns the current number of pending closures
virtual int num_pending_closures() const GRPC_ABSTRACT;
virtual int num_pending_closures() const = 0;
// Returns the capacity of pool (number of worker threads in pool)
virtual int pool_capacity() const GRPC_ABSTRACT;
virtual int pool_capacity() const = 0;
// Thread option accessor
virtual const Thread::Options& thread_options() const GRPC_ABSTRACT;
virtual const Thread::Options& thread_options() const = 0;
// Returns the thread name for threads in this ThreadPool.
virtual const char* thread_name() const GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS
virtual const char* thread_name() const = 0;
};
// Worker thread for threadpool. Executes closures in the queue, until getting a

@ -16,8 +16,8 @@
*
*/
#ifndef GRPC_CORE_LIB_IOMGR_GEVENT_UTIL_H
#define GRPC_CORE_LIB_IOMGR_GEVENT_UTIL_H
#ifndef GRPC_CORE_LIB_IOMGR_PYTHON_UTIL_H
#define GRPC_CORE_LIB_IOMGR_PYTHON_UTIL_H
#include <grpc/support/port_platform.h>
@ -25,8 +25,8 @@
#include <grpc/status.h>
#include "src/core/lib/iomgr/error.h"
// These are only used by the gRPC Python extension for gevent
// support. They are easier to define here (rather than in Cython)
// These are only used by the gRPC Python extensions.
// They are easier to define here (rather than in Cython)
// because Cython doesn't handle #defines well.
grpc_error* grpc_socket_error(char* error) {

@ -24,7 +24,6 @@
#include <grpc/grpc.h>
#include <grpc/impl/codegen/grpc_types.h>
#include "src/core/lib/gprpp/abstract.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/endpoint.h"
#include "src/core/lib/iomgr/resolve_address.h"
@ -57,9 +56,7 @@ class TcpServerFdHandler {
public:
virtual ~TcpServerFdHandler() = default;
virtual void Handle(int listener_fd, int fd,
grpc_byte_buffer* pending_read) GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS;
grpc_byte_buffer* pending_read) = 0;
};
} // namespace grpc_core

@ -21,7 +21,6 @@
#include <grpc/support/port_platform.h>
#include "src/core/lib/gprpp/abstract.h"
#include "src/core/lib/iomgr/endpoint.h"
#include "src/core/lib/iomgr/ev_posix.h"
#include "src/core/lib/iomgr/resolve_address.h"
@ -47,18 +46,16 @@ class GrpcUdpHandler {
// Called when data is available to read from the socket. Returns true if
// there is more data to read after this call.
virtual bool Read() GRPC_ABSTRACT;
virtual bool Read() = 0;
// Called when socket becomes write unblocked. The given closure should be
// scheduled when the socket becomes blocked next time.
virtual void OnCanWrite(void* user_data,
grpc_closure* notify_on_write_closure) GRPC_ABSTRACT;
grpc_closure* notify_on_write_closure) = 0;
// Called before the gRPC FD is orphaned. Notify udp server to continue
// orphaning fd by scheduling the given closure, afterwards the associated fd
// will be closed.
virtual void OnFdAboutToOrphan(grpc_closure* orphan_fd_closure,
void* user_data) GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS
void* user_data) = 0;
};
class GrpcUdpHandlerFactory {
@ -67,11 +64,8 @@ class GrpcUdpHandlerFactory {
/* Called when start to listen on a socket.
* Return an instance of the implementation of GrpcUdpHandler interface which
* will process I/O events for this socket from now on. */
virtual GrpcUdpHandler* CreateUdpHandler(grpc_fd* emfd,
void* user_data) GRPC_ABSTRACT;
virtual void DestroyUdpHandler(GrpcUdpHandler* handler) GRPC_ABSTRACT;
GRPC_ABSTRACT_BASE_CLASS
virtual GrpcUdpHandler* CreateUdpHandler(grpc_fd* emfd, void* user_data) = 0;
virtual void DestroyUdpHandler(GrpcUdpHandler* handler) = 0;
};
/* Create a server, initially not bound to any ports */

@ -45,18 +45,18 @@ void grpc_channel_credentials_release(grpc_channel_credentials* creds) {
if (creds) creds->Unref();
}
static grpc_core::Map<grpc_core::UniquePtr<char>,
grpc_core::RefCountedPtr<grpc_channel_credentials>,
grpc_core::StringLess>* g_grpc_control_plane_creds;
static std::map<grpc_core::UniquePtr<char>,
grpc_core::RefCountedPtr<grpc_channel_credentials>,
grpc_core::StringLess>* g_grpc_control_plane_creds;
static gpr_mu g_control_plane_creds_mu;
static void do_control_plane_creds_init() {
gpr_mu_init(&g_control_plane_creds_mu);
GPR_ASSERT(g_grpc_control_plane_creds == nullptr);
g_grpc_control_plane_creds = grpc_core::New<
grpc_core::Map<grpc_core::UniquePtr<char>,
grpc_core::RefCountedPtr<grpc_channel_credentials>,
grpc_core::StringLess>>();
std::map<grpc_core::UniquePtr<char>,
grpc_core::RefCountedPtr<grpc_channel_credentials>,
grpc_core::StringLess>>();
}
void grpc_control_plane_credentials_init() {

@ -110,17 +110,7 @@ struct grpc_channel_credentials
create_security_connector(
grpc_core::RefCountedPtr<grpc_call_credentials> call_creds,
const char* target, const grpc_channel_args* args,
grpc_channel_args** new_args)
#if GRPC_USE_CPP_STD_LIB
= 0;
#else
{
// Tell clang-tidy that call_creds cannot be passed as const-ref.
call_creds.reset();
gpr_log(GPR_ERROR, "Function marked GRPC_ABSTRACT was not implemented");
GPR_ASSERT(false);
}
#endif
grpc_channel_args** new_args) = 0;
// Creates a version of the channel credentials without any attached call
// credentials. This can be used in order to open a channel to a non-trusted
@ -156,13 +146,11 @@ struct grpc_channel_credentials
const char* type() const { return type_; }
GRPC_ABSTRACT_BASE_CLASS
private:
const char* type_;
grpc_core::Map<grpc_core::UniquePtr<char>,
grpc_core::RefCountedPtr<grpc_channel_credentials>,
grpc_core::StringLess>
std::map<grpc_core::UniquePtr<char>,
grpc_core::RefCountedPtr<grpc_channel_credentials>,
grpc_core::StringLess>
local_control_plane_creds_;
};
@ -248,18 +236,16 @@ struct grpc_call_credentials
grpc_auth_metadata_context context,
grpc_credentials_mdelem_array* md_array,
grpc_closure* on_request_metadata,
grpc_error** error) GRPC_ABSTRACT;
grpc_error** error) = 0;
// Cancels a pending asynchronous operation started by
// grpc_call_credentials_get_request_metadata() with the corresponding
// value of \a md_array.
virtual void cancel_get_request_metadata(
grpc_credentials_mdelem_array* md_array, grpc_error* error) GRPC_ABSTRACT;
grpc_credentials_mdelem_array* md_array, grpc_error* error) = 0;
const char* type() const { return type_; }
GRPC_ABSTRACT_BASE_CLASS
private:
const char* type_;
};
@ -282,7 +268,7 @@ struct grpc_server_credentials
virtual ~grpc_server_credentials() { DestroyProcessor(); }
virtual grpc_core::RefCountedPtr<grpc_server_security_connector>
create_security_connector() GRPC_ABSTRACT;
create_security_connector() = 0;
const char* type() const { return type_; }
@ -292,8 +278,6 @@ struct grpc_server_credentials
void set_auth_metadata_processor(
const grpc_auth_metadata_processor& processor);
GRPC_ABSTRACT_BASE_CLASS
private:
void DestroyProcessor() {
if (processor_.destroy != nullptr && processor_.state != nullptr) {

@ -85,13 +85,11 @@ class grpc_oauth2_token_fetcher_credentials : public grpc_call_credentials {
void on_http_response(grpc_credentials_metadata_request* r,
grpc_error* error);
GRPC_ABSTRACT_BASE_CLASS
protected:
virtual void fetch_oauth2(grpc_credentials_metadata_request* req,
grpc_httpcli_context* httpcli_context,
grpc_polling_entity* pollent, grpc_iomgr_cb_func cb,
grpc_millis deadline) GRPC_ABSTRACT;
grpc_millis deadline) = 0;
private:
gpr_mu mu_;

@ -58,15 +58,13 @@ class grpc_security_connector
virtual void check_peer(
tsi_peer peer, grpc_endpoint* ep,
grpc_core::RefCountedPtr<grpc_auth_context>* auth_context,
grpc_closure* on_peer_checked) GRPC_ABSTRACT;
grpc_closure* on_peer_checked) = 0;
/* Compares two security connectors. */
virtual int cmp(const grpc_security_connector* other) const GRPC_ABSTRACT;
virtual int cmp(const grpc_security_connector* other) const = 0;
const char* url_scheme() const { return url_scheme_; }
GRPC_ABSTRACT_BASE_CLASS
private:
const char* url_scheme_;
};
@ -103,16 +101,16 @@ class grpc_channel_security_connector : public grpc_security_connector {
virtual bool check_call_host(grpc_core::StringView host,
grpc_auth_context* auth_context,
grpc_closure* on_call_host_checked,
grpc_error** error) GRPC_ABSTRACT;
grpc_error** error) = 0;
/// Cancels a pending asynchronous call to
/// grpc_channel_security_connector_check_call_host() with
/// \a on_call_host_checked as its callback.
virtual void cancel_check_call_host(grpc_closure* on_call_host_checked,
grpc_error* error) GRPC_ABSTRACT;
grpc_error* error) = 0;
/// Registers handshakers with \a handshake_mgr.
virtual void add_handshakers(
const grpc_channel_args* args, grpc_pollset_set* interested_parties,
grpc_core::HandshakeManager* handshake_mgr) GRPC_ABSTRACT;
virtual void add_handshakers(const grpc_channel_args* args,
grpc_pollset_set* interested_parties,
grpc_core::HandshakeManager* handshake_mgr) = 0;
const grpc_channel_credentials* channel_creds() const {
return channel_creds_.get();
@ -127,8 +125,6 @@ class grpc_channel_security_connector : public grpc_security_connector {
return request_metadata_creds_.get();
}
GRPC_ABSTRACT_BASE_CLASS
protected:
// Helper methods to be used in subclasses.
int channel_security_connector_cmp(
@ -157,9 +153,9 @@ class grpc_server_security_connector : public grpc_security_connector {
grpc_core::RefCountedPtr<grpc_server_credentials> server_creds);
~grpc_server_security_connector() override = default;
virtual void add_handshakers(
const grpc_channel_args* args, grpc_pollset_set* interested_parties,
grpc_core::HandshakeManager* handshake_mgr) GRPC_ABSTRACT;
virtual void add_handshakers(const grpc_channel_args* args,
grpc_pollset_set* interested_parties,
grpc_core::HandshakeManager* handshake_mgr) = 0;
const grpc_server_credentials* server_creds() const {
return server_creds_.get();
@ -168,8 +164,6 @@ class grpc_server_security_connector : public grpc_security_connector {
return server_creds_.get();
}
GRPC_ABSTRACT_BASE_CLASS
protected:
// Helper methods to be used in subclasses.
int server_security_connector_cmp(

@ -56,7 +56,8 @@ grpc_error* ssl_check_peer(
gpr_free(msg);
return error;
}
*auth_context = grpc_ssl_peer_to_auth_context(peer);
*auth_context =
grpc_ssl_peer_to_auth_context(peer, GRPC_SSL_TRANSPORT_SECURITY_TYPE);
return GRPC_ERROR_NONE;
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save