Merge remote-tracking branch 'upstream/master'

pull/18955/head
vam 6 years ago
commit f4affeec66
  1. 1
      .gitignore
  2. 10
      BUILD
  3. 14
      BUILD.gn
  4. 86
      CMakeLists.txt
  5. 106
      Makefile
  6. 7
      WORKSPACE
  7. 202
      bazel/generate_cc.bzl
  8. 14
      bazel/grpc_python_deps.bzl
  9. 84
      bazel/protobuf.bzl
  10. 203
      bazel/python_rules.bzl
  11. 28
      build.yaml
  12. 4
      config.m4
  13. 4
      config.w32
  14. 12
      examples/BUILD
  15. 4
      examples/python/errors/client.py
  16. 4
      examples/python/errors/server.py
  17. 2
      examples/python/errors/test/_error_handling_example_test.py
  18. 17
      examples/python/multiprocessing/BUILD
  19. 11
      examples/python/wait_for_ready/wait_for_ready_example.py
  20. 10
      gRPC-C++.podspec
  21. 14
      gRPC-Core.podspec
  22. 9
      grpc.gemspec
  23. 7
      grpc.gyp
  24. 3
      include/grpc/impl/codegen/port_platform.h
  25. 2
      include/grpc/support/alloc.h
  26. 10
      include/grpcpp/impl/codegen/async_generic_service.h
  27. 2
      include/grpcpp/impl/codegen/async_stream.h
  28. 10
      include/grpcpp/impl/codegen/completion_queue.h
  29. 7
      include/grpcpp/impl/codegen/server_context.h
  30. 7
      include/grpcpp/impl/codegen/service_type.h
  31. 2
      include/grpcpp/impl/server_initializer_impl.h
  32. 4
      include/grpcpp/security/server_credentials.h
  33. 4
      include/grpcpp/security/server_credentials_impl.h
  34. 328
      include/grpcpp/server.h
  35. 1
      include/grpcpp/server_builder.h
  36. 2
      include/grpcpp/server_builder_impl.h
  37. 6
      include/grpcpp/server_impl.h
  38. 9
      package.xml
  39. 27
      src/core/ext/filters/client_channel/backup_poller.cc
  40. 3
      src/core/ext/filters/client_channel/backup_poller.h
  41. 14
      src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc
  42. 6
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc
  43. 179
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc
  44. 4
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc
  45. 4
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc
  46. 52
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc
  47. 83
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.cc
  48. 34
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.h
  49. 51
      src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc
  50. 22
      src/core/ext/filters/client_channel/subchannel.cc
  51. 13
      src/core/ext/transport/chttp2/transport/chttp2_plugin.cc
  52. 43
      src/core/lib/channel/channel_stack.cc
  53. 73
      src/core/lib/gpr/alloc.cc
  54. 10
      src/core/lib/gpr/alloc.h
  55. 3
      src/core/lib/gpr/env.h
  56. 5
      src/core/lib/gpr/env_linux.cc
  57. 5
      src/core/lib/gpr/env_posix.cc
  58. 7
      src/core/lib/gpr/env_windows.cc
  59. 18
      src/core/lib/gpr/string.cc
  60. 6
      src/core/lib/gpr/string.h
  61. 8
      src/core/lib/gprpp/arena.cc
  62. 6
      src/core/lib/gprpp/arena.h
  63. 87
      src/core/lib/gprpp/global_config.h
  64. 29
      src/core/lib/gprpp/global_config_custom.h
  65. 135
      src/core/lib/gprpp/global_config_env.cc
  66. 131
      src/core/lib/gprpp/global_config_env.h
  67. 44
      src/core/lib/gprpp/global_config_generic.h
  68. 2
      src/core/lib/iomgr/combiner.h
  69. 10
      src/core/lib/iomgr/iomgr.cc
  70. 12
      src/core/lib/security/security_connector/ssl_utils.cc
  71. 5
      src/core/lib/slice/slice_buffer.cc
  72. 2
      src/core/lib/slice/slice_internal.h
  73. 6
      src/core/lib/surface/call.cc
  74. 12
      src/core/lib/transport/error_utils.cc
  75. 2
      src/core/lib/transport/transport.cc
  76. 602
      src/cpp/server/server_cc.cc
  77. 0
      src/csharp/Grpc.Core.Api/Interceptors/ClientInterceptorContext.cs
  78. 0
      src/csharp/Grpc.Core.Api/Interceptors/Interceptor.cs
  79. 11
      src/csharp/Grpc.Core/ForwardedTypes.cs
  80. 5
      src/proto/grpc/channelz/BUILD
  81. 5
      src/proto/grpc/health/v1/BUILD
  82. 5
      src/proto/grpc/reflection/v1alpha/BUILD
  83. 41
      src/proto/grpc/testing/BUILD
  84. 30
      src/proto/grpc/testing/proto2/BUILD.bazel
  85. 4
      src/python/grpcio/grpc_core_dependencies.py
  86. 26
      src/python/grpcio_channelz/grpc_channelz/v1/BUILD.bazel
  87. 19
      src/python/grpcio_health_checking/grpc_health/v1/BUILD.bazel
  88. 17
      src/python/grpcio_reflection/grpc_reflection/v1alpha/BUILD.bazel
  89. 4
      src/python/grpcio_tests/tests/fork/_fork_interop_test.py
  90. 87
      src/python/grpcio_tests/tests/interop/BUILD.bazel
  91. 4
      src/python/grpcio_tests/tests/interop/_insecure_intraop_test.py
  92. 4
      src/python/grpcio_tests/tests/interop/_secure_intraop_test.py
  93. 68
      src/python/grpcio_tests/tests/interop/methods.py
  94. 4
      src/python/grpcio_tests/tests/interop/server.py
  95. 97
      src/python/grpcio_tests/tests/interop/service.py
  96. 1
      src/python/grpcio_tests/tests/reflection/BUILD.bazel
  97. 18
      test/core/gpr/alloc_test.cc
  98. 14
      test/core/gpr/env_test.cc
  99. 29
      test/core/gpr/string_test.cc
  100. 26
      test/core/gprpp/BUILD
  101. Some files were not shown because too many files have changed in this diff Show More

1
.gitignore vendored

@ -115,6 +115,7 @@ bazel-genfiles
bazel-grpc
bazel-out
bazel-testlogs
bazel_format_virtual_environment/
# Debug output
gdb.txt

10
BUILD

@ -256,6 +256,7 @@ GRPCXX_PUBLIC_HDRS = [
"include/grpcpp/security/server_credentials.h",
"include/grpcpp/security/server_credentials_impl.h",
"include/grpcpp/server.h",
"include/grpcpp/server_impl.h",
"include/grpcpp/server_builder.h",
"include/grpcpp/server_builder_impl.h",
"include/grpcpp/server_context.h",
@ -577,6 +578,7 @@ grpc_cc_library(
"src/core/lib/gpr/wrap_memcpy.cc",
"src/core/lib/gprpp/arena.cc",
"src/core/lib/gprpp/fork.cc",
"src/core/lib/gprpp/global_config_env.cc",
"src/core/lib/gprpp/thd_posix.cc",
"src/core/lib/gprpp/thd_windows.cc",
"src/core/lib/profiling/basic_timers.cc",
@ -603,6 +605,10 @@ grpc_cc_library(
"src/core/lib/gprpp/arena.h",
"src/core/lib/gprpp/atomic.h",
"src/core/lib/gprpp/fork.h",
"src/core/lib/gprpp/global_config_custom.h",
"src/core/lib/gprpp/global_config_env.h",
"src/core/lib/gprpp/global_config_generic.h",
"src/core/lib/gprpp/global_config.h",
"src/core/lib/gprpp/manual_constructor.h",
"src/core/lib/gprpp/map.h",
"src/core/lib/gprpp/memory.h",
@ -1570,16 +1576,20 @@ grpc_cc_library(
srcs = [
"src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc",
],
hdrs = [
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.h",
],
external_deps = [
"cares",

@ -184,6 +184,11 @@ config("grpc_config") {
"src/core/lib/gprpp/atomic.h",
"src/core/lib/gprpp/fork.cc",
"src/core/lib/gprpp/fork.h",
"src/core/lib/gprpp/global_config.h",
"src/core/lib/gprpp/global_config_custom.h",
"src/core/lib/gprpp/global_config_env.cc",
"src/core/lib/gprpp/global_config_env.h",
"src/core/lib/gprpp/global_config_generic.h",
"src/core/lib/gprpp/manual_constructor.h",
"src/core/lib/gprpp/map.h",
"src/core/lib/gprpp/memory.h",
@ -310,11 +315,15 @@ config("grpc_config") {
"src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.h",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc",
"src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc",
"src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc",
@ -1103,6 +1112,7 @@ config("grpc_config") {
"include/grpcpp/server_builder.h",
"include/grpcpp/server_builder_impl.h",
"include/grpcpp/server_context.h",
"include/grpcpp/server_impl.h",
"include/grpcpp/server_posix.h",
"include/grpcpp/server_posix_impl.h",
"include/grpcpp/support/async_stream.h",
@ -1172,6 +1182,10 @@ config("grpc_config") {
"src/core/lib/gprpp/atomic.h",
"src/core/lib/gprpp/debug_location.h",
"src/core/lib/gprpp/fork.h",
"src/core/lib/gprpp/global_config.h",
"src/core/lib/gprpp/global_config_custom.h",
"src/core/lib/gprpp/global_config_env.h",
"src/core/lib/gprpp/global_config_generic.h",
"src/core/lib/gprpp/inlined_vector.h",
"src/core/lib/gprpp/manual_constructor.h",
"src/core/lib/gprpp/map.h",

@ -629,6 +629,8 @@ add_dependencies(buildtests_cxx error_details_test)
add_dependencies(buildtests_cxx exception_test)
add_dependencies(buildtests_cxx filter_end2end_test)
add_dependencies(buildtests_cxx generic_end2end_test)
add_dependencies(buildtests_cxx global_config_env_test)
add_dependencies(buildtests_cxx global_config_test)
add_dependencies(buildtests_cxx golden_file_test)
add_dependencies(buildtests_cxx grpc_alts_credentials_options_test)
add_dependencies(buildtests_cxx grpc_cli)
@ -873,6 +875,7 @@ add_library(gpr
src/core/lib/gpr/wrap_memcpy.cc
src/core/lib/gprpp/arena.cc
src/core/lib/gprpp/fork.cc
src/core/lib/gprpp/global_config_env.cc
src/core/lib/gprpp/thd_posix.cc
src/core/lib/gprpp/thd_windows.cc
src/core/lib/profiling/basic_timers.cc
@ -1289,10 +1292,13 @@ add_library(grpc
src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc
src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc
@ -2682,10 +2688,13 @@ add_library(grpc_unsecure
src/core/ext/transport/inproc/inproc_transport.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc
src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc
@ -3071,6 +3080,7 @@ foreach(_hdr
include/grpcpp/server_builder.h
include/grpcpp/server_builder_impl.h
include/grpcpp/server_context.h
include/grpcpp/server_impl.h
include/grpcpp/server_posix.h
include/grpcpp/server_posix_impl.h
include/grpcpp/support/async_stream.h
@ -3684,6 +3694,7 @@ foreach(_hdr
include/grpcpp/server_builder.h
include/grpcpp/server_builder_impl.h
include/grpcpp/server_context.h
include/grpcpp/server_impl.h
include/grpcpp/server_posix.h
include/grpcpp/server_posix_impl.h
include/grpcpp/support/async_stream.h
@ -4669,6 +4680,7 @@ foreach(_hdr
include/grpcpp/server_builder.h
include/grpcpp/server_builder_impl.h
include/grpcpp/server_context.h
include/grpcpp/server_impl.h
include/grpcpp/server_posix.h
include/grpcpp/server_posix_impl.h
include/grpcpp/support/async_stream.h
@ -13428,6 +13440,80 @@ target_link_libraries(generic_end2end_test
)
endif (gRPC_BUILD_TESTS)
if (gRPC_BUILD_TESTS)
add_executable(global_config_env_test
test/core/gprpp/global_config_env_test.cc
third_party/googletest/googletest/src/gtest-all.cc
third_party/googletest/googlemock/src/gmock-all.cc
)
target_include_directories(global_config_env_test
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include
PRIVATE ${_gRPC_SSL_INCLUDE_DIR}
PRIVATE ${_gRPC_PROTOBUF_INCLUDE_DIR}
PRIVATE ${_gRPC_ZLIB_INCLUDE_DIR}
PRIVATE ${_gRPC_BENCHMARK_INCLUDE_DIR}
PRIVATE ${_gRPC_CARES_INCLUDE_DIR}
PRIVATE ${_gRPC_GFLAGS_INCLUDE_DIR}
PRIVATE ${_gRPC_ADDRESS_SORTING_INCLUDE_DIR}
PRIVATE ${_gRPC_NANOPB_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(global_config_env_test
${_gRPC_PROTOBUF_LIBRARIES}
${_gRPC_ALLTARGETS_LIBRARIES}
gpr
grpc_test_util_unsecure
${_gRPC_GFLAGS_LIBRARIES}
)
endif (gRPC_BUILD_TESTS)
if (gRPC_BUILD_TESTS)
add_executable(global_config_test
test/core/gprpp/global_config_test.cc
third_party/googletest/googletest/src/gtest-all.cc
third_party/googletest/googlemock/src/gmock-all.cc
)
target_include_directories(global_config_test
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include
PRIVATE ${_gRPC_SSL_INCLUDE_DIR}
PRIVATE ${_gRPC_PROTOBUF_INCLUDE_DIR}
PRIVATE ${_gRPC_ZLIB_INCLUDE_DIR}
PRIVATE ${_gRPC_BENCHMARK_INCLUDE_DIR}
PRIVATE ${_gRPC_CARES_INCLUDE_DIR}
PRIVATE ${_gRPC_GFLAGS_INCLUDE_DIR}
PRIVATE ${_gRPC_ADDRESS_SORTING_INCLUDE_DIR}
PRIVATE ${_gRPC_NANOPB_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(global_config_test
${_gRPC_PROTOBUF_LIBRARIES}
${_gRPC_ALLTARGETS_LIBRARIES}
gpr
grpc_test_util_unsecure
${_gRPC_GFLAGS_LIBRARIES}
)
endif (gRPC_BUILD_TESTS)
if (gRPC_BUILD_TESTS)

@ -1206,6 +1206,8 @@ error_details_test: $(BINDIR)/$(CONFIG)/error_details_test
exception_test: $(BINDIR)/$(CONFIG)/exception_test
filter_end2end_test: $(BINDIR)/$(CONFIG)/filter_end2end_test
generic_end2end_test: $(BINDIR)/$(CONFIG)/generic_end2end_test
global_config_env_test: $(BINDIR)/$(CONFIG)/global_config_env_test
global_config_test: $(BINDIR)/$(CONFIG)/global_config_test
golden_file_test: $(BINDIR)/$(CONFIG)/golden_file_test
grpc_alts_credentials_options_test: $(BINDIR)/$(CONFIG)/grpc_alts_credentials_options_test
grpc_cli: $(BINDIR)/$(CONFIG)/grpc_cli
@ -1682,6 +1684,8 @@ buildtests_cxx: privatelibs_cxx \
$(BINDIR)/$(CONFIG)/exception_test \
$(BINDIR)/$(CONFIG)/filter_end2end_test \
$(BINDIR)/$(CONFIG)/generic_end2end_test \
$(BINDIR)/$(CONFIG)/global_config_env_test \
$(BINDIR)/$(CONFIG)/global_config_test \
$(BINDIR)/$(CONFIG)/golden_file_test \
$(BINDIR)/$(CONFIG)/grpc_alts_credentials_options_test \
$(BINDIR)/$(CONFIG)/grpc_cli \
@ -1826,6 +1830,8 @@ buildtests_cxx: privatelibs_cxx \
$(BINDIR)/$(CONFIG)/exception_test \
$(BINDIR)/$(CONFIG)/filter_end2end_test \
$(BINDIR)/$(CONFIG)/generic_end2end_test \
$(BINDIR)/$(CONFIG)/global_config_env_test \
$(BINDIR)/$(CONFIG)/global_config_test \
$(BINDIR)/$(CONFIG)/golden_file_test \
$(BINDIR)/$(CONFIG)/grpc_alts_credentials_options_test \
$(BINDIR)/$(CONFIG)/grpc_cli \
@ -2318,6 +2324,10 @@ test_cxx: buildtests_cxx
$(Q) $(BINDIR)/$(CONFIG)/filter_end2end_test || ( echo test filter_end2end_test failed ; exit 1 )
$(E) "[RUN] Testing generic_end2end_test"
$(Q) $(BINDIR)/$(CONFIG)/generic_end2end_test || ( echo test generic_end2end_test failed ; exit 1 )
$(E) "[RUN] Testing global_config_env_test"
$(Q) $(BINDIR)/$(CONFIG)/global_config_env_test || ( echo test global_config_env_test failed ; exit 1 )
$(E) "[RUN] Testing global_config_test"
$(Q) $(BINDIR)/$(CONFIG)/global_config_test || ( echo test global_config_test failed ; exit 1 )
$(E) "[RUN] Testing golden_file_test"
$(Q) $(BINDIR)/$(CONFIG)/golden_file_test || ( echo test golden_file_test failed ; exit 1 )
$(E) "[RUN] Testing grpc_alts_credentials_options_test"
@ -3354,6 +3364,7 @@ LIBGPR_SRC = \
src/core/lib/gpr/wrap_memcpy.cc \
src/core/lib/gprpp/arena.cc \
src/core/lib/gprpp/fork.cc \
src/core/lib/gprpp/global_config_env.cc \
src/core/lib/gprpp/thd_posix.cc \
src/core/lib/gprpp/thd_windows.cc \
src/core/lib/profiling/basic_timers.cc \
@ -3749,10 +3760,13 @@ LIBGRPC_SRC = \
src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc \
src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc \
@ -5090,10 +5104,13 @@ LIBGRPC_UNSECURE_SRC = \
src/core/ext/transport/inproc/inproc_transport.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc \
src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc \
@ -5411,6 +5428,7 @@ PUBLIC_HEADERS_CXX += \
include/grpcpp/server_builder.h \
include/grpcpp/server_builder_impl.h \
include/grpcpp/server_context.h \
include/grpcpp/server_impl.h \
include/grpcpp/server_posix.h \
include/grpcpp/server_posix_impl.h \
include/grpcpp/support/async_stream.h \
@ -6032,6 +6050,7 @@ PUBLIC_HEADERS_CXX += \
include/grpcpp/server_builder.h \
include/grpcpp/server_builder_impl.h \
include/grpcpp/server_context.h \
include/grpcpp/server_impl.h \
include/grpcpp/server_posix.h \
include/grpcpp/server_posix_impl.h \
include/grpcpp/support/async_stream.h \
@ -6966,6 +6985,7 @@ PUBLIC_HEADERS_CXX += \
include/grpcpp/server_builder.h \
include/grpcpp/server_builder_impl.h \
include/grpcpp/server_context.h \
include/grpcpp/server_impl.h \
include/grpcpp/server_posix.h \
include/grpcpp/server_posix_impl.h \
include/grpcpp/support/async_stream.h \
@ -16396,6 +16416,92 @@ endif
endif
GLOBAL_CONFIG_ENV_TEST_SRC = \
test/core/gprpp/global_config_env_test.cc \
GLOBAL_CONFIG_ENV_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GLOBAL_CONFIG_ENV_TEST_SRC))))
ifeq ($(NO_SECURE),true)
# You can't build secure targets if you don't have OpenSSL.
$(BINDIR)/$(CONFIG)/global_config_env_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)/global_config_env_test: protobuf_dep_error
else
$(BINDIR)/$(CONFIG)/global_config_env_test: $(PROTOBUF_DEP) $(GLOBAL_CONFIG_ENV_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr.a $(LIBDIR)/$(CONFIG)/libgrpc_test_util_unsecure.a
$(E) "[LD] Linking $@"
$(Q) mkdir -p `dirname $@`
$(Q) $(LDXX) $(LDFLAGS) $(GLOBAL_CONFIG_ENV_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr.a $(LIBDIR)/$(CONFIG)/libgrpc_test_util_unsecure.a $(LDLIBSXX) $(LDLIBS_PROTOBUF) $(LDLIBS) $(LDLIBS_SECURE) $(GTEST_LIB) -o $(BINDIR)/$(CONFIG)/global_config_env_test
endif
endif
$(OBJDIR)/$(CONFIG)/test/core/gprpp/global_config_env_test.o: $(LIBDIR)/$(CONFIG)/libgpr.a $(LIBDIR)/$(CONFIG)/libgrpc_test_util_unsecure.a
deps_global_config_env_test: $(GLOBAL_CONFIG_ENV_TEST_OBJS:.o=.dep)
ifneq ($(NO_SECURE),true)
ifneq ($(NO_DEPS),true)
-include $(GLOBAL_CONFIG_ENV_TEST_OBJS:.o=.dep)
endif
endif
GLOBAL_CONFIG_TEST_SRC = \
test/core/gprpp/global_config_test.cc \
GLOBAL_CONFIG_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GLOBAL_CONFIG_TEST_SRC))))
ifeq ($(NO_SECURE),true)
# You can't build secure targets if you don't have OpenSSL.
$(BINDIR)/$(CONFIG)/global_config_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)/global_config_test: protobuf_dep_error
else
$(BINDIR)/$(CONFIG)/global_config_test: $(PROTOBUF_DEP) $(GLOBAL_CONFIG_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr.a $(LIBDIR)/$(CONFIG)/libgrpc_test_util_unsecure.a
$(E) "[LD] Linking $@"
$(Q) mkdir -p `dirname $@`
$(Q) $(LDXX) $(LDFLAGS) $(GLOBAL_CONFIG_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr.a $(LIBDIR)/$(CONFIG)/libgrpc_test_util_unsecure.a $(LDLIBSXX) $(LDLIBS_PROTOBUF) $(LDLIBS) $(LDLIBS_SECURE) $(GTEST_LIB) -o $(BINDIR)/$(CONFIG)/global_config_test
endif
endif
$(OBJDIR)/$(CONFIG)/test/core/gprpp/global_config_test.o: $(LIBDIR)/$(CONFIG)/libgpr.a $(LIBDIR)/$(CONFIG)/libgrpc_test_util_unsecure.a
deps_global_config_test: $(GLOBAL_CONFIG_TEST_OBJS:.o=.dep)
ifneq ($(NO_SECURE),true)
ifneq ($(NO_DEPS),true)
-include $(GLOBAL_CONFIG_TEST_OBJS:.o=.dep)
endif
endif
GOLDEN_FILE_TEST_SRC = \
$(GENDIR)/src/proto/grpc/testing/compiler_test.pb.cc $(GENDIR)/src/proto/grpc/testing/compiler_test.grpc.pb.cc \
test/cpp/codegen/golden_file_test.cc \

@ -18,13 +18,6 @@ register_toolchains(
"//third_party/toolchains/bazel_0.23.2_rbe_windows:cc-toolchain-x64_windows",
)
# TODO(https://github.com/grpc/grpc/issues/18331): Move off of this dependency.
git_repository(
name = "org_pubref_rules_protobuf",
remote = "https://github.com/ghostwriternr/rules_protobuf",
tag = "v0.8.2.1-alpha",
)
git_repository(
name = "io_bazel_rules_python",
commit = "8b5d0683a7d878b28fffe464779c8a53659fc645",

@ -4,81 +4,132 @@ This is an internal rule used by cc_grpc_library, and shouldn't be used
directly.
"""
def generate_cc_impl(ctx):
"""Implementation of the generate_cc rule."""
protos = [f for src in ctx.attr.srcs for f in src.proto.direct_sources]
includes = [f for src in ctx.attr.srcs for f in src.proto.transitive_imports]
outs = []
# label_len is length of the path from WORKSPACE root to the location of this build file
label_len = 0
# proto_root is the directory relative to which generated include paths should be
proto_root = ""
if ctx.label.package:
# The +1 is for the trailing slash.
label_len += len(ctx.label.package) + 1
if ctx.label.workspace_root:
label_len += len(ctx.label.workspace_root) + 1
proto_root = "/" + ctx.label.workspace_root
load(
"//bazel:protobuf.bzl",
"get_include_protoc_args",
"get_plugin_args",
"get_proto_root",
"proto_path_to_generated_filename",
)
_GRPC_PROTO_HEADER_FMT = "{}.grpc.pb.h"
_GRPC_PROTO_SRC_FMT = "{}.grpc.pb.cc"
_GRPC_PROTO_MOCK_HEADER_FMT = "{}_mock.grpc.pb.h"
_PROTO_HEADER_FMT = "{}.pb.h"
_PROTO_SRC_FMT = "{}.pb.cc"
if ctx.executable.plugin:
outs += [proto.path[label_len:-len(".proto")] + ".grpc.pb.h" for proto in protos]
outs += [proto.path[label_len:-len(".proto")] + ".grpc.pb.cc" for proto in protos]
if ctx.attr.generate_mocks:
outs += [proto.path[label_len:-len(".proto")] + "_mock.grpc.pb.h" for proto in protos]
else:
outs += [proto.path[label_len:-len(".proto")] + ".pb.h" for proto in protos]
outs += [proto.path[label_len:-len(".proto")] + ".pb.cc" for proto in protos]
out_files = [ctx.actions.declare_file(out) for out in outs]
dir_out = str(ctx.genfiles_dir.path + proto_root)
def _strip_package_from_path(label_package, path):
if len(label_package) == 0:
return path
if not path.startswith(label_package + "/"):
fail("'{}' does not lie within '{}'.".format(path, label_package))
return path[len(label_package + "/"):]
arguments = []
if ctx.executable.plugin:
arguments += ["--plugin=protoc-gen-PLUGIN=" + ctx.executable.plugin.path]
flags = list(ctx.attr.flags)
if ctx.attr.generate_mocks:
flags.append("generate_mock_code=true")
arguments += ["--PLUGIN_out=" + ",".join(flags) + ":" + dir_out]
tools = [ctx.executable.plugin]
else:
arguments += ["--cpp_out=" + ",".join(ctx.attr.flags) + ":" + dir_out]
tools = []
def _join_directories(directories):
massaged_directories = [directory for directory in directories if len(directory) != 0]
return "/".join(massaged_directories)
# Import protos relative to their workspace root so that protoc prints the
# right include paths.
for include in includes:
directory = include.path
if directory.startswith("external"):
external_sep = directory.find("/")
repository_sep = directory.find("/", external_sep + 1)
arguments += ["--proto_path=" + directory[:repository_sep]]
def generate_cc_impl(ctx):
"""Implementation of the generate_cc rule."""
protos = [f for src in ctx.attr.srcs for f in src.proto.direct_sources]
includes = [
f
for src in ctx.attr.srcs
for f in src.proto.transitive_imports
]
outs = []
proto_root = get_proto_root(
ctx.label.workspace_root,
)
label_package = _join_directories([ctx.label.workspace_root, ctx.label.package])
if ctx.executable.plugin:
outs += [
proto_path_to_generated_filename(
_strip_package_from_path(label_package, proto.path),
_GRPC_PROTO_HEADER_FMT,
)
for proto in protos
]
outs += [
proto_path_to_generated_filename(
_strip_package_from_path(label_package, proto.path),
_GRPC_PROTO_SRC_FMT,
)
for proto in protos
]
if ctx.attr.generate_mocks:
outs += [
proto_path_to_generated_filename(
_strip_package_from_path(label_package, proto.path),
_GRPC_PROTO_MOCK_HEADER_FMT,
)
for proto in protos
]
else:
arguments += ["--proto_path=."]
# Include the output directory so that protoc puts the generated code in the
# right directory.
arguments += ["--proto_path={0}{1}".format(dir_out, proto_root)]
arguments += [proto.path for proto in protos]
outs += [
proto_path_to_generated_filename(
_strip_package_from_path(label_package, proto.path),
_PROTO_HEADER_FMT,
)
for proto in protos
]
outs += [
proto_path_to_generated_filename(
_strip_package_from_path(label_package, proto.path),
_PROTO_SRC_FMT,
)
for proto in protos
]
out_files = [ctx.actions.declare_file(out) for out in outs]
dir_out = str(ctx.genfiles_dir.path + proto_root)
# create a list of well known proto files if the argument is non-None
well_known_proto_files = []
if ctx.attr.well_known_protos:
f = ctx.attr.well_known_protos.files.to_list()[0].dirname
if f != "external/com_google_protobuf/src/google/protobuf":
print("Error: Only @com_google_protobuf//:well_known_protos is supported")
arguments = []
if ctx.executable.plugin:
arguments += get_plugin_args(
ctx.executable.plugin,
ctx.attr.flags,
dir_out,
ctx.attr.generate_mocks,
)
tools = [ctx.executable.plugin]
else:
# f points to "external/com_google_protobuf/src/google/protobuf"
# add -I argument to protoc so it knows where to look for the proto files.
arguments += ["-I{0}".format(f + "/../..")]
well_known_proto_files = [f for f in ctx.attr.well_known_protos.files]
arguments += ["--cpp_out=" + ",".join(ctx.attr.flags) + ":" + dir_out]
tools = []
arguments += get_include_protoc_args(includes)
ctx.actions.run(
inputs = protos + includes + well_known_proto_files,
tools = tools,
outputs = out_files,
executable = ctx.executable._protoc,
arguments = arguments,
)
# Include the output directory so that protoc puts the generated code in the
# right directory.
arguments += ["--proto_path={0}{1}".format(dir_out, proto_root)]
arguments += [proto.path for proto in protos]
return struct(files=depset(out_files))
# create a list of well known proto files if the argument is non-None
well_known_proto_files = []
if ctx.attr.well_known_protos:
f = ctx.attr.well_known_protos.files.to_list()[0].dirname
if f != "external/com_google_protobuf/src/google/protobuf":
print(
"Error: Only @com_google_protobuf//:well_known_protos is supported",
)
else:
# f points to "external/com_google_protobuf/src/google/protobuf"
# add -I argument to protoc so it knows where to look for the proto files.
arguments += ["-I{0}".format(f + "/../..")]
well_known_proto_files = [
f
for f in ctx.attr.well_known_protos.files
]
ctx.actions.run(
inputs = protos + includes + well_known_proto_files,
tools = tools,
outputs = out_files,
executable = ctx.executable._protoc,
arguments = arguments,
)
return struct(files = depset(out_files))
_generate_cc = rule(
attrs = {
@ -96,10 +147,8 @@ _generate_cc = rule(
mandatory = False,
allow_empty = True,
),
"well_known_protos" : attr.label(
mandatory = False,
),
"generate_mocks" : attr.bool(
"well_known_protos": attr.label(mandatory = False),
"generate_mocks": attr.bool(
default = False,
mandatory = False,
),
@ -115,7 +164,10 @@ _generate_cc = rule(
)
def generate_cc(well_known_protos, **kwargs):
if well_known_protos:
_generate_cc(well_known_protos="@com_google_protobuf//:well_known_protos", **kwargs)
else:
_generate_cc(**kwargs)
if well_known_protos:
_generate_cc(
well_known_protos = "@com_google_protobuf//:well_known_protos",
**kwargs
)
else:
_generate_cc(**kwargs)

@ -1,16 +1,8 @@
load("//third_party/py:python_configure.bzl", "python_configure")
load("@io_bazel_rules_python//python:pip.bzl", "pip_repositories")
load("@grpc_python_dependencies//:requirements.bzl", "pip_install")
load("@org_pubref_rules_protobuf//python:rules.bzl", "py_proto_repositories")
def grpc_python_deps():
# TODO(https://github.com/grpc/grpc/issues/18256): Remove conditional.
if hasattr(native, "http_archive"):
python_configure(name = "local_config_python")
pip_repositories()
pip_install()
py_proto_repositories()
else:
print("Building Python gRPC with bazel 23.0+ is disabled pending " +
"resolution of https://github.com/grpc/grpc/issues/18256.")
python_configure(name = "local_config_python")
pip_repositories()
pip_install()

@ -0,0 +1,84 @@
"""Utility functions for generating protobuf code."""
_PROTO_EXTENSION = ".proto"
def get_proto_root(workspace_root):
"""Gets the root protobuf directory.
Args:
workspace_root: context.label.workspace_root
Returns:
The directory relative to which generated include paths should be.
"""
if workspace_root:
return "/{}".format(workspace_root)
else:
return ""
def _strip_proto_extension(proto_filename):
if not proto_filename.endswith(_PROTO_EXTENSION):
fail('"{}" does not end with "{}"'.format(
proto_filename,
_PROTO_EXTENSION,
))
return proto_filename[:-len(_PROTO_EXTENSION)]
def proto_path_to_generated_filename(proto_path, fmt_str):
"""Calculates the name of a generated file for a protobuf path.
For example, "examples/protos/helloworld.proto" might map to
"helloworld.pb.h".
Args:
proto_path: The path to the .proto file.
fmt_str: A format string used to calculate the generated filename. For
example, "{}.pb.h" might be used to calculate a C++ header filename.
Returns:
The generated filename.
"""
return fmt_str.format(_strip_proto_extension(proto_path))
def _get_include_directory(include):
directory = include.path
if directory.startswith("external"):
external_separator = directory.find("/")
repository_separator = directory.find("/", external_separator + 1)
return directory[:repository_separator]
else:
return "."
def get_include_protoc_args(includes):
"""Returns protoc args that imports protos relative to their import root.
Args:
includes: A list of included proto files.
Returns:
A list of arguments to be passed to protoc. For example, ["--proto_path=."].
"""
return [
"--proto_path={}".format(_get_include_directory(include))
for include in includes
]
def get_plugin_args(plugin, flags, dir_out, generate_mocks):
"""Returns arguments configuring protoc to use a plugin for a language.
Args:
plugin: An executable file to run as the protoc plugin.
flags: The plugin flags to be passed to protoc.
dir_out: The output directory for the plugin.
generate_mocks: A bool indicating whether to generate mocks.
Returns:
A list of protoc arguments configuring the plugin.
"""
augmented_flags = list(flags)
if generate_mocks:
augmented_flags.append("generate_mock_code=true")
return [
"--plugin=protoc-gen-PLUGIN=" + plugin.path,
"--PLUGIN_out=" + ",".join(augmented_flags) + ":" + dir_out,
]

@ -0,0 +1,203 @@
"""Generates and compiles Python gRPC stubs from proto_library rules."""
load("@grpc_python_dependencies//:requirements.bzl", "requirement")
load(
"//bazel:protobuf.bzl",
"get_include_protoc_args",
"get_plugin_args",
"get_proto_root",
"proto_path_to_generated_filename",
)
_GENERATED_PROTO_FORMAT = "{}_pb2.py"
_GENERATED_GRPC_PROTO_FORMAT = "{}_pb2_grpc.py"
def _get_staged_proto_file(context, source_file):
if source_file.dirname == context.label.package:
return source_file
else:
copied_proto = context.actions.declare_file(source_file.basename)
context.actions.run_shell(
inputs = [source_file],
outputs = [copied_proto],
command = "cp {} {}".format(source_file.path, copied_proto.path),
mnemonic = "CopySourceProto",
)
return copied_proto
def _generate_py_impl(context):
protos = []
for src in context.attr.deps:
for file in src.proto.direct_sources:
protos.append(_get_staged_proto_file(context, file))
includes = [
file
for src in context.attr.deps
for file in src.proto.transitive_imports
]
proto_root = get_proto_root(context.label.workspace_root)
format_str = (_GENERATED_GRPC_PROTO_FORMAT if context.executable.plugin else _GENERATED_PROTO_FORMAT)
out_files = [
context.actions.declare_file(
proto_path_to_generated_filename(
proto.basename,
format_str,
),
)
for proto in protos
]
arguments = []
tools = [context.executable._protoc]
if context.executable.plugin:
arguments += get_plugin_args(
context.executable.plugin,
context.attr.flags,
context.genfiles_dir.path,
False,
)
tools += [context.executable.plugin]
else:
arguments += [
"--python_out={}:{}".format(
",".join(context.attr.flags),
context.genfiles_dir.path,
),
]
arguments += get_include_protoc_args(includes)
arguments += [
"--proto_path={}".format(context.genfiles_dir.path)
for proto in protos
]
for proto in protos:
massaged_path = proto.path
if massaged_path.startswith(context.genfiles_dir.path):
massaged_path = proto.path[len(context.genfiles_dir.path) + 1:]
arguments.append(massaged_path)
well_known_proto_files = []
if context.attr.well_known_protos:
well_known_proto_directory = context.attr.well_known_protos.files.to_list(
)[0].dirname
arguments += ["-I{}".format(well_known_proto_directory + "/../..")]
well_known_proto_files = context.attr.well_known_protos.files.to_list()
context.actions.run(
inputs = protos + includes + well_known_proto_files,
tools = tools,
outputs = out_files,
executable = context.executable._protoc,
arguments = arguments,
mnemonic = "ProtocInvocation",
)
return struct(files = depset(out_files))
__generate_py = rule(
attrs = {
"deps": attr.label_list(
mandatory = True,
allow_empty = False,
providers = ["proto"],
),
"plugin": attr.label(
executable = True,
providers = ["files_to_run"],
cfg = "host",
),
"flags": attr.string_list(
mandatory = False,
allow_empty = True,
),
"well_known_protos": attr.label(mandatory = False),
"_protoc": attr.label(
default = Label("//external:protocol_compiler"),
executable = True,
cfg = "host",
),
},
output_to_genfiles = True,
implementation = _generate_py_impl,
)
def _generate_py(well_known_protos, **kwargs):
if well_known_protos:
__generate_py(
well_known_protos = "@com_google_protobuf//:well_known_protos",
**kwargs
)
else:
__generate_py(**kwargs)
_WELL_KNOWN_PROTO_LIBS = [
"@com_google_protobuf//:any_proto",
"@com_google_protobuf//:api_proto",
"@com_google_protobuf//:compiler_plugin_proto",
"@com_google_protobuf//:descriptor_proto",
"@com_google_protobuf//:duration_proto",
"@com_google_protobuf//:empty_proto",
"@com_google_protobuf//:field_mask_proto",
"@com_google_protobuf//:source_context_proto",
"@com_google_protobuf//:struct_proto",
"@com_google_protobuf//:timestamp_proto",
"@com_google_protobuf//:type_proto",
"@com_google_protobuf//:wrappers_proto",
]
def py_proto_library(
name,
deps,
well_known_protos = True,
proto_only = False,
**kwargs):
"""Generate python code for a protobuf.
Args:
name: The name of the target.
deps: A list of dependencies. Must contain a single element.
well_known_protos: A bool indicating whether or not to include well-known
protos.
proto_only: A bool indicating whether to generate vanilla protobuf code
or to also generate gRPC code.
"""
if len(deps) > 1:
fail("The supported length of 'deps' is 1.")
codegen_target = "_{}_codegen".format(name)
codegen_grpc_target = "_{}_grpc_codegen".format(name)
well_known_proto_rules = _WELL_KNOWN_PROTO_LIBS if well_known_protos else []
_generate_py(
name = codegen_target,
deps = deps,
well_known_protos = well_known_protos,
**kwargs
)
if not proto_only:
_generate_py(
name = codegen_grpc_target,
deps = deps,
plugin = "//:grpc_python_plugin",
well_known_protos = well_known_protos,
**kwargs
)
native.py_library(
name = name,
srcs = [
":{}".format(codegen_grpc_target),
":{}".format(codegen_target),
],
deps = [requirement("protobuf")],
**kwargs
)
else:
native.py_library(
name = name,
srcs = [":{}".format(codegen_target), ":{}".format(codegen_target)],
deps = [requirement("protobuf")],
**kwargs
)

@ -148,6 +148,7 @@ filegroups:
- src/core/lib/gpr/wrap_memcpy.cc
- src/core/lib/gprpp/arena.cc
- src/core/lib/gprpp/fork.cc
- src/core/lib/gprpp/global_config_env.cc
- src/core/lib/gprpp/thd_posix.cc
- src/core/lib/gprpp/thd_windows.cc
- src/core/lib/profiling/basic_timers.cc
@ -194,6 +195,10 @@ filegroups:
- src/core/lib/gprpp/arena.h
- src/core/lib/gprpp/atomic.h
- src/core/lib/gprpp/fork.h
- src/core/lib/gprpp/global_config.h
- src/core/lib/gprpp/global_config_custom.h
- src/core/lib/gprpp/global_config_env.h
- src/core/lib/gprpp/global_config_generic.h
- src/core/lib/gprpp/manual_constructor.h
- src/core/lib/gprpp/map.h
- src/core/lib/gprpp/memory.h
@ -775,13 +780,17 @@ filegroups:
headers:
- src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h
- src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h
- src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.h
src:
- src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc
- src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc
- src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc
- src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc
- src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc
- src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc
- src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc
- src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc
- src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.cc
- src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc
- src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc
plugin: grpc_resolver_dns_ares
@ -1383,6 +1392,7 @@ filegroups:
- include/grpcpp/server_builder.h
- include/grpcpp/server_builder_impl.h
- include/grpcpp/server_context.h
- include/grpcpp/server_impl.h
- include/grpcpp/server_posix.h
- include/grpcpp/server_posix_impl.h
- include/grpcpp/support/async_stream.h
@ -4724,6 +4734,24 @@ targets:
- grpc++
- grpc
- gpr
- name: global_config_env_test
build: test
language: c++
src:
- test/core/gprpp/global_config_env_test.cc
deps:
- gpr
- grpc_test_util_unsecure
uses_polling: false
- name: global_config_test
build: test
language: c++
src:
- test/core/gprpp/global_config_test.cc
deps:
- gpr
- grpc_test_util_unsecure
uses_polling: false
- name: golden_file_test
gtest: true
build: test

@ -79,6 +79,7 @@ if test "$PHP_GRPC" != "no"; then
src/core/lib/gpr/wrap_memcpy.cc \
src/core/lib/gprpp/arena.cc \
src/core/lib/gprpp/fork.cc \
src/core/lib/gprpp/global_config_env.cc \
src/core/lib/gprpp/thd_posix.cc \
src/core/lib/gprpp/thd_windows.cc \
src/core/lib/profiling/basic_timers.cc \
@ -402,10 +403,13 @@ if test "$PHP_GRPC" != "no"; then
src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc \
src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc \
src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc \

@ -54,6 +54,7 @@ if (PHP_GRPC != "no") {
"src\\core\\lib\\gpr\\wrap_memcpy.cc " +
"src\\core\\lib\\gprpp\\arena.cc " +
"src\\core\\lib\\gprpp\\fork.cc " +
"src\\core\\lib\\gprpp\\global_config_env.cc " +
"src\\core\\lib\\gprpp\\thd_posix.cc " +
"src\\core\\lib\\gprpp\\thd_windows.cc " +
"src\\core\\lib\\profiling\\basic_timers.cc " +
@ -377,10 +378,13 @@ if (PHP_GRPC != "no") {
"src\\core\\ext\\filters\\client_channel\\lb_policy\\round_robin\\round_robin.cc " +
"src\\core\\ext\\filters\\client_channel\\resolver\\dns\\c_ares\\dns_resolver_ares.cc " +
"src\\core\\ext\\filters\\client_channel\\resolver\\dns\\c_ares\\grpc_ares_ev_driver.cc " +
"src\\core\\ext\\filters\\client_channel\\resolver\\dns\\c_ares\\grpc_ares_ev_driver_libuv.cc " +
"src\\core\\ext\\filters\\client_channel\\resolver\\dns\\c_ares\\grpc_ares_ev_driver_posix.cc " +
"src\\core\\ext\\filters\\client_channel\\resolver\\dns\\c_ares\\grpc_ares_ev_driver_windows.cc " +
"src\\core\\ext\\filters\\client_channel\\resolver\\dns\\c_ares\\grpc_ares_wrapper.cc " +
"src\\core\\ext\\filters\\client_channel\\resolver\\dns\\c_ares\\grpc_ares_wrapper_fallback.cc " +
"src\\core\\ext\\filters\\client_channel\\resolver\\dns\\c_ares\\grpc_ares_wrapper_libuv.cc " +
"src\\core\\ext\\filters\\client_channel\\resolver\\dns\\c_ares\\grpc_ares_wrapper_libuv_windows.cc " +
"src\\core\\ext\\filters\\client_channel\\resolver\\dns\\c_ares\\grpc_ares_wrapper_posix.cc " +
"src\\core\\ext\\filters\\client_channel\\resolver\\dns\\c_ares\\grpc_ares_wrapper_windows.cc " +
"src\\core\\ext\\filters\\client_channel\\resolver\\dns\\native\\dns_resolver.cc " +

@ -16,10 +16,9 @@ licenses(["notice"]) # 3-clause BSD
package(default_visibility = ["//visibility:public"])
load("@grpc_python_dependencies//:requirements.bzl", "requirement")
load("//bazel:grpc_build_system.bzl", "grpc_proto_library")
load("//bazel:cc_grpc_library.bzl", "cc_grpc_library")
load("@org_pubref_rules_protobuf//python:rules.bzl", "py_proto_library")
load("//bazel:python_rules.bzl", "py_proto_library")
grpc_proto_library(
name = "auth_sample",
@ -60,11 +59,14 @@ grpc_proto_library(
srcs = ["protos/keyvaluestore.proto"],
)
proto_library(
name = "helloworld_proto_descriptor",
srcs = ["protos/helloworld.proto"],
)
py_proto_library(
name = "py_helloworld",
protos = ["protos/helloworld.proto"],
with_grpc = True,
deps = [requirement("protobuf")],
deps = [":helloworld_proto_descriptor"],
)
cc_binary(

@ -20,8 +20,8 @@ import grpc
from grpc_status import rpc_status
from google.rpc import error_details_pb2
from examples.protos import helloworld_pb2
from examples.protos import helloworld_pb2_grpc
from examples import helloworld_pb2
from examples import helloworld_pb2_grpc
_LOGGER = logging.getLogger(__name__)

@ -24,8 +24,8 @@ from grpc_status import rpc_status
from google.protobuf import any_pb2
from google.rpc import code_pb2, status_pb2, error_details_pb2
from examples.protos import helloworld_pb2
from examples.protos import helloworld_pb2_grpc
from examples import helloworld_pb2
from examples import helloworld_pb2_grpc
_ONE_DAY_IN_SECONDS = 60 * 60 * 24

@ -26,7 +26,7 @@ import logging
import grpc
from examples.protos import helloworld_pb2_grpc
from examples import helloworld_pb2_grpc
from examples.python.errors import client as error_handling_client
from examples.python.errors import server as error_handling_server

@ -15,12 +15,17 @@
# limitations under the License.
load("@grpc_python_dependencies//:requirements.bzl", "requirement")
load("@org_pubref_rules_protobuf//python:rules.bzl", "py_proto_library")
load("//bazel:python_rules.bzl", "py_proto_library")
py_proto_library(
proto_library(
name = "prime_proto",
protos = ["prime.proto",],
deps = [requirement("protobuf")],
srcs = ["prime.proto"]
)
py_proto_library(
name = "prime_proto_pb2",
deps = [":prime_proto"],
well_known_protos = False,
)
py_binary(
@ -29,7 +34,7 @@ py_binary(
srcs = ["client.py"],
deps = [
"//src/python/grpcio/grpc:grpcio",
":prime_proto",
":prime_proto_pb2",
],
default_python_version = "PY3",
)
@ -40,7 +45,7 @@ py_binary(
srcs = ["server.py"],
deps = [
"//src/python/grpcio/grpc:grpcio",
":prime_proto"
":prime_proto_pb2"
] + select({
"//conditions:default": [requirement("futures")],
"//:python3": [],

@ -22,8 +22,8 @@ import threading
import grpc
from examples.protos import helloworld_pb2
from examples.protos import helloworld_pb2_grpc
from examples import helloworld_pb2
from examples import helloworld_pb2_grpc
_LOGGER = logging.getLogger(__name__)
_LOGGER.setLevel(logging.INFO)
@ -33,10 +33,13 @@ _ONE_DAY_IN_SECONDS = 60 * 60 * 24
@contextmanager
def get_free_loopback_tcp_port():
tcp_socket = socket.socket(socket.AF_INET6)
if socket.has_ipv6:
tcp_socket = socket.socket(socket.AF_INET6)
else:
tcp_socket = socket.socket(socket.AF_INET)
tcp_socket.bind(('', 0))
address_tuple = tcp_socket.getsockname()
yield "[::1]:%s" % (address_tuple[1])
yield "localhost:%s" % (address_tuple[1])
tcp_socket.close()

@ -123,6 +123,7 @@ Pod::Spec.new do |s|
'include/grpcpp/server_builder.h',
'include/grpcpp/server_builder_impl.h',
'include/grpcpp/server_context.h',
'include/grpcpp/server_impl.h',
'include/grpcpp/server_posix.h',
'include/grpcpp/server_posix_impl.h',
'include/grpcpp/support/async_stream.h',
@ -269,6 +270,10 @@ Pod::Spec.new do |s|
'src/core/lib/gprpp/arena.h',
'src/core/lib/gprpp/atomic.h',
'src/core/lib/gprpp/fork.h',
'src/core/lib/gprpp/global_config.h',
'src/core/lib/gprpp/global_config_custom.h',
'src/core/lib/gprpp/global_config_env.h',
'src/core/lib/gprpp/global_config_generic.h',
'src/core/lib/gprpp/manual_constructor.h',
'src/core/lib/gprpp/map.h',
'src/core/lib/gprpp/memory.h',
@ -555,6 +560,7 @@ Pod::Spec.new do |s|
'src/core/ext/filters/client_channel/lb_policy/subchannel_list.h',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.h',
'src/core/ext/filters/max_age/max_age_filter.h',
'src/core/ext/filters/message_size/message_size_filter.h',
'src/core/ext/filters/http/client_authority_filter.h',
@ -591,6 +597,10 @@ Pod::Spec.new do |s|
'src/core/lib/gprpp/arena.h',
'src/core/lib/gprpp/atomic.h',
'src/core/lib/gprpp/fork.h',
'src/core/lib/gprpp/global_config.h',
'src/core/lib/gprpp/global_config_custom.h',
'src/core/lib/gprpp/global_config_env.h',
'src/core/lib/gprpp/global_config_generic.h',
'src/core/lib/gprpp/manual_constructor.h',
'src/core/lib/gprpp/map.h',
'src/core/lib/gprpp/memory.h',

@ -208,6 +208,10 @@ Pod::Spec.new do |s|
'src/core/lib/gprpp/arena.h',
'src/core/lib/gprpp/atomic.h',
'src/core/lib/gprpp/fork.h',
'src/core/lib/gprpp/global_config.h',
'src/core/lib/gprpp/global_config_custom.h',
'src/core/lib/gprpp/global_config_env.h',
'src/core/lib/gprpp/global_config_generic.h',
'src/core/lib/gprpp/manual_constructor.h',
'src/core/lib/gprpp/map.h',
'src/core/lib/gprpp/memory.h',
@ -250,6 +254,7 @@ Pod::Spec.new do |s|
'src/core/lib/gpr/wrap_memcpy.cc',
'src/core/lib/gprpp/arena.cc',
'src/core/lib/gprpp/fork.cc',
'src/core/lib/gprpp/global_config_env.cc',
'src/core/lib/gprpp/thd_posix.cc',
'src/core/lib/gprpp/thd_windows.cc',
'src/core/lib/profiling/basic_timers.cc',
@ -533,6 +538,7 @@ Pod::Spec.new do |s|
'src/core/ext/filters/client_channel/lb_policy/subchannel_list.h',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.h',
'src/core/ext/filters/max_age/max_age_filter.h',
'src/core/ext/filters/message_size/message_size_filter.h',
'src/core/ext/filters/http/client_authority_filter.h',
@ -854,10 +860,13 @@ Pod::Spec.new do |s|
'src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc',
'src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc',
@ -890,6 +899,10 @@ Pod::Spec.new do |s|
'src/core/lib/gprpp/arena.h',
'src/core/lib/gprpp/atomic.h',
'src/core/lib/gprpp/fork.h',
'src/core/lib/gprpp/global_config.h',
'src/core/lib/gprpp/global_config_custom.h',
'src/core/lib/gprpp/global_config_env.h',
'src/core/lib/gprpp/global_config_generic.h',
'src/core/lib/gprpp/manual_constructor.h',
'src/core/lib/gprpp/map.h',
'src/core/lib/gprpp/memory.h',
@ -1176,6 +1189,7 @@ Pod::Spec.new do |s|
'src/core/ext/filters/client_channel/lb_policy/subchannel_list.h',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.h',
'src/core/ext/filters/max_age/max_age_filter.h',
'src/core/ext/filters/message_size/message_size_filter.h',
'src/core/ext/filters/http/client_authority_filter.h',

@ -102,6 +102,10 @@ Gem::Specification.new do |s|
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 )
s.files += %w( src/core/lib/gprpp/global_config.h )
s.files += %w( src/core/lib/gprpp/global_config_custom.h )
s.files += %w( src/core/lib/gprpp/global_config_env.h )
s.files += %w( src/core/lib/gprpp/global_config_generic.h )
s.files += %w( src/core/lib/gprpp/manual_constructor.h )
s.files += %w( src/core/lib/gprpp/map.h )
s.files += %w( src/core/lib/gprpp/memory.h )
@ -144,6 +148,7 @@ Gem::Specification.new do |s|
s.files += %w( src/core/lib/gpr/wrap_memcpy.cc )
s.files += %w( src/core/lib/gprpp/arena.cc )
s.files += %w( src/core/lib/gprpp/fork.cc )
s.files += %w( src/core/lib/gprpp/global_config_env.cc )
s.files += %w( src/core/lib/gprpp/thd_posix.cc )
s.files += %w( src/core/lib/gprpp/thd_windows.cc )
s.files += %w( src/core/lib/profiling/basic_timers.cc )
@ -467,6 +472,7 @@ Gem::Specification.new do |s|
s.files += %w( src/core/ext/filters/client_channel/lb_policy/subchannel_list.h )
s.files += %w( src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h )
s.files += %w( src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h )
s.files += %w( src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.h )
s.files += %w( src/core/ext/filters/max_age/max_age_filter.h )
s.files += %w( src/core/ext/filters/message_size/message_size_filter.h )
s.files += %w( src/core/ext/filters/http/client_authority_filter.h )
@ -791,10 +797,13 @@ Gem::Specification.new do |s|
s.files += %w( src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc )
s.files += %w( src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc )
s.files += %w( src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc )
s.files += %w( src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc )
s.files += %w( src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc )
s.files += %w( src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc )
s.files += %w( src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc )
s.files += %w( src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc )
s.files += %w( src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc )
s.files += %w( src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.cc )
s.files += %w( src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc )
s.files += %w( src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc )
s.files += %w( src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc )

@ -252,6 +252,7 @@
'src/core/lib/gpr/wrap_memcpy.cc',
'src/core/lib/gprpp/arena.cc',
'src/core/lib/gprpp/fork.cc',
'src/core/lib/gprpp/global_config_env.cc',
'src/core/lib/gprpp/thd_posix.cc',
'src/core/lib/gprpp/thd_windows.cc',
'src/core/lib/profiling/basic_timers.cc',
@ -584,10 +585,13 @@
'src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc',
'src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc',
@ -1341,10 +1345,13 @@
'src/core/ext/transport/inproc/inproc_transport.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc',
'src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc',

@ -77,6 +77,7 @@
#define GPR_WINDOWS 1
#define GPR_WINDOWS_SUBPROCESS 1
#define GPR_WINDOWS_ENV
#define GPR_HAS_ALIGNED_MALLOC 1
#ifdef __MSYS__
#define GPR_GETPID_IN_UNISTD_H 1
#define GPR_MSYS_TMPFILE
@ -173,6 +174,7 @@
#define GPR_POSIX_SYNC 1
#define GPR_POSIX_TIME 1
#define GPR_HAS_PTHREAD_H 1
#define GPR_HAS_ALIGNED_ALLOC 1
#define GPR_GETPID_IN_UNISTD_H 1
#ifdef _LP64
#define GPR_ARCH_64 1
@ -238,6 +240,7 @@
#define GPR_POSIX_SUBPROCESS 1
#define GPR_POSIX_SYNC 1
#define GPR_POSIX_TIME 1
#define GPR_HAS_POSIX_MEMALIGN 1
#define GPR_HAS_PTHREAD_H 1
#define GPR_GETPID_IN_UNISTD_H 1
#ifndef GRPC_CFSTREAM

@ -32,6 +32,8 @@ typedef struct gpr_allocation_functions {
void* (*zalloc_fn)(size_t size); /** if NULL, uses malloc_fn then memset */
void* (*realloc_fn)(void* ptr, size_t size);
void (*free_fn)(void* ptr);
void* (*aligned_alloc_fn)(size_t size, size_t alignment);
void (*aligned_free_fn)(void* ptr);
} gpr_allocation_functions;
/** malloc.

@ -39,7 +39,7 @@ class GenericServerContext final : public ServerContext {
const grpc::string& host() const { return host_; }
private:
friend class Server;
friend class grpc_impl::Server;
friend class ServerInterface;
void Clear() {
@ -79,8 +79,8 @@ class AsyncGenericService final {
ServerCompletionQueue* notification_cq, void* tag);
private:
friend class Server;
Server* server_;
friend class grpc_impl::Server;
grpc_impl::Server* server_;
};
namespace experimental {
@ -135,14 +135,14 @@ class CallbackGenericService {
}
private:
friend class ::grpc::Server;
friend class ::grpc_impl::Server;
internal::CallbackBidiHandler<ByteBuffer, ByteBuffer>* Handler() {
return new internal::CallbackBidiHandler<ByteBuffer, ByteBuffer>(
[this] { return CreateReactor(); });
}
Server* server_{nullptr};
grpc_impl::Server* server_{nullptr};
};
} // namespace experimental
} // namespace grpc

@ -1099,7 +1099,7 @@ class ServerAsyncReaderWriter final
}
private:
friend class ::grpc::Server;
friend class ::grpc_impl::Server;
void BindCall(::grpc::internal::Call* call) override { call_ = *call; }

@ -43,8 +43,9 @@ struct grpc_completion_queue;
namespace grpc_impl {
class Server;
class ServerBuilder;
}
} // namespace grpc_impl
namespace grpc {
template <class R>
@ -66,7 +67,6 @@ class Channel;
class ChannelInterface;
class ClientContext;
class CompletionQueue;
class Server;
class ServerContext;
class ServerInterface;
@ -274,7 +274,7 @@ class CompletionQueue : private GrpcLibraryCodegen {
friend class ::grpc::internal::TemplatedBidiStreamingHandler;
template <StatusCode code>
friend class ::grpc::internal::ErrorMethodHandler;
friend class ::grpc::Server;
friend class ::grpc_impl::Server;
friend class ::grpc::ServerContext;
friend class ::grpc::ServerInterface;
template <class InputMessage, class OutputMessage>
@ -408,8 +408,8 @@ class ServerCompletionQueue : public CompletionQueue {
polling_type_(polling_type) {}
grpc_cq_polling_type polling_type_;
friend class ::grpc_impl::ServerBuilder;
friend class Server;
friend class grpc_impl::ServerBuilder;
friend class grpc_impl::Server;
};
} // namespace grpc

@ -41,11 +41,14 @@ struct grpc_metadata;
struct grpc_call;
struct census_context;
namespace grpc_impl {
class Server;
} // namespace grpc_impl
namespace grpc {
class ClientContext;
class GenericServerContext;
class CompletionQueue;
class Server;
class ServerInterface;
template <class W, class R>
class ServerAsyncReader;
@ -269,7 +272,7 @@ class ServerContext {
friend class ::grpc::testing::InteropServerContextInspector;
friend class ::grpc::testing::ServerContextTestSpouse;
friend class ::grpc::ServerInterface;
friend class ::grpc::Server;
friend class ::grpc_impl::Server;
template <class W, class R>
friend class ::grpc::ServerAsyncReader;
template <class W>

@ -26,10 +26,13 @@
#include <grpcpp/impl/codegen/server_interface.h>
#include <grpcpp/impl/codegen/status.h>
namespace grpc_impl {
class Server;
} // namespace grpc_impl
namespace grpc {
class CompletionQueue;
class Server;
class ServerInterface;
class ServerCompletionQueue;
class ServerContext;
@ -233,7 +236,7 @@ class Service {
}
private:
friend class Server;
friend class grpc_impl::Server;
friend class ServerInterface;
ServerInterface* server_;
std::vector<std::unique_ptr<internal::RpcServiceMethod>> methods_;

@ -26,10 +26,10 @@
namespace grpc {
class Server;
class Service;
} // namespace grpc
namespace grpc_impl {
class Server;
class ServerInitializer {
public:

@ -21,6 +21,10 @@
#include <grpcpp/security/server_credentials_impl.h>
namespace grpc_impl {
class Server;
} // namespace grpc_impl
namespace grpc {
typedef ::grpc_impl::ServerCredentials ServerCredentials;

@ -30,10 +30,10 @@ struct grpc_server;
namespace grpc {
class Server;
struct SslServerCredentialsOptions;
} // namespace grpc
namespace grpc_impl {
class Server;
/// Wrapper around \a grpc_server_credentials, a way to authenticate a server.
class ServerCredentials {
@ -46,7 +46,7 @@ class ServerCredentials {
const std::shared_ptr<grpc::AuthMetadataProcessor>& processor) = 0;
private:
friend class ::grpc::Server;
friend class ::grpc_impl::Server;
/// Tries to bind \a server to the given \a addr (eg, localhost:1234,
/// 192.168.1.1:31416, [::1]:27182, etc.)

@ -1,6 +1,6 @@
/*
*
* Copyright 2015 gRPC authors.
* 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.
@ -19,333 +19,11 @@
#ifndef GRPCPP_SERVER_H
#define GRPCPP_SERVER_H
#include <condition_variable>
#include <list>
#include <memory>
#include <mutex>
#include <vector>
#include <grpcpp/server_impl.h>
#include <grpc/compression.h>
#include <grpc/support/atm.h>
#include <grpcpp/completion_queue.h>
#include <grpcpp/health_check_service_interface.h>
#include <grpcpp/impl/call.h>
#include <grpcpp/impl/codegen/client_interceptor.h>
#include <grpcpp/impl/codegen/grpc_library.h>
#include <grpcpp/impl/codegen/server_interface.h>
#include <grpcpp/impl/rpc_service_method.h>
#include <grpcpp/security/server_credentials.h>
#include <grpcpp/support/channel_arguments.h>
#include <grpcpp/support/config.h>
#include <grpcpp/support/status.h>
struct grpc_server;
namespace grpc_impl {
class ServerInitializer;
}
namespace grpc {
class AsyncGenericService;
class ServerContext;
/// Represents a gRPC server.
///
/// Use a \a grpc::ServerBuilder to create, configure, and start
/// \a Server instances.
class Server : public ServerInterface, private GrpcLibraryCodegen {
public:
~Server();
/// Block until the server shuts down.
///
/// \warning The server must be either shutting down or some other thread must
/// call \a Shutdown for this function to ever return.
void Wait() override;
/// Global callbacks are a set of hooks that are called when server
/// events occur. \a SetGlobalCallbacks method is used to register
/// the hooks with gRPC. Note that
/// the \a GlobalCallbacks instance will be shared among all
/// \a Server instances in an application and can be set exactly
/// once per application.
class GlobalCallbacks {
public:
virtual ~GlobalCallbacks() {}
/// Called before server is created.
virtual void UpdateArguments(ChannelArguments* args) {}
/// Called before application callback for each synchronous server request
virtual void PreSynchronousRequest(ServerContext* context) = 0;
/// Called after application callback for each synchronous server request
virtual void PostSynchronousRequest(ServerContext* context) = 0;
/// Called before server is started.
virtual void PreServerStart(Server* server) {}
/// Called after a server port is added.
virtual void AddPort(Server* server, const grpc::string& addr,
ServerCredentials* creds, int port) {}
};
/// Set the global callback object. Can only be called once per application.
/// Does not take ownership of callbacks, and expects the pointed to object
/// to be alive until all server objects in the process have been destroyed.
/// The same \a GlobalCallbacks object will be used throughout the
/// application and is shared among all \a Server objects.
static void SetGlobalCallbacks(GlobalCallbacks* callbacks);
/// Returns a \em raw pointer to the underlying \a grpc_server instance.
/// EXPERIMENTAL: for internal/test use only
grpc_server* c_server();
/// Returns the health check service.
HealthCheckServiceInterface* GetHealthCheckService() const {
return health_check_service_.get();
}
/// Establish a channel for in-process communication
std::shared_ptr<Channel> InProcessChannel(const ChannelArguments& args);
/// NOTE: class experimental_type is not part of the public API of this class.
/// TODO(yashykt): Integrate into public API when this is no longer
/// experimental.
class experimental_type {
public:
explicit experimental_type(Server* server) : server_(server) {}
/// Establish a channel for in-process communication with client
/// interceptors
std::shared_ptr<Channel> InProcessChannelWithInterceptors(
const ChannelArguments& args,
std::vector<
std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
interceptor_creators);
private:
Server* server_;
};
/// NOTE: The function experimental() is not stable public API. It is a view
/// to the experimental components of this class. It may be changed or removed
/// at any time.
experimental_type experimental() { return experimental_type(this); }
protected:
/// Register a service. This call does not take ownership of the service.
/// The service must exist for the lifetime of the Server instance.
bool RegisterService(const grpc::string* host, Service* service) override;
/// Try binding the server to the given \a addr endpoint
/// (port, and optionally including IP address to bind to).
///
/// It can be invoked multiple times. Should be used before
/// starting the server.
///
/// \param addr The address to try to bind to the server (eg, localhost:1234,
/// 192.168.1.1:31416, [::1]:27182, etc.).
/// \param creds The credentials associated with the server.
///
/// \return bound port number on success, 0 on failure.
///
/// \warning It is an error to call this method on an already started server.
int AddListeningPort(const grpc::string& addr,
ServerCredentials* creds) override;
/// NOTE: This is *NOT* a public API. The server constructors are supposed to
/// be used by \a ServerBuilder class only. The constructor will be made
/// 'private' very soon.
///
/// Server constructors. To be used by \a ServerBuilder only.
///
/// \param max_message_size Maximum message length that the channel can
/// receive.
///
/// \param args The channel args
///
/// \param sync_server_cqs The completion queues to use if the server is a
/// synchronous server (or a hybrid server). The server polls for new RPCs on
/// these queues
///
/// \param min_pollers The minimum number of polling threads per server
/// completion queue (in param sync_server_cqs) to use for listening to
/// incoming requests (used only in case of sync server)
///
/// \param max_pollers The maximum number of polling threads per server
/// completion queue (in param sync_server_cqs) to use for listening to
/// incoming requests (used only in case of sync server)
///
/// \param sync_cq_timeout_msec The timeout to use when calling AsyncNext() on
/// server completion queues passed via sync_server_cqs param.
Server(int max_message_size, ChannelArguments* args,
std::shared_ptr<std::vector<std::unique_ptr<ServerCompletionQueue>>>
sync_server_cqs,
int min_pollers, int max_pollers, int sync_cq_timeout_msec,
grpc_resource_quota* server_rq = nullptr,
std::vector<
std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
interceptor_creators = std::vector<std::unique_ptr<
experimental::ServerInterceptorFactoryInterface>>());
/// Start the server.
///
/// \param cqs Completion queues for handling asynchronous services. The
/// caller is required to keep all completion queues live until the server is
/// destroyed.
/// \param num_cqs How many completion queues does \a cqs hold.
void Start(ServerCompletionQueue** cqs, size_t num_cqs) override;
grpc_server* server() override { return server_; }
private:
std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>*
interceptor_creators() override {
return &interceptor_creators_;
}
friend class AsyncGenericService;
friend class grpc_impl::ServerBuilder;
friend class grpc_impl::ServerInitializer;
class SyncRequest;
class CallbackRequestBase;
template <class ServerContextType>
class CallbackRequest;
class UnimplementedAsyncRequest;
class UnimplementedAsyncResponse;
/// SyncRequestThreadManager is an implementation of ThreadManager. This class
/// is responsible for polling for incoming RPCs and calling the RPC handlers.
/// This is only used in case of a Sync server (i.e a server exposing a sync
/// interface)
class SyncRequestThreadManager;
/// Register a generic service. This call does not take ownership of the
/// service. The service must exist for the lifetime of the Server instance.
void RegisterAsyncGenericService(AsyncGenericService* service) override;
/// NOTE: class experimental_registration_type is not part of the public API
/// of this class
/// TODO(vjpai): Move these contents to the public API of Server when
/// they are no longer experimental
class experimental_registration_type final
: public experimental_registration_interface {
public:
explicit experimental_registration_type(Server* server) : server_(server) {}
void RegisterCallbackGenericService(
experimental::CallbackGenericService* service) override {
server_->RegisterCallbackGenericService(service);
}
private:
Server* server_;
};
/// TODO(vjpai): Mark this override when experimental type above is deleted
void RegisterCallbackGenericService(
experimental::CallbackGenericService* service);
/// NOTE: The function experimental_registration() is not stable public API.
/// It is a view to the experimental components of this class. It may be
/// changed or removed at any time.
experimental_registration_interface* experimental_registration() override {
return &experimental_registration_;
}
void PerformOpsOnCall(internal::CallOpSetInterface* ops,
internal::Call* call) override;
void ShutdownInternal(gpr_timespec deadline) override;
int max_receive_message_size() const override {
return max_receive_message_size_;
}
CompletionQueue* CallbackCQ() override;
grpc_impl::ServerInitializer* initializer();
// A vector of interceptor factory objects.
// This should be destroyed after health_check_service_ and this requirement
// is satisfied by declaring interceptor_creators_ before
// health_check_service_. (C++ mandates that member objects be destroyed in
// the reverse order of initialization.)
std::vector<std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
interceptor_creators_;
const int max_receive_message_size_;
/// The following completion queues are ONLY used in case of Sync API
/// i.e. if the server has any services with sync methods. The server uses
/// these completion queues to poll for new RPCs
std::shared_ptr<std::vector<std::unique_ptr<ServerCompletionQueue>>>
sync_server_cqs_;
/// List of \a ThreadManager instances (one for each cq in
/// the \a sync_server_cqs)
std::vector<std::unique_ptr<SyncRequestThreadManager>> sync_req_mgrs_;
// Outstanding unmatched callback requests, indexed by method.
// NOTE: Using a gpr_atm rather than atomic_int because atomic_int isn't
// copyable or movable and thus will cause compilation errors. We
// actually only want to extend the vector before the threaded use
// starts, but this is still a limitation.
std::vector<gpr_atm> callback_unmatched_reqs_count_;
// List of callback requests to start when server actually starts.
std::list<CallbackRequestBase*> callback_reqs_to_start_;
// For registering experimental callback generic service; remove when that
// method longer experimental
experimental_registration_type experimental_registration_{this};
// Server status
grpc::internal::Mutex mu_;
bool started_;
bool shutdown_;
bool shutdown_notified_; // Was notify called on the shutdown_cv_
grpc::internal::CondVar shutdown_cv_;
// It is ok (but not required) to nest callback_reqs_mu_ under mu_ .
// Incrementing callback_reqs_outstanding_ is ok without a lock but it must be
// decremented under the lock in case it is the last request and enables the
// server shutdown. The increment is performance-critical since it happens
// during periods of increasing load; the decrement happens only when memory
// is maxed out, during server shutdown, or (possibly in a future version)
// during decreasing load, so it is less performance-critical.
grpc::internal::Mutex callback_reqs_mu_;
grpc::internal::CondVar callback_reqs_done_cv_;
std::atomic_int callback_reqs_outstanding_{0};
std::shared_ptr<GlobalCallbacks> global_callbacks_;
std::vector<grpc::string> services_;
bool has_async_generic_service_{false};
bool has_callback_generic_service_{false};
// Pointer to the wrapped grpc_server.
grpc_server* server_;
std::unique_ptr<grpc_impl::ServerInitializer> server_initializer_;
std::unique_ptr<HealthCheckServiceInterface> health_check_service_;
bool health_check_service_disabled_;
// When appropriate, use a default callback generic service to handle
// unimplemented methods
std::unique_ptr<experimental::CallbackGenericService> unimplemented_service_;
// A special handler for resource exhausted in sync case
std::unique_ptr<internal::MethodHandler> resource_exhausted_handler_;
// Handler for callback generic service, if any
std::unique_ptr<internal::MethodHandler> generic_handler_;
// callback_cq_ references the callbackable completion queue associated
// with this server (if any). It is set on the first call to CallbackCQ().
// It is _not owned_ by the server; ownership belongs with its internal
// shutdown callback tag (invoked when the CQ is fully shutdown).
// It is protected by mu_
CompletionQueue* callback_cq_ = nullptr;
};
typedef ::grpc_impl::Server Server;
} // namespace grpc

@ -23,6 +23,7 @@
namespace grpc_impl {
class Server;
class ServerCredentials;
class ResourceQuota;
} // namespace grpc_impl

@ -31,6 +31,7 @@
#include <grpcpp/impl/codegen/server_interceptor.h>
#include <grpcpp/impl/server_builder_option.h>
#include <grpcpp/impl/server_builder_plugin.h>
#include <grpcpp/server.h>
#include <grpcpp/support/config.h>
struct grpc_resource_quota;
@ -44,7 +45,6 @@ namespace grpc {
class AsyncGenericService;
class CompletionQueue;
class Server;
class ServerCompletionQueue;
class Service;

@ -28,6 +28,7 @@
#include <grpc/compression.h>
#include <grpc/support/atm.h>
#include <grpcpp/completion_queue.h>
#include <grpcpp/health_check_service_interface.h>
#include <grpcpp/impl/call.h>
#include <grpcpp/impl/codegen/client_interceptor.h>
#include <grpcpp/impl/codegen/grpc_library.h>
@ -49,7 +50,6 @@ class ServerContext;
namespace grpc_impl {
class HealthCheckServiceInterface;
class ServerInitializer;
/// Represents a gRPC server.
@ -99,7 +99,7 @@ class Server : public grpc::ServerInterface, private grpc::GrpcLibraryCodegen {
grpc_server* c_server();
/// Returns the health check service.
grpc_impl::HealthCheckServiceInterface* GetHealthCheckService() const {
grpc::HealthCheckServiceInterface* GetHealthCheckService() const {
return health_check_service_.get();
}
@ -333,7 +333,7 @@ class Server : public grpc::ServerInterface, private grpc::GrpcLibraryCodegen {
std::unique_ptr<grpc_impl::ServerInitializer> server_initializer_;
std::unique_ptr<grpc_impl::HealthCheckServiceInterface> health_check_service_;
std::unique_ptr<grpc::HealthCheckServiceInterface> health_check_service_;
bool health_check_service_disabled_;
// When appropriate, use a default callback generic service to handle

@ -107,6 +107,10 @@
<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" />
<file baseinstalldir="/" name="src/core/lib/gprpp/global_config.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/global_config_custom.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/global_config_env.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/global_config_generic.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/manual_constructor.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/map.h" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/memory.h" role="src" />
@ -149,6 +153,7 @@
<file baseinstalldir="/" name="src/core/lib/gpr/wrap_memcpy.cc" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/arena.cc" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/fork.cc" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/global_config_env.cc" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/thd_posix.cc" role="src" />
<file baseinstalldir="/" name="src/core/lib/gprpp/thd_windows.cc" role="src" />
<file baseinstalldir="/" name="src/core/lib/profiling/basic_timers.cc" role="src" />
@ -472,6 +477,7 @@
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/lb_policy/subchannel_list.h" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.h" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/max_age/max_age_filter.h" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/message_size/message_size_filter.h" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/http/client_authority_filter.h" role="src" />
@ -796,10 +802,13 @@
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.cc" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc" role="src" />
<file baseinstalldir="/" name="src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc" role="src" />

@ -25,8 +25,8 @@
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include "src/core/ext/filters/client_channel/client_channel.h"
#include "src/core/lib/gpr/env.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/timer.h"
@ -56,21 +56,22 @@ static backup_poller* g_poller = nullptr; // guarded by g_poller_mu
// treated as const.
static int g_poll_interval_ms = DEFAULT_POLL_INTERVAL_MS;
GPR_GLOBAL_CONFIG_DEFINE_INT32(grpc_client_channel_backup_poll_interval_ms,
DEFAULT_POLL_INTERVAL_MS,
"Client channel backup poll interval (ms)");
static void init_globals() {
gpr_mu_init(&g_poller_mu);
char* env = gpr_getenv("GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS");
if (env != nullptr) {
int poll_interval_ms = gpr_parse_nonnegative_int(env);
if (poll_interval_ms == -1) {
gpr_log(GPR_ERROR,
"Invalid GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS: %s, "
"default value %d will be used.",
env, g_poll_interval_ms);
} else {
g_poll_interval_ms = poll_interval_ms;
}
int32_t poll_interval_ms =
GPR_GLOBAL_CONFIG_GET(grpc_client_channel_backup_poll_interval_ms);
if (poll_interval_ms < 0) {
gpr_log(GPR_ERROR,
"Invalid GRPC_CLIENT_CHANNEL_BACKUP_POLL_INTERVAL_MS: %d, "
"default value %d will be used.",
poll_interval_ms, g_poll_interval_ms);
} else {
g_poll_interval_ms = poll_interval_ms;
}
gpr_free(env);
}
static void backup_poller_shutdown_unref(backup_poller* p) {

@ -23,6 +23,9 @@
#include <grpc/grpc.h>
#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/gprpp/global_config.h"
GPR_GLOBAL_CONFIG_DECLARE_INT32(grpc_client_channel_backup_poll_interval_ms);
/* Start polling \a interested_parties periodically in the timer thread */
void grpc_client_channel_start_backup_polling(

@ -18,7 +18,7 @@
#include <grpc/support/port_platform.h>
#if GRPC_ARES == 1 && !defined(GRPC_UV)
#if GRPC_ARES == 1
#include <limits.h>
#include <stdio.h>
@ -430,6 +430,13 @@ static grpc_error* blocking_resolve_address_ares(
static grpc_address_resolver_vtable ares_resolver = {
grpc_resolve_address_ares, blocking_resolve_address_ares};
#ifdef GRPC_UV
/* TODO(murgatroid99): Remove this when we want the cares resolver to be the
* default when using libuv */
static bool should_use_ares(const char* resolver_env) {
return resolver_env != nullptr && gpr_stricmp(resolver_env, "ares") == 0;
}
#else /* GRPC_UV */
static bool should_use_ares(const char* resolver_env) {
// TODO(lidiz): Remove the "g_custom_iomgr_enabled" flag once c-ares support
// custom IO managers (e.g. gevent).
@ -437,6 +444,7 @@ static bool should_use_ares(const char* resolver_env) {
(resolver_env == nullptr || strlen(resolver_env) == 0 ||
gpr_stricmp(resolver_env, "ares") == 0);
}
#endif /* GRPC_UV */
void grpc_resolver_dns_ares_init() {
char* resolver_env = gpr_getenv("GRPC_DNS_RESOLVER");
@ -468,10 +476,10 @@ void grpc_resolver_dns_ares_shutdown() {
gpr_free(resolver_env);
}
#else /* GRPC_ARES == 1 && !defined(GRPC_UV) */
#else /* GRPC_ARES == 1 */
void grpc_resolver_dns_ares_init(void) {}
void grpc_resolver_dns_ares_shutdown(void) {}
#endif /* GRPC_ARES == 1 && !defined(GRPC_UV) */
#endif /* GRPC_ARES == 1 */

@ -18,7 +18,7 @@
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/port.h"
#if GRPC_ARES == 1 && !defined(GRPC_UV)
#if GRPC_ARES == 1
#include <ares.h>
#include <string.h>
@ -218,6 +218,7 @@ static void on_timeout_locked(void* arg, grpc_error* error) {
static void on_readable_locked(void* arg, grpc_error* error) {
fd_node* fdn = static_cast<fd_node*>(arg);
GPR_ASSERT(fdn->readable_registered);
grpc_ares_ev_driver* ev_driver = fdn->ev_driver;
const ares_socket_t as = fdn->grpc_polled_fd->GetWrappedAresSocketLocked();
fdn->readable_registered = false;
@ -242,6 +243,7 @@ static void on_readable_locked(void* arg, grpc_error* error) {
static void on_writable_locked(void* arg, grpc_error* error) {
fd_node* fdn = static_cast<fd_node*>(arg);
GPR_ASSERT(fdn->writable_registered);
grpc_ares_ev_driver* ev_driver = fdn->ev_driver;
const ares_socket_t as = fdn->grpc_polled_fd->GetWrappedAresSocketLocked();
fdn->writable_registered = false;
@ -365,4 +367,4 @@ void grpc_ares_ev_driver_start_locked(grpc_ares_ev_driver* ev_driver) {
}
}
#endif /* GRPC_ARES == 1 && !defined(GRPC_UV) */
#endif /* GRPC_ARES == 1 */

@ -0,0 +1,179 @@
/*
*
* 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.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/port.h"
#if GRPC_ARES == 1 && defined(GRPC_UV)
#include <ares.h>
#include <uv.h>
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/iomgr/combiner.h"
namespace grpc_core {
void ares_uv_poll_cb(uv_poll_t* handle, int status, int events);
void ares_uv_poll_close_cb(uv_handle_t* handle) { Delete(handle); }
class GrpcPolledFdLibuv : public GrpcPolledFd {
public:
GrpcPolledFdLibuv(ares_socket_t as, grpc_combiner* combiner)
: as_(as), combiner_(combiner) {
gpr_asprintf(&name_, "c-ares socket: %" PRIdPTR, (intptr_t)as);
handle_ = New<uv_poll_t>();
uv_poll_init_socket(uv_default_loop(), handle_, as);
handle_->data = this;
GRPC_COMBINER_REF(combiner_, "libuv ares event driver");
}
~GrpcPolledFdLibuv() {
gpr_free(name_);
GRPC_COMBINER_UNREF(combiner_, "libuv ares event driver");
}
void RegisterForOnReadableLocked(grpc_closure* read_closure) override {
GPR_ASSERT(read_closure_ == nullptr);
GPR_ASSERT((poll_events_ & UV_READABLE) == 0);
read_closure_ = read_closure;
poll_events_ |= UV_READABLE;
uv_poll_start(handle_, poll_events_, ares_uv_poll_cb);
}
void RegisterForOnWriteableLocked(grpc_closure* write_closure) override {
GPR_ASSERT(write_closure_ == nullptr);
GPR_ASSERT((poll_events_ & UV_WRITABLE) == 0);
write_closure_ = write_closure;
poll_events_ |= UV_WRITABLE;
uv_poll_start(handle_, poll_events_, ares_uv_poll_cb);
}
bool IsFdStillReadableLocked() override {
/* uv_poll_t is based on poll, which is level triggered. So, if cares
* leaves some data unread, the event will trigger again. */
return false;
}
void ShutdownInternalLocked(grpc_error* error) {
uv_poll_stop(handle_);
uv_close(reinterpret_cast<uv_handle_t*>(handle_), ares_uv_poll_close_cb);
if (read_closure_ != nullptr) {
GRPC_CLOSURE_SCHED(read_closure_, GRPC_ERROR_CANCELLED);
}
if (write_closure_ != nullptr) {
GRPC_CLOSURE_SCHED(write_closure_, GRPC_ERROR_CANCELLED);
}
}
void ShutdownLocked(grpc_error* error) override {
if (grpc_core::ExecCtx::Get() == nullptr) {
grpc_core::ExecCtx exec_ctx;
ShutdownInternalLocked(error);
} else {
ShutdownInternalLocked(error);
}
}
ares_socket_t GetWrappedAresSocketLocked() override { return as_; }
const char* GetName() override { return name_; }
char* name_;
ares_socket_t as_;
uv_poll_t* handle_;
grpc_closure* read_closure_ = nullptr;
grpc_closure* write_closure_ = nullptr;
int poll_events_ = 0;
grpc_combiner* combiner_;
};
struct AresUvPollCbArg {
AresUvPollCbArg(uv_poll_t* handle, int status, int events)
: handle(handle), status(status), events(events) {}
uv_poll_t* handle;
int status;
int events;
};
static void ares_uv_poll_cb_locked(void* arg, grpc_error* error) {
grpc_core::UniquePtr<AresUvPollCbArg> arg_struct(
reinterpret_cast<AresUvPollCbArg*>(arg));
uv_poll_t* handle = arg_struct->handle;
int status = arg_struct->status;
int events = arg_struct->events;
GrpcPolledFdLibuv* polled_fd =
reinterpret_cast<GrpcPolledFdLibuv*>(handle->data);
if (status < 0) {
error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("cares polling error");
error =
grpc_error_set_str(error, GRPC_ERROR_STR_OS_ERROR,
grpc_slice_from_static_string(uv_strerror(status)));
}
if (events & UV_READABLE) {
GPR_ASSERT(polled_fd->read_closure_ != nullptr);
GRPC_CLOSURE_SCHED(polled_fd->read_closure_, error);
polled_fd->read_closure_ = nullptr;
polled_fd->poll_events_ &= ~UV_READABLE;
}
if (events & UV_WRITABLE) {
GPR_ASSERT(polled_fd->write_closure_ != nullptr);
GRPC_CLOSURE_SCHED(polled_fd->write_closure_, error);
polled_fd->write_closure_ = nullptr;
polled_fd->poll_events_ &= ~UV_WRITABLE;
}
uv_poll_start(handle, polled_fd->poll_events_, ares_uv_poll_cb);
}
void ares_uv_poll_cb(uv_poll_t* handle, int status, int events) {
grpc_core::ExecCtx exec_ctx;
GrpcPolledFdLibuv* polled_fd =
reinterpret_cast<GrpcPolledFdLibuv*>(handle->data);
AresUvPollCbArg* arg = New<AresUvPollCbArg>(handle, status, events);
GRPC_CLOSURE_SCHED(
GRPC_CLOSURE_CREATE(ares_uv_poll_cb_locked, arg,
grpc_combiner_scheduler(polled_fd->combiner_)),
GRPC_ERROR_NONE);
}
class GrpcPolledFdFactoryLibuv : public GrpcPolledFdFactory {
public:
GrpcPolledFd* NewGrpcPolledFdLocked(ares_socket_t as,
grpc_pollset_set* driver_pollset_set,
grpc_combiner* combiner) override {
return New<GrpcPolledFdLibuv>(as, combiner);
}
void ConfigureAresChannelLocked(ares_channel channel) override {}
};
UniquePtr<GrpcPolledFdFactory> NewGrpcPolledFdFactory(grpc_combiner* combiner) {
return UniquePtr<GrpcPolledFdFactory>(New<GrpcPolledFdFactoryLibuv>());
}
} // namespace grpc_core
#endif /* GRPC_ARES == 1 && defined(GRPC_UV) */

@ -18,7 +18,7 @@
#include <grpc/support/port_platform.h>
#if GRPC_ARES == 1 && !defined(GRPC_UV)
#if GRPC_ARES == 1
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
#include "src/core/lib/iomgr/sockaddr.h"
@ -687,4 +687,4 @@ void (*grpc_resolve_address_ares)(
grpc_pollset_set* interested_parties, grpc_closure* on_done,
grpc_resolved_addresses** addrs) = grpc_resolve_address_ares_impl;
#endif /* GRPC_ARES == 1 && !defined(GRPC_UV) */
#endif /* GRPC_ARES == 1 */

@ -18,7 +18,7 @@
#include <grpc/support/port_platform.h>
#if GRPC_ARES != 1 || defined(GRPC_UV)
#if GRPC_ARES != 1
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
@ -62,4 +62,4 @@ void (*grpc_resolve_address_ares)(
grpc_pollset_set* interested_parties, grpc_closure* on_done,
grpc_resolved_addresses** addrs) = grpc_resolve_address_ares_impl;
#endif /* GRPC_ARES != 1 || defined(GRPC_UV) */
#endif /* GRPC_ARES != 1 */

@ -0,0 +1,52 @@
/*
*
* Copyright 2016 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/port.h"
#if GRPC_ARES == 1 && defined(GRPC_UV)
#include <grpc/support/string_util.h>
#include "src/core/ext/filters/client_channel/parse_address.h"
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.h"
#include "src/core/ext/filters/client_channel/server_address.h"
#include "src/core/lib/gpr/host_port.h"
#include "src/core/lib/gpr/string.h"
bool grpc_ares_query_ipv6() {
/* The libuv grpc code currently does not have the code to probe for this,
* so we assume for now that IPv6 is always available in contexts where this
* code will be used. */
return true;
}
bool grpc_ares_maybe_resolve_localhost_manually_locked(
const char* name, const char* default_port,
grpc_core::UniquePtr<grpc_core::ServerAddressList>* addrs) {
char* host = nullptr;
char* port = nullptr;
bool out = inner_maybe_resolve_localhost_manually_locked(name, default_port,
addrs, &host, &port);
gpr_free(host);
gpr_free(port);
return out;
}
#endif /* GRPC_ARES == 1 && defined(GRPC_UV) */

@ -0,0 +1,83 @@
/*
*
* 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.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/port.h"
#if GRPC_ARES == 1 && (defined(GRPC_UV) || defined(GPR_WINDOWS))
#include <grpc/support/string_util.h>
#include "src/core/ext/filters/client_channel/parse_address.h"
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.h"
#include "src/core/ext/filters/client_channel/server_address.h"
#include "src/core/lib/gpr/host_port.h"
#include "src/core/lib/gpr/string.h"
bool inner_maybe_resolve_localhost_manually_locked(
const char* name, const char* default_port,
grpc_core::UniquePtr<grpc_core::ServerAddressList>* addrs, char** host,
char** port) {
gpr_split_host_port(name, host, port);
if (*host == nullptr) {
gpr_log(GPR_ERROR,
"Failed to parse %s into host:port during manual localhost "
"resolution check.",
name);
return false;
}
if (*port == nullptr) {
if (default_port == nullptr) {
gpr_log(GPR_ERROR,
"No port or default port for %s during manual localhost "
"resolution check.",
name);
return false;
}
*port = gpr_strdup(default_port);
}
if (gpr_stricmp(*host, "localhost") == 0) {
GPR_ASSERT(*addrs == nullptr);
*addrs = grpc_core::MakeUnique<grpc_core::ServerAddressList>();
uint16_t numeric_port = grpc_strhtons(*port);
// Append the ipv6 loopback address.
struct sockaddr_in6 ipv6_loopback_addr;
memset(&ipv6_loopback_addr, 0, sizeof(ipv6_loopback_addr));
((char*)&ipv6_loopback_addr.sin6_addr)[15] = 1;
ipv6_loopback_addr.sin6_family = AF_INET6;
ipv6_loopback_addr.sin6_port = numeric_port;
(*addrs)->emplace_back(&ipv6_loopback_addr, sizeof(ipv6_loopback_addr),
nullptr /* args */);
// Append the ipv4 loopback address.
struct sockaddr_in ipv4_loopback_addr;
memset(&ipv4_loopback_addr, 0, sizeof(ipv4_loopback_addr));
((char*)&ipv4_loopback_addr.sin_addr)[0] = 0x7f;
((char*)&ipv4_loopback_addr.sin_addr)[3] = 0x01;
ipv4_loopback_addr.sin_family = AF_INET;
ipv4_loopback_addr.sin_port = numeric_port;
(*addrs)->emplace_back(&ipv4_loopback_addr, sizeof(ipv4_loopback_addr),
nullptr /* args */);
// Let the address sorter figure out which one should be tried first.
grpc_cares_wrapper_address_sorting_sort(addrs->get());
return true;
}
return false;
}
#endif /* GRPC_ARES == 1 && (defined(GRPC_UV) || defined(GPR_WINDOWS)) */

@ -0,0 +1,34 @@
/*
*
* 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.
*
*/
#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_WRAPPER_LIBUV_WINDOWS_H
#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_WRAPPER_LIBUV_WINDOWS_H
#include <grpc/support/port_platform.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
bool inner_maybe_resolve_localhost_manually_locked(
const char* name, const char* default_port,
grpc_core::UniquePtr<grpc_core::ServerAddressList>* addrs, char** host,
char** port);
#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_WRAPPER_LIBUV_WINDOWS_H \
*/

@ -25,6 +25,7 @@
#include "src/core/ext/filters/client_channel/parse_address.h"
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h"
#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.h"
#include "src/core/ext/filters/client_channel/server_address.h"
#include "src/core/lib/gpr/host_port.h"
#include "src/core/lib/gpr/string.h"
@ -32,56 +33,6 @@
bool grpc_ares_query_ipv6() { return grpc_ipv6_loopback_available(); }
static bool inner_maybe_resolve_localhost_manually_locked(
const char* name, const char* default_port,
grpc_core::UniquePtr<grpc_core::ServerAddressList>* addrs, char** host,
char** port) {
gpr_split_host_port(name, host, port);
if (*host == nullptr) {
gpr_log(GPR_ERROR,
"Failed to parse %s into host:port during Windows localhost "
"resolution check.",
name);
return false;
}
if (*port == nullptr) {
if (default_port == nullptr) {
gpr_log(GPR_ERROR,
"No port or default port for %s during Windows localhost "
"resolution check.",
name);
return false;
}
*port = gpr_strdup(default_port);
}
if (gpr_stricmp(*host, "localhost") == 0) {
GPR_ASSERT(*addrs == nullptr);
*addrs = grpc_core::MakeUnique<grpc_core::ServerAddressList>();
uint16_t numeric_port = grpc_strhtons(*port);
// Append the ipv6 loopback address.
struct sockaddr_in6 ipv6_loopback_addr;
memset(&ipv6_loopback_addr, 0, sizeof(ipv6_loopback_addr));
((char*)&ipv6_loopback_addr.sin6_addr)[15] = 1;
ipv6_loopback_addr.sin6_family = AF_INET6;
ipv6_loopback_addr.sin6_port = numeric_port;
(*addrs)->emplace_back(&ipv6_loopback_addr, sizeof(ipv6_loopback_addr),
nullptr /* args */);
// Append the ipv4 loopback address.
struct sockaddr_in ipv4_loopback_addr;
memset(&ipv4_loopback_addr, 0, sizeof(ipv4_loopback_addr));
((char*)&ipv4_loopback_addr.sin_addr)[0] = 0x7f;
((char*)&ipv4_loopback_addr.sin_addr)[3] = 0x01;
ipv4_loopback_addr.sin_family = AF_INET;
ipv4_loopback_addr.sin_port = numeric_port;
(*addrs)->emplace_back(&ipv4_loopback_addr, sizeof(ipv4_loopback_addr),
nullptr /* args */);
// Let the address sorter figure out which one should be tried first.
grpc_cares_wrapper_address_sorting_sort(addrs->get());
return true;
}
return false;
}
bool grpc_ares_maybe_resolve_localhost_manually_locked(
const char* name, const char* default_port,
grpc_core::UniquePtr<grpc_core::ServerAddressList>* addrs) {

@ -66,12 +66,13 @@
#define GRPC_SUBCHANNEL_RECONNECT_JITTER 0.2
// Conversion between subchannel call and call stack.
#define SUBCHANNEL_CALL_TO_CALL_STACK(call) \
(grpc_call_stack*)((char*)(call) + \
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall)))
#define CALL_STACK_TO_SUBCHANNEL_CALL(callstack) \
(SubchannelCall*)(((char*)(call_stack)) - \
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall)))
#define SUBCHANNEL_CALL_TO_CALL_STACK(call) \
(grpc_call_stack*)((char*)(call) + GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE( \
sizeof(SubchannelCall)))
#define CALL_STACK_TO_SUBCHANNEL_CALL(callstack) \
(SubchannelCall*)(((char*)(call_stack)) - \
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE( \
sizeof(SubchannelCall)))
namespace grpc_core {
@ -151,10 +152,10 @@ RefCountedPtr<SubchannelCall> ConnectedSubchannel::CreateCall(
size_t ConnectedSubchannel::GetInitialCallSizeEstimate(
size_t parent_data_size) const {
size_t allocation_size =
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall));
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(sizeof(SubchannelCall));
if (parent_data_size > 0) {
allocation_size +=
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(channel_stack_->call_stack_size) +
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(channel_stack_->call_stack_size) +
parent_data_size;
} else {
allocation_size += channel_stack_->call_stack_size;
@ -178,8 +179,9 @@ void SubchannelCall::StartTransportStreamOpBatch(
void* SubchannelCall::GetParentData() {
grpc_channel_stack* chanstk = connected_subchannel_->channel_stack();
return (char*)this + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall)) +
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(chanstk->call_stack_size);
return (char*)this +
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(sizeof(SubchannelCall)) +
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(chanstk->call_stack_size);
}
grpc_call_stack* SubchannelCall::GetCallStack() {

@ -20,16 +20,15 @@
#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gpr/env.h"
#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/transport/metadata.h"
GPR_GLOBAL_CONFIG_DEFINE_BOOL(grpc_experimental_disable_flow_control, false,
"Disable flow control");
void grpc_chttp2_plugin_init(void) {
g_flow_control_enabled = true;
char* env_variable = gpr_getenv("GRPC_EXPERIMENTAL_DISABLE_FLOW_CONTROL");
if (env_variable != nullptr) {
g_flow_control_enabled = false;
gpr_free(env_variable);
}
g_flow_control_enabled =
!GPR_GLOBAL_CONFIG_GET(grpc_experimental_disable_flow_control);
}
void grpc_chttp2_plugin_shutdown(void) {}

@ -47,9 +47,9 @@ grpc_core::TraceFlag grpc_trace_channel(false, "channel");
size_t grpc_channel_stack_size(const grpc_channel_filter** filters,
size_t filter_count) {
/* always need the header, and size for the channel elements */
size_t size = GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_channel_stack)) +
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filter_count *
sizeof(grpc_channel_element));
size_t size = GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(sizeof(grpc_channel_stack)) +
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(
filter_count * sizeof(grpc_channel_element));
size_t i;
GPR_ASSERT((GPR_MAX_ALIGNMENT & (GPR_MAX_ALIGNMENT - 1)) == 0 &&
@ -57,18 +57,18 @@ size_t grpc_channel_stack_size(const grpc_channel_filter** filters,
/* add the size for each filter */
for (i = 0; i < filter_count; i++) {
size += GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filters[i]->sizeof_channel_data);
size += GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(filters[i]->sizeof_channel_data);
}
return size;
}
#define CHANNEL_ELEMS_FROM_STACK(stk) \
((grpc_channel_element*)((char*)(stk) + GPR_ROUND_UP_TO_ALIGNMENT_SIZE( \
#define CHANNEL_ELEMS_FROM_STACK(stk) \
((grpc_channel_element*)((char*)(stk) + GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE( \
sizeof(grpc_channel_stack))))
#define CALL_ELEMS_FROM_STACK(stk) \
((grpc_call_element*)((char*)(stk) + GPR_ROUND_UP_TO_ALIGNMENT_SIZE( \
#define CALL_ELEMS_FROM_STACK(stk) \
((grpc_call_element*)((char*)(stk) + GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE( \
sizeof(grpc_call_stack))))
grpc_channel_element* grpc_channel_stack_element(
@ -92,8 +92,9 @@ grpc_error* grpc_channel_stack_init(
const grpc_channel_args* channel_args, grpc_transport* optional_transport,
const char* name, grpc_channel_stack* stack) {
size_t call_size =
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call_stack)) +
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filter_count * sizeof(grpc_call_element));
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(sizeof(grpc_call_stack)) +
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(filter_count *
sizeof(grpc_call_element));
grpc_channel_element* elems;
grpc_channel_element_args args;
char* user_data;
@ -104,8 +105,8 @@ grpc_error* grpc_channel_stack_init(
name);
elems = CHANNEL_ELEMS_FROM_STACK(stack);
user_data = (reinterpret_cast<char*>(elems)) +
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filter_count *
sizeof(grpc_channel_element));
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(filter_count *
sizeof(grpc_channel_element));
/* init per-filter data */
grpc_error* first_error = GRPC_ERROR_NONE;
@ -126,8 +127,9 @@ grpc_error* grpc_channel_stack_init(
}
}
user_data +=
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filters[i]->sizeof_channel_data);
call_size += GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filters[i]->sizeof_call_data);
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(filters[i]->sizeof_channel_data);
call_size +=
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(filters[i]->sizeof_call_data);
}
GPR_ASSERT(user_data > (char*)stack);
@ -162,8 +164,9 @@ grpc_error* grpc_call_stack_init(grpc_channel_stack* channel_stack,
GRPC_STREAM_REF_INIT(&elem_args->call_stack->refcount, initial_refs, destroy,
destroy_arg, "CALL_STACK");
call_elems = CALL_ELEMS_FROM_STACK(elem_args->call_stack);
user_data = (reinterpret_cast<char*>(call_elems)) +
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(count * sizeof(grpc_call_element));
user_data =
(reinterpret_cast<char*>(call_elems)) +
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(count * sizeof(grpc_call_element));
/* init per-filter data */
grpc_error* first_error = GRPC_ERROR_NONE;
@ -171,8 +174,8 @@ grpc_error* grpc_call_stack_init(grpc_channel_stack* channel_stack,
call_elems[i].filter = channel_elems[i].filter;
call_elems[i].channel_data = channel_elems[i].channel_data;
call_elems[i].call_data = user_data;
user_data +=
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(call_elems[i].filter->sizeof_call_data);
user_data += GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(
call_elems[i].filter->sizeof_call_data);
}
for (size_t i = 0; i < count; i++) {
grpc_error* error =
@ -242,11 +245,11 @@ grpc_channel_stack* grpc_channel_stack_from_top_element(
grpc_channel_element* elem) {
return reinterpret_cast<grpc_channel_stack*>(
reinterpret_cast<char*>(elem) -
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_channel_stack)));
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(sizeof(grpc_channel_stack)));
}
grpc_call_stack* grpc_call_stack_from_top_element(grpc_call_element* elem) {
return reinterpret_cast<grpc_call_stack*>(
reinterpret_cast<char*>(elem) -
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call_stack)));
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(sizeof(grpc_call_stack)));
}

@ -23,6 +23,7 @@
#include <grpc/support/log.h>
#include <stdlib.h>
#include <string.h>
#include "src/core/lib/gpr/alloc.h"
#include "src/core/lib/profiling/timers.h"
static void* zalloc_with_calloc(size_t sz) { return calloc(sz, 1); }
@ -33,8 +34,56 @@ static void* zalloc_with_gpr_malloc(size_t sz) {
return p;
}
static gpr_allocation_functions g_alloc_functions = {malloc, zalloc_with_calloc,
realloc, free};
#ifndef NDEBUG
static constexpr bool is_power_of_two(size_t value) {
// 2^N = 100000...000
// 2^N - 1 = 011111...111
// (2^N) && ((2^N)-1)) = 0
return (value & (value - 1)) == 0;
}
#endif
static void* platform_malloc_aligned(size_t size, size_t alignment) {
#if defined(GPR_HAS_ALIGNED_ALLOC)
GPR_DEBUG_ASSERT(is_power_of_two(alignment));
size = GPR_ROUND_UP_TO_ALIGNMENT_SIZE(size, alignment);
void* ret = aligned_alloc(alignment, size);
GPR_ASSERT(ret != nullptr);
return ret;
#elif defined(GPR_HAS_ALIGNED_MALLOC)
GPR_DEBUG_ASSERT(is_power_of_two(alignment));
void* ret = _aligned_malloc(size, alignment);
GPR_ASSERT(ret != nullptr);
return ret;
#elif defined(GPR_HAS_POSIX_MEMALIGN)
GPR_DEBUG_ASSERT(is_power_of_two(alignment));
GPR_DEBUG_ASSERT(alignment % sizeof(void*) == 0);
void* ret = nullptr;
GPR_ASSERT(posix_memalign(&ret, alignment, size) == 0);
return ret;
#else
GPR_DEBUG_ASSERT(is_power_of_two(alignment));
size_t extra = alignment - 1 + sizeof(void*);
void* p = gpr_malloc(size + extra);
void** ret = (void**)(((uintptr_t)p + extra) & ~(alignment - 1));
ret[-1] = p;
return (void*)ret;
#endif
}
static void platform_free_aligned(void* ptr) {
#if defined(GPR_HAS_ALIGNED_ALLOC) || defined(GPR_HAS_POSIX_MEMALIGN)
free(ptr);
#elif defined(GPR_HAS_ALIGNED_MALLOC)
_aligned_free(ptr);
#else
gpr_free((static_cast<void**>(ptr))[-1]);
#endif
}
static gpr_allocation_functions g_alloc_functions = {
malloc, zalloc_with_calloc, realloc,
free, platform_malloc_aligned, platform_free_aligned};
gpr_allocation_functions gpr_get_allocation_functions() {
return g_alloc_functions;
@ -47,6 +96,12 @@ void gpr_set_allocation_functions(gpr_allocation_functions functions) {
if (functions.zalloc_fn == nullptr) {
functions.zalloc_fn = zalloc_with_gpr_malloc;
}
GPR_ASSERT((functions.aligned_alloc_fn == nullptr) ==
(functions.aligned_free_fn == nullptr));
if (functions.aligned_alloc_fn == nullptr) {
functions.aligned_alloc_fn = platform_malloc_aligned;
functions.aligned_free_fn = platform_free_aligned;
}
g_alloc_functions = functions;
}
@ -88,12 +143,12 @@ void* gpr_realloc(void* p, size_t size) {
}
void* gpr_malloc_aligned(size_t size, size_t alignment) {
GPR_ASSERT(((alignment - 1) & alignment) == 0); // Must be power of 2.
size_t extra = alignment - 1 + sizeof(void*);
void* p = gpr_malloc(size + extra);
void** ret = (void**)(((uintptr_t)p + extra) & ~(alignment - 1));
ret[-1] = p;
return (void*)ret;
GPR_TIMER_SCOPE("gpr_malloc_aligned", 0);
if (size == 0) return nullptr;
return g_alloc_functions.aligned_alloc_fn(size, alignment);
}
void gpr_free_aligned(void* ptr) { gpr_free((static_cast<void**>(ptr))[-1]); }
void gpr_free_aligned(void* ptr) {
GPR_TIMER_SCOPE("gpr_free_aligned", 0);
g_alloc_functions.aligned_free_fn(ptr);
}

@ -22,7 +22,13 @@
#include <grpc/support/port_platform.h>
/// Given a size, round up to the next multiple of sizeof(void*).
#define GPR_ROUND_UP_TO_ALIGNMENT_SIZE(x) \
(((x) + GPR_MAX_ALIGNMENT - 1u) & ~(GPR_MAX_ALIGNMENT - 1u))
#define GPR_ROUND_UP_TO_ALIGNMENT_SIZE(x, align) \
(((x) + (align)-1u) & ~((align)-1u))
#define GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(x) \
GPR_ROUND_UP_TO_ALIGNMENT_SIZE((x), GPR_MAX_ALIGNMENT)
#define GPR_ROUND_UP_TO_CACHELINE_SIZE(x) \
GPR_ROUND_UP_TO_ALIGNMENT_SIZE((x), GPR_CACHELINE_SIZE)
#endif /* GRPC_CORE_LIB_GPR_ALLOC_H */

@ -40,4 +40,7 @@ void gpr_setenv(const char* name, const char* value);
level of logging. So DO NOT USE THIS. */
const char* gpr_getenv_silent(const char* name, char** dst);
/* Deletes the variable name from the environment. */
void gpr_unsetenv(const char* name);
#endif /* GRPC_CORE_LIB_GPR_ENV_H */

@ -79,4 +79,9 @@ void gpr_setenv(const char* name, const char* value) {
GPR_ASSERT(res == 0);
}
void gpr_unsetenv(const char* name) {
int res = unsetenv(name);
GPR_ASSERT(res == 0);
}
#endif /* GPR_LINUX_ENV */

@ -44,4 +44,9 @@ void gpr_setenv(const char* name, const char* value) {
GPR_ASSERT(res == 0);
}
void gpr_unsetenv(const char* name) {
int res = unsetenv(name);
GPR_ASSERT(res == 0);
}
#endif /* GPR_POSIX_ENV */

@ -69,4 +69,11 @@ void gpr_setenv(const char* name, const char* value) {
GPR_ASSERT(res);
}
void gpr_unsetenv(const char* name) {
LPTSTR tname = gpr_char_to_tchar(name);
BOOL res = SetEnvironmentVariable(tname, NULL);
gpr_free(tname);
GPR_ASSERT(res);
}
#endif /* GPR_WINDOWS_ENV */

@ -332,16 +332,22 @@ void* gpr_memrchr(const void* s, int c, size_t n) {
return nullptr;
}
bool gpr_is_true(const char* s) {
size_t i;
bool gpr_parse_bool_value(const char* s, bool* dst) {
const char* kTrue[] = {"1", "t", "true", "y", "yes"};
const char* kFalse[] = {"0", "f", "false", "n", "no"};
static_assert(sizeof(kTrue) == sizeof(kFalse), "true_false_equal");
if (s == nullptr) {
return false;
}
static const char* truthy[] = {"yes", "true", "1"};
for (i = 0; i < GPR_ARRAY_SIZE(truthy); i++) {
if (0 == gpr_stricmp(s, truthy[i])) {
for (size_t i = 0; i < GPR_ARRAY_SIZE(kTrue); ++i) {
if (gpr_stricmp(s, kTrue[i]) == 0) {
*dst = true;
return true;
} else if (gpr_stricmp(s, kFalse[i]) == 0) {
*dst = false;
return true;
}
}
return false;
return false; // didn't match a legal input
}

@ -113,7 +113,9 @@ int gpr_stricmp(const char* a, const char* b);
void* gpr_memrchr(const void* s, int c, size_t n);
/** Return true if lower(s) equals "true", "yes" or "1", otherwise false. */
bool gpr_is_true(const char* s);
/* Try to parse given string into a boolean value.
When parsed successfully, dst will have the value and returns true.
Otherwise, it returns false. */
bool gpr_parse_bool_value(const char* value, bool* dst);
#endif /* GRPC_CORE_LIB_GPR_STRING_H */

@ -35,8 +35,8 @@ namespace {
void* ArenaStorage(size_t initial_size) {
static constexpr size_t base_size =
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_core::Arena));
initial_size = GPR_ROUND_UP_TO_ALIGNMENT_SIZE(initial_size);
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(sizeof(grpc_core::Arena));
initial_size = GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(initial_size);
size_t alloc_size = base_size + initial_size;
static constexpr size_t alignment =
(GPR_CACHELINE_SIZE > GPR_MAX_ALIGNMENT &&
@ -67,7 +67,7 @@ Arena* Arena::Create(size_t initial_size) {
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));
GPR_ROUND_UP_TO_MAX_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;
@ -88,7 +88,7 @@ void* Arena::AllocZone(size_t size) {
// sizing hysteresis (that is, most calls should have a large enough initial
// zone and will not need to grow the arena).
static constexpr size_t zone_base_size =
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(Zone));
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(sizeof(Zone));
size_t alloc_size = zone_base_size + size;
Zone* z = new (gpr_malloc_aligned(alloc_size, GPR_MAX_ALIGNMENT)) Zone();
{

@ -58,10 +58,10 @@ class Arena {
// Allocate \a size bytes from the arena.
void* Alloc(size_t size) {
static constexpr size_t base_size =
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(Arena));
size = GPR_ROUND_UP_TO_ALIGNMENT_SIZE(size);
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(sizeof(Arena));
size = GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(size);
size_t begin = total_used_.FetchAdd(size, MemoryOrder::RELAXED);
if (begin + size <= initial_zone_size_) {
if (GPR_LIKELY(begin + size <= initial_zone_size_)) {
return reinterpret_cast<char*>(this) + base_size + begin;
} else {
return AllocZone(size);

@ -0,0 +1,87 @@
/*
*
* 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.
*
*/
#ifndef GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_H
#define GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_H
#include <grpc/support/port_platform.h>
#include <stdint.h>
// --------------------------------------------------------------------
// How to use global configuration variables:
//
// Defining config variables of a specified type:
// GPR_GLOBAL_CONFIG_DEFINE_*TYPE*(name, default_value, help);
//
// Supported TYPEs: BOOL, INT32, STRING
//
// It's recommended to use lowercase letters for 'name' like
// regular variables. The builtin configuration system uses
// environment variable and the name is converted to uppercase
// when looking up the value. For example,
// GPR_GLOBAL_CONFIG_DEFINE(grpc_latency) looks up the value with the
// name, "GRPC_LATENCY".
//
// The variable initially has the specified 'default_value'
// which must be an expression convertible to 'Type'.
// 'default_value' may be evaluated 0 or more times,
// and at an unspecified time; keep it
// simple and usually free of side-effects.
//
// GPR_GLOBAL_CONFIG_DEFINE_*TYPE* should not be called in a C++ header.
// It should be called at the top-level (outside any namespaces)
// in a .cc file.
//
// Getting the variables:
// GPR_GLOBAL_CONFIG_GET(name)
//
// If error happens during getting variables, error messages will
// be logged and default value will be returned.
//
// Setting the variables with new value:
// GPR_GLOBAL_CONFIG_SET(name, new_value)
//
// Declaring config variables for other modules to access:
// GPR_GLOBAL_CONFIG_DECLARE_*TYPE*(name)
// --------------------------------------------------------------------
// How to customize the global configuration system:
//
// How to read and write configuration value can be customized.
// Builtin system uses environment variables but it can be extended to
// support command-line flag, file, etc.
//
// To customize it, following macros should be redefined.
//
// GPR_GLOBAL_CONFIG_DEFINE_BOOL
// GPR_GLOBAL_CONFIG_DEFINE_INT32
// GPR_GLOBAL_CONFIG_DEFINE_STRING
//
// These macros should define functions for getting and setting variable.
// For example, GPR_GLOBAL_CONFIG_DEFINE_BOOL(test, ...) would define two
// functions.
//
// bool gpr_global_config_get_test();
// void gpr_global_config_set_test(bool value);
#include "src/core/lib/gprpp/global_config_env.h"
#include "src/core/lib/gprpp/global_config_custom.h"
#endif /* GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_H */

@ -0,0 +1,29 @@
/*
*
* 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.
*
*/
#ifndef GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_CUSTOM_H
#define GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_CUSTOM_H
// This is a placeholder for custom global configuration implementaion.
// To use the custom one, please define following macros here.
//
// GPR_GLOBAL_CONFIG_DEFINE_BOOL
// GPR_GLOBAL_CONFIG_DEFINE_INT32
// GPR_GLOBAL_CONFIG_DEFINE_STRING
#endif /* GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_CUSTOM_H */

@ -0,0 +1,135 @@
/*
*
* 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.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/lib/gprpp/global_config_env.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/gpr/env.h"
#include "src/core/lib/gpr/string.h"
#include <ctype.h>
#include <string.h>
namespace grpc_core {
namespace {
void DefaultGlobalConfigEnvErrorFunction(const char* error_message) {
gpr_log(GPR_ERROR, "%s", error_message);
}
GlobalConfigEnvErrorFunctionType g_global_config_env_error_func =
DefaultGlobalConfigEnvErrorFunction;
void LogParsingError(const char* name, const char* value) {
char* error_message;
gpr_asprintf(&error_message,
"Illegal value '%s' specified for environment variable '%s'",
value, name);
(*g_global_config_env_error_func)(error_message);
gpr_free(error_message);
}
} // namespace
void SetGlobalConfigEnvErrorFunction(GlobalConfigEnvErrorFunctionType func) {
g_global_config_env_error_func = func;
}
UniquePtr<char> GlobalConfigEnv::GetValue() {
return UniquePtr<char>(gpr_getenv(GetName()));
}
void GlobalConfigEnv::SetValue(const char* value) {
gpr_setenv(GetName(), value);
}
void GlobalConfigEnv::Unset() { gpr_unsetenv(GetName()); }
char* GlobalConfigEnv::GetName() {
// This makes sure that name_ is in a canonical form having uppercase
// letters. This is okay to be called serveral times.
for (char* c = name_; *c != 0; ++c) {
*c = toupper(*c);
}
return name_;
}
static_assert(std::is_trivially_destructible<GlobalConfigEnvBool>::value,
"GlobalConfigEnvBool needs to be trivially destructible.");
bool GlobalConfigEnvBool::Get() {
UniquePtr<char> str = GetValue();
if (str == nullptr) {
return default_value_;
}
// parsing given value string.
bool result = false;
if (!gpr_parse_bool_value(str.get(), &result)) {
LogParsingError(GetName(), str.get());
result = default_value_;
}
return result;
}
void GlobalConfigEnvBool::Set(bool value) {
SetValue(value ? "true" : "false");
}
static_assert(std::is_trivially_destructible<GlobalConfigEnvInt32>::value,
"GlobalConfigEnvInt32 needs to be trivially destructible.");
int32_t GlobalConfigEnvInt32::Get() {
UniquePtr<char> str = GetValue();
if (str == nullptr) {
return default_value_;
}
// parsing given value string.
char* end = str.get();
long result = strtol(str.get(), &end, 10);
if (*end != 0) {
LogParsingError(GetName(), str.get());
result = default_value_;
}
return static_cast<int32_t>(result);
}
void GlobalConfigEnvInt32::Set(int32_t value) {
char buffer[GPR_LTOA_MIN_BUFSIZE];
gpr_ltoa(value, buffer);
SetValue(buffer);
}
static_assert(std::is_trivially_destructible<GlobalConfigEnvString>::value,
"GlobalConfigEnvString needs to be trivially destructible.");
UniquePtr<char> GlobalConfigEnvString::Get() {
UniquePtr<char> str = GetValue();
if (str == nullptr) {
return UniquePtr<char>(gpr_strdup(default_value_));
}
return str;
}
void GlobalConfigEnvString::Set(const char* value) { SetValue(value); }
} // namespace grpc_core

@ -0,0 +1,131 @@
/*
*
* 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.
*
*/
#ifndef GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_ENV_H
#define GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_ENV_H
#include <grpc/support/port_platform.h>
#include "src/core/lib/gprpp/global_config_generic.h"
#include "src/core/lib/gprpp/memory.h"
namespace grpc_core {
typedef void (*GlobalConfigEnvErrorFunctionType)(const char* error_message);
/*
* Set global_config_env_error_function which is called when config system
* encounters errors such as parsing error. What the default function does
* is logging error message.
*/
void SetGlobalConfigEnvErrorFunction(GlobalConfigEnvErrorFunctionType func);
// Base class for all classes to access environment variables.
class GlobalConfigEnv {
protected:
// `name` should be writable and alive after constructor is called.
constexpr explicit GlobalConfigEnv(char* name) : name_(name) {}
public:
// Returns the value of `name` variable.
UniquePtr<char> GetValue();
// Sets the value of `name` variable.
void SetValue(const char* value);
// Unsets `name` variable.
void Unset();
protected:
char* GetName();
private:
char* name_;
};
class GlobalConfigEnvBool : public GlobalConfigEnv {
public:
constexpr GlobalConfigEnvBool(char* name, bool default_value)
: GlobalConfigEnv(name), default_value_(default_value) {}
bool Get();
void Set(bool value);
private:
bool default_value_;
};
class GlobalConfigEnvInt32 : public GlobalConfigEnv {
public:
constexpr GlobalConfigEnvInt32(char* name, int32_t default_value)
: GlobalConfigEnv(name), default_value_(default_value) {}
int32_t Get();
void Set(int32_t value);
private:
int32_t default_value_;
};
class GlobalConfigEnvString : public GlobalConfigEnv {
public:
constexpr GlobalConfigEnvString(char* name, const char* default_value)
: GlobalConfigEnv(name), default_value_(default_value) {}
UniquePtr<char> Get();
void Set(const char* value);
private:
const char* default_value_;
};
} // namespace grpc_core
// Macros for defining global config instances using environment variables.
// This defines a GlobalConfig*Type* instance with arguments for
// mutable variable name and default value.
// Mutable name (g_env_str_##name) is here for having an array
// for the canonical name without dynamic allocation.
// `help` argument is ignored for this implementation.
#define GPR_GLOBAL_CONFIG_DEFINE_BOOL(name, default_value, help) \
static char g_env_str_##name[] = #name; \
static ::grpc_core::GlobalConfigEnvBool g_env_##name(g_env_str_##name, \
default_value); \
bool gpr_global_config_get_##name() { return g_env_##name.Get(); } \
void gpr_global_config_set_##name(bool value) { g_env_##name.Set(value); }
#define GPR_GLOBAL_CONFIG_DEFINE_INT32(name, default_value, help) \
static char g_env_str_##name[] = #name; \
static ::grpc_core::GlobalConfigEnvInt32 g_env_##name(g_env_str_##name, \
default_value); \
int32_t gpr_global_config_get_##name() { return g_env_##name.Get(); } \
void gpr_global_config_set_##name(int32_t value) { g_env_##name.Set(value); }
#define GPR_GLOBAL_CONFIG_DEFINE_STRING(name, default_value, help) \
static char g_env_str_##name[] = #name; \
static ::grpc_core::GlobalConfigEnvString g_env_##name(g_env_str_##name, \
default_value); \
::grpc_core::UniquePtr<char> gpr_global_config_get_##name() { \
return g_env_##name.Get(); \
} \
void gpr_global_config_set_##name(const char* value) { \
g_env_##name.Set(value); \
}
#endif /* GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_ENV_H */

@ -0,0 +1,44 @@
/*
*
* 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.
*
*/
#ifndef GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_GENERIC_H
#define GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_GENERIC_H
#include <grpc/support/port_platform.h>
#include "src/core/lib/gprpp/memory.h"
#include <stdint.h>
#define GPR_GLOBAL_CONFIG_GET(name) gpr_global_config_get_##name()
#define GPR_GLOBAL_CONFIG_SET(name, value) gpr_global_config_set_##name(value)
#define GPR_GLOBAL_CONFIG_DECLARE_BOOL(name) \
extern bool gpr_global_config_get_##name(); \
extern void gpr_global_config_set_##name(bool value)
#define GPR_GLOBAL_CONFIG_DECLARE_INT32(name) \
extern int32_t gpr_global_config_get_##name(); \
extern void gpr_global_config_set_##name(int32_t value)
#define GPR_GLOBAL_CONFIG_DECLARE_STRING(name) \
extern grpc_core::UniquePtr<char> gpr_global_config_get_##name(); \
extern void gpr_global_config_set_##name(const char* value)
#endif /* GRPC_CORE_LIB_GPRPP_GLOBAL_CONFIG_GENERIC_H */

@ -31,7 +31,7 @@
// Provides serialized access to some resource.
// Each action queued on a combiner is executed serially in a borrowed thread.
// The actual thread executing actions may change over time (but there will only
// every be one at a time).
// ever be one at a time).
// Initialize the lock, with an optional workqueue to shift load to when
// necessary

@ -29,9 +29,9 @@
#include <grpc/support/string_util.h>
#include <grpc/support/sync.h>
#include "src/core/lib/gpr/env.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/buffer_list.h"
#include "src/core/lib/iomgr/exec_ctx.h"
@ -41,6 +41,9 @@
#include "src/core/lib/iomgr/timer.h"
#include "src/core/lib/iomgr/timer_manager.h"
GPR_GLOBAL_CONFIG_DEFINE_BOOL(grpc_abort_on_leaks, false,
"Abort when leak is found");
static gpr_mu g_mu;
static gpr_cv g_rcv;
static int g_shutdown;
@ -186,8 +189,5 @@ void grpc_iomgr_unregister_object(grpc_iomgr_object* obj) {
}
bool grpc_iomgr_abort_on_leaks(void) {
char* env = gpr_getenv("GRPC_ABORT_ON_LEAKS");
bool should_we = gpr_is_true(env);
gpr_free(env);
return should_we;
return GPR_GLOBAL_CONFIG_GET(grpc_abort_on_leaks);
}

@ -30,6 +30,7 @@
#include "src/core/lib/gpr/env.h"
#include "src/core/lib/gpr/host_port.h"
#include "src/core/lib/gpr/string.h"
#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/iomgr/load_file.h"
#include "src/core/lib/security/context/security_context.h"
@ -47,9 +48,8 @@ static const char* installed_roots_path =
/** Environment variable used as a flag to enable/disable loading system root
certificates from the OS trust store. */
#ifndef GRPC_NOT_USE_SYSTEM_SSL_ROOTS_ENV_VAR
#define GRPC_NOT_USE_SYSTEM_SSL_ROOTS_ENV_VAR "GRPC_NOT_USE_SYSTEM_SSL_ROOTS"
#endif
GPR_GLOBAL_CONFIG_DEFINE_BOOL(grpc_not_use_system_ssl_roots, false,
"Disable loading system root certificates.");
#ifndef TSI_OPENSSL_ALPN_SUPPORT
#define TSI_OPENSSL_ALPN_SUPPORT 1
@ -428,10 +428,8 @@ const char* DefaultSslRootStore::GetPemRootCerts() {
grpc_slice DefaultSslRootStore::ComputePemRootCerts() {
grpc_slice result = grpc_empty_slice();
char* not_use_system_roots_env_value =
gpr_getenv(GRPC_NOT_USE_SYSTEM_SSL_ROOTS_ENV_VAR);
const bool not_use_system_roots = gpr_is_true(not_use_system_roots_env_value);
gpr_free(not_use_system_roots_env_value);
const bool not_use_system_roots =
GPR_GLOBAL_CONFIG_GET(grpc_not_use_system_ssl_roots);
// First try to load the roots from the environment.
char* default_root_certs_path =
gpr_getenv(GRPC_DEFAULT_SSL_ROOTS_FILE_PATH_ENV_VAR);

@ -33,6 +33,10 @@
#define GROW(x) (3 * (x) / 2)
static void maybe_embiggen(grpc_slice_buffer* sb) {
if (sb->length == 0) {
sb->slices = sb->base_slices;
}
/* How far away from sb->base_slices is sb->slices pointer */
size_t slice_offset = static_cast<size_t>(sb->slices - sb->base_slices);
size_t slice_count = sb->count + slice_offset;
@ -177,6 +181,7 @@ void grpc_slice_buffer_reset_and_unref_internal(grpc_slice_buffer* sb) {
sb->count = 0;
sb->length = 0;
sb->slices = sb->base_slices;
}
void grpc_slice_buffer_reset_and_unref(grpc_slice_buffer* sb) {

@ -222,7 +222,7 @@ inline uint32_t grpc_slice_refcount::Hash(const grpc_slice& slice) {
g_hash_seed);
}
inline grpc_slice grpc_slice_ref_internal(const grpc_slice& slice) {
inline const grpc_slice& grpc_slice_ref_internal(const grpc_slice& slice) {
if (slice.refcount) {
slice.refcount->Ref();
}

@ -260,10 +260,10 @@ grpc_core::TraceFlag grpc_compression_trace(false, "compression");
#define CALL_STACK_FROM_CALL(call) \
(grpc_call_stack*)((char*)(call) + \
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call)))
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(sizeof(grpc_call)))
#define CALL_FROM_CALL_STACK(call_stack) \
(grpc_call*)(((char*)(call_stack)) - \
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call)))
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(sizeof(grpc_call)))
#define CALL_ELEM_FROM_CALL(call, idx) \
grpc_call_stack_element(CALL_STACK_FROM_CALL(call), idx)
@ -329,7 +329,7 @@ grpc_error* grpc_call_create(const grpc_call_create_args* args,
size_t initial_size = grpc_channel_get_call_size_estimate(args->channel);
GRPC_STATS_INC_CALL_INITIAL_SIZE(initial_size);
size_t call_and_stack_size =
GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call)) +
GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(sizeof(grpc_call)) +
channel_stack->call_stack_size;
size_t call_alloc_size =
call_and_stack_size + (args->parent ? sizeof(child_call) : 0);

@ -48,6 +48,18 @@ void grpc_error_get_status(grpc_error* error, grpc_millis deadline,
grpc_status_code* code, grpc_slice* slice,
grpc_http2_error_code* http_error,
const char** error_string) {
// Fast path: We expect no error.
if (GPR_LIKELY(error == GRPC_ERROR_NONE)) {
if (code != nullptr) *code = GRPC_STATUS_OK;
if (slice != nullptr) {
grpc_error_get_str(error, GRPC_ERROR_STR_GRPC_MESSAGE, slice);
}
if (http_error != nullptr) {
*http_error = GRPC_HTTP2_NO_ERROR;
}
return;
}
// Start with the parent error and recurse through the tree of children
// until we find the first one that has a status code.
grpc_error* found_error =

@ -115,7 +115,7 @@ void grpc_transport_move_stats(grpc_transport_stream_stats* from,
}
size_t grpc_transport_stream_size(grpc_transport* transport) {
return GPR_ROUND_UP_TO_ALIGNMENT_SIZE(transport->vtable->sizeof_stream);
return GPR_ROUND_UP_TO_MAX_ALIGNMENT_SIZE(transport->vtable->sizeof_stream);
}
void grpc_transport_destroy(grpc_transport* transport) {

@ -106,15 +106,183 @@ class UnimplementedAsyncRequestContext {
} // namespace
ServerInterface::BaseAsyncRequest::BaseAsyncRequest(
ServerInterface* server, ServerContext* context,
internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
: server_(server),
context_(context),
stream_(stream),
call_cq_(call_cq),
notification_cq_(notification_cq),
tag_(tag),
delete_on_finalize_(delete_on_finalize),
call_(nullptr),
done_intercepting_(false) {
/* Set up interception state partially for the receive ops. call_wrapper_ is
* not filled at this point, but it will be filled before the interceptors are
* run. */
interceptor_methods_.SetCall(&call_wrapper_);
interceptor_methods_.SetReverse();
call_cq_->RegisterAvalanching(); // This op will trigger more ops
}
ServerInterface::BaseAsyncRequest::~BaseAsyncRequest() {
call_cq_->CompleteAvalanching();
}
bool ServerInterface::BaseAsyncRequest::FinalizeResult(void** tag,
bool* status) {
if (done_intercepting_) {
*tag = tag_;
if (delete_on_finalize_) {
delete this;
}
return true;
}
context_->set_call(call_);
context_->cq_ = call_cq_;
if (call_wrapper_.call() == nullptr) {
// Fill it since it is empty.
call_wrapper_ = internal::Call(
call_, server_, call_cq_, server_->max_receive_message_size(), nullptr);
}
// just the pointers inside call are copied here
stream_->BindCall(&call_wrapper_);
if (*status && call_ && call_wrapper_.server_rpc_info()) {
done_intercepting_ = true;
// Set interception point for RECV INITIAL METADATA
interceptor_methods_.AddInterceptionHookPoint(
experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA);
interceptor_methods_.SetRecvInitialMetadata(&context_->client_metadata_);
if (interceptor_methods_.RunInterceptors(
[this]() { ContinueFinalizeResultAfterInterception(); })) {
// There are no interceptors to run. Continue
} else {
// There were interceptors to be run, so
// ContinueFinalizeResultAfterInterception will be run when interceptors
// are done.
return false;
}
}
if (*status && call_) {
context_->BeginCompletionOp(&call_wrapper_, nullptr, nullptr);
}
*tag = tag_;
if (delete_on_finalize_) {
delete this;
}
return true;
}
void ServerInterface::BaseAsyncRequest::
ContinueFinalizeResultAfterInterception() {
context_->BeginCompletionOp(&call_wrapper_, nullptr, nullptr);
// Queue a tag which will be returned immediately
grpc_core::ExecCtx exec_ctx;
grpc_cq_begin_op(notification_cq_->cq(), this);
grpc_cq_end_op(
notification_cq_->cq(), this, GRPC_ERROR_NONE,
[](void* arg, grpc_cq_completion* completion) { delete completion; },
nullptr, new grpc_cq_completion());
}
ServerInterface::RegisteredAsyncRequest::RegisteredAsyncRequest(
ServerInterface* server, ServerContext* context,
internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
ServerCompletionQueue* notification_cq, void* tag, const char* name,
internal::RpcMethod::RpcType type)
: BaseAsyncRequest(server, context, stream, call_cq, notification_cq, tag,
true),
name_(name),
type_(type) {}
void ServerInterface::RegisteredAsyncRequest::IssueRequest(
void* registered_method, grpc_byte_buffer** payload,
ServerCompletionQueue* notification_cq) {
GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_registered_call(
server_->server(), registered_method, &call_,
&context_->deadline_,
context_->client_metadata_.arr(), payload,
call_cq_->cq(), notification_cq->cq(), this));
}
ServerInterface::GenericAsyncRequest::GenericAsyncRequest(
ServerInterface* server, GenericServerContext* context,
internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
: BaseAsyncRequest(server, context, stream, call_cq, notification_cq, tag,
delete_on_finalize) {
grpc_call_details_init(&call_details_);
GPR_ASSERT(notification_cq);
GPR_ASSERT(call_cq);
GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call(
server->server(), &call_, &call_details_,
context->client_metadata_.arr(), call_cq->cq(),
notification_cq->cq(), this));
}
bool ServerInterface::GenericAsyncRequest::FinalizeResult(void** tag,
bool* status) {
// If we are done intercepting, there is nothing more for us to do
if (done_intercepting_) {
return BaseAsyncRequest::FinalizeResult(tag, status);
}
// TODO(yangg) remove the copy here.
if (*status) {
static_cast<GenericServerContext*>(context_)->method_ =
StringFromCopiedSlice(call_details_.method);
static_cast<GenericServerContext*>(context_)->host_ =
StringFromCopiedSlice(call_details_.host);
context_->deadline_ = call_details_.deadline;
}
grpc_slice_unref(call_details_.method);
grpc_slice_unref(call_details_.host);
call_wrapper_ = internal::Call(
call_, server_, call_cq_, server_->max_receive_message_size(),
context_->set_server_rpc_info(
static_cast<GenericServerContext*>(context_)->method_.c_str(),
internal::RpcMethod::BIDI_STREAMING,
*server_->interceptor_creators()));
return BaseAsyncRequest::FinalizeResult(tag, status);
}
namespace {
class ShutdownCallback : public grpc_experimental_completion_queue_functor {
public:
ShutdownCallback() { functor_run = &ShutdownCallback::Run; }
// TakeCQ takes ownership of the cq into the shutdown callback
// so that the shutdown callback will be responsible for destroying it
void TakeCQ(CompletionQueue* cq) { cq_ = cq; }
// The Run function will get invoked by the completion queue library
// when the shutdown is actually complete
static void Run(grpc_experimental_completion_queue_functor* cb, int) {
auto* callback = static_cast<ShutdownCallback*>(cb);
delete callback->cq_;
delete callback;
}
private:
CompletionQueue* cq_ = nullptr;
};
} // namespace
} // namespace grpc
namespace grpc_impl {
/// Use private inheritance rather than composition only to establish order
/// of construction, since the public base class should be constructed after the
/// elements belonging to the private base class are constructed. This is not
/// possible using true composition.
class Server::UnimplementedAsyncRequest final
: private UnimplementedAsyncRequestContext,
: private grpc::UnimplementedAsyncRequestContext,
public GenericAsyncRequest {
public:
UnimplementedAsyncRequest(Server* server, ServerCompletionQueue* cq)
UnimplementedAsyncRequest(Server* server, grpc::ServerCompletionQueue* cq)
: GenericAsyncRequest(server, &server_context_, &generic_stream_, cq, cq,
nullptr, false),
server_(server),
@ -122,27 +290,29 @@ class Server::UnimplementedAsyncRequest final
bool FinalizeResult(void** tag, bool* status) override;
ServerContext* context() { return &server_context_; }
GenericServerAsyncReaderWriter* stream() { return &generic_stream_; }
grpc::ServerContext* context() { return &server_context_; }
grpc::GenericServerAsyncReaderWriter* stream() { return &generic_stream_; }
private:
Server* const server_;
ServerCompletionQueue* const cq_;
grpc::ServerCompletionQueue* const cq_;
};
/// UnimplementedAsyncResponse should not post user-visible completions to the
/// C++ completion queue, but is generated as a CQ event by the core
class Server::UnimplementedAsyncResponse final
: public internal::CallOpSet<internal::CallOpSendInitialMetadata,
internal::CallOpServerSendStatus> {
: public grpc::internal::CallOpSet<
grpc::internal::CallOpSendInitialMetadata,
grpc::internal::CallOpServerSendStatus> {
public:
UnimplementedAsyncResponse(UnimplementedAsyncRequest* request);
~UnimplementedAsyncResponse() { delete request_; }
bool FinalizeResult(void** tag, bool* status) override {
if (internal::CallOpSet<
internal::CallOpSendInitialMetadata,
internal::CallOpServerSendStatus>::FinalizeResult(tag, status)) {
if (grpc::internal::CallOpSet<
grpc::internal::CallOpSendInitialMetadata,
grpc::internal::CallOpServerSendStatus>::FinalizeResult(tag,
status)) {
delete this;
} else {
// The tag was swallowed due to interception. We will see it again.
@ -154,15 +324,16 @@ class Server::UnimplementedAsyncResponse final
UnimplementedAsyncRequest* const request_;
};
class Server::SyncRequest final : public internal::CompletionQueueTag {
class Server::SyncRequest final : public grpc::internal::CompletionQueueTag {
public:
SyncRequest(internal::RpcServiceMethod* method, void* method_tag)
SyncRequest(grpc::internal::RpcServiceMethod* method, void* method_tag)
: method_(method),
method_tag_(method_tag),
in_flight_(false),
has_request_payload_(
method->method_type() == internal::RpcMethod::NORMAL_RPC ||
method->method_type() == internal::RpcMethod::SERVER_STREAMING),
has_request_payload_(method->method_type() ==
grpc::internal::RpcMethod::NORMAL_RPC ||
method->method_type() ==
grpc::internal::RpcMethod::SERVER_STREAMING),
call_details_(nullptr),
cq_(nullptr) {
grpc_metadata_array_init(&request_metadata_);
@ -273,7 +444,8 @@ class Server::SyncRequest final : public internal::CompletionQueueTag {
interceptor_methods_.SetReverse();
// Set interception point for RECV INITIAL METADATA
interceptor_methods_.AddInterceptionHookPoint(
experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA);
grpc::experimental::InterceptionHookPoints::
POST_RECV_INITIAL_METADATA);
interceptor_methods_.SetRecvInitialMetadata(&ctx_.client_metadata_);
if (has_request_payload_) {
@ -285,7 +457,7 @@ class Server::SyncRequest final : public internal::CompletionQueueTag {
request_payload_ = nullptr;
interceptor_methods_.AddInterceptionHookPoint(
experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
grpc::experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
interceptor_methods_.SetRecvMessage(request_, nullptr);
}
@ -304,40 +476,40 @@ class Server::SyncRequest final : public internal::CompletionQueueTag {
global_callbacks_->PreSynchronousRequest(&ctx_);
auto* handler = resources_ ? method_->handler()
: server_->resource_exhausted_handler_.get();
handler->RunHandler(internal::MethodHandler::HandlerParameter(
handler->RunHandler(grpc::internal::MethodHandler::HandlerParameter(
&call_, &ctx_, request_, request_status_, nullptr, nullptr));
request_ = nullptr;
global_callbacks_->PostSynchronousRequest(&ctx_);
cq_.Shutdown();
internal::CompletionQueueTag* op_tag = ctx_.GetCompletionOpTag();
grpc::internal::CompletionQueueTag* op_tag = ctx_.GetCompletionOpTag();
cq_.TryPluck(op_tag, gpr_inf_future(GPR_CLOCK_REALTIME));
/* Ensure the cq_ is shutdown */
DummyTag ignored_tag;
grpc::DummyTag ignored_tag;
GPR_ASSERT(cq_.Pluck(&ignored_tag) == false);
}
delete this;
}
private:
CompletionQueue cq_;
ServerContext ctx_;
grpc::CompletionQueue cq_;
grpc::ServerContext ctx_;
const bool has_request_payload_;
grpc_byte_buffer* request_payload_;
void* request_;
Status request_status_;
internal::RpcServiceMethod* const method_;
internal::Call call_;
grpc::Status request_status_;
grpc::internal::RpcServiceMethod* const method_;
grpc::internal::Call call_;
Server* server_;
std::shared_ptr<GlobalCallbacks> global_callbacks_;
bool resources_;
internal::InterceptorBatchMethodsImpl interceptor_methods_;
grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_;
};
private:
internal::RpcServiceMethod* const method_;
grpc::internal::RpcServiceMethod* const method_;
void* const method_tag_;
bool in_flight_;
const bool has_request_payload_;
@ -349,7 +521,7 @@ class Server::SyncRequest final : public internal::CompletionQueueTag {
grpc_completion_queue* cq_;
};
class Server::CallbackRequestBase : public internal::CompletionQueueTag {
class Server::CallbackRequestBase : public grpc::internal::CompletionQueueTag {
public:
virtual ~CallbackRequestBase() {}
virtual bool Request() = 0;
@ -358,7 +530,7 @@ class Server::CallbackRequestBase : public internal::CompletionQueueTag {
template <class ServerContextType>
class Server::CallbackRequest final : public Server::CallbackRequestBase {
public:
static_assert(std::is_base_of<ServerContext, ServerContextType>::value,
static_assert(std::is_base_of<grpc::ServerContext, ServerContextType>::value,
"ServerContextType must be derived from ServerContext");
// The constructor needs to know the server for this callback request and its
@ -368,15 +540,16 @@ class Server::CallbackRequest final : public Server::CallbackRequestBase {
// requested. For generic services, method and method_tag are nullptr since
// these services don't have pre-defined methods or method registration tags.
CallbackRequest(Server* server, size_t method_idx,
internal::RpcServiceMethod* method, void* method_tag)
grpc::internal::RpcServiceMethod* method, void* method_tag)
: server_(server),
method_index_(method_idx),
method_(method),
method_tag_(method_tag),
has_request_payload_(
method_ != nullptr &&
(method->method_type() == internal::RpcMethod::NORMAL_RPC ||
method->method_type() == internal::RpcMethod::SERVER_STREAMING)),
(method->method_type() == grpc::internal::RpcMethod::NORMAL_RPC ||
method->method_type() ==
grpc::internal::RpcMethod::SERVER_STREAMING)),
cq_(server->CallbackCQ()),
tag_(this) {
server_->callback_reqs_outstanding_++;
@ -440,7 +613,7 @@ class Server::CallbackRequest final : public Server::CallbackRequestBase {
private:
Server::CallbackRequest<ServerContextType>* req_;
internal::Call* call_;
grpc::internal::Call* call_;
static void StaticRun(grpc_experimental_completion_queue_functor* cb,
int ok) {
@ -491,21 +664,24 @@ class Server::CallbackRequest final : public Server::CallbackRequestBase {
req_->request_metadata_.count = 0;
// Create a C++ Call to control the underlying core call
call_ = new (grpc_call_arena_alloc(req_->call_, sizeof(internal::Call)))
internal::Call(req_->call_, req_->server_, req_->cq_,
req_->server_->max_receive_message_size(),
req_->ctx_.set_server_rpc_info(
req_->method_name(),
(req_->method_ != nullptr)
? req_->method_->method_type()
: internal::RpcMethod::BIDI_STREAMING,
req_->server_->interceptor_creators_));
call_ =
new (grpc_call_arena_alloc(req_->call_, sizeof(grpc::internal::Call)))
grpc::internal::Call(
req_->call_, req_->server_, req_->cq_,
req_->server_->max_receive_message_size(),
req_->ctx_.set_server_rpc_info(
req_->method_name(),
(req_->method_ != nullptr)
? req_->method_->method_type()
: grpc::internal::RpcMethod::BIDI_STREAMING,
req_->server_->interceptor_creators_));
req_->interceptor_methods_.SetCall(call_);
req_->interceptor_methods_.SetReverse();
// Set interception point for RECV INITIAL METADATA
req_->interceptor_methods_.AddInterceptionHookPoint(
experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA);
grpc::experimental::InterceptionHookPoints::
POST_RECV_INITIAL_METADATA);
req_->interceptor_methods_.SetRecvInitialMetadata(
&req_->ctx_.client_metadata_);
@ -516,7 +692,7 @@ class Server::CallbackRequest final : public Server::CallbackRequestBase {
&req_->handler_data_);
req_->request_payload_ = nullptr;
req_->interceptor_methods_.AddInterceptionHookPoint(
experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
grpc::experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
req_->interceptor_methods_.SetRecvMessage(req_->request_, nullptr);
}
@ -532,7 +708,7 @@ class Server::CallbackRequest final : public Server::CallbackRequestBase {
auto* handler = (req_->method_ != nullptr)
? req_->method_->handler()
: req_->server_->generic_handler_.get();
handler->RunHandler(internal::MethodHandler::HandlerParameter(
handler->RunHandler(grpc::internal::MethodHandler::HandlerParameter(
call_, &req_->ctx_, req_->request_, req_->request_status_,
req_->handler_data_, [this] {
// Recycle this request if there aren't too many outstanding.
@ -580,41 +756,41 @@ class Server::CallbackRequest final : public Server::CallbackRequestBase {
request_payload_ = nullptr;
request_ = nullptr;
handler_data_ = nullptr;
request_status_ = Status();
request_status_ = grpc::Status();
}
Server* const server_;
const size_t method_index_;
internal::RpcServiceMethod* const method_;
grpc::internal::RpcServiceMethod* const method_;
void* const method_tag_;
const bool has_request_payload_;
grpc_byte_buffer* request_payload_;
void* request_;
void* handler_data_;
Status request_status_;
grpc::Status request_status_;
grpc_call_details* call_details_ = nullptr;
grpc_call* call_;
gpr_timespec deadline_;
grpc_metadata_array request_metadata_;
CompletionQueue* cq_;
grpc::CompletionQueue* cq_;
CallbackCallTag tag_;
ServerContextType ctx_;
internal::InterceptorBatchMethodsImpl interceptor_methods_;
grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_;
};
template <>
bool Server::CallbackRequest<ServerContext>::FinalizeResult(void** tag,
bool* status) {
bool Server::CallbackRequest<grpc::ServerContext>::FinalizeResult(
void** tag, bool* status) {
return false;
}
template <>
bool Server::CallbackRequest<GenericServerContext>::FinalizeResult(
bool Server::CallbackRequest<grpc::GenericServerContext>::FinalizeResult(
void** tag, bool* status) {
if (*status) {
// TODO(yangg) remove the copy here
ctx_.method_ = StringFromCopiedSlice(call_details_->method);
ctx_.host_ = StringFromCopiedSlice(call_details_->host);
ctx_.method_ = grpc::StringFromCopiedSlice(call_details_->method);
ctx_.host_ = grpc::StringFromCopiedSlice(call_details_->host);
}
grpc_slice_unref(call_details_->method);
grpc_slice_unref(call_details_->host);
@ -622,21 +798,22 @@ bool Server::CallbackRequest<GenericServerContext>::FinalizeResult(
}
template <>
const char* Server::CallbackRequest<ServerContext>::method_name() const {
const char* Server::CallbackRequest<grpc::ServerContext>::method_name() const {
return method_->name();
}
template <>
const char* Server::CallbackRequest<GenericServerContext>::method_name() const {
const char* Server::CallbackRequest<grpc::GenericServerContext>::method_name()
const {
return ctx_.method().c_str();
}
// Implementation of ThreadManager. Each instance of SyncRequestThreadManager
// manages a pool of threads that poll for incoming Sync RPCs and call the
// appropriate RPC handlers
class Server::SyncRequestThreadManager : public ThreadManager {
class Server::SyncRequestThreadManager : public grpc::ThreadManager {
public:
SyncRequestThreadManager(Server* server, CompletionQueue* server_cq,
SyncRequestThreadManager(Server* server, grpc::CompletionQueue* server_cq,
std::shared_ptr<GlobalCallbacks> global_callbacks,
grpc_resource_quota* rq, int min_pollers,
int max_pollers, int cq_timeout_msec)
@ -655,11 +832,11 @@ class Server::SyncRequestThreadManager : public ThreadManager {
gpr_time_from_millis(cq_timeout_msec_, GPR_TIMESPAN));
switch (server_cq_->AsyncNext(tag, ok, deadline)) {
case CompletionQueue::TIMEOUT:
case grpc::CompletionQueue::TIMEOUT:
return TIMEOUT;
case CompletionQueue::SHUTDOWN:
case grpc::CompletionQueue::SHUTDOWN:
return SHUTDOWN;
case CompletionQueue::GOT_EVENT:
case grpc::CompletionQueue::GOT_EVENT:
return WORK_FOUND;
}
@ -694,15 +871,15 @@ class Server::SyncRequestThreadManager : public ThreadManager {
// object
}
void AddSyncMethod(internal::RpcServiceMethod* method, void* tag) {
void AddSyncMethod(grpc::internal::RpcServiceMethod* method, void* tag) {
sync_requests_.emplace_back(new SyncRequest(method, tag));
}
void AddUnknownSyncMethod() {
if (!sync_requests_.empty()) {
unknown_method_.reset(new internal::RpcServiceMethod(
"unknown", internal::RpcMethod::BIDI_STREAMING,
new internal::UnknownMethodHandler));
unknown_method_.reset(new grpc::internal::RpcServiceMethod(
"unknown", grpc::internal::RpcMethod::BIDI_STREAMING,
new grpc::internal::UnknownMethodHandler));
sync_requests_.emplace_back(
new SyncRequest(unknown_method_.get(), nullptr));
}
@ -746,22 +923,22 @@ class Server::SyncRequestThreadManager : public ThreadManager {
private:
Server* server_;
CompletionQueue* server_cq_;
grpc::CompletionQueue* server_cq_;
int cq_timeout_msec_;
std::vector<std::unique_ptr<SyncRequest>> sync_requests_;
std::unique_ptr<internal::RpcServiceMethod> unknown_method_;
std::unique_ptr<grpc::internal::RpcServiceMethod> unknown_method_;
std::shared_ptr<Server::GlobalCallbacks> global_callbacks_;
};
static internal::GrpcLibraryInitializer g_gli_initializer;
static grpc::internal::GrpcLibraryInitializer g_gli_initializer;
Server::Server(
int max_receive_message_size, ChannelArguments* args,
std::shared_ptr<std::vector<std::unique_ptr<ServerCompletionQueue>>>
int max_receive_message_size, grpc::ChannelArguments* args,
std::shared_ptr<std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>>
sync_server_cqs,
int min_pollers, int max_pollers, int sync_cq_timeout_msec,
grpc_resource_quota* server_rq,
std::vector<
std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>
std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>>
interceptor_creators)
: interceptor_creators_(std::move(interceptor_creators)),
max_receive_message_size_(max_receive_message_size),
@ -773,8 +950,8 @@ Server::Server(
server_initializer_(new grpc_impl::ServerInitializer(this)),
health_check_service_disabled_(false) {
g_gli_initializer.summon();
gpr_once_init(&g_once_init_callbacks, InitGlobalCallbacks);
global_callbacks_ = g_callbacks;
gpr_once_init(&grpc::g_once_init_callbacks, grpc::InitGlobalCallbacks);
global_callbacks_ = grpc::g_callbacks;
global_callbacks_->UpdateArguments(args);
if (sync_server_cqs_ != nullptr) {
@ -801,13 +978,14 @@ Server::Server(
args->SetChannelArgs(&channel_args);
for (size_t i = 0; i < channel_args.num_args; i++) {
if (0 ==
strcmp(channel_args.args[i].key, kHealthCheckServiceInterfaceArg)) {
if (0 == strcmp(channel_args.args[i].key,
grpc::kHealthCheckServiceInterfaceArg)) {
if (channel_args.args[i].value.pointer.p == nullptr) {
health_check_service_disabled_ = true;
} else {
health_check_service_.reset(static_cast<HealthCheckServiceInterface*>(
channel_args.args[i].value.pointer.p));
health_check_service_.reset(
static_cast<grpc::HealthCheckServiceInterface*>(
channel_args.args[i].value.pointer.p));
}
break;
}
@ -844,49 +1022,49 @@ Server::~Server() {
}
void Server::SetGlobalCallbacks(GlobalCallbacks* callbacks) {
GPR_ASSERT(!g_callbacks);
GPR_ASSERT(!grpc::g_callbacks);
GPR_ASSERT(callbacks);
g_callbacks.reset(callbacks);
grpc::g_callbacks.reset(callbacks);
}
grpc_server* Server::c_server() { return server_; }
std::shared_ptr<Channel> Server::InProcessChannel(
const ChannelArguments& args) {
std::shared_ptr<grpc::Channel> Server::InProcessChannel(
const grpc::ChannelArguments& args) {
grpc_channel_args channel_args = args.c_channel_args();
return CreateChannelInternal(
return grpc::CreateChannelInternal(
"inproc", grpc_inproc_channel_create(server_, &channel_args, nullptr),
std::vector<
std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>());
std::vector<std::unique_ptr<
grpc::experimental::ClientInterceptorFactoryInterface>>());
}
std::shared_ptr<Channel>
std::shared_ptr<grpc::Channel>
Server::experimental_type::InProcessChannelWithInterceptors(
const ChannelArguments& args,
const grpc::ChannelArguments& args,
std::vector<
std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>
interceptor_creators) {
grpc_channel_args channel_args = args.c_channel_args();
return CreateChannelInternal(
return grpc::CreateChannelInternal(
"inproc",
grpc_inproc_channel_create(server_->server_, &channel_args, nullptr),
std::move(interceptor_creators));
}
static grpc_server_register_method_payload_handling PayloadHandlingForMethod(
internal::RpcServiceMethod* method) {
grpc::internal::RpcServiceMethod* method) {
switch (method->method_type()) {
case internal::RpcMethod::NORMAL_RPC:
case internal::RpcMethod::SERVER_STREAMING:
case grpc::internal::RpcMethod::NORMAL_RPC:
case grpc::internal::RpcMethod::SERVER_STREAMING:
return GRPC_SRM_PAYLOAD_READ_INITIAL_BYTE_BUFFER;
case internal::RpcMethod::CLIENT_STREAMING:
case internal::RpcMethod::BIDI_STREAMING:
case grpc::internal::RpcMethod::CLIENT_STREAMING:
case grpc::internal::RpcMethod::BIDI_STREAMING:
return GRPC_SRM_PAYLOAD_NONE;
}
GPR_UNREACHABLE_CODE(return GRPC_SRM_PAYLOAD_NONE;);
}
bool Server::RegisterService(const grpc::string* host, Service* service) {
bool Server::RegisterService(const grpc::string* host, grpc::Service* service) {
bool has_async_methods = service->has_async_methods();
if (has_async_methods) {
GPR_ASSERT(service->server_ == nullptr &&
@ -902,7 +1080,7 @@ bool Server::RegisterService(const grpc::string* host, Service* service) {
continue;
}
internal::RpcServiceMethod* method = it->get();
grpc::internal::RpcServiceMethod* method = it->get();
void* method_registration_tag = grpc_server_register_method(
server_, method->name(), host ? host->c_str() : nullptr,
PayloadHandlingForMethod(method), 0);
@ -915,7 +1093,7 @@ bool Server::RegisterService(const grpc::string* host, Service* service) {
if (method->handler() == nullptr) { // Async method without handler
method->set_server_tag(method_registration_tag);
} else if (method->api_type() ==
internal::RpcServiceMethod::ApiType::SYNC) {
grpc::internal::RpcServiceMethod::ApiType::SYNC) {
for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
(*it)->AddSyncMethod(method, method_registration_tag);
}
@ -925,8 +1103,9 @@ bool Server::RegisterService(const grpc::string* host, Service* service) {
auto method_index = callback_unmatched_reqs_count_.size() - 1;
// TODO(vjpai): Register these dynamically based on need
for (int i = 0; i < DEFAULT_CALLBACK_REQS_PER_METHOD; i++) {
callback_reqs_to_start_.push_back(new CallbackRequest<ServerContext>(
this, method_index, method, method_registration_tag));
callback_reqs_to_start_.push_back(
new CallbackRequest<grpc::ServerContext>(this, method_index, method,
method_registration_tag));
}
// Enqueue it so that it will be Request'ed later after all request
// matchers are created at core server startup
@ -947,7 +1126,7 @@ bool Server::RegisterService(const grpc::string* host, Service* service) {
return true;
}
void Server::RegisterAsyncGenericService(AsyncGenericService* service) {
void Server::RegisterAsyncGenericService(grpc::AsyncGenericService* service) {
GPR_ASSERT(service->server_ == nullptr &&
"Can only register an async generic service against one server.");
service->server_ = this;
@ -955,7 +1134,7 @@ void Server::RegisterAsyncGenericService(AsyncGenericService* service) {
}
void Server::RegisterCallbackGenericService(
experimental::CallbackGenericService* service) {
grpc::experimental::CallbackGenericService* service) {
GPR_ASSERT(
service->server_ == nullptr &&
"Can only register a callback generic service against one server.");
@ -967,44 +1146,45 @@ void Server::RegisterCallbackGenericService(
auto method_index = callback_unmatched_reqs_count_.size() - 1;
// TODO(vjpai): Register these dynamically based on need
for (int i = 0; i < DEFAULT_CALLBACK_REQS_PER_METHOD; i++) {
callback_reqs_to_start_.push_back(new CallbackRequest<GenericServerContext>(
this, method_index, nullptr, nullptr));
callback_reqs_to_start_.push_back(
new CallbackRequest<grpc::GenericServerContext>(this, method_index,
nullptr, nullptr));
}
}
int Server::AddListeningPort(const grpc::string& addr,
ServerCredentials* creds) {
grpc::ServerCredentials* creds) {
GPR_ASSERT(!started_);
int port = creds->AddPortToServer(addr, server_);
global_callbacks_->AddPort(this, addr, creds, port);
return port;
}
void Server::Start(ServerCompletionQueue** cqs, size_t num_cqs) {
void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) {
GPR_ASSERT(!started_);
global_callbacks_->PreServerStart(this);
started_ = true;
// Only create default health check service when user did not provide an
// explicit one.
ServerCompletionQueue* health_check_cq = nullptr;
DefaultHealthCheckService::HealthCheckServiceImpl*
grpc::ServerCompletionQueue* health_check_cq = nullptr;
grpc::DefaultHealthCheckService::HealthCheckServiceImpl*
default_health_check_service_impl = nullptr;
if (health_check_service_ == nullptr && !health_check_service_disabled_ &&
DefaultHealthCheckServiceEnabled()) {
auto* default_hc_service = new DefaultHealthCheckService;
grpc::DefaultHealthCheckServiceEnabled()) {
auto* default_hc_service = new grpc::DefaultHealthCheckService;
health_check_service_.reset(default_hc_service);
// We create a non-polling CQ to avoid impacting application
// performance. This ensures that we don't introduce thread hops
// for application requests that wind up on this CQ, which is polled
// in its own thread.
health_check_cq =
new ServerCompletionQueue(GRPC_CQ_NEXT, GRPC_CQ_NON_POLLING, nullptr);
health_check_cq = new grpc::ServerCompletionQueue(
GRPC_CQ_NEXT, GRPC_CQ_NON_POLLING, nullptr);
grpc_server_register_completion_queue(server_, health_check_cq->cq(),
nullptr);
default_health_check_service_impl =
default_hc_service->GetHealthCheckService(
std::unique_ptr<ServerCompletionQueue>(health_check_cq));
std::unique_ptr<grpc::ServerCompletionQueue>(health_check_cq));
RegisterService(nullptr, default_health_check_service_impl);
}
@ -1012,7 +1192,8 @@ void Server::Start(ServerCompletionQueue** cqs, size_t num_cqs) {
// service to handle any unimplemented methods using the default reactor
// creator
if (!callback_reqs_to_start_.empty() && !has_callback_generic_service_) {
unimplemented_service_.reset(new experimental::CallbackGenericService);
unimplemented_service_.reset(
new grpc::experimental::CallbackGenericService);
RegisterCallbackGenericService(unimplemented_service_.get());
}
@ -1037,7 +1218,8 @@ void Server::Start(ServerCompletionQueue** cqs, size_t num_cqs) {
// server CQs), make sure that we have a ResourceExhausted handler
// to deal with the case of thread exhaustion
if (sync_server_cqs_ != nullptr && !sync_server_cqs_->empty()) {
resource_exhausted_handler_.reset(new internal::ResourceExhaustedHandler);
resource_exhausted_handler_.reset(
new grpc::internal::ResourceExhaustedHandler);
}
for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) {
@ -1063,20 +1245,20 @@ void Server::ShutdownInternal(gpr_timespec deadline) {
shutdown_ = true;
/// The completion queue to use for server shutdown completion notification
CompletionQueue shutdown_cq;
ShutdownTag shutdown_tag; // Dummy shutdown tag
grpc::CompletionQueue shutdown_cq;
grpc::ShutdownTag shutdown_tag; // Dummy shutdown tag
grpc_server_shutdown_and_notify(server_, shutdown_cq.cq(), &shutdown_tag);
shutdown_cq.Shutdown();
void* tag;
bool ok;
CompletionQueue::NextStatus status =
grpc::CompletionQueue::NextStatus status =
shutdown_cq.AsyncNext(&tag, &ok, deadline);
// If this timed out, it means we are done with the grace period for a clean
// shutdown. We should force a shutdown now by cancelling all inflight calls
if (status == CompletionQueue::NextStatus::TIMEOUT) {
if (status == grpc::CompletionQueue::NextStatus::TIMEOUT) {
grpc_server_cancel_all_calls(server_);
}
// Else in case of SHUTDOWN or GOT_EVENT, it means that the server has
@ -1128,154 +1310,11 @@ void Server::Wait() {
}
}
void Server::PerformOpsOnCall(internal::CallOpSetInterface* ops,
internal::Call* call) {
void Server::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops,
grpc::internal::Call* call) {
ops->FillOps(call);
}
ServerInterface::BaseAsyncRequest::BaseAsyncRequest(
ServerInterface* server, ServerContext* context,
internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
: server_(server),
context_(context),
stream_(stream),
call_cq_(call_cq),
notification_cq_(notification_cq),
tag_(tag),
delete_on_finalize_(delete_on_finalize),
call_(nullptr),
done_intercepting_(false) {
/* Set up interception state partially for the receive ops. call_wrapper_ is
* not filled at this point, but it will be filled before the interceptors are
* run. */
interceptor_methods_.SetCall(&call_wrapper_);
interceptor_methods_.SetReverse();
call_cq_->RegisterAvalanching(); // This op will trigger more ops
}
ServerInterface::BaseAsyncRequest::~BaseAsyncRequest() {
call_cq_->CompleteAvalanching();
}
bool ServerInterface::BaseAsyncRequest::FinalizeResult(void** tag,
bool* status) {
if (done_intercepting_) {
*tag = tag_;
if (delete_on_finalize_) {
delete this;
}
return true;
}
context_->set_call(call_);
context_->cq_ = call_cq_;
if (call_wrapper_.call() == nullptr) {
// Fill it since it is empty.
call_wrapper_ = internal::Call(
call_, server_, call_cq_, server_->max_receive_message_size(), nullptr);
}
// just the pointers inside call are copied here
stream_->BindCall(&call_wrapper_);
if (*status && call_ && call_wrapper_.server_rpc_info()) {
done_intercepting_ = true;
// Set interception point for RECV INITIAL METADATA
interceptor_methods_.AddInterceptionHookPoint(
experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA);
interceptor_methods_.SetRecvInitialMetadata(&context_->client_metadata_);
if (interceptor_methods_.RunInterceptors(
[this]() { ContinueFinalizeResultAfterInterception(); })) {
// There are no interceptors to run. Continue
} else {
// There were interceptors to be run, so
// ContinueFinalizeResultAfterInterception will be run when interceptors
// are done.
return false;
}
}
if (*status && call_) {
context_->BeginCompletionOp(&call_wrapper_, nullptr, nullptr);
}
*tag = tag_;
if (delete_on_finalize_) {
delete this;
}
return true;
}
void ServerInterface::BaseAsyncRequest::
ContinueFinalizeResultAfterInterception() {
context_->BeginCompletionOp(&call_wrapper_, nullptr, nullptr);
// Queue a tag which will be returned immediately
grpc_core::ExecCtx exec_ctx;
grpc_cq_begin_op(notification_cq_->cq(), this);
grpc_cq_end_op(
notification_cq_->cq(), this, GRPC_ERROR_NONE,
[](void* arg, grpc_cq_completion* completion) { delete completion; },
nullptr, new grpc_cq_completion());
}
ServerInterface::RegisteredAsyncRequest::RegisteredAsyncRequest(
ServerInterface* server, ServerContext* context,
internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
ServerCompletionQueue* notification_cq, void* tag, const char* name,
internal::RpcMethod::RpcType type)
: BaseAsyncRequest(server, context, stream, call_cq, notification_cq, tag,
true),
name_(name),
type_(type) {}
void ServerInterface::RegisteredAsyncRequest::IssueRequest(
void* registered_method, grpc_byte_buffer** payload,
ServerCompletionQueue* notification_cq) {
GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_registered_call(
server_->server(), registered_method, &call_,
&context_->deadline_,
context_->client_metadata_.arr(), payload,
call_cq_->cq(), notification_cq->cq(), this));
}
ServerInterface::GenericAsyncRequest::GenericAsyncRequest(
ServerInterface* server, GenericServerContext* context,
internal::ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq,
ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize)
: BaseAsyncRequest(server, context, stream, call_cq, notification_cq, tag,
delete_on_finalize) {
grpc_call_details_init(&call_details_);
GPR_ASSERT(notification_cq);
GPR_ASSERT(call_cq);
GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call(
server->server(), &call_, &call_details_,
context->client_metadata_.arr(), call_cq->cq(),
notification_cq->cq(), this));
}
bool ServerInterface::GenericAsyncRequest::FinalizeResult(void** tag,
bool* status) {
// If we are done intercepting, there is nothing more for us to do
if (done_intercepting_) {
return BaseAsyncRequest::FinalizeResult(tag, status);
}
// TODO(yangg) remove the copy here.
if (*status) {
static_cast<GenericServerContext*>(context_)->method_ =
StringFromCopiedSlice(call_details_.method);
static_cast<GenericServerContext*>(context_)->host_ =
StringFromCopiedSlice(call_details_.host);
context_->deadline_ = call_details_.deadline;
}
grpc_slice_unref(call_details_.method);
grpc_slice_unref(call_details_.host);
call_wrapper_ = internal::Call(
call_, server_, call_cq_, server_->max_receive_message_size(),
context_->set_server_rpc_info(
static_cast<GenericServerContext*>(context_)->method_.c_str(),
internal::RpcMethod::BIDI_STREAMING,
*server_->interceptor_creators()));
return BaseAsyncRequest::FinalizeResult(tag, status);
}
bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag,
bool* status) {
if (GenericAsyncRequest::FinalizeResult(tag, status)) {
@ -1295,41 +1334,22 @@ bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag,
Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse(
UnimplementedAsyncRequest* request)
: request_(request) {
Status status(StatusCode::UNIMPLEMENTED, "");
internal::UnknownMethodHandler::FillOps(request_->context(), this);
grpc::Status status(grpc::StatusCode::UNIMPLEMENTED, "");
grpc::internal::UnknownMethodHandler::FillOps(request_->context(), this);
request_->stream()->call_.PerformOps(this);
}
ServerInitializer* Server::initializer() { return server_initializer_.get(); }
namespace {
class ShutdownCallback : public grpc_experimental_completion_queue_functor {
public:
ShutdownCallback() { functor_run = &ShutdownCallback::Run; }
// TakeCQ takes ownership of the cq into the shutdown callback
// so that the shutdown callback will be responsible for destroying it
void TakeCQ(CompletionQueue* cq) { cq_ = cq; }
// The Run function will get invoked by the completion queue library
// when the shutdown is actually complete
static void Run(grpc_experimental_completion_queue_functor* cb, int) {
auto* callback = static_cast<ShutdownCallback*>(cb);
delete callback->cq_;
delete callback;
}
private:
CompletionQueue* cq_ = nullptr;
};
} // namespace
grpc::ServerInitializer* Server::initializer() {
return server_initializer_.get();
}
CompletionQueue* Server::CallbackCQ() {
grpc::CompletionQueue* Server::CallbackCQ() {
// TODO(vjpai): Consider using a single global CQ for the default CQ
// if there is no explicit per-server CQ registered
grpc::internal::MutexLock l(&mu_);
if (callback_cq_ == nullptr) {
auto* shutdown_callback = new ShutdownCallback;
callback_cq_ = new CompletionQueue(grpc_completion_queue_attributes{
auto* shutdown_callback = new grpc::ShutdownCallback;
callback_cq_ = new grpc::CompletionQueue(grpc_completion_queue_attributes{
GRPC_CQ_CURRENT_VERSION, GRPC_CQ_CALLBACK, GRPC_CQ_DEFAULT_POLLING,
shutdown_callback});
@ -1339,4 +1359,4 @@ CompletionQueue* Server::CallbackCQ() {
return callback_cq_;
}
} // namespace grpc
} // namespace grpc_impl

@ -18,6 +18,7 @@
using System.Runtime.CompilerServices;
using Grpc.Core;
using Grpc.Core.Interceptors;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
@ -32,16 +33,18 @@ using Grpc.Core.Utils;
[assembly:TypeForwardedToAttribute(typeof(AuthContext))]
[assembly:TypeForwardedToAttribute(typeof(AsyncAuthInterceptor))]
[assembly:TypeForwardedToAttribute(typeof(AuthInterceptorContext))]
[assembly: TypeForwardedToAttribute(typeof(CallCredentials))]
[assembly: TypeForwardedToAttribute(typeof(CallFlags))]
[assembly: TypeForwardedToAttribute(typeof(CallInvoker))]
[assembly: TypeForwardedToAttribute(typeof(CallOptions))]
[assembly:TypeForwardedToAttribute(typeof(CallCredentials))]
[assembly:TypeForwardedToAttribute(typeof(CallFlags))]
[assembly:TypeForwardedToAttribute(typeof(CallInvoker))]
[assembly:TypeForwardedToAttribute(typeof(CallOptions))]
[assembly:TypeForwardedToAttribute(typeof(ClientInterceptorContext<,>))]
[assembly:TypeForwardedToAttribute(typeof(ContextPropagationOptions))]
[assembly:TypeForwardedToAttribute(typeof(ContextPropagationToken))]
[assembly:TypeForwardedToAttribute(typeof(DeserializationContext))]
[assembly:TypeForwardedToAttribute(typeof(IAsyncStreamReader<>))]
[assembly:TypeForwardedToAttribute(typeof(IAsyncStreamWriter<>))]
[assembly:TypeForwardedToAttribute(typeof(IClientStreamWriter<>))]
[assembly:TypeForwardedToAttribute(typeof(Interceptor))]
[assembly:TypeForwardedToAttribute(typeof(IServerStreamWriter<>))]
[assembly:TypeForwardedToAttribute(typeof(Marshaller<>))]
[assembly:TypeForwardedToAttribute(typeof(Marshallers))]

@ -25,6 +25,11 @@ grpc_proto_library(
well_known_protos = True,
)
proto_library(
name = "channelz_proto_descriptors",
srcs = ["channelz.proto"],
)
filegroup(
name = "channelz_proto_file",
srcs = [

@ -23,6 +23,11 @@ grpc_proto_library(
srcs = ["health.proto"],
)
proto_library(
name = "health_proto_descriptor",
srcs = ["health.proto"],
)
filegroup(
name = "health_proto_file",
srcs = [

@ -23,6 +23,11 @@ grpc_proto_library(
srcs = ["reflection.proto"],
)
proto_library(
name = "reflection_proto_descriptor",
srcs = ["reflection.proto"],
)
filegroup(
name = "reflection_proto_file",
srcs = [

@ -16,7 +16,7 @@ licenses(["notice"]) # Apache v2
load("//bazel:grpc_build_system.bzl", "grpc_proto_library", "grpc_package")
load("@grpc_python_dependencies//:requirements.bzl", "requirement")
load("@org_pubref_rules_protobuf//python:rules.bzl", "py_proto_library")
load("//bazel:python_rules.bzl", "py_proto_library")
grpc_package(name = "testing", visibility = "public")
@ -61,13 +61,14 @@ grpc_proto_library(
has_services = False,
)
proto_library(
name = "empty_proto_descriptor",
srcs = ["empty.proto"],
)
py_proto_library(
name = "py_empty_proto",
protos = ["empty.proto",],
with_grpc = True,
deps = [
requirement('protobuf'),
],
deps = [":empty_proto_descriptor"],
)
grpc_proto_library(
@ -76,13 +77,14 @@ grpc_proto_library(
has_services = False,
)
proto_library(
name = "messages_proto_descriptor",
srcs = ["messages.proto"],
)
py_proto_library(
name = "py_messages_proto",
protos = ["messages.proto",],
with_grpc = True,
deps = [
requirement('protobuf'),
],
deps = [":messages_proto_descriptor"],
)
grpc_proto_library(
@ -144,16 +146,19 @@ grpc_proto_library(
],
)
proto_library(
name = "test_proto_descriptor",
srcs = ["test.proto"],
deps = [
":empty_proto_descriptor",
":messages_proto_descriptor",
],
)
py_proto_library(
name = "py_test_proto",
protos = ["test.proto",],
with_grpc = True,
deps = [
requirement('protobuf'),
],
proto_deps = [
":py_empty_proto",
":py_messages_proto",
":test_proto_descriptor",
]
)

@ -1,30 +1,32 @@
load("@grpc_python_dependencies//:requirements.bzl", "requirement")
load("@org_pubref_rules_protobuf//python:rules.bzl", "py_proto_library")
package(default_visibility = ["//visibility:public"])
load("//bazel:python_rules.bzl", "py_proto_library")
proto_library(
name = "empty2_proto_descriptor",
srcs = ["empty2.proto"],
)
py_proto_library(
name = "empty2_proto",
protos = [
"empty2.proto",
],
with_grpc = True,
deps = [
requirement('protobuf'),
":empty2_proto_descriptor",
],
)
proto_library(
name = "empty2_extensions_proto_descriptor",
srcs = ["empty2_extensions.proto"],
deps = [
":empty2_proto_descriptor",
]
)
py_proto_library(
name = "empty2_extensions_proto",
protos = [
"empty2_extensions.proto",
],
proto_deps = [
":empty2_proto",
],
with_grpc = True,
deps = [
requirement('protobuf'),
":empty2_extensions_proto_descriptor",
],
)

@ -53,6 +53,7 @@ CORE_SOURCE_FILES = [
'src/core/lib/gpr/wrap_memcpy.cc',
'src/core/lib/gprpp/arena.cc',
'src/core/lib/gprpp/fork.cc',
'src/core/lib/gprpp/global_config_env.cc',
'src/core/lib/gprpp/thd_posix.cc',
'src/core/lib/gprpp/thd_windows.cc',
'src/core/lib/profiling/basic_timers.cc',
@ -376,10 +377,13 @@ CORE_SOURCE_FILES = [
'src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_libuv.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_libuv_windows.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc',
'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc',
'src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc',

@ -1,30 +1,10 @@
load("@grpc_python_dependencies//:requirements.bzl", "requirement")
load("@org_pubref_rules_protobuf//python:rules.bzl", "py_proto_library")
load("//bazel:python_rules.bzl", "py_proto_library")
package(default_visibility = ["//visibility:public"])
genrule(
name = "mv_channelz_proto",
srcs = [
"//src/proto/grpc/channelz:channelz_proto_file",
],
outs = ["channelz.proto",],
cmd = "cp $< $@",
)
py_proto_library(
name = "py_channelz_proto",
protos = ["mv_channelz_proto",],
imports = [
"external/com_google_protobuf/src/",
],
inputs = [
"@com_google_protobuf//:well_known_protos",
],
with_grpc = True,
deps = [
requirement('protobuf'),
],
well_known_protos = True,
deps = ["//src/proto/grpc/channelz:channelz_proto_descriptors"],
)
py_library(

@ -1,24 +1,9 @@
load("@grpc_python_dependencies//:requirements.bzl", "requirement")
load("@org_pubref_rules_protobuf//python:rules.bzl", "py_proto_library")
load("//bazel:python_rules.bzl", "py_proto_library")
package(default_visibility = ["//visibility:public"])
genrule(
name = "mv_health_proto",
srcs = [
"//src/proto/grpc/health/v1:health_proto_file",
],
outs = ["health.proto",],
cmd = "cp $< $@",
)
py_proto_library(
name = "py_health_proto",
protos = [":mv_health_proto",],
with_grpc = True,
deps = [
requirement('protobuf'),
],
deps = ["//src/proto/grpc/health/v1:health_proto_descriptor",],
)
py_library(

@ -1,24 +1,11 @@
load("//bazel:python_rules.bzl", "py_proto_library")
load("@grpc_python_dependencies//:requirements.bzl", "requirement")
load("@org_pubref_rules_protobuf//python:rules.bzl", "py_proto_library")
package(default_visibility = ["//visibility:public"])
genrule(
name = "mv_reflection_proto",
srcs = [
"//src/proto/grpc/reflection/v1alpha:reflection_proto_file",
],
outs = ["reflection.proto",],
cmd = "cp $< $@",
)
py_proto_library(
name = "py_reflection_proto",
protos = [":mv_reflection_proto",],
with_grpc = True,
deps = [
requirement('protobuf'),
],
deps = ["//src/proto/grpc/reflection/v1alpha:reflection_proto_descriptor",],
)
py_library(

@ -56,12 +56,12 @@ class ForkInteropTest(unittest.TestCase):
import grpc
from src.proto.grpc.testing import test_pb2_grpc
from tests.interop import methods as interop_methods
from tests.interop import service as interop_service
from tests.unit import test_common
server = test_common.test_server()
test_pb2_grpc.add_TestServiceServicer_to_server(
interop_methods.TestService(), server)
interop_service.TestService(), server)
port = server.add_insecure_port('[::]:0')
server.start()
print(port)

@ -5,45 +5,45 @@ package(default_visibility = ["//visibility:public"])
py_library(
name = "_intraop_test_case",
srcs = ["_intraop_test_case.py"],
imports = ["../../"],
deps = [
":methods",
],
imports=["../../",],
)
py_library(
name = "client",
srcs = ["client.py"],
imports = ["../../"],
deps = [
"//src/python/grpcio/grpc:grpcio",
":methods",
":resources",
"//src/proto/grpc/testing:py_test_proto",
requirement('google-auth'),
"//src/python/grpcio/grpc:grpcio",
requirement("google-auth"),
],
imports=["../../",],
)
py_library(
name = "methods",
srcs = ["methods.py"],
imports = ["../../"],
deps = [
"//src/python/grpcio/grpc:grpcio",
"//src/python/grpcio_tests/tests:bazel_namespace_package_hack",
"//src/proto/grpc/testing:py_empty_proto",
"//src/proto/grpc/testing:py_messages_proto",
"//src/proto/grpc/testing:py_test_proto",
requirement('google-auth'),
requirement('requests'),
requirement('urllib3'),
requirement('chardet'),
requirement('certifi'),
requirement('idna'),
requirement("google-auth"),
requirement("requests"),
requirement("urllib3"),
requirement("chardet"),
requirement("certifi"),
requirement("idna"),
] + select({
"//conditions:default": [requirement('enum34'),],
"//conditions:default": [requirement("enum34")],
"//:python3": [],
}),
imports=["../../",],
)
py_library(
@ -54,51 +54,62 @@ py_library(
],
)
py_library(
name = "service",
srcs = ["service.py"],
imports = ["../../"],
deps = [
"//src/proto/grpc/testing:py_empty_proto",
"//src/proto/grpc/testing:py_messages_proto",
"//src/proto/grpc/testing:py_test_proto",
"//src/python/grpcio/grpc:grpcio",
],
)
py_library(
name = "server",
srcs = ["server.py"],
imports = ["../../"],
deps = [
"//src/python/grpcio/grpc:grpcio",
":methods",
":resources",
"//src/python/grpcio_tests/tests/unit:test_common",
":service",
"//src/proto/grpc/testing:py_test_proto",
"//src/python/grpcio/grpc:grpcio",
"//src/python/grpcio_tests/tests/unit:test_common",
],
imports=["../../",],
)
py_test(
name="_insecure_intraop_test",
size="small",
srcs=["_insecure_intraop_test.py",],
main="_insecure_intraop_test.py",
deps=[
"//src/python/grpcio/grpc:grpcio",
name = "_insecure_intraop_test",
size = "small",
srcs = ["_insecure_intraop_test.py"],
data = [
"//src/python/grpcio_tests/tests/unit/credentials",
],
imports = ["../../"],
main = "_insecure_intraop_test.py",
deps = [
":_intraop_test_case",
":methods",
":server",
"//src/python/grpcio_tests/tests/unit:test_common",
":service",
"//src/proto/grpc/testing:py_test_proto",
],
imports=["../../",],
data=[
"//src/python/grpcio_tests/tests/unit/credentials",
"//src/python/grpcio/grpc:grpcio",
"//src/python/grpcio_tests/tests/unit:test_common",
],
)
py_test(
name="_secure_intraop_test",
size="small",
srcs=["_secure_intraop_test.py",],
main="_secure_intraop_test.py",
deps=[
"//src/python/grpcio/grpc:grpcio",
name = "_secure_intraop_test",
size = "small",
srcs = ["_secure_intraop_test.py"],
imports = ["../../"],
main = "_secure_intraop_test.py",
deps = [
":_intraop_test_case",
":methods",
":server",
"//src/python/grpcio_tests/tests/unit:test_common",
":service",
"//src/proto/grpc/testing:py_test_proto",
"//src/python/grpcio/grpc:grpcio",
"//src/python/grpcio_tests/tests/unit:test_common",
],
imports=["../../",],
)

@ -19,7 +19,7 @@ import grpc
from src.proto.grpc.testing import test_pb2_grpc
from tests.interop import _intraop_test_case
from tests.interop import methods
from tests.interop import service
from tests.interop import server
from tests.unit import test_common
@ -29,7 +29,7 @@ class InsecureIntraopTest(_intraop_test_case.IntraopTestCase,
def setUp(self):
self.server = test_common.test_server()
test_pb2_grpc.add_TestServiceServicer_to_server(methods.TestService(),
test_pb2_grpc.add_TestServiceServicer_to_server(service.TestService(),
self.server)
port = self.server.add_insecure_port('[::]:0')
self.server.start()

@ -19,7 +19,7 @@ import grpc
from src.proto.grpc.testing import test_pb2_grpc
from tests.interop import _intraop_test_case
from tests.interop import methods
from tests.interop import service
from tests.interop import resources
from tests.unit import test_common
@ -30,7 +30,7 @@ class SecureIntraopTest(_intraop_test_case.IntraopTestCase, unittest.TestCase):
def setUp(self):
self.server = test_common.test_server()
test_pb2_grpc.add_TestServiceServicer_to_server(methods.TestService(),
test_pb2_grpc.add_TestServiceServicer_to_server(service.TestService(),
self.server)
port = self.server.add_secure_port(
'[::]:0',

@ -25,6 +25,7 @@ import enum
import json
import os
import threading
import time
from google import auth as google_auth
from google.auth import environment_vars as google_auth_environment_vars
@ -34,78 +35,11 @@ import grpc
from src.proto.grpc.testing import empty_pb2
from src.proto.grpc.testing import messages_pb2
from src.proto.grpc.testing import test_pb2_grpc
_INITIAL_METADATA_KEY = "x-grpc-test-echo-initial"
_TRAILING_METADATA_KEY = "x-grpc-test-echo-trailing-bin"
def _maybe_echo_metadata(servicer_context):
"""Copies metadata from request to response if it is present."""
invocation_metadata = dict(servicer_context.invocation_metadata())
if _INITIAL_METADATA_KEY in invocation_metadata:
initial_metadatum = (_INITIAL_METADATA_KEY,
invocation_metadata[_INITIAL_METADATA_KEY])
servicer_context.send_initial_metadata((initial_metadatum,))
if _TRAILING_METADATA_KEY in invocation_metadata:
trailing_metadatum = (_TRAILING_METADATA_KEY,
invocation_metadata[_TRAILING_METADATA_KEY])
servicer_context.set_trailing_metadata((trailing_metadatum,))
def _maybe_echo_status_and_message(request, servicer_context):
"""Sets the response context code and details if the request asks for them"""
if request.HasField('response_status'):
servicer_context.set_code(request.response_status.code)
servicer_context.set_details(request.response_status.message)
class TestService(test_pb2_grpc.TestServiceServicer):
def EmptyCall(self, request, context):
_maybe_echo_metadata(context)
return empty_pb2.Empty()
def UnaryCall(self, request, context):
_maybe_echo_metadata(context)
_maybe_echo_status_and_message(request, context)
return messages_pb2.SimpleResponse(
payload=messages_pb2.Payload(
type=messages_pb2.COMPRESSABLE,
body=b'\x00' * request.response_size))
def StreamingOutputCall(self, request, context):
_maybe_echo_status_and_message(request, context)
for response_parameters in request.response_parameters:
yield messages_pb2.StreamingOutputCallResponse(
payload=messages_pb2.Payload(
type=request.response_type,
body=b'\x00' * response_parameters.size))
def StreamingInputCall(self, request_iterator, context):
aggregate_size = 0
for request in request_iterator:
if request.payload is not None and request.payload.body:
aggregate_size += len(request.payload.body)
return messages_pb2.StreamingInputCallResponse(
aggregated_payload_size=aggregate_size)
def FullDuplexCall(self, request_iterator, context):
_maybe_echo_metadata(context)
for request in request_iterator:
_maybe_echo_status_and_message(request, context)
for response_parameters in request.response_parameters:
yield messages_pb2.StreamingOutputCallResponse(
payload=messages_pb2.Payload(
type=request.payload.type,
body=b'\x00' * response_parameters.size))
# NOTE(nathaniel): Apparently this is the same as the full-duplex call?
# NOTE(atash): It isn't even called in the interop spec (Oct 22 2015)...
def HalfDuplexCall(self, request_iterator, context):
return self.FullDuplexCall(request_iterator, context)
def _expect_status_code(call, expected_code):
if call.code() != expected_code:
raise ValueError('expected code %s, got %s' % (expected_code,

@ -21,7 +21,7 @@ import time
import grpc
from src.proto.grpc.testing import test_pb2_grpc
from tests.interop import methods
from tests.interop import service
from tests.interop import resources
from tests.unit import test_common
@ -42,7 +42,7 @@ def serve():
args = parser.parse_args()
server = test_common.test_server()
test_pb2_grpc.add_TestServiceServicer_to_server(methods.TestService(),
test_pb2_grpc.add_TestServiceServicer_to_server(service.TestService(),
server)
if args.use_tls:
private_key = resources.private_key()

@ -0,0 +1,97 @@
# Copyright 2019 The 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.
"""The Python implementation of the TestServicer."""
import time
import grpc
from src.proto.grpc.testing import empty_pb2
from src.proto.grpc.testing import messages_pb2
from src.proto.grpc.testing import test_pb2_grpc
_INITIAL_METADATA_KEY = "x-grpc-test-echo-initial"
_TRAILING_METADATA_KEY = "x-grpc-test-echo-trailing-bin"
_US_IN_A_SECOND = 1000 * 1000
def _maybe_echo_metadata(servicer_context):
"""Copies metadata from request to response if it is present."""
invocation_metadata = dict(servicer_context.invocation_metadata())
if _INITIAL_METADATA_KEY in invocation_metadata:
initial_metadatum = (_INITIAL_METADATA_KEY,
invocation_metadata[_INITIAL_METADATA_KEY])
servicer_context.send_initial_metadata((initial_metadatum,))
if _TRAILING_METADATA_KEY in invocation_metadata:
trailing_metadatum = (_TRAILING_METADATA_KEY,
invocation_metadata[_TRAILING_METADATA_KEY])
servicer_context.set_trailing_metadata((trailing_metadatum,))
def _maybe_echo_status_and_message(request, servicer_context):
"""Sets the response context code and details if the request asks for them"""
if request.HasField('response_status'):
servicer_context.set_code(request.response_status.code)
servicer_context.set_details(request.response_status.message)
class TestService(test_pb2_grpc.TestServiceServicer):
def EmptyCall(self, request, context):
_maybe_echo_metadata(context)
return empty_pb2.Empty()
def UnaryCall(self, request, context):
_maybe_echo_metadata(context)
_maybe_echo_status_and_message(request, context)
return messages_pb2.SimpleResponse(
payload=messages_pb2.Payload(
type=messages_pb2.COMPRESSABLE,
body=b'\x00' * request.response_size))
def StreamingOutputCall(self, request, context):
_maybe_echo_status_and_message(request, context)
for response_parameters in request.response_parameters:
if response_parameters.interval_us != 0:
time.sleep(response_parameters.interval_us / _US_IN_A_SECOND)
yield messages_pb2.StreamingOutputCallResponse(
payload=messages_pb2.Payload(
type=request.response_type,
body=b'\x00' * response_parameters.size))
def StreamingInputCall(self, request_iterator, context):
aggregate_size = 0
for request in request_iterator:
if request.payload is not None and request.payload.body:
aggregate_size += len(request.payload.body)
return messages_pb2.StreamingInputCallResponse(
aggregated_payload_size=aggregate_size)
def FullDuplexCall(self, request_iterator, context):
_maybe_echo_metadata(context)
for request in request_iterator:
_maybe_echo_status_and_message(request, context)
for response_parameters in request.response_parameters:
if response_parameters.interval_us != 0:
time.sleep(
response_parameters.interval_us / _US_IN_A_SECOND)
yield messages_pb2.StreamingOutputCallResponse(
payload=messages_pb2.Payload(
type=request.payload.type,
body=b'\x00' * response_parameters.size))
# NOTE(nathaniel): Apparently this is the same as the full-duplex call?
# NOTE(atash): It isn't even called in the interop spec (Oct 22 2015)...
def HalfDuplexCall(self, request_iterator, context):
return self.FullDuplexCall(request_iterator, context)

@ -14,6 +14,7 @@ py_test(
"//src/python/grpcio_tests/tests/unit:test_common",
"//src/proto/grpc/testing:py_empty_proto",
"//src/proto/grpc/testing/proto2:empty2_extensions_proto",
"//src/proto/grpc/testing/proto2:empty2_proto",
requirement('protobuf'),
],
imports=["../../",],

@ -31,12 +31,21 @@ static void fake_free(void* addr) {
*(static_cast<intptr_t*>(addr)) = static_cast<intptr_t>(0xdeadd00d);
}
static void* fake_aligned_malloc(size_t size, size_t alignment) {
return (void*)(size + alignment);
}
static void fake_aligned_free(void* addr) {
*(static_cast<intptr_t*>(addr)) = static_cast<intptr_t>(0xcafef00d);
}
static void test_custom_allocs() {
const gpr_allocation_functions default_fns = gpr_get_allocation_functions();
intptr_t addr_to_free = 0;
char* i;
gpr_allocation_functions fns = {fake_malloc, nullptr, fake_realloc,
fake_free};
gpr_allocation_functions fns = {fake_malloc, nullptr,
fake_realloc, fake_free,
fake_aligned_malloc, fake_aligned_free};
gpr_set_allocation_functions(fns);
GPR_ASSERT((void*)(size_t)0xdeadbeef == gpr_malloc(0xdeadbeef));
@ -45,6 +54,11 @@ static void test_custom_allocs() {
gpr_free(&addr_to_free);
GPR_ASSERT(addr_to_free == (intptr_t)0xdeadd00d);
GPR_ASSERT((void*)(size_t)(0xdeadbeef + 64) ==
gpr_malloc_aligned(0xdeadbeef, 64));
gpr_free_aligned(&addr_to_free);
GPR_ASSERT(addr_to_free == (intptr_t)0xcafef00d);
/* Restore and check we don't get funky values and that we don't leak */
gpr_set_allocation_functions(default_fns);
GPR_ASSERT((void*)sizeof(*i) !=

@ -42,8 +42,22 @@ static void test_setenv_getenv(void) {
gpr_free(retrieved_value);
}
static void test_unsetenv(void) {
const char* name = "FOO";
const char* value = "BAR";
char* retrieved_value;
LOG_TEST_NAME("test_unsetenv");
gpr_setenv(name, value);
gpr_unsetenv(name);
retrieved_value = gpr_getenv(name);
GPR_ASSERT(retrieved_value == nullptr);
}
int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(argc, argv);
test_setenv_getenv();
test_unsetenv();
return 0;
}

@ -279,19 +279,20 @@ static void test_memrchr(void) {
GPR_ASSERT(0 == strcmp((const char*)gpr_memrchr("hello", 'l', 5), "lo"));
}
static void test_is_true(void) {
LOG_TEST_NAME("test_is_true");
GPR_ASSERT(true == gpr_is_true("True"));
GPR_ASSERT(true == gpr_is_true("true"));
GPR_ASSERT(true == gpr_is_true("TRUE"));
GPR_ASSERT(true == gpr_is_true("Yes"));
GPR_ASSERT(true == gpr_is_true("yes"));
GPR_ASSERT(true == gpr_is_true("YES"));
GPR_ASSERT(true == gpr_is_true("1"));
GPR_ASSERT(false == gpr_is_true(nullptr));
GPR_ASSERT(false == gpr_is_true(""));
GPR_ASSERT(false == gpr_is_true("0"));
static void test_parse_bool_value(void) {
LOG_TEST_NAME("test_parse_bool_value");
bool ret;
GPR_ASSERT(true == gpr_parse_bool_value("truE", &ret) && true == ret);
GPR_ASSERT(true == gpr_parse_bool_value("falsE", &ret) && false == ret);
GPR_ASSERT(true == gpr_parse_bool_value("1", &ret) && true == ret);
GPR_ASSERT(true == gpr_parse_bool_value("0", &ret) && false == ret);
GPR_ASSERT(true == gpr_parse_bool_value("Yes", &ret) && true == ret);
GPR_ASSERT(true == gpr_parse_bool_value("No", &ret) && false == ret);
GPR_ASSERT(true == gpr_parse_bool_value("Y", &ret) && true == ret);
GPR_ASSERT(true == gpr_parse_bool_value("N", &ret) && false == ret);
GPR_ASSERT(false == gpr_parse_bool_value(nullptr, &ret));
GPR_ASSERT(false == gpr_parse_bool_value("", &ret));
}
int main(int argc, char** argv) {
@ -307,6 +308,6 @@ int main(int argc, char** argv) {
test_leftpad();
test_stricmp();
test_memrchr();
test_is_true();
test_parse_bool_value();
return 0;
}

@ -28,6 +28,32 @@ grpc_cc_test(
],
)
grpc_cc_test(
name = "global_config_test",
srcs = ["global_config_test.cc"],
external_deps = [
"gtest",
],
language = "C++",
deps = [
"//:gpr",
"//test/core/util:grpc_test_util",
],
)
grpc_cc_test(
name = "global_config_env_test",
srcs = ["global_config_env_test.cc"],
external_deps = [
"gtest",
],
language = "C++",
deps = [
"//:gpr",
"//test/core/util:grpc_test_util",
],
)
grpc_cc_test(
name = "manual_constructor_test",
srcs = ["manual_constructor_test.cc"],

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

Loading…
Cancel
Save