diff --git a/.clang-format b/.clang-format index 4b3f13fa55e..3b2451958b3 100644 --- a/.clang-format +++ b/.clang-format @@ -1,5 +1,7 @@ --- Language: Cpp BasedOnStyle: Google +DerivePointerAlignment: false +PointerAlignment: Left ... diff --git a/.clang_complete b/.clang_complete index 4c4a86f0be9..aa77554f4ee 100644 --- a/.clang_complete +++ b/.clang_complete @@ -10,3 +10,8 @@ -Ithird_party/zlib -Ithird_party/protobuf/src -Ithird_party/abseil-cpp +-Ithird_party/cares/cares +-Ithird_party/cares +-Ithird_party/googletest/googletest/include +-Ithird_party/googletest/googlemock/include + diff --git a/.gitignore b/.gitignore index 5ccad2e4f2f..2b35c5fb9a3 100644 --- a/.gitignore +++ b/.gitignore @@ -56,6 +56,7 @@ Gemfile.lock # Temporary test reports report.xml +*/sponge_log.xml latency_trace.txt latency_trace.*.txt @@ -120,6 +121,7 @@ gdb.txt tags # perf data +memory_usage.csv perf.data perf.data.old diff --git a/BUILD b/BUILD index f2848fdfc8b..13843195ea7 100644 --- a/BUILD +++ b/BUILD @@ -33,6 +33,16 @@ load( "grpc_generate_one_off_targets", ) +config_setting( + name = "grpc_no_ares", + values = {"define": "grpc_no_ares=true"}, +) + +config_setting( + name = "remote_execution", + values = {"define": "GRPC_PORT_ISOLATED_RUNTIME=1"}, +) + # This should be updated along with build.yaml g_stands_for = "generous" @@ -49,7 +59,6 @@ GPR_PUBLIC_HDRS = [ "include/grpc/support/avl.h", "include/grpc/support/cmdline.h", "include/grpc/support/cpu.h", - "include/grpc/support/histogram.h", "include/grpc/support/host_port.h", "include/grpc/support/log.h", "include/grpc/support/log_windows.h", @@ -74,10 +83,11 @@ GRPC_PUBLIC_HDRS = [ "include/grpc/byte_buffer.h", "include/grpc/byte_buffer_reader.h", "include/grpc/compression.h", - "include/grpc/load_reporting.h", + "include/grpc/fork.h", "include/grpc/grpc.h", "include/grpc/grpc_posix.h", "include/grpc/grpc_security_constants.h", + "include/grpc/load_reporting.h", "include/grpc/slice.h", "include/grpc/slice_buffer.h", "include/grpc/status.h", @@ -413,7 +423,6 @@ grpc_cc_library( ], external_deps = [ "nanopb", - "libssl", ], language = "c++", public_hdrs = [ @@ -441,7 +450,7 @@ grpc_cc_library( "src/core/lib/support/env_linux.cc", "src/core/lib/support/env_posix.cc", "src/core/lib/support/env_windows.cc", - "src/core/lib/support/histogram.cc", + "src/core/lib/support/fork.cc", "src/core/lib/support/host_port.cc", "src/core/lib/support/log.cc", "src/core/lib/support/log_android.cc", @@ -450,7 +459,6 @@ grpc_cc_library( "src/core/lib/support/log_windows.cc", "src/core/lib/support/mpscq.cc", "src/core/lib/support/murmur_hash.cc", - "src/core/lib/support/stack_lockfree.cc", "src/core/lib/support/string.cc", "src/core/lib/support/string_posix.cc", "src/core/lib/support/string_util_windows.cc", @@ -475,28 +483,30 @@ grpc_cc_library( ], hdrs = [ "src/core/lib/profiling/timers.h", + "src/core/lib/support/abstract.h", "src/core/lib/support/arena.h", "src/core/lib/support/atomic.h", "src/core/lib/support/atomic_with_atm.h", "src/core/lib/support/atomic_with_std.h", "src/core/lib/support/env.h", - "src/core/lib/support/memory.h", - "src/core/lib/support/vector.h", + "src/core/lib/support/fork.h", "src/core/lib/support/manual_constructor.h", + "src/core/lib/support/memory.h", "src/core/lib/support/mpscq.h", "src/core/lib/support/murmur_hash.h", "src/core/lib/support/spinlock.h", - "src/core/lib/support/stack_lockfree.h", "src/core/lib/support/string.h", "src/core/lib/support/string_windows.h", + "src/core/lib/support/thd_internal.h", "src/core/lib/support/time_precise.h", "src/core/lib/support/tmpfile.h", + "src/core/lib/support/vector.h", ], language = "c++", public_hdrs = GPR_PUBLIC_HDRS, deps = [ "gpr_codegen", - "@com_google_absl//absl/container:inlined_vector" + "@com_google_absl//absl/container:inlined_vector", ], ) @@ -508,6 +518,7 @@ grpc_cc_library( "include/grpc/impl/codegen/atm_gcc_atomic.h", "include/grpc/impl/codegen/atm_gcc_sync.h", "include/grpc/impl/codegen/atm_windows.h", + "include/grpc/impl/codegen/fork.h", "include/grpc/impl/codegen/gpr_slice.h", "include/grpc/impl/codegen/gpr_types.h", "include/grpc/impl/codegen/port_platform.h", @@ -531,6 +542,28 @@ grpc_cc_library( ], ) +grpc_cc_library( + name = "debug_location", + public_hdrs = ["src/core/lib/support/debug_location.h"], + language = "c++", +) + +grpc_cc_library( + name = "ref_counted", + public_hdrs = ["src/core/lib/support/ref_counted.h"], + language = "c++", + deps = [ + "grpc_trace", + "debug_location", + ], +) + +grpc_cc_library( + name = "ref_counted_ptr", + public_hdrs = ["src/core/lib/support/ref_counted_ptr.h"], + language = "c++", +) + grpc_cc_library( name = "grpc_base_c", srcs = [ @@ -553,7 +586,6 @@ grpc_cc_library( "src/core/lib/http/httpcli.cc", "src/core/lib/http/parser.cc", "src/core/lib/iomgr/call_combiner.cc", - "src/core/lib/iomgr/closure.cc", "src/core/lib/iomgr/combiner.cc", "src/core/lib/iomgr/endpoint.cc", "src/core/lib/iomgr/endpoint_pair_posix.cc", @@ -568,6 +600,8 @@ grpc_cc_library( "src/core/lib/iomgr/ev_windows.cc", "src/core/lib/iomgr/exec_ctx.cc", "src/core/lib/iomgr/executor.cc", + "src/core/lib/iomgr/fork_posix.cc", + "src/core/lib/iomgr/fork_windows.cc", "src/core/lib/iomgr/gethostname_fallback.cc", "src/core/lib/iomgr/gethostname_host_name_max.cc", "src/core/lib/iomgr/gethostname_sysconf.cc", @@ -667,6 +701,7 @@ grpc_cc_library( "src/core/lib/transport/transport_op_string.cc", ], hdrs = [ + "src/core/lib/backoff/backoff.h", "src/core/lib/channel/channel_args.h", "src/core/lib/channel/channel_stack.h", "src/core/lib/channel/channel_stack_builder.h", @@ -685,6 +720,7 @@ grpc_cc_library( "src/core/lib/http/format_request.h", "src/core/lib/http/httpcli.h", "src/core/lib/http/parser.h", + "src/core/lib/iomgr/block_annotate.h", "src/core/lib/iomgr/call_combiner.h", "src/core/lib/iomgr/closure.h", "src/core/lib/iomgr/combiner.h", @@ -729,7 +765,6 @@ grpc_cc_library( "src/core/lib/iomgr/socket_utils_posix.h", "src/core/lib/iomgr/socket_windows.h", "src/core/lib/iomgr/sys_epoll_wrapper.h", - "src/core/lib/iomgr/block_annotate.h", "src/core/lib/iomgr/tcp_client.h", "src/core/lib/iomgr/tcp_client_posix.h", "src/core/lib/iomgr/tcp_posix.h", @@ -785,7 +820,6 @@ grpc_cc_library( "src/core/lib/transport/timeout_encoding.h", "src/core/lib/transport/transport.h", "src/core/lib/transport/transport_impl.h", - "src/core/lib/backoff/backoff.h", ], external_deps = [ "zlib", @@ -1245,8 +1279,8 @@ grpc_cc_library( "src/core/ext/transport/chttp2/transport/bin_decoder.h", "src/core/ext/transport/chttp2/transport/bin_encoder.h", "src/core/ext/transport/chttp2/transport/chttp2_transport.h", - "src/core/ext/transport/chttp2/transport/frame.h", "src/core/ext/transport/chttp2/transport/flow_control.h", + "src/core/ext/transport/chttp2/transport/frame.h", "src/core/ext/transport/chttp2/transport/frame_data.h", "src/core/ext/transport/chttp2/transport/frame_goaway.h", "src/core/ext/transport/chttp2/transport/frame_ping.h", @@ -1545,7 +1579,7 @@ grpc_cc_library( grpc_cc_library( name = "grpc++_config_proto", external_deps = [ - "protobuf", + "protobuf_headers", ], language = "c++", public_hdrs = [ diff --git a/CMakeLists.txt b/CMakeLists.txt index c20c97d61a2..22a1ab79af1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -24,7 +24,7 @@ cmake_minimum_required(VERSION 2.8) set(PACKAGE_NAME "grpc") -set(PACKAGE_VERSION "1.8.0-dev") +set(PACKAGE_VERSION "1.9.0-dev") set(PACKAGE_STRING "${PACKAGE_NAME} ${PACKAGE_VERSION}") set(PACKAGE_TARNAME "${PACKAGE_NAME}-${PACKAGE_VERSION}") set(PACKAGE_BUGREPORT "https://github.com/grpc/grpc/issues/") @@ -235,6 +235,7 @@ if("${gRPC_SSL_PROVIDER}" STREQUAL "module") elseif("${gRPC_SSL_PROVIDER}" STREQUAL "package") find_package(OpenSSL REQUIRED) set(_gRPC_SSL_LIBRARIES ${OPENSSL_LIBRARIES}) + include_directories(${OPENSSL_INCLUDE_DIR}) set(_gRPC_FIND_SSL "if(NOT OPENSSL_FOUND)\n find_package(OpenSSL)\nendif()") endif() @@ -427,12 +428,11 @@ add_dependencies(buildtests_c gpr_avl_test) add_dependencies(buildtests_c gpr_cmdline_test) add_dependencies(buildtests_c gpr_cpu_test) add_dependencies(buildtests_c gpr_env_test) -add_dependencies(buildtests_c gpr_histogram_test) add_dependencies(buildtests_c gpr_host_port_test) add_dependencies(buildtests_c gpr_log_test) +add_dependencies(buildtests_c gpr_manual_constructor_test) add_dependencies(buildtests_c gpr_mpscq_test) add_dependencies(buildtests_c gpr_spinlock_test) -add_dependencies(buildtests_c gpr_stack_lockfree_test) add_dependencies(buildtests_c gpr_string_test) add_dependencies(buildtests_c gpr_sync_test) add_dependencies(buildtests_c gpr_thd_test) @@ -462,6 +462,10 @@ endif() if(_gRPC_PLATFORM_LINUX) add_dependencies(buildtests_c handshake_server) endif() +if(_gRPC_PLATFORM_LINUX) +add_dependencies(buildtests_c handshake_server_with_readahead_handshaker) +endif() +add_dependencies(buildtests_c histogram_test) add_dependencies(buildtests_c hpack_parser_test) add_dependencies(buildtests_c hpack_table_test) add_dependencies(buildtests_c http_parser_test) @@ -674,7 +678,9 @@ add_dependencies(buildtests_cxx bm_pollset) endif() add_dependencies(buildtests_cxx channel_arguments_test) add_dependencies(buildtests_cxx channel_filter_test) +add_dependencies(buildtests_cxx chttp2_settings_timeout_test) add_dependencies(buildtests_cxx cli_call_test) +add_dependencies(buildtests_cxx client_channel_stress_test) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_dependencies(buildtests_cxx client_crash_test) endif() @@ -734,6 +740,8 @@ endif() add_dependencies(buildtests_cxx qps_worker) add_dependencies(buildtests_cxx reconnect_interop_client) add_dependencies(buildtests_cxx reconnect_interop_server) +add_dependencies(buildtests_cxx ref_counted_ptr_test) +add_dependencies(buildtests_cxx ref_counted_test) add_dependencies(buildtests_cxx secure_auth_context_test) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_dependencies(buildtests_cxx secure_sync_unary_ping_pong_test) @@ -756,7 +764,6 @@ add_dependencies(buildtests_cxx stress_test) add_dependencies(buildtests_cxx thread_manager_test) add_dependencies(buildtests_cxx thread_stress_test) add_dependencies(buildtests_cxx transport_pid_controller_test) -add_dependencies(buildtests_cxx vector_test) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_dependencies(buildtests_cxx writes_per_rpc_test) endif() @@ -793,7 +800,7 @@ add_library(gpr src/core/lib/support/env_linux.cc src/core/lib/support/env_posix.cc src/core/lib/support/env_windows.cc - src/core/lib/support/histogram.cc + src/core/lib/support/fork.cc src/core/lib/support/host_port.cc src/core/lib/support/log.cc src/core/lib/support/log_android.cc @@ -802,7 +809,6 @@ add_library(gpr src/core/lib/support/log_windows.cc src/core/lib/support/mpscq.cc src/core/lib/support/murmur_hash.cc - src/core/lib/support/stack_lockfree.cc src/core/lib/support/string.cc src/core/lib/support/string_posix.cc src/core/lib/support/string_util_windows.cc @@ -849,7 +855,6 @@ target_include_directories(gpr PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gpr @@ -865,7 +870,6 @@ foreach(_hdr include/grpc/support/avl.h include/grpc/support/cmdline.h include/grpc/support/cpu.h - include/grpc/support/histogram.h include/grpc/support/host_port.h include/grpc/support/log.h include/grpc/support/log_windows.h @@ -888,6 +892,7 @@ foreach(_hdr include/grpc/impl/codegen/atm_gcc_atomic.h include/grpc/impl/codegen/atm_gcc_sync.h include/grpc/impl/codegen/atm_windows.h + include/grpc/impl/codegen/fork.h include/grpc/impl/codegen/gpr_slice.h include/grpc/impl/codegen/gpr_types.h include/grpc/impl/codegen/port_platform.h @@ -916,7 +921,7 @@ endif() if (gRPC_BUILD_TESTS) add_library(gpr_test_util - test/core/util/test_config.c + test/core/util/test_config.cc ) if(WIN32 AND MSVC) @@ -942,7 +947,6 @@ target_include_directories(gpr_test_util PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gpr_test_util @@ -974,7 +978,6 @@ add_library(grpc src/core/lib/http/httpcli.cc src/core/lib/http/parser.cc src/core/lib/iomgr/call_combiner.cc - src/core/lib/iomgr/closure.cc src/core/lib/iomgr/combiner.cc src/core/lib/iomgr/endpoint.cc src/core/lib/iomgr/endpoint_pair_posix.cc @@ -989,6 +992,8 @@ add_library(grpc src/core/lib/iomgr/ev_windows.cc src/core/lib/iomgr/exec_ctx.cc src/core/lib/iomgr/executor.cc + src/core/lib/iomgr/fork_posix.cc + src/core/lib/iomgr/fork_windows.cc src/core/lib/iomgr/gethostname_fallback.cc src/core/lib/iomgr/gethostname_host_name_max.cc src/core/lib/iomgr/gethostname_sysconf.cc @@ -1229,7 +1234,6 @@ target_include_directories(grpc PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc @@ -1255,6 +1259,7 @@ foreach(_hdr include/grpc/impl/codegen/atm_gcc_atomic.h include/grpc/impl/codegen/atm_gcc_sync.h include/grpc/impl/codegen/atm_windows.h + include/grpc/impl/codegen/fork.h include/grpc/impl/codegen/gpr_slice.h include/grpc/impl/codegen/gpr_types.h include/grpc/impl/codegen/port_platform.h @@ -1267,6 +1272,7 @@ foreach(_hdr include/grpc/byte_buffer.h include/grpc/byte_buffer_reader.h include/grpc/compression.h + include/grpc/fork.h include/grpc/grpc.h include/grpc/grpc_posix.h include/grpc/grpc_security_constants.h @@ -1315,7 +1321,6 @@ add_library(grpc_cronet src/core/lib/http/httpcli.cc src/core/lib/http/parser.cc src/core/lib/iomgr/call_combiner.cc - src/core/lib/iomgr/closure.cc src/core/lib/iomgr/combiner.cc src/core/lib/iomgr/endpoint.cc src/core/lib/iomgr/endpoint_pair_posix.cc @@ -1330,6 +1335,8 @@ add_library(grpc_cronet src/core/lib/iomgr/ev_windows.cc src/core/lib/iomgr/exec_ctx.cc src/core/lib/iomgr/executor.cc + src/core/lib/iomgr/fork_posix.cc + src/core/lib/iomgr/fork_windows.cc src/core/lib/iomgr/gethostname_fallback.cc src/core/lib/iomgr/gethostname_host_name_max.cc src/core/lib/iomgr/gethostname_sysconf.cc @@ -1541,7 +1548,6 @@ target_include_directories(grpc_cronet PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_cronet @@ -1567,6 +1573,7 @@ foreach(_hdr include/grpc/impl/codegen/atm_gcc_atomic.h include/grpc/impl/codegen/atm_gcc_sync.h include/grpc/impl/codegen/atm_windows.h + include/grpc/impl/codegen/fork.h include/grpc/impl/codegen/gpr_slice.h include/grpc/impl/codegen/gpr_types.h include/grpc/impl/codegen/port_platform.h @@ -1598,26 +1605,29 @@ endif() if (gRPC_BUILD_TESTS) add_library(grpc_test_util - test/core/end2end/data/client_certs.c - test/core/end2end/data/server1_cert.c - test/core/end2end/data/server1_key.c - test/core/end2end/data/test_root_cert.c - test/core/security/oauth2_utils.c + test/core/end2end/data/client_certs.cc + test/core/end2end/data/server1_cert.cc + test/core/end2end/data/server1_key.cc + test/core/end2end/data/test_root_cert.cc + test/core/security/oauth2_utils.cc src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc - test/core/end2end/cq_verifier.c - test/core/end2end/fixtures/http_proxy_fixture.c - test/core/end2end/fixtures/proxy.c - test/core/iomgr/endpoint_tests.c + test/core/end2end/cq_verifier.cc + test/core/end2end/fixtures/http_proxy_fixture.cc + test/core/end2end/fixtures/proxy.cc + test/core/iomgr/endpoint_tests.cc test/core/util/debugger_macros.cc - test/core/util/grpc_profiler.c - test/core/util/memory_counters.c - test/core/util/mock_endpoint.c - test/core/util/parse_hexstring.c - test/core/util/passthru_endpoint.c - test/core/util/port.c - test/core/util/port_server_client.c - test/core/util/slice_splitter.c - test/core/util/trickle_endpoint.c + test/core/util/grpc_profiler.cc + test/core/util/histogram.cc + test/core/util/memory_counters.cc + test/core/util/mock_endpoint.cc + test/core/util/parse_hexstring.cc + test/core/util/passthru_endpoint.cc + test/core/util/port.cc + test/core/util/port_isolated_runtime_environment.cc + test/core/util/port_server_client.cc + test/core/util/slice_splitter.cc + test/core/util/tracer_util.cc + test/core/util/trickle_endpoint.cc src/core/lib/backoff/backoff.cc src/core/lib/channel/channel_args.cc src/core/lib/channel/channel_stack.cc @@ -1637,7 +1647,6 @@ add_library(grpc_test_util src/core/lib/http/httpcli.cc src/core/lib/http/parser.cc src/core/lib/iomgr/call_combiner.cc - src/core/lib/iomgr/closure.cc src/core/lib/iomgr/combiner.cc src/core/lib/iomgr/endpoint.cc src/core/lib/iomgr/endpoint_pair_posix.cc @@ -1652,6 +1661,8 @@ add_library(grpc_test_util src/core/lib/iomgr/ev_windows.cc src/core/lib/iomgr/exec_ctx.cc src/core/lib/iomgr/executor.cc + src/core/lib/iomgr/fork_posix.cc + src/core/lib/iomgr/fork_windows.cc src/core/lib/iomgr/gethostname_fallback.cc src/core/lib/iomgr/gethostname_host_name_max.cc src/core/lib/iomgr/gethostname_sysconf.cc @@ -1825,7 +1836,6 @@ target_include_directories(grpc_test_util PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_test_util @@ -1849,6 +1859,7 @@ foreach(_hdr include/grpc/impl/codegen/atm_gcc_atomic.h include/grpc/impl/codegen/atm_gcc_sync.h include/grpc/impl/codegen/atm_windows.h + include/grpc/impl/codegen/fork.h include/grpc/impl/codegen/gpr_slice.h include/grpc/impl/codegen/gpr_types.h include/grpc/impl/codegen/port_platform.h @@ -1870,20 +1881,23 @@ if (gRPC_BUILD_TESTS) add_library(grpc_test_util_unsecure src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc - test/core/end2end/cq_verifier.c - test/core/end2end/fixtures/http_proxy_fixture.c - test/core/end2end/fixtures/proxy.c - test/core/iomgr/endpoint_tests.c + test/core/end2end/cq_verifier.cc + test/core/end2end/fixtures/http_proxy_fixture.cc + test/core/end2end/fixtures/proxy.cc + test/core/iomgr/endpoint_tests.cc test/core/util/debugger_macros.cc - test/core/util/grpc_profiler.c - test/core/util/memory_counters.c - test/core/util/mock_endpoint.c - test/core/util/parse_hexstring.c - test/core/util/passthru_endpoint.c - test/core/util/port.c - test/core/util/port_server_client.c - test/core/util/slice_splitter.c - test/core/util/trickle_endpoint.c + test/core/util/grpc_profiler.cc + test/core/util/histogram.cc + test/core/util/memory_counters.cc + test/core/util/mock_endpoint.cc + test/core/util/parse_hexstring.cc + test/core/util/passthru_endpoint.cc + test/core/util/port.cc + test/core/util/port_isolated_runtime_environment.cc + test/core/util/port_server_client.cc + test/core/util/slice_splitter.cc + test/core/util/tracer_util.cc + test/core/util/trickle_endpoint.cc src/core/lib/backoff/backoff.cc src/core/lib/channel/channel_args.cc src/core/lib/channel/channel_stack.cc @@ -1903,7 +1917,6 @@ add_library(grpc_test_util_unsecure src/core/lib/http/httpcli.cc src/core/lib/http/parser.cc src/core/lib/iomgr/call_combiner.cc - src/core/lib/iomgr/closure.cc src/core/lib/iomgr/combiner.cc src/core/lib/iomgr/endpoint.cc src/core/lib/iomgr/endpoint_pair_posix.cc @@ -1918,6 +1931,8 @@ add_library(grpc_test_util_unsecure src/core/lib/iomgr/ev_windows.cc src/core/lib/iomgr/exec_ctx.cc src/core/lib/iomgr/executor.cc + src/core/lib/iomgr/fork_posix.cc + src/core/lib/iomgr/fork_windows.cc src/core/lib/iomgr/gethostname_fallback.cc src/core/lib/iomgr/gethostname_host_name_max.cc src/core/lib/iomgr/gethostname_sysconf.cc @@ -2091,7 +2106,6 @@ target_include_directories(grpc_test_util_unsecure PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_test_util_unsecure @@ -2115,6 +2129,7 @@ foreach(_hdr include/grpc/impl/codegen/atm_gcc_atomic.h include/grpc/impl/codegen/atm_gcc_sync.h include/grpc/impl/codegen/atm_windows.h + include/grpc/impl/codegen/fork.h include/grpc/impl/codegen/gpr_slice.h include/grpc/impl/codegen/gpr_types.h include/grpc/impl/codegen/port_platform.h @@ -2155,7 +2170,6 @@ add_library(grpc_unsecure src/core/lib/http/httpcli.cc src/core/lib/http/parser.cc src/core/lib/iomgr/call_combiner.cc - src/core/lib/iomgr/closure.cc src/core/lib/iomgr/combiner.cc src/core/lib/iomgr/endpoint.cc src/core/lib/iomgr/endpoint_pair_posix.cc @@ -2170,6 +2184,8 @@ add_library(grpc_unsecure src/core/lib/iomgr/ev_windows.cc src/core/lib/iomgr/exec_ctx.cc src/core/lib/iomgr/executor.cc + src/core/lib/iomgr/fork_posix.cc + src/core/lib/iomgr/fork_windows.cc src/core/lib/iomgr/gethostname_fallback.cc src/core/lib/iomgr/gethostname_host_name_max.cc src/core/lib/iomgr/gethostname_sysconf.cc @@ -2378,7 +2394,6 @@ target_include_directories(grpc_unsecure PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_unsecure @@ -2403,6 +2418,7 @@ foreach(_hdr include/grpc/impl/codegen/atm_gcc_atomic.h include/grpc/impl/codegen/atm_gcc_sync.h include/grpc/impl/codegen/atm_windows.h + include/grpc/impl/codegen/fork.h include/grpc/impl/codegen/gpr_slice.h include/grpc/impl/codegen/gpr_types.h include/grpc/impl/codegen/port_platform.h @@ -2414,6 +2430,7 @@ foreach(_hdr include/grpc/byte_buffer.h include/grpc/byte_buffer_reader.h include/grpc/compression.h + include/grpc/fork.h include/grpc/grpc.h include/grpc/grpc_posix.h include/grpc/grpc_security_constants.h @@ -2443,7 +2460,7 @@ endif() if (gRPC_BUILD_TESTS) add_library(reconnect_server - test/core/util/reconnect_server.c + test/core/util/reconnect_server.cc ) if(WIN32 AND MSVC) @@ -2469,7 +2486,6 @@ target_include_directories(reconnect_server PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(reconnect_server @@ -2486,7 +2502,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_library(test_tcp_server - test/core/util/test_tcp_server.c + test/core/util/test_tcp_server.cc ) if(WIN32 AND MSVC) @@ -2512,7 +2528,6 @@ target_include_directories(test_tcp_server PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(test_tcp_server @@ -2594,7 +2609,6 @@ target_include_directories(grpc++ PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE ${_gRPC_PROTO_GENS_DIR} ) @@ -2661,7 +2675,6 @@ foreach(_hdr include/grpc/support/avl.h include/grpc/support/cmdline.h include/grpc/support/cpu.h - include/grpc/support/histogram.h include/grpc/support/host_port.h include/grpc/support/log.h include/grpc/support/log_windows.h @@ -2684,6 +2697,7 @@ foreach(_hdr include/grpc/impl/codegen/atm_gcc_atomic.h include/grpc/impl/codegen/atm_gcc_sync.h include/grpc/impl/codegen/atm_windows.h + include/grpc/impl/codegen/fork.h include/grpc/impl/codegen/gpr_slice.h include/grpc/impl/codegen/gpr_types.h include/grpc/impl/codegen/port_platform.h @@ -2695,6 +2709,7 @@ foreach(_hdr include/grpc/byte_buffer.h include/grpc/byte_buffer_reader.h include/grpc/compression.h + include/grpc/fork.h include/grpc/grpc.h include/grpc/grpc_posix.h include/grpc/grpc_security_constants.h @@ -2797,7 +2812,6 @@ target_include_directories(grpc++_core_stats PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -2906,7 +2920,6 @@ add_library(grpc++_cronet src/core/lib/http/httpcli.cc src/core/lib/http/parser.cc src/core/lib/iomgr/call_combiner.cc - src/core/lib/iomgr/closure.cc src/core/lib/iomgr/combiner.cc src/core/lib/iomgr/endpoint.cc src/core/lib/iomgr/endpoint_pair_posix.cc @@ -2921,6 +2934,8 @@ add_library(grpc++_cronet src/core/lib/iomgr/ev_windows.cc src/core/lib/iomgr/exec_ctx.cc src/core/lib/iomgr/executor.cc + src/core/lib/iomgr/fork_posix.cc + src/core/lib/iomgr/fork_windows.cc src/core/lib/iomgr/gethostname_fallback.cc src/core/lib/iomgr/gethostname_host_name_max.cc src/core/lib/iomgr/gethostname_sysconf.cc @@ -3079,7 +3094,6 @@ target_include_directories(grpc++_cronet PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE ${_gRPC_PROTO_GENS_DIR} ) @@ -3147,7 +3161,6 @@ foreach(_hdr include/grpc/support/avl.h include/grpc/support/cmdline.h include/grpc/support/cpu.h - include/grpc/support/histogram.h include/grpc/support/host_port.h include/grpc/support/log.h include/grpc/support/log_windows.h @@ -3170,6 +3183,7 @@ foreach(_hdr include/grpc/impl/codegen/atm_gcc_atomic.h include/grpc/impl/codegen/atm_gcc_sync.h include/grpc/impl/codegen/atm_windows.h + include/grpc/impl/codegen/fork.h include/grpc/impl/codegen/gpr_slice.h include/grpc/impl/codegen/gpr_types.h include/grpc/impl/codegen/port_platform.h @@ -3181,6 +3195,7 @@ foreach(_hdr include/grpc/byte_buffer.h include/grpc/byte_buffer_reader.h include/grpc/compression.h + include/grpc/fork.h include/grpc/grpc.h include/grpc/grpc_posix.h include/grpc/grpc_security_constants.h @@ -3281,7 +3296,6 @@ target_include_directories(grpc++_error_details PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE ${_gRPC_PROTO_GENS_DIR} ) @@ -3347,7 +3361,6 @@ target_include_directories(grpc++_proto_reflection_desc_db PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -3409,7 +3422,6 @@ target_include_directories(grpc++_reflection PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE ${_gRPC_PROTO_GENS_DIR} ) @@ -3468,7 +3480,6 @@ target_include_directories(grpc++_test_config PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -3547,7 +3558,6 @@ target_include_directories(grpc++_test_util PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -3607,6 +3617,7 @@ foreach(_hdr include/grpc/impl/codegen/atm_gcc_atomic.h include/grpc/impl/codegen/atm_gcc_sync.h include/grpc/impl/codegen/atm_windows.h + include/grpc/impl/codegen/fork.h include/grpc/impl/codegen/gpr_slice.h include/grpc/impl/codegen/gpr_types.h include/grpc/impl/codegen/port_platform.h @@ -3688,7 +3699,6 @@ target_include_directories(grpc++_test_util_unsecure PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -3748,6 +3758,7 @@ foreach(_hdr include/grpc/impl/codegen/atm_gcc_atomic.h include/grpc/impl/codegen/atm_gcc_sync.h include/grpc/impl/codegen/atm_windows.h + include/grpc/impl/codegen/fork.h include/grpc/impl/codegen/gpr_slice.h include/grpc/impl/codegen/gpr_types.h include/grpc/impl/codegen/port_platform.h @@ -3831,7 +3842,6 @@ target_include_directories(grpc++_unsecure PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE ${_gRPC_PROTO_GENS_DIR} ) @@ -3897,7 +3907,6 @@ foreach(_hdr include/grpc/support/avl.h include/grpc/support/cmdline.h include/grpc/support/cpu.h - include/grpc/support/histogram.h include/grpc/support/host_port.h include/grpc/support/log.h include/grpc/support/log_windows.h @@ -3920,6 +3929,7 @@ foreach(_hdr include/grpc/impl/codegen/atm_gcc_atomic.h include/grpc/impl/codegen/atm_gcc_sync.h include/grpc/impl/codegen/atm_windows.h + include/grpc/impl/codegen/fork.h include/grpc/impl/codegen/gpr_slice.h include/grpc/impl/codegen/gpr_types.h include/grpc/impl/codegen/port_platform.h @@ -3931,6 +3941,7 @@ foreach(_hdr include/grpc/byte_buffer.h include/grpc/byte_buffer_reader.h include/grpc/compression.h + include/grpc/fork.h include/grpc/grpc.h include/grpc/grpc_posix.h include/grpc/grpc_security_constants.h @@ -4024,7 +4035,6 @@ target_include_directories(grpc_benchmark PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -4084,7 +4094,6 @@ target_include_directories(grpc_cli_libs PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -4145,7 +4154,6 @@ target_include_directories(grpc_plugin_support PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE ${_gRPC_PROTO_GENS_DIR} ) @@ -4224,7 +4232,6 @@ target_include_directories(http2_client_main PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -4280,7 +4287,6 @@ target_include_directories(interop_client_helper PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -4351,7 +4357,6 @@ target_include_directories(interop_client_main PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -4403,7 +4408,6 @@ target_include_directories(interop_server_helper PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -4473,7 +4477,6 @@ target_include_directories(interop_server_lib PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -4525,7 +4528,6 @@ target_include_directories(interop_server_main PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -4614,7 +4616,6 @@ target_include_directories(qps PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -4662,7 +4663,6 @@ target_include_directories(grpc_csharp_ext PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_csharp_ext @@ -4758,7 +4758,6 @@ target_include_directories(ares PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(ares @@ -4771,7 +4770,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_library(bad_client_test - test/core/bad_client/bad_client.c + test/core/bad_client/bad_client.cc ) if(WIN32 AND MSVC) @@ -4797,7 +4796,6 @@ target_include_directories(bad_client_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(bad_client_test @@ -4813,7 +4811,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_library(bad_ssl_test_server - test/core/bad_ssl/server_common.c + test/core/bad_ssl/server_common.cc ) if(WIN32 AND MSVC) @@ -4839,7 +4837,6 @@ target_include_directories(bad_ssl_test_server PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(bad_ssl_test_server @@ -4855,67 +4852,67 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_library(end2end_tests - test/core/end2end/end2end_tests.c - test/core/end2end/end2end_test_utils.c - test/core/end2end/tests/authority_not_supported.c - test/core/end2end/tests/bad_hostname.c - test/core/end2end/tests/bad_ping.c - test/core/end2end/tests/binary_metadata.c - test/core/end2end/tests/call_creds.c - test/core/end2end/tests/cancel_after_accept.c - test/core/end2end/tests/cancel_after_client_done.c - test/core/end2end/tests/cancel_after_invoke.c - test/core/end2end/tests/cancel_after_round_trip.c - test/core/end2end/tests/cancel_before_invoke.c - test/core/end2end/tests/cancel_in_a_vacuum.c - test/core/end2end/tests/cancel_with_status.c - test/core/end2end/tests/compressed_payload.c - test/core/end2end/tests/connectivity.c - test/core/end2end/tests/default_host.c - test/core/end2end/tests/disappearing_server.c - test/core/end2end/tests/empty_batch.c - test/core/end2end/tests/filter_call_init_fails.c - test/core/end2end/tests/filter_causes_close.c - test/core/end2end/tests/filter_latency.c - test/core/end2end/tests/graceful_server_shutdown.c - test/core/end2end/tests/high_initial_seqno.c - test/core/end2end/tests/hpack_size.c - test/core/end2end/tests/idempotent_request.c - test/core/end2end/tests/invoke_large_request.c - test/core/end2end/tests/keepalive_timeout.c - test/core/end2end/tests/large_metadata.c - test/core/end2end/tests/load_reporting_hook.c - test/core/end2end/tests/max_concurrent_streams.c - test/core/end2end/tests/max_connection_age.c - test/core/end2end/tests/max_connection_idle.c - test/core/end2end/tests/max_message_length.c - test/core/end2end/tests/negative_deadline.c - test/core/end2end/tests/network_status_change.c - test/core/end2end/tests/no_logging.c - test/core/end2end/tests/no_op.c - test/core/end2end/tests/payload.c - test/core/end2end/tests/ping.c - test/core/end2end/tests/ping_pong_streaming.c - test/core/end2end/tests/proxy_auth.c - test/core/end2end/tests/registered_call.c - test/core/end2end/tests/request_with_flags.c - test/core/end2end/tests/request_with_payload.c - test/core/end2end/tests/resource_quota_server.c - test/core/end2end/tests/server_finishes_request.c - test/core/end2end/tests/shutdown_finishes_calls.c - test/core/end2end/tests/shutdown_finishes_tags.c - test/core/end2end/tests/simple_cacheable_request.c - test/core/end2end/tests/simple_delayed_request.c - test/core/end2end/tests/simple_metadata.c - test/core/end2end/tests/simple_request.c - test/core/end2end/tests/stream_compression_compressed_payload.c - test/core/end2end/tests/stream_compression_payload.c - test/core/end2end/tests/stream_compression_ping_pong_streaming.c - test/core/end2end/tests/streaming_error_response.c - test/core/end2end/tests/trailing_metadata.c - test/core/end2end/tests/workaround_cronet_compression.c - test/core/end2end/tests/write_buffering.c - test/core/end2end/tests/write_buffering_at_end.c + test/core/end2end/end2end_tests.cc + test/core/end2end/end2end_test_utils.cc + test/core/end2end/tests/authority_not_supported.cc + test/core/end2end/tests/bad_hostname.cc + test/core/end2end/tests/bad_ping.cc + test/core/end2end/tests/binary_metadata.cc + test/core/end2end/tests/call_creds.cc + test/core/end2end/tests/cancel_after_accept.cc + test/core/end2end/tests/cancel_after_client_done.cc + test/core/end2end/tests/cancel_after_invoke.cc + test/core/end2end/tests/cancel_after_round_trip.cc + test/core/end2end/tests/cancel_before_invoke.cc + test/core/end2end/tests/cancel_in_a_vacuum.cc + test/core/end2end/tests/cancel_with_status.cc + test/core/end2end/tests/compressed_payload.cc + test/core/end2end/tests/connectivity.cc + test/core/end2end/tests/default_host.cc + test/core/end2end/tests/disappearing_server.cc + test/core/end2end/tests/empty_batch.cc + test/core/end2end/tests/filter_call_init_fails.cc + test/core/end2end/tests/filter_causes_close.cc + test/core/end2end/tests/filter_latency.cc + test/core/end2end/tests/graceful_server_shutdown.cc + test/core/end2end/tests/high_initial_seqno.cc + test/core/end2end/tests/hpack_size.cc + test/core/end2end/tests/idempotent_request.cc + test/core/end2end/tests/invoke_large_request.cc + test/core/end2end/tests/keepalive_timeout.cc + test/core/end2end/tests/large_metadata.cc + test/core/end2end/tests/load_reporting_hook.cc + test/core/end2end/tests/max_concurrent_streams.cc + test/core/end2end/tests/max_connection_age.cc + test/core/end2end/tests/max_connection_idle.cc + test/core/end2end/tests/max_message_length.cc + test/core/end2end/tests/negative_deadline.cc + test/core/end2end/tests/network_status_change.cc + test/core/end2end/tests/no_logging.cc + test/core/end2end/tests/no_op.cc + test/core/end2end/tests/payload.cc + test/core/end2end/tests/ping.cc + test/core/end2end/tests/ping_pong_streaming.cc + test/core/end2end/tests/proxy_auth.cc + test/core/end2end/tests/registered_call.cc + test/core/end2end/tests/request_with_flags.cc + test/core/end2end/tests/request_with_payload.cc + test/core/end2end/tests/resource_quota_server.cc + test/core/end2end/tests/server_finishes_request.cc + test/core/end2end/tests/shutdown_finishes_calls.cc + test/core/end2end/tests/shutdown_finishes_tags.cc + test/core/end2end/tests/simple_cacheable_request.cc + test/core/end2end/tests/simple_delayed_request.cc + test/core/end2end/tests/simple_metadata.cc + test/core/end2end/tests/simple_request.cc + test/core/end2end/tests/stream_compression_compressed_payload.cc + test/core/end2end/tests/stream_compression_payload.cc + test/core/end2end/tests/stream_compression_ping_pong_streaming.cc + test/core/end2end/tests/streaming_error_response.cc + test/core/end2end/tests/trailing_metadata.cc + test/core/end2end/tests/workaround_cronet_compression.cc + test/core/end2end/tests/write_buffering.cc + test/core/end2end/tests/write_buffering_at_end.cc ) if(WIN32 AND MSVC) @@ -4941,7 +4938,6 @@ target_include_directories(end2end_tests PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(end2end_tests @@ -4958,66 +4954,66 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_library(end2end_nosec_tests - test/core/end2end/end2end_nosec_tests.c - test/core/end2end/end2end_test_utils.c - test/core/end2end/tests/authority_not_supported.c - test/core/end2end/tests/bad_hostname.c - test/core/end2end/tests/bad_ping.c - test/core/end2end/tests/binary_metadata.c - test/core/end2end/tests/cancel_after_accept.c - test/core/end2end/tests/cancel_after_client_done.c - test/core/end2end/tests/cancel_after_invoke.c - test/core/end2end/tests/cancel_after_round_trip.c - test/core/end2end/tests/cancel_before_invoke.c - test/core/end2end/tests/cancel_in_a_vacuum.c - test/core/end2end/tests/cancel_with_status.c - test/core/end2end/tests/compressed_payload.c - test/core/end2end/tests/connectivity.c - test/core/end2end/tests/default_host.c - test/core/end2end/tests/disappearing_server.c - test/core/end2end/tests/empty_batch.c - test/core/end2end/tests/filter_call_init_fails.c - test/core/end2end/tests/filter_causes_close.c - test/core/end2end/tests/filter_latency.c - test/core/end2end/tests/graceful_server_shutdown.c - test/core/end2end/tests/high_initial_seqno.c - test/core/end2end/tests/hpack_size.c - test/core/end2end/tests/idempotent_request.c - test/core/end2end/tests/invoke_large_request.c - test/core/end2end/tests/keepalive_timeout.c - test/core/end2end/tests/large_metadata.c - test/core/end2end/tests/load_reporting_hook.c - test/core/end2end/tests/max_concurrent_streams.c - test/core/end2end/tests/max_connection_age.c - test/core/end2end/tests/max_connection_idle.c - test/core/end2end/tests/max_message_length.c - test/core/end2end/tests/negative_deadline.c - test/core/end2end/tests/network_status_change.c - test/core/end2end/tests/no_logging.c - test/core/end2end/tests/no_op.c - test/core/end2end/tests/payload.c - test/core/end2end/tests/ping.c - test/core/end2end/tests/ping_pong_streaming.c - test/core/end2end/tests/proxy_auth.c - test/core/end2end/tests/registered_call.c - test/core/end2end/tests/request_with_flags.c - test/core/end2end/tests/request_with_payload.c - test/core/end2end/tests/resource_quota_server.c - test/core/end2end/tests/server_finishes_request.c - test/core/end2end/tests/shutdown_finishes_calls.c - test/core/end2end/tests/shutdown_finishes_tags.c - test/core/end2end/tests/simple_cacheable_request.c - test/core/end2end/tests/simple_delayed_request.c - test/core/end2end/tests/simple_metadata.c - test/core/end2end/tests/simple_request.c - test/core/end2end/tests/stream_compression_compressed_payload.c - test/core/end2end/tests/stream_compression_payload.c - test/core/end2end/tests/stream_compression_ping_pong_streaming.c - test/core/end2end/tests/streaming_error_response.c - test/core/end2end/tests/trailing_metadata.c - test/core/end2end/tests/workaround_cronet_compression.c - test/core/end2end/tests/write_buffering.c - test/core/end2end/tests/write_buffering_at_end.c + test/core/end2end/end2end_nosec_tests.cc + test/core/end2end/end2end_test_utils.cc + test/core/end2end/tests/authority_not_supported.cc + test/core/end2end/tests/bad_hostname.cc + test/core/end2end/tests/bad_ping.cc + test/core/end2end/tests/binary_metadata.cc + test/core/end2end/tests/cancel_after_accept.cc + test/core/end2end/tests/cancel_after_client_done.cc + test/core/end2end/tests/cancel_after_invoke.cc + test/core/end2end/tests/cancel_after_round_trip.cc + test/core/end2end/tests/cancel_before_invoke.cc + test/core/end2end/tests/cancel_in_a_vacuum.cc + test/core/end2end/tests/cancel_with_status.cc + test/core/end2end/tests/compressed_payload.cc + test/core/end2end/tests/connectivity.cc + test/core/end2end/tests/default_host.cc + test/core/end2end/tests/disappearing_server.cc + test/core/end2end/tests/empty_batch.cc + test/core/end2end/tests/filter_call_init_fails.cc + test/core/end2end/tests/filter_causes_close.cc + test/core/end2end/tests/filter_latency.cc + test/core/end2end/tests/graceful_server_shutdown.cc + test/core/end2end/tests/high_initial_seqno.cc + test/core/end2end/tests/hpack_size.cc + test/core/end2end/tests/idempotent_request.cc + test/core/end2end/tests/invoke_large_request.cc + test/core/end2end/tests/keepalive_timeout.cc + test/core/end2end/tests/large_metadata.cc + test/core/end2end/tests/load_reporting_hook.cc + test/core/end2end/tests/max_concurrent_streams.cc + test/core/end2end/tests/max_connection_age.cc + test/core/end2end/tests/max_connection_idle.cc + test/core/end2end/tests/max_message_length.cc + test/core/end2end/tests/negative_deadline.cc + test/core/end2end/tests/network_status_change.cc + test/core/end2end/tests/no_logging.cc + test/core/end2end/tests/no_op.cc + test/core/end2end/tests/payload.cc + test/core/end2end/tests/ping.cc + test/core/end2end/tests/ping_pong_streaming.cc + test/core/end2end/tests/proxy_auth.cc + test/core/end2end/tests/registered_call.cc + test/core/end2end/tests/request_with_flags.cc + test/core/end2end/tests/request_with_payload.cc + test/core/end2end/tests/resource_quota_server.cc + test/core/end2end/tests/server_finishes_request.cc + test/core/end2end/tests/shutdown_finishes_calls.cc + test/core/end2end/tests/shutdown_finishes_tags.cc + test/core/end2end/tests/simple_cacheable_request.cc + test/core/end2end/tests/simple_delayed_request.cc + test/core/end2end/tests/simple_metadata.cc + test/core/end2end/tests/simple_request.cc + test/core/end2end/tests/stream_compression_compressed_payload.cc + test/core/end2end/tests/stream_compression_payload.cc + test/core/end2end/tests/stream_compression_ping_pong_streaming.cc + test/core/end2end/tests/streaming_error_response.cc + test/core/end2end/tests/trailing_metadata.cc + test/core/end2end/tests/workaround_cronet_compression.cc + test/core/end2end/tests/write_buffering.cc + test/core/end2end/tests/write_buffering_at_end.cc ) if(WIN32 AND MSVC) @@ -5043,7 +5039,6 @@ target_include_directories(end2end_nosec_tests PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(end2end_nosec_tests @@ -5060,7 +5055,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(alarm_test - test/core/surface/alarm_test.c + test/core/surface/alarm_test.cc ) @@ -5075,7 +5070,6 @@ target_include_directories(alarm_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(alarm_test @@ -5090,7 +5084,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(algorithm_test - test/core/compression/algorithm_test.c + test/core/compression/algorithm_test.cc ) @@ -5105,7 +5099,6 @@ target_include_directories(algorithm_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(algorithm_test @@ -5120,7 +5113,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(alloc_test - test/core/support/alloc_test.c + test/core/support/alloc_test.cc ) @@ -5135,7 +5128,6 @@ target_include_directories(alloc_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(alloc_test @@ -5148,7 +5140,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(alpn_test - test/core/transport/chttp2/alpn_test.c + test/core/transport/chttp2/alpn_test.cc ) @@ -5163,7 +5155,6 @@ target_include_directories(alpn_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(alpn_test @@ -5178,7 +5169,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(arena_test - test/core/support/arena_test.c + test/core/support/arena_test.cc ) @@ -5193,7 +5184,6 @@ target_include_directories(arena_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(arena_test @@ -5206,7 +5196,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(backoff_test - test/core/backoff/backoff_test.c + test/core/backoff/backoff_test.cc ) @@ -5221,7 +5211,6 @@ target_include_directories(backoff_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(backoff_test @@ -5236,7 +5225,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(bad_server_response_test - test/core/end2end/bad_server_response_test.c + test/core/end2end/bad_server_response_test.cc ) @@ -5251,7 +5240,6 @@ target_include_directories(bad_server_response_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(bad_server_response_test @@ -5267,7 +5255,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(bin_decoder_test - test/core/transport/chttp2/bin_decoder_test.c + test/core/transport/chttp2/bin_decoder_test.cc ) @@ -5282,7 +5270,6 @@ target_include_directories(bin_decoder_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(bin_decoder_test @@ -5295,7 +5282,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(bin_encoder_test - test/core/transport/chttp2/bin_encoder_test.c + test/core/transport/chttp2/bin_encoder_test.cc ) @@ -5310,7 +5297,6 @@ target_include_directories(bin_encoder_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(bin_encoder_test @@ -5323,7 +5309,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(byte_stream_test - test/core/transport/byte_stream_test.c + test/core/transport/byte_stream_test.cc ) @@ -5338,7 +5324,6 @@ target_include_directories(byte_stream_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(byte_stream_test @@ -5353,7 +5338,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(channel_create_test - test/core/surface/channel_create_test.c + test/core/surface/channel_create_test.cc ) @@ -5368,7 +5353,6 @@ target_include_directories(channel_create_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(channel_create_test @@ -5397,7 +5381,6 @@ target_include_directories(check_epollexclusive PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(check_epollexclusive @@ -5418,7 +5401,7 @@ endif() if (gRPC_BUILD_TESTS) add_executable(chttp2_hpack_encoder_test - test/core/transport/chttp2/hpack_encoder_test.c + test/core/transport/chttp2/hpack_encoder_test.cc ) @@ -5433,7 +5416,6 @@ target_include_directories(chttp2_hpack_encoder_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(chttp2_hpack_encoder_test @@ -5448,7 +5430,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(chttp2_stream_map_test - test/core/transport/chttp2/stream_map_test.c + test/core/transport/chttp2/stream_map_test.cc ) @@ -5463,7 +5445,6 @@ target_include_directories(chttp2_stream_map_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(chttp2_stream_map_test @@ -5478,7 +5459,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(chttp2_varint_test - test/core/transport/chttp2/varint_test.c + test/core/transport/chttp2/varint_test.cc ) @@ -5493,7 +5474,6 @@ target_include_directories(chttp2_varint_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(chttp2_varint_test @@ -5508,7 +5488,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(combiner_test - test/core/iomgr/combiner_test.c + test/core/iomgr/combiner_test.cc ) @@ -5523,7 +5503,6 @@ target_include_directories(combiner_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(combiner_test @@ -5538,7 +5517,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(compression_test - test/core/compression/compression_test.c + test/core/compression/compression_test.cc ) @@ -5553,7 +5532,6 @@ target_include_directories(compression_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(compression_test @@ -5568,7 +5546,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(concurrent_connectivity_test - test/core/surface/concurrent_connectivity_test.c + test/core/surface/concurrent_connectivity_test.cc ) @@ -5583,7 +5561,6 @@ target_include_directories(concurrent_connectivity_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(concurrent_connectivity_test @@ -5598,7 +5575,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(connection_refused_test - test/core/end2end/connection_refused_test.c + test/core/end2end/connection_refused_test.cc ) @@ -5613,7 +5590,6 @@ target_include_directories(connection_refused_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(connection_refused_test @@ -5628,7 +5604,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(dns_resolver_connectivity_test - test/core/client_channel/resolvers/dns_resolver_connectivity_test.c + test/core/client_channel/resolvers/dns_resolver_connectivity_test.cc ) @@ -5643,7 +5619,6 @@ target_include_directories(dns_resolver_connectivity_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(dns_resolver_connectivity_test @@ -5658,7 +5633,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(dns_resolver_test - test/core/client_channel/resolvers/dns_resolver_test.c + test/core/client_channel/resolvers/dns_resolver_test.cc ) @@ -5673,7 +5648,6 @@ target_include_directories(dns_resolver_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(dns_resolver_test @@ -5689,7 +5663,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(dualstack_socket_test - test/core/end2end/dualstack_socket_test.c + test/core/end2end/dualstack_socket_test.cc ) @@ -5704,7 +5678,6 @@ target_include_directories(dualstack_socket_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(dualstack_socket_test @@ -5720,7 +5693,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(endpoint_pair_test - test/core/iomgr/endpoint_pair_test.c + test/core/iomgr/endpoint_pair_test.cc ) @@ -5735,7 +5708,6 @@ target_include_directories(endpoint_pair_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(endpoint_pair_test @@ -5750,7 +5722,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(error_test - test/core/iomgr/error_test.c + test/core/iomgr/error_test.cc ) @@ -5765,7 +5737,6 @@ target_include_directories(error_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(error_test @@ -5781,7 +5752,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX) add_executable(ev_epollsig_linux_test - test/core/iomgr/ev_epollsig_linux_test.c + test/core/iomgr/ev_epollsig_linux_test.cc ) @@ -5796,7 +5767,6 @@ target_include_directories(ev_epollsig_linux_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(ev_epollsig_linux_test @@ -5812,7 +5782,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(fake_resolver_test - test/core/client_channel/resolvers/fake_resolver_test.c + test/core/client_channel/resolvers/fake_resolver_test.cc ) @@ -5827,7 +5797,6 @@ target_include_directories(fake_resolver_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(fake_resolver_test @@ -5843,8 +5812,8 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(fake_transport_security_test - test/core/tsi/fake_transport_security_test.c - test/core/tsi/transport_security_test_lib.c + test/core/tsi/fake_transport_security_test.cc + test/core/tsi/transport_security_test_lib.cc ) @@ -5859,7 +5828,6 @@ target_include_directories(fake_transport_security_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(fake_transport_security_test @@ -5875,7 +5843,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(fd_conservation_posix_test - test/core/iomgr/fd_conservation_posix_test.c + test/core/iomgr/fd_conservation_posix_test.cc ) @@ -5890,7 +5858,6 @@ target_include_directories(fd_conservation_posix_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(fd_conservation_posix_test @@ -5907,7 +5874,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(fd_posix_test - test/core/iomgr/fd_posix_test.c + test/core/iomgr/fd_posix_test.cc ) @@ -5922,7 +5889,6 @@ target_include_directories(fd_posix_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(fd_posix_test @@ -5938,7 +5904,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(fling_client - test/core/fling/client.c + test/core/fling/client.cc ) @@ -5953,7 +5919,6 @@ target_include_directories(fling_client PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(fling_client @@ -5968,7 +5933,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(fling_server - test/core/fling/server.c + test/core/fling/server.cc ) @@ -5983,7 +5948,6 @@ target_include_directories(fling_server PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(fling_server @@ -5999,7 +5963,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(fling_stream_test - test/core/fling/fling_stream_test.c + test/core/fling/fling_stream_test.cc ) @@ -6014,7 +5978,6 @@ target_include_directories(fling_stream_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(fling_stream_test @@ -6031,7 +5994,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(fling_test - test/core/fling/fling_test.c + test/core/fling/fling_test.cc ) @@ -6046,7 +6009,6 @@ target_include_directories(fling_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(fling_test @@ -6076,7 +6038,6 @@ target_include_directories(gen_hpack_tables PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gen_hpack_tables @@ -6111,7 +6072,6 @@ target_include_directories(gen_legal_metadata_characters PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gen_legal_metadata_characters @@ -6144,7 +6104,6 @@ target_include_directories(gen_percent_encoding_tables PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gen_percent_encoding_tables @@ -6164,7 +6123,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(goaway_server_test - test/core/end2end/goaway_server_test.c + test/core/end2end/goaway_server_test.cc ) @@ -6179,7 +6138,6 @@ target_include_directories(goaway_server_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(goaway_server_test @@ -6195,7 +6153,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(gpr_avl_test - test/core/support/avl_test.c + test/core/support/avl_test.cc ) @@ -6210,7 +6168,6 @@ target_include_directories(gpr_avl_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gpr_avl_test @@ -6223,7 +6180,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(gpr_cmdline_test - test/core/support/cmdline_test.c + test/core/support/cmdline_test.cc ) @@ -6238,7 +6195,6 @@ target_include_directories(gpr_cmdline_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gpr_cmdline_test @@ -6251,7 +6207,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(gpr_cpu_test - test/core/support/cpu_test.c + test/core/support/cpu_test.cc ) @@ -6266,7 +6222,6 @@ target_include_directories(gpr_cpu_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gpr_cpu_test @@ -6279,7 +6234,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(gpr_env_test - test/core/support/env_test.c + test/core/support/env_test.cc ) @@ -6294,7 +6249,6 @@ target_include_directories(gpr_env_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gpr_env_test @@ -6306,36 +6260,8 @@ target_link_libraries(gpr_env_test endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) -add_executable(gpr_histogram_test - test/core/support/histogram_test.c -) - - -target_include_directories(gpr_histogram_test - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include - PRIVATE ${BORINGSSL_ROOT_DIR}/include - PRIVATE ${PROTOBUF_ROOT_DIR}/src - PRIVATE ${BENCHMARK_ROOT_DIR}/include - PRIVATE ${ZLIB_ROOT_DIR} - PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/zlib - PRIVATE ${CARES_INCLUDE_DIR} - PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares - PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp -) - -target_link_libraries(gpr_histogram_test - ${_gRPC_ALLTARGETS_LIBRARIES} - gpr_test_util - gpr -) - -endif (gRPC_BUILD_TESTS) -if (gRPC_BUILD_TESTS) - add_executable(gpr_host_port_test - test/core/support/host_port_test.c + test/core/support/host_port_test.cc ) @@ -6350,7 +6276,6 @@ target_include_directories(gpr_host_port_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gpr_host_port_test @@ -6363,7 +6288,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(gpr_log_test - test/core/support/log_test.c + test/core/support/log_test.cc ) @@ -6378,7 +6303,6 @@ target_include_directories(gpr_log_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gpr_log_test @@ -6390,12 +6314,12 @@ target_link_libraries(gpr_log_test endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) -add_executable(gpr_mpscq_test - test/core/support/mpscq_test.c +add_executable(gpr_manual_constructor_test + test/core/support/manual_constructor_test.cc ) -target_include_directories(gpr_mpscq_test +target_include_directories(gpr_manual_constructor_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include PRIVATE ${BORINGSSL_ROOT_DIR}/include @@ -6406,10 +6330,9 @@ target_include_directories(gpr_mpscq_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) -target_link_libraries(gpr_mpscq_test +target_link_libraries(gpr_manual_constructor_test ${_gRPC_ALLTARGETS_LIBRARIES} gpr_test_util gpr @@ -6418,12 +6341,12 @@ target_link_libraries(gpr_mpscq_test endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) -add_executable(gpr_spinlock_test - test/core/support/spinlock_test.c +add_executable(gpr_mpscq_test + test/core/support/mpscq_test.cc ) -target_include_directories(gpr_spinlock_test +target_include_directories(gpr_mpscq_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include PRIVATE ${BORINGSSL_ROOT_DIR}/include @@ -6434,10 +6357,9 @@ target_include_directories(gpr_spinlock_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) -target_link_libraries(gpr_spinlock_test +target_link_libraries(gpr_mpscq_test ${_gRPC_ALLTARGETS_LIBRARIES} gpr_test_util gpr @@ -6446,12 +6368,12 @@ target_link_libraries(gpr_spinlock_test endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) -add_executable(gpr_stack_lockfree_test - test/core/support/stack_lockfree_test.c +add_executable(gpr_spinlock_test + test/core/support/spinlock_test.cc ) -target_include_directories(gpr_stack_lockfree_test +target_include_directories(gpr_spinlock_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include PRIVATE ${BORINGSSL_ROOT_DIR}/include @@ -6462,10 +6384,9 @@ target_include_directories(gpr_stack_lockfree_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) -target_link_libraries(gpr_stack_lockfree_test +target_link_libraries(gpr_spinlock_test ${_gRPC_ALLTARGETS_LIBRARIES} gpr_test_util gpr @@ -6475,7 +6396,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(gpr_string_test - test/core/support/string_test.c + test/core/support/string_test.cc ) @@ -6490,7 +6411,6 @@ target_include_directories(gpr_string_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gpr_string_test @@ -6503,7 +6423,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(gpr_sync_test - test/core/support/sync_test.c + test/core/support/sync_test.cc ) @@ -6518,7 +6438,6 @@ target_include_directories(gpr_sync_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gpr_sync_test @@ -6531,7 +6450,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(gpr_thd_test - test/core/support/thd_test.c + test/core/support/thd_test.cc ) @@ -6546,7 +6465,6 @@ target_include_directories(gpr_thd_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gpr_thd_test @@ -6559,7 +6477,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(gpr_time_test - test/core/support/time_test.c + test/core/support/time_test.cc ) @@ -6574,7 +6492,6 @@ target_include_directories(gpr_time_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gpr_time_test @@ -6587,7 +6504,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(gpr_tls_test - test/core/support/tls_test.c + test/core/support/tls_test.cc ) @@ -6602,7 +6519,6 @@ target_include_directories(gpr_tls_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gpr_tls_test @@ -6615,7 +6531,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(gpr_useful_test - test/core/support/useful_test.c + test/core/support/useful_test.cc ) @@ -6630,7 +6546,6 @@ target_include_directories(gpr_useful_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(gpr_useful_test @@ -6643,7 +6558,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(grpc_auth_context_test - test/core/security/auth_context_test.c + test/core/security/auth_context_test.cc ) @@ -6658,7 +6573,6 @@ target_include_directories(grpc_auth_context_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_auth_context_test @@ -6673,7 +6587,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(grpc_b64_test - test/core/slice/b64_test.c + test/core/slice/b64_test.cc ) @@ -6688,7 +6602,6 @@ target_include_directories(grpc_b64_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_b64_test @@ -6703,7 +6616,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(grpc_byte_buffer_reader_test - test/core/surface/byte_buffer_reader_test.c + test/core/surface/byte_buffer_reader_test.cc ) @@ -6718,7 +6631,6 @@ target_include_directories(grpc_byte_buffer_reader_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_byte_buffer_reader_test @@ -6733,7 +6645,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(grpc_channel_args_test - test/core/channel/channel_args_test.c + test/core/channel/channel_args_test.cc ) @@ -6748,7 +6660,6 @@ target_include_directories(grpc_channel_args_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_channel_args_test @@ -6763,7 +6674,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(grpc_channel_stack_builder_test - test/core/channel/channel_stack_builder_test.c + test/core/channel/channel_stack_builder_test.cc ) @@ -6778,7 +6689,6 @@ target_include_directories(grpc_channel_stack_builder_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_channel_stack_builder_test @@ -6793,7 +6703,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(grpc_channel_stack_test - test/core/channel/channel_stack_test.c + test/core/channel/channel_stack_test.cc ) @@ -6808,7 +6718,6 @@ target_include_directories(grpc_channel_stack_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_channel_stack_test @@ -6823,7 +6732,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(grpc_completion_queue_test - test/core/surface/completion_queue_test.c + test/core/surface/completion_queue_test.cc ) @@ -6838,7 +6747,6 @@ target_include_directories(grpc_completion_queue_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_completion_queue_test @@ -6853,7 +6761,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(grpc_completion_queue_threading_test - test/core/surface/completion_queue_threading_test.c + test/core/surface/completion_queue_threading_test.cc ) @@ -6868,7 +6776,6 @@ target_include_directories(grpc_completion_queue_threading_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_completion_queue_threading_test @@ -6882,7 +6789,7 @@ target_link_libraries(grpc_completion_queue_threading_test endif (gRPC_BUILD_TESTS) add_executable(grpc_create_jwt - test/core/security/create_jwt.c + test/core/security/create_jwt.cc ) @@ -6897,7 +6804,6 @@ target_include_directories(grpc_create_jwt PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_create_jwt @@ -6919,7 +6825,7 @@ endif() if (gRPC_BUILD_TESTS) add_executable(grpc_credentials_test - test/core/security/credentials_test.c + test/core/security/credentials_test.cc ) @@ -6934,7 +6840,6 @@ target_include_directories(grpc_credentials_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_credentials_test @@ -6949,7 +6854,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(grpc_fetch_oauth2 - test/core/security/fetch_oauth2.c + test/core/security/fetch_oauth2.cc ) @@ -6964,7 +6869,6 @@ target_include_directories(grpc_fetch_oauth2 PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_fetch_oauth2 @@ -6979,7 +6883,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(grpc_invalid_channel_args_test - test/core/surface/invalid_channel_args_test.c + test/core/surface/invalid_channel_args_test.cc ) @@ -6994,7 +6898,6 @@ target_include_directories(grpc_invalid_channel_args_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_invalid_channel_args_test @@ -7010,7 +6913,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(grpc_json_token_test - test/core/security/json_token_test.c + test/core/security/json_token_test.cc ) @@ -7025,7 +6928,6 @@ target_include_directories(grpc_json_token_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_json_token_test @@ -7041,7 +6943,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(grpc_jwt_verifier_test - test/core/security/jwt_verifier_test.c + test/core/security/jwt_verifier_test.cc ) @@ -7056,7 +6958,6 @@ target_include_directories(grpc_jwt_verifier_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_jwt_verifier_test @@ -7070,7 +6971,7 @@ target_link_libraries(grpc_jwt_verifier_test endif (gRPC_BUILD_TESTS) add_executable(grpc_print_google_default_creds_token - test/core/security/print_google_default_creds_token.c + test/core/security/print_google_default_creds_token.cc ) @@ -7085,7 +6986,6 @@ target_include_directories(grpc_print_google_default_creds_token PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_print_google_default_creds_token @@ -7106,7 +7006,7 @@ endif() if (gRPC_BUILD_TESTS) add_executable(grpc_security_connector_test - test/core/security/security_connector_test.c + test/core/security/security_connector_test.cc ) @@ -7121,7 +7021,6 @@ target_include_directories(grpc_security_connector_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_security_connector_test @@ -7136,7 +7035,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(grpc_ssl_credentials_test - test/core/security/ssl_credentials_test.c + test/core/security/ssl_credentials_test.cc ) @@ -7151,7 +7050,6 @@ target_include_directories(grpc_ssl_credentials_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_ssl_credentials_test @@ -7165,7 +7063,7 @@ target_link_libraries(grpc_ssl_credentials_test endif (gRPC_BUILD_TESTS) add_executable(grpc_verify_jwt - test/core/security/verify_jwt.c + test/core/security/verify_jwt.cc ) @@ -7180,7 +7078,6 @@ target_include_directories(grpc_verify_jwt PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(grpc_verify_jwt @@ -7202,7 +7099,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX) add_executable(handshake_client - test/core/handshake/client_ssl.c + test/core/handshake/client_ssl.cc ) @@ -7217,7 +7114,6 @@ target_include_directories(handshake_client PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(handshake_client @@ -7235,7 +7131,8 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX) add_executable(handshake_server - test/core/handshake/server_ssl.c + test/core/handshake/server_ssl.cc + test/core/handshake/server_ssl_common.cc ) @@ -7250,7 +7147,6 @@ target_include_directories(handshake_server PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(handshake_server @@ -7263,11 +7159,71 @@ target_link_libraries(handshake_server ) endif() +endif (gRPC_BUILD_TESTS) +if (gRPC_BUILD_TESTS) +if(_gRPC_PLATFORM_LINUX) + +add_executable(handshake_server_with_readahead_handshaker + test/core/handshake/readahead_handshaker_server_ssl.cc + test/core/handshake/server_ssl_common.cc +) + + +target_include_directories(handshake_server_with_readahead_handshaker + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include + PRIVATE ${BORINGSSL_ROOT_DIR}/include + PRIVATE ${PROTOBUF_ROOT_DIR}/src + PRIVATE ${BENCHMARK_ROOT_DIR}/include + PRIVATE ${ZLIB_ROOT_DIR} + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/zlib + PRIVATE ${CARES_INCLUDE_DIR} + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include +) + +target_link_libraries(handshake_server_with_readahead_handshaker + ${_gRPC_SSL_LIBRARIES} + ${_gRPC_ALLTARGETS_LIBRARIES} + grpc_test_util + grpc + gpr_test_util + gpr +) + +endif() +endif (gRPC_BUILD_TESTS) +if (gRPC_BUILD_TESTS) + +add_executable(histogram_test + test/core/util/histogram_test.cc +) + + +target_include_directories(histogram_test + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include + PRIVATE ${BORINGSSL_ROOT_DIR}/include + PRIVATE ${PROTOBUF_ROOT_DIR}/src + PRIVATE ${BENCHMARK_ROOT_DIR}/include + PRIVATE ${ZLIB_ROOT_DIR} + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/zlib + PRIVATE ${CARES_INCLUDE_DIR} + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include +) + +target_link_libraries(histogram_test + ${_gRPC_ALLTARGETS_LIBRARIES} + grpc_test_util + gpr +) + endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(hpack_parser_test - test/core/transport/chttp2/hpack_parser_test.c + test/core/transport/chttp2/hpack_parser_test.cc ) @@ -7282,7 +7238,6 @@ target_include_directories(hpack_parser_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(hpack_parser_test @@ -7297,7 +7252,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(hpack_table_test - test/core/transport/chttp2/hpack_table_test.c + test/core/transport/chttp2/hpack_table_test.cc ) @@ -7312,7 +7267,6 @@ target_include_directories(hpack_table_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(hpack_table_test @@ -7327,7 +7281,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(http_parser_test - test/core/http/parser_test.c + test/core/http/parser_test.cc ) @@ -7342,7 +7296,6 @@ target_include_directories(http_parser_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(http_parser_test @@ -7357,7 +7310,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(httpcli_format_request_test - test/core/http/format_request_test.c + test/core/http/format_request_test.cc ) @@ -7372,7 +7325,6 @@ target_include_directories(httpcli_format_request_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(httpcli_format_request_test @@ -7388,7 +7340,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(httpcli_test - test/core/http/httpcli_test.c + test/core/http/httpcli_test.cc ) @@ -7403,7 +7355,6 @@ target_include_directories(httpcli_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(httpcli_test @@ -7420,7 +7371,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX) add_executable(httpscli_test - test/core/http/httpscli_test.c + test/core/http/httpscli_test.cc ) @@ -7435,7 +7386,6 @@ target_include_directories(httpscli_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(httpscli_test @@ -7451,7 +7401,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(init_test - test/core/surface/init_test.c + test/core/surface/init_test.cc ) @@ -7466,7 +7416,6 @@ target_include_directories(init_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(init_test @@ -7481,7 +7430,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(invalid_call_argument_test - test/core/end2end/invalid_call_argument_test.c + test/core/end2end/invalid_call_argument_test.cc ) @@ -7496,7 +7445,6 @@ target_include_directories(invalid_call_argument_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(invalid_call_argument_test @@ -7511,7 +7459,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(json_rewrite - test/core/json/json_rewrite.c + test/core/json/json_rewrite.cc ) @@ -7526,7 +7474,6 @@ target_include_directories(json_rewrite PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(json_rewrite @@ -7539,7 +7486,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(json_rewrite_test - test/core/json/json_rewrite_test.c + test/core/json/json_rewrite_test.cc ) @@ -7554,7 +7501,6 @@ target_include_directories(json_rewrite_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(json_rewrite_test @@ -7569,7 +7515,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(json_stream_error_test - test/core/json/json_stream_error_test.c + test/core/json/json_stream_error_test.cc ) @@ -7584,7 +7530,6 @@ target_include_directories(json_stream_error_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(json_stream_error_test @@ -7599,7 +7544,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(json_test - test/core/json/json_test.c + test/core/json/json_test.cc ) @@ -7614,7 +7559,6 @@ target_include_directories(json_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(json_test @@ -7629,7 +7573,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(lame_client_test - test/core/surface/lame_client_test.c + test/core/surface/lame_client_test.cc ) @@ -7644,7 +7588,6 @@ target_include_directories(lame_client_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(lame_client_test @@ -7659,7 +7602,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(lb_policies_test - test/core/client_channel/lb_policies_test.c + test/core/client_channel/lb_policies_test.cc ) @@ -7674,7 +7617,6 @@ target_include_directories(lb_policies_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(lb_policies_test @@ -7689,7 +7631,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(load_file_test - test/core/iomgr/load_file_test.c + test/core/iomgr/load_file_test.cc ) @@ -7704,7 +7646,6 @@ target_include_directories(load_file_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(load_file_test @@ -7719,7 +7660,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(memory_profile_client - test/core/memory_usage/client.c + test/core/memory_usage/client.cc ) @@ -7734,7 +7675,6 @@ target_include_directories(memory_profile_client PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(memory_profile_client @@ -7749,7 +7689,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(memory_profile_server - test/core/memory_usage/server.c + test/core/memory_usage/server.cc ) @@ -7764,7 +7704,6 @@ target_include_directories(memory_profile_server PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(memory_profile_server @@ -7780,7 +7719,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(memory_profile_test - test/core/memory_usage/memory_usage_test.c + test/core/memory_usage/memory_usage_test.cc ) @@ -7795,7 +7734,6 @@ target_include_directories(memory_profile_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(memory_profile_test @@ -7811,7 +7749,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(message_compress_test - test/core/compression/message_compress_test.c + test/core/compression/message_compress_test.cc ) @@ -7826,7 +7764,6 @@ target_include_directories(message_compress_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(message_compress_test @@ -7841,7 +7778,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(minimal_stack_is_minimal_test - test/core/channel/minimal_stack_is_minimal_test.c + test/core/channel/minimal_stack_is_minimal_test.cc ) @@ -7856,7 +7793,6 @@ target_include_directories(minimal_stack_is_minimal_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(minimal_stack_is_minimal_test @@ -7871,7 +7807,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(multiple_server_queues_test - test/core/end2end/multiple_server_queues_test.c + test/core/end2end/multiple_server_queues_test.cc ) @@ -7886,7 +7822,6 @@ target_include_directories(multiple_server_queues_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(multiple_server_queues_test @@ -7901,7 +7836,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(murmur_hash_test - test/core/support/murmur_hash_test.c + test/core/support/murmur_hash_test.cc ) @@ -7916,7 +7851,6 @@ target_include_directories(murmur_hash_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(murmur_hash_test @@ -7929,7 +7863,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(no_server_test - test/core/end2end/no_server_test.c + test/core/end2end/no_server_test.cc ) @@ -7944,7 +7878,6 @@ target_include_directories(no_server_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(no_server_test @@ -7959,7 +7892,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(num_external_connectivity_watchers_test - test/core/surface/num_external_connectivity_watchers_test.c + test/core/surface/num_external_connectivity_watchers_test.cc ) @@ -7974,7 +7907,6 @@ target_include_directories(num_external_connectivity_watchers_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(num_external_connectivity_watchers_test @@ -7989,7 +7921,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(parse_address_test - test/core/client_channel/parse_address_test.c + test/core/client_channel/parse_address_test.cc ) @@ -8004,7 +7936,6 @@ target_include_directories(parse_address_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(parse_address_test @@ -8019,7 +7950,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(percent_encoding_test - test/core/slice/percent_encoding_test.c + test/core/slice/percent_encoding_test.cc ) @@ -8034,7 +7965,6 @@ target_include_directories(percent_encoding_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(percent_encoding_test @@ -8050,7 +7980,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX) add_executable(pollset_set_test - test/core/iomgr/pollset_set_test.c + test/core/iomgr/pollset_set_test.cc ) @@ -8065,7 +7995,6 @@ target_include_directories(pollset_set_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(pollset_set_test @@ -8082,7 +8011,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(resolve_address_posix_test - test/core/iomgr/resolve_address_posix_test.c + test/core/iomgr/resolve_address_posix_test.cc ) @@ -8097,7 +8026,6 @@ target_include_directories(resolve_address_posix_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(resolve_address_posix_test @@ -8113,7 +8041,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(resolve_address_test - test/core/iomgr/resolve_address_test.c + test/core/iomgr/resolve_address_test.cc ) @@ -8128,7 +8056,6 @@ target_include_directories(resolve_address_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(resolve_address_test @@ -8143,7 +8070,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(resource_quota_test - test/core/iomgr/resource_quota_test.c + test/core/iomgr/resource_quota_test.cc ) @@ -8158,7 +8085,6 @@ target_include_directories(resource_quota_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(resource_quota_test @@ -8173,7 +8099,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(secure_channel_create_test - test/core/surface/secure_channel_create_test.c + test/core/surface/secure_channel_create_test.cc ) @@ -8188,7 +8114,6 @@ target_include_directories(secure_channel_create_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(secure_channel_create_test @@ -8203,7 +8128,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(secure_endpoint_test - test/core/security/secure_endpoint_test.c + test/core/security/secure_endpoint_test.cc ) @@ -8218,7 +8143,6 @@ target_include_directories(secure_endpoint_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(secure_endpoint_test @@ -8233,7 +8157,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(sequential_connectivity_test - test/core/surface/sequential_connectivity_test.c + test/core/surface/sequential_connectivity_test.cc ) @@ -8248,7 +8172,6 @@ target_include_directories(sequential_connectivity_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(sequential_connectivity_test @@ -8263,7 +8186,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(server_chttp2_test - test/core/surface/server_chttp2_test.c + test/core/surface/server_chttp2_test.cc ) @@ -8278,7 +8201,6 @@ target_include_directories(server_chttp2_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(server_chttp2_test @@ -8293,7 +8215,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(server_test - test/core/surface/server_test.c + test/core/surface/server_test.cc ) @@ -8308,7 +8230,6 @@ target_include_directories(server_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(server_test @@ -8323,7 +8244,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(slice_buffer_test - test/core/slice/slice_buffer_test.c + test/core/slice/slice_buffer_test.cc ) @@ -8338,7 +8259,6 @@ target_include_directories(slice_buffer_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(slice_buffer_test @@ -8353,7 +8273,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(slice_hash_table_test - test/core/slice/slice_hash_table_test.c + test/core/slice/slice_hash_table_test.cc ) @@ -8368,7 +8288,6 @@ target_include_directories(slice_hash_table_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(slice_hash_table_test @@ -8383,7 +8302,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(slice_string_helpers_test - test/core/slice/slice_string_helpers_test.c + test/core/slice/slice_string_helpers_test.cc ) @@ -8398,7 +8317,6 @@ target_include_directories(slice_string_helpers_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(slice_string_helpers_test @@ -8413,7 +8331,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(slice_test - test/core/slice/slice_test.c + test/core/slice/slice_test.cc ) @@ -8428,7 +8346,6 @@ target_include_directories(slice_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(slice_test @@ -8443,7 +8360,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(sockaddr_resolver_test - test/core/client_channel/resolvers/sockaddr_resolver_test.c + test/core/client_channel/resolvers/sockaddr_resolver_test.cc ) @@ -8458,7 +8375,6 @@ target_include_directories(sockaddr_resolver_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(sockaddr_resolver_test @@ -8473,7 +8389,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(sockaddr_utils_test - test/core/iomgr/sockaddr_utils_test.c + test/core/iomgr/sockaddr_utils_test.cc ) @@ -8488,7 +8404,6 @@ target_include_directories(sockaddr_utils_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(sockaddr_utils_test @@ -8504,7 +8419,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(socket_utils_test - test/core/iomgr/socket_utils_test.c + test/core/iomgr/socket_utils_test.cc ) @@ -8519,7 +8434,6 @@ target_include_directories(socket_utils_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(socket_utils_test @@ -8536,8 +8450,8 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(ssl_transport_security_test - test/core/tsi/ssl_transport_security_test.c - test/core/tsi/transport_security_test_lib.c + test/core/tsi/ssl_transport_security_test.cc + test/core/tsi/transport_security_test_lib.cc ) @@ -8552,7 +8466,6 @@ target_include_directories(ssl_transport_security_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(ssl_transport_security_test @@ -8567,7 +8480,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(status_conversion_test - test/core/transport/status_conversion_test.c + test/core/transport/status_conversion_test.cc ) @@ -8582,7 +8495,6 @@ target_include_directories(status_conversion_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(status_conversion_test @@ -8597,7 +8509,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(stream_compression_test - test/core/compression/stream_compression_test.c + test/core/compression/stream_compression_test.cc ) @@ -8612,7 +8524,6 @@ target_include_directories(stream_compression_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(stream_compression_test @@ -8627,7 +8538,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(stream_owned_slice_test - test/core/transport/stream_owned_slice_test.c + test/core/transport/stream_owned_slice_test.cc ) @@ -8642,7 +8553,6 @@ target_include_directories(stream_owned_slice_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(stream_owned_slice_test @@ -8658,7 +8568,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(tcp_client_posix_test - test/core/iomgr/tcp_client_posix_test.c + test/core/iomgr/tcp_client_posix_test.cc ) @@ -8673,7 +8583,6 @@ target_include_directories(tcp_client_posix_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(tcp_client_posix_test @@ -8689,7 +8598,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(tcp_client_uv_test - test/core/iomgr/tcp_client_uv_test.c + test/core/iomgr/tcp_client_uv_test.cc ) @@ -8704,7 +8613,6 @@ target_include_directories(tcp_client_uv_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(tcp_client_uv_test @@ -8720,7 +8628,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(tcp_posix_test - test/core/iomgr/tcp_posix_test.c + test/core/iomgr/tcp_posix_test.cc ) @@ -8735,7 +8643,6 @@ target_include_directories(tcp_posix_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(tcp_posix_test @@ -8752,7 +8659,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(tcp_server_posix_test - test/core/iomgr/tcp_server_posix_test.c + test/core/iomgr/tcp_server_posix_test.cc ) @@ -8767,7 +8674,6 @@ target_include_directories(tcp_server_posix_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(tcp_server_posix_test @@ -8783,7 +8689,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(tcp_server_uv_test - test/core/iomgr/tcp_server_uv_test.c + test/core/iomgr/tcp_server_uv_test.cc ) @@ -8798,7 +8704,6 @@ target_include_directories(tcp_server_uv_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(tcp_server_uv_test @@ -8813,7 +8718,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(time_averaged_stats_test - test/core/iomgr/time_averaged_stats_test.c + test/core/iomgr/time_averaged_stats_test.cc ) @@ -8828,7 +8733,6 @@ target_include_directories(time_averaged_stats_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(time_averaged_stats_test @@ -8843,7 +8747,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(timeout_encoding_test - test/core/transport/timeout_encoding_test.c + test/core/transport/timeout_encoding_test.cc ) @@ -8858,7 +8762,6 @@ target_include_directories(timeout_encoding_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(timeout_encoding_test @@ -8873,7 +8776,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(timer_heap_test - test/core/iomgr/timer_heap_test.c + test/core/iomgr/timer_heap_test.cc ) @@ -8888,7 +8791,6 @@ target_include_directories(timer_heap_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(timer_heap_test @@ -8903,7 +8805,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(timer_list_test - test/core/iomgr/timer_list_test.c + test/core/iomgr/timer_list_test.cc ) @@ -8918,7 +8820,6 @@ target_include_directories(timer_list_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(timer_list_test @@ -8933,7 +8834,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(transport_connectivity_state_test - test/core/transport/connectivity_state_test.c + test/core/transport/connectivity_state_test.cc ) @@ -8948,7 +8849,6 @@ target_include_directories(transport_connectivity_state_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(transport_connectivity_state_test @@ -8963,7 +8863,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(transport_metadata_test - test/core/transport/metadata_test.c + test/core/transport/metadata_test.cc ) @@ -8978,7 +8878,6 @@ target_include_directories(transport_metadata_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(transport_metadata_test @@ -8994,7 +8893,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(transport_security_test - test/core/tsi/transport_security_test.c + test/core/tsi/transport_security_test.cc ) @@ -9009,7 +8908,6 @@ target_include_directories(transport_security_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(transport_security_test @@ -9026,7 +8924,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(udp_server_test - test/core/iomgr/udp_server_test.c + test/core/iomgr/udp_server_test.cc ) @@ -9041,7 +8939,6 @@ target_include_directories(udp_server_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(udp_server_test @@ -9057,7 +8954,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(uri_parser_test - test/core/client_channel/uri_parser_test.c + test/core/client_channel/uri_parser_test.cc ) @@ -9072,7 +8969,6 @@ target_include_directories(uri_parser_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(uri_parser_test @@ -9088,7 +8984,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(wakeup_fd_cv_test - test/core/iomgr/wakeup_fd_cv_test.c + test/core/iomgr/wakeup_fd_cv_test.cc ) @@ -9103,7 +8999,6 @@ target_include_directories(wakeup_fd_cv_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(wakeup_fd_cv_test @@ -9136,7 +9031,6 @@ target_include_directories(alarm_cpp_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9177,7 +9071,6 @@ target_include_directories(async_end2end_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9218,7 +9111,6 @@ target_include_directories(auth_property_iterator_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9259,7 +9151,6 @@ target_include_directories(bdp_estimator_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9301,7 +9192,6 @@ target_include_directories(bm_arena PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9346,7 +9236,6 @@ target_include_directories(bm_call_create PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9391,7 +9280,6 @@ target_include_directories(bm_chttp2_hpack PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9436,7 +9324,6 @@ target_include_directories(bm_chttp2_transport PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9481,7 +9368,6 @@ target_include_directories(bm_closure PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9526,7 +9412,6 @@ target_include_directories(bm_cq PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9571,7 +9456,6 @@ target_include_directories(bm_cq_multiple_threads PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9616,7 +9500,6 @@ target_include_directories(bm_error PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9661,7 +9544,6 @@ target_include_directories(bm_fullstack_streaming_ping_pong PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9706,7 +9588,6 @@ target_include_directories(bm_fullstack_streaming_pump PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9751,7 +9632,6 @@ target_include_directories(bm_fullstack_trickle PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9797,7 +9677,6 @@ target_include_directories(bm_fullstack_unary_ping_pong PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9842,7 +9721,6 @@ target_include_directories(bm_metadata PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9887,7 +9765,6 @@ target_include_directories(bm_pollset PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9931,7 +9808,6 @@ target_include_directories(channel_arguments_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9969,7 +9845,6 @@ target_include_directories(channel_filter_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -9989,6 +9864,44 @@ target_link_libraries(channel_filter_test endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) +add_executable(chttp2_settings_timeout_test + test/core/transport/chttp2/settings_timeout_test.cc + third_party/googletest/googletest/src/gtest-all.cc + third_party/googletest/googlemock/src/gmock-all.cc +) + + +target_include_directories(chttp2_settings_timeout_test + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include + PRIVATE ${BORINGSSL_ROOT_DIR}/include + PRIVATE ${PROTOBUF_ROOT_DIR}/src + PRIVATE ${BENCHMARK_ROOT_DIR}/include + PRIVATE ${ZLIB_ROOT_DIR} + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/zlib + PRIVATE ${CARES_INCLUDE_DIR} + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include + 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(chttp2_settings_timeout_test + ${_gRPC_PROTOBUF_LIBRARIES} + ${_gRPC_ALLTARGETS_LIBRARIES} + grpc_test_util + grpc + gpr_test_util + gpr + ${_gRPC_GFLAGS_LIBRARIES} +) + +endif (gRPC_BUILD_TESTS) +if (gRPC_BUILD_TESTS) + add_executable(cli_call_test test/cpp/util/cli_call_test.cc third_party/googletest/googletest/src/gtest-all.cc @@ -10007,7 +9920,6 @@ target_include_directories(cli_call_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10028,6 +9940,53 @@ target_link_libraries(cli_call_test ${_gRPC_GFLAGS_LIBRARIES} ) +endif (gRPC_BUILD_TESTS) +if (gRPC_BUILD_TESTS) + +add_executable(client_channel_stress_test + ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/lb/v1/load_balancer.pb.cc + ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/lb/v1/load_balancer.grpc.pb.cc + ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/lb/v1/load_balancer.pb.h + ${_gRPC_PROTO_GENS_DIR}/src/proto/grpc/lb/v1/load_balancer.grpc.pb.h + test/cpp/client/client_channel_stress_test.cc + third_party/googletest/googletest/src/gtest-all.cc + third_party/googletest/googlemock/src/gmock-all.cc +) + +protobuf_generate_grpc_cpp( + src/proto/grpc/lb/v1/load_balancer.proto +) + +target_include_directories(client_channel_stress_test + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include + PRIVATE ${BORINGSSL_ROOT_DIR}/include + PRIVATE ${PROTOBUF_ROOT_DIR}/src + PRIVATE ${BENCHMARK_ROOT_DIR}/include + PRIVATE ${ZLIB_ROOT_DIR} + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/zlib + PRIVATE ${CARES_INCLUDE_DIR} + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include + 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(client_channel_stress_test + ${_gRPC_PROTOBUF_LIBRARIES} + ${_gRPC_ALLTARGETS_LIBRARIES} + grpc++_test_util + grpc_test_util + grpc++ + grpc + gpr_test_util + gpr + ${_gRPC_GFLAGS_LIBRARIES} +) + endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) @@ -10050,7 +10009,6 @@ target_include_directories(client_crash_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10092,7 +10050,6 @@ target_include_directories(client_crash_test_server PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10133,7 +10090,6 @@ target_include_directories(client_lb_end2end_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10209,7 +10165,6 @@ target_include_directories(codegen_test_full PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10284,7 +10239,6 @@ target_include_directories(codegen_test_minimal PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10322,7 +10276,6 @@ target_include_directories(credentials_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10360,7 +10313,6 @@ target_include_directories(cxx_byte_buffer_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10400,7 +10352,6 @@ target_include_directories(cxx_slice_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10440,7 +10391,6 @@ target_include_directories(cxx_string_ref_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10477,7 +10427,6 @@ target_include_directories(cxx_time_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10517,7 +10466,6 @@ target_include_directories(end2end_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10565,7 +10513,6 @@ target_include_directories(error_details_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10602,7 +10549,6 @@ target_include_directories(filter_end2end_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10643,7 +10589,6 @@ target_include_directories(generic_end2end_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10691,7 +10636,6 @@ target_include_directories(golden_file_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10729,7 +10673,6 @@ target_include_directories(grpc_cli PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -10767,7 +10710,6 @@ target_include_directories(grpc_cpp_plugin PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE ${_gRPC_PROTO_GENS_DIR} ) @@ -10804,7 +10746,6 @@ target_include_directories(grpc_csharp_plugin PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE ${_gRPC_PROTO_GENS_DIR} ) @@ -10841,7 +10782,6 @@ target_include_directories(grpc_node_plugin PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE ${_gRPC_PROTO_GENS_DIR} ) @@ -10878,7 +10818,6 @@ target_include_directories(grpc_objective_c_plugin PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE ${_gRPC_PROTO_GENS_DIR} ) @@ -10915,7 +10854,6 @@ target_include_directories(grpc_php_plugin PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE ${_gRPC_PROTO_GENS_DIR} ) @@ -10952,7 +10890,6 @@ target_include_directories(grpc_python_plugin PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE ${_gRPC_PROTO_GENS_DIR} ) @@ -10989,7 +10926,6 @@ target_include_directories(grpc_ruby_plugin PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE ${_gRPC_PROTO_GENS_DIR} ) @@ -11043,7 +10979,6 @@ target_include_directories(grpc_tool_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11094,7 +11029,6 @@ target_include_directories(grpclb_api_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11140,7 +11074,6 @@ target_include_directories(grpclb_end2end_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11188,7 +11121,6 @@ target_include_directories(grpclb_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11229,7 +11161,6 @@ target_include_directories(h2_ssl_cert_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11269,7 +11200,6 @@ target_include_directories(health_service_end2end_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11310,7 +11240,6 @@ target_include_directories(http2_client PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11352,7 +11281,6 @@ target_include_directories(hybrid_end2end_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11394,7 +11322,6 @@ target_include_directories(inproc_sync_unary_ping_pong_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11439,7 +11366,6 @@ target_include_directories(interop_client PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11484,7 +11410,6 @@ target_include_directories(interop_server PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11531,7 +11456,6 @@ target_include_directories(interop_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11573,7 +11497,6 @@ target_include_directories(json_run_localhost PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11616,7 +11539,6 @@ target_include_directories(memory_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11663,7 +11585,6 @@ target_include_directories(metrics_client PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11702,7 +11623,6 @@ target_include_directories(mock_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11743,7 +11663,6 @@ target_include_directories(noop-benchmark PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11779,7 +11698,6 @@ target_include_directories(proto_server_reflection_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11822,7 +11740,6 @@ target_include_directories(proto_utils_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11860,7 +11777,6 @@ target_include_directories(qps_interarrival_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11904,7 +11820,6 @@ target_include_directories(qps_json_driver PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11949,7 +11864,6 @@ target_include_directories(qps_openloop_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -11994,7 +11908,6 @@ target_include_directories(qps_worker PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12059,7 +11972,6 @@ target_include_directories(reconnect_interop_client PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12122,7 +12034,6 @@ target_include_directories(reconnect_interop_server PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12148,6 +12059,84 @@ target_link_libraries(reconnect_interop_server endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) +add_executable(ref_counted_ptr_test + test/core/support/ref_counted_ptr_test.cc + third_party/googletest/googletest/src/gtest-all.cc + third_party/googletest/googlemock/src/gmock-all.cc +) + + +target_include_directories(ref_counted_ptr_test + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include + PRIVATE ${BORINGSSL_ROOT_DIR}/include + PRIVATE ${PROTOBUF_ROOT_DIR}/src + PRIVATE ${BENCHMARK_ROOT_DIR}/include + PRIVATE ${ZLIB_ROOT_DIR} + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/zlib + PRIVATE ${CARES_INCLUDE_DIR} + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include + 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(ref_counted_ptr_test + ${_gRPC_PROTOBUF_LIBRARIES} + ${_gRPC_ALLTARGETS_LIBRARIES} + grpc_test_util + grpc++ + grpc + gpr_test_util + gpr + ${_gRPC_GFLAGS_LIBRARIES} +) + +endif (gRPC_BUILD_TESTS) +if (gRPC_BUILD_TESTS) + +add_executable(ref_counted_test + test/core/support/ref_counted_test.cc + third_party/googletest/googletest/src/gtest-all.cc + third_party/googletest/googlemock/src/gmock-all.cc +) + + +target_include_directories(ref_counted_test + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include + PRIVATE ${BORINGSSL_ROOT_DIR}/include + PRIVATE ${PROTOBUF_ROOT_DIR}/src + PRIVATE ${BENCHMARK_ROOT_DIR}/include + PRIVATE ${ZLIB_ROOT_DIR} + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/zlib + PRIVATE ${CARES_INCLUDE_DIR} + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares + PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include + 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(ref_counted_test + ${_gRPC_PROTOBUF_LIBRARIES} + ${_gRPC_ALLTARGETS_LIBRARIES} + grpc_test_util + grpc++ + grpc + gpr_test_util + gpr + ${_gRPC_GFLAGS_LIBRARIES} +) + +endif (gRPC_BUILD_TESTS) +if (gRPC_BUILD_TESTS) + add_executable(secure_auth_context_test test/cpp/common/secure_auth_context_test.cc third_party/googletest/googletest/src/gtest-all.cc @@ -12166,7 +12155,6 @@ target_include_directories(secure_auth_context_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12208,7 +12196,6 @@ target_include_directories(secure_sync_unary_ping_pong_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12253,7 +12240,6 @@ target_include_directories(server_builder_plugin_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12308,7 +12294,6 @@ target_include_directories(server_builder_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12349,7 +12334,6 @@ target_include_directories(server_context_test_spouse_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12390,7 +12374,6 @@ target_include_directories(server_crash_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12432,7 +12415,6 @@ target_include_directories(server_crash_test_client PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12487,7 +12469,6 @@ target_include_directories(server_request_call_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12528,7 +12509,6 @@ target_include_directories(shutdown_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12569,7 +12549,6 @@ target_include_directories(stats_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12609,7 +12588,6 @@ target_include_directories(status_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12650,7 +12628,6 @@ target_include_directories(streaming_throughput_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12723,7 +12700,6 @@ target_include_directories(stress_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12765,7 +12741,6 @@ target_include_directories(thread_manager_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12804,7 +12779,6 @@ target_include_directories(thread_stress_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12845,7 +12819,6 @@ target_include_directories(transport_pid_controller_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12865,46 +12838,6 @@ target_link_libraries(transport_pid_controller_test ${_gRPC_GFLAGS_LIBRARIES} ) -endif (gRPC_BUILD_TESTS) -if (gRPC_BUILD_TESTS) - -add_executable(vector_test - test/core/support/vector_test.cc - third_party/googletest/googletest/src/gtest-all.cc - third_party/googletest/googlemock/src/gmock-all.cc -) - - -target_include_directories(vector_test - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include - PRIVATE ${BORINGSSL_ROOT_DIR}/include - PRIVATE ${PROTOBUF_ROOT_DIR}/src - PRIVATE ${BENCHMARK_ROOT_DIR}/include - PRIVATE ${ZLIB_ROOT_DIR} - PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/zlib - PRIVATE ${CARES_INCLUDE_DIR} - PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares - PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp - 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(vector_test - ${_gRPC_PROTOBUF_LIBRARIES} - ${_gRPC_ALLTARGETS_LIBRARIES} - grpc_test_util - grpc++ - grpc - gpr_test_util - gpr - ${_gRPC_GFLAGS_LIBRARIES} -) - endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) @@ -12927,7 +12860,6 @@ target_include_directories(writes_per_rpc_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -12967,7 +12899,6 @@ target_include_directories(public_headers_must_be_c89 PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(public_headers_must_be_c89 @@ -12980,7 +12911,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(badreq_bad_client_test - test/core/bad_client/tests/badreq.c + test/core/bad_client/tests/badreq.cc ) @@ -12995,7 +12926,6 @@ target_include_directories(badreq_bad_client_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(badreq_bad_client_test @@ -13012,7 +12942,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(connection_prefix_bad_client_test - test/core/bad_client/tests/connection_prefix.c + test/core/bad_client/tests/connection_prefix.cc ) @@ -13027,7 +12957,6 @@ target_include_directories(connection_prefix_bad_client_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(connection_prefix_bad_client_test @@ -13044,7 +12973,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(head_of_line_blocking_bad_client_test - test/core/bad_client/tests/head_of_line_blocking.c + test/core/bad_client/tests/head_of_line_blocking.cc ) @@ -13059,7 +12988,6 @@ target_include_directories(head_of_line_blocking_bad_client_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(head_of_line_blocking_bad_client_test @@ -13076,7 +13004,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(headers_bad_client_test - test/core/bad_client/tests/headers.c + test/core/bad_client/tests/headers.cc ) @@ -13091,7 +13019,6 @@ target_include_directories(headers_bad_client_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(headers_bad_client_test @@ -13108,7 +13035,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(initial_settings_frame_bad_client_test - test/core/bad_client/tests/initial_settings_frame.c + test/core/bad_client/tests/initial_settings_frame.cc ) @@ -13123,7 +13050,6 @@ target_include_directories(initial_settings_frame_bad_client_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(initial_settings_frame_bad_client_test @@ -13140,7 +13066,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(server_registered_method_bad_client_test - test/core/bad_client/tests/server_registered_method.c + test/core/bad_client/tests/server_registered_method.cc ) @@ -13155,7 +13081,6 @@ target_include_directories(server_registered_method_bad_client_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(server_registered_method_bad_client_test @@ -13172,7 +13097,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(simple_request_bad_client_test - test/core/bad_client/tests/simple_request.c + test/core/bad_client/tests/simple_request.cc ) @@ -13187,7 +13112,6 @@ target_include_directories(simple_request_bad_client_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(simple_request_bad_client_test @@ -13204,7 +13128,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(unknown_frame_bad_client_test - test/core/bad_client/tests/unknown_frame.c + test/core/bad_client/tests/unknown_frame.cc ) @@ -13219,7 +13143,6 @@ target_include_directories(unknown_frame_bad_client_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(unknown_frame_bad_client_test @@ -13236,7 +13159,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(window_overflow_bad_client_test - test/core/bad_client/tests/window_overflow.c + test/core/bad_client/tests/window_overflow.cc ) @@ -13251,7 +13174,6 @@ target_include_directories(window_overflow_bad_client_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(window_overflow_bad_client_test @@ -13269,7 +13191,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(bad_ssl_cert_server - test/core/bad_ssl/servers/cert.c + test/core/bad_ssl/servers/cert.cc ) @@ -13284,7 +13206,6 @@ target_include_directories(bad_ssl_cert_server PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(bad_ssl_cert_server @@ -13302,7 +13223,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(bad_ssl_cert_test - test/core/bad_ssl/bad_ssl_test.c + test/core/bad_ssl/bad_ssl_test.cc ) @@ -13317,7 +13238,6 @@ target_include_directories(bad_ssl_cert_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(bad_ssl_cert_test @@ -13333,7 +13253,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_census_test - test/core/end2end/fixtures/h2_census.c + test/core/end2end/fixtures/h2_census.cc ) @@ -13348,7 +13268,6 @@ target_include_directories(h2_census_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_census_test @@ -13364,7 +13283,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_compress_test - test/core/end2end/fixtures/h2_compress.c + test/core/end2end/fixtures/h2_compress.cc ) @@ -13379,7 +13298,6 @@ target_include_directories(h2_compress_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_compress_test @@ -13395,7 +13313,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_fakesec_test - test/core/end2end/fixtures/h2_fakesec.c + test/core/end2end/fixtures/h2_fakesec.cc ) @@ -13410,7 +13328,6 @@ target_include_directories(h2_fakesec_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_fakesec_test @@ -13427,7 +13344,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(h2_fd_test - test/core/end2end/fixtures/h2_fd.c + test/core/end2end/fixtures/h2_fd.cc ) @@ -13442,7 +13359,6 @@ target_include_directories(h2_fd_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_fd_test @@ -13459,7 +13375,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_full_test - test/core/end2end/fixtures/h2_full.c + test/core/end2end/fixtures/h2_full.cc ) @@ -13474,7 +13390,6 @@ target_include_directories(h2_full_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_full_test @@ -13491,7 +13406,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX) add_executable(h2_full+pipe_test - test/core/end2end/fixtures/h2_full+pipe.c + test/core/end2end/fixtures/h2_full+pipe.cc ) @@ -13506,7 +13421,6 @@ target_include_directories(h2_full+pipe_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_full+pipe_test @@ -13523,7 +13437,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_full+trace_test - test/core/end2end/fixtures/h2_full+trace.c + test/core/end2end/fixtures/h2_full+trace.cc ) @@ -13538,7 +13452,6 @@ target_include_directories(h2_full+trace_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_full+trace_test @@ -13554,7 +13467,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_full+workarounds_test - test/core/end2end/fixtures/h2_full+workarounds.c + test/core/end2end/fixtures/h2_full+workarounds.cc ) @@ -13569,7 +13482,6 @@ target_include_directories(h2_full+workarounds_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_full+workarounds_test @@ -13585,7 +13497,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_http_proxy_test - test/core/end2end/fixtures/h2_http_proxy.c + test/core/end2end/fixtures/h2_http_proxy.cc ) @@ -13600,7 +13512,6 @@ target_include_directories(h2_http_proxy_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_http_proxy_test @@ -13616,7 +13527,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_load_reporting_test - test/core/end2end/fixtures/h2_load_reporting.c + test/core/end2end/fixtures/h2_load_reporting.cc ) @@ -13631,7 +13542,6 @@ target_include_directories(h2_load_reporting_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_load_reporting_test @@ -13647,7 +13557,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_oauth2_test - test/core/end2end/fixtures/h2_oauth2.c + test/core/end2end/fixtures/h2_oauth2.cc ) @@ -13662,7 +13572,6 @@ target_include_directories(h2_oauth2_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_oauth2_test @@ -13678,7 +13587,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_proxy_test - test/core/end2end/fixtures/h2_proxy.c + test/core/end2end/fixtures/h2_proxy.cc ) @@ -13693,7 +13602,6 @@ target_include_directories(h2_proxy_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_proxy_test @@ -13709,7 +13617,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_sockpair_test - test/core/end2end/fixtures/h2_sockpair.c + test/core/end2end/fixtures/h2_sockpair.cc ) @@ -13724,7 +13632,6 @@ target_include_directories(h2_sockpair_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_sockpair_test @@ -13740,7 +13647,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_sockpair+trace_test - test/core/end2end/fixtures/h2_sockpair+trace.c + test/core/end2end/fixtures/h2_sockpair+trace.cc ) @@ -13755,7 +13662,6 @@ target_include_directories(h2_sockpair+trace_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_sockpair+trace_test @@ -13771,7 +13677,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_sockpair_1byte_test - test/core/end2end/fixtures/h2_sockpair_1byte.c + test/core/end2end/fixtures/h2_sockpair_1byte.cc ) @@ -13786,7 +13692,6 @@ target_include_directories(h2_sockpair_1byte_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_sockpair_1byte_test @@ -13802,7 +13707,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_ssl_test - test/core/end2end/fixtures/h2_ssl.c + test/core/end2end/fixtures/h2_ssl.cc ) @@ -13817,7 +13722,6 @@ target_include_directories(h2_ssl_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_ssl_test @@ -13833,7 +13737,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_ssl_proxy_test - test/core/end2end/fixtures/h2_ssl_proxy.c + test/core/end2end/fixtures/h2_ssl_proxy.cc ) @@ -13848,7 +13752,6 @@ target_include_directories(h2_ssl_proxy_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_ssl_proxy_test @@ -13865,7 +13768,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(h2_uds_test - test/core/end2end/fixtures/h2_uds.c + test/core/end2end/fixtures/h2_uds.cc ) @@ -13880,7 +13783,6 @@ target_include_directories(h2_uds_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_uds_test @@ -13897,7 +13799,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(inproc_test - test/core/end2end/fixtures/inproc.c + test/core/end2end/fixtures/inproc.cc ) @@ -13912,7 +13814,6 @@ target_include_directories(inproc_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(inproc_test @@ -13928,7 +13829,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_census_nosec_test - test/core/end2end/fixtures/h2_census.c + test/core/end2end/fixtures/h2_census.cc ) @@ -13943,7 +13844,6 @@ target_include_directories(h2_census_nosec_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_census_nosec_test @@ -13959,7 +13859,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_compress_nosec_test - test/core/end2end/fixtures/h2_compress.c + test/core/end2end/fixtures/h2_compress.cc ) @@ -13974,7 +13874,6 @@ target_include_directories(h2_compress_nosec_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_compress_nosec_test @@ -13991,7 +13890,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(h2_fd_nosec_test - test/core/end2end/fixtures/h2_fd.c + test/core/end2end/fixtures/h2_fd.cc ) @@ -14006,7 +13905,6 @@ target_include_directories(h2_fd_nosec_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_fd_nosec_test @@ -14023,7 +13921,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_full_nosec_test - test/core/end2end/fixtures/h2_full.c + test/core/end2end/fixtures/h2_full.cc ) @@ -14038,7 +13936,6 @@ target_include_directories(h2_full_nosec_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_full_nosec_test @@ -14055,7 +13952,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX) add_executable(h2_full+pipe_nosec_test - test/core/end2end/fixtures/h2_full+pipe.c + test/core/end2end/fixtures/h2_full+pipe.cc ) @@ -14070,7 +13967,6 @@ target_include_directories(h2_full+pipe_nosec_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_full+pipe_nosec_test @@ -14087,7 +13983,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_full+trace_nosec_test - test/core/end2end/fixtures/h2_full+trace.c + test/core/end2end/fixtures/h2_full+trace.cc ) @@ -14102,7 +13998,6 @@ target_include_directories(h2_full+trace_nosec_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_full+trace_nosec_test @@ -14118,7 +14013,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_full+workarounds_nosec_test - test/core/end2end/fixtures/h2_full+workarounds.c + test/core/end2end/fixtures/h2_full+workarounds.cc ) @@ -14133,7 +14028,6 @@ target_include_directories(h2_full+workarounds_nosec_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_full+workarounds_nosec_test @@ -14149,7 +14043,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_http_proxy_nosec_test - test/core/end2end/fixtures/h2_http_proxy.c + test/core/end2end/fixtures/h2_http_proxy.cc ) @@ -14164,7 +14058,6 @@ target_include_directories(h2_http_proxy_nosec_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_http_proxy_nosec_test @@ -14180,7 +14073,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_load_reporting_nosec_test - test/core/end2end/fixtures/h2_load_reporting.c + test/core/end2end/fixtures/h2_load_reporting.cc ) @@ -14195,7 +14088,6 @@ target_include_directories(h2_load_reporting_nosec_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_load_reporting_nosec_test @@ -14211,7 +14103,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_proxy_nosec_test - test/core/end2end/fixtures/h2_proxy.c + test/core/end2end/fixtures/h2_proxy.cc ) @@ -14226,7 +14118,6 @@ target_include_directories(h2_proxy_nosec_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_proxy_nosec_test @@ -14242,7 +14133,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_sockpair_nosec_test - test/core/end2end/fixtures/h2_sockpair.c + test/core/end2end/fixtures/h2_sockpair.cc ) @@ -14257,7 +14148,6 @@ target_include_directories(h2_sockpair_nosec_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_sockpair_nosec_test @@ -14273,7 +14163,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_sockpair+trace_nosec_test - test/core/end2end/fixtures/h2_sockpair+trace.c + test/core/end2end/fixtures/h2_sockpair+trace.cc ) @@ -14288,7 +14178,6 @@ target_include_directories(h2_sockpair+trace_nosec_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_sockpair+trace_nosec_test @@ -14304,7 +14193,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(h2_sockpair_1byte_nosec_test - test/core/end2end/fixtures/h2_sockpair_1byte.c + test/core/end2end/fixtures/h2_sockpair_1byte.cc ) @@ -14319,7 +14208,6 @@ target_include_directories(h2_sockpair_1byte_nosec_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_sockpair_1byte_nosec_test @@ -14336,7 +14224,7 @@ if (gRPC_BUILD_TESTS) if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) add_executable(h2_uds_nosec_test - test/core/end2end/fixtures/h2_uds.c + test/core/end2end/fixtures/h2_uds.cc ) @@ -14351,7 +14239,6 @@ target_include_directories(h2_uds_nosec_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(h2_uds_nosec_test @@ -14368,7 +14255,7 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(inproc_nosec_test - test/core/end2end/fixtures/inproc.c + test/core/end2end/fixtures/inproc.cc ) @@ -14383,7 +14270,6 @@ target_include_directories(inproc_nosec_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(inproc_nosec_test @@ -14417,7 +14303,6 @@ target_include_directories(resolver_component_test_unsecure PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -14461,7 +14346,6 @@ target_include_directories(resolver_component_test PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -14505,7 +14389,6 @@ target_include_directories(resolver_component_tests_runner_invoker_unsecure PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -14549,7 +14432,6 @@ target_include_directories(resolver_component_tests_runner_invoker PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp PRIVATE third_party/googletest/googletest/include PRIVATE third_party/googletest/googletest PRIVATE third_party/googletest/googlemock/include @@ -14575,8 +14457,8 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(api_fuzzer_one_entry - test/core/end2end/fuzzers/api_fuzzer.c - test/core/util/one_corpus_entry_fuzzer.c + test/core/end2end/fuzzers/api_fuzzer.cc + test/core/util/one_corpus_entry_fuzzer.cc ) @@ -14591,7 +14473,6 @@ target_include_directories(api_fuzzer_one_entry PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(api_fuzzer_one_entry @@ -14606,8 +14487,8 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(client_fuzzer_one_entry - test/core/end2end/fuzzers/client_fuzzer.c - test/core/util/one_corpus_entry_fuzzer.c + test/core/end2end/fuzzers/client_fuzzer.cc + test/core/util/one_corpus_entry_fuzzer.cc ) @@ -14622,7 +14503,6 @@ target_include_directories(client_fuzzer_one_entry PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(client_fuzzer_one_entry @@ -14637,8 +14517,8 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(hpack_parser_fuzzer_test_one_entry - test/core/transport/chttp2/hpack_parser_fuzzer_test.c - test/core/util/one_corpus_entry_fuzzer.c + test/core/transport/chttp2/hpack_parser_fuzzer_test.cc + test/core/util/one_corpus_entry_fuzzer.cc ) @@ -14653,7 +14533,6 @@ target_include_directories(hpack_parser_fuzzer_test_one_entry PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(hpack_parser_fuzzer_test_one_entry @@ -14668,8 +14547,8 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(http_request_fuzzer_test_one_entry - test/core/http/request_fuzzer.c - test/core/util/one_corpus_entry_fuzzer.c + test/core/http/request_fuzzer.cc + test/core/util/one_corpus_entry_fuzzer.cc ) @@ -14684,7 +14563,6 @@ target_include_directories(http_request_fuzzer_test_one_entry PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(http_request_fuzzer_test_one_entry @@ -14699,8 +14577,8 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(http_response_fuzzer_test_one_entry - test/core/http/response_fuzzer.c - test/core/util/one_corpus_entry_fuzzer.c + test/core/http/response_fuzzer.cc + test/core/util/one_corpus_entry_fuzzer.cc ) @@ -14715,7 +14593,6 @@ target_include_directories(http_response_fuzzer_test_one_entry PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(http_response_fuzzer_test_one_entry @@ -14730,8 +14607,8 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(json_fuzzer_test_one_entry - test/core/json/fuzzer.c - test/core/util/one_corpus_entry_fuzzer.c + test/core/json/fuzzer.cc + test/core/util/one_corpus_entry_fuzzer.cc ) @@ -14746,7 +14623,6 @@ target_include_directories(json_fuzzer_test_one_entry PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(json_fuzzer_test_one_entry @@ -14761,8 +14637,8 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(nanopb_fuzzer_response_test_one_entry - test/core/nanopb/fuzzer_response.c - test/core/util/one_corpus_entry_fuzzer.c + test/core/nanopb/fuzzer_response.cc + test/core/util/one_corpus_entry_fuzzer.cc ) @@ -14777,7 +14653,6 @@ target_include_directories(nanopb_fuzzer_response_test_one_entry PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(nanopb_fuzzer_response_test_one_entry @@ -14792,8 +14667,8 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(nanopb_fuzzer_serverlist_test_one_entry - test/core/nanopb/fuzzer_serverlist.c - test/core/util/one_corpus_entry_fuzzer.c + test/core/nanopb/fuzzer_serverlist.cc + test/core/util/one_corpus_entry_fuzzer.cc ) @@ -14808,7 +14683,6 @@ target_include_directories(nanopb_fuzzer_serverlist_test_one_entry PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(nanopb_fuzzer_serverlist_test_one_entry @@ -14823,8 +14697,8 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(percent_decode_fuzzer_one_entry - test/core/slice/percent_decode_fuzzer.c - test/core/util/one_corpus_entry_fuzzer.c + test/core/slice/percent_decode_fuzzer.cc + test/core/util/one_corpus_entry_fuzzer.cc ) @@ -14839,7 +14713,6 @@ target_include_directories(percent_decode_fuzzer_one_entry PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(percent_decode_fuzzer_one_entry @@ -14854,8 +14727,8 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(percent_encode_fuzzer_one_entry - test/core/slice/percent_encode_fuzzer.c - test/core/util/one_corpus_entry_fuzzer.c + test/core/slice/percent_encode_fuzzer.cc + test/core/util/one_corpus_entry_fuzzer.cc ) @@ -14870,7 +14743,6 @@ target_include_directories(percent_encode_fuzzer_one_entry PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(percent_encode_fuzzer_one_entry @@ -14885,8 +14757,8 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(server_fuzzer_one_entry - test/core/end2end/fuzzers/server_fuzzer.c - test/core/util/one_corpus_entry_fuzzer.c + test/core/end2end/fuzzers/server_fuzzer.cc + test/core/util/one_corpus_entry_fuzzer.cc ) @@ -14901,7 +14773,6 @@ target_include_directories(server_fuzzer_one_entry PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(server_fuzzer_one_entry @@ -14916,8 +14787,8 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(ssl_server_fuzzer_one_entry - test/core/security/ssl_server_fuzzer.c - test/core/util/one_corpus_entry_fuzzer.c + test/core/security/ssl_server_fuzzer.cc + test/core/util/one_corpus_entry_fuzzer.cc ) @@ -14932,7 +14803,6 @@ target_include_directories(ssl_server_fuzzer_one_entry PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(ssl_server_fuzzer_one_entry @@ -14947,8 +14817,8 @@ endif (gRPC_BUILD_TESTS) if (gRPC_BUILD_TESTS) add_executable(uri_fuzzer_test_one_entry - test/core/client_channel/uri_fuzzer_test.c - test/core/util/one_corpus_entry_fuzzer.c + test/core/client_channel/uri_fuzzer_test.cc + test/core/util/one_corpus_entry_fuzzer.cc ) @@ -14963,7 +14833,6 @@ target_include_directories(uri_fuzzer_test_one_entry PRIVATE ${CARES_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/cares/cares PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/third_party/gflags/include - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp ) target_link_libraries(uri_fuzzer_test_one_entry diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e9c5fe20141..af462468225 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,7 +7,7 @@ If you are new to github, please start by reading [Pull Request howto](https://h ## Legal requirements In order to protect both you and ourselves, you will need to sign the -[Contributor License Agreement](https://cla.developers.google.com/clas). +[Contributor License Agreement](https://identity.linuxfoundation.org/projects/cncf). ## Running tests diff --git a/INSTALL.md b/INSTALL.md index 15725bd188e..430fd71989e 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -95,37 +95,50 @@ on experience with the tools involved. Builds gRPC C and C++ with boringssl. - Install Visual Studio 2015 or 2017 (Visual C++ compiler will be used). +- Install [Git](https://git-scm.com/). - Install [CMake](https://cmake.org/download/). -- Install [Active State Perl](https://www.activestate.com/activeperl/) (`choco install activeperl`) -- Install [Ninja](https://ninja-build.org/) (`choco install ninja`) -- Install [Go](https://golang.org/dl/) (`choco install golang`) -- Install [yasm](http://yasm.tortall.net/) and add it to `PATH` (`choco install yasm`) -- Run these commands in the repo root directory - -#### cmake: Using Ninja (faster build, supports boringssl's assembly optimizations). -Please note that when using Ninja, you'll still need Visual C++ (part of Visual Studio) -installed to be able to compile the C/C++ sources. +- Install [Active State Perl](https://www.activestate.com/activeperl/) (`choco install activeperl`) - *required by boringssl* +- Install [Go](https://golang.org/dl/) (`choco install golang`) - *required by boringssl* +- Install [yasm](http://yasm.tortall.net/) and add it to `PATH` (`choco install yasm`) - *required by boringssl* +- (Optional) Install [Ninja](https://ninja-build.org/) (`choco install ninja`) + +#### Clone grpc sources including submodules +Before building, you need to clone the gRPC github repository and download submodules containing source code +for gRPC's dependencies (that's done by the `submodule` command). ``` -> md .build -> cd .build -> call "%VS140COMNTOOLS%..\..\VC\vcvarsall.bat" x64 -> cmake .. -GNinja -DCMAKE_BUILD_TYPE=Release -> cmake --build . +> @rem You can also do just "git clone --recursive -b THE_BRANCH_YOU_WANT https://github.com/grpc/grpc" +> powershell git clone --recursive -b ((New-Object System.Net.WebClient).DownloadString(\"https://grpc.io/release\").Trim()) https://github.com/grpc/grpc +> cd grpc +> @rem To update submodules at later time, run "git submodule update --init" ``` -#### cmake: Using Visual Studio 2015 (can only build with OPENSSL_NO_ASM). +#### cmake: Using Visual Studio 2015 or 2017 (can only build with OPENSSL_NO_ASM). When using the "Visual Studio" generator, cmake will generate a solution (`grpc.sln`) that contains a VS project for every target defined in `CMakeLists.txt` (+ few extra convenience projects added automatically by cmake). After opening the solution with Visual Studio you will be able to browse and build the code as usual. ``` +> @rem Run from grpc directory after cloning the repo with --recursive or updating submodules. > md .build > cd .build > cmake .. -G "Visual Studio 14 2015" -DCMAKE_BUILD_TYPE=Release > cmake --build . ``` +#### cmake: Using Ninja (faster build, supports boringssl's assembly optimizations). +Please note that when using Ninja, you'll still need Visual C++ (part of Visual Studio) +installed to be able to compile the C/C++ sources. +``` +> @rem Run from grpc directory after cloning the repo with --recursive or updating submodules. +> md .build +> cd .build +> call "%VS140COMNTOOLS%..\..\VC\vcvarsall.bat" x64 +> cmake .. -GNinja -DCMAKE_BUILD_TYPE=Release +> cmake --build . +> ninja +``` + ### msys2 (with mingw) The Makefile (and source code) should support msys2's mingw32 and mingw64 diff --git a/Makefile b/Makefile index ff26247548d..9dfd2a8ae2c 100644 --- a/Makefile +++ b/Makefile @@ -114,7 +114,7 @@ CC_msan = clang CXX_msan = clang++ LD_msan = clang++ LDXX_msan = clang++ -CPPFLAGS_msan = -O0 -fsanitize-coverage=edge -fsanitize=memory -fsanitize-memory-track-origins -fno-omit-frame-pointer -DGTEST_HAS_TR1_TUPLE=0 -DGTEST_USE_OWN_TR1_TUPLE=1 -Wno-unused-command-line-argument -fPIE -pie -DGPR_NO_DIRECT_SYSCALLS +CPPFLAGS_msan = -O0 -fsanitize-coverage=edge -fsanitize=memory -fsanitize-memory-track-origins -fsanitize-memory-use-after-dtor -fno-omit-frame-pointer -DGTEST_HAS_TR1_TUPLE=0 -DGTEST_USE_OWN_TR1_TUPLE=1 -Wno-unused-command-line-argument -fPIE -pie -DGPR_NO_DIRECT_SYSCALLS LDFLAGS_msan = -fsanitize=memory -DGTEST_HAS_TR1_TUPLE=0 -DGTEST_USE_OWN_TR1_TUPLE=1 -fPIE -pie $(if $(JENKINS_BUILD),-Wl$(comma)-Ttext-segment=0x7e0000000000,) DEFINES_msan = NDEBUG @@ -327,7 +327,8 @@ CXXFLAGS += -std=c++11 ifeq ($(SYSTEM),Darwin) CXXFLAGS += -stdlib=libc++ endif -CPPFLAGS += -g -Wall -Wextra -Werror -Wno-long-long -Wno-unused-parameter -DOSATOMIC_USE_INLINED=1 -Ithird_party/abseil-cpp +CPPFLAGS += -g -Wall -Wextra -Werror -Wno-long-long -Wno-unused-parameter -DOSATOMIC_USE_INLINED=1 +COREFLAGS += -fno-rtti -fno-exceptions LDFLAGS += -g CPPFLAGS += $(CPPFLAGS_$(CONFIG)) @@ -411,8 +412,8 @@ Q = @ endif CORE_VERSION = 5.0.0-dev -CPP_VERSION = 1.8.0-dev -CSHARP_VERSION = 1.8.0-dev +CPP_VERSION = 1.9.0-dev +CSHARP_VERSION = 1.9.0-dev CPPFLAGS_NO_ARCH += $(addprefix -I, $(INCLUDES)) $(addprefix -D, $(DEFINES)) CPPFLAGS += $(CPPFLAGS_NO_ARCH) $(ARCH_FLAGS) @@ -987,12 +988,11 @@ gpr_avl_test: $(BINDIR)/$(CONFIG)/gpr_avl_test gpr_cmdline_test: $(BINDIR)/$(CONFIG)/gpr_cmdline_test gpr_cpu_test: $(BINDIR)/$(CONFIG)/gpr_cpu_test gpr_env_test: $(BINDIR)/$(CONFIG)/gpr_env_test -gpr_histogram_test: $(BINDIR)/$(CONFIG)/gpr_histogram_test gpr_host_port_test: $(BINDIR)/$(CONFIG)/gpr_host_port_test gpr_log_test: $(BINDIR)/$(CONFIG)/gpr_log_test +gpr_manual_constructor_test: $(BINDIR)/$(CONFIG)/gpr_manual_constructor_test gpr_mpscq_test: $(BINDIR)/$(CONFIG)/gpr_mpscq_test gpr_spinlock_test: $(BINDIR)/$(CONFIG)/gpr_spinlock_test -gpr_stack_lockfree_test: $(BINDIR)/$(CONFIG)/gpr_stack_lockfree_test gpr_string_test: $(BINDIR)/$(CONFIG)/gpr_string_test gpr_sync_test: $(BINDIR)/$(CONFIG)/gpr_sync_test gpr_thd_test: $(BINDIR)/$(CONFIG)/gpr_thd_test @@ -1019,6 +1019,8 @@ grpc_ssl_credentials_test: $(BINDIR)/$(CONFIG)/grpc_ssl_credentials_test grpc_verify_jwt: $(BINDIR)/$(CONFIG)/grpc_verify_jwt handshake_client: $(BINDIR)/$(CONFIG)/handshake_client handshake_server: $(BINDIR)/$(CONFIG)/handshake_server +handshake_server_with_readahead_handshaker: $(BINDIR)/$(CONFIG)/handshake_server_with_readahead_handshaker +histogram_test: $(BINDIR)/$(CONFIG)/histogram_test hpack_parser_fuzzer_test: $(BINDIR)/$(CONFIG)/hpack_parser_fuzzer_test hpack_parser_test: $(BINDIR)/$(CONFIG)/hpack_parser_test hpack_table_test: $(BINDIR)/$(CONFIG)/hpack_table_test @@ -1112,7 +1114,9 @@ bm_metadata: $(BINDIR)/$(CONFIG)/bm_metadata bm_pollset: $(BINDIR)/$(CONFIG)/bm_pollset channel_arguments_test: $(BINDIR)/$(CONFIG)/channel_arguments_test channel_filter_test: $(BINDIR)/$(CONFIG)/channel_filter_test +chttp2_settings_timeout_test: $(BINDIR)/$(CONFIG)/chttp2_settings_timeout_test cli_call_test: $(BINDIR)/$(CONFIG)/cli_call_test +client_channel_stress_test: $(BINDIR)/$(CONFIG)/client_channel_stress_test client_crash_test: $(BINDIR)/$(CONFIG)/client_crash_test client_crash_test_server: $(BINDIR)/$(CONFIG)/client_crash_test_server client_lb_end2end_test: $(BINDIR)/$(CONFIG)/client_lb_end2end_test @@ -1161,6 +1165,8 @@ qps_openloop_test: $(BINDIR)/$(CONFIG)/qps_openloop_test qps_worker: $(BINDIR)/$(CONFIG)/qps_worker reconnect_interop_client: $(BINDIR)/$(CONFIG)/reconnect_interop_client reconnect_interop_server: $(BINDIR)/$(CONFIG)/reconnect_interop_server +ref_counted_ptr_test: $(BINDIR)/$(CONFIG)/ref_counted_ptr_test +ref_counted_test: $(BINDIR)/$(CONFIG)/ref_counted_test secure_auth_context_test: $(BINDIR)/$(CONFIG)/secure_auth_context_test secure_sync_unary_ping_pong_test: $(BINDIR)/$(CONFIG)/secure_sync_unary_ping_pong_test server_builder_plugin_test: $(BINDIR)/$(CONFIG)/server_builder_plugin_test @@ -1177,7 +1183,6 @@ stress_test: $(BINDIR)/$(CONFIG)/stress_test thread_manager_test: $(BINDIR)/$(CONFIG)/thread_manager_test thread_stress_test: $(BINDIR)/$(CONFIG)/thread_stress_test transport_pid_controller_test: $(BINDIR)/$(CONFIG)/transport_pid_controller_test -vector_test: $(BINDIR)/$(CONFIG)/vector_test writes_per_rpc_test: $(BINDIR)/$(CONFIG)/writes_per_rpc_test public_headers_must_be_c89: $(BINDIR)/$(CONFIG)/public_headers_must_be_c89 boringssl_aes_test: $(BINDIR)/$(CONFIG)/boringssl_aes_test @@ -1379,12 +1384,11 @@ buildtests_c: privatelibs_c \ $(BINDIR)/$(CONFIG)/gpr_cmdline_test \ $(BINDIR)/$(CONFIG)/gpr_cpu_test \ $(BINDIR)/$(CONFIG)/gpr_env_test \ - $(BINDIR)/$(CONFIG)/gpr_histogram_test \ $(BINDIR)/$(CONFIG)/gpr_host_port_test \ $(BINDIR)/$(CONFIG)/gpr_log_test \ + $(BINDIR)/$(CONFIG)/gpr_manual_constructor_test \ $(BINDIR)/$(CONFIG)/gpr_mpscq_test \ $(BINDIR)/$(CONFIG)/gpr_spinlock_test \ - $(BINDIR)/$(CONFIG)/gpr_stack_lockfree_test \ $(BINDIR)/$(CONFIG)/gpr_string_test \ $(BINDIR)/$(CONFIG)/gpr_sync_test \ $(BINDIR)/$(CONFIG)/gpr_thd_test \ @@ -1408,6 +1412,8 @@ buildtests_c: privatelibs_c \ $(BINDIR)/$(CONFIG)/grpc_ssl_credentials_test \ $(BINDIR)/$(CONFIG)/handshake_client \ $(BINDIR)/$(CONFIG)/handshake_server \ + $(BINDIR)/$(CONFIG)/handshake_server_with_readahead_handshaker \ + $(BINDIR)/$(CONFIG)/histogram_test \ $(BINDIR)/$(CONFIG)/hpack_parser_test \ $(BINDIR)/$(CONFIG)/hpack_table_test \ $(BINDIR)/$(CONFIG)/http_parser_test \ @@ -1552,7 +1558,9 @@ buildtests_cxx: privatelibs_cxx \ $(BINDIR)/$(CONFIG)/bm_pollset \ $(BINDIR)/$(CONFIG)/channel_arguments_test \ $(BINDIR)/$(CONFIG)/channel_filter_test \ + $(BINDIR)/$(CONFIG)/chttp2_settings_timeout_test \ $(BINDIR)/$(CONFIG)/cli_call_test \ + $(BINDIR)/$(CONFIG)/client_channel_stress_test \ $(BINDIR)/$(CONFIG)/client_crash_test \ $(BINDIR)/$(CONFIG)/client_crash_test_server \ $(BINDIR)/$(CONFIG)/client_lb_end2end_test \ @@ -1594,6 +1602,8 @@ buildtests_cxx: privatelibs_cxx \ $(BINDIR)/$(CONFIG)/qps_worker \ $(BINDIR)/$(CONFIG)/reconnect_interop_client \ $(BINDIR)/$(CONFIG)/reconnect_interop_server \ + $(BINDIR)/$(CONFIG)/ref_counted_ptr_test \ + $(BINDIR)/$(CONFIG)/ref_counted_test \ $(BINDIR)/$(CONFIG)/secure_auth_context_test \ $(BINDIR)/$(CONFIG)/secure_sync_unary_ping_pong_test \ $(BINDIR)/$(CONFIG)/server_builder_plugin_test \ @@ -1610,7 +1620,6 @@ buildtests_cxx: privatelibs_cxx \ $(BINDIR)/$(CONFIG)/thread_manager_test \ $(BINDIR)/$(CONFIG)/thread_stress_test \ $(BINDIR)/$(CONFIG)/transport_pid_controller_test \ - $(BINDIR)/$(CONFIG)/vector_test \ $(BINDIR)/$(CONFIG)/writes_per_rpc_test \ $(BINDIR)/$(CONFIG)/boringssl_aes_test \ $(BINDIR)/$(CONFIG)/boringssl_asn1_test \ @@ -1677,7 +1686,9 @@ buildtests_cxx: privatelibs_cxx \ $(BINDIR)/$(CONFIG)/bm_pollset \ $(BINDIR)/$(CONFIG)/channel_arguments_test \ $(BINDIR)/$(CONFIG)/channel_filter_test \ + $(BINDIR)/$(CONFIG)/chttp2_settings_timeout_test \ $(BINDIR)/$(CONFIG)/cli_call_test \ + $(BINDIR)/$(CONFIG)/client_channel_stress_test \ $(BINDIR)/$(CONFIG)/client_crash_test \ $(BINDIR)/$(CONFIG)/client_crash_test_server \ $(BINDIR)/$(CONFIG)/client_lb_end2end_test \ @@ -1719,6 +1730,8 @@ buildtests_cxx: privatelibs_cxx \ $(BINDIR)/$(CONFIG)/qps_worker \ $(BINDIR)/$(CONFIG)/reconnect_interop_client \ $(BINDIR)/$(CONFIG)/reconnect_interop_server \ + $(BINDIR)/$(CONFIG)/ref_counted_ptr_test \ + $(BINDIR)/$(CONFIG)/ref_counted_test \ $(BINDIR)/$(CONFIG)/secure_auth_context_test \ $(BINDIR)/$(CONFIG)/secure_sync_unary_ping_pong_test \ $(BINDIR)/$(CONFIG)/server_builder_plugin_test \ @@ -1735,7 +1748,6 @@ buildtests_cxx: privatelibs_cxx \ $(BINDIR)/$(CONFIG)/thread_manager_test \ $(BINDIR)/$(CONFIG)/thread_stress_test \ $(BINDIR)/$(CONFIG)/transport_pid_controller_test \ - $(BINDIR)/$(CONFIG)/vector_test \ $(BINDIR)/$(CONFIG)/writes_per_rpc_test \ $(BINDIR)/$(CONFIG)/resolver_component_test_unsecure \ $(BINDIR)/$(CONFIG)/resolver_component_test \ @@ -1820,18 +1832,16 @@ test_c: buildtests_c $(Q) $(BINDIR)/$(CONFIG)/gpr_cpu_test || ( echo test gpr_cpu_test failed ; exit 1 ) $(E) "[RUN] Testing gpr_env_test" $(Q) $(BINDIR)/$(CONFIG)/gpr_env_test || ( echo test gpr_env_test failed ; exit 1 ) - $(E) "[RUN] Testing gpr_histogram_test" - $(Q) $(BINDIR)/$(CONFIG)/gpr_histogram_test || ( echo test gpr_histogram_test failed ; exit 1 ) $(E) "[RUN] Testing gpr_host_port_test" $(Q) $(BINDIR)/$(CONFIG)/gpr_host_port_test || ( echo test gpr_host_port_test failed ; exit 1 ) $(E) "[RUN] Testing gpr_log_test" $(Q) $(BINDIR)/$(CONFIG)/gpr_log_test || ( echo test gpr_log_test failed ; exit 1 ) + $(E) "[RUN] Testing gpr_manual_constructor_test" + $(Q) $(BINDIR)/$(CONFIG)/gpr_manual_constructor_test || ( echo test gpr_manual_constructor_test failed ; exit 1 ) $(E) "[RUN] Testing gpr_mpscq_test" $(Q) $(BINDIR)/$(CONFIG)/gpr_mpscq_test || ( echo test gpr_mpscq_test failed ; exit 1 ) $(E) "[RUN] Testing gpr_spinlock_test" $(Q) $(BINDIR)/$(CONFIG)/gpr_spinlock_test || ( echo test gpr_spinlock_test failed ; exit 1 ) - $(E) "[RUN] Testing gpr_stack_lockfree_test" - $(Q) $(BINDIR)/$(CONFIG)/gpr_stack_lockfree_test || ( echo test gpr_stack_lockfree_test failed ; exit 1 ) $(E) "[RUN] Testing gpr_string_test" $(Q) $(BINDIR)/$(CONFIG)/gpr_string_test || ( echo test gpr_string_test failed ; exit 1 ) $(E) "[RUN] Testing gpr_sync_test" @@ -1876,6 +1886,10 @@ test_c: buildtests_c $(Q) $(BINDIR)/$(CONFIG)/handshake_client || ( echo test handshake_client failed ; exit 1 ) $(E) "[RUN] Testing handshake_server" $(Q) $(BINDIR)/$(CONFIG)/handshake_server || ( echo test handshake_server failed ; exit 1 ) + $(E) "[RUN] Testing handshake_server_with_readahead_handshaker" + $(Q) $(BINDIR)/$(CONFIG)/handshake_server_with_readahead_handshaker || ( echo test handshake_server_with_readahead_handshaker failed ; exit 1 ) + $(E) "[RUN] Testing histogram_test" + $(Q) $(BINDIR)/$(CONFIG)/histogram_test || ( echo test histogram_test failed ; exit 1 ) $(E) "[RUN] Testing hpack_parser_test" $(Q) $(BINDIR)/$(CONFIG)/hpack_parser_test || ( echo test hpack_parser_test failed ; exit 1 ) $(E) "[RUN] Testing hpack_table_test" @@ -2058,8 +2072,12 @@ test_cxx: buildtests_cxx $(Q) $(BINDIR)/$(CONFIG)/channel_arguments_test || ( echo test channel_arguments_test failed ; exit 1 ) $(E) "[RUN] Testing channel_filter_test" $(Q) $(BINDIR)/$(CONFIG)/channel_filter_test || ( echo test channel_filter_test failed ; exit 1 ) + $(E) "[RUN] Testing chttp2_settings_timeout_test" + $(Q) $(BINDIR)/$(CONFIG)/chttp2_settings_timeout_test || ( echo test chttp2_settings_timeout_test failed ; exit 1 ) $(E) "[RUN] Testing cli_call_test" $(Q) $(BINDIR)/$(CONFIG)/cli_call_test || ( echo test cli_call_test failed ; exit 1 ) + $(E) "[RUN] Testing client_channel_stress_test" + $(Q) $(BINDIR)/$(CONFIG)/client_channel_stress_test || ( echo test client_channel_stress_test failed ; exit 1 ) $(E) "[RUN] Testing client_crash_test" $(Q) $(BINDIR)/$(CONFIG)/client_crash_test || ( echo test client_crash_test failed ; exit 1 ) $(E) "[RUN] Testing client_lb_end2end_test" @@ -2116,6 +2134,10 @@ test_cxx: buildtests_cxx $(Q) $(BINDIR)/$(CONFIG)/proto_utils_test || ( echo test proto_utils_test failed ; exit 1 ) $(E) "[RUN] Testing qps_openloop_test" $(Q) $(BINDIR)/$(CONFIG)/qps_openloop_test || ( echo test qps_openloop_test failed ; exit 1 ) + $(E) "[RUN] Testing ref_counted_ptr_test" + $(Q) $(BINDIR)/$(CONFIG)/ref_counted_ptr_test || ( echo test ref_counted_ptr_test failed ; exit 1 ) + $(E) "[RUN] Testing ref_counted_test" + $(Q) $(BINDIR)/$(CONFIG)/ref_counted_test || ( echo test ref_counted_test failed ; exit 1 ) $(E) "[RUN] Testing secure_auth_context_test" $(Q) $(BINDIR)/$(CONFIG)/secure_auth_context_test || ( echo test secure_auth_context_test failed ; exit 1 ) $(E) "[RUN] Testing secure_sync_unary_ping_pong_test" @@ -2144,8 +2166,6 @@ test_cxx: buildtests_cxx $(Q) $(BINDIR)/$(CONFIG)/thread_stress_test || ( echo test thread_stress_test failed ; exit 1 ) $(E) "[RUN] Testing transport_pid_controller_test" $(Q) $(BINDIR)/$(CONFIG)/transport_pid_controller_test || ( echo test transport_pid_controller_test failed ; exit 1 ) - $(E) "[RUN] Testing vector_test" - $(Q) $(BINDIR)/$(CONFIG)/vector_test || ( echo test vector_test failed ; exit 1 ) $(E) "[RUN] Testing writes_per_rpc_test" $(Q) $(BINDIR)/$(CONFIG)/writes_per_rpc_test || ( echo test writes_per_rpc_test failed ; exit 1 ) $(E) "[RUN] Testing resolver_component_tests_runner_invoker_unsecure" @@ -2499,12 +2519,12 @@ $(GENDIR)/src/proto/grpc/testing/services.pb.cc: protoc_dep_error $(GENDIR)/src/proto/grpc/testing/services.grpc.pb.cc: protoc_dep_error else -$(GENDIR)/src/proto/grpc/testing/services.pb.cc: src/proto/grpc/testing/services.proto $(PROTOBUF_DEP) $(PROTOC_PLUGINS) $(GENDIR)/src/proto/grpc/testing/messages.pb.cc $(GENDIR)/src/proto/grpc/testing/control.pb.cc $(GENDIR)/src/proto/grpc/testing/stats.pb.cc +$(GENDIR)/src/proto/grpc/testing/services.pb.cc: src/proto/grpc/testing/services.proto $(PROTOBUF_DEP) $(PROTOC_PLUGINS) $(GENDIR)/src/proto/grpc/testing/messages.pb.cc $(GENDIR)/src/proto/grpc/testing/control.pb.cc $(E) "[PROTOC] Generating protobuf CC file from $<" $(Q) mkdir -p `dirname $@` $(Q) $(PROTOC) -Ithird_party/protobuf/src -I. --cpp_out=$(GENDIR) $< -$(GENDIR)/src/proto/grpc/testing/services.grpc.pb.cc: src/proto/grpc/testing/services.proto $(GENDIR)/src/proto/grpc/testing/services.pb.cc $(PROTOBUF_DEP) $(PROTOC_PLUGINS) $(GENDIR)/src/proto/grpc/testing/messages.pb.cc $(GENDIR)/src/proto/grpc/testing/messages.grpc.pb.cc $(GENDIR)/src/proto/grpc/testing/control.pb.cc $(GENDIR)/src/proto/grpc/testing/control.grpc.pb.cc $(GENDIR)/src/proto/grpc/testing/stats.pb.cc $(GENDIR)/src/proto/grpc/testing/stats.grpc.pb.cc +$(GENDIR)/src/proto/grpc/testing/services.grpc.pb.cc: src/proto/grpc/testing/services.proto $(GENDIR)/src/proto/grpc/testing/services.pb.cc $(PROTOBUF_DEP) $(PROTOC_PLUGINS) $(GENDIR)/src/proto/grpc/testing/messages.pb.cc $(GENDIR)/src/proto/grpc/testing/messages.grpc.pb.cc $(GENDIR)/src/proto/grpc/testing/control.pb.cc $(GENDIR)/src/proto/grpc/testing/control.grpc.pb.cc $(E) "[GRPC] Generating gRPC's protobuf service CC file from $<" $(Q) mkdir -p `dirname $@` $(Q) $(PROTOC) -Ithird_party/protobuf/src -I. --grpc_out=$(GENDIR) --plugin=protoc-gen-grpc=$(PROTOC_PLUGINS_DIR)/grpc_cpp_plugin$(EXECUTABLE_SUFFIX) $< @@ -2570,6 +2590,16 @@ $(OBJDIR)/$(CONFIG)/src/compiler/%.o : src/compiler/%.cc $(Q) mkdir -p `dirname $@` $(Q) $(HOST_CXX) $(HOST_CXXFLAGS) $(HOST_CPPFLAGS) -MMD -MF $(addsuffix .dep, $(basename $@)) -c -o $@ $< +$(OBJDIR)/$(CONFIG)/src/core/%.o : src/core/%.cc + $(E) "[CXX] Compiling $<" + $(Q) mkdir -p `dirname $@` + $(Q) $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(COREFLAGS) -MMD -MF $(addsuffix .dep, $(basename $@)) -c -o $@ $< + +$(OBJDIR)/$(CONFIG)/test/core/%.o : test/core/%.cc + $(E) "[CXX] Compiling $<" + $(Q) mkdir -p `dirname $@` + $(Q) $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(COREFLAGS) -MMD -MF $(addsuffix .dep, $(basename $@)) -c -o $@ $< + $(OBJDIR)/$(CONFIG)/%.o : %.cc $(E) "[CXX] Compiling $<" $(Q) mkdir -p `dirname $@` @@ -2803,7 +2833,7 @@ LIBGPR_SRC = \ src/core/lib/support/env_linux.cc \ src/core/lib/support/env_posix.cc \ src/core/lib/support/env_windows.cc \ - src/core/lib/support/histogram.cc \ + src/core/lib/support/fork.cc \ src/core/lib/support/host_port.cc \ src/core/lib/support/log.cc \ src/core/lib/support/log_android.cc \ @@ -2812,7 +2842,6 @@ LIBGPR_SRC = \ src/core/lib/support/log_windows.cc \ src/core/lib/support/mpscq.cc \ src/core/lib/support/murmur_hash.cc \ - src/core/lib/support/stack_lockfree.cc \ src/core/lib/support/string.cc \ src/core/lib/support/string_posix.cc \ src/core/lib/support/string_util_windows.cc \ @@ -2844,7 +2873,6 @@ PUBLIC_HEADERS_C += \ include/grpc/support/avl.h \ include/grpc/support/cmdline.h \ include/grpc/support/cpu.h \ - include/grpc/support/histogram.h \ include/grpc/support/host_port.h \ include/grpc/support/log.h \ include/grpc/support/log_windows.h \ @@ -2867,6 +2895,7 @@ PUBLIC_HEADERS_C += \ include/grpc/impl/codegen/atm_gcc_atomic.h \ include/grpc/impl/codegen/atm_gcc_sync.h \ include/grpc/impl/codegen/atm_windows.h \ + include/grpc/impl/codegen/fork.h \ include/grpc/impl/codegen/gpr_slice.h \ include/grpc/impl/codegen/gpr_types.h \ include/grpc/impl/codegen/port_platform.h \ @@ -2914,7 +2943,7 @@ endif LIBGPR_TEST_UTIL_SRC = \ - test/core/util/test_config.c \ + test/core/util/test_config.cc \ PUBLIC_HEADERS_C += \ @@ -2959,7 +2988,6 @@ LIBGRPC_SRC = \ src/core/lib/http/httpcli.cc \ src/core/lib/http/parser.cc \ src/core/lib/iomgr/call_combiner.cc \ - src/core/lib/iomgr/closure.cc \ src/core/lib/iomgr/combiner.cc \ src/core/lib/iomgr/endpoint.cc \ src/core/lib/iomgr/endpoint_pair_posix.cc \ @@ -2974,6 +3002,8 @@ LIBGRPC_SRC = \ src/core/lib/iomgr/ev_windows.cc \ src/core/lib/iomgr/exec_ctx.cc \ src/core/lib/iomgr/executor.cc \ + src/core/lib/iomgr/fork_posix.cc \ + src/core/lib/iomgr/fork_windows.cc \ src/core/lib/iomgr/gethostname_fallback.cc \ src/core/lib/iomgr/gethostname_host_name_max.cc \ src/core/lib/iomgr/gethostname_sysconf.cc \ @@ -3204,6 +3234,7 @@ PUBLIC_HEADERS_C += \ include/grpc/impl/codegen/atm_gcc_atomic.h \ include/grpc/impl/codegen/atm_gcc_sync.h \ include/grpc/impl/codegen/atm_windows.h \ + include/grpc/impl/codegen/fork.h \ include/grpc/impl/codegen/gpr_slice.h \ include/grpc/impl/codegen/gpr_types.h \ include/grpc/impl/codegen/port_platform.h \ @@ -3216,6 +3247,7 @@ PUBLIC_HEADERS_C += \ include/grpc/byte_buffer.h \ include/grpc/byte_buffer_reader.h \ include/grpc/compression.h \ + include/grpc/fork.h \ include/grpc/grpc.h \ include/grpc/grpc_posix.h \ include/grpc/grpc_security_constants.h \ @@ -3299,7 +3331,6 @@ LIBGRPC_CRONET_SRC = \ src/core/lib/http/httpcli.cc \ src/core/lib/http/parser.cc \ src/core/lib/iomgr/call_combiner.cc \ - src/core/lib/iomgr/closure.cc \ src/core/lib/iomgr/combiner.cc \ src/core/lib/iomgr/endpoint.cc \ src/core/lib/iomgr/endpoint_pair_posix.cc \ @@ -3314,6 +3345,8 @@ LIBGRPC_CRONET_SRC = \ src/core/lib/iomgr/ev_windows.cc \ src/core/lib/iomgr/exec_ctx.cc \ src/core/lib/iomgr/executor.cc \ + src/core/lib/iomgr/fork_posix.cc \ + src/core/lib/iomgr/fork_windows.cc \ src/core/lib/iomgr/gethostname_fallback.cc \ src/core/lib/iomgr/gethostname_host_name_max.cc \ src/core/lib/iomgr/gethostname_sysconf.cc \ @@ -3515,6 +3548,7 @@ PUBLIC_HEADERS_C += \ include/grpc/impl/codegen/atm_gcc_atomic.h \ include/grpc/impl/codegen/atm_gcc_sync.h \ include/grpc/impl/codegen/atm_windows.h \ + include/grpc/impl/codegen/fork.h \ include/grpc/impl/codegen/gpr_slice.h \ include/grpc/impl/codegen/gpr_types.h \ include/grpc/impl/codegen/port_platform.h \ @@ -3580,26 +3614,29 @@ endif LIBGRPC_TEST_UTIL_SRC = \ - test/core/end2end/data/client_certs.c \ - test/core/end2end/data/server1_cert.c \ - test/core/end2end/data/server1_key.c \ - test/core/end2end/data/test_root_cert.c \ - test/core/security/oauth2_utils.c \ + test/core/end2end/data/client_certs.cc \ + test/core/end2end/data/server1_cert.cc \ + test/core/end2end/data/server1_key.cc \ + test/core/end2end/data/test_root_cert.cc \ + test/core/security/oauth2_utils.cc \ src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc \ - test/core/end2end/cq_verifier.c \ - test/core/end2end/fixtures/http_proxy_fixture.c \ - test/core/end2end/fixtures/proxy.c \ - test/core/iomgr/endpoint_tests.c \ + test/core/end2end/cq_verifier.cc \ + test/core/end2end/fixtures/http_proxy_fixture.cc \ + test/core/end2end/fixtures/proxy.cc \ + test/core/iomgr/endpoint_tests.cc \ test/core/util/debugger_macros.cc \ - test/core/util/grpc_profiler.c \ - test/core/util/memory_counters.c \ - test/core/util/mock_endpoint.c \ - test/core/util/parse_hexstring.c \ - test/core/util/passthru_endpoint.c \ - test/core/util/port.c \ - test/core/util/port_server_client.c \ - test/core/util/slice_splitter.c \ - test/core/util/trickle_endpoint.c \ + test/core/util/grpc_profiler.cc \ + test/core/util/histogram.cc \ + test/core/util/memory_counters.cc \ + test/core/util/mock_endpoint.cc \ + test/core/util/parse_hexstring.cc \ + test/core/util/passthru_endpoint.cc \ + test/core/util/port.cc \ + test/core/util/port_isolated_runtime_environment.cc \ + test/core/util/port_server_client.cc \ + test/core/util/slice_splitter.cc \ + test/core/util/tracer_util.cc \ + test/core/util/trickle_endpoint.cc \ src/core/lib/backoff/backoff.cc \ src/core/lib/channel/channel_args.cc \ src/core/lib/channel/channel_stack.cc \ @@ -3619,7 +3656,6 @@ LIBGRPC_TEST_UTIL_SRC = \ src/core/lib/http/httpcli.cc \ src/core/lib/http/parser.cc \ src/core/lib/iomgr/call_combiner.cc \ - src/core/lib/iomgr/closure.cc \ src/core/lib/iomgr/combiner.cc \ src/core/lib/iomgr/endpoint.cc \ src/core/lib/iomgr/endpoint_pair_posix.cc \ @@ -3634,6 +3670,8 @@ LIBGRPC_TEST_UTIL_SRC = \ src/core/lib/iomgr/ev_windows.cc \ src/core/lib/iomgr/exec_ctx.cc \ src/core/lib/iomgr/executor.cc \ + src/core/lib/iomgr/fork_posix.cc \ + src/core/lib/iomgr/fork_windows.cc \ src/core/lib/iomgr/gethostname_fallback.cc \ src/core/lib/iomgr/gethostname_host_name_max.cc \ src/core/lib/iomgr/gethostname_sysconf.cc \ @@ -3797,6 +3835,7 @@ PUBLIC_HEADERS_C += \ include/grpc/impl/codegen/atm_gcc_atomic.h \ include/grpc/impl/codegen/atm_gcc_sync.h \ include/grpc/impl/codegen/atm_windows.h \ + include/grpc/impl/codegen/fork.h \ include/grpc/impl/codegen/gpr_slice.h \ include/grpc/impl/codegen/gpr_types.h \ include/grpc/impl/codegen/port_platform.h \ @@ -3842,20 +3881,23 @@ endif LIBGRPC_TEST_UTIL_UNSECURE_SRC = \ src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc \ - test/core/end2end/cq_verifier.c \ - test/core/end2end/fixtures/http_proxy_fixture.c \ - test/core/end2end/fixtures/proxy.c \ - test/core/iomgr/endpoint_tests.c \ + test/core/end2end/cq_verifier.cc \ + test/core/end2end/fixtures/http_proxy_fixture.cc \ + test/core/end2end/fixtures/proxy.cc \ + test/core/iomgr/endpoint_tests.cc \ test/core/util/debugger_macros.cc \ - test/core/util/grpc_profiler.c \ - test/core/util/memory_counters.c \ - test/core/util/mock_endpoint.c \ - test/core/util/parse_hexstring.c \ - test/core/util/passthru_endpoint.c \ - test/core/util/port.c \ - test/core/util/port_server_client.c \ - test/core/util/slice_splitter.c \ - test/core/util/trickle_endpoint.c \ + test/core/util/grpc_profiler.cc \ + test/core/util/histogram.cc \ + test/core/util/memory_counters.cc \ + test/core/util/mock_endpoint.cc \ + test/core/util/parse_hexstring.cc \ + test/core/util/passthru_endpoint.cc \ + test/core/util/port.cc \ + test/core/util/port_isolated_runtime_environment.cc \ + test/core/util/port_server_client.cc \ + test/core/util/slice_splitter.cc \ + test/core/util/tracer_util.cc \ + test/core/util/trickle_endpoint.cc \ src/core/lib/backoff/backoff.cc \ src/core/lib/channel/channel_args.cc \ src/core/lib/channel/channel_stack.cc \ @@ -3875,7 +3917,6 @@ LIBGRPC_TEST_UTIL_UNSECURE_SRC = \ src/core/lib/http/httpcli.cc \ src/core/lib/http/parser.cc \ src/core/lib/iomgr/call_combiner.cc \ - src/core/lib/iomgr/closure.cc \ src/core/lib/iomgr/combiner.cc \ src/core/lib/iomgr/endpoint.cc \ src/core/lib/iomgr/endpoint_pair_posix.cc \ @@ -3890,6 +3931,8 @@ LIBGRPC_TEST_UTIL_UNSECURE_SRC = \ src/core/lib/iomgr/ev_windows.cc \ src/core/lib/iomgr/exec_ctx.cc \ src/core/lib/iomgr/executor.cc \ + src/core/lib/iomgr/fork_posix.cc \ + src/core/lib/iomgr/fork_windows.cc \ src/core/lib/iomgr/gethostname_fallback.cc \ src/core/lib/iomgr/gethostname_host_name_max.cc \ src/core/lib/iomgr/gethostname_sysconf.cc \ @@ -4053,6 +4096,7 @@ PUBLIC_HEADERS_C += \ include/grpc/impl/codegen/atm_gcc_atomic.h \ include/grpc/impl/codegen/atm_gcc_sync.h \ include/grpc/impl/codegen/atm_windows.h \ + include/grpc/impl/codegen/fork.h \ include/grpc/impl/codegen/gpr_slice.h \ include/grpc/impl/codegen/gpr_types.h \ include/grpc/impl/codegen/port_platform.h \ @@ -4104,7 +4148,6 @@ LIBGRPC_UNSECURE_SRC = \ src/core/lib/http/httpcli.cc \ src/core/lib/http/parser.cc \ src/core/lib/iomgr/call_combiner.cc \ - src/core/lib/iomgr/closure.cc \ src/core/lib/iomgr/combiner.cc \ src/core/lib/iomgr/endpoint.cc \ src/core/lib/iomgr/endpoint_pair_posix.cc \ @@ -4119,6 +4162,8 @@ LIBGRPC_UNSECURE_SRC = \ src/core/lib/iomgr/ev_windows.cc \ src/core/lib/iomgr/exec_ctx.cc \ src/core/lib/iomgr/executor.cc \ + src/core/lib/iomgr/fork_posix.cc \ + src/core/lib/iomgr/fork_windows.cc \ src/core/lib/iomgr/gethostname_fallback.cc \ src/core/lib/iomgr/gethostname_host_name_max.cc \ src/core/lib/iomgr/gethostname_sysconf.cc \ @@ -4317,6 +4362,7 @@ PUBLIC_HEADERS_C += \ include/grpc/impl/codegen/atm_gcc_atomic.h \ include/grpc/impl/codegen/atm_gcc_sync.h \ include/grpc/impl/codegen/atm_windows.h \ + include/grpc/impl/codegen/fork.h \ include/grpc/impl/codegen/gpr_slice.h \ include/grpc/impl/codegen/gpr_types.h \ include/grpc/impl/codegen/port_platform.h \ @@ -4328,6 +4374,7 @@ PUBLIC_HEADERS_C += \ include/grpc/byte_buffer.h \ include/grpc/byte_buffer_reader.h \ include/grpc/compression.h \ + include/grpc/fork.h \ include/grpc/grpc.h \ include/grpc/grpc_posix.h \ include/grpc/grpc_security_constants.h \ @@ -4376,7 +4423,7 @@ endif LIBRECONNECT_SERVER_SRC = \ - test/core/util/reconnect_server.c \ + test/core/util/reconnect_server.cc \ PUBLIC_HEADERS_C += \ @@ -4415,7 +4462,7 @@ endif LIBTEST_TCP_SERVER_SRC = \ - test/core/util/test_tcp_server.c \ + test/core/util/test_tcp_server.cc \ PUBLIC_HEADERS_C += \ @@ -4551,7 +4598,6 @@ PUBLIC_HEADERS_CXX += \ include/grpc/support/avl.h \ include/grpc/support/cmdline.h \ include/grpc/support/cpu.h \ - include/grpc/support/histogram.h \ include/grpc/support/host_port.h \ include/grpc/support/log.h \ include/grpc/support/log_windows.h \ @@ -4574,6 +4620,7 @@ PUBLIC_HEADERS_CXX += \ include/grpc/impl/codegen/atm_gcc_atomic.h \ include/grpc/impl/codegen/atm_gcc_sync.h \ include/grpc/impl/codegen/atm_windows.h \ + include/grpc/impl/codegen/fork.h \ include/grpc/impl/codegen/gpr_slice.h \ include/grpc/impl/codegen/gpr_types.h \ include/grpc/impl/codegen/port_platform.h \ @@ -4585,6 +4632,7 @@ PUBLIC_HEADERS_CXX += \ include/grpc/byte_buffer.h \ include/grpc/byte_buffer_reader.h \ include/grpc/compression.h \ + include/grpc/fork.h \ include/grpc/grpc.h \ include/grpc/grpc_posix.h \ include/grpc/grpc_security_constants.h \ @@ -4833,7 +4881,6 @@ LIBGRPC++_CRONET_SRC = \ src/core/lib/http/httpcli.cc \ src/core/lib/http/parser.cc \ src/core/lib/iomgr/call_combiner.cc \ - src/core/lib/iomgr/closure.cc \ src/core/lib/iomgr/combiner.cc \ src/core/lib/iomgr/endpoint.cc \ src/core/lib/iomgr/endpoint_pair_posix.cc \ @@ -4848,6 +4895,8 @@ LIBGRPC++_CRONET_SRC = \ src/core/lib/iomgr/ev_windows.cc \ src/core/lib/iomgr/exec_ctx.cc \ src/core/lib/iomgr/executor.cc \ + src/core/lib/iomgr/fork_posix.cc \ + src/core/lib/iomgr/fork_windows.cc \ src/core/lib/iomgr/gethostname_fallback.cc \ src/core/lib/iomgr/gethostname_host_name_max.cc \ src/core/lib/iomgr/gethostname_sysconf.cc \ @@ -5036,7 +5085,6 @@ PUBLIC_HEADERS_CXX += \ include/grpc/support/avl.h \ include/grpc/support/cmdline.h \ include/grpc/support/cpu.h \ - include/grpc/support/histogram.h \ include/grpc/support/host_port.h \ include/grpc/support/log.h \ include/grpc/support/log_windows.h \ @@ -5059,6 +5107,7 @@ PUBLIC_HEADERS_CXX += \ include/grpc/impl/codegen/atm_gcc_atomic.h \ include/grpc/impl/codegen/atm_gcc_sync.h \ include/grpc/impl/codegen/atm_windows.h \ + include/grpc/impl/codegen/fork.h \ include/grpc/impl/codegen/gpr_slice.h \ include/grpc/impl/codegen/gpr_types.h \ include/grpc/impl/codegen/port_platform.h \ @@ -5070,6 +5119,7 @@ PUBLIC_HEADERS_CXX += \ include/grpc/byte_buffer.h \ include/grpc/byte_buffer_reader.h \ include/grpc/compression.h \ + include/grpc/fork.h \ include/grpc/grpc.h \ include/grpc/grpc_posix.h \ include/grpc/grpc_security_constants.h \ @@ -5484,6 +5534,7 @@ PUBLIC_HEADERS_CXX += \ include/grpc/impl/codegen/atm_gcc_atomic.h \ include/grpc/impl/codegen/atm_gcc_sync.h \ include/grpc/impl/codegen/atm_windows.h \ + include/grpc/impl/codegen/fork.h \ include/grpc/impl/codegen/gpr_slice.h \ include/grpc/impl/codegen/gpr_types.h \ include/grpc/impl/codegen/port_platform.h \ @@ -5601,6 +5652,7 @@ PUBLIC_HEADERS_CXX += \ include/grpc/impl/codegen/atm_gcc_atomic.h \ include/grpc/impl/codegen/atm_gcc_sync.h \ include/grpc/impl/codegen/atm_windows.h \ + include/grpc/impl/codegen/fork.h \ include/grpc/impl/codegen/gpr_slice.h \ include/grpc/impl/codegen/gpr_types.h \ include/grpc/impl/codegen/port_platform.h \ @@ -5754,7 +5806,6 @@ PUBLIC_HEADERS_CXX += \ include/grpc/support/avl.h \ include/grpc/support/cmdline.h \ include/grpc/support/cpu.h \ - include/grpc/support/histogram.h \ include/grpc/support/host_port.h \ include/grpc/support/log.h \ include/grpc/support/log_windows.h \ @@ -5777,6 +5828,7 @@ PUBLIC_HEADERS_CXX += \ include/grpc/impl/codegen/atm_gcc_atomic.h \ include/grpc/impl/codegen/atm_gcc_sync.h \ include/grpc/impl/codegen/atm_windows.h \ + include/grpc/impl/codegen/fork.h \ include/grpc/impl/codegen/gpr_slice.h \ include/grpc/impl/codegen/gpr_types.h \ include/grpc/impl/codegen/port_platform.h \ @@ -5788,6 +5840,7 @@ PUBLIC_HEADERS_CXX += \ include/grpc/byte_buffer.h \ include/grpc/byte_buffer_reader.h \ include/grpc/compression.h \ + include/grpc/fork.h \ include/grpc/grpc.h \ include/grpc/grpc_posix.h \ include/grpc/grpc_security_constants.h \ @@ -8403,7 +8456,7 @@ endif LIBBAD_CLIENT_TEST_SRC = \ - test/core/bad_client/bad_client.c \ + test/core/bad_client/bad_client.cc \ PUBLIC_HEADERS_C += \ @@ -8442,7 +8495,7 @@ endif LIBBAD_SSL_TEST_SERVER_SRC = \ - test/core/bad_ssl/server_common.c \ + test/core/bad_ssl/server_common.cc \ PUBLIC_HEADERS_C += \ @@ -8481,67 +8534,67 @@ endif LIBEND2END_TESTS_SRC = \ - test/core/end2end/end2end_tests.c \ - test/core/end2end/end2end_test_utils.c \ - test/core/end2end/tests/authority_not_supported.c \ - test/core/end2end/tests/bad_hostname.c \ - test/core/end2end/tests/bad_ping.c \ - test/core/end2end/tests/binary_metadata.c \ - test/core/end2end/tests/call_creds.c \ - test/core/end2end/tests/cancel_after_accept.c \ - test/core/end2end/tests/cancel_after_client_done.c \ - test/core/end2end/tests/cancel_after_invoke.c \ - test/core/end2end/tests/cancel_after_round_trip.c \ - test/core/end2end/tests/cancel_before_invoke.c \ - test/core/end2end/tests/cancel_in_a_vacuum.c \ - test/core/end2end/tests/cancel_with_status.c \ - test/core/end2end/tests/compressed_payload.c \ - test/core/end2end/tests/connectivity.c \ - test/core/end2end/tests/default_host.c \ - test/core/end2end/tests/disappearing_server.c \ - test/core/end2end/tests/empty_batch.c \ - test/core/end2end/tests/filter_call_init_fails.c \ - test/core/end2end/tests/filter_causes_close.c \ - test/core/end2end/tests/filter_latency.c \ - test/core/end2end/tests/graceful_server_shutdown.c \ - test/core/end2end/tests/high_initial_seqno.c \ - test/core/end2end/tests/hpack_size.c \ - test/core/end2end/tests/idempotent_request.c \ - test/core/end2end/tests/invoke_large_request.c \ - test/core/end2end/tests/keepalive_timeout.c \ - test/core/end2end/tests/large_metadata.c \ - test/core/end2end/tests/load_reporting_hook.c \ - test/core/end2end/tests/max_concurrent_streams.c \ - test/core/end2end/tests/max_connection_age.c \ - test/core/end2end/tests/max_connection_idle.c \ - test/core/end2end/tests/max_message_length.c \ - test/core/end2end/tests/negative_deadline.c \ - test/core/end2end/tests/network_status_change.c \ - test/core/end2end/tests/no_logging.c \ - test/core/end2end/tests/no_op.c \ - test/core/end2end/tests/payload.c \ - test/core/end2end/tests/ping.c \ - test/core/end2end/tests/ping_pong_streaming.c \ - test/core/end2end/tests/proxy_auth.c \ - test/core/end2end/tests/registered_call.c \ - test/core/end2end/tests/request_with_flags.c \ - test/core/end2end/tests/request_with_payload.c \ - test/core/end2end/tests/resource_quota_server.c \ - test/core/end2end/tests/server_finishes_request.c \ - test/core/end2end/tests/shutdown_finishes_calls.c \ - test/core/end2end/tests/shutdown_finishes_tags.c \ - test/core/end2end/tests/simple_cacheable_request.c \ - test/core/end2end/tests/simple_delayed_request.c \ - test/core/end2end/tests/simple_metadata.c \ - test/core/end2end/tests/simple_request.c \ - test/core/end2end/tests/stream_compression_compressed_payload.c \ - test/core/end2end/tests/stream_compression_payload.c \ - test/core/end2end/tests/stream_compression_ping_pong_streaming.c \ - test/core/end2end/tests/streaming_error_response.c \ - test/core/end2end/tests/trailing_metadata.c \ - test/core/end2end/tests/workaround_cronet_compression.c \ - test/core/end2end/tests/write_buffering.c \ - test/core/end2end/tests/write_buffering_at_end.c \ + test/core/end2end/end2end_tests.cc \ + test/core/end2end/end2end_test_utils.cc \ + test/core/end2end/tests/authority_not_supported.cc \ + test/core/end2end/tests/bad_hostname.cc \ + test/core/end2end/tests/bad_ping.cc \ + test/core/end2end/tests/binary_metadata.cc \ + test/core/end2end/tests/call_creds.cc \ + test/core/end2end/tests/cancel_after_accept.cc \ + test/core/end2end/tests/cancel_after_client_done.cc \ + test/core/end2end/tests/cancel_after_invoke.cc \ + test/core/end2end/tests/cancel_after_round_trip.cc \ + test/core/end2end/tests/cancel_before_invoke.cc \ + test/core/end2end/tests/cancel_in_a_vacuum.cc \ + test/core/end2end/tests/cancel_with_status.cc \ + test/core/end2end/tests/compressed_payload.cc \ + test/core/end2end/tests/connectivity.cc \ + test/core/end2end/tests/default_host.cc \ + test/core/end2end/tests/disappearing_server.cc \ + test/core/end2end/tests/empty_batch.cc \ + test/core/end2end/tests/filter_call_init_fails.cc \ + test/core/end2end/tests/filter_causes_close.cc \ + test/core/end2end/tests/filter_latency.cc \ + test/core/end2end/tests/graceful_server_shutdown.cc \ + test/core/end2end/tests/high_initial_seqno.cc \ + test/core/end2end/tests/hpack_size.cc \ + test/core/end2end/tests/idempotent_request.cc \ + test/core/end2end/tests/invoke_large_request.cc \ + test/core/end2end/tests/keepalive_timeout.cc \ + test/core/end2end/tests/large_metadata.cc \ + test/core/end2end/tests/load_reporting_hook.cc \ + test/core/end2end/tests/max_concurrent_streams.cc \ + test/core/end2end/tests/max_connection_age.cc \ + test/core/end2end/tests/max_connection_idle.cc \ + test/core/end2end/tests/max_message_length.cc \ + test/core/end2end/tests/negative_deadline.cc \ + test/core/end2end/tests/network_status_change.cc \ + test/core/end2end/tests/no_logging.cc \ + test/core/end2end/tests/no_op.cc \ + test/core/end2end/tests/payload.cc \ + test/core/end2end/tests/ping.cc \ + test/core/end2end/tests/ping_pong_streaming.cc \ + test/core/end2end/tests/proxy_auth.cc \ + test/core/end2end/tests/registered_call.cc \ + test/core/end2end/tests/request_with_flags.cc \ + test/core/end2end/tests/request_with_payload.cc \ + test/core/end2end/tests/resource_quota_server.cc \ + test/core/end2end/tests/server_finishes_request.cc \ + test/core/end2end/tests/shutdown_finishes_calls.cc \ + test/core/end2end/tests/shutdown_finishes_tags.cc \ + test/core/end2end/tests/simple_cacheable_request.cc \ + test/core/end2end/tests/simple_delayed_request.cc \ + test/core/end2end/tests/simple_metadata.cc \ + test/core/end2end/tests/simple_request.cc \ + test/core/end2end/tests/stream_compression_compressed_payload.cc \ + test/core/end2end/tests/stream_compression_payload.cc \ + test/core/end2end/tests/stream_compression_ping_pong_streaming.cc \ + test/core/end2end/tests/streaming_error_response.cc \ + test/core/end2end/tests/trailing_metadata.cc \ + test/core/end2end/tests/workaround_cronet_compression.cc \ + test/core/end2end/tests/write_buffering.cc \ + test/core/end2end/tests/write_buffering_at_end.cc \ PUBLIC_HEADERS_C += \ @@ -8580,66 +8633,66 @@ endif LIBEND2END_NOSEC_TESTS_SRC = \ - test/core/end2end/end2end_nosec_tests.c \ - test/core/end2end/end2end_test_utils.c \ - test/core/end2end/tests/authority_not_supported.c \ - test/core/end2end/tests/bad_hostname.c \ - test/core/end2end/tests/bad_ping.c \ - test/core/end2end/tests/binary_metadata.c \ - test/core/end2end/tests/cancel_after_accept.c \ - test/core/end2end/tests/cancel_after_client_done.c \ - test/core/end2end/tests/cancel_after_invoke.c \ - test/core/end2end/tests/cancel_after_round_trip.c \ - test/core/end2end/tests/cancel_before_invoke.c \ - test/core/end2end/tests/cancel_in_a_vacuum.c \ - test/core/end2end/tests/cancel_with_status.c \ - test/core/end2end/tests/compressed_payload.c \ - test/core/end2end/tests/connectivity.c \ - test/core/end2end/tests/default_host.c \ - test/core/end2end/tests/disappearing_server.c \ - test/core/end2end/tests/empty_batch.c \ - test/core/end2end/tests/filter_call_init_fails.c \ - test/core/end2end/tests/filter_causes_close.c \ - test/core/end2end/tests/filter_latency.c \ - test/core/end2end/tests/graceful_server_shutdown.c \ - test/core/end2end/tests/high_initial_seqno.c \ - test/core/end2end/tests/hpack_size.c \ - test/core/end2end/tests/idempotent_request.c \ - test/core/end2end/tests/invoke_large_request.c \ - test/core/end2end/tests/keepalive_timeout.c \ - test/core/end2end/tests/large_metadata.c \ - test/core/end2end/tests/load_reporting_hook.c \ - test/core/end2end/tests/max_concurrent_streams.c \ - test/core/end2end/tests/max_connection_age.c \ - test/core/end2end/tests/max_connection_idle.c \ - test/core/end2end/tests/max_message_length.c \ - test/core/end2end/tests/negative_deadline.c \ - test/core/end2end/tests/network_status_change.c \ - test/core/end2end/tests/no_logging.c \ - test/core/end2end/tests/no_op.c \ - test/core/end2end/tests/payload.c \ - test/core/end2end/tests/ping.c \ - test/core/end2end/tests/ping_pong_streaming.c \ - test/core/end2end/tests/proxy_auth.c \ - test/core/end2end/tests/registered_call.c \ - test/core/end2end/tests/request_with_flags.c \ - test/core/end2end/tests/request_with_payload.c \ - test/core/end2end/tests/resource_quota_server.c \ - test/core/end2end/tests/server_finishes_request.c \ - test/core/end2end/tests/shutdown_finishes_calls.c \ - test/core/end2end/tests/shutdown_finishes_tags.c \ - test/core/end2end/tests/simple_cacheable_request.c \ - test/core/end2end/tests/simple_delayed_request.c \ - test/core/end2end/tests/simple_metadata.c \ - test/core/end2end/tests/simple_request.c \ - test/core/end2end/tests/stream_compression_compressed_payload.c \ - test/core/end2end/tests/stream_compression_payload.c \ - test/core/end2end/tests/stream_compression_ping_pong_streaming.c \ - test/core/end2end/tests/streaming_error_response.c \ - test/core/end2end/tests/trailing_metadata.c \ - test/core/end2end/tests/workaround_cronet_compression.c \ - test/core/end2end/tests/write_buffering.c \ - test/core/end2end/tests/write_buffering_at_end.c \ + test/core/end2end/end2end_nosec_tests.cc \ + test/core/end2end/end2end_test_utils.cc \ + test/core/end2end/tests/authority_not_supported.cc \ + test/core/end2end/tests/bad_hostname.cc \ + test/core/end2end/tests/bad_ping.cc \ + test/core/end2end/tests/binary_metadata.cc \ + test/core/end2end/tests/cancel_after_accept.cc \ + test/core/end2end/tests/cancel_after_client_done.cc \ + test/core/end2end/tests/cancel_after_invoke.cc \ + test/core/end2end/tests/cancel_after_round_trip.cc \ + test/core/end2end/tests/cancel_before_invoke.cc \ + test/core/end2end/tests/cancel_in_a_vacuum.cc \ + test/core/end2end/tests/cancel_with_status.cc \ + test/core/end2end/tests/compressed_payload.cc \ + test/core/end2end/tests/connectivity.cc \ + test/core/end2end/tests/default_host.cc \ + test/core/end2end/tests/disappearing_server.cc \ + test/core/end2end/tests/empty_batch.cc \ + test/core/end2end/tests/filter_call_init_fails.cc \ + test/core/end2end/tests/filter_causes_close.cc \ + test/core/end2end/tests/filter_latency.cc \ + test/core/end2end/tests/graceful_server_shutdown.cc \ + test/core/end2end/tests/high_initial_seqno.cc \ + test/core/end2end/tests/hpack_size.cc \ + test/core/end2end/tests/idempotent_request.cc \ + test/core/end2end/tests/invoke_large_request.cc \ + test/core/end2end/tests/keepalive_timeout.cc \ + test/core/end2end/tests/large_metadata.cc \ + test/core/end2end/tests/load_reporting_hook.cc \ + test/core/end2end/tests/max_concurrent_streams.cc \ + test/core/end2end/tests/max_connection_age.cc \ + test/core/end2end/tests/max_connection_idle.cc \ + test/core/end2end/tests/max_message_length.cc \ + test/core/end2end/tests/negative_deadline.cc \ + test/core/end2end/tests/network_status_change.cc \ + test/core/end2end/tests/no_logging.cc \ + test/core/end2end/tests/no_op.cc \ + test/core/end2end/tests/payload.cc \ + test/core/end2end/tests/ping.cc \ + test/core/end2end/tests/ping_pong_streaming.cc \ + test/core/end2end/tests/proxy_auth.cc \ + test/core/end2end/tests/registered_call.cc \ + test/core/end2end/tests/request_with_flags.cc \ + test/core/end2end/tests/request_with_payload.cc \ + test/core/end2end/tests/resource_quota_server.cc \ + test/core/end2end/tests/server_finishes_request.cc \ + test/core/end2end/tests/shutdown_finishes_calls.cc \ + test/core/end2end/tests/shutdown_finishes_tags.cc \ + test/core/end2end/tests/simple_cacheable_request.cc \ + test/core/end2end/tests/simple_delayed_request.cc \ + test/core/end2end/tests/simple_metadata.cc \ + test/core/end2end/tests/simple_request.cc \ + test/core/end2end/tests/stream_compression_compressed_payload.cc \ + test/core/end2end/tests/stream_compression_payload.cc \ + test/core/end2end/tests/stream_compression_ping_pong_streaming.cc \ + test/core/end2end/tests/streaming_error_response.cc \ + test/core/end2end/tests/trailing_metadata.cc \ + test/core/end2end/tests/workaround_cronet_compression.cc \ + test/core/end2end/tests/write_buffering.cc \ + test/core/end2end/tests/write_buffering_at_end.cc \ PUBLIC_HEADERS_C += \ @@ -8668,7 +8721,7 @@ endif ALARM_TEST_SRC = \ - test/core/surface/alarm_test.c \ + test/core/surface/alarm_test.cc \ ALARM_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(ALARM_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -8700,7 +8753,7 @@ endif ALGORITHM_TEST_SRC = \ - test/core/compression/algorithm_test.c \ + test/core/compression/algorithm_test.cc \ ALGORITHM_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(ALGORITHM_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -8732,7 +8785,7 @@ endif ALLOC_TEST_SRC = \ - test/core/support/alloc_test.c \ + test/core/support/alloc_test.cc \ ALLOC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(ALLOC_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -8764,7 +8817,7 @@ endif ALPN_TEST_SRC = \ - test/core/transport/chttp2/alpn_test.c \ + test/core/transport/chttp2/alpn_test.cc \ ALPN_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(ALPN_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -8796,7 +8849,7 @@ endif API_FUZZER_SRC = \ - test/core/end2end/fuzzers/api_fuzzer.c \ + test/core/end2end/fuzzers/api_fuzzer.cc \ API_FUZZER_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(API_FUZZER_SRC)))) ifeq ($(NO_SECURE),true) @@ -8828,7 +8881,7 @@ endif ARENA_TEST_SRC = \ - test/core/support/arena_test.c \ + test/core/support/arena_test.cc \ ARENA_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(ARENA_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -8860,7 +8913,7 @@ endif BACKOFF_TEST_SRC = \ - test/core/backoff/backoff_test.c \ + test/core/backoff/backoff_test.cc \ BACKOFF_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(BACKOFF_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -8892,7 +8945,7 @@ endif BAD_SERVER_RESPONSE_TEST_SRC = \ - test/core/end2end/bad_server_response_test.c \ + test/core/end2end/bad_server_response_test.cc \ BAD_SERVER_RESPONSE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(BAD_SERVER_RESPONSE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -8924,7 +8977,7 @@ endif BIN_DECODER_TEST_SRC = \ - test/core/transport/chttp2/bin_decoder_test.c \ + test/core/transport/chttp2/bin_decoder_test.cc \ BIN_DECODER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(BIN_DECODER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -8956,7 +9009,7 @@ endif BIN_ENCODER_TEST_SRC = \ - test/core/transport/chttp2/bin_encoder_test.c \ + test/core/transport/chttp2/bin_encoder_test.cc \ BIN_ENCODER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(BIN_ENCODER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -8988,7 +9041,7 @@ endif BYTE_STREAM_TEST_SRC = \ - test/core/transport/byte_stream_test.c \ + test/core/transport/byte_stream_test.cc \ BYTE_STREAM_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(BYTE_STREAM_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9020,7 +9073,7 @@ endif CHANNEL_CREATE_TEST_SRC = \ - test/core/surface/channel_create_test.c \ + test/core/surface/channel_create_test.cc \ CHANNEL_CREATE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(CHANNEL_CREATE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9084,7 +9137,7 @@ endif CHTTP2_HPACK_ENCODER_TEST_SRC = \ - test/core/transport/chttp2/hpack_encoder_test.c \ + test/core/transport/chttp2/hpack_encoder_test.cc \ CHTTP2_HPACK_ENCODER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_HPACK_ENCODER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9116,7 +9169,7 @@ endif CHTTP2_STREAM_MAP_TEST_SRC = \ - test/core/transport/chttp2/stream_map_test.c \ + test/core/transport/chttp2/stream_map_test.cc \ CHTTP2_STREAM_MAP_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_STREAM_MAP_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9148,7 +9201,7 @@ endif CHTTP2_VARINT_TEST_SRC = \ - test/core/transport/chttp2/varint_test.c \ + test/core/transport/chttp2/varint_test.cc \ CHTTP2_VARINT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_VARINT_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9180,7 +9233,7 @@ endif CLIENT_FUZZER_SRC = \ - test/core/end2end/fuzzers/client_fuzzer.c \ + test/core/end2end/fuzzers/client_fuzzer.cc \ CLIENT_FUZZER_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(CLIENT_FUZZER_SRC)))) ifeq ($(NO_SECURE),true) @@ -9212,7 +9265,7 @@ endif COMBINER_TEST_SRC = \ - test/core/iomgr/combiner_test.c \ + test/core/iomgr/combiner_test.cc \ COMBINER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(COMBINER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9244,7 +9297,7 @@ endif COMPRESSION_TEST_SRC = \ - test/core/compression/compression_test.c \ + test/core/compression/compression_test.cc \ COMPRESSION_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(COMPRESSION_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9276,7 +9329,7 @@ endif CONCURRENT_CONNECTIVITY_TEST_SRC = \ - test/core/surface/concurrent_connectivity_test.c \ + test/core/surface/concurrent_connectivity_test.cc \ CONCURRENT_CONNECTIVITY_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(CONCURRENT_CONNECTIVITY_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9308,7 +9361,7 @@ endif CONNECTION_REFUSED_TEST_SRC = \ - test/core/end2end/connection_refused_test.c \ + test/core/end2end/connection_refused_test.cc \ CONNECTION_REFUSED_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(CONNECTION_REFUSED_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9340,7 +9393,7 @@ endif DNS_RESOLVER_CONNECTIVITY_TEST_SRC = \ - test/core/client_channel/resolvers/dns_resolver_connectivity_test.c \ + test/core/client_channel/resolvers/dns_resolver_connectivity_test.cc \ DNS_RESOLVER_CONNECTIVITY_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(DNS_RESOLVER_CONNECTIVITY_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9372,7 +9425,7 @@ endif DNS_RESOLVER_TEST_SRC = \ - test/core/client_channel/resolvers/dns_resolver_test.c \ + test/core/client_channel/resolvers/dns_resolver_test.cc \ DNS_RESOLVER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(DNS_RESOLVER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9404,7 +9457,7 @@ endif DUALSTACK_SOCKET_TEST_SRC = \ - test/core/end2end/dualstack_socket_test.c \ + test/core/end2end/dualstack_socket_test.cc \ DUALSTACK_SOCKET_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(DUALSTACK_SOCKET_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9436,7 +9489,7 @@ endif ENDPOINT_PAIR_TEST_SRC = \ - test/core/iomgr/endpoint_pair_test.c \ + test/core/iomgr/endpoint_pair_test.cc \ ENDPOINT_PAIR_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(ENDPOINT_PAIR_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9468,7 +9521,7 @@ endif ERROR_TEST_SRC = \ - test/core/iomgr/error_test.c \ + test/core/iomgr/error_test.cc \ ERROR_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(ERROR_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9500,7 +9553,7 @@ endif EV_EPOLLSIG_LINUX_TEST_SRC = \ - test/core/iomgr/ev_epollsig_linux_test.c \ + test/core/iomgr/ev_epollsig_linux_test.cc \ EV_EPOLLSIG_LINUX_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(EV_EPOLLSIG_LINUX_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9532,7 +9585,7 @@ endif FAKE_RESOLVER_TEST_SRC = \ - test/core/client_channel/resolvers/fake_resolver_test.c \ + test/core/client_channel/resolvers/fake_resolver_test.cc \ FAKE_RESOLVER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(FAKE_RESOLVER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9564,8 +9617,8 @@ endif FAKE_TRANSPORT_SECURITY_TEST_SRC = \ - test/core/tsi/fake_transport_security_test.c \ - test/core/tsi/transport_security_test_lib.c \ + test/core/tsi/fake_transport_security_test.cc \ + test/core/tsi/transport_security_test_lib.cc \ FAKE_TRANSPORT_SECURITY_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(FAKE_TRANSPORT_SECURITY_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9599,7 +9652,7 @@ endif FD_CONSERVATION_POSIX_TEST_SRC = \ - test/core/iomgr/fd_conservation_posix_test.c \ + test/core/iomgr/fd_conservation_posix_test.cc \ FD_CONSERVATION_POSIX_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(FD_CONSERVATION_POSIX_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9631,7 +9684,7 @@ endif FD_POSIX_TEST_SRC = \ - test/core/iomgr/fd_posix_test.c \ + test/core/iomgr/fd_posix_test.cc \ FD_POSIX_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(FD_POSIX_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9663,7 +9716,7 @@ endif FLING_CLIENT_SRC = \ - test/core/fling/client.c \ + test/core/fling/client.cc \ FLING_CLIENT_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(FLING_CLIENT_SRC)))) ifeq ($(NO_SECURE),true) @@ -9695,7 +9748,7 @@ endif FLING_SERVER_SRC = \ - test/core/fling/server.c \ + test/core/fling/server.cc \ FLING_SERVER_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(FLING_SERVER_SRC)))) ifeq ($(NO_SECURE),true) @@ -9727,7 +9780,7 @@ endif FLING_STREAM_TEST_SRC = \ - test/core/fling/fling_stream_test.c \ + test/core/fling/fling_stream_test.cc \ FLING_STREAM_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(FLING_STREAM_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9759,7 +9812,7 @@ endif FLING_TEST_SRC = \ - test/core/fling/fling_test.c \ + test/core/fling/fling_test.cc \ FLING_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(FLING_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9887,7 +9940,7 @@ endif GOAWAY_SERVER_TEST_SRC = \ - test/core/end2end/goaway_server_test.c \ + test/core/end2end/goaway_server_test.cc \ GOAWAY_SERVER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GOAWAY_SERVER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9919,7 +9972,7 @@ endif GPR_AVL_TEST_SRC = \ - test/core/support/avl_test.c \ + test/core/support/avl_test.cc \ GPR_AVL_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_AVL_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9951,7 +10004,7 @@ endif GPR_CMDLINE_TEST_SRC = \ - test/core/support/cmdline_test.c \ + test/core/support/cmdline_test.cc \ GPR_CMDLINE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_CMDLINE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -9983,7 +10036,7 @@ endif GPR_CPU_TEST_SRC = \ - test/core/support/cpu_test.c \ + test/core/support/cpu_test.cc \ GPR_CPU_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_CPU_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10015,7 +10068,7 @@ endif GPR_ENV_TEST_SRC = \ - test/core/support/env_test.c \ + test/core/support/env_test.cc \ GPR_ENV_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_ENV_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10046,40 +10099,8 @@ endif endif -GPR_HISTOGRAM_TEST_SRC = \ - test/core/support/histogram_test.c \ - -GPR_HISTOGRAM_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_HISTOGRAM_TEST_SRC)))) -ifeq ($(NO_SECURE),true) - -# You can't build secure targets if you don't have OpenSSL. - -$(BINDIR)/$(CONFIG)/gpr_histogram_test: openssl_dep_error - -else - - - -$(BINDIR)/$(CONFIG)/gpr_histogram_test: $(GPR_HISTOGRAM_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a - $(E) "[LD] Linking $@" - $(Q) mkdir -p `dirname $@` - $(Q) $(LD) $(LDFLAGS) $(GPR_HISTOGRAM_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LDLIBS) $(LDLIBS_SECURE) -o $(BINDIR)/$(CONFIG)/gpr_histogram_test - -endif - -$(OBJDIR)/$(CONFIG)/test/core/support/histogram_test.o: $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a - -deps_gpr_histogram_test: $(GPR_HISTOGRAM_TEST_OBJS:.o=.dep) - -ifneq ($(NO_SECURE),true) -ifneq ($(NO_DEPS),true) --include $(GPR_HISTOGRAM_TEST_OBJS:.o=.dep) -endif -endif - - GPR_HOST_PORT_TEST_SRC = \ - test/core/support/host_port_test.c \ + test/core/support/host_port_test.cc \ GPR_HOST_PORT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_HOST_PORT_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10111,7 +10132,7 @@ endif GPR_LOG_TEST_SRC = \ - test/core/support/log_test.c \ + test/core/support/log_test.cc \ GPR_LOG_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_LOG_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10142,104 +10163,104 @@ endif endif -GPR_MPSCQ_TEST_SRC = \ - test/core/support/mpscq_test.c \ +GPR_MANUAL_CONSTRUCTOR_TEST_SRC = \ + test/core/support/manual_constructor_test.cc \ -GPR_MPSCQ_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_MPSCQ_TEST_SRC)))) +GPR_MANUAL_CONSTRUCTOR_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_MANUAL_CONSTRUCTOR_TEST_SRC)))) ifeq ($(NO_SECURE),true) # You can't build secure targets if you don't have OpenSSL. -$(BINDIR)/$(CONFIG)/gpr_mpscq_test: openssl_dep_error +$(BINDIR)/$(CONFIG)/gpr_manual_constructor_test: openssl_dep_error else -$(BINDIR)/$(CONFIG)/gpr_mpscq_test: $(GPR_MPSCQ_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a +$(BINDIR)/$(CONFIG)/gpr_manual_constructor_test: $(GPR_MANUAL_CONSTRUCTOR_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(E) "[LD] Linking $@" $(Q) mkdir -p `dirname $@` - $(Q) $(LD) $(LDFLAGS) $(GPR_MPSCQ_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LDLIBS) $(LDLIBS_SECURE) -o $(BINDIR)/$(CONFIG)/gpr_mpscq_test + $(Q) $(LD) $(LDFLAGS) $(GPR_MANUAL_CONSTRUCTOR_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LDLIBS) $(LDLIBS_SECURE) -o $(BINDIR)/$(CONFIG)/gpr_manual_constructor_test endif -$(OBJDIR)/$(CONFIG)/test/core/support/mpscq_test.o: $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a +$(OBJDIR)/$(CONFIG)/test/core/support/manual_constructor_test.o: $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a -deps_gpr_mpscq_test: $(GPR_MPSCQ_TEST_OBJS:.o=.dep) +deps_gpr_manual_constructor_test: $(GPR_MANUAL_CONSTRUCTOR_TEST_OBJS:.o=.dep) ifneq ($(NO_SECURE),true) ifneq ($(NO_DEPS),true) --include $(GPR_MPSCQ_TEST_OBJS:.o=.dep) +-include $(GPR_MANUAL_CONSTRUCTOR_TEST_OBJS:.o=.dep) endif endif -GPR_SPINLOCK_TEST_SRC = \ - test/core/support/spinlock_test.c \ +GPR_MPSCQ_TEST_SRC = \ + test/core/support/mpscq_test.cc \ -GPR_SPINLOCK_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_SPINLOCK_TEST_SRC)))) +GPR_MPSCQ_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_MPSCQ_TEST_SRC)))) ifeq ($(NO_SECURE),true) # You can't build secure targets if you don't have OpenSSL. -$(BINDIR)/$(CONFIG)/gpr_spinlock_test: openssl_dep_error +$(BINDIR)/$(CONFIG)/gpr_mpscq_test: openssl_dep_error else -$(BINDIR)/$(CONFIG)/gpr_spinlock_test: $(GPR_SPINLOCK_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a +$(BINDIR)/$(CONFIG)/gpr_mpscq_test: $(GPR_MPSCQ_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(E) "[LD] Linking $@" $(Q) mkdir -p `dirname $@` - $(Q) $(LD) $(LDFLAGS) $(GPR_SPINLOCK_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LDLIBS) $(LDLIBS_SECURE) -o $(BINDIR)/$(CONFIG)/gpr_spinlock_test + $(Q) $(LD) $(LDFLAGS) $(GPR_MPSCQ_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LDLIBS) $(LDLIBS_SECURE) -o $(BINDIR)/$(CONFIG)/gpr_mpscq_test endif -$(OBJDIR)/$(CONFIG)/test/core/support/spinlock_test.o: $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a +$(OBJDIR)/$(CONFIG)/test/core/support/mpscq_test.o: $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a -deps_gpr_spinlock_test: $(GPR_SPINLOCK_TEST_OBJS:.o=.dep) +deps_gpr_mpscq_test: $(GPR_MPSCQ_TEST_OBJS:.o=.dep) ifneq ($(NO_SECURE),true) ifneq ($(NO_DEPS),true) --include $(GPR_SPINLOCK_TEST_OBJS:.o=.dep) +-include $(GPR_MPSCQ_TEST_OBJS:.o=.dep) endif endif -GPR_STACK_LOCKFREE_TEST_SRC = \ - test/core/support/stack_lockfree_test.c \ +GPR_SPINLOCK_TEST_SRC = \ + test/core/support/spinlock_test.cc \ -GPR_STACK_LOCKFREE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_STACK_LOCKFREE_TEST_SRC)))) +GPR_SPINLOCK_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_SPINLOCK_TEST_SRC)))) ifeq ($(NO_SECURE),true) # You can't build secure targets if you don't have OpenSSL. -$(BINDIR)/$(CONFIG)/gpr_stack_lockfree_test: openssl_dep_error +$(BINDIR)/$(CONFIG)/gpr_spinlock_test: openssl_dep_error else -$(BINDIR)/$(CONFIG)/gpr_stack_lockfree_test: $(GPR_STACK_LOCKFREE_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a +$(BINDIR)/$(CONFIG)/gpr_spinlock_test: $(GPR_SPINLOCK_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(E) "[LD] Linking $@" $(Q) mkdir -p `dirname $@` - $(Q) $(LD) $(LDFLAGS) $(GPR_STACK_LOCKFREE_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LDLIBS) $(LDLIBS_SECURE) -o $(BINDIR)/$(CONFIG)/gpr_stack_lockfree_test + $(Q) $(LD) $(LDFLAGS) $(GPR_SPINLOCK_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LDLIBS) $(LDLIBS_SECURE) -o $(BINDIR)/$(CONFIG)/gpr_spinlock_test endif -$(OBJDIR)/$(CONFIG)/test/core/support/stack_lockfree_test.o: $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a +$(OBJDIR)/$(CONFIG)/test/core/support/spinlock_test.o: $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a -deps_gpr_stack_lockfree_test: $(GPR_STACK_LOCKFREE_TEST_OBJS:.o=.dep) +deps_gpr_spinlock_test: $(GPR_SPINLOCK_TEST_OBJS:.o=.dep) ifneq ($(NO_SECURE),true) ifneq ($(NO_DEPS),true) --include $(GPR_STACK_LOCKFREE_TEST_OBJS:.o=.dep) +-include $(GPR_SPINLOCK_TEST_OBJS:.o=.dep) endif endif GPR_STRING_TEST_SRC = \ - test/core/support/string_test.c \ + test/core/support/string_test.cc \ GPR_STRING_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_STRING_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10271,7 +10292,7 @@ endif GPR_SYNC_TEST_SRC = \ - test/core/support/sync_test.c \ + test/core/support/sync_test.cc \ GPR_SYNC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_SYNC_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10303,7 +10324,7 @@ endif GPR_THD_TEST_SRC = \ - test/core/support/thd_test.c \ + test/core/support/thd_test.cc \ GPR_THD_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_THD_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10335,7 +10356,7 @@ endif GPR_TIME_TEST_SRC = \ - test/core/support/time_test.c \ + test/core/support/time_test.cc \ GPR_TIME_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_TIME_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10367,7 +10388,7 @@ endif GPR_TLS_TEST_SRC = \ - test/core/support/tls_test.c \ + test/core/support/tls_test.cc \ GPR_TLS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_TLS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10399,7 +10420,7 @@ endif GPR_USEFUL_TEST_SRC = \ - test/core/support/useful_test.c \ + test/core/support/useful_test.cc \ GPR_USEFUL_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GPR_USEFUL_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10431,7 +10452,7 @@ endif GRPC_AUTH_CONTEXT_TEST_SRC = \ - test/core/security/auth_context_test.c \ + test/core/security/auth_context_test.cc \ GRPC_AUTH_CONTEXT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_AUTH_CONTEXT_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10463,7 +10484,7 @@ endif GRPC_B64_TEST_SRC = \ - test/core/slice/b64_test.c \ + test/core/slice/b64_test.cc \ GRPC_B64_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_B64_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10495,7 +10516,7 @@ endif GRPC_BYTE_BUFFER_READER_TEST_SRC = \ - test/core/surface/byte_buffer_reader_test.c \ + test/core/surface/byte_buffer_reader_test.cc \ GRPC_BYTE_BUFFER_READER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_BYTE_BUFFER_READER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10527,7 +10548,7 @@ endif GRPC_CHANNEL_ARGS_TEST_SRC = \ - test/core/channel/channel_args_test.c \ + test/core/channel/channel_args_test.cc \ GRPC_CHANNEL_ARGS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_CHANNEL_ARGS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10559,7 +10580,7 @@ endif GRPC_CHANNEL_STACK_BUILDER_TEST_SRC = \ - test/core/channel/channel_stack_builder_test.c \ + test/core/channel/channel_stack_builder_test.cc \ GRPC_CHANNEL_STACK_BUILDER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_CHANNEL_STACK_BUILDER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10591,7 +10612,7 @@ endif GRPC_CHANNEL_STACK_TEST_SRC = \ - test/core/channel/channel_stack_test.c \ + test/core/channel/channel_stack_test.cc \ GRPC_CHANNEL_STACK_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_CHANNEL_STACK_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10623,7 +10644,7 @@ endif GRPC_COMPLETION_QUEUE_TEST_SRC = \ - test/core/surface/completion_queue_test.c \ + test/core/surface/completion_queue_test.cc \ GRPC_COMPLETION_QUEUE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_COMPLETION_QUEUE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10655,7 +10676,7 @@ endif GRPC_COMPLETION_QUEUE_THREADING_TEST_SRC = \ - test/core/surface/completion_queue_threading_test.c \ + test/core/surface/completion_queue_threading_test.cc \ GRPC_COMPLETION_QUEUE_THREADING_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_COMPLETION_QUEUE_THREADING_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10687,7 +10708,7 @@ endif GRPC_CREATE_JWT_SRC = \ - test/core/security/create_jwt.c \ + test/core/security/create_jwt.cc \ GRPC_CREATE_JWT_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_CREATE_JWT_SRC)))) ifeq ($(NO_SECURE),true) @@ -10719,7 +10740,7 @@ endif GRPC_CREDENTIALS_TEST_SRC = \ - test/core/security/credentials_test.c \ + test/core/security/credentials_test.cc \ GRPC_CREDENTIALS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_CREDENTIALS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10751,7 +10772,7 @@ endif GRPC_FETCH_OAUTH2_SRC = \ - test/core/security/fetch_oauth2.c \ + test/core/security/fetch_oauth2.cc \ GRPC_FETCH_OAUTH2_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_FETCH_OAUTH2_SRC)))) ifeq ($(NO_SECURE),true) @@ -10783,7 +10804,7 @@ endif GRPC_INVALID_CHANNEL_ARGS_TEST_SRC = \ - test/core/surface/invalid_channel_args_test.c \ + test/core/surface/invalid_channel_args_test.cc \ GRPC_INVALID_CHANNEL_ARGS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_INVALID_CHANNEL_ARGS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10815,7 +10836,7 @@ endif GRPC_JSON_TOKEN_TEST_SRC = \ - test/core/security/json_token_test.c \ + test/core/security/json_token_test.cc \ GRPC_JSON_TOKEN_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_JSON_TOKEN_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10847,7 +10868,7 @@ endif GRPC_JWT_VERIFIER_TEST_SRC = \ - test/core/security/jwt_verifier_test.c \ + test/core/security/jwt_verifier_test.cc \ GRPC_JWT_VERIFIER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_JWT_VERIFIER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10879,7 +10900,7 @@ endif GRPC_PRINT_GOOGLE_DEFAULT_CREDS_TOKEN_SRC = \ - test/core/security/print_google_default_creds_token.c \ + test/core/security/print_google_default_creds_token.cc \ GRPC_PRINT_GOOGLE_DEFAULT_CREDS_TOKEN_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_PRINT_GOOGLE_DEFAULT_CREDS_TOKEN_SRC)))) ifeq ($(NO_SECURE),true) @@ -10911,7 +10932,7 @@ endif GRPC_SECURITY_CONNECTOR_TEST_SRC = \ - test/core/security/security_connector_test.c \ + test/core/security/security_connector_test.cc \ GRPC_SECURITY_CONNECTOR_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_SECURITY_CONNECTOR_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10943,7 +10964,7 @@ endif GRPC_SSL_CREDENTIALS_TEST_SRC = \ - test/core/security/ssl_credentials_test.c \ + test/core/security/ssl_credentials_test.cc \ GRPC_SSL_CREDENTIALS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_SSL_CREDENTIALS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -10975,7 +10996,7 @@ endif GRPC_VERIFY_JWT_SRC = \ - test/core/security/verify_jwt.c \ + test/core/security/verify_jwt.cc \ GRPC_VERIFY_JWT_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_VERIFY_JWT_SRC)))) ifeq ($(NO_SECURE),true) @@ -11007,7 +11028,7 @@ endif HANDSHAKE_CLIENT_SRC = \ - test/core/handshake/client_ssl.c \ + test/core/handshake/client_ssl.cc \ HANDSHAKE_CLIENT_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HANDSHAKE_CLIENT_SRC)))) ifeq ($(NO_SECURE),true) @@ -11039,7 +11060,8 @@ endif HANDSHAKE_SERVER_SRC = \ - test/core/handshake/server_ssl.c \ + test/core/handshake/server_ssl.cc \ + test/core/handshake/server_ssl_common.cc \ HANDSHAKE_SERVER_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HANDSHAKE_SERVER_SRC)))) ifeq ($(NO_SECURE),true) @@ -11061,6 +11083,8 @@ endif $(OBJDIR)/$(CONFIG)/test/core/handshake/server_ssl.o: $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a +$(OBJDIR)/$(CONFIG)/test/core/handshake/server_ssl_common.o: $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a + deps_handshake_server: $(HANDSHAKE_SERVER_OBJS:.o=.dep) ifneq ($(NO_SECURE),true) @@ -11070,8 +11094,75 @@ endif endif +HANDSHAKE_SERVER_WITH_READAHEAD_HANDSHAKER_SRC = \ + test/core/handshake/readahead_handshaker_server_ssl.cc \ + test/core/handshake/server_ssl_common.cc \ + +HANDSHAKE_SERVER_WITH_READAHEAD_HANDSHAKER_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HANDSHAKE_SERVER_WITH_READAHEAD_HANDSHAKER_SRC)))) +ifeq ($(NO_SECURE),true) + +# You can't build secure targets if you don't have OpenSSL. + +$(BINDIR)/$(CONFIG)/handshake_server_with_readahead_handshaker: openssl_dep_error + +else + + + +$(BINDIR)/$(CONFIG)/handshake_server_with_readahead_handshaker: $(HANDSHAKE_SERVER_WITH_READAHEAD_HANDSHAKER_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a + $(E) "[LD] Linking $@" + $(Q) mkdir -p `dirname $@` + $(Q) $(LD) $(LDFLAGS) $(HANDSHAKE_SERVER_WITH_READAHEAD_HANDSHAKER_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LDLIBS) $(LDLIBS_SECURE) -o $(BINDIR)/$(CONFIG)/handshake_server_with_readahead_handshaker + +endif + +$(OBJDIR)/$(CONFIG)/test/core/handshake/readahead_handshaker_server_ssl.o: $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a + +$(OBJDIR)/$(CONFIG)/test/core/handshake/server_ssl_common.o: $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a + +deps_handshake_server_with_readahead_handshaker: $(HANDSHAKE_SERVER_WITH_READAHEAD_HANDSHAKER_OBJS:.o=.dep) + +ifneq ($(NO_SECURE),true) +ifneq ($(NO_DEPS),true) +-include $(HANDSHAKE_SERVER_WITH_READAHEAD_HANDSHAKER_OBJS:.o=.dep) +endif +endif + + +HISTOGRAM_TEST_SRC = \ + test/core/util/histogram_test.cc \ + +HISTOGRAM_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HISTOGRAM_TEST_SRC)))) +ifeq ($(NO_SECURE),true) + +# You can't build secure targets if you don't have OpenSSL. + +$(BINDIR)/$(CONFIG)/histogram_test: openssl_dep_error + +else + + + +$(BINDIR)/$(CONFIG)/histogram_test: $(HISTOGRAM_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a + $(E) "[LD] Linking $@" + $(Q) mkdir -p `dirname $@` + $(Q) $(LD) $(LDFLAGS) $(HISTOGRAM_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LDLIBS) $(LDLIBS_SECURE) -o $(BINDIR)/$(CONFIG)/histogram_test + +endif + +$(OBJDIR)/$(CONFIG)/test/core/util/histogram_test.o: $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a + +deps_histogram_test: $(HISTOGRAM_TEST_OBJS:.o=.dep) + +ifneq ($(NO_SECURE),true) +ifneq ($(NO_DEPS),true) +-include $(HISTOGRAM_TEST_OBJS:.o=.dep) +endif +endif + + HPACK_PARSER_FUZZER_TEST_SRC = \ - test/core/transport/chttp2/hpack_parser_fuzzer_test.c \ + test/core/transport/chttp2/hpack_parser_fuzzer_test.cc \ HPACK_PARSER_FUZZER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HPACK_PARSER_FUZZER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11103,7 +11194,7 @@ endif HPACK_PARSER_TEST_SRC = \ - test/core/transport/chttp2/hpack_parser_test.c \ + test/core/transport/chttp2/hpack_parser_test.cc \ HPACK_PARSER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HPACK_PARSER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11135,7 +11226,7 @@ endif HPACK_TABLE_TEST_SRC = \ - test/core/transport/chttp2/hpack_table_test.c \ + test/core/transport/chttp2/hpack_table_test.cc \ HPACK_TABLE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HPACK_TABLE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11167,7 +11258,7 @@ endif HTTP_PARSER_TEST_SRC = \ - test/core/http/parser_test.c \ + test/core/http/parser_test.cc \ HTTP_PARSER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HTTP_PARSER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11199,7 +11290,7 @@ endif HTTP_REQUEST_FUZZER_TEST_SRC = \ - test/core/http/request_fuzzer.c \ + test/core/http/request_fuzzer.cc \ HTTP_REQUEST_FUZZER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HTTP_REQUEST_FUZZER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11231,7 +11322,7 @@ endif HTTP_RESPONSE_FUZZER_TEST_SRC = \ - test/core/http/response_fuzzer.c \ + test/core/http/response_fuzzer.cc \ HTTP_RESPONSE_FUZZER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HTTP_RESPONSE_FUZZER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11263,7 +11354,7 @@ endif HTTPCLI_FORMAT_REQUEST_TEST_SRC = \ - test/core/http/format_request_test.c \ + test/core/http/format_request_test.cc \ HTTPCLI_FORMAT_REQUEST_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HTTPCLI_FORMAT_REQUEST_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11295,7 +11386,7 @@ endif HTTPCLI_TEST_SRC = \ - test/core/http/httpcli_test.c \ + test/core/http/httpcli_test.cc \ HTTPCLI_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HTTPCLI_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11327,7 +11418,7 @@ endif HTTPSCLI_TEST_SRC = \ - test/core/http/httpscli_test.c \ + test/core/http/httpscli_test.cc \ HTTPSCLI_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HTTPSCLI_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11359,7 +11450,7 @@ endif INIT_TEST_SRC = \ - test/core/surface/init_test.c \ + test/core/surface/init_test.cc \ INIT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(INIT_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11391,7 +11482,7 @@ endif INVALID_CALL_ARGUMENT_TEST_SRC = \ - test/core/end2end/invalid_call_argument_test.c \ + test/core/end2end/invalid_call_argument_test.cc \ INVALID_CALL_ARGUMENT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(INVALID_CALL_ARGUMENT_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11423,7 +11514,7 @@ endif JSON_FUZZER_TEST_SRC = \ - test/core/json/fuzzer.c \ + test/core/json/fuzzer.cc \ JSON_FUZZER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(JSON_FUZZER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11455,7 +11546,7 @@ endif JSON_REWRITE_SRC = \ - test/core/json/json_rewrite.c \ + test/core/json/json_rewrite.cc \ JSON_REWRITE_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(JSON_REWRITE_SRC)))) ifeq ($(NO_SECURE),true) @@ -11487,7 +11578,7 @@ endif JSON_REWRITE_TEST_SRC = \ - test/core/json/json_rewrite_test.c \ + test/core/json/json_rewrite_test.cc \ JSON_REWRITE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(JSON_REWRITE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11519,7 +11610,7 @@ endif JSON_STREAM_ERROR_TEST_SRC = \ - test/core/json/json_stream_error_test.c \ + test/core/json/json_stream_error_test.cc \ JSON_STREAM_ERROR_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(JSON_STREAM_ERROR_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11551,7 +11642,7 @@ endif JSON_TEST_SRC = \ - test/core/json/json_test.c \ + test/core/json/json_test.cc \ JSON_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(JSON_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11583,7 +11674,7 @@ endif LAME_CLIENT_TEST_SRC = \ - test/core/surface/lame_client_test.c \ + test/core/surface/lame_client_test.cc \ LAME_CLIENT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(LAME_CLIENT_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11615,7 +11706,7 @@ endif LB_POLICIES_TEST_SRC = \ - test/core/client_channel/lb_policies_test.c \ + test/core/client_channel/lb_policies_test.cc \ LB_POLICIES_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(LB_POLICIES_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11647,7 +11738,7 @@ endif LOAD_FILE_TEST_SRC = \ - test/core/iomgr/load_file_test.c \ + test/core/iomgr/load_file_test.cc \ LOAD_FILE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(LOAD_FILE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11679,7 +11770,7 @@ endif LOW_LEVEL_PING_PONG_BENCHMARK_SRC = \ - test/core/network_benchmarks/low_level_ping_pong.c \ + test/core/network_benchmarks/low_level_ping_pong.cc \ LOW_LEVEL_PING_PONG_BENCHMARK_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(LOW_LEVEL_PING_PONG_BENCHMARK_SRC)))) ifeq ($(NO_SECURE),true) @@ -11711,7 +11802,7 @@ endif MEMORY_PROFILE_CLIENT_SRC = \ - test/core/memory_usage/client.c \ + test/core/memory_usage/client.cc \ MEMORY_PROFILE_CLIENT_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(MEMORY_PROFILE_CLIENT_SRC)))) ifeq ($(NO_SECURE),true) @@ -11743,7 +11834,7 @@ endif MEMORY_PROFILE_SERVER_SRC = \ - test/core/memory_usage/server.c \ + test/core/memory_usage/server.cc \ MEMORY_PROFILE_SERVER_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(MEMORY_PROFILE_SERVER_SRC)))) ifeq ($(NO_SECURE),true) @@ -11775,7 +11866,7 @@ endif MEMORY_PROFILE_TEST_SRC = \ - test/core/memory_usage/memory_usage_test.c \ + test/core/memory_usage/memory_usage_test.cc \ MEMORY_PROFILE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(MEMORY_PROFILE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11807,7 +11898,7 @@ endif MESSAGE_COMPRESS_TEST_SRC = \ - test/core/compression/message_compress_test.c \ + test/core/compression/message_compress_test.cc \ MESSAGE_COMPRESS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(MESSAGE_COMPRESS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11839,7 +11930,7 @@ endif MINIMAL_STACK_IS_MINIMAL_TEST_SRC = \ - test/core/channel/minimal_stack_is_minimal_test.c \ + test/core/channel/minimal_stack_is_minimal_test.cc \ MINIMAL_STACK_IS_MINIMAL_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(MINIMAL_STACK_IS_MINIMAL_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11871,7 +11962,7 @@ endif MULTIPLE_SERVER_QUEUES_TEST_SRC = \ - test/core/end2end/multiple_server_queues_test.c \ + test/core/end2end/multiple_server_queues_test.cc \ MULTIPLE_SERVER_QUEUES_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(MULTIPLE_SERVER_QUEUES_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11903,7 +11994,7 @@ endif MURMUR_HASH_TEST_SRC = \ - test/core/support/murmur_hash_test.c \ + test/core/support/murmur_hash_test.cc \ MURMUR_HASH_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(MURMUR_HASH_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11935,7 +12026,7 @@ endif NANOPB_FUZZER_RESPONSE_TEST_SRC = \ - test/core/nanopb/fuzzer_response.c \ + test/core/nanopb/fuzzer_response.cc \ NANOPB_FUZZER_RESPONSE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(NANOPB_FUZZER_RESPONSE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11967,7 +12058,7 @@ endif NANOPB_FUZZER_SERVERLIST_TEST_SRC = \ - test/core/nanopb/fuzzer_serverlist.c \ + test/core/nanopb/fuzzer_serverlist.cc \ NANOPB_FUZZER_SERVERLIST_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(NANOPB_FUZZER_SERVERLIST_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -11999,7 +12090,7 @@ endif NO_SERVER_TEST_SRC = \ - test/core/end2end/no_server_test.c \ + test/core/end2end/no_server_test.cc \ NO_SERVER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(NO_SERVER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12031,7 +12122,7 @@ endif NUM_EXTERNAL_CONNECTIVITY_WATCHERS_TEST_SRC = \ - test/core/surface/num_external_connectivity_watchers_test.c \ + test/core/surface/num_external_connectivity_watchers_test.cc \ NUM_EXTERNAL_CONNECTIVITY_WATCHERS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(NUM_EXTERNAL_CONNECTIVITY_WATCHERS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12063,7 +12154,7 @@ endif PARSE_ADDRESS_TEST_SRC = \ - test/core/client_channel/parse_address_test.c \ + test/core/client_channel/parse_address_test.cc \ PARSE_ADDRESS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(PARSE_ADDRESS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12095,7 +12186,7 @@ endif PERCENT_DECODE_FUZZER_SRC = \ - test/core/slice/percent_decode_fuzzer.c \ + test/core/slice/percent_decode_fuzzer.cc \ PERCENT_DECODE_FUZZER_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(PERCENT_DECODE_FUZZER_SRC)))) ifeq ($(NO_SECURE),true) @@ -12127,7 +12218,7 @@ endif PERCENT_ENCODE_FUZZER_SRC = \ - test/core/slice/percent_encode_fuzzer.c \ + test/core/slice/percent_encode_fuzzer.cc \ PERCENT_ENCODE_FUZZER_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(PERCENT_ENCODE_FUZZER_SRC)))) ifeq ($(NO_SECURE),true) @@ -12159,7 +12250,7 @@ endif PERCENT_ENCODING_TEST_SRC = \ - test/core/slice/percent_encoding_test.c \ + test/core/slice/percent_encoding_test.cc \ PERCENT_ENCODING_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(PERCENT_ENCODING_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12191,7 +12282,7 @@ endif POLLSET_SET_TEST_SRC = \ - test/core/iomgr/pollset_set_test.c \ + test/core/iomgr/pollset_set_test.cc \ POLLSET_SET_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(POLLSET_SET_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12223,7 +12314,7 @@ endif RESOLVE_ADDRESS_POSIX_TEST_SRC = \ - test/core/iomgr/resolve_address_posix_test.c \ + test/core/iomgr/resolve_address_posix_test.cc \ RESOLVE_ADDRESS_POSIX_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(RESOLVE_ADDRESS_POSIX_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12255,7 +12346,7 @@ endif RESOLVE_ADDRESS_TEST_SRC = \ - test/core/iomgr/resolve_address_test.c \ + test/core/iomgr/resolve_address_test.cc \ RESOLVE_ADDRESS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(RESOLVE_ADDRESS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12287,7 +12378,7 @@ endif RESOURCE_QUOTA_TEST_SRC = \ - test/core/iomgr/resource_quota_test.c \ + test/core/iomgr/resource_quota_test.cc \ RESOURCE_QUOTA_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(RESOURCE_QUOTA_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12319,7 +12410,7 @@ endif SECURE_CHANNEL_CREATE_TEST_SRC = \ - test/core/surface/secure_channel_create_test.c \ + test/core/surface/secure_channel_create_test.cc \ SECURE_CHANNEL_CREATE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SECURE_CHANNEL_CREATE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12351,7 +12442,7 @@ endif SECURE_ENDPOINT_TEST_SRC = \ - test/core/security/secure_endpoint_test.c \ + test/core/security/secure_endpoint_test.cc \ SECURE_ENDPOINT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SECURE_ENDPOINT_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12383,7 +12474,7 @@ endif SEQUENTIAL_CONNECTIVITY_TEST_SRC = \ - test/core/surface/sequential_connectivity_test.c \ + test/core/surface/sequential_connectivity_test.cc \ SEQUENTIAL_CONNECTIVITY_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SEQUENTIAL_CONNECTIVITY_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12415,7 +12506,7 @@ endif SERVER_CHTTP2_TEST_SRC = \ - test/core/surface/server_chttp2_test.c \ + test/core/surface/server_chttp2_test.cc \ SERVER_CHTTP2_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SERVER_CHTTP2_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12447,7 +12538,7 @@ endif SERVER_FUZZER_SRC = \ - test/core/end2end/fuzzers/server_fuzzer.c \ + test/core/end2end/fuzzers/server_fuzzer.cc \ SERVER_FUZZER_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SERVER_FUZZER_SRC)))) ifeq ($(NO_SECURE),true) @@ -12479,7 +12570,7 @@ endif SERVER_TEST_SRC = \ - test/core/surface/server_test.c \ + test/core/surface/server_test.cc \ SERVER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SERVER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12511,7 +12602,7 @@ endif SLICE_BUFFER_TEST_SRC = \ - test/core/slice/slice_buffer_test.c \ + test/core/slice/slice_buffer_test.cc \ SLICE_BUFFER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SLICE_BUFFER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12543,7 +12634,7 @@ endif SLICE_HASH_TABLE_TEST_SRC = \ - test/core/slice/slice_hash_table_test.c \ + test/core/slice/slice_hash_table_test.cc \ SLICE_HASH_TABLE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SLICE_HASH_TABLE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12575,7 +12666,7 @@ endif SLICE_STRING_HELPERS_TEST_SRC = \ - test/core/slice/slice_string_helpers_test.c \ + test/core/slice/slice_string_helpers_test.cc \ SLICE_STRING_HELPERS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SLICE_STRING_HELPERS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12607,7 +12698,7 @@ endif SLICE_TEST_SRC = \ - test/core/slice/slice_test.c \ + test/core/slice/slice_test.cc \ SLICE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SLICE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12639,7 +12730,7 @@ endif SOCKADDR_RESOLVER_TEST_SRC = \ - test/core/client_channel/resolvers/sockaddr_resolver_test.c \ + test/core/client_channel/resolvers/sockaddr_resolver_test.cc \ SOCKADDR_RESOLVER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SOCKADDR_RESOLVER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12671,7 +12762,7 @@ endif SOCKADDR_UTILS_TEST_SRC = \ - test/core/iomgr/sockaddr_utils_test.c \ + test/core/iomgr/sockaddr_utils_test.cc \ SOCKADDR_UTILS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SOCKADDR_UTILS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12703,7 +12794,7 @@ endif SOCKET_UTILS_TEST_SRC = \ - test/core/iomgr/socket_utils_test.c \ + test/core/iomgr/socket_utils_test.cc \ SOCKET_UTILS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SOCKET_UTILS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12735,7 +12826,7 @@ endif SSL_SERVER_FUZZER_SRC = \ - test/core/security/ssl_server_fuzzer.c \ + test/core/security/ssl_server_fuzzer.cc \ SSL_SERVER_FUZZER_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SSL_SERVER_FUZZER_SRC)))) ifeq ($(NO_SECURE),true) @@ -12767,8 +12858,8 @@ endif SSL_TRANSPORT_SECURITY_TEST_SRC = \ - test/core/tsi/ssl_transport_security_test.c \ - test/core/tsi/transport_security_test_lib.c \ + test/core/tsi/ssl_transport_security_test.cc \ + test/core/tsi/transport_security_test_lib.cc \ SSL_TRANSPORT_SECURITY_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SSL_TRANSPORT_SECURITY_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12802,7 +12893,7 @@ endif STATUS_CONVERSION_TEST_SRC = \ - test/core/transport/status_conversion_test.c \ + test/core/transport/status_conversion_test.cc \ STATUS_CONVERSION_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(STATUS_CONVERSION_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12834,7 +12925,7 @@ endif STREAM_COMPRESSION_TEST_SRC = \ - test/core/compression/stream_compression_test.c \ + test/core/compression/stream_compression_test.cc \ STREAM_COMPRESSION_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(STREAM_COMPRESSION_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12866,7 +12957,7 @@ endif STREAM_OWNED_SLICE_TEST_SRC = \ - test/core/transport/stream_owned_slice_test.c \ + test/core/transport/stream_owned_slice_test.cc \ STREAM_OWNED_SLICE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(STREAM_OWNED_SLICE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12898,7 +12989,7 @@ endif TCP_CLIENT_POSIX_TEST_SRC = \ - test/core/iomgr/tcp_client_posix_test.c \ + test/core/iomgr/tcp_client_posix_test.cc \ TCP_CLIENT_POSIX_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(TCP_CLIENT_POSIX_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12930,7 +13021,7 @@ endif TCP_CLIENT_UV_TEST_SRC = \ - test/core/iomgr/tcp_client_uv_test.c \ + test/core/iomgr/tcp_client_uv_test.cc \ TCP_CLIENT_UV_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(TCP_CLIENT_UV_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12962,7 +13053,7 @@ endif TCP_POSIX_TEST_SRC = \ - test/core/iomgr/tcp_posix_test.c \ + test/core/iomgr/tcp_posix_test.cc \ TCP_POSIX_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(TCP_POSIX_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12994,7 +13085,7 @@ endif TCP_SERVER_POSIX_TEST_SRC = \ - test/core/iomgr/tcp_server_posix_test.c \ + test/core/iomgr/tcp_server_posix_test.cc \ TCP_SERVER_POSIX_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(TCP_SERVER_POSIX_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -13026,7 +13117,7 @@ endif TCP_SERVER_UV_TEST_SRC = \ - test/core/iomgr/tcp_server_uv_test.c \ + test/core/iomgr/tcp_server_uv_test.cc \ TCP_SERVER_UV_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(TCP_SERVER_UV_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -13058,7 +13149,7 @@ endif TIME_AVERAGED_STATS_TEST_SRC = \ - test/core/iomgr/time_averaged_stats_test.c \ + test/core/iomgr/time_averaged_stats_test.cc \ TIME_AVERAGED_STATS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(TIME_AVERAGED_STATS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -13090,7 +13181,7 @@ endif TIMEOUT_ENCODING_TEST_SRC = \ - test/core/transport/timeout_encoding_test.c \ + test/core/transport/timeout_encoding_test.cc \ TIMEOUT_ENCODING_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(TIMEOUT_ENCODING_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -13122,7 +13213,7 @@ endif TIMER_HEAP_TEST_SRC = \ - test/core/iomgr/timer_heap_test.c \ + test/core/iomgr/timer_heap_test.cc \ TIMER_HEAP_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(TIMER_HEAP_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -13154,7 +13245,7 @@ endif TIMER_LIST_TEST_SRC = \ - test/core/iomgr/timer_list_test.c \ + test/core/iomgr/timer_list_test.cc \ TIMER_LIST_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(TIMER_LIST_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -13186,7 +13277,7 @@ endif TRANSPORT_CONNECTIVITY_STATE_TEST_SRC = \ - test/core/transport/connectivity_state_test.c \ + test/core/transport/connectivity_state_test.cc \ TRANSPORT_CONNECTIVITY_STATE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(TRANSPORT_CONNECTIVITY_STATE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -13218,7 +13309,7 @@ endif TRANSPORT_METADATA_TEST_SRC = \ - test/core/transport/metadata_test.c \ + test/core/transport/metadata_test.cc \ TRANSPORT_METADATA_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(TRANSPORT_METADATA_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -13250,7 +13341,7 @@ endif TRANSPORT_SECURITY_TEST_SRC = \ - test/core/tsi/transport_security_test.c \ + test/core/tsi/transport_security_test.cc \ TRANSPORT_SECURITY_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(TRANSPORT_SECURITY_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -13282,7 +13373,7 @@ endif UDP_SERVER_TEST_SRC = \ - test/core/iomgr/udp_server_test.c \ + test/core/iomgr/udp_server_test.cc \ UDP_SERVER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(UDP_SERVER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -13314,7 +13405,7 @@ endif URI_FUZZER_TEST_SRC = \ - test/core/client_channel/uri_fuzzer_test.c \ + test/core/client_channel/uri_fuzzer_test.cc \ URI_FUZZER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(URI_FUZZER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -13346,7 +13437,7 @@ endif URI_PARSER_TEST_SRC = \ - test/core/client_channel/uri_parser_test.c \ + test/core/client_channel/uri_parser_test.cc \ URI_PARSER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(URI_PARSER_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -13378,7 +13469,7 @@ endif WAKEUP_FD_CV_TEST_SRC = \ - test/core/iomgr/wakeup_fd_cv_test.c \ + test/core/iomgr/wakeup_fd_cv_test.cc \ WAKEUP_FD_CV_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(WAKEUP_FD_CV_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -14283,6 +14374,49 @@ endif endif +CHTTP2_SETTINGS_TIMEOUT_TEST_SRC = \ + test/core/transport/chttp2/settings_timeout_test.cc \ + +CHTTP2_SETTINGS_TIMEOUT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(CHTTP2_SETTINGS_TIMEOUT_TEST_SRC)))) +ifeq ($(NO_SECURE),true) + +# You can't build secure targets if you don't have OpenSSL. + +$(BINDIR)/$(CONFIG)/chttp2_settings_timeout_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.0.0+. + +$(BINDIR)/$(CONFIG)/chttp2_settings_timeout_test: protobuf_dep_error + +else + +$(BINDIR)/$(CONFIG)/chttp2_settings_timeout_test: $(PROTOBUF_DEP) $(CHTTP2_SETTINGS_TIMEOUT_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a + $(E) "[LD] Linking $@" + $(Q) mkdir -p `dirname $@` + $(Q) $(LDXX) $(LDFLAGS) $(CHTTP2_SETTINGS_TIMEOUT_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LDLIBSXX) $(LDLIBS_PROTOBUF) $(LDLIBS) $(LDLIBS_SECURE) $(GTEST_LIB) -o $(BINDIR)/$(CONFIG)/chttp2_settings_timeout_test + +endif + +endif + +$(OBJDIR)/$(CONFIG)/test/core/transport/chttp2/settings_timeout_test.o: $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a + +deps_chttp2_settings_timeout_test: $(CHTTP2_SETTINGS_TIMEOUT_TEST_OBJS:.o=.dep) + +ifneq ($(NO_SECURE),true) +ifneq ($(NO_DEPS),true) +-include $(CHTTP2_SETTINGS_TIMEOUT_TEST_OBJS:.o=.dep) +endif +endif + + CLI_CALL_TEST_SRC = \ test/cpp/util/cli_call_test.cc \ @@ -14326,6 +14460,53 @@ endif endif +CLIENT_CHANNEL_STRESS_TEST_SRC = \ + $(GENDIR)/src/proto/grpc/lb/v1/load_balancer.pb.cc $(GENDIR)/src/proto/grpc/lb/v1/load_balancer.grpc.pb.cc \ + test/cpp/client/client_channel_stress_test.cc \ + +CLIENT_CHANNEL_STRESS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(CLIENT_CHANNEL_STRESS_TEST_SRC)))) +ifeq ($(NO_SECURE),true) + +# You can't build secure targets if you don't have OpenSSL. + +$(BINDIR)/$(CONFIG)/client_channel_stress_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.0.0+. + +$(BINDIR)/$(CONFIG)/client_channel_stress_test: protobuf_dep_error + +else + +$(BINDIR)/$(CONFIG)/client_channel_stress_test: $(PROTOBUF_DEP) $(CLIENT_CHANNEL_STRESS_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc++_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a + $(E) "[LD] Linking $@" + $(Q) mkdir -p `dirname $@` + $(Q) $(LDXX) $(LDFLAGS) $(CLIENT_CHANNEL_STRESS_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc++_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LDLIBSXX) $(LDLIBS_PROTOBUF) $(LDLIBS) $(LDLIBS_SECURE) $(GTEST_LIB) -o $(BINDIR)/$(CONFIG)/client_channel_stress_test + +endif + +endif + +$(OBJDIR)/$(CONFIG)/src/proto/grpc/lb/v1/load_balancer.o: $(LIBDIR)/$(CONFIG)/libgrpc++_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a + +$(OBJDIR)/$(CONFIG)/test/cpp/client/client_channel_stress_test.o: $(LIBDIR)/$(CONFIG)/libgrpc++_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a + +deps_client_channel_stress_test: $(CLIENT_CHANNEL_STRESS_TEST_OBJS:.o=.dep) + +ifneq ($(NO_SECURE),true) +ifneq ($(NO_DEPS),true) +-include $(CLIENT_CHANNEL_STRESS_TEST_OBJS:.o=.dep) +endif +endif +$(OBJDIR)/$(CONFIG)/test/cpp/client/client_channel_stress_test.o: $(GENDIR)/src/proto/grpc/lb/v1/load_balancer.pb.cc $(GENDIR)/src/proto/grpc/lb/v1/load_balancer.grpc.pb.cc + + CLIENT_CRASH_TEST_SRC = \ test/cpp/end2end/client_crash_test.cc \ @@ -16358,6 +16539,92 @@ endif $(OBJDIR)/$(CONFIG)/test/cpp/interop/reconnect_interop_server.o: $(GENDIR)/src/proto/grpc/testing/empty.pb.cc $(GENDIR)/src/proto/grpc/testing/empty.grpc.pb.cc $(GENDIR)/src/proto/grpc/testing/messages.pb.cc $(GENDIR)/src/proto/grpc/testing/messages.grpc.pb.cc $(GENDIR)/src/proto/grpc/testing/test.pb.cc $(GENDIR)/src/proto/grpc/testing/test.grpc.pb.cc +REF_COUNTED_PTR_TEST_SRC = \ + test/core/support/ref_counted_ptr_test.cc \ + +REF_COUNTED_PTR_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(REF_COUNTED_PTR_TEST_SRC)))) +ifeq ($(NO_SECURE),true) + +# You can't build secure targets if you don't have OpenSSL. + +$(BINDIR)/$(CONFIG)/ref_counted_ptr_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.0.0+. + +$(BINDIR)/$(CONFIG)/ref_counted_ptr_test: protobuf_dep_error + +else + +$(BINDIR)/$(CONFIG)/ref_counted_ptr_test: $(PROTOBUF_DEP) $(REF_COUNTED_PTR_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a + $(E) "[LD] Linking $@" + $(Q) mkdir -p `dirname $@` + $(Q) $(LDXX) $(LDFLAGS) $(REF_COUNTED_PTR_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LDLIBSXX) $(LDLIBS_PROTOBUF) $(LDLIBS) $(LDLIBS_SECURE) $(GTEST_LIB) -o $(BINDIR)/$(CONFIG)/ref_counted_ptr_test + +endif + +endif + +$(OBJDIR)/$(CONFIG)/test/core/support/ref_counted_ptr_test.o: $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a + +deps_ref_counted_ptr_test: $(REF_COUNTED_PTR_TEST_OBJS:.o=.dep) + +ifneq ($(NO_SECURE),true) +ifneq ($(NO_DEPS),true) +-include $(REF_COUNTED_PTR_TEST_OBJS:.o=.dep) +endif +endif + + +REF_COUNTED_TEST_SRC = \ + test/core/support/ref_counted_test.cc \ + +REF_COUNTED_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(REF_COUNTED_TEST_SRC)))) +ifeq ($(NO_SECURE),true) + +# You can't build secure targets if you don't have OpenSSL. + +$(BINDIR)/$(CONFIG)/ref_counted_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.0.0+. + +$(BINDIR)/$(CONFIG)/ref_counted_test: protobuf_dep_error + +else + +$(BINDIR)/$(CONFIG)/ref_counted_test: $(PROTOBUF_DEP) $(REF_COUNTED_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a + $(E) "[LD] Linking $@" + $(Q) mkdir -p `dirname $@` + $(Q) $(LDXX) $(LDFLAGS) $(REF_COUNTED_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LDLIBSXX) $(LDLIBS_PROTOBUF) $(LDLIBS) $(LDLIBS_SECURE) $(GTEST_LIB) -o $(BINDIR)/$(CONFIG)/ref_counted_test + +endif + +endif + +$(OBJDIR)/$(CONFIG)/test/core/support/ref_counted_test.o: $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a + +deps_ref_counted_test: $(REF_COUNTED_TEST_OBJS:.o=.dep) + +ifneq ($(NO_SECURE),true) +ifneq ($(NO_DEPS),true) +-include $(REF_COUNTED_TEST_OBJS:.o=.dep) +endif +endif + + SECURE_AUTH_CONTEXT_TEST_SRC = \ test/cpp/common/secure_auth_context_test.cc \ @@ -17085,49 +17352,6 @@ endif endif -VECTOR_TEST_SRC = \ - test/core/support/vector_test.cc \ - -VECTOR_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(VECTOR_TEST_SRC)))) -ifeq ($(NO_SECURE),true) - -# You can't build secure targets if you don't have OpenSSL. - -$(BINDIR)/$(CONFIG)/vector_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.0.0+. - -$(BINDIR)/$(CONFIG)/vector_test: protobuf_dep_error - -else - -$(BINDIR)/$(CONFIG)/vector_test: $(PROTOBUF_DEP) $(VECTOR_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a - $(E) "[LD] Linking $@" - $(Q) mkdir -p `dirname $@` - $(Q) $(LDXX) $(LDFLAGS) $(VECTOR_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LDLIBSXX) $(LDLIBS_PROTOBUF) $(LDLIBS) $(LDLIBS_SECURE) $(GTEST_LIB) -o $(BINDIR)/$(CONFIG)/vector_test - -endif - -endif - -$(OBJDIR)/$(CONFIG)/test/core/support/vector_test.o: $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a - -deps_vector_test: $(VECTOR_TEST_OBJS:.o=.dep) - -ifneq ($(NO_SECURE),true) -ifneq ($(NO_DEPS),true) --include $(VECTOR_TEST_OBJS:.o=.dep) -endif -endif - - WRITES_PER_RPC_TEST_SRC = \ test/cpp/performance/writes_per_rpc_test.cc \ @@ -18310,7 +18534,7 @@ $(BORINGSSL_V3NAME_TEST_OBJS): CFLAGS += -Wno-sign-conversion -Wno-conversion -W BADREQ_BAD_CLIENT_TEST_SRC = \ - test/core/bad_client/tests/badreq.c \ + test/core/bad_client/tests/badreq.cc \ BADREQ_BAD_CLIENT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(BADREQ_BAD_CLIENT_TEST_SRC)))) @@ -18330,7 +18554,7 @@ endif CONNECTION_PREFIX_BAD_CLIENT_TEST_SRC = \ - test/core/bad_client/tests/connection_prefix.c \ + test/core/bad_client/tests/connection_prefix.cc \ CONNECTION_PREFIX_BAD_CLIENT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(CONNECTION_PREFIX_BAD_CLIENT_TEST_SRC)))) @@ -18350,7 +18574,7 @@ endif HEAD_OF_LINE_BLOCKING_BAD_CLIENT_TEST_SRC = \ - test/core/bad_client/tests/head_of_line_blocking.c \ + test/core/bad_client/tests/head_of_line_blocking.cc \ HEAD_OF_LINE_BLOCKING_BAD_CLIENT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HEAD_OF_LINE_BLOCKING_BAD_CLIENT_TEST_SRC)))) @@ -18370,7 +18594,7 @@ endif HEADERS_BAD_CLIENT_TEST_SRC = \ - test/core/bad_client/tests/headers.c \ + test/core/bad_client/tests/headers.cc \ HEADERS_BAD_CLIENT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HEADERS_BAD_CLIENT_TEST_SRC)))) @@ -18390,7 +18614,7 @@ endif INITIAL_SETTINGS_FRAME_BAD_CLIENT_TEST_SRC = \ - test/core/bad_client/tests/initial_settings_frame.c \ + test/core/bad_client/tests/initial_settings_frame.cc \ INITIAL_SETTINGS_FRAME_BAD_CLIENT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(INITIAL_SETTINGS_FRAME_BAD_CLIENT_TEST_SRC)))) @@ -18410,7 +18634,7 @@ endif SERVER_REGISTERED_METHOD_BAD_CLIENT_TEST_SRC = \ - test/core/bad_client/tests/server_registered_method.c \ + test/core/bad_client/tests/server_registered_method.cc \ SERVER_REGISTERED_METHOD_BAD_CLIENT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SERVER_REGISTERED_METHOD_BAD_CLIENT_TEST_SRC)))) @@ -18430,7 +18654,7 @@ endif SIMPLE_REQUEST_BAD_CLIENT_TEST_SRC = \ - test/core/bad_client/tests/simple_request.c \ + test/core/bad_client/tests/simple_request.cc \ SIMPLE_REQUEST_BAD_CLIENT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SIMPLE_REQUEST_BAD_CLIENT_TEST_SRC)))) @@ -18450,7 +18674,7 @@ endif UNKNOWN_FRAME_BAD_CLIENT_TEST_SRC = \ - test/core/bad_client/tests/unknown_frame.c \ + test/core/bad_client/tests/unknown_frame.cc \ UNKNOWN_FRAME_BAD_CLIENT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(UNKNOWN_FRAME_BAD_CLIENT_TEST_SRC)))) @@ -18470,7 +18694,7 @@ endif WINDOW_OVERFLOW_BAD_CLIENT_TEST_SRC = \ - test/core/bad_client/tests/window_overflow.c \ + test/core/bad_client/tests/window_overflow.cc \ WINDOW_OVERFLOW_BAD_CLIENT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(WINDOW_OVERFLOW_BAD_CLIENT_TEST_SRC)))) @@ -18490,7 +18714,7 @@ endif BAD_SSL_CERT_SERVER_SRC = \ - test/core/bad_ssl/servers/cert.c \ + test/core/bad_ssl/servers/cert.cc \ BAD_SSL_CERT_SERVER_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(BAD_SSL_CERT_SERVER_SRC)))) ifeq ($(NO_SECURE),true) @@ -18522,7 +18746,7 @@ endif BAD_SSL_CERT_TEST_SRC = \ - test/core/bad_ssl/bad_ssl_test.c \ + test/core/bad_ssl/bad_ssl_test.cc \ BAD_SSL_CERT_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(BAD_SSL_CERT_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -18554,7 +18778,7 @@ endif H2_CENSUS_TEST_SRC = \ - test/core/end2end/fixtures/h2_census.c \ + test/core/end2end/fixtures/h2_census.cc \ H2_CENSUS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_CENSUS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -18586,7 +18810,7 @@ endif H2_COMPRESS_TEST_SRC = \ - test/core/end2end/fixtures/h2_compress.c \ + test/core/end2end/fixtures/h2_compress.cc \ H2_COMPRESS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_COMPRESS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -18618,7 +18842,7 @@ endif H2_FAKESEC_TEST_SRC = \ - test/core/end2end/fixtures/h2_fakesec.c \ + test/core/end2end/fixtures/h2_fakesec.cc \ H2_FAKESEC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_FAKESEC_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -18650,7 +18874,7 @@ endif H2_FD_TEST_SRC = \ - test/core/end2end/fixtures/h2_fd.c \ + test/core/end2end/fixtures/h2_fd.cc \ H2_FD_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_FD_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -18682,7 +18906,7 @@ endif H2_FULL_TEST_SRC = \ - test/core/end2end/fixtures/h2_full.c \ + test/core/end2end/fixtures/h2_full.cc \ H2_FULL_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_FULL_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -18714,7 +18938,7 @@ endif H2_FULL+PIPE_TEST_SRC = \ - test/core/end2end/fixtures/h2_full+pipe.c \ + test/core/end2end/fixtures/h2_full+pipe.cc \ H2_FULL+PIPE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_FULL+PIPE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -18746,7 +18970,7 @@ endif H2_FULL+TRACE_TEST_SRC = \ - test/core/end2end/fixtures/h2_full+trace.c \ + test/core/end2end/fixtures/h2_full+trace.cc \ H2_FULL+TRACE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_FULL+TRACE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -18778,7 +19002,7 @@ endif H2_FULL+WORKAROUNDS_TEST_SRC = \ - test/core/end2end/fixtures/h2_full+workarounds.c \ + test/core/end2end/fixtures/h2_full+workarounds.cc \ H2_FULL+WORKAROUNDS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_FULL+WORKAROUNDS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -18810,7 +19034,7 @@ endif H2_HTTP_PROXY_TEST_SRC = \ - test/core/end2end/fixtures/h2_http_proxy.c \ + test/core/end2end/fixtures/h2_http_proxy.cc \ H2_HTTP_PROXY_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_HTTP_PROXY_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -18842,7 +19066,7 @@ endif H2_LOAD_REPORTING_TEST_SRC = \ - test/core/end2end/fixtures/h2_load_reporting.c \ + test/core/end2end/fixtures/h2_load_reporting.cc \ H2_LOAD_REPORTING_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_LOAD_REPORTING_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -18874,7 +19098,7 @@ endif H2_OAUTH2_TEST_SRC = \ - test/core/end2end/fixtures/h2_oauth2.c \ + test/core/end2end/fixtures/h2_oauth2.cc \ H2_OAUTH2_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_OAUTH2_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -18906,7 +19130,7 @@ endif H2_PROXY_TEST_SRC = \ - test/core/end2end/fixtures/h2_proxy.c \ + test/core/end2end/fixtures/h2_proxy.cc \ H2_PROXY_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_PROXY_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -18938,7 +19162,7 @@ endif H2_SOCKPAIR_TEST_SRC = \ - test/core/end2end/fixtures/h2_sockpair.c \ + test/core/end2end/fixtures/h2_sockpair.cc \ H2_SOCKPAIR_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_SOCKPAIR_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -18970,7 +19194,7 @@ endif H2_SOCKPAIR+TRACE_TEST_SRC = \ - test/core/end2end/fixtures/h2_sockpair+trace.c \ + test/core/end2end/fixtures/h2_sockpair+trace.cc \ H2_SOCKPAIR+TRACE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_SOCKPAIR+TRACE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -19002,7 +19226,7 @@ endif H2_SOCKPAIR_1BYTE_TEST_SRC = \ - test/core/end2end/fixtures/h2_sockpair_1byte.c \ + test/core/end2end/fixtures/h2_sockpair_1byte.cc \ H2_SOCKPAIR_1BYTE_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_SOCKPAIR_1BYTE_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -19034,7 +19258,7 @@ endif H2_SSL_TEST_SRC = \ - test/core/end2end/fixtures/h2_ssl.c \ + test/core/end2end/fixtures/h2_ssl.cc \ H2_SSL_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_SSL_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -19066,7 +19290,7 @@ endif H2_SSL_PROXY_TEST_SRC = \ - test/core/end2end/fixtures/h2_ssl_proxy.c \ + test/core/end2end/fixtures/h2_ssl_proxy.cc \ H2_SSL_PROXY_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_SSL_PROXY_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -19098,7 +19322,7 @@ endif H2_UDS_TEST_SRC = \ - test/core/end2end/fixtures/h2_uds.c \ + test/core/end2end/fixtures/h2_uds.cc \ H2_UDS_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_UDS_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -19130,7 +19354,7 @@ endif INPROC_TEST_SRC = \ - test/core/end2end/fixtures/inproc.c \ + test/core/end2end/fixtures/inproc.cc \ INPROC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(INPROC_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -19162,7 +19386,7 @@ endif H2_CENSUS_NOSEC_TEST_SRC = \ - test/core/end2end/fixtures/h2_census.c \ + test/core/end2end/fixtures/h2_census.cc \ H2_CENSUS_NOSEC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_CENSUS_NOSEC_TEST_SRC)))) @@ -19182,7 +19406,7 @@ endif H2_COMPRESS_NOSEC_TEST_SRC = \ - test/core/end2end/fixtures/h2_compress.c \ + test/core/end2end/fixtures/h2_compress.cc \ H2_COMPRESS_NOSEC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_COMPRESS_NOSEC_TEST_SRC)))) @@ -19202,7 +19426,7 @@ endif H2_FD_NOSEC_TEST_SRC = \ - test/core/end2end/fixtures/h2_fd.c \ + test/core/end2end/fixtures/h2_fd.cc \ H2_FD_NOSEC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_FD_NOSEC_TEST_SRC)))) @@ -19222,7 +19446,7 @@ endif H2_FULL_NOSEC_TEST_SRC = \ - test/core/end2end/fixtures/h2_full.c \ + test/core/end2end/fixtures/h2_full.cc \ H2_FULL_NOSEC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_FULL_NOSEC_TEST_SRC)))) @@ -19242,7 +19466,7 @@ endif H2_FULL+PIPE_NOSEC_TEST_SRC = \ - test/core/end2end/fixtures/h2_full+pipe.c \ + test/core/end2end/fixtures/h2_full+pipe.cc \ H2_FULL+PIPE_NOSEC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_FULL+PIPE_NOSEC_TEST_SRC)))) @@ -19262,7 +19486,7 @@ endif H2_FULL+TRACE_NOSEC_TEST_SRC = \ - test/core/end2end/fixtures/h2_full+trace.c \ + test/core/end2end/fixtures/h2_full+trace.cc \ H2_FULL+TRACE_NOSEC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_FULL+TRACE_NOSEC_TEST_SRC)))) @@ -19282,7 +19506,7 @@ endif H2_FULL+WORKAROUNDS_NOSEC_TEST_SRC = \ - test/core/end2end/fixtures/h2_full+workarounds.c \ + test/core/end2end/fixtures/h2_full+workarounds.cc \ H2_FULL+WORKAROUNDS_NOSEC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_FULL+WORKAROUNDS_NOSEC_TEST_SRC)))) @@ -19302,7 +19526,7 @@ endif H2_HTTP_PROXY_NOSEC_TEST_SRC = \ - test/core/end2end/fixtures/h2_http_proxy.c \ + test/core/end2end/fixtures/h2_http_proxy.cc \ H2_HTTP_PROXY_NOSEC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_HTTP_PROXY_NOSEC_TEST_SRC)))) @@ -19322,7 +19546,7 @@ endif H2_LOAD_REPORTING_NOSEC_TEST_SRC = \ - test/core/end2end/fixtures/h2_load_reporting.c \ + test/core/end2end/fixtures/h2_load_reporting.cc \ H2_LOAD_REPORTING_NOSEC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_LOAD_REPORTING_NOSEC_TEST_SRC)))) @@ -19342,7 +19566,7 @@ endif H2_PROXY_NOSEC_TEST_SRC = \ - test/core/end2end/fixtures/h2_proxy.c \ + test/core/end2end/fixtures/h2_proxy.cc \ H2_PROXY_NOSEC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_PROXY_NOSEC_TEST_SRC)))) @@ -19362,7 +19586,7 @@ endif H2_SOCKPAIR_NOSEC_TEST_SRC = \ - test/core/end2end/fixtures/h2_sockpair.c \ + test/core/end2end/fixtures/h2_sockpair.cc \ H2_SOCKPAIR_NOSEC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_SOCKPAIR_NOSEC_TEST_SRC)))) @@ -19382,7 +19606,7 @@ endif H2_SOCKPAIR+TRACE_NOSEC_TEST_SRC = \ - test/core/end2end/fixtures/h2_sockpair+trace.c \ + test/core/end2end/fixtures/h2_sockpair+trace.cc \ H2_SOCKPAIR+TRACE_NOSEC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_SOCKPAIR+TRACE_NOSEC_TEST_SRC)))) @@ -19402,7 +19626,7 @@ endif H2_SOCKPAIR_1BYTE_NOSEC_TEST_SRC = \ - test/core/end2end/fixtures/h2_sockpair_1byte.c \ + test/core/end2end/fixtures/h2_sockpair_1byte.cc \ H2_SOCKPAIR_1BYTE_NOSEC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_SOCKPAIR_1BYTE_NOSEC_TEST_SRC)))) @@ -19422,7 +19646,7 @@ endif H2_UDS_NOSEC_TEST_SRC = \ - test/core/end2end/fixtures/h2_uds.c \ + test/core/end2end/fixtures/h2_uds.cc \ H2_UDS_NOSEC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(H2_UDS_NOSEC_TEST_SRC)))) @@ -19442,7 +19666,7 @@ endif INPROC_NOSEC_TEST_SRC = \ - test/core/end2end/fixtures/inproc.c \ + test/core/end2end/fixtures/inproc.cc \ INPROC_NOSEC_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(INPROC_NOSEC_TEST_SRC)))) @@ -19634,8 +19858,8 @@ endif API_FUZZER_ONE_ENTRY_SRC = \ - test/core/end2end/fuzzers/api_fuzzer.c \ - test/core/util/one_corpus_entry_fuzzer.c \ + test/core/end2end/fuzzers/api_fuzzer.cc \ + test/core/util/one_corpus_entry_fuzzer.cc \ API_FUZZER_ONE_ENTRY_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(API_FUZZER_ONE_ENTRY_SRC)))) ifeq ($(NO_SECURE),true) @@ -19669,8 +19893,8 @@ endif CLIENT_FUZZER_ONE_ENTRY_SRC = \ - test/core/end2end/fuzzers/client_fuzzer.c \ - test/core/util/one_corpus_entry_fuzzer.c \ + test/core/end2end/fuzzers/client_fuzzer.cc \ + test/core/util/one_corpus_entry_fuzzer.cc \ CLIENT_FUZZER_ONE_ENTRY_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(CLIENT_FUZZER_ONE_ENTRY_SRC)))) ifeq ($(NO_SECURE),true) @@ -19704,8 +19928,8 @@ endif HPACK_PARSER_FUZZER_TEST_ONE_ENTRY_SRC = \ - test/core/transport/chttp2/hpack_parser_fuzzer_test.c \ - test/core/util/one_corpus_entry_fuzzer.c \ + test/core/transport/chttp2/hpack_parser_fuzzer_test.cc \ + test/core/util/one_corpus_entry_fuzzer.cc \ HPACK_PARSER_FUZZER_TEST_ONE_ENTRY_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HPACK_PARSER_FUZZER_TEST_ONE_ENTRY_SRC)))) ifeq ($(NO_SECURE),true) @@ -19739,8 +19963,8 @@ endif HTTP_REQUEST_FUZZER_TEST_ONE_ENTRY_SRC = \ - test/core/http/request_fuzzer.c \ - test/core/util/one_corpus_entry_fuzzer.c \ + test/core/http/request_fuzzer.cc \ + test/core/util/one_corpus_entry_fuzzer.cc \ HTTP_REQUEST_FUZZER_TEST_ONE_ENTRY_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HTTP_REQUEST_FUZZER_TEST_ONE_ENTRY_SRC)))) ifeq ($(NO_SECURE),true) @@ -19774,8 +19998,8 @@ endif HTTP_RESPONSE_FUZZER_TEST_ONE_ENTRY_SRC = \ - test/core/http/response_fuzzer.c \ - test/core/util/one_corpus_entry_fuzzer.c \ + test/core/http/response_fuzzer.cc \ + test/core/util/one_corpus_entry_fuzzer.cc \ HTTP_RESPONSE_FUZZER_TEST_ONE_ENTRY_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(HTTP_RESPONSE_FUZZER_TEST_ONE_ENTRY_SRC)))) ifeq ($(NO_SECURE),true) @@ -19809,8 +20033,8 @@ endif JSON_FUZZER_TEST_ONE_ENTRY_SRC = \ - test/core/json/fuzzer.c \ - test/core/util/one_corpus_entry_fuzzer.c \ + test/core/json/fuzzer.cc \ + test/core/util/one_corpus_entry_fuzzer.cc \ JSON_FUZZER_TEST_ONE_ENTRY_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(JSON_FUZZER_TEST_ONE_ENTRY_SRC)))) ifeq ($(NO_SECURE),true) @@ -19844,8 +20068,8 @@ endif NANOPB_FUZZER_RESPONSE_TEST_ONE_ENTRY_SRC = \ - test/core/nanopb/fuzzer_response.c \ - test/core/util/one_corpus_entry_fuzzer.c \ + test/core/nanopb/fuzzer_response.cc \ + test/core/util/one_corpus_entry_fuzzer.cc \ NANOPB_FUZZER_RESPONSE_TEST_ONE_ENTRY_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(NANOPB_FUZZER_RESPONSE_TEST_ONE_ENTRY_SRC)))) ifeq ($(NO_SECURE),true) @@ -19879,8 +20103,8 @@ endif NANOPB_FUZZER_SERVERLIST_TEST_ONE_ENTRY_SRC = \ - test/core/nanopb/fuzzer_serverlist.c \ - test/core/util/one_corpus_entry_fuzzer.c \ + test/core/nanopb/fuzzer_serverlist.cc \ + test/core/util/one_corpus_entry_fuzzer.cc \ NANOPB_FUZZER_SERVERLIST_TEST_ONE_ENTRY_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(NANOPB_FUZZER_SERVERLIST_TEST_ONE_ENTRY_SRC)))) ifeq ($(NO_SECURE),true) @@ -19914,8 +20138,8 @@ endif PERCENT_DECODE_FUZZER_ONE_ENTRY_SRC = \ - test/core/slice/percent_decode_fuzzer.c \ - test/core/util/one_corpus_entry_fuzzer.c \ + test/core/slice/percent_decode_fuzzer.cc \ + test/core/util/one_corpus_entry_fuzzer.cc \ PERCENT_DECODE_FUZZER_ONE_ENTRY_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(PERCENT_DECODE_FUZZER_ONE_ENTRY_SRC)))) ifeq ($(NO_SECURE),true) @@ -19949,8 +20173,8 @@ endif PERCENT_ENCODE_FUZZER_ONE_ENTRY_SRC = \ - test/core/slice/percent_encode_fuzzer.c \ - test/core/util/one_corpus_entry_fuzzer.c \ + test/core/slice/percent_encode_fuzzer.cc \ + test/core/util/one_corpus_entry_fuzzer.cc \ PERCENT_ENCODE_FUZZER_ONE_ENTRY_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(PERCENT_ENCODE_FUZZER_ONE_ENTRY_SRC)))) ifeq ($(NO_SECURE),true) @@ -19984,8 +20208,8 @@ endif SERVER_FUZZER_ONE_ENTRY_SRC = \ - test/core/end2end/fuzzers/server_fuzzer.c \ - test/core/util/one_corpus_entry_fuzzer.c \ + test/core/end2end/fuzzers/server_fuzzer.cc \ + test/core/util/one_corpus_entry_fuzzer.cc \ SERVER_FUZZER_ONE_ENTRY_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SERVER_FUZZER_ONE_ENTRY_SRC)))) ifeq ($(NO_SECURE),true) @@ -20019,8 +20243,8 @@ endif SSL_SERVER_FUZZER_ONE_ENTRY_SRC = \ - test/core/security/ssl_server_fuzzer.c \ - test/core/util/one_corpus_entry_fuzzer.c \ + test/core/security/ssl_server_fuzzer.cc \ + test/core/util/one_corpus_entry_fuzzer.cc \ SSL_SERVER_FUZZER_ONE_ENTRY_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(SSL_SERVER_FUZZER_ONE_ENTRY_SRC)))) ifeq ($(NO_SECURE),true) @@ -20054,8 +20278,8 @@ endif URI_FUZZER_TEST_ONE_ENTRY_SRC = \ - test/core/client_channel/uri_fuzzer_test.c \ - test/core/util/one_corpus_entry_fuzzer.c \ + test/core/client_channel/uri_fuzzer_test.cc \ + test/core/util/one_corpus_entry_fuzzer.cc \ URI_FUZZER_TEST_ONE_ENTRY_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(URI_FUZZER_TEST_ONE_ENTRY_SRC)))) ifeq ($(NO_SECURE),true) @@ -20146,17 +20370,17 @@ src/cpp/server/secure_server_credentials.cc: $(OPENSSL_DEP) src/cpp/util/core_stats.cc: $(OPENSSL_DEP) src/cpp/util/error_details.cc: $(OPENSSL_DEP) src/csharp/ext/grpc_csharp_ext.c: $(OPENSSL_DEP) -test/core/bad_client/bad_client.c: $(OPENSSL_DEP) -test/core/bad_ssl/server_common.c: $(OPENSSL_DEP) -test/core/end2end/data/client_certs.c: $(OPENSSL_DEP) -test/core/end2end/data/server1_cert.c: $(OPENSSL_DEP) -test/core/end2end/data/server1_key.c: $(OPENSSL_DEP) -test/core/end2end/data/test_root_cert.c: $(OPENSSL_DEP) -test/core/end2end/end2end_tests.c: $(OPENSSL_DEP) -test/core/end2end/tests/call_creds.c: $(OPENSSL_DEP) -test/core/security/oauth2_utils.c: $(OPENSSL_DEP) -test/core/util/reconnect_server.c: $(OPENSSL_DEP) -test/core/util/test_tcp_server.c: $(OPENSSL_DEP) +test/core/bad_client/bad_client.cc: $(OPENSSL_DEP) +test/core/bad_ssl/server_common.cc: $(OPENSSL_DEP) +test/core/end2end/data/client_certs.cc: $(OPENSSL_DEP) +test/core/end2end/data/server1_cert.cc: $(OPENSSL_DEP) +test/core/end2end/data/server1_key.cc: $(OPENSSL_DEP) +test/core/end2end/data/test_root_cert.cc: $(OPENSSL_DEP) +test/core/end2end/end2end_tests.cc: $(OPENSSL_DEP) +test/core/end2end/tests/call_creds.cc: $(OPENSSL_DEP) +test/core/security/oauth2_utils.cc: $(OPENSSL_DEP) +test/core/util/reconnect_server.cc: $(OPENSSL_DEP) +test/core/util/test_tcp_server.cc: $(OPENSSL_DEP) test/cpp/end2end/test_service_impl.cc: $(OPENSSL_DEP) test/cpp/interop/client.cc: $(OPENSSL_DEP) test/cpp/interop/client_helper.cc: $(OPENSSL_DEP) diff --git a/README.md b/README.md index 61479f34aa2..048614a2057 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,6 @@ Libraries in different languages may be in different states of development. We a | Shared C [core library] | [src/core](src/core) | 1.6 | | C++ | [src/cpp](src/cpp) | 1.6 | | Ruby | [src/ruby](src/ruby) | 1.6 | -| NodeJS | [src/node](src/node) | 1.6 | | Python | [src/python](src/python) | 1.6 | | PHP | [src/php](src/php) | 1.6 | | C# | [src/csharp](src/csharp) | 1.6 | @@ -38,7 +37,8 @@ Libraries in different languages may be in different states of development. We a Java source code is in the [grpc-java](http://github.com/grpc/grpc-java) repository. Go source code is in the -[grpc-go](http://github.com/grpc/grpc-go) repository. +[grpc-go](http://github.com/grpc/grpc-go) repository. NodeJS source code is in the +[grpc-node](https://github.com/grpc/grpc-node) repository. See [MANIFEST.md](MANIFEST.md) for a listing of top-level items in the repository. diff --git a/WORKSPACE b/WORKSPACE index 907cef1fcae..bf09aa7cc93 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -10,7 +10,7 @@ bind( bind( name = "zlib", - actual = "@submodule_zlib//:z", + actual = "@com_github_madler_zlib//:z", ) bind( @@ -23,6 +23,11 @@ bind( actual = "@com_google_protobuf//:protoc_lib", ) +bind( + name = "protobuf_headers", + actual = "@com_google_protobuf//:protobuf_headers", +) + bind( name = "protocol_compiler", actual = "@com_google_protobuf//:protoc", @@ -30,22 +35,22 @@ bind( bind( name = "cares", - actual = "@submodule_cares//:ares", + actual = "@com_github_cares_cares//:ares", ) bind( name = "gtest", - actual = "@submodule_gtest//:gtest", + actual = "@com_github_google_googletest//:gtest", ) bind( name = "gmock", - actual = "@submodule_gtest//:gmock", + actual = "@com_github_google_googletest//:gmock", ) bind( name = "benchmark", - actual = "@submodule_benchmark//:benchmark", + actual = "@com_github_google_benchmark//:benchmark", ) bind( @@ -53,47 +58,70 @@ bind( actual = "@com_github_gflags_gflags//:gflags", ) -local_repository( +http_archive( name = "boringssl", - path = "third_party/boringssl-with-bazel", + # on the master-with-bazel branch + url = "https://boringssl.googlesource.com/boringssl/+archive/886e7d75368e3f4fab3f4d0d3584e4abfc557755.tar.gz", ) -new_local_repository( - name = "submodule_zlib", +new_http_archive( + name = "com_github_madler_zlib", build_file = "third_party/zlib.BUILD", - path = "third_party/zlib", + strip_prefix = "zlib-cacf7f1d4e3d44d871b605da3b647f07d718623f", + url = "https://github.com/madler/zlib/archive/cacf7f1d4e3d44d871b605da3b647f07d718623f.tar.gz", ) -new_local_repository( +http_archive( name = "com_google_protobuf", - build_file = "third_party/protobuf/BUILD", - path = "third_party/protobuf", + strip_prefix = "protobuf-2761122b810fe8861004ae785cc3ab39f384d342", + url = "https://github.com/google/protobuf/archive/2761122b810fe8861004ae785cc3ab39f384d342.tar.gz", ) -new_local_repository( - name = "submodule_gtest", +new_http_archive( + name = "com_github_google_googletest", build_file = "third_party/gtest.BUILD", - path = "third_party/googletest", + strip_prefix = "googletest-ec44c6c1675c25b9827aacd08c02433cccde7780", + url = "https://github.com/google/googletest/archive/ec44c6c1675c25b9827aacd08c02433cccde7780.tar.gz", ) -local_repository( +http_archive( name = "com_github_gflags_gflags", - path = "third_party/gflags", + strip_prefix = "gflags-30dbc81fb5ffdc98ea9b14b1918bfe4e8779b26e", + url = "https://github.com/gflags/gflags/archive/30dbc81fb5ffdc98ea9b14b1918bfe4e8779b26e.tar.gz", ) -new_local_repository( - name = "submodule_benchmark", - path = "third_party/benchmark", +new_http_archive( + name = "com_github_google_benchmark", build_file = "third_party/benchmark.BUILD", + strip_prefix = "benchmark-5b7683f49e1e9223cf9927b24f6fd3d6bd82e3f8", + url = "https://github.com/google/benchmark/archive/5b7683f49e1e9223cf9927b24f6fd3d6bd82e3f8.tar.gz", ) new_local_repository( - name = "submodule_cares", + name = "cares_local_files", + build_file = "third_party/cares/cares_local_files.BUILD", path = "third_party/cares", +) + +new_http_archive( + name = "com_github_cares_cares", build_file = "third_party/cares/cares.BUILD", + strip_prefix = "c-ares-3be1924221e1326df520f8498d704a5c4c8d0cce", + url = "https://github.com/c-ares/c-ares/archive/3be1924221e1326df520f8498d704a5c4c8d0cce.tar.gz", ) -local_repository( +http_archive( name = "com_google_absl", - path = "third_party/abseil-cpp", + strip_prefix = "abseil-cpp-cc4bed2d74f7c8717e31f9579214ab52a9c9c610", + url = "https://github.com/abseil/abseil-cpp/archive/cc4bed2d74f7c8717e31f9579214ab52a9c9c610.tar.gz", +) + +http_archive( + name = "bazel_toolchains", + urls = [ + "https://mirror.bazel.build/github.com/bazelbuild/bazel-toolchains/archive/af4681c3d19f063f090222ec3d04108c4e0ca255.tar.gz", + "https://github.com/bazelbuild/bazel-toolchains/archive/af4681c3d19f063f090222ec3d04108c4e0ca255.tar.gz", + ], + strip_prefix = "bazel-toolchains-af4681c3d19f063f090222ec3d04108c4e0ca255", + sha256 = "d58bb2d6c8603f600d522b6104d6192a65339aa26cbba9f11ff5c4b36dedb928", ) diff --git a/bazel/cc_grpc_library.bzl b/bazel/cc_grpc_library.bzl index afc5543795a..94781ed7ae5 100644 --- a/bazel/cc_grpc_library.bzl +++ b/bazel/cc_grpc_library.bzl @@ -60,10 +60,10 @@ def cc_grpc_library(name, srcs, deps, proto_only, well_known_protos, generate_mo if use_external: # when this file is used by non-grpc projects - grpc_deps = ["//external:grpc++", "//external:grpc++_codegen_proto", + grpc_deps = ["//external:grpc++_codegen_proto", "//external:protobuf"] else: - grpc_deps = ["//:grpc++", "//:grpc++_codegen_proto", "//external:protobuf"] + grpc_deps = ["//:grpc++_codegen_proto", "//external:protobuf"] native.cc_library( name = name, diff --git a/bazel/grpc_build_system.bzl b/bazel/grpc_build_system.bzl index 6cfed6b0e72..2ef85445023 100644 --- a/bazel/grpc_build_system.bzl +++ b/bazel/grpc_build_system.bzl @@ -23,6 +23,9 @@ # each change must be ported from one to the other. # +# The set of pollers to test against if a test exercises polling +POLLERS = ['epollex', 'epollsig', 'epoll1', 'poll', 'poll-cv'] + def grpc_cc_library(name, srcs = [], public_hdrs = [], hdrs = [], external_deps = [], deps = [], standalone = False, language = "C++", testonly = False, visibility = None, @@ -33,6 +36,10 @@ def grpc_cc_library(name, srcs = [], public_hdrs = [], hdrs = [], native.cc_library( name = name, srcs = srcs, + defines = select({"//:grpc_no_ares": ["GRPC_ARES=0"], + "//conditions:default": [],}) + + select({"//:remote_execution": ["GRPC_PORT_ISOLATED_RUNTIME=1"], + "//conditions:default": [],}), hdrs = hdrs + public_hdrs, deps = deps + ["//external:" + dep for dep in external_deps], copts = copts, @@ -66,19 +73,35 @@ def grpc_proto_library(name, srcs = [], deps = [], well_known_protos = False, generate_mock = generate_mock, ) -def grpc_cc_test(name, srcs = [], deps = [], external_deps = [], args = [], data = [], language = "C++"): +def grpc_cc_test(name, srcs = [], deps = [], external_deps = [], args = [], data = [], uses_polling = True, language = "C++"): copts = [] if language.upper() == "C": copts = ["-std=c99"] - native.cc_test( - name = name, - srcs = srcs, - args = args, - data = data, - deps = deps + ["//external:" + dep for dep in external_deps], - copts = copts, - linkopts = ["-pthread"], - ) + args = { + 'name': name, + 'srcs': srcs, + 'args': args, + 'data': data, + 'deps': deps + ["//external:" + dep for dep in external_deps], + 'copts': copts, + 'linkopts': ["-pthread"], + } + if uses_polling: + native.cc_binary(testonly=True, **args) + for poller in POLLERS: + native.sh_test( + name = name + '@poller=' + poller, + data = [name], + srcs = [ + '//test/core/util:run_with_poller_sh', + ], + args = [ + poller, + '$(location %s)' % name + ], + ) + else: + native.cc_test(**args) def grpc_cc_binary(name, srcs = [], deps = [], external_deps = [], args = [], data = [], language = "C++", testonly = False, linkshared = False, linkopts = []): copts = [] diff --git a/binding.gyp b/binding.gyp index 65a82fefb78..cb0a2fbab19 100644 --- a/binding.gyp +++ b/binding.gyp @@ -63,7 +63,6 @@ '-Wno-long-long', '-Wno-unused-parameter', '-DOSATOMIC_USE_INLINED=1', - '-Ithird_party/abseil-cpp', ], 'ldflags': [ '-g', @@ -102,7 +101,6 @@ '-fprofile-arcs', '-ftest-coverage', '-rdynamic', - '-lstdc++', ], }], ['grpc_alpine=="true"', { @@ -185,7 +183,6 @@ '-Wno-long-long', '-Wno-unused-parameter', '-DOSATOMIC_USE_INLINED=1', - '-Ithird_party/abseil-cpp', ], 'OTHER_CPLUSPLUSFLAGS': [ '-g', @@ -195,7 +192,6 @@ '-Wno-long-long', '-Wno-unused-parameter', '-DOSATOMIC_USE_INLINED=1', - '-Ithird_party/abseil-cpp', '-stdlib=libc++', '-std=c++11', '-Wno-error=deprecated-declarations' @@ -597,51 +593,53 @@ 'dependencies': [ ], 'sources': [ - 'src/core/lib/profiling/basic_timers.cc', - 'src/core/lib/profiling/stap_timers.cc', - 'src/core/lib/support/alloc.cc', - 'src/core/lib/support/arena.cc', - 'src/core/lib/support/atm.cc', - 'src/core/lib/support/avl.cc', - 'src/core/lib/support/cmdline.cc', - 'src/core/lib/support/cpu_iphone.cc', - 'src/core/lib/support/cpu_linux.cc', - 'src/core/lib/support/cpu_posix.cc', - 'src/core/lib/support/cpu_windows.cc', - 'src/core/lib/support/env_linux.cc', - 'src/core/lib/support/env_posix.cc', - 'src/core/lib/support/env_windows.cc', - 'src/core/lib/support/histogram.cc', - 'src/core/lib/support/host_port.cc', - 'src/core/lib/support/log.cc', - 'src/core/lib/support/log_android.cc', - 'src/core/lib/support/log_linux.cc', - 'src/core/lib/support/log_posix.cc', - 'src/core/lib/support/log_windows.cc', - 'src/core/lib/support/mpscq.cc', - 'src/core/lib/support/murmur_hash.cc', - 'src/core/lib/support/stack_lockfree.cc', - 'src/core/lib/support/string.cc', - 'src/core/lib/support/string_posix.cc', - 'src/core/lib/support/string_util_windows.cc', - 'src/core/lib/support/string_windows.cc', - 'src/core/lib/support/subprocess_posix.cc', - 'src/core/lib/support/subprocess_windows.cc', - 'src/core/lib/support/sync.cc', - 'src/core/lib/support/sync_posix.cc', - 'src/core/lib/support/sync_windows.cc', - 'src/core/lib/support/thd.cc', - 'src/core/lib/support/thd_posix.cc', - 'src/core/lib/support/thd_windows.cc', - 'src/core/lib/support/time.cc', - 'src/core/lib/support/time_posix.cc', - 'src/core/lib/support/time_precise.cc', - 'src/core/lib/support/time_windows.cc', - 'src/core/lib/support/tls_pthread.cc', - 'src/core/lib/support/tmpfile_msys.cc', - 'src/core/lib/support/tmpfile_posix.cc', - 'src/core/lib/support/tmpfile_windows.cc', - 'src/core/lib/support/wrap_memcpy.cc', + 'src/core/lib/profiling/basic_timers.c', + 'src/core/lib/profiling/stap_timers.c', + 'src/core/lib/support/alloc.c', + 'src/core/lib/support/arena.c', + 'src/core/lib/support/atm.c', + 'src/core/lib/support/avl.c', + 'src/core/lib/support/backoff.c', + 'src/core/lib/support/cmdline.c', + 'src/core/lib/support/cpu_iphone.c', + 'src/core/lib/support/cpu_linux.c', + 'src/core/lib/support/cpu_posix.c', + 'src/core/lib/support/cpu_windows.c', + 'src/core/lib/support/env_linux.c', + 'src/core/lib/support/env_posix.c', + 'src/core/lib/support/env_windows.c', + 'src/core/lib/support/fork.c', + 'src/core/lib/support/histogram.c', + 'src/core/lib/support/host_port.c', + 'src/core/lib/support/log.c', + 'src/core/lib/support/log_android.c', + 'src/core/lib/support/log_linux.c', + 'src/core/lib/support/log_posix.c', + 'src/core/lib/support/log_windows.c', + 'src/core/lib/support/mpscq.c', + 'src/core/lib/support/murmur_hash.c', + 'src/core/lib/support/stack_lockfree.c', + 'src/core/lib/support/string.c', + 'src/core/lib/support/string_posix.c', + 'src/core/lib/support/string_util_windows.c', + 'src/core/lib/support/string_windows.c', + 'src/core/lib/support/subprocess_posix.c', + 'src/core/lib/support/subprocess_windows.c', + 'src/core/lib/support/sync.c', + 'src/core/lib/support/sync_posix.c', + 'src/core/lib/support/sync_windows.c', + 'src/core/lib/support/thd.c', + 'src/core/lib/support/thd_posix.c', + 'src/core/lib/support/thd_windows.c', + 'src/core/lib/support/time.c', + 'src/core/lib/support/time_posix.c', + 'src/core/lib/support/time_precise.c', + 'src/core/lib/support/time_windows.c', + 'src/core/lib/support/tls_pthread.c', + 'src/core/lib/support/tmpfile_msys.c', + 'src/core/lib/support/tmpfile_posix.c', + 'src/core/lib/support/tmpfile_windows.c', + 'src/core/lib/support/wrap_memcpy.c', ], 'conditions': [ ['OS == "mac"', { @@ -659,256 +657,269 @@ 'gpr', ], 'sources': [ - 'src/core/lib/surface/init.cc', - 'src/core/lib/backoff/backoff.cc', - 'src/core/lib/channel/channel_args.cc', - 'src/core/lib/channel/channel_stack.cc', - 'src/core/lib/channel/channel_stack_builder.cc', - 'src/core/lib/channel/connected_channel.cc', - 'src/core/lib/channel/handshaker.cc', - 'src/core/lib/channel/handshaker_factory.cc', - 'src/core/lib/channel/handshaker_registry.cc', - 'src/core/lib/compression/compression.cc', - 'src/core/lib/compression/message_compress.cc', - 'src/core/lib/compression/stream_compression.cc', - 'src/core/lib/compression/stream_compression_gzip.cc', - 'src/core/lib/compression/stream_compression_identity.cc', - 'src/core/lib/debug/stats.cc', - 'src/core/lib/debug/stats_data.cc', - 'src/core/lib/http/format_request.cc', - 'src/core/lib/http/httpcli.cc', - 'src/core/lib/http/parser.cc', - 'src/core/lib/iomgr/call_combiner.cc', - 'src/core/lib/iomgr/closure.cc', - 'src/core/lib/iomgr/combiner.cc', - 'src/core/lib/iomgr/endpoint.cc', - 'src/core/lib/iomgr/endpoint_pair_posix.cc', - 'src/core/lib/iomgr/endpoint_pair_uv.cc', - 'src/core/lib/iomgr/endpoint_pair_windows.cc', - 'src/core/lib/iomgr/error.cc', - 'src/core/lib/iomgr/ev_epoll1_linux.cc', - 'src/core/lib/iomgr/ev_epollex_linux.cc', - 'src/core/lib/iomgr/ev_epollsig_linux.cc', - 'src/core/lib/iomgr/ev_poll_posix.cc', - 'src/core/lib/iomgr/ev_posix.cc', - 'src/core/lib/iomgr/ev_windows.cc', - 'src/core/lib/iomgr/exec_ctx.cc', - 'src/core/lib/iomgr/executor.cc', - 'src/core/lib/iomgr/gethostname_fallback.cc', - 'src/core/lib/iomgr/gethostname_host_name_max.cc', - 'src/core/lib/iomgr/gethostname_sysconf.cc', - 'src/core/lib/iomgr/iocp_windows.cc', - 'src/core/lib/iomgr/iomgr.cc', - 'src/core/lib/iomgr/iomgr_posix.cc', - 'src/core/lib/iomgr/iomgr_uv.cc', - 'src/core/lib/iomgr/iomgr_windows.cc', - 'src/core/lib/iomgr/is_epollexclusive_available.cc', - 'src/core/lib/iomgr/load_file.cc', - 'src/core/lib/iomgr/lockfree_event.cc', - 'src/core/lib/iomgr/network_status_tracker.cc', - 'src/core/lib/iomgr/polling_entity.cc', - 'src/core/lib/iomgr/pollset_set_uv.cc', - 'src/core/lib/iomgr/pollset_set_windows.cc', - 'src/core/lib/iomgr/pollset_uv.cc', - 'src/core/lib/iomgr/pollset_windows.cc', - 'src/core/lib/iomgr/resolve_address_posix.cc', - 'src/core/lib/iomgr/resolve_address_uv.cc', - 'src/core/lib/iomgr/resolve_address_windows.cc', - 'src/core/lib/iomgr/resource_quota.cc', - 'src/core/lib/iomgr/sockaddr_utils.cc', - 'src/core/lib/iomgr/socket_factory_posix.cc', - 'src/core/lib/iomgr/socket_mutator.cc', - 'src/core/lib/iomgr/socket_utils_common_posix.cc', - 'src/core/lib/iomgr/socket_utils_linux.cc', - 'src/core/lib/iomgr/socket_utils_posix.cc', - 'src/core/lib/iomgr/socket_utils_uv.cc', - 'src/core/lib/iomgr/socket_utils_windows.cc', - 'src/core/lib/iomgr/socket_windows.cc', - 'src/core/lib/iomgr/tcp_client_posix.cc', - 'src/core/lib/iomgr/tcp_client_uv.cc', - 'src/core/lib/iomgr/tcp_client_windows.cc', - 'src/core/lib/iomgr/tcp_posix.cc', - 'src/core/lib/iomgr/tcp_server_posix.cc', - 'src/core/lib/iomgr/tcp_server_utils_posix_common.cc', - 'src/core/lib/iomgr/tcp_server_utils_posix_ifaddrs.cc', - 'src/core/lib/iomgr/tcp_server_utils_posix_noifaddrs.cc', - 'src/core/lib/iomgr/tcp_server_uv.cc', - 'src/core/lib/iomgr/tcp_server_windows.cc', - 'src/core/lib/iomgr/tcp_uv.cc', - 'src/core/lib/iomgr/tcp_windows.cc', - 'src/core/lib/iomgr/time_averaged_stats.cc', - 'src/core/lib/iomgr/timer_generic.cc', - 'src/core/lib/iomgr/timer_heap.cc', - 'src/core/lib/iomgr/timer_manager.cc', - 'src/core/lib/iomgr/timer_uv.cc', - 'src/core/lib/iomgr/udp_server.cc', - 'src/core/lib/iomgr/unix_sockets_posix.cc', - 'src/core/lib/iomgr/unix_sockets_posix_noop.cc', - 'src/core/lib/iomgr/wakeup_fd_cv.cc', - 'src/core/lib/iomgr/wakeup_fd_eventfd.cc', - 'src/core/lib/iomgr/wakeup_fd_nospecial.cc', - 'src/core/lib/iomgr/wakeup_fd_pipe.cc', - 'src/core/lib/iomgr/wakeup_fd_posix.cc', - 'src/core/lib/json/json.cc', - 'src/core/lib/json/json_reader.cc', - 'src/core/lib/json/json_string.cc', - 'src/core/lib/json/json_writer.cc', - 'src/core/lib/slice/b64.cc', - 'src/core/lib/slice/percent_encoding.cc', - 'src/core/lib/slice/slice.cc', - 'src/core/lib/slice/slice_buffer.cc', - 'src/core/lib/slice/slice_hash_table.cc', - 'src/core/lib/slice/slice_intern.cc', - 'src/core/lib/slice/slice_string_helpers.cc', - 'src/core/lib/surface/alarm.cc', - 'src/core/lib/surface/api_trace.cc', - 'src/core/lib/surface/byte_buffer.cc', - 'src/core/lib/surface/byte_buffer_reader.cc', - 'src/core/lib/surface/call.cc', - 'src/core/lib/surface/call_details.cc', - 'src/core/lib/surface/call_log_batch.cc', - 'src/core/lib/surface/channel.cc', - 'src/core/lib/surface/channel_init.cc', - 'src/core/lib/surface/channel_ping.cc', - 'src/core/lib/surface/channel_stack_type.cc', - 'src/core/lib/surface/completion_queue.cc', - 'src/core/lib/surface/completion_queue_factory.cc', - 'src/core/lib/surface/event_string.cc', + 'src/core/lib/surface/init.c', + 'src/core/lib/channel/channel_args.c', + 'src/core/lib/channel/channel_stack.c', + 'src/core/lib/channel/channel_stack_builder.c', + 'src/core/lib/channel/connected_channel.c', + 'src/core/lib/channel/handshaker.c', + 'src/core/lib/channel/handshaker_factory.c', + 'src/core/lib/channel/handshaker_registry.c', + 'src/core/lib/compression/compression.c', + 'src/core/lib/compression/message_compress.c', + 'src/core/lib/compression/stream_compression.c', + 'src/core/lib/compression/stream_compression_gzip.c', + 'src/core/lib/compression/stream_compression_identity.c', + 'src/core/lib/debug/stats.c', + 'src/core/lib/debug/stats_data.c', + 'src/core/lib/http/format_request.c', + 'src/core/lib/http/httpcli.c', + 'src/core/lib/http/parser.c', + 'src/core/lib/iomgr/call_combiner.c', + 'src/core/lib/iomgr/closure.c', + 'src/core/lib/iomgr/combiner.c', + 'src/core/lib/iomgr/endpoint.c', + 'src/core/lib/iomgr/endpoint_pair_posix.c', + 'src/core/lib/iomgr/endpoint_pair_uv.c', + 'src/core/lib/iomgr/endpoint_pair_windows.c', + 'src/core/lib/iomgr/error.c', + 'src/core/lib/iomgr/ev_epoll1_linux.c', + 'src/core/lib/iomgr/ev_epollex_linux.c', + 'src/core/lib/iomgr/ev_epollsig_linux.c', + 'src/core/lib/iomgr/ev_poll_posix.c', + 'src/core/lib/iomgr/ev_posix.c', + 'src/core/lib/iomgr/ev_windows.c', + 'src/core/lib/iomgr/exec_ctx.c', + 'src/core/lib/iomgr/executor.c', + 'src/core/lib/iomgr/fork_posix.c', + 'src/core/lib/iomgr/fork_windows.c', + 'src/core/lib/iomgr/gethostname_fallback.c', + 'src/core/lib/iomgr/gethostname_host_name_max.c', + 'src/core/lib/iomgr/gethostname_sysconf.c', + 'src/core/lib/iomgr/iocp_windows.c', + 'src/core/lib/iomgr/iomgr.c', + 'src/core/lib/iomgr/iomgr_posix.c', + 'src/core/lib/iomgr/iomgr_uv.c', + 'src/core/lib/iomgr/iomgr_windows.c', + 'src/core/lib/iomgr/is_epollexclusive_available.c', + 'src/core/lib/iomgr/load_file.c', + 'src/core/lib/iomgr/lockfree_event.c', + 'src/core/lib/iomgr/network_status_tracker.c', + 'src/core/lib/iomgr/polling_entity.c', + 'src/core/lib/iomgr/pollset_set_uv.c', + 'src/core/lib/iomgr/pollset_set_windows.c', + 'src/core/lib/iomgr/pollset_uv.c', + 'src/core/lib/iomgr/pollset_windows.c', + 'src/core/lib/iomgr/resolve_address_posix.c', + 'src/core/lib/iomgr/resolve_address_uv.c', + 'src/core/lib/iomgr/resolve_address_windows.c', + 'src/core/lib/iomgr/resource_quota.c', + 'src/core/lib/iomgr/sockaddr_utils.c', + 'src/core/lib/iomgr/socket_factory_posix.c', + 'src/core/lib/iomgr/socket_mutator.c', + 'src/core/lib/iomgr/socket_utils_common_posix.c', + 'src/core/lib/iomgr/socket_utils_linux.c', + 'src/core/lib/iomgr/socket_utils_posix.c', + 'src/core/lib/iomgr/socket_utils_uv.c', + 'src/core/lib/iomgr/socket_utils_windows.c', + 'src/core/lib/iomgr/socket_windows.c', + 'src/core/lib/iomgr/tcp_client_posix.c', + 'src/core/lib/iomgr/tcp_client_uv.c', + 'src/core/lib/iomgr/tcp_client_windows.c', + 'src/core/lib/iomgr/tcp_posix.c', + 'src/core/lib/iomgr/tcp_server_posix.c', + 'src/core/lib/iomgr/tcp_server_utils_posix_common.c', + 'src/core/lib/iomgr/tcp_server_utils_posix_ifaddrs.c', + 'src/core/lib/iomgr/tcp_server_utils_posix_noifaddrs.c', + 'src/core/lib/iomgr/tcp_server_uv.c', + 'src/core/lib/iomgr/tcp_server_windows.c', + 'src/core/lib/iomgr/tcp_uv.c', + 'src/core/lib/iomgr/tcp_windows.c', + 'src/core/lib/iomgr/time_averaged_stats.c', + 'src/core/lib/iomgr/timer_generic.c', + 'src/core/lib/iomgr/timer_heap.c', + 'src/core/lib/iomgr/timer_manager.c', + 'src/core/lib/iomgr/timer_uv.c', + 'src/core/lib/iomgr/udp_server.c', + 'src/core/lib/iomgr/unix_sockets_posix.c', + 'src/core/lib/iomgr/unix_sockets_posix_noop.c', + 'src/core/lib/iomgr/wakeup_fd_cv.c', + 'src/core/lib/iomgr/wakeup_fd_eventfd.c', + 'src/core/lib/iomgr/wakeup_fd_nospecial.c', + 'src/core/lib/iomgr/wakeup_fd_pipe.c', + 'src/core/lib/iomgr/wakeup_fd_posix.c', + 'src/core/lib/json/json.c', + 'src/core/lib/json/json_reader.c', + 'src/core/lib/json/json_string.c', + 'src/core/lib/json/json_writer.c', + 'src/core/lib/slice/b64.c', + 'src/core/lib/slice/percent_encoding.c', + 'src/core/lib/slice/slice.c', + 'src/core/lib/slice/slice_buffer.c', + 'src/core/lib/slice/slice_hash_table.c', + 'src/core/lib/slice/slice_intern.c', + 'src/core/lib/slice/slice_string_helpers.c', + 'src/core/lib/surface/alarm.c', + 'src/core/lib/surface/api_trace.c', + 'src/core/lib/surface/byte_buffer.c', + 'src/core/lib/surface/byte_buffer_reader.c', + 'src/core/lib/surface/call.c', + 'src/core/lib/surface/call_details.c', + 'src/core/lib/surface/call_log_batch.c', + 'src/core/lib/surface/channel.c', + 'src/core/lib/surface/channel_init.c', + 'src/core/lib/surface/channel_ping.c', + 'src/core/lib/surface/channel_stack_type.c', + 'src/core/lib/surface/completion_queue.c', + 'src/core/lib/surface/completion_queue_factory.c', + 'src/core/lib/surface/event_string.c', 'src/core/lib/surface/lame_client.cc', - 'src/core/lib/surface/metadata_array.cc', - 'src/core/lib/surface/server.cc', - 'src/core/lib/surface/validate_metadata.cc', - 'src/core/lib/surface/version.cc', - 'src/core/lib/transport/bdp_estimator.cc', - 'src/core/lib/transport/byte_stream.cc', - 'src/core/lib/transport/connectivity_state.cc', - 'src/core/lib/transport/error_utils.cc', - 'src/core/lib/transport/metadata.cc', - 'src/core/lib/transport/metadata_batch.cc', - 'src/core/lib/transport/pid_controller.cc', - 'src/core/lib/transport/service_config.cc', - 'src/core/lib/transport/static_metadata.cc', - 'src/core/lib/transport/status_conversion.cc', - 'src/core/lib/transport/timeout_encoding.cc', - 'src/core/lib/transport/transport.cc', - 'src/core/lib/transport/transport_op_string.cc', - 'src/core/lib/debug/trace.cc', - 'src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc', - 'src/core/ext/transport/chttp2/transport/bin_decoder.cc', - 'src/core/ext/transport/chttp2/transport/bin_encoder.cc', - 'src/core/ext/transport/chttp2/transport/chttp2_plugin.cc', - 'src/core/ext/transport/chttp2/transport/chttp2_transport.cc', - 'src/core/ext/transport/chttp2/transport/flow_control.cc', - 'src/core/ext/transport/chttp2/transport/frame_data.cc', - 'src/core/ext/transport/chttp2/transport/frame_goaway.cc', - 'src/core/ext/transport/chttp2/transport/frame_ping.cc', - 'src/core/ext/transport/chttp2/transport/frame_rst_stream.cc', - 'src/core/ext/transport/chttp2/transport/frame_settings.cc', - 'src/core/ext/transport/chttp2/transport/frame_window_update.cc', - 'src/core/ext/transport/chttp2/transport/hpack_encoder.cc', - 'src/core/ext/transport/chttp2/transport/hpack_parser.cc', - 'src/core/ext/transport/chttp2/transport/hpack_table.cc', - 'src/core/ext/transport/chttp2/transport/http2_settings.cc', - 'src/core/ext/transport/chttp2/transport/huffsyms.cc', - 'src/core/ext/transport/chttp2/transport/incoming_metadata.cc', - 'src/core/ext/transport/chttp2/transport/parsing.cc', - 'src/core/ext/transport/chttp2/transport/stream_lists.cc', - 'src/core/ext/transport/chttp2/transport/stream_map.cc', - 'src/core/ext/transport/chttp2/transport/varint.cc', - 'src/core/ext/transport/chttp2/transport/writing.cc', - 'src/core/ext/transport/chttp2/alpn/alpn.cc', - 'src/core/ext/filters/http/client/http_client_filter.cc', - 'src/core/ext/filters/http/http_filters_plugin.cc', - 'src/core/ext/filters/http/message_compress/message_compress_filter.cc', - 'src/core/ext/filters/http/server/http_server_filter.cc', - 'src/core/lib/http/httpcli_security_connector.cc', - 'src/core/lib/security/context/security_context.cc', - 'src/core/lib/security/credentials/composite/composite_credentials.cc', - 'src/core/lib/security/credentials/credentials.cc', - 'src/core/lib/security/credentials/credentials_metadata.cc', - 'src/core/lib/security/credentials/fake/fake_credentials.cc', - 'src/core/lib/security/credentials/google_default/credentials_generic.cc', - 'src/core/lib/security/credentials/google_default/google_default_credentials.cc', - 'src/core/lib/security/credentials/iam/iam_credentials.cc', - 'src/core/lib/security/credentials/jwt/json_token.cc', - 'src/core/lib/security/credentials/jwt/jwt_credentials.cc', - 'src/core/lib/security/credentials/jwt/jwt_verifier.cc', - 'src/core/lib/security/credentials/oauth2/oauth2_credentials.cc', - 'src/core/lib/security/credentials/plugin/plugin_credentials.cc', - 'src/core/lib/security/credentials/ssl/ssl_credentials.cc', - 'src/core/lib/security/transport/client_auth_filter.cc', - 'src/core/lib/security/transport/lb_targets_info.cc', - 'src/core/lib/security/transport/secure_endpoint.cc', - 'src/core/lib/security/transport/security_connector.cc', - 'src/core/lib/security/transport/security_handshaker.cc', - 'src/core/lib/security/transport/server_auth_filter.cc', - 'src/core/lib/security/transport/tsi_error.cc', - 'src/core/lib/security/util/json_util.cc', - 'src/core/lib/surface/init_secure.cc', - 'src/core/tsi/fake_transport_security.cc', - 'src/core/tsi/gts_transport_security.cc', - 'src/core/tsi/ssl_transport_security.cc', - 'src/core/tsi/transport_security_grpc.cc', - 'src/core/tsi/transport_security.cc', - 'src/core/tsi/transport_security_adapter.cc', - 'src/core/ext/transport/chttp2/server/chttp2_server.cc', - 'src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc', - 'src/core/ext/filters/client_channel/backup_poller.cc', - 'src/core/ext/filters/client_channel/channel_connectivity.cc', - 'src/core/ext/filters/client_channel/client_channel.cc', - 'src/core/ext/filters/client_channel/client_channel_factory.cc', - 'src/core/ext/filters/client_channel/client_channel_plugin.cc', - 'src/core/ext/filters/client_channel/connector.cc', - 'src/core/ext/filters/client_channel/http_connect_handshaker.cc', - 'src/core/ext/filters/client_channel/http_proxy.cc', - 'src/core/ext/filters/client_channel/lb_policy.cc', - 'src/core/ext/filters/client_channel/lb_policy_factory.cc', - 'src/core/ext/filters/client_channel/lb_policy_registry.cc', - 'src/core/ext/filters/client_channel/parse_address.cc', - 'src/core/ext/filters/client_channel/proxy_mapper.cc', - 'src/core/ext/filters/client_channel/proxy_mapper_registry.cc', - 'src/core/ext/filters/client_channel/resolver.cc', - 'src/core/ext/filters/client_channel/resolver_factory.cc', - 'src/core/ext/filters/client_channel/resolver_registry.cc', - 'src/core/ext/filters/client_channel/retry_throttle.cc', - 'src/core/ext/filters/client_channel/subchannel.cc', - 'src/core/ext/filters/client_channel/subchannel_index.cc', - 'src/core/ext/filters/client_channel/uri_parser.cc', - 'src/core/ext/filters/deadline/deadline_filter.cc', - 'src/core/ext/transport/chttp2/client/chttp2_connector.cc', - 'src/core/ext/transport/chttp2/server/insecure/server_chttp2.cc', - 'src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc', - 'src/core/ext/transport/chttp2/client/insecure/channel_create.cc', - 'src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc', - 'src/core/ext/transport/inproc/inproc_plugin.cc', - 'src/core/ext/transport/inproc/inproc_transport.cc', - 'src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc', - 'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc', - 'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc', - 'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc', - 'src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc', + 'src/core/lib/surface/metadata_array.c', + 'src/core/lib/surface/server.c', + 'src/core/lib/surface/validate_metadata.c', + 'src/core/lib/surface/version.c', + 'src/core/lib/transport/bdp_estimator.c', + 'src/core/lib/transport/byte_stream.c', + 'src/core/lib/transport/connectivity_state.c', + 'src/core/lib/transport/error_utils.c', + 'src/core/lib/transport/metadata.c', + 'src/core/lib/transport/metadata_batch.c', + 'src/core/lib/transport/pid_controller.c', + 'src/core/lib/transport/service_config.c', + 'src/core/lib/transport/static_metadata.c', + 'src/core/lib/transport/status_conversion.c', + 'src/core/lib/transport/timeout_encoding.c', + 'src/core/lib/transport/transport.c', + 'src/core/lib/transport/transport_op_string.c', + 'src/core/lib/debug/trace.c', + 'src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.c', + 'src/core/ext/transport/chttp2/transport/bin_decoder.c', + 'src/core/ext/transport/chttp2/transport/bin_encoder.c', + 'src/core/ext/transport/chttp2/transport/chttp2_plugin.c', + 'src/core/ext/transport/chttp2/transport/chttp2_transport.c', + 'src/core/ext/transport/chttp2/transport/flow_control.c', + 'src/core/ext/transport/chttp2/transport/frame_data.c', + 'src/core/ext/transport/chttp2/transport/frame_goaway.c', + 'src/core/ext/transport/chttp2/transport/frame_ping.c', + 'src/core/ext/transport/chttp2/transport/frame_rst_stream.c', + 'src/core/ext/transport/chttp2/transport/frame_settings.c', + 'src/core/ext/transport/chttp2/transport/frame_window_update.c', + 'src/core/ext/transport/chttp2/transport/hpack_encoder.c', + 'src/core/ext/transport/chttp2/transport/hpack_parser.c', + 'src/core/ext/transport/chttp2/transport/hpack_table.c', + 'src/core/ext/transport/chttp2/transport/http2_settings.c', + 'src/core/ext/transport/chttp2/transport/huffsyms.c', + 'src/core/ext/transport/chttp2/transport/incoming_metadata.c', + 'src/core/ext/transport/chttp2/transport/parsing.c', + 'src/core/ext/transport/chttp2/transport/stream_lists.c', + 'src/core/ext/transport/chttp2/transport/stream_map.c', + 'src/core/ext/transport/chttp2/transport/varint.c', + 'src/core/ext/transport/chttp2/transport/writing.c', + 'src/core/ext/transport/chttp2/alpn/alpn.c', + 'src/core/ext/filters/http/client/http_client_filter.c', + 'src/core/ext/filters/http/http_filters_plugin.c', + 'src/core/ext/filters/http/message_compress/message_compress_filter.c', + 'src/core/ext/filters/http/server/http_server_filter.c', + 'src/core/lib/http/httpcli_security_connector.c', + 'src/core/lib/security/context/security_context.c', + 'src/core/lib/security/credentials/composite/composite_credentials.c', + 'src/core/lib/security/credentials/credentials.c', + 'src/core/lib/security/credentials/credentials_metadata.c', + 'src/core/lib/security/credentials/fake/fake_credentials.c', + 'src/core/lib/security/credentials/google_default/credentials_generic.c', + 'src/core/lib/security/credentials/google_default/google_default_credentials.c', + 'src/core/lib/security/credentials/iam/iam_credentials.c', + 'src/core/lib/security/credentials/jwt/json_token.c', + 'src/core/lib/security/credentials/jwt/jwt_credentials.c', + 'src/core/lib/security/credentials/jwt/jwt_verifier.c', + 'src/core/lib/security/credentials/oauth2/oauth2_credentials.c', + 'src/core/lib/security/credentials/plugin/plugin_credentials.c', + 'src/core/lib/security/credentials/ssl/ssl_credentials.c', + 'src/core/lib/security/transport/client_auth_filter.c', + 'src/core/lib/security/transport/lb_targets_info.c', + 'src/core/lib/security/transport/secure_endpoint.c', + 'src/core/lib/security/transport/security_connector.c', + 'src/core/lib/security/transport/security_handshaker.c', + 'src/core/lib/security/transport/server_auth_filter.c', + 'src/core/lib/security/transport/tsi_error.c', + 'src/core/lib/security/util/json_util.c', + 'src/core/lib/surface/init_secure.c', + 'src/core/tsi/fake_transport_security.c', + 'src/core/tsi/gts_transport_security.c', + 'src/core/tsi/ssl_transport_security.c', + 'src/core/tsi/transport_security_grpc.c', + 'src/core/tsi/transport_security.c', + 'src/core/tsi/transport_security_adapter.c', + 'src/core/ext/transport/chttp2/server/chttp2_server.c', + 'src/core/ext/transport/chttp2/client/secure/secure_channel_create.c', + 'src/core/ext/filters/client_channel/channel_connectivity.c', + 'src/core/ext/filters/client_channel/client_channel.c', + 'src/core/ext/filters/client_channel/client_channel_factory.c', + 'src/core/ext/filters/client_channel/client_channel_plugin.c', + 'src/core/ext/filters/client_channel/connector.c', + 'src/core/ext/filters/client_channel/http_connect_handshaker.c', + 'src/core/ext/filters/client_channel/http_proxy.c', + 'src/core/ext/filters/client_channel/lb_policy.c', + 'src/core/ext/filters/client_channel/lb_policy_factory.c', + 'src/core/ext/filters/client_channel/lb_policy_registry.c', + 'src/core/ext/filters/client_channel/parse_address.c', + 'src/core/ext/filters/client_channel/proxy_mapper.c', + 'src/core/ext/filters/client_channel/proxy_mapper_registry.c', + 'src/core/ext/filters/client_channel/resolver.c', + 'src/core/ext/filters/client_channel/resolver_factory.c', + 'src/core/ext/filters/client_channel/resolver_registry.c', + 'src/core/ext/filters/client_channel/retry_throttle.c', + 'src/core/ext/filters/client_channel/subchannel.c', + 'src/core/ext/filters/client_channel/subchannel_index.c', + 'src/core/ext/filters/client_channel/uri_parser.c', + 'src/core/ext/filters/deadline/deadline_filter.c', + 'src/core/ext/transport/chttp2/client/chttp2_connector.c', + 'src/core/ext/transport/chttp2/server/insecure/server_chttp2.c', + 'src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.c', + 'src/core/ext/transport/chttp2/client/insecure/channel_create.c', + 'src/core/ext/transport/chttp2/client/insecure/channel_create_posix.c', + 'src/core/ext/transport/inproc/inproc_plugin.c', + 'src/core/ext/transport/inproc/inproc_transport.c', + 'src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.c', + 'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.c', + 'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.c', + 'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.c', + 'src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.c', 'src/core/ext/filters/client_channel/lb_policy/grpclb/proto/grpc/lb/v1/load_balancer.pb.c', 'third_party/nanopb/pb_common.c', 'third_party/nanopb/pb_decode.c', 'third_party/nanopb/pb_encode.c', - 'src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc', - 'src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc', - 'src/core/ext/filters/client_channel/lb_policy/subchannel_list.cc', - '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_posix.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/native/dns_resolver.cc', - 'src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc', - 'src/core/ext/filters/load_reporting/server_load_reporting_filter.cc', - 'src/core/ext/filters/load_reporting/server_load_reporting_plugin.cc', - 'src/core/ext/census/grpc_context.cc', - 'src/core/ext/filters/max_age/max_age_filter.cc', - 'src/core/ext/filters/message_size/message_size_filter.cc', - 'src/core/ext/filters/workarounds/workaround_cronet_compression_filter.cc', - 'src/core/ext/filters/workarounds/workaround_utils.cc', - 'src/core/plugin_registry/grpc_plugin_registry.cc', + 'src/core/ext/filters/client_channel/resolver/fake/fake_resolver.c', + 'src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.c', + 'src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.c', + 'src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.c', + 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.c', + 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.c', + 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.c', + 'src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.c', + 'src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.c', + 'src/core/ext/filters/load_reporting/server_load_reporting_filter.c', + 'src/core/ext/filters/load_reporting/server_load_reporting_plugin.c', + 'src/core/ext/census/base_resources.c', + 'src/core/ext/census/context.c', + 'src/core/ext/census/gen/census.pb.c', + 'src/core/ext/census/gen/trace_context.pb.c', + 'src/core/ext/census/grpc_context.c', + 'src/core/ext/census/grpc_filter.c', + 'src/core/ext/census/grpc_plugin.c', + 'src/core/ext/census/initialize.c', + 'src/core/ext/census/intrusive_hash_map.c', + 'src/core/ext/census/mlog.c', + 'src/core/ext/census/operation.c', + 'src/core/ext/census/placeholders.c', + 'src/core/ext/census/resource.c', + 'src/core/ext/census/trace_context.c', + 'src/core/ext/census/tracing.c', + 'src/core/ext/filters/max_age/max_age_filter.c', + 'src/core/ext/filters/message_size/message_size_filter.c', + 'src/core/ext/filters/workarounds/workaround_cronet_compression_filter.c', + 'src/core/ext/filters/workarounds/workaround_utils.c', + 'src/core/plugin_registry/grpc_plugin_registry.c', ], 'conditions': [ ['OS == "mac"', { diff --git a/build.yaml b/build.yaml index 47f26102022..6158b466ea7 100644 --- a/build.yaml +++ b/build.yaml @@ -13,8 +13,8 @@ settings: '#09': Per-language overrides are possible with (eg) ruby_version tag here '#10': See the expand_version.py for all the quirks here core_version: 5.0.0-dev - g_stands_for: generous - version: 1.8.0-dev + g_stands_for: glossy + version: 1.9.0-dev filegroups: - name: census public_headers: @@ -40,7 +40,7 @@ filegroups: - src/core/lib/support/env_linux.cc - src/core/lib/support/env_posix.cc - src/core/lib/support/env_windows.cc - - src/core/lib/support/histogram.cc + - src/core/lib/support/fork.cc - src/core/lib/support/host_port.cc - src/core/lib/support/log.cc - src/core/lib/support/log_android.cc @@ -49,7 +49,6 @@ filegroups: - src/core/lib/support/log_windows.cc - src/core/lib/support/mpscq.cc - src/core/lib/support/murmur_hash.cc - - src/core/lib/support/stack_lockfree.cc - src/core/lib/support/string.cc - src/core/lib/support/string_posix.cc - src/core/lib/support/string_util_windows.cc @@ -83,7 +82,6 @@ filegroups: - include/grpc/support/avl.h - include/grpc/support/cmdline.h - include/grpc/support/cpu.h - - include/grpc/support/histogram.h - include/grpc/support/host_port.h - include/grpc/support/log.h - include/grpc/support/log_windows.h @@ -104,19 +102,21 @@ filegroups: - include/grpc/support/useful.h headers: - src/core/lib/profiling/timers.h + - src/core/lib/support/abstract.h - src/core/lib/support/arena.h - src/core/lib/support/atomic.h - src/core/lib/support/atomic_with_atm.h - src/core/lib/support/atomic_with_std.h - src/core/lib/support/env.h + - src/core/lib/support/fork.h - src/core/lib/support/manual_constructor.h - src/core/lib/support/memory.h - src/core/lib/support/mpscq.h - src/core/lib/support/murmur_hash.h - src/core/lib/support/spinlock.h - - src/core/lib/support/stack_lockfree.h - src/core/lib/support/string.h - src/core/lib/support/string_windows.h + - src/core/lib/support/thd_internal.h - src/core/lib/support/time_precise.h - src/core/lib/support/tmpfile.h uses: @@ -127,6 +127,7 @@ filegroups: - include/grpc/impl/codegen/atm_gcc_atomic.h - include/grpc/impl/codegen/atm_gcc_sync.h - include/grpc/impl/codegen/atm_windows.h + - include/grpc/impl/codegen/fork.h - include/grpc/impl/codegen/gpr_slice.h - include/grpc/impl/codegen/gpr_types.h - include/grpc/impl/codegen/port_platform.h @@ -168,7 +169,6 @@ filegroups: - src/core/lib/http/httpcli.cc - src/core/lib/http/parser.cc - src/core/lib/iomgr/call_combiner.cc - - src/core/lib/iomgr/closure.cc - src/core/lib/iomgr/combiner.cc - src/core/lib/iomgr/endpoint.cc - src/core/lib/iomgr/endpoint_pair_posix.cc @@ -183,6 +183,8 @@ filegroups: - src/core/lib/iomgr/ev_windows.cc - src/core/lib/iomgr/exec_ctx.cc - src/core/lib/iomgr/executor.cc + - src/core/lib/iomgr/fork_posix.cc + - src/core/lib/iomgr/fork_windows.cc - src/core/lib/iomgr/gethostname_fallback.cc - src/core/lib/iomgr/gethostname_host_name_max.cc - src/core/lib/iomgr/gethostname_sysconf.cc @@ -293,6 +295,7 @@ filegroups: - include/grpc/byte_buffer.h - include/grpc/byte_buffer_reader.h - include/grpc/compression.h + - include/grpc/fork.h - include/grpc/grpc.h - include/grpc/grpc_posix.h - include/grpc/grpc_security_constants.h @@ -393,7 +396,9 @@ filegroups: - src/core/lib/slice/slice_hash_table.h - src/core/lib/slice/slice_internal.h - src/core/lib/slice/slice_string_helpers.h - - src/core/lib/support/vector.h + - src/core/lib/support/debug_location.h + - src/core/lib/support/ref_counted.h + - src/core/lib/support/ref_counted_ptr.h - src/core/lib/surface/alarm_internal.h - src/core/lib/surface/api_trace.h - src/core/lib/surface/call.h @@ -707,6 +712,7 @@ filegroups: - test/core/iomgr/endpoint_tests.h - test/core/util/debugger_macros.h - test/core/util/grpc_profiler.h + - test/core/util/histogram.h - test/core/util/memory_counters.h - test/core/util/mock_endpoint.h - test/core/util/parse_hexstring.h @@ -714,23 +720,27 @@ filegroups: - test/core/util/port.h - test/core/util/port_server_client.h - test/core/util/slice_splitter.h + - test/core/util/tracer_util.h - test/core/util/trickle_endpoint.h src: - src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc - - test/core/end2end/cq_verifier.c - - test/core/end2end/fixtures/http_proxy_fixture.c - - test/core/end2end/fixtures/proxy.c - - test/core/iomgr/endpoint_tests.c + - test/core/end2end/cq_verifier.cc + - test/core/end2end/fixtures/http_proxy_fixture.cc + - test/core/end2end/fixtures/proxy.cc + - test/core/iomgr/endpoint_tests.cc - test/core/util/debugger_macros.cc - - test/core/util/grpc_profiler.c - - test/core/util/memory_counters.c - - test/core/util/mock_endpoint.c - - test/core/util/parse_hexstring.c - - test/core/util/passthru_endpoint.c - - test/core/util/port.c - - test/core/util/port_server_client.c - - test/core/util/slice_splitter.c - - test/core/util/trickle_endpoint.c + - test/core/util/grpc_profiler.cc + - test/core/util/histogram.cc + - test/core/util/memory_counters.cc + - test/core/util/mock_endpoint.cc + - test/core/util/parse_hexstring.cc + - test/core/util/passthru_endpoint.cc + - test/core/util/port.cc + - test/core/util/port_isolated_runtime_environment.cc + - test/core/util/port_server_client.cc + - test/core/util/slice_splitter.cc + - test/core/util/tracer_util.cc + - test/core/util/trickle_endpoint.cc deps: - gpr_test_util - gpr @@ -915,7 +925,7 @@ filegroups: headers: - test/core/tsi/transport_security_test_lib.h src: - - test/core/tsi/transport_security_test_lib.c + - test/core/tsi/transport_security_test_lib.cc deps: - grpc - name: tsi @@ -1125,7 +1135,7 @@ libs: headers: - test/core/util/test_config.h src: - - test/core/util/test_config.c + - test/core/util/test_config.cc deps: - gpr secure: false @@ -1211,11 +1221,11 @@ libs: - test/core/end2end/data/ssl_test_data.h - test/core/security/oauth2_utils.h src: - - test/core/end2end/data/client_certs.c - - test/core/end2end/data/server1_cert.c - - test/core/end2end/data/server1_key.c - - test/core/end2end/data/test_root_cert.c - - test/core/security/oauth2_utils.c + - test/core/end2end/data/client_certs.cc + - test/core/end2end/data/server1_cert.cc + - test/core/end2end/data/server1_key.cc + - test/core/end2end/data/test_root_cert.cc + - test/core/security/oauth2_utils.cc deps: - gpr_test_util - gpr @@ -1271,7 +1281,7 @@ libs: headers: - test/core/util/reconnect_server.h src: - - test/core/util/reconnect_server.c + - test/core/util/reconnect_server.cc deps: - test_tcp_server - grpc_test_util @@ -1284,7 +1294,7 @@ libs: headers: - test/core/util/test_tcp_server.h src: - - test/core/util/test_tcp_server.c + - test/core/util/test_tcp_server.cc deps: - grpc_test_util - grpc @@ -1700,7 +1710,7 @@ targets: build: test language: c src: - - test/core/surface/alarm_test.c + - test/core/surface/alarm_test.cc deps: - grpc_test_util - grpc @@ -1710,7 +1720,7 @@ targets: build: test language: c src: - - test/core/compression/algorithm_test.c + - test/core/compression/algorithm_test.cc deps: - grpc_test_util - grpc @@ -1721,7 +1731,7 @@ targets: build: test language: c src: - - test/core/support/alloc_test.c + - test/core/support/alloc_test.cc deps: - gpr_test_util - gpr @@ -1730,7 +1740,7 @@ targets: build: test language: c src: - - test/core/transport/chttp2/alpn_test.c + - test/core/transport/chttp2/alpn_test.cc deps: - grpc_test_util - grpc @@ -1740,7 +1750,7 @@ targets: build: fuzzer language: c src: - - test/core/end2end/fuzzers/api_fuzzer.c + - test/core/end2end/fuzzers/api_fuzzer.cc deps: - grpc_test_util - grpc @@ -1754,7 +1764,7 @@ targets: build: test language: c src: - - test/core/support/arena_test.c + - test/core/support/arena_test.cc deps: - gpr_test_util - gpr @@ -1763,7 +1773,7 @@ targets: build: test language: c src: - - test/core/backoff/backoff_test.c + - test/core/backoff/backoff_test.cc deps: - grpc_test_util - grpc @@ -1774,7 +1784,7 @@ targets: build: test language: c src: - - test/core/end2end/bad_server_response_test.c + - test/core/end2end/bad_server_response_test.cc deps: - test_tcp_server - grpc_test_util @@ -1787,7 +1797,7 @@ targets: build: test language: c src: - - test/core/transport/chttp2/bin_decoder_test.c + - test/core/transport/chttp2/bin_decoder_test.cc deps: - grpc_test_util - grpc @@ -1796,7 +1806,7 @@ targets: build: test language: c src: - - test/core/transport/chttp2/bin_encoder_test.c + - test/core/transport/chttp2/bin_encoder_test.cc deps: - grpc_test_util - grpc @@ -1805,7 +1815,7 @@ targets: build: test language: c src: - - test/core/transport/byte_stream_test.c + - test/core/transport/byte_stream_test.cc deps: - grpc_test_util - grpc @@ -1816,7 +1826,7 @@ targets: build: test language: c src: - - test/core/surface/channel_create_test.c + - test/core/surface/channel_create_test.cc deps: - grpc_test_util - grpc @@ -1834,7 +1844,7 @@ targets: build: test language: c src: - - test/core/transport/chttp2/hpack_encoder_test.c + - test/core/transport/chttp2/hpack_encoder_test.cc deps: - grpc_test_util - grpc @@ -1845,7 +1855,7 @@ targets: build: test language: c src: - - test/core/transport/chttp2/stream_map_test.c + - test/core/transport/chttp2/stream_map_test.cc deps: - grpc_test_util - grpc @@ -1856,7 +1866,7 @@ targets: build: test language: c src: - - test/core/transport/chttp2/varint_test.c + - test/core/transport/chttp2/varint_test.cc deps: - grpc_test_util - grpc @@ -1867,7 +1877,7 @@ targets: build: fuzzer language: c src: - - test/core/end2end/fuzzers/client_fuzzer.c + - test/core/end2end/fuzzers/client_fuzzer.cc deps: - grpc_test_util - grpc @@ -1882,7 +1892,7 @@ targets: build: test language: c src: - - test/core/iomgr/combiner_test.c + - test/core/iomgr/combiner_test.cc deps: - grpc_test_util - grpc @@ -1892,7 +1902,7 @@ targets: build: test language: c src: - - test/core/compression/compression_test.c + - test/core/compression/compression_test.cc deps: - grpc_test_util - grpc @@ -1904,7 +1914,7 @@ targets: build: test language: c src: - - test/core/surface/concurrent_connectivity_test.c + - test/core/surface/concurrent_connectivity_test.cc deps: - grpc_test_util - grpc @@ -1917,7 +1927,7 @@ targets: build: test language: c src: - - test/core/end2end/connection_refused_test.c + - test/core/end2end/connection_refused_test.cc deps: - grpc_test_util - grpc @@ -1928,7 +1938,7 @@ targets: build: test language: c src: - - test/core/client_channel/resolvers/dns_resolver_connectivity_test.c + - test/core/client_channel/resolvers/dns_resolver_connectivity_test.cc deps: - grpc_test_util - grpc @@ -1940,7 +1950,7 @@ targets: build: test language: c src: - - test/core/client_channel/resolvers/dns_resolver_test.c + - test/core/client_channel/resolvers/dns_resolver_test.cc deps: - grpc_test_util - grpc @@ -1951,7 +1961,7 @@ targets: build: test language: c src: - - test/core/end2end/dualstack_socket_test.c + - test/core/end2end/dualstack_socket_test.cc deps: - grpc_test_util - grpc @@ -1967,7 +1977,7 @@ targets: build: test language: c src: - - test/core/iomgr/endpoint_pair_test.c + - test/core/iomgr/endpoint_pair_test.cc deps: - grpc_test_util - grpc @@ -1980,7 +1990,7 @@ targets: build: test language: c src: - - test/core/iomgr/error_test.c + - test/core/iomgr/error_test.cc deps: - grpc_test_util - grpc @@ -1992,7 +2002,7 @@ targets: build: test language: c src: - - test/core/iomgr/ev_epollsig_linux_test.c + - test/core/iomgr/ev_epollsig_linux_test.cc deps: - grpc_test_util - grpc @@ -2006,7 +2016,7 @@ targets: build: test language: c src: - - test/core/client_channel/resolvers/fake_resolver_test.c + - test/core/client_channel/resolvers/fake_resolver_test.cc deps: - grpc_test_util - grpc @@ -2016,7 +2026,7 @@ targets: build: test language: c src: - - test/core/tsi/fake_transport_security_test.c + - test/core/tsi/fake_transport_security_test.cc deps: - gpr_test_util - gpr @@ -2031,7 +2041,7 @@ targets: build: test language: c src: - - test/core/iomgr/fd_conservation_posix_test.c + - test/core/iomgr/fd_conservation_posix_test.cc deps: - grpc_test_util - grpc @@ -2047,7 +2057,7 @@ targets: build: test language: c src: - - test/core/iomgr/fd_posix_test.c + - test/core/iomgr/fd_posix_test.cc deps: - grpc_test_util - grpc @@ -2064,7 +2074,7 @@ targets: run: false language: c src: - - test/core/fling/client.c + - test/core/fling/client.cc deps: - grpc_test_util - grpc @@ -2075,7 +2085,7 @@ targets: run: false language: c src: - - test/core/fling/server.c + - test/core/fling/server.cc deps: - grpc_test_util - grpc @@ -2086,7 +2096,7 @@ targets: build: test language: c src: - - test/core/fling/fling_stream_test.c + - test/core/fling/fling_stream_test.cc deps: - grpc_test_util - grpc @@ -2101,7 +2111,7 @@ targets: build: test language: c src: - - test/core/fling/fling_test.c + - test/core/fling/fling_test.cc deps: - grpc_test_util - grpc @@ -2138,7 +2148,7 @@ targets: build: test language: c src: - - test/core/end2end/goaway_server_test.c + - test/core/end2end/goaway_server_test.cc deps: - grpc_test_util - grpc @@ -2154,7 +2164,7 @@ targets: build: test language: c src: - - test/core/support/avl_test.c + - test/core/support/avl_test.cc deps: - gpr_test_util - gpr @@ -2163,7 +2173,7 @@ targets: build: test language: c src: - - test/core/support/cmdline_test.c + - test/core/support/cmdline_test.cc deps: - gpr_test_util - gpr @@ -2173,7 +2183,7 @@ targets: build: test language: c src: - - test/core/support/cpu_test.c + - test/core/support/cpu_test.cc deps: - gpr_test_util - gpr @@ -2182,34 +2192,35 @@ targets: build: test language: c src: - - test/core/support/env_test.c + - test/core/support/env_test.cc deps: - gpr_test_util - gpr uses_polling: false -- name: gpr_histogram_test +- name: gpr_host_port_test build: test language: c src: - - test/core/support/histogram_test.c + - test/core/support/host_port_test.cc deps: - gpr_test_util - gpr uses_polling: false -- name: gpr_host_port_test +- name: gpr_log_test build: test language: c src: - - test/core/support/host_port_test.c + - test/core/support/log_test.cc deps: - gpr_test_util - gpr uses_polling: false -- name: gpr_log_test +- name: gpr_manual_constructor_test + cpu_cost: 3 build: test language: c src: - - test/core/support/log_test.c + - test/core/support/manual_constructor_test.cc deps: - gpr_test_util - gpr @@ -2219,7 +2230,7 @@ targets: build: test language: c src: - - test/core/support/mpscq_test.c + - test/core/support/mpscq_test.cc deps: - gpr_test_util - gpr @@ -2229,17 +2240,7 @@ targets: build: test language: c src: - - test/core/support/spinlock_test.c - deps: - - gpr_test_util - - gpr - uses_polling: false -- name: gpr_stack_lockfree_test - cpu_cost: 7 - build: test - language: c - src: - - test/core/support/stack_lockfree_test.c + - test/core/support/spinlock_test.cc deps: - gpr_test_util - gpr @@ -2248,7 +2249,7 @@ targets: build: test language: c src: - - test/core/support/string_test.c + - test/core/support/string_test.cc deps: - gpr_test_util - gpr @@ -2258,7 +2259,7 @@ targets: build: test language: c src: - - test/core/support/sync_test.c + - test/core/support/sync_test.cc deps: - gpr_test_util - gpr @@ -2268,7 +2269,7 @@ targets: build: test language: c src: - - test/core/support/thd_test.c + - test/core/support/thd_test.cc deps: - gpr_test_util - gpr @@ -2277,7 +2278,7 @@ targets: build: test language: c src: - - test/core/support/time_test.c + - test/core/support/time_test.cc deps: - gpr_test_util - gpr @@ -2286,7 +2287,7 @@ targets: build: test language: c src: - - test/core/support/tls_test.c + - test/core/support/tls_test.cc deps: - gpr_test_util - gpr @@ -2295,7 +2296,7 @@ targets: build: test language: c src: - - test/core/support/useful_test.c + - test/core/support/useful_test.cc deps: - gpr_test_util - gpr @@ -2304,7 +2305,7 @@ targets: build: test language: c src: - - test/core/security/auth_context_test.c + - test/core/security/auth_context_test.cc deps: - grpc_test_util - grpc @@ -2315,7 +2316,7 @@ targets: build: test language: c src: - - test/core/slice/b64_test.c + - test/core/slice/b64_test.cc deps: - grpc_test_util - grpc @@ -2326,7 +2327,7 @@ targets: build: test language: c src: - - test/core/surface/byte_buffer_reader_test.c + - test/core/surface/byte_buffer_reader_test.cc deps: - grpc_test_util - grpc @@ -2337,7 +2338,7 @@ targets: build: test language: c src: - - test/core/channel/channel_args_test.c + - test/core/channel/channel_args_test.cc deps: - grpc_test_util - grpc @@ -2348,7 +2349,7 @@ targets: build: test language: c src: - - test/core/channel/channel_stack_builder_test.c + - test/core/channel/channel_stack_builder_test.cc deps: - grpc_test_util - grpc @@ -2358,7 +2359,7 @@ targets: build: test language: c src: - - test/core/channel/channel_stack_test.c + - test/core/channel/channel_stack_test.cc deps: - grpc_test_util - grpc @@ -2369,7 +2370,7 @@ targets: build: test language: c src: - - test/core/surface/completion_queue_test.c + - test/core/surface/completion_queue_test.cc deps: - grpc_test_util - grpc @@ -2379,7 +2380,7 @@ targets: build: test language: c src: - - test/core/surface/completion_queue_threading_test.c + - test/core/surface/completion_queue_threading_test.cc deps: - grpc_test_util - grpc @@ -2391,7 +2392,7 @@ targets: build: tool language: c src: - - test/core/security/create_jwt.c + - test/core/security/create_jwt.cc deps: - grpc - gpr @@ -2401,7 +2402,7 @@ targets: build: test language: c src: - - test/core/security/credentials_test.c + - test/core/security/credentials_test.cc deps: - grpc_test_util - grpc @@ -2412,7 +2413,7 @@ targets: run: false language: c src: - - test/core/security/fetch_oauth2.c + - test/core/security/fetch_oauth2.cc deps: - grpc_test_util - grpc @@ -2422,7 +2423,7 @@ targets: build: test language: c src: - - test/core/surface/invalid_channel_args_test.c + - test/core/surface/invalid_channel_args_test.cc deps: - grpc_test_util - grpc @@ -2433,7 +2434,7 @@ targets: build: test language: c src: - - test/core/security/json_token_test.c + - test/core/security/json_token_test.cc deps: - grpc_test_util - grpc @@ -2448,7 +2449,7 @@ targets: build: test language: c src: - - test/core/security/jwt_verifier_test.c + - test/core/security/jwt_verifier_test.cc deps: - grpc_test_util - grpc @@ -2459,7 +2460,7 @@ targets: build: tool language: c src: - - test/core/security/print_google_default_creds_token.c + - test/core/security/print_google_default_creds_token.cc deps: - grpc - gpr @@ -2468,7 +2469,7 @@ targets: build: test language: c src: - - test/core/security/security_connector_test.c + - test/core/security/security_connector_test.cc deps: - grpc_test_util - grpc @@ -2478,7 +2479,7 @@ targets: build: test language: c src: - - test/core/security/ssl_credentials_test.c + - test/core/security/ssl_credentials_test.cc deps: - grpc_test_util - grpc @@ -2488,7 +2489,7 @@ targets: build: tool language: c src: - - test/core/security/verify_jwt.c + - test/core/security/verify_jwt.cc deps: - grpc - gpr @@ -2497,7 +2498,7 @@ targets: build: test language: c src: - - test/core/handshake/client_ssl.c + - test/core/handshake/client_ssl.cc deps: - grpc_test_util - grpc @@ -2511,8 +2512,29 @@ targets: - name: handshake_server build: test language: c + headers: + - test/core/handshake/server_ssl_common.h + src: + - test/core/handshake/server_ssl.cc + - test/core/handshake/server_ssl_common.cc + deps: + - grpc_test_util + - grpc + - gpr_test_util + - gpr + exclude_iomgrs: + - uv + platforms: + - linux + secure: true +- name: handshake_server_with_readahead_handshaker + build: test + language: c + headers: + - test/core/handshake/server_ssl_common.h src: - - test/core/handshake/server_ssl.c + - test/core/handshake/readahead_handshaker_server_ssl.cc + - test/core/handshake/server_ssl_common.cc deps: - grpc_test_util - grpc @@ -2523,11 +2545,20 @@ targets: platforms: - linux secure: true +- name: histogram_test + build: test + language: c + src: + - test/core/util/histogram_test.cc + deps: + - grpc_test_util + - gpr + uses_polling: false - name: hpack_parser_fuzzer_test build: fuzzer language: c src: - - test/core/transport/chttp2/hpack_parser_fuzzer_test.c + - test/core/transport/chttp2/hpack_parser_fuzzer_test.cc deps: - grpc_test_util - grpc @@ -2541,7 +2572,7 @@ targets: build: test language: c src: - - test/core/transport/chttp2/hpack_parser_test.c + - test/core/transport/chttp2/hpack_parser_test.cc deps: - grpc_test_util - grpc @@ -2552,7 +2583,7 @@ targets: build: test language: c src: - - test/core/transport/chttp2/hpack_table_test.c + - test/core/transport/chttp2/hpack_table_test.cc deps: - grpc_test_util - grpc @@ -2563,7 +2594,7 @@ targets: build: test language: c src: - - test/core/http/parser_test.c + - test/core/http/parser_test.cc deps: - grpc_test_util - grpc @@ -2574,7 +2605,7 @@ targets: build: fuzzer language: c src: - - test/core/http/request_fuzzer.c + - test/core/http/request_fuzzer.cc deps: - grpc_test_util - grpc @@ -2587,7 +2618,7 @@ targets: build: fuzzer language: c src: - - test/core/http/response_fuzzer.c + - test/core/http/response_fuzzer.cc deps: - grpc_test_util - grpc @@ -2600,7 +2631,7 @@ targets: build: test language: c src: - - test/core/http/format_request_test.c + - test/core/http/format_request_test.cc deps: - grpc_test_util - grpc @@ -2611,7 +2642,7 @@ targets: build: test language: c src: - - test/core/http/httpcli_test.c + - test/core/http/httpcli_test.cc deps: - grpc_test_util - grpc @@ -2626,7 +2657,7 @@ targets: build: test language: c src: - - test/core/http/httpscli_test.c + - test/core/http/httpscli_test.cc deps: - grpc_test_util - grpc @@ -2638,7 +2669,7 @@ targets: build: test language: c src: - - test/core/surface/init_test.c + - test/core/surface/init_test.cc deps: - grpc_test_util - grpc @@ -2650,7 +2681,7 @@ targets: build: test language: c src: - - test/core/end2end/invalid_call_argument_test.c + - test/core/end2end/invalid_call_argument_test.cc deps: - grpc_test_util - grpc @@ -2660,7 +2691,7 @@ targets: build: fuzzer language: c src: - - test/core/json/fuzzer.c + - test/core/json/fuzzer.cc deps: - grpc_test_util - grpc @@ -2674,7 +2705,7 @@ targets: run: false language: c src: - - test/core/json/json_rewrite.c + - test/core/json/json_rewrite.cc deps: - grpc - gpr @@ -2683,7 +2714,7 @@ targets: build: test language: c src: - - test/core/json/json_rewrite_test.c + - test/core/json/json_rewrite_test.cc deps: - grpc_test_util - grpc @@ -2694,7 +2725,7 @@ targets: build: test language: c src: - - test/core/json/json_stream_error_test.c + - test/core/json/json_stream_error_test.cc deps: - grpc_test_util - grpc @@ -2705,7 +2736,7 @@ targets: build: test language: c src: - - test/core/json/json_test.c + - test/core/json/json_test.cc deps: - grpc_test_util - grpc @@ -2716,7 +2747,7 @@ targets: build: test language: c src: - - test/core/surface/lame_client_test.c + - test/core/surface/lame_client_test.cc deps: - grpc_test_util - grpc @@ -2728,7 +2759,7 @@ targets: run: false language: c src: - - test/core/client_channel/lb_policies_test.c + - test/core/client_channel/lb_policies_test.cc deps: - grpc_test_util - grpc @@ -2739,7 +2770,7 @@ targets: build: test language: c src: - - test/core/iomgr/load_file_test.c + - test/core/iomgr/load_file_test.cc deps: - grpc_test_util - grpc @@ -2750,7 +2781,7 @@ targets: build: benchmark language: c src: - - test/core/network_benchmarks/low_level_ping_pong.c + - test/core/network_benchmarks/low_level_ping_pong.cc deps: - grpc_test_util - grpc @@ -2765,7 +2796,7 @@ targets: run: false language: c src: - - test/core/memory_usage/client.c + - test/core/memory_usage/client.cc deps: - grpc_test_util - grpc @@ -2777,7 +2808,7 @@ targets: run: false language: c src: - - test/core/memory_usage/server.c + - test/core/memory_usage/server.cc deps: - grpc_test_util - grpc @@ -2788,7 +2819,7 @@ targets: build: test language: c src: - - test/core/memory_usage/memory_usage_test.c + - test/core/memory_usage/memory_usage_test.cc deps: - grpc_test_util - grpc @@ -2802,7 +2833,7 @@ targets: build: test language: c src: - - test/core/compression/message_compress_test.c + - test/core/compression/message_compress_test.cc deps: - grpc_test_util - grpc @@ -2813,7 +2844,7 @@ targets: build: test language: c src: - - test/core/channel/minimal_stack_is_minimal_test.c + - test/core/channel/minimal_stack_is_minimal_test.cc deps: - grpc_test_util - grpc @@ -2824,7 +2855,7 @@ targets: build: test language: c src: - - test/core/end2end/multiple_server_queues_test.c + - test/core/end2end/multiple_server_queues_test.cc deps: - grpc_test_util - grpc @@ -2834,7 +2865,7 @@ targets: build: test language: c src: - - test/core/support/murmur_hash_test.c + - test/core/support/murmur_hash_test.cc deps: - gpr_test_util - gpr @@ -2843,7 +2874,7 @@ targets: build: fuzzer language: c src: - - test/core/nanopb/fuzzer_response.c + - test/core/nanopb/fuzzer_response.cc deps: - grpc_test_util - grpc @@ -2856,7 +2887,7 @@ targets: build: fuzzer language: c src: - - test/core/nanopb/fuzzer_serverlist.c + - test/core/nanopb/fuzzer_serverlist.cc deps: - grpc_test_util - grpc @@ -2870,7 +2901,7 @@ targets: build: test language: c src: - - test/core/end2end/no_server_test.c + - test/core/end2end/no_server_test.cc deps: - grpc_test_util - grpc @@ -2880,7 +2911,7 @@ targets: build: test language: c src: - - test/core/surface/num_external_connectivity_watchers_test.c + - test/core/surface/num_external_connectivity_watchers_test.cc deps: - grpc_test_util - grpc @@ -2892,7 +2923,7 @@ targets: build: test language: c src: - - test/core/client_channel/parse_address_test.c + - test/core/client_channel/parse_address_test.cc deps: - grpc_test_util - grpc @@ -2903,7 +2934,7 @@ targets: build: fuzzer language: c src: - - test/core/slice/percent_decode_fuzzer.c + - test/core/slice/percent_decode_fuzzer.cc deps: - grpc_test_util - grpc @@ -2916,7 +2947,7 @@ targets: build: fuzzer language: c src: - - test/core/slice/percent_encode_fuzzer.c + - test/core/slice/percent_encode_fuzzer.cc deps: - grpc_test_util - grpc @@ -2929,7 +2960,7 @@ targets: build: test language: c src: - - test/core/slice/percent_encoding_test.c + - test/core/slice/percent_encoding_test.cc deps: - grpc_test_util - grpc @@ -2940,7 +2971,7 @@ targets: build: test language: c src: - - test/core/iomgr/pollset_set_test.c + - test/core/iomgr/pollset_set_test.cc deps: - grpc_test_util - grpc @@ -2954,7 +2985,7 @@ targets: build: test language: c src: - - test/core/iomgr/resolve_address_posix_test.c + - test/core/iomgr/resolve_address_posix_test.cc deps: - grpc_test_util - grpc @@ -2970,7 +3001,7 @@ targets: build: test language: c src: - - test/core/iomgr/resolve_address_test.c + - test/core/iomgr/resolve_address_test.cc deps: - grpc_test_util - grpc @@ -2981,7 +3012,7 @@ targets: build: test language: c src: - - test/core/iomgr/resource_quota_test.c + - test/core/iomgr/resource_quota_test.cc deps: - grpc_test_util - grpc @@ -2991,7 +3022,7 @@ targets: build: test language: c src: - - test/core/surface/secure_channel_create_test.c + - test/core/surface/secure_channel_create_test.cc deps: - grpc_test_util - grpc @@ -3001,7 +3032,7 @@ targets: build: test language: c src: - - test/core/security/secure_endpoint_test.c + - test/core/security/secure_endpoint_test.cc deps: - grpc_test_util - grpc @@ -3013,7 +3044,7 @@ targets: build: test language: c src: - - test/core/surface/sequential_connectivity_test.c + - test/core/surface/sequential_connectivity_test.cc deps: - grpc_test_util - grpc @@ -3025,7 +3056,7 @@ targets: build: test language: c src: - - test/core/surface/server_chttp2_test.c + - test/core/surface/server_chttp2_test.cc deps: - grpc_test_util - grpc @@ -3035,7 +3066,7 @@ targets: build: fuzzer language: c src: - - test/core/end2end/fuzzers/server_fuzzer.c + - test/core/end2end/fuzzers/server_fuzzer.cc deps: - grpc_test_util - grpc @@ -3049,7 +3080,7 @@ targets: build: test language: c src: - - test/core/surface/server_test.c + - test/core/surface/server_test.cc deps: - grpc_test_util - grpc @@ -3059,7 +3090,7 @@ targets: build: test language: c src: - - test/core/slice/slice_buffer_test.c + - test/core/slice/slice_buffer_test.cc deps: - grpc_test_util - grpc @@ -3070,7 +3101,7 @@ targets: build: test language: c src: - - test/core/slice/slice_hash_table_test.c + - test/core/slice/slice_hash_table_test.cc deps: - grpc_test_util - grpc @@ -3081,7 +3112,7 @@ targets: build: test language: c src: - - test/core/slice/slice_string_helpers_test.c + - test/core/slice/slice_string_helpers_test.cc deps: - grpc_test_util - grpc @@ -3092,7 +3123,7 @@ targets: build: test language: c src: - - test/core/slice/slice_test.c + - test/core/slice/slice_test.cc deps: - grpc_test_util - grpc @@ -3103,7 +3134,7 @@ targets: build: test language: c src: - - test/core/client_channel/resolvers/sockaddr_resolver_test.c + - test/core/client_channel/resolvers/sockaddr_resolver_test.cc deps: - grpc_test_util - grpc @@ -3113,7 +3144,7 @@ targets: build: test language: c src: - - test/core/iomgr/sockaddr_utils_test.c + - test/core/iomgr/sockaddr_utils_test.cc deps: - grpc_test_util - grpc @@ -3123,7 +3154,7 @@ targets: build: test language: c src: - - test/core/iomgr/socket_utils_test.c + - test/core/iomgr/socket_utils_test.cc deps: - grpc_test_util - grpc @@ -3139,7 +3170,7 @@ targets: build: fuzzer language: c src: - - test/core/security/ssl_server_fuzzer.c + - test/core/security/ssl_server_fuzzer.cc deps: - grpc_test_util - grpc @@ -3152,7 +3183,7 @@ targets: build: test language: c src: - - test/core/tsi/ssl_transport_security_test.c + - test/core/tsi/ssl_transport_security_test.cc deps: - gpr_test_util - gpr @@ -3167,7 +3198,7 @@ targets: build: test language: c src: - - test/core/transport/status_conversion_test.c + - test/core/transport/status_conversion_test.cc deps: - grpc_test_util - grpc @@ -3178,7 +3209,7 @@ targets: build: test language: c src: - - test/core/compression/stream_compression_test.c + - test/core/compression/stream_compression_test.cc deps: - grpc_test_util - grpc @@ -3189,7 +3220,7 @@ targets: build: test language: c src: - - test/core/transport/stream_owned_slice_test.c + - test/core/transport/stream_owned_slice_test.cc deps: - grpc_test_util - grpc @@ -3201,7 +3232,7 @@ targets: build: test language: c src: - - test/core/iomgr/tcp_client_posix_test.c + - test/core/iomgr/tcp_client_posix_test.cc deps: - grpc_test_util - grpc @@ -3218,7 +3249,7 @@ targets: build: test language: c src: - - test/core/iomgr/tcp_client_uv_test.c + - test/core/iomgr/tcp_client_uv_test.cc deps: - grpc_test_util - grpc @@ -3231,7 +3262,7 @@ targets: build: test language: c src: - - test/core/iomgr/tcp_posix_test.c + - test/core/iomgr/tcp_posix_test.cc deps: - grpc_test_util - grpc @@ -3247,7 +3278,7 @@ targets: build: test language: c src: - - test/core/iomgr/tcp_server_posix_test.c + - test/core/iomgr/tcp_server_posix_test.cc deps: - grpc_test_util - grpc @@ -3263,7 +3294,7 @@ targets: build: test language: c src: - - test/core/iomgr/tcp_server_uv_test.c + - test/core/iomgr/tcp_server_uv_test.cc deps: - grpc_test_util - grpc @@ -3275,7 +3306,7 @@ targets: build: test language: c src: - - test/core/iomgr/time_averaged_stats_test.c + - test/core/iomgr/time_averaged_stats_test.cc deps: - grpc_test_util - grpc @@ -3286,7 +3317,7 @@ targets: build: test language: c src: - - test/core/transport/timeout_encoding_test.c + - test/core/transport/timeout_encoding_test.cc deps: - grpc_test_util - grpc @@ -3297,7 +3328,7 @@ targets: build: test language: c src: - - test/core/iomgr/timer_heap_test.c + - test/core/iomgr/timer_heap_test.cc deps: - grpc_test_util - grpc @@ -3310,7 +3341,7 @@ targets: build: test language: c src: - - test/core/iomgr/timer_list_test.c + - test/core/iomgr/timer_list_test.cc deps: - grpc_test_util - grpc @@ -3323,7 +3354,7 @@ targets: build: test language: c src: - - test/core/transport/connectivity_state_test.c + - test/core/transport/connectivity_state_test.cc deps: - grpc_test_util - grpc @@ -3333,7 +3364,7 @@ targets: build: test language: c src: - - test/core/transport/metadata_test.c + - test/core/transport/metadata_test.cc deps: - grpc_test_util - grpc @@ -3343,7 +3374,7 @@ targets: build: test language: c src: - - test/core/tsi/transport_security_test.c + - test/core/tsi/transport_security_test.cc deps: - grpc_test_util - grpc @@ -3357,7 +3388,7 @@ targets: build: test language: c src: - - test/core/iomgr/udp_server_test.c + - test/core/iomgr/udp_server_test.cc deps: - grpc_test_util - grpc @@ -3373,7 +3404,7 @@ targets: build: fuzzer language: c src: - - test/core/client_channel/uri_fuzzer_test.c + - test/core/client_channel/uri_fuzzer_test.cc deps: - grpc_test_util - grpc @@ -3386,7 +3417,7 @@ targets: build: test language: c src: - - test/core/client_channel/uri_parser_test.c + - test/core/client_channel/uri_parser_test.cc deps: - grpc_test_util - grpc @@ -3396,7 +3427,7 @@ targets: build: test language: c src: - - test/core/iomgr/wakeup_fd_cv_test.c + - test/core/iomgr/wakeup_fd_cv_test.cc deps: - grpc_test_util - grpc @@ -3475,8 +3506,6 @@ targets: - grpc_unsecure - gpr_test_util - gpr - args: - - --benchmark_min_time=0 benchmark: true defaults: benchmark platforms: @@ -3498,8 +3527,6 @@ targets: - grpc_unsecure - gpr_test_util - gpr - args: - - --benchmark_min_time=0 benchmark: true defaults: benchmark platforms: @@ -3521,8 +3548,6 @@ targets: - grpc_unsecure - gpr_test_util - gpr - args: - - --benchmark_min_time=0 benchmark: true defaults: benchmark platforms: @@ -3544,8 +3569,6 @@ targets: - grpc_unsecure - gpr_test_util - gpr - args: - - --benchmark_min_time=0 benchmark: true defaults: benchmark platforms: @@ -3566,8 +3589,6 @@ targets: - grpc_unsecure - gpr_test_util - gpr - args: - - --benchmark_min_time=0 benchmark: true defaults: benchmark platforms: @@ -3588,8 +3609,6 @@ targets: - grpc_unsecure - gpr_test_util - gpr - args: - - --benchmark_min_time=0 benchmark: true defaults: benchmark platforms: @@ -3610,8 +3629,6 @@ targets: - grpc_unsecure - gpr_test_util - gpr - args: - - --benchmark_min_time=4 benchmark: true defaults: benchmark platforms: @@ -3632,8 +3649,6 @@ targets: - grpc_unsecure - gpr_test_util - gpr - args: - - --benchmark_min_time=0 benchmark: true defaults: benchmark platforms: @@ -3657,8 +3672,6 @@ targets: - grpc_unsecure - gpr_test_util - gpr - args: - - --benchmark_min_time=0 benchmark: true defaults: benchmark excluded_poll_engines: @@ -3685,8 +3698,6 @@ targets: - grpc_unsecure - gpr_test_util - gpr - args: - - --benchmark_min_time=0 benchmark: true defaults: benchmark excluded_poll_engines: @@ -3712,8 +3723,6 @@ targets: - gpr_test_util - gpr - grpc++_test_config - args: - - --benchmark_min_time=0 benchmark: true defaults: benchmark exclude_configs: @@ -3742,8 +3751,6 @@ targets: - grpc_unsecure - gpr_test_util - gpr - args: - - --benchmark_min_time=0 benchmark: true defaults: benchmark excluded_poll_engines: @@ -3768,8 +3775,6 @@ targets: - grpc_unsecure - gpr_test_util - gpr - args: - - --benchmark_min_time=0 benchmark: true defaults: benchmark platforms: @@ -3791,8 +3796,6 @@ targets: - grpc_unsecure - gpr_test_util - gpr - args: - - --benchmark_min_time=0 benchmark: true defaults: benchmark platforms: @@ -3821,6 +3824,18 @@ targets: - grpc - gpr uses_polling: false +- name: chttp2_settings_timeout_test + gtest: true + build: test + language: c++ + src: + - test/core/transport/chttp2/settings_timeout_test.cc + deps: + - grpc_test_util + - grpc + - gpr_test_util + - gpr + uses_polling: true - name: cli_call_test gtest: true build: test @@ -3835,6 +3850,20 @@ targets: - grpc - gpr_test_util - gpr +- name: client_channel_stress_test + gtest: false + build: test + language: c++ + src: + - src/proto/grpc/lb/v1/load_balancer.proto + - test/cpp/client/client_channel_stress_test.cc + deps: + - grpc++_test_util + - grpc_test_util + - grpc++ + - grpc + - gpr_test_util + - gpr - name: client_crash_test gtest: true cpu_cost: 0.1 @@ -4522,6 +4551,34 @@ targets: - gpr_test_util - gpr - grpc++_test_config +- name: ref_counted_ptr_test + gtest: true + build: test + language: c++ + src: + - test/core/support/ref_counted_ptr_test.cc + deps: + - grpc_test_util + - grpc++ + - grpc + - gpr_test_util + - gpr + uses: + - grpc++_test +- name: ref_counted_test + gtest: true + build: test + language: c++ + src: + - test/core/support/ref_counted_test.cc + deps: + - grpc_test_util + - grpc++ + - grpc + - gpr_test_util + - gpr + uses: + - grpc++_test - name: secure_auth_context_test gtest: true build: test @@ -4763,20 +4820,6 @@ targets: - grpc - gpr_test_util - gpr -- name: vector_test - gtest: true - build: test - language: c++ - src: - - test/core/support/vector_test.cc - deps: - - grpc_test_util - - grpc++ - - grpc - - gpr_test_util - - gpr - uses: - - grpc++_test - name: writes_per_rpc_test gtest: true cpu_cost: 0.5 @@ -4896,8 +4939,8 @@ configs: msan: CC: clang CPPFLAGS: -O0 -fsanitize-coverage=edge -fsanitize=memory -fsanitize-memory-track-origins - -fno-omit-frame-pointer -DGTEST_HAS_TR1_TUPLE=0 -DGTEST_USE_OWN_TR1_TUPLE=1 - -Wno-unused-command-line-argument -fPIE -pie -DGPR_NO_DIRECT_SYSCALLS + -fsanitize-memory-use-after-dtor -fno-omit-frame-pointer -DGTEST_HAS_TR1_TUPLE=0 + -DGTEST_USE_OWN_TR1_TUPLE=1 -Wno-unused-command-line-argument -fPIE -pie -DGPR_NO_DIRECT_SYSCALLS CXX: clang++ DEFINES: NDEBUG LD: clang++ @@ -4905,6 +4948,8 @@ configs: -fPIE -pie $(if $(JENKINS_BUILD),-Wl$(comma)-Ttext-segment=0x7e0000000000,) LDXX: clang++ compile_the_world: true + test_environ: + MSAN_OPTIONS: poison_in_dtor=1 mutrace: CPPFLAGS: -O3 -fno-omit-frame-pointer DEFINES: NDEBUG @@ -4957,51 +5002,12 @@ defaults: CPPFLAGS: -Ithird_party/boringssl/include -fvisibility=hidden -DOPENSSL_NO_ASM -D_GNU_SOURCE -DWIN32_LEAN_AND_MEAN -D_HAS_EXCEPTIONS=0 -DNOMINMAX global: + COREFLAGS: -fno-rtti -fno-exceptions CPPFLAGS: -g -Wall -Wextra -Werror -Wno-long-long -Wno-unused-parameter -DOSATOMIC_USE_INLINED=1 - -Ithird_party/abseil-cpp LDFLAGS: -g zlib: CFLAGS: -Wno-sign-conversion -Wno-conversion -Wno-unused-value -Wno-implicit-function-declaration $(W_NO_SHIFT_NEGATIVE_VALUE) -fvisibility=hidden -node_modules: -- deps: - - grpc - - gpr - - boringssl - - z - headers: - - src/node/ext/byte_buffer.h - - src/node/ext/call.h - - src/node/ext/call_credentials.h - - src/node/ext/channel.h - - src/node/ext/channel_credentials.h - - src/node/ext/completion_queue.h - - src/node/ext/server.h - - src/node/ext/server_credentials.h - - src/node/ext/slice.h - - src/node/ext/timeval.h - js: - - src/node/index.js - - src/node/src/client.js - - src/node/src/common.js - - src/node/src/credentials.js - - src/node/src/constants.js - - src/node/src/grpc_extension.js - - src/node/src/metadata.js - - src/node/src/server.js - name: grpc_node - src: - - src/node/ext/byte_buffer.cc - - src/node/ext/call.cc - - src/node/ext/call_credentials.cc - - src/node/ext/channel.cc - - src/node/ext/channel_credentials.cc - - src/node/ext/completion_queue.cc - - src/node/ext/node_grpc.cc - - src/node/ext/server.cc - - src/node/ext/server_credentials.cc - - src/node/ext/slice.cc - - src/node/ext/timeval.cc openssl_fallback: base_uri: https://openssl.org/source/old/1.0.2/ extraction_dir: openssl-1.0.2f diff --git a/config.m4 b/config.m4 index 5cb46cf054a..c026b83f359 100644 --- a/config.m4 +++ b/config.m4 @@ -53,7 +53,7 @@ if test "$PHP_GRPC" != "no"; then src/core/lib/support/env_linux.cc \ src/core/lib/support/env_posix.cc \ src/core/lib/support/env_windows.cc \ - src/core/lib/support/histogram.cc \ + src/core/lib/support/fork.cc \ src/core/lib/support/host_port.cc \ src/core/lib/support/log.cc \ src/core/lib/support/log_android.cc \ @@ -62,7 +62,6 @@ if test "$PHP_GRPC" != "no"; then src/core/lib/support/log_windows.cc \ src/core/lib/support/mpscq.cc \ src/core/lib/support/murmur_hash.cc \ - src/core/lib/support/stack_lockfree.cc \ src/core/lib/support/string.cc \ src/core/lib/support/string_posix.cc \ src/core/lib/support/string_util_windows.cc \ @@ -104,7 +103,6 @@ if test "$PHP_GRPC" != "no"; then src/core/lib/http/httpcli.cc \ src/core/lib/http/parser.cc \ src/core/lib/iomgr/call_combiner.cc \ - src/core/lib/iomgr/closure.cc \ src/core/lib/iomgr/combiner.cc \ src/core/lib/iomgr/endpoint.cc \ src/core/lib/iomgr/endpoint_pair_posix.cc \ @@ -119,6 +117,8 @@ if test "$PHP_GRPC" != "no"; then src/core/lib/iomgr/ev_windows.cc \ src/core/lib/iomgr/exec_ctx.cc \ src/core/lib/iomgr/executor.cc \ + src/core/lib/iomgr/fork_posix.cc \ + src/core/lib/iomgr/fork_windows.cc \ src/core/lib/iomgr/gethostname_fallback.cc \ src/core/lib/iomgr/gethostname_host_name_max.cc \ src/core/lib/iomgr/gethostname_sysconf.cc \ diff --git a/config.w32 b/config.w32 index 0fc5066b292..cd3a16a4653 100644 --- a/config.w32 +++ b/config.w32 @@ -30,7 +30,7 @@ if (PHP_GRPC != "no") { "src\\core\\lib\\support\\env_linux.cc " + "src\\core\\lib\\support\\env_posix.cc " + "src\\core\\lib\\support\\env_windows.cc " + - "src\\core\\lib\\support\\histogram.cc " + + "src\\core\\lib\\support\\fork.cc " + "src\\core\\lib\\support\\host_port.cc " + "src\\core\\lib\\support\\log.cc " + "src\\core\\lib\\support\\log_android.cc " + @@ -39,7 +39,6 @@ if (PHP_GRPC != "no") { "src\\core\\lib\\support\\log_windows.cc " + "src\\core\\lib\\support\\mpscq.cc " + "src\\core\\lib\\support\\murmur_hash.cc " + - "src\\core\\lib\\support\\stack_lockfree.cc " + "src\\core\\lib\\support\\string.cc " + "src\\core\\lib\\support\\string_posix.cc " + "src\\core\\lib\\support\\string_util_windows.cc " + @@ -81,7 +80,6 @@ if (PHP_GRPC != "no") { "src\\core\\lib\\http\\httpcli.cc " + "src\\core\\lib\\http\\parser.cc " + "src\\core\\lib\\iomgr\\call_combiner.cc " + - "src\\core\\lib\\iomgr\\closure.cc " + "src\\core\\lib\\iomgr\\combiner.cc " + "src\\core\\lib\\iomgr\\endpoint.cc " + "src\\core\\lib\\iomgr\\endpoint_pair_posix.cc " + @@ -96,6 +94,8 @@ if (PHP_GRPC != "no") { "src\\core\\lib\\iomgr\\ev_windows.cc " + "src\\core\\lib\\iomgr\\exec_ctx.cc " + "src\\core\\lib\\iomgr\\executor.cc " + + "src\\core\\lib\\iomgr\\fork_posix.cc " + + "src\\core\\lib\\iomgr\\fork_windows.cc " + "src\\core\\lib\\iomgr\\gethostname_fallback.cc " + "src\\core\\lib\\iomgr\\gethostname_host_name_max.cc " + "src\\core\\lib\\iomgr\\gethostname_sysconf.cc " + diff --git a/doc/connectivity-semantics-and-api.md b/doc/connectivity-semantics-and-api.md index 6d39619d650..dc30fe5348b 100644 --- a/doc/connectivity-semantics-and-api.md +++ b/doc/connectivity-semantics-and-api.md @@ -115,8 +115,14 @@ Channel State API ----------------- All gRPC libraries will expose a channel-level API method to poll the current -state of a channel. In C++, this method is called GetCurrentState and returns -an enum for one of the five legal states. +state of a channel. In C++, this method is called GetState and returns an enum +for one of the five legal states. It also accepts a boolean `try_to_connect` to +transition to CONNECTING if the channel is currently IDLE. The boolean should +act as if an RPC occurred, so it should also reset IDLE_TIMEOUT. + +```cpp +grpc_connectivity_state GetState(bool try_to_connect); +``` All libraries should also expose an API that enables the application (user of the gRPC API) to be notified when the channel state changes. Since state @@ -127,11 +133,11 @@ the user to poll the channel for the current state. The synchronous version of this API is: ```cpp -bool WaitForStateChange(gpr_timespec deadline, ChannelState source_state); +bool WaitForStateChange(grpc_connectivity_state source_state, gpr_timespec deadline); ``` -which returns true when the state changes to something other than the -source_state and false if the deadline expires. Asynchronous and futures based +which returns `true` when the state is something other than the +`source_state` and `false` if the deadline expires. Asynchronous- and futures-based APIs should have a corresponding method that allows the application to be notified when the state of a channel changes. diff --git a/doc/core/transport_explainer.md b/doc/core/transport_explainer.md new file mode 100644 index 00000000000..f48fa0f3b1f --- /dev/null +++ b/doc/core/transport_explainer.md @@ -0,0 +1,197 @@ +# Transport Explainer + +@vjpai + +## Existing Transports + +[gRPC +transports](https://github.com/grpc/grpc/tree/master/src/core/ext/transport) +plug in below the core API (one level below the C++ or other wrapped-language +API). You can write your transport in C or C++ though; currently (Nov 2017) all +the transports are nominally written in C++ though they are idiomatically C. The +existing transports are: + +* [HTTP/2](https://github.com/grpc/grpc/tree/master/src/core/ext/transport/chttp2) +* [Cronet](https://github.com/grpc/grpc/tree/master/src/core/ext/transport/cronet) +* [In-process](https://github.com/grpc/grpc/tree/master/src/core/ext/transport/inproc) + +Among these, the in-process is likely the easiest to understand, though arguably +also the least similar to a "real" sockets-based transport since it is only used +in a single process. + +## Transport stream ops + +In the gRPC core implementation, a fundamental struct is the +`grpc_transport_stream_op_batch` which represents a collection of stream +operations sent to a transport. (Note that in gRPC, _stream_ and _RPC_ are used +synonymously since all RPCs are actually streams internally.) The ops in a batch +can include: + +* send\_initial\_metadata + - Client: initate an RPC + - Server: supply response headers +* recv\_initial\_metadata + - Client: get response headers + - Server: accept an RPC +* send\_message (zero or more) : send a data buffer +* recv\_message (zero or more) : receive a data buffer +* send\_trailing\_metadata + - Client: half-close indicating that no more messages will be coming + - Server: full-close providing final status for the RPC +* recv\_trailing\_metadata: get final status for the RPC + - Server extra: This op shouldn't actually be considered complete until the + server has also sent trailing metadata to provide the other side with final + status +* cancel\_stream: Attempt to cancel an RPC +* collect\_stats: Get stats + +The fundamental responsibility of the transport is to transform between this +internal format and an actual wire format, so the processing of these operations +is largely transport-specific. + +One or more of these ops are grouped into a batch. Applications can start all of +a call's ops in a single batch, or they can split them up into multiple +batches. Results of each batch are returned asynchronously via a completion +queue. + +Internally, we use callbacks to indicate completion. The surface layer creates a +callback when starting a new batch and sends it down the filter stack along with +the batch. The transport must invoke this callback when the batch is complete, +and then the surface layer returns an event to the application via the +completion queue. Each batch can have up to 3 callbacks: + +* recv\_initial\_metadata\_ready (called by the transport when the + recv\_initial\_metadata op is complete) +* recv\_message\_ready (called by the transport when the recv_message op is + complete) +* on\_complete (called by the transport when the entire batch is complete) + +## Timelines of transport stream op batches + +The transport's job is to sequence and interpret various possible interleavings +of the basic stream ops. For example, a sample timeline of batches would be: + +1. Client send\_initial\_metadata: Initiate an RPC with a path (method) and authority +1. Server recv\_initial\_metadata: accept an RPC +1. Client send\_message: Supply the input proto for the RPC +1. Server recv\_message: Get the input proto from the RPC +1. Client send\_trailing\_metadata: This is a half-close indicating that the + client will not be sending any more messages +1. Server recv\_trailing\_metadata: The server sees this from the client and + knows that it will not get any more messages. This won't complete yet though, + as described above. +1. Server send\_initial\_metadata, send\_message, send\_trailing\_metadata: A + batch can contain multiple ops, and this batch provides the RPC response + headers, response content, and status. Note that sending the trailing + metadata will also complete the server's receive of trailing metadata. +1. Client recv\_initial\_metadata: The number of ops in one side of the batch + has no relation with the number of ops on the other side of the batch. In + this case, the client is just collecting the response headers. +1. Client recv\_message, recv\_trailing\_metadata: Get the data response and + status + + +There are other possible sample timelines. For example, for client-side streaming, a "typical" sequence would be: + +1. Server: recv\_initial\_metadata + - At API-level, that would be the server requesting an RPC +1. Server: recv\_trailing\_metadata + - This is for when the server wants to know the final completion of the RPC + through an `AsyncNotifyWhenDone` API in C++ +1. Client: send\_initial\_metadata, recv\_message, recv\_trailing\_metadata + - At API-level, that's a client invoking a client-side streaming call. The + send\_initial\_metadata is the call invocation, the recv\_message colects + the final response from the server, and the recv\_trailing\_metadata gets + the `grpc::Status` value that will be returned from the call +1. Client: send\_message / Server: recv\_message + - Repeat the above step numerous times; these correspond to a client issuing + `Write` in a loop and a server doing `Read` in a loop until `Read` fails +1. Client: send\_trailing\_metadata / Server: recv\_message that indicates doneness (NULL) + - These correspond to a client issuing `WritesDone` which causes the server's + `Read` to fail +1. Server: send\_message, send\_trailing\_metadata + - These correpond to the server doing `Finish` + +The sends on one side will call their own callbacks when complete, and they will +in turn trigger actions that cause the other side's recv operations to +complete. In some transports, a send can sometimes complete before the recv on +the other side (e.g., in HTTP/2 if there is sufficient flow-control buffer space +available) + +## Other transport duties + +In addition to these basic stream ops, the transport must handle cancellations +of a stream at any time and pass their effects to the other side. For example, +in HTTP/2, this triggers a `RST_STREAM` being sent on the wire. The transport +must perform operations like pings and statistics that are used to shape +transport-level characteristics like flow control (see, for example, their use +in the HTTP/2 transport). + +## Putting things together with detail: Sending Metadata + +* API layer: `map` that is specific to this RPC +* Core surface layer: array of `{slice, slice}` pairs where each slice + references an underlying string +* [Core transport + layer](https://github.com/grpc/grpc/tree/master/src/core/lib/transport): list + of `{slice, slice}` pairs that includes the above plus possibly some general + metadata (e.g., Method and Authority for initial metadata) +* [Specific transport + layer](https://github.com/grpc/grpc/tree/master/src/core/ext/transport): + - Either send it to the other side using transport-specific API (e.g., Cronet) + - Or have it sent through the [iomgr/endpoint + layer](https://github.com/grpc/grpc/tree/master/src/core/lib/iomgr) (e.g., + HTTP/2) + - Or just manipulate pointers to get it from one side to the other (e.g., + In-process) + +## Requirements for any transport + +Each transport implements several operations in a vtbl (may change to actual +virtual functions as transport moves to idiomatic C++). + +The most important and common one is `perform_stream_op`. This function +processes a single stream op batch on a specific stream that is associated with +a specific transport: + +* Gets the 6 ops/cancel passed down from the surface +* Pass metadata from one side to the other as described above +* Transform messages between slice buffer structure and stream of bytes to pass + to other side + - May require insertion of extra bytes (e.g., per-message headers in HTTP/2) +* React to metadata to preserve expected orderings (*) +* Schedule invocation of completion callbacks + +There are other functions in the vtbl as well. + +* `perform_transport_op` + - Configure the transport instance for the connectivity state change notifier + or the server-side accept callback + - Disconnect transport or set up a goaway for later streams +* `init_stream` + - Starts a stream from the client-side + - (*) Server-side of the transport must call `accept_stream_cb` when a new + stream is available + * Triggers request-matcher +* `destroy_stream`, `destroy_transport` + - Free up data related to a stream or transport +* `set_pollset`, `set_pollset_set`, `get_endpoint` + - Map each specific instance of the transport to FDs being used by iomgr (for + HTTP/2) + - Get a pointer to the endpoint structure that actually moves the data + (wrapper around a socket for HTTP/2) + +## Book-keeping responsibilities of the transport layer + +A given transport must keep all of its transport and streams ref-counted. This +is essential to make sure that no struct disappears before it is done being +used. + +A transport must also preserve relevant orders for the different categories of +ops on a stream, as described above. A transport must also make sure that all +relevant batch operations have completed before scheduling the `on_complete` +closure for a batch. Further examples include the idea that the server logic +expects to not complete recv\_trailing\_metadata until after it actually sends +trailing metadata since it would have already found this out by seeing a NULL’ed +recv\_message. This is considered part of the transport's duties in preserving +orders. diff --git a/doc/g_stands_for.md b/doc/g_stands_for.md index 4e2ca33276c..edc6dc1e798 100644 --- a/doc/g_stands_for.md +++ b/doc/g_stands_for.md @@ -12,3 +12,4 @@ future), and the corresponding version numbers that used them: - 1.6 'g' stands for 'garcia' - 1.7 'g' stands for 'gambit' - 1.8 'g' stands for 'generous' +- 1.9 'g' stands for 'glossy' diff --git a/doc/service_config.md b/doc/service_config.md index 0abbd7f324d..dd1cbc56300 100644 --- a/doc/service_config.md +++ b/doc/service_config.md @@ -12,7 +12,7 @@ The service config is a JSON string of the following form: ``` { - // Load balancing policy name. + // Load balancing policy name (case insensitive). // Currently, the only selectable client-side policy provided with gRPC // is 'round_robin', but third parties may add their own policies. // This field is optional; if unset, the default behavior is to pick diff --git a/examples/BUILD b/examples/BUILD index 3e9e508ec28..0f18cfa9ba7 100644 --- a/examples/BUILD +++ b/examples/BUILD @@ -42,12 +42,12 @@ cc_binary( name = "greeter_client", srcs = ["cpp/helloworld/greeter_client.cc"], defines = ["BAZEL_BUILD"], - deps = [":helloworld"], + deps = [":helloworld", "//:grpc++"], ) cc_binary( name = "greeter_server", srcs = ["cpp/helloworld/greeter_server.cc"], defines = ["BAZEL_BUILD"], - deps = [":helloworld"], + deps = [":helloworld", "//:grpc++"], ) diff --git a/examples/cpp/helloworld/CMakeLists.txt b/examples/cpp/helloworld/CMakeLists.txt index 71a8db4f24f..49684a13b04 100644 --- a/examples/cpp/helloworld/CMakeLists.txt +++ b/examples/cpp/helloworld/CMakeLists.txt @@ -6,13 +6,29 @@ project(HelloWorld C CXX) if(NOT MSVC) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") +else() + add_definitions(-D_WIN32_WINNT=0x600) endif() # Protobuf -set(protobuf_MODULE_COMPATIBLE TRUE) -find_package(protobuf CONFIG REQUIRED) +# NOTE: we cannot use "CONFIG" mode here because protobuf-config.cmake +# is broken when used with CMAKE_INSTALL_PREFIX +find_package(Protobuf REQUIRED) message(STATUS "Using protobuf ${protobuf_VERSION}") +if(Protobuf_FOUND) + # Protobuf_FOUND is set for package type "CONFIG" + set(_PROTOBUF_LIBPROTOBUF protobuf::libprotobuf) + set(_PROTOBUF_PROTOC protobuf::protoc) +elseif(PROTOBUF_FOUND) + # PROTOBUF_FOUND is set for package type "MODULE" + set(_PROTOBUF_LIBPROTOBUF ${PROTOBUF_LIBRARIES}) + set(_PROTOBUF_PROTOC ${PROTOBUF_PROTOC_EXECUTABLE}) + include_directories(${PROTOBUF_INCLUDE_DIRS}) +else() + message(WARNING "Failed to locate libprotobuf and protoc!") +endif() + # gRPC find_package(gRPC CONFIG REQUIRED) message(STATUS "Using gRPC ${gRPC_VERSION}") @@ -31,7 +47,7 @@ set(hw_grpc_srcs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.grpc.pb.cc") set(hw_grpc_hdrs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.grpc.pb.h") add_custom_command( OUTPUT "${hw_grpc_srcs}" "${hw_grpc_hdrs}" - COMMAND protobuf::protoc + COMMAND ${_PROTOBUF_PROTOC} ARGS --grpc_out "${CMAKE_CURRENT_BINARY_DIR}" -I "${hw_proto_path}" --plugin=protoc-gen-grpc="${gRPC_CPP_PLUGIN_EXECUTABLE}" "${hw_proto}" @@ -48,6 +64,6 @@ foreach(_target ${hw_proto_srcs} ${hw_grpc_srcs}) target_link_libraries(${_target} - protobuf::libprotobuf + ${_PROTOBUF_LIBPROTOBUF} gRPC::grpc++_unsecure) endforeach() diff --git a/examples/php/README.md b/examples/php/README.md index d30cbdafd09..49703ce172c 100644 --- a/examples/php/README.md +++ b/examples/php/README.md @@ -41,10 +41,11 @@ TRY IT! $ node greeter_server.js ``` - - Run the client + - Generate proto files and run the client ``` $ cd examples/php + $ ./greeter_proto_gen.sh $ ./run_greeter_client.sh ``` diff --git a/examples/php/greeter_client.php b/examples/php/greeter_client.php index 981319a451e..bb94a085278 100644 --- a/examples/php/greeter_client.php +++ b/examples/php/greeter_client.php @@ -17,12 +17,14 @@ * */ +// php:generate protoc --proto_path=./../protos --php_out=./ --grpc_out=./ --plugin=protoc-gen-grpc=./../../bins/opt/grpc_php_plugin ./../protos/helloworld.proto + require dirname(__FILE__).'/vendor/autoload.php'; -// The following includes are needed when using protobuf 3.1.0 -// and will suppress warnings when using protobuf 3.2.0+ -@include_once dirname(__FILE__).'/helloworld.pb.php'; -@include_once dirname(__FILE__).'/helloworld_grpc_pb.php'; +@include_once dirname(__FILE__).'/Helloworld/GreeterClient.php'; +@include_once dirname(__FILE__).'/Helloworld/HelloReply.php'; +@include_once dirname(__FILE__).'/Helloworld/HelloRequest.php'; +@include_once dirname(__FILE__).'/GPBMetadata/Helloworld.php'; function greet($name) { diff --git a/tools/run_tests/helper_scripts/pre_build_node_electron.sh b/examples/php/greeter_proto_gen.sh similarity index 75% rename from tools/run_tests/helper_scripts/pre_build_node_electron.sh rename to examples/php/greeter_proto_gen.sh index 29394d294f6..a0d7b29c86e 100755 --- a/tools/run_tests/helper_scripts/pre_build_node_electron.sh +++ b/examples/php/greeter_proto_gen.sh @@ -1,6 +1,5 @@ #!/bin/bash - -# Copyright 2016 gRPC authors. +# Copyright 2017 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,11 +13,5 @@ # See the License for the specific language governing permissions and # limitations under the License. -ELECTRON_VERSION=$1 - -nvm install 8 -set -ex - -npm install xvfb-maybe +protoc --proto_path=./../protos --php_out=./ --grpc_out=./ --plugin=protoc-gen-grpc=./../../bins/opt/grpc_php_plugin ./../protos/helloworld.proto -npm install electron@$ELECTRON_VERSION diff --git a/examples/php/helloworld.pb.php b/examples/php/helloworld.pb.php deleted file mode 100644 index 757a4a58f5f..00000000000 --- a/examples/php/helloworld.pb.php +++ /dev/null @@ -1,58 +0,0 @@ -name; - } - - public function setName($var) - { - GPBUtil::checkString($var, True); - $this->name = $var; - } - -} - -class HelloReply extends \Google\Protobuf\Internal\Message -{ - private $message = ''; - - public function getMessage() - { - return $this->message; - } - - public function setMessage($var) - { - GPBUtil::checkString($var, True); - $this->message = $var; - } - -} - -$pool = DescriptorPool::getGeneratedPool(); - -$pool->internalAddGeneratedFile(hex2bin( - "0ae6010a1068656c6c6f776f726c642e70726f746f120a68656c6c6f776f" . - "726c64221c0a0c48656c6c6f52657175657374120c0a046e616d65180120" . - "012809221d0a0a48656c6c6f5265706c79120f0a076d6573736167651801" . - "2001280932490a0747726565746572123e0a0853617948656c6c6f12182e" . - "68656c6c6f776f726c642e48656c6c6f526571756573741a162e68656c6c" . - "6f776f726c642e48656c6c6f5265706c79220042360a1b696f2e67727063" . - "2e6578616d706c65732e68656c6c6f776f726c64420f48656c6c6f576f72" . - "6c6450726f746f5001a20203484c57620670726f746f33" -)); - diff --git a/examples/php/helloworld_grpc_pb.php b/examples/php/helloworld_grpc_pb.php deleted file mode 100644 index ba83ed26146..00000000000 --- a/examples/php/helloworld_grpc_pb.php +++ /dev/null @@ -1,49 +0,0 @@ -_simpleRequest('/helloworld.Greeter/SayHello', - $argument, - ['\Helloworld\HelloReply', 'decode'], - $metadata, $options); - } - - } - -} diff --git a/examples/php/route_guide/route_guide.pb.php b/examples/php/route_guide/route_guide.pb.php deleted file mode 100644 index 78f3ea6e2a7..00000000000 --- a/examples/php/route_guide/route_guide.pb.php +++ /dev/null @@ -1,209 +0,0 @@ -latitude; - } - - public function setLatitude($var) - { - GPBUtil::checkInt32($var); - $this->latitude = $var; - } - - public function getLongitude() - { - return $this->longitude; - } - - public function setLongitude($var) - { - GPBUtil::checkInt32($var); - $this->longitude = $var; - } - -} - -class Rectangle extends \Google\Protobuf\Internal\Message -{ - private $lo = null; - private $hi = null; - - public function getLo() - { - return $this->lo; - } - - public function setLo(&$var) - { - GPBUtil::checkMessage($var, \Routeguide\Point::class); - $this->lo = $var; - } - - public function getHi() - { - return $this->hi; - } - - public function setHi(&$var) - { - GPBUtil::checkMessage($var, \Routeguide\Point::class); - $this->hi = $var; - } - -} - -class Feature extends \Google\Protobuf\Internal\Message -{ - private $name = ''; - private $location = null; - - public function getName() - { - return $this->name; - } - - public function setName($var) - { - GPBUtil::checkString($var, True); - $this->name = $var; - } - - public function getLocation() - { - return $this->location; - } - - public function setLocation(&$var) - { - GPBUtil::checkMessage($var, \Routeguide\Point::class); - $this->location = $var; - } - -} - -class RouteNote extends \Google\Protobuf\Internal\Message -{ - private $location = null; - private $message = ''; - - public function getLocation() - { - return $this->location; - } - - public function setLocation(&$var) - { - GPBUtil::checkMessage($var, \Routeguide\Point::class); - $this->location = $var; - } - - public function getMessage() - { - return $this->message; - } - - public function setMessage($var) - { - GPBUtil::checkString($var, True); - $this->message = $var; - } - -} - -class RouteSummary extends \Google\Protobuf\Internal\Message -{ - private $point_count = 0; - private $feature_count = 0; - private $distance = 0; - private $elapsed_time = 0; - - public function getPointCount() - { - return $this->point_count; - } - - public function setPointCount($var) - { - GPBUtil::checkInt32($var); - $this->point_count = $var; - } - - public function getFeatureCount() - { - return $this->feature_count; - } - - public function setFeatureCount($var) - { - GPBUtil::checkInt32($var); - $this->feature_count = $var; - } - - public function getDistance() - { - return $this->distance; - } - - public function setDistance($var) - { - GPBUtil::checkInt32($var); - $this->distance = $var; - } - - public function getElapsedTime() - { - return $this->elapsed_time; - } - - public function setElapsedTime($var) - { - GPBUtil::checkInt32($var); - $this->elapsed_time = $var; - } - -} - -$pool = DescriptorPool::getGeneratedPool(); - -$pool->internalAddGeneratedFile(hex2bin( - "0ac5050a11726f7574655f67756964652e70726f746f120a726f75746567" . - "75696465222c0a05506f696e7412100a086c617469747564651801200128" . - "0512110a096c6f6e67697475646518022001280522490a0952656374616e" . - "676c65121d0a026c6f18012001280b32112e726f75746567756964652e50" . - "6f696e74121d0a02686918022001280b32112e726f75746567756964652e" . - "506f696e74223c0a0746656174757265120c0a046e616d65180120012809" . - "12230a086c6f636174696f6e18022001280b32112e726f75746567756964" . - "652e506f696e7422410a09526f7574654e6f746512230a086c6f63617469" . - "6f6e18012001280b32112e726f75746567756964652e506f696e74120f0a" . - "076d65737361676518022001280922620a0c526f75746553756d6d617279" . - "12130a0b706f696e745f636f756e7418012001280512150a0d6665617475" . - "72655f636f756e7418022001280512100a0864697374616e636518032001" . - "280512140a0c656c61707365645f74696d651804200128053285020a0a52" . - "6f757465477569646512360a0a4765744665617475726512112e726f7574" . - "6567756964652e506f696e741a132e726f75746567756964652e46656174" . - "7572652200123e0a0c4c697374466561747572657312152e726f75746567" . - "756964652e52656374616e676c651a132e726f75746567756964652e4665" . - "617475726522003001123e0a0b5265636f7264526f75746512112e726f75" . - "746567756964652e506f696e741a182e726f75746567756964652e526f75" . - "746553756d6d61727922002801123f0a09526f7574654368617412152e72" . - "6f75746567756964652e526f7574654e6f74651a152e726f757465677569" . - "64652e526f7574654e6f746522002801300142360a1b696f2e677270632e" . - "6578616d706c65732e726f7574656775696465420f526f75746547756964" . - "6550726f746f5001a20203525447620670726f746f33" -)); - diff --git a/examples/php/route_guide/route_guide_client.php b/examples/php/route_guide/route_guide_client.php index 8ac797722c7..92b2bacecd5 100644 --- a/examples/php/route_guide/route_guide_client.php +++ b/examples/php/route_guide/route_guide_client.php @@ -17,12 +17,9 @@ * */ -require dirname(__FILE__).'/../vendor/autoload.php'; +// php:generate protoc --proto_path=./../../protos --php_out=./ --grpc_out=./ --plugin=protoc-gen-grpc=./../../../bins/opt/grpc_php_plugin ./../../protos/route_guide.proto -// The following includes are needed when using protobuf 3.1.0 -// and will suppress warnings when using protobuf 3.2.0+ -@include_once dirname(__FILE__).'/route_guide.pb.php'; -@include_once dirname(__FILE__).'/route_guide_grpc_pb.php'; +require dirname(__FILE__).'/../vendor/autoload.php'; define('COORD_FACTOR', 1e7); @@ -38,9 +35,12 @@ function printFeature($feature) } else { $name_str = "feature called $name"; } - echo sprintf("Found %s \n at %f, %f\n", $name_str, + echo sprintf( + "Found %s \n at %f, %f\n", + $name_str, $feature->getLocation()->getLatitude() / COORD_FACTOR, - $feature->getLocation()->getLongitude() / COORD_FACTOR); + $feature->getLocation()->getLongitude() / COORD_FACTOR + ); } /** @@ -122,19 +122,24 @@ function runRecordRoute() $feature_name = $db[$index]['name']; $point->setLatitude($lat); $point->setLongitude($long); - echo sprintf("Visiting point %f, %f,\n with feature name: %s\n", - $lat / COORD_FACTOR, $long / COORD_FACTOR, - $feature_name ? $feature_name : ''); + echo sprintf( + "Visiting point %f, %f,\n with feature name: %s\n", + $lat / COORD_FACTOR, + $long / COORD_FACTOR, + $feature_name ? $feature_name : '' + ); usleep(rand(300000, 800000)); $call->write($point); } list($route_summary, $status) = $call->wait(); - echo sprintf("Finished trip with %d points\nPassed %d features\n". + echo sprintf( + "Finished trip with %d points\nPassed %d features\n". "Travelled %d meters\nIt took %d seconds\n", $route_summary->getPointCount(), $route_summary->getFeatureCount(), $route_summary->getDistance(), - $route_summary->getElapsedTime()); + $route_summary->getElapsedTime() + ); } /** @@ -166,8 +171,12 @@ function runRouteChat() $route_note->setLocation($point); $route_note->setMessage($message = $n[2]); - echo sprintf("Sending message: '%s' at (%d, %d)\n", - $message, $lat, $long); + echo sprintf( + "Sending message: '%s' at (%d, %d)\n", + $message, + $lat, + $long + ); // send a bunch of messages to the server $call->write($route_note); } @@ -175,10 +184,12 @@ function runRouteChat() // read from the server until there's no more while ($route_note_reply = $call->read()) { - echo sprintf("Previous left message at (%d, %d): '%s'\n", + echo sprintf( + "Previous left message at (%d, %d): '%s'\n", $route_note_reply->getLocation()->getLatitude(), $route_note_reply->getLocation()->getLongitude(), - $route_note_reply->getMessage()); + $route_note_reply->getMessage() + ); } } diff --git a/examples/php/route_guide/route_guide_grpc_pb.php b/examples/php/route_guide/route_guide_grpc_pb.php deleted file mode 100644 index e7a9cd39cd8..00000000000 --- a/examples/php/route_guide/route_guide_grpc_pb.php +++ /dev/null @@ -1,101 +0,0 @@ -_simpleRequest('/routeguide.RouteGuide/GetFeature', - $argument, - ['\Routeguide\Feature', 'decode'], - $metadata, $options); - } - - /** - * A server-to-client streaming RPC. - * - * Obtains the Features available within the given Rectangle. Results are - * streamed rather than returned at once (e.g. in a response message with a - * repeated field), as the rectangle may cover a large area and contain a - * huge number of features. - * @param \Routeguide\Rectangle $argument input argument - * @param array $metadata metadata - * @param array $options call options - */ - public function ListFeatures(\Routeguide\Rectangle $argument, - $metadata = [], $options = []) { - return $this->_serverStreamRequest('/routeguide.RouteGuide/ListFeatures', - $argument, - ['\Routeguide\Feature', 'decode'], - $metadata, $options); - } - - /** - * A client-to-server streaming RPC. - * - * Accepts a stream of Points on a route being traversed, returning a - * RouteSummary when traversal is completed. - * @param array $metadata metadata - * @param array $options call options - */ - public function RecordRoute($metadata = [], $options = []) { - return $this->_clientStreamRequest('/routeguide.RouteGuide/RecordRoute', - ['\Routeguide\RouteSummary','decode'], - $metadata, $options); - } - - /** - * A Bidirectional streaming RPC. - * - * Accepts a stream of RouteNotes sent while a route is being traversed, - * while receiving other RouteNotes (e.g. from other users). - * @param array $metadata metadata - * @param array $options call options - */ - public function RouteChat($metadata = [], $options = []) { - return $this->_bidiRequest('/routeguide.RouteGuide/RouteChat', - ['\Routeguide\RouteNote','decode'], - $metadata, $options); - } - - } - -} diff --git a/tools/run_tests/helper_scripts/pre_build_node.sh b/examples/php/route_guide/route_guide_proto_gen.sh similarity index 74% rename from tools/run_tests/helper_scripts/pre_build_node.sh rename to examples/php/route_guide/route_guide_proto_gen.sh index d4702b8705e..bfd7cdb725c 100755 --- a/tools/run_tests/helper_scripts/pre_build_node.sh +++ b/examples/php/route_guide/route_guide_proto_gen.sh @@ -1,5 +1,4 @@ #!/bin/bash - # Copyright 2015 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -NODE_VERSION=$1 -source ~/.nvm/nvm.sh - -nvm install $NODE_VERSION -set -ex - -export GRPC_CONFIG=${CONFIG:-opt} - -npm update --prefer-online - -npm install node-gyp-install -./node_modules/.bin/node-gyp-install +protoc --proto_path=./../../protos --php_out=./ --grpc_out=./ --plugin=protoc-gen-grpc=./../../../bins/opt/grpc_php_plugin ./../../protos/route_guide.proto diff --git a/examples/python/helloworld/helloworld_pb2.py b/examples/python/helloworld/helloworld_pb2.py index 6665b1f6878..e18ab9acc7a 100644 --- a/examples/python/helloworld/helloworld_pb2.py +++ b/examples/python/helloworld/helloworld_pb2.py @@ -21,7 +21,6 @@ DESCRIPTOR = _descriptor.FileDescriptor( syntax='proto3', serialized_pb=_b('\n\x10helloworld.proto\x12\nhelloworld\"\x1c\n\x0cHelloRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x01 \x01(\t2I\n\x07Greeter\x12>\n\x08SayHello\x12\x18.helloworld.HelloRequest\x1a\x16.helloworld.HelloReply\"\x00\x42\x36\n\x1bio.grpc.examples.helloworldB\x0fHelloWorldProtoP\x01\xa2\x02\x03HLWb\x06proto3') ) -_sym_db.RegisterFileDescriptor(DESCRIPTOR) @@ -89,6 +88,7 @@ _HELLOREPLY = _descriptor.Descriptor( DESCRIPTOR.message_types_by_name['HelloRequest'] = _HELLOREQUEST DESCRIPTOR.message_types_by_name['HelloReply'] = _HELLOREPLY +_sym_db.RegisterFileDescriptor(DESCRIPTOR) HelloRequest = _reflection.GeneratedProtocolMessageType('HelloRequest', (_message.Message,), dict( DESCRIPTOR = _HELLOREQUEST, @@ -107,123 +107,28 @@ _sym_db.RegisterMessage(HelloReply) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\033io.grpc.examples.helloworldB\017HelloWorldProtoP\001\242\002\003HLW')) -try: - # THESE ELEMENTS WILL BE DEPRECATED. - # Please use the generated *_pb2_grpc.py files instead. - import grpc - from grpc.framework.common import cardinality - from grpc.framework.interfaces.face import utilities as face_utilities - from grpc.beta import implementations as beta_implementations - from grpc.beta import interfaces as beta_interfaces - - - class GreeterStub(object): - """The greeting service definition. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.SayHello = channel.unary_unary( - '/helloworld.Greeter/SayHello', - request_serializer=HelloRequest.SerializeToString, - response_deserializer=HelloReply.FromString, - ) - - - class GreeterServicer(object): - """The greeting service definition. - """ - - def SayHello(self, request, context): - """Sends a greeting - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - - def add_GreeterServicer_to_server(servicer, server): - rpc_method_handlers = { - 'SayHello': grpc.unary_unary_rpc_method_handler( - servicer.SayHello, - request_deserializer=HelloRequest.FromString, - response_serializer=HelloReply.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - 'helloworld.Greeter', rpc_method_handlers) - server.add_generic_rpc_handlers((generic_handler,)) - - - class BetaGreeterServicer(object): - """The Beta API is deprecated for 0.15.0 and later. - - It is recommended to use the GA API (classes and functions in this - file not marked beta) for all further purposes. This class was generated - only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0.""" - """The greeting service definition. - """ - def SayHello(self, request, context): - """Sends a greeting - """ - context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) - - - class BetaGreeterStub(object): - """The Beta API is deprecated for 0.15.0 and later. - - It is recommended to use the GA API (classes and functions in this - file not marked beta) for all further purposes. This class was generated - only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0.""" - """The greeting service definition. - """ - def SayHello(self, request, timeout, metadata=None, with_call=False, protocol_options=None): - """Sends a greeting - """ - raise NotImplementedError() - SayHello.future = None - - - def beta_create_Greeter_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None): - """The Beta API is deprecated for 0.15.0 and later. - - It is recommended to use the GA API (classes and functions in this - file not marked beta) for all further purposes. This function was - generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0""" - request_deserializers = { - ('helloworld.Greeter', 'SayHello'): HelloRequest.FromString, - } - response_serializers = { - ('helloworld.Greeter', 'SayHello'): HelloReply.SerializeToString, - } - method_implementations = { - ('helloworld.Greeter', 'SayHello'): face_utilities.unary_unary_inline(servicer.SayHello), - } - server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout) - return beta_implementations.server(method_implementations, options=server_options) - - - def beta_create_Greeter_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None): - """The Beta API is deprecated for 0.15.0 and later. - - It is recommended to use the GA API (classes and functions in this - file not marked beta) for all further purposes. This function was - generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0""" - request_serializers = { - ('helloworld.Greeter', 'SayHello'): HelloRequest.SerializeToString, - } - response_deserializers = { - ('helloworld.Greeter', 'SayHello'): HelloReply.FromString, - } - cardinalities = { - 'SayHello': cardinality.Cardinality.UNARY_UNARY, - } - stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size) - return beta_implementations.dynamic_stub(channel, 'helloworld.Greeter', cardinalities, options=stub_options) -except ImportError: - pass + +_GREETER = _descriptor.ServiceDescriptor( + name='Greeter', + full_name='helloworld.Greeter', + file=DESCRIPTOR, + index=0, + options=None, + serialized_start=93, + serialized_end=166, + methods=[ + _descriptor.MethodDescriptor( + name='SayHello', + full_name='helloworld.Greeter.SayHello', + index=0, + containing_service=None, + input_type=_HELLOREQUEST, + output_type=_HELLOREPLY, + options=None, + ), +]) +_sym_db.RegisterServiceDescriptor(_GREETER) + +DESCRIPTOR.services_by_name['Greeter'] = _GREETER + # @@protoc_insertion_point(module_scope) diff --git a/examples/python/helloworld/helloworld_pb2_grpc.py b/examples/python/helloworld/helloworld_pb2_grpc.py index 682dc36cd89..18e07d16797 100644 --- a/examples/python/helloworld/helloworld_pb2_grpc.py +++ b/examples/python/helloworld/helloworld_pb2_grpc.py @@ -1,6 +1,5 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc -from grpc.framework.common import cardinality -from grpc.framework.interfaces.face import utilities as face_utilities import helloworld_pb2 as helloworld__pb2 diff --git a/examples/python/route_guide/route_guide_client.py b/examples/python/route_guide/route_guide_client.py index 653f0d02c62..a0e32fb6f53 100644 --- a/examples/python/route_guide/route_guide_client.py +++ b/examples/python/route_guide/route_guide_client.py @@ -17,7 +17,6 @@ from __future__ import print_function import random -import time import grpc @@ -66,7 +65,6 @@ def generate_route(feature_list): random_feature = feature_list[random.randint(0, len(feature_list) - 1)] print("Visiting point %s" % random_feature.location) yield random_feature.location - time.sleep(random.uniform(0.5, 1.5)) def guide_record_route(stub): @@ -91,7 +89,6 @@ def generate_messages(): for msg in messages: print("Sending %s at %s" % (msg.message, msg.location)) yield msg - time.sleep(random.uniform(0.5, 1.0)) def guide_route_chat(stub): diff --git a/examples/python/route_guide/route_guide_pb2.py b/examples/python/route_guide/route_guide_pb2.py index e6775eb8140..fbbc194a580 100644 --- a/examples/python/route_guide/route_guide_pb2.py +++ b/examples/python/route_guide/route_guide_pb2.py @@ -21,7 +21,6 @@ DESCRIPTOR = _descriptor.FileDescriptor( syntax='proto3', serialized_pb=_b('\n\x11route_guide.proto\x12\nrouteguide\",\n\x05Point\x12\x10\n\x08latitude\x18\x01 \x01(\x05\x12\x11\n\tlongitude\x18\x02 \x01(\x05\"I\n\tRectangle\x12\x1d\n\x02lo\x18\x01 \x01(\x0b\x32\x11.routeguide.Point\x12\x1d\n\x02hi\x18\x02 \x01(\x0b\x32\x11.routeguide.Point\"<\n\x07\x46\x65\x61ture\x12\x0c\n\x04name\x18\x01 \x01(\t\x12#\n\x08location\x18\x02 \x01(\x0b\x32\x11.routeguide.Point\"A\n\tRouteNote\x12#\n\x08location\x18\x01 \x01(\x0b\x32\x11.routeguide.Point\x12\x0f\n\x07message\x18\x02 \x01(\t\"b\n\x0cRouteSummary\x12\x13\n\x0bpoint_count\x18\x01 \x01(\x05\x12\x15\n\rfeature_count\x18\x02 \x01(\x05\x12\x10\n\x08\x64istance\x18\x03 \x01(\x05\x12\x14\n\x0c\x65lapsed_time\x18\x04 \x01(\x05\x32\x85\x02\n\nRouteGuide\x12\x36\n\nGetFeature\x12\x11.routeguide.Point\x1a\x13.routeguide.Feature\"\x00\x12>\n\x0cListFeatures\x12\x15.routeguide.Rectangle\x1a\x13.routeguide.Feature\"\x00\x30\x01\x12>\n\x0bRecordRoute\x12\x11.routeguide.Point\x1a\x18.routeguide.RouteSummary\"\x00(\x01\x12?\n\tRouteChat\x12\x15.routeguide.RouteNote\x1a\x15.routeguide.RouteNote\"\x00(\x01\x30\x01\x42\x36\n\x1bio.grpc.examples.routeguideB\x0fRouteGuideProtoP\x01\xa2\x02\x03RTGb\x06proto3') ) -_sym_db.RegisterFileDescriptor(DESCRIPTOR) @@ -238,6 +237,7 @@ DESCRIPTOR.message_types_by_name['Rectangle'] = _RECTANGLE DESCRIPTOR.message_types_by_name['Feature'] = _FEATURE DESCRIPTOR.message_types_by_name['RouteNote'] = _ROUTENOTE DESCRIPTOR.message_types_by_name['RouteSummary'] = _ROUTESUMMARY +_sym_db.RegisterFileDescriptor(DESCRIPTOR) Point = _reflection.GeneratedProtocolMessageType('Point', (_message.Message,), dict( DESCRIPTOR = _POINT, @@ -277,265 +277,55 @@ _sym_db.RegisterMessage(RouteSummary) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\033io.grpc.examples.routeguideB\017RouteGuideProtoP\001\242\002\003RTG')) -try: - # THESE ELEMENTS WILL BE DEPRECATED. - # Please use the generated *_pb2_grpc.py files instead. - import grpc - from grpc.framework.common import cardinality - from grpc.framework.interfaces.face import utilities as face_utilities - from grpc.beta import implementations as beta_implementations - from grpc.beta import interfaces as beta_interfaces - - - class RouteGuideStub(object): - """Interface exported by the server. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.GetFeature = channel.unary_unary( - '/routeguide.RouteGuide/GetFeature', - request_serializer=Point.SerializeToString, - response_deserializer=Feature.FromString, - ) - self.ListFeatures = channel.unary_stream( - '/routeguide.RouteGuide/ListFeatures', - request_serializer=Rectangle.SerializeToString, - response_deserializer=Feature.FromString, - ) - self.RecordRoute = channel.stream_unary( - '/routeguide.RouteGuide/RecordRoute', - request_serializer=Point.SerializeToString, - response_deserializer=RouteSummary.FromString, - ) - self.RouteChat = channel.stream_stream( - '/routeguide.RouteGuide/RouteChat', - request_serializer=RouteNote.SerializeToString, - response_deserializer=RouteNote.FromString, - ) - - - class RouteGuideServicer(object): - """Interface exported by the server. - """ - - def GetFeature(self, request, context): - """A simple RPC. - - Obtains the feature at a given position. - - A feature with an empty name is returned if there's no feature at the given - position. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - def ListFeatures(self, request, context): - """A server-to-client streaming RPC. - - Obtains the Features available within the given Rectangle. Results are - streamed rather than returned at once (e.g. in a response message with a - repeated field), as the rectangle may cover a large area and contain a - huge number of features. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - def RecordRoute(self, request_iterator, context): - """A client-to-server streaming RPC. - - Accepts a stream of Points on a route being traversed, returning a - RouteSummary when traversal is completed. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - def RouteChat(self, request_iterator, context): - """A Bidirectional streaming RPC. - - Accepts a stream of RouteNotes sent while a route is being traversed, - while receiving other RouteNotes (e.g. from other users). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details('Method not implemented!') - raise NotImplementedError('Method not implemented!') - - - def add_RouteGuideServicer_to_server(servicer, server): - rpc_method_handlers = { - 'GetFeature': grpc.unary_unary_rpc_method_handler( - servicer.GetFeature, - request_deserializer=Point.FromString, - response_serializer=Feature.SerializeToString, - ), - 'ListFeatures': grpc.unary_stream_rpc_method_handler( - servicer.ListFeatures, - request_deserializer=Rectangle.FromString, - response_serializer=Feature.SerializeToString, - ), - 'RecordRoute': grpc.stream_unary_rpc_method_handler( - servicer.RecordRoute, - request_deserializer=Point.FromString, - response_serializer=RouteSummary.SerializeToString, - ), - 'RouteChat': grpc.stream_stream_rpc_method_handler( - servicer.RouteChat, - request_deserializer=RouteNote.FromString, - response_serializer=RouteNote.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - 'routeguide.RouteGuide', rpc_method_handlers) - server.add_generic_rpc_handlers((generic_handler,)) - - - class BetaRouteGuideServicer(object): - """The Beta API is deprecated for 0.15.0 and later. - It is recommended to use the GA API (classes and functions in this - file not marked beta) for all further purposes. This class was generated - only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0.""" - """Interface exported by the server. - """ - def GetFeature(self, request, context): - """A simple RPC. - - Obtains the feature at a given position. - - A feature with an empty name is returned if there's no feature at the given - position. - """ - context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) - def ListFeatures(self, request, context): - """A server-to-client streaming RPC. - - Obtains the Features available within the given Rectangle. Results are - streamed rather than returned at once (e.g. in a response message with a - repeated field), as the rectangle may cover a large area and contain a - huge number of features. - """ - context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) - def RecordRoute(self, request_iterator, context): - """A client-to-server streaming RPC. - - Accepts a stream of Points on a route being traversed, returning a - RouteSummary when traversal is completed. - """ - context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) - def RouteChat(self, request_iterator, context): - """A Bidirectional streaming RPC. - - Accepts a stream of RouteNotes sent while a route is being traversed, - while receiving other RouteNotes (e.g. from other users). - """ - context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) - - - class BetaRouteGuideStub(object): - """The Beta API is deprecated for 0.15.0 and later. - - It is recommended to use the GA API (classes and functions in this - file not marked beta) for all further purposes. This class was generated - only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0.""" - """Interface exported by the server. - """ - def GetFeature(self, request, timeout, metadata=None, with_call=False, protocol_options=None): - """A simple RPC. - - Obtains the feature at a given position. - - A feature with an empty name is returned if there's no feature at the given - position. - """ - raise NotImplementedError() - GetFeature.future = None - def ListFeatures(self, request, timeout, metadata=None, with_call=False, protocol_options=None): - """A server-to-client streaming RPC. - - Obtains the Features available within the given Rectangle. Results are - streamed rather than returned at once (e.g. in a response message with a - repeated field), as the rectangle may cover a large area and contain a - huge number of features. - """ - raise NotImplementedError() - def RecordRoute(self, request_iterator, timeout, metadata=None, with_call=False, protocol_options=None): - """A client-to-server streaming RPC. - - Accepts a stream of Points on a route being traversed, returning a - RouteSummary when traversal is completed. - """ - raise NotImplementedError() - RecordRoute.future = None - def RouteChat(self, request_iterator, timeout, metadata=None, with_call=False, protocol_options=None): - """A Bidirectional streaming RPC. - - Accepts a stream of RouteNotes sent while a route is being traversed, - while receiving other RouteNotes (e.g. from other users). - """ - raise NotImplementedError() - - - def beta_create_RouteGuide_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None): - """The Beta API is deprecated for 0.15.0 and later. - - It is recommended to use the GA API (classes and functions in this - file not marked beta) for all further purposes. This function was - generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0""" - request_deserializers = { - ('routeguide.RouteGuide', 'GetFeature'): Point.FromString, - ('routeguide.RouteGuide', 'ListFeatures'): Rectangle.FromString, - ('routeguide.RouteGuide', 'RecordRoute'): Point.FromString, - ('routeguide.RouteGuide', 'RouteChat'): RouteNote.FromString, - } - response_serializers = { - ('routeguide.RouteGuide', 'GetFeature'): Feature.SerializeToString, - ('routeguide.RouteGuide', 'ListFeatures'): Feature.SerializeToString, - ('routeguide.RouteGuide', 'RecordRoute'): RouteSummary.SerializeToString, - ('routeguide.RouteGuide', 'RouteChat'): RouteNote.SerializeToString, - } - method_implementations = { - ('routeguide.RouteGuide', 'GetFeature'): face_utilities.unary_unary_inline(servicer.GetFeature), - ('routeguide.RouteGuide', 'ListFeatures'): face_utilities.unary_stream_inline(servicer.ListFeatures), - ('routeguide.RouteGuide', 'RecordRoute'): face_utilities.stream_unary_inline(servicer.RecordRoute), - ('routeguide.RouteGuide', 'RouteChat'): face_utilities.stream_stream_inline(servicer.RouteChat), - } - server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout) - return beta_implementations.server(method_implementations, options=server_options) - - - def beta_create_RouteGuide_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None): - """The Beta API is deprecated for 0.15.0 and later. +_ROUTEGUIDE = _descriptor.ServiceDescriptor( + name='RouteGuide', + full_name='routeguide.RouteGuide', + file=DESCRIPTOR, + index=0, + options=None, + serialized_start=384, + serialized_end=645, + methods=[ + _descriptor.MethodDescriptor( + name='GetFeature', + full_name='routeguide.RouteGuide.GetFeature', + index=0, + containing_service=None, + input_type=_POINT, + output_type=_FEATURE, + options=None, + ), + _descriptor.MethodDescriptor( + name='ListFeatures', + full_name='routeguide.RouteGuide.ListFeatures', + index=1, + containing_service=None, + input_type=_RECTANGLE, + output_type=_FEATURE, + options=None, + ), + _descriptor.MethodDescriptor( + name='RecordRoute', + full_name='routeguide.RouteGuide.RecordRoute', + index=2, + containing_service=None, + input_type=_POINT, + output_type=_ROUTESUMMARY, + options=None, + ), + _descriptor.MethodDescriptor( + name='RouteChat', + full_name='routeguide.RouteGuide.RouteChat', + index=3, + containing_service=None, + input_type=_ROUTENOTE, + output_type=_ROUTENOTE, + options=None, + ), +]) +_sym_db.RegisterServiceDescriptor(_ROUTEGUIDE) + +DESCRIPTOR.services_by_name['RouteGuide'] = _ROUTEGUIDE - It is recommended to use the GA API (classes and functions in this - file not marked beta) for all further purposes. This function was - generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0""" - request_serializers = { - ('routeguide.RouteGuide', 'GetFeature'): Point.SerializeToString, - ('routeguide.RouteGuide', 'ListFeatures'): Rectangle.SerializeToString, - ('routeguide.RouteGuide', 'RecordRoute'): Point.SerializeToString, - ('routeguide.RouteGuide', 'RouteChat'): RouteNote.SerializeToString, - } - response_deserializers = { - ('routeguide.RouteGuide', 'GetFeature'): Feature.FromString, - ('routeguide.RouteGuide', 'ListFeatures'): Feature.FromString, - ('routeguide.RouteGuide', 'RecordRoute'): RouteSummary.FromString, - ('routeguide.RouteGuide', 'RouteChat'): RouteNote.FromString, - } - cardinalities = { - 'GetFeature': cardinality.Cardinality.UNARY_UNARY, - 'ListFeatures': cardinality.Cardinality.UNARY_STREAM, - 'RecordRoute': cardinality.Cardinality.STREAM_UNARY, - 'RouteChat': cardinality.Cardinality.STREAM_STREAM, - } - stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size) - return beta_implementations.dynamic_stub(channel, 'routeguide.RouteGuide', cardinalities, options=stub_options) -except ImportError: - pass # @@protoc_insertion_point(module_scope) diff --git a/examples/python/route_guide/route_guide_pb2_grpc.py b/examples/python/route_guide/route_guide_pb2_grpc.py index 27b24c747db..05c1b793128 100644 --- a/examples/python/route_guide/route_guide_pb2_grpc.py +++ b/examples/python/route_guide/route_guide_pb2_grpc.py @@ -1,6 +1,5 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc -from grpc.framework.common import cardinality -from grpc.framework.interfaces.face import utilities as face_utilities import route_guide_pb2 as route__guide__pb2 diff --git a/gRPC-Core.podspec b/gRPC-Core.podspec index b2313a5c817..39b848414ad 100644 --- a/gRPC-Core.podspec +++ b/gRPC-Core.podspec @@ -22,7 +22,7 @@ Pod::Spec.new do |s| s.name = 'gRPC-Core' - version = '1.8.0-dev' + version = '1.9.0-dev' s.version = version s.summary = 'Core cross-platform gRPC library, written in C' s.homepage = 'https://grpc.io' @@ -85,6 +85,7 @@ Pod::Spec.new do |s| 'USE_HEADERMAP' => 'NO', 'ALWAYS_SEARCH_USER_PATHS' => 'NO', 'GCC_PREPROCESSOR_DEFINITIONS' => '"$(inherited)" "COCOAPODS=1" "PB_NO_PACKED_STRUCTS=1"', + 'CLANG_WARN_STRICT_PROTOTYPES' => 'NO', } s.default_subspecs = 'Interface', 'Implementation' @@ -112,7 +113,6 @@ Pod::Spec.new do |s| 'include/grpc/support/avl.h', 'include/grpc/support/cmdline.h', 'include/grpc/support/cpu.h', - 'include/grpc/support/histogram.h', 'include/grpc/support/host_port.h', 'include/grpc/support/log.h', 'include/grpc/support/log_windows.h', @@ -135,6 +135,7 @@ Pod::Spec.new do |s| 'include/grpc/impl/codegen/atm_gcc_atomic.h', 'include/grpc/impl/codegen/atm_gcc_sync.h', 'include/grpc/impl/codegen/atm_windows.h', + 'include/grpc/impl/codegen/fork.h', 'include/grpc/impl/codegen/gpr_slice.h', 'include/grpc/impl/codegen/gpr_types.h', 'include/grpc/impl/codegen/port_platform.h', @@ -156,6 +157,7 @@ Pod::Spec.new do |s| 'include/grpc/impl/codegen/atm_gcc_atomic.h', 'include/grpc/impl/codegen/atm_gcc_sync.h', 'include/grpc/impl/codegen/atm_windows.h', + 'include/grpc/impl/codegen/fork.h', 'include/grpc/impl/codegen/gpr_slice.h', 'include/grpc/impl/codegen/gpr_types.h', 'include/grpc/impl/codegen/port_platform.h', @@ -168,6 +170,7 @@ Pod::Spec.new do |s| 'include/grpc/byte_buffer.h', 'include/grpc/byte_buffer_reader.h', 'include/grpc/compression.h', + 'include/grpc/fork.h', 'include/grpc/grpc.h', 'include/grpc/grpc_posix.h', 'include/grpc/grpc_security_constants.h', @@ -187,19 +190,21 @@ Pod::Spec.new do |s| # To save you from scrolling, this is the last part of the podspec. ss.source_files = 'src/core/lib/profiling/timers.h', + 'src/core/lib/support/abstract.h', 'src/core/lib/support/arena.h', 'src/core/lib/support/atomic.h', 'src/core/lib/support/atomic_with_atm.h', 'src/core/lib/support/atomic_with_std.h', 'src/core/lib/support/env.h', + 'src/core/lib/support/fork.h', 'src/core/lib/support/manual_constructor.h', 'src/core/lib/support/memory.h', 'src/core/lib/support/mpscq.h', 'src/core/lib/support/murmur_hash.h', 'src/core/lib/support/spinlock.h', - 'src/core/lib/support/stack_lockfree.h', 'src/core/lib/support/string.h', 'src/core/lib/support/string_windows.h', + 'src/core/lib/support/thd_internal.h', 'src/core/lib/support/time_precise.h', 'src/core/lib/support/tmpfile.h', 'src/core/lib/profiling/basic_timers.cc', @@ -216,7 +221,7 @@ Pod::Spec.new do |s| 'src/core/lib/support/env_linux.cc', 'src/core/lib/support/env_posix.cc', 'src/core/lib/support/env_windows.cc', - 'src/core/lib/support/histogram.cc', + 'src/core/lib/support/fork.cc', 'src/core/lib/support/host_port.cc', 'src/core/lib/support/log.cc', 'src/core/lib/support/log_android.cc', @@ -225,7 +230,6 @@ Pod::Spec.new do |s| 'src/core/lib/support/log_windows.cc', 'src/core/lib/support/mpscq.cc', 'src/core/lib/support/murmur_hash.cc', - 'src/core/lib/support/stack_lockfree.cc', 'src/core/lib/support/string.cc', 'src/core/lib/support/string_posix.cc', 'src/core/lib/support/string_util_windows.cc', @@ -412,7 +416,9 @@ Pod::Spec.new do |s| 'src/core/lib/slice/slice_hash_table.h', 'src/core/lib/slice/slice_internal.h', 'src/core/lib/slice/slice_string_helpers.h', - 'src/core/lib/support/vector.h', + 'src/core/lib/support/debug_location.h', + 'src/core/lib/support/ref_counted.h', + 'src/core/lib/support/ref_counted_ptr.h', 'src/core/lib/surface/alarm_internal.h', 'src/core/lib/surface/api_trace.h', 'src/core/lib/surface/call.h', @@ -478,7 +484,6 @@ Pod::Spec.new do |s| 'src/core/lib/http/httpcli.cc', 'src/core/lib/http/parser.cc', 'src/core/lib/iomgr/call_combiner.cc', - 'src/core/lib/iomgr/closure.cc', 'src/core/lib/iomgr/combiner.cc', 'src/core/lib/iomgr/endpoint.cc', 'src/core/lib/iomgr/endpoint_pair_posix.cc', @@ -493,6 +498,8 @@ Pod::Spec.new do |s| 'src/core/lib/iomgr/ev_windows.cc', 'src/core/lib/iomgr/exec_ctx.cc', 'src/core/lib/iomgr/executor.cc', + 'src/core/lib/iomgr/fork_posix.cc', + 'src/core/lib/iomgr/fork_windows.cc', 'src/core/lib/iomgr/gethostname_fallback.cc', 'src/core/lib/iomgr/gethostname_host_name_max.cc', 'src/core/lib/iomgr/gethostname_sysconf.cc', @@ -707,19 +714,21 @@ Pod::Spec.new do |s| 'src/core/plugin_registry/grpc_plugin_registry.cc' ss.private_header_files = 'src/core/lib/profiling/timers.h', + 'src/core/lib/support/abstract.h', 'src/core/lib/support/arena.h', 'src/core/lib/support/atomic.h', 'src/core/lib/support/atomic_with_atm.h', 'src/core/lib/support/atomic_with_std.h', 'src/core/lib/support/env.h', + 'src/core/lib/support/fork.h', 'src/core/lib/support/manual_constructor.h', 'src/core/lib/support/memory.h', 'src/core/lib/support/mpscq.h', 'src/core/lib/support/murmur_hash.h', 'src/core/lib/support/spinlock.h', - 'src/core/lib/support/stack_lockfree.h', 'src/core/lib/support/string.h', 'src/core/lib/support/string_windows.h', + 'src/core/lib/support/thd_internal.h', 'src/core/lib/support/time_precise.h', 'src/core/lib/support/tmpfile.h', 'src/core/ext/transport/chttp2/transport/bin_decoder.h', @@ -887,7 +896,9 @@ Pod::Spec.new do |s| 'src/core/lib/slice/slice_hash_table.h', 'src/core/lib/slice/slice_internal.h', 'src/core/lib/slice/slice_string_helpers.h', - 'src/core/lib/support/vector.h', + 'src/core/lib/support/debug_location.h', + 'src/core/lib/support/ref_counted.h', + 'src/core/lib/support/ref_counted_ptr.h', 'src/core/lib/surface/alarm_internal.h', 'src/core/lib/surface/api_trace.h', 'src/core/lib/surface/call.h', @@ -958,17 +969,17 @@ Pod::Spec.new do |s| ss.dependency "#{s.name}/Interface", version ss.dependency "#{s.name}/Implementation", version - ss.source_files = 'test/core/end2end/cq_verifier.{c,h}', - 'test/core/end2end/end2end_tests.{c,h}', - 'test/core/end2end/end2end_test_utils.c', - 'test/core/end2end/tests/*.{c,h}', + ss.source_files = 'test/core/end2end/cq_verifier.{cc,h}', + 'test/core/end2end/end2end_tests.{cc,h}', + 'test/core/end2end/end2end_test_utils.cc', + 'test/core/end2end/tests/*.{cc,h}', 'test/core/end2end/fixtures/*.h', - 'test/core/end2end/data/*.{c,h}', + 'test/core/end2end/data/*.{cc,h}', 'test/core/util/debugger_macros.{cc,h}', - 'test/core/util/test_config.{c,h}', + 'test/core/util/test_config.{cc,h}', 'test/core/util/port.h', - 'test/core/util/port.c', - 'test/core/util/port_server_client.{c,h}' + 'test/core/util/port.cc', + 'test/core/util/port_server_client.{cc,h}' end # TODO (mxyan): Instead of this hack, add include path "third_party" to C core's include path? diff --git a/gRPC-ProtoRPC.podspec b/gRPC-ProtoRPC.podspec index db1e8db06c0..cb1c5480dab 100644 --- a/gRPC-ProtoRPC.podspec +++ b/gRPC-ProtoRPC.podspec @@ -21,7 +21,7 @@ Pod::Spec.new do |s| s.name = 'gRPC-ProtoRPC' - version = '1.8.0-dev' + version = '1.9.0-dev' s.version = version s.summary = 'RPC library for Protocol Buffers, based on gRPC' s.homepage = 'https://grpc.io' @@ -52,5 +52,6 @@ Pod::Spec.new do |s| 'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS=1', # This is needed by all pods that depend on gRPC-RxLibrary: 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES', + 'CLANG_WARN_STRICT_PROTOTYPES' => 'NO', } end diff --git a/gRPC-RxLibrary.podspec b/gRPC-RxLibrary.podspec index 36897790395..0f9abb6f4b3 100644 --- a/gRPC-RxLibrary.podspec +++ b/gRPC-RxLibrary.podspec @@ -21,7 +21,7 @@ Pod::Spec.new do |s| s.name = 'gRPC-RxLibrary' - version = '1.8.0-dev' + version = '1.9.0-dev' s.version = version s.summary = 'Reactive Extensions library for iOS/OSX.' s.homepage = 'https://grpc.io' @@ -44,4 +44,8 @@ Pod::Spec.new do |s| s.source_files = "#{src_dir}/*.{h,m}", "#{src_dir}/**/*.{h,m}" s.private_header_files = "#{src_dir}/private/*.h" s.header_mappings_dir = "#{src_dir}" + + s.pod_target_xcconfig = { + 'CLANG_WARN_STRICT_PROTOTYPES' => 'NO', + } end diff --git a/gRPC.podspec b/gRPC.podspec index 4c6cd3535f6..1f3a0a9950c 100644 --- a/gRPC.podspec +++ b/gRPC.podspec @@ -20,7 +20,7 @@ Pod::Spec.new do |s| s.name = 'gRPC' - version = '1.8.0-dev' + version = '1.9.0-dev' s.version = version s.summary = 'gRPC client library for iOS/OSX' s.homepage = 'https://grpc.io' @@ -50,6 +50,7 @@ Pod::Spec.new do |s| s.pod_target_xcconfig = { # This is needed by all pods that depend on gRPC-RxLibrary: 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES', + 'CLANG_WARN_STRICT_PROTOTYPES' => 'NO', } s.subspec 'Main' do |ss| diff --git a/grpc.def b/grpc.def index 710be52a3b4..d4a18ccefc1 100644 --- a/grpc.def +++ b/grpc.def @@ -149,7 +149,6 @@ EXPORTS grpc_slice_eq grpc_slice_cmp grpc_slice_str_cmp - grpc_slice_buf_cmp grpc_slice_buf_start_eq grpc_slice_rchr grpc_slice_chr @@ -201,21 +200,6 @@ EXPORTS gpr_cmdline_usage_string gpr_cpu_num_cores gpr_cpu_current_cpu - gpr_histogram_create - gpr_histogram_destroy - gpr_histogram_add - gpr_histogram_merge - gpr_histogram_percentile - gpr_histogram_mean - gpr_histogram_stddev - gpr_histogram_variance - gpr_histogram_maximum - gpr_histogram_minimum - gpr_histogram_count - gpr_histogram_sum - gpr_histogram_sum_of_squares - gpr_histogram_get_contents - gpr_histogram_merge_contents gpr_join_host_port gpr_split_host_port gpr_log_severity_string diff --git a/grpc.gemspec b/grpc.gemspec index 2fe2536cc76..d1859952619 100644 --- a/grpc.gemspec +++ b/grpc.gemspec @@ -52,7 +52,6 @@ Gem::Specification.new do |s| s.files += %w( include/grpc/support/avl.h ) s.files += %w( include/grpc/support/cmdline.h ) s.files += %w( include/grpc/support/cpu.h ) - s.files += %w( include/grpc/support/histogram.h ) s.files += %w( include/grpc/support/host_port.h ) s.files += %w( include/grpc/support/log.h ) s.files += %w( include/grpc/support/log_windows.h ) @@ -75,6 +74,7 @@ Gem::Specification.new do |s| s.files += %w( include/grpc/impl/codegen/atm_gcc_atomic.h ) s.files += %w( include/grpc/impl/codegen/atm_gcc_sync.h ) s.files += %w( include/grpc/impl/codegen/atm_windows.h ) + s.files += %w( include/grpc/impl/codegen/fork.h ) s.files += %w( include/grpc/impl/codegen/gpr_slice.h ) s.files += %w( include/grpc/impl/codegen/gpr_types.h ) s.files += %w( include/grpc/impl/codegen/port_platform.h ) @@ -84,19 +84,21 @@ Gem::Specification.new do |s| s.files += %w( include/grpc/impl/codegen/sync_posix.h ) s.files += %w( include/grpc/impl/codegen/sync_windows.h ) s.files += %w( src/core/lib/profiling/timers.h ) + s.files += %w( src/core/lib/support/abstract.h ) s.files += %w( src/core/lib/support/arena.h ) s.files += %w( src/core/lib/support/atomic.h ) s.files += %w( src/core/lib/support/atomic_with_atm.h ) s.files += %w( src/core/lib/support/atomic_with_std.h ) s.files += %w( src/core/lib/support/env.h ) + s.files += %w( src/core/lib/support/fork.h ) s.files += %w( src/core/lib/support/manual_constructor.h ) s.files += %w( src/core/lib/support/memory.h ) s.files += %w( src/core/lib/support/mpscq.h ) s.files += %w( src/core/lib/support/murmur_hash.h ) s.files += %w( src/core/lib/support/spinlock.h ) - s.files += %w( src/core/lib/support/stack_lockfree.h ) s.files += %w( src/core/lib/support/string.h ) s.files += %w( src/core/lib/support/string_windows.h ) + s.files += %w( src/core/lib/support/thd_internal.h ) s.files += %w( src/core/lib/support/time_precise.h ) s.files += %w( src/core/lib/support/tmpfile.h ) s.files += %w( src/core/lib/profiling/basic_timers.cc ) @@ -113,7 +115,7 @@ Gem::Specification.new do |s| s.files += %w( src/core/lib/support/env_linux.cc ) s.files += %w( src/core/lib/support/env_posix.cc ) s.files += %w( src/core/lib/support/env_windows.cc ) - s.files += %w( src/core/lib/support/histogram.cc ) + s.files += %w( src/core/lib/support/fork.cc ) s.files += %w( src/core/lib/support/host_port.cc ) s.files += %w( src/core/lib/support/log.cc ) s.files += %w( src/core/lib/support/log_android.cc ) @@ -122,7 +124,6 @@ Gem::Specification.new do |s| s.files += %w( src/core/lib/support/log_windows.cc ) s.files += %w( src/core/lib/support/mpscq.cc ) s.files += %w( src/core/lib/support/murmur_hash.cc ) - s.files += %w( src/core/lib/support/stack_lockfree.cc ) s.files += %w( src/core/lib/support/string.cc ) s.files += %w( src/core/lib/support/string_posix.cc ) s.files += %w( src/core/lib/support/string_util_windows.cc ) @@ -157,6 +158,7 @@ Gem::Specification.new do |s| s.files += %w( include/grpc/impl/codegen/atm_gcc_atomic.h ) s.files += %w( include/grpc/impl/codegen/atm_gcc_sync.h ) s.files += %w( include/grpc/impl/codegen/atm_windows.h ) + s.files += %w( include/grpc/impl/codegen/fork.h ) s.files += %w( include/grpc/impl/codegen/gpr_slice.h ) s.files += %w( include/grpc/impl/codegen/gpr_types.h ) s.files += %w( include/grpc/impl/codegen/port_platform.h ) @@ -169,6 +171,7 @@ Gem::Specification.new do |s| s.files += %w( include/grpc/byte_buffer.h ) s.files += %w( include/grpc/byte_buffer_reader.h ) s.files += %w( include/grpc/compression.h ) + s.files += %w( include/grpc/fork.h ) s.files += %w( include/grpc/grpc.h ) s.files += %w( include/grpc/grpc_posix.h ) s.files += %w( include/grpc/grpc_security_constants.h ) @@ -343,7 +346,9 @@ Gem::Specification.new do |s| s.files += %w( src/core/lib/slice/slice_hash_table.h ) s.files += %w( src/core/lib/slice/slice_internal.h ) s.files += %w( src/core/lib/slice/slice_string_helpers.h ) - s.files += %w( src/core/lib/support/vector.h ) + s.files += %w( src/core/lib/support/debug_location.h ) + s.files += %w( src/core/lib/support/ref_counted.h ) + s.files += %w( src/core/lib/support/ref_counted_ptr.h ) s.files += %w( src/core/lib/surface/alarm_internal.h ) s.files += %w( src/core/lib/surface/api_trace.h ) s.files += %w( src/core/lib/surface/call.h ) @@ -413,7 +418,6 @@ Gem::Specification.new do |s| s.files += %w( src/core/lib/http/httpcli.cc ) s.files += %w( src/core/lib/http/parser.cc ) s.files += %w( src/core/lib/iomgr/call_combiner.cc ) - s.files += %w( src/core/lib/iomgr/closure.cc ) s.files += %w( src/core/lib/iomgr/combiner.cc ) s.files += %w( src/core/lib/iomgr/endpoint.cc ) s.files += %w( src/core/lib/iomgr/endpoint_pair_posix.cc ) @@ -428,6 +432,8 @@ Gem::Specification.new do |s| s.files += %w( src/core/lib/iomgr/ev_windows.cc ) s.files += %w( src/core/lib/iomgr/exec_ctx.cc ) s.files += %w( src/core/lib/iomgr/executor.cc ) + s.files += %w( src/core/lib/iomgr/fork_posix.cc ) + s.files += %w( src/core/lib/iomgr/fork_windows.cc ) s.files += %w( src/core/lib/iomgr/gethostname_fallback.cc ) s.files += %w( src/core/lib/iomgr/gethostname_host_name_max.cc ) s.files += %w( src/core/lib/iomgr/gethostname_sysconf.cc ) diff --git a/grpc.gyp b/grpc.gyp index 32b6dc2cb83..c34206b1a5d 100644 --- a/grpc.gyp +++ b/grpc.gyp @@ -57,7 +57,6 @@ '-Wno-long-long', '-Wno-unused-parameter', '-DOSATOMIC_USE_INLINED=1', - '-Ithird_party/abseil-cpp', ], 'ldflags': [ '-g', @@ -135,7 +134,6 @@ '-Wno-long-long', '-Wno-unused-parameter', '-DOSATOMIC_USE_INLINED=1', - '-Ithird_party/abseil-cpp', ], 'OTHER_CPLUSPLUSFLAGS': [ '-g', @@ -145,7 +143,6 @@ '-Wno-long-long', '-Wno-unused-parameter', '-DOSATOMIC_USE_INLINED=1', - '-Ithird_party/abseil-cpp', '-stdlib=libc++', '-std=c++11', '-Wno-error=deprecated-declarations' @@ -175,7 +172,7 @@ 'src/core/lib/support/env_linux.cc', 'src/core/lib/support/env_posix.cc', 'src/core/lib/support/env_windows.cc', - 'src/core/lib/support/histogram.cc', + 'src/core/lib/support/fork.cc', 'src/core/lib/support/host_port.cc', 'src/core/lib/support/log.cc', 'src/core/lib/support/log_android.cc', @@ -184,7 +181,6 @@ 'src/core/lib/support/log_windows.cc', 'src/core/lib/support/mpscq.cc', 'src/core/lib/support/murmur_hash.cc', - 'src/core/lib/support/stack_lockfree.cc', 'src/core/lib/support/string.cc', 'src/core/lib/support/string_posix.cc', 'src/core/lib/support/string_util_windows.cc', @@ -215,7 +211,7 @@ 'gpr', ], 'sources': [ - 'test/core/util/test_config.c', + 'test/core/util/test_config.cc', ], }, { @@ -245,7 +241,6 @@ 'src/core/lib/http/httpcli.cc', 'src/core/lib/http/parser.cc', 'src/core/lib/iomgr/call_combiner.cc', - 'src/core/lib/iomgr/closure.cc', 'src/core/lib/iomgr/combiner.cc', 'src/core/lib/iomgr/endpoint.cc', 'src/core/lib/iomgr/endpoint_pair_posix.cc', @@ -260,6 +255,8 @@ 'src/core/lib/iomgr/ev_windows.cc', 'src/core/lib/iomgr/exec_ctx.cc', 'src/core/lib/iomgr/executor.cc', + 'src/core/lib/iomgr/fork_posix.cc', + 'src/core/lib/iomgr/fork_windows.cc', 'src/core/lib/iomgr/gethostname_fallback.cc', 'src/core/lib/iomgr/gethostname_host_name_max.cc', 'src/core/lib/iomgr/gethostname_sysconf.cc', @@ -496,26 +493,29 @@ 'grpc', ], 'sources': [ - 'test/core/end2end/data/client_certs.c', - 'test/core/end2end/data/server1_cert.c', - 'test/core/end2end/data/server1_key.c', - 'test/core/end2end/data/test_root_cert.c', - 'test/core/security/oauth2_utils.c', + 'test/core/end2end/data/client_certs.cc', + 'test/core/end2end/data/server1_cert.cc', + 'test/core/end2end/data/server1_key.cc', + 'test/core/end2end/data/test_root_cert.cc', + 'test/core/security/oauth2_utils.cc', 'src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc', - 'test/core/end2end/cq_verifier.c', - 'test/core/end2end/fixtures/http_proxy_fixture.c', - 'test/core/end2end/fixtures/proxy.c', - 'test/core/iomgr/endpoint_tests.c', + 'test/core/end2end/cq_verifier.cc', + 'test/core/end2end/fixtures/http_proxy_fixture.cc', + 'test/core/end2end/fixtures/proxy.cc', + 'test/core/iomgr/endpoint_tests.cc', 'test/core/util/debugger_macros.cc', - 'test/core/util/grpc_profiler.c', - 'test/core/util/memory_counters.c', - 'test/core/util/mock_endpoint.c', - 'test/core/util/parse_hexstring.c', - 'test/core/util/passthru_endpoint.c', - 'test/core/util/port.c', - 'test/core/util/port_server_client.c', - 'test/core/util/slice_splitter.c', - 'test/core/util/trickle_endpoint.c', + 'test/core/util/grpc_profiler.cc', + 'test/core/util/histogram.cc', + 'test/core/util/memory_counters.cc', + 'test/core/util/mock_endpoint.cc', + 'test/core/util/parse_hexstring.cc', + 'test/core/util/passthru_endpoint.cc', + 'test/core/util/port.cc', + 'test/core/util/port_isolated_runtime_environment.cc', + 'test/core/util/port_server_client.cc', + 'test/core/util/slice_splitter.cc', + 'test/core/util/tracer_util.cc', + 'test/core/util/trickle_endpoint.cc', 'src/core/lib/backoff/backoff.cc', 'src/core/lib/channel/channel_args.cc', 'src/core/lib/channel/channel_stack.cc', @@ -535,7 +535,6 @@ 'src/core/lib/http/httpcli.cc', 'src/core/lib/http/parser.cc', 'src/core/lib/iomgr/call_combiner.cc', - 'src/core/lib/iomgr/closure.cc', 'src/core/lib/iomgr/combiner.cc', 'src/core/lib/iomgr/endpoint.cc', 'src/core/lib/iomgr/endpoint_pair_posix.cc', @@ -550,6 +549,8 @@ 'src/core/lib/iomgr/ev_windows.cc', 'src/core/lib/iomgr/exec_ctx.cc', 'src/core/lib/iomgr/executor.cc', + 'src/core/lib/iomgr/fork_posix.cc', + 'src/core/lib/iomgr/fork_windows.cc', 'src/core/lib/iomgr/gethostname_fallback.cc', 'src/core/lib/iomgr/gethostname_host_name_max.cc', 'src/core/lib/iomgr/gethostname_sysconf.cc', @@ -710,20 +711,23 @@ ], 'sources': [ 'src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc', - 'test/core/end2end/cq_verifier.c', - 'test/core/end2end/fixtures/http_proxy_fixture.c', - 'test/core/end2end/fixtures/proxy.c', - 'test/core/iomgr/endpoint_tests.c', + 'test/core/end2end/cq_verifier.cc', + 'test/core/end2end/fixtures/http_proxy_fixture.cc', + 'test/core/end2end/fixtures/proxy.cc', + 'test/core/iomgr/endpoint_tests.cc', 'test/core/util/debugger_macros.cc', - 'test/core/util/grpc_profiler.c', - 'test/core/util/memory_counters.c', - 'test/core/util/mock_endpoint.c', - 'test/core/util/parse_hexstring.c', - 'test/core/util/passthru_endpoint.c', - 'test/core/util/port.c', - 'test/core/util/port_server_client.c', - 'test/core/util/slice_splitter.c', - 'test/core/util/trickle_endpoint.c', + 'test/core/util/grpc_profiler.cc', + 'test/core/util/histogram.cc', + 'test/core/util/memory_counters.cc', + 'test/core/util/mock_endpoint.cc', + 'test/core/util/parse_hexstring.cc', + 'test/core/util/passthru_endpoint.cc', + 'test/core/util/port.cc', + 'test/core/util/port_isolated_runtime_environment.cc', + 'test/core/util/port_server_client.cc', + 'test/core/util/slice_splitter.cc', + 'test/core/util/tracer_util.cc', + 'test/core/util/trickle_endpoint.cc', 'src/core/lib/backoff/backoff.cc', 'src/core/lib/channel/channel_args.cc', 'src/core/lib/channel/channel_stack.cc', @@ -743,7 +747,6 @@ 'src/core/lib/http/httpcli.cc', 'src/core/lib/http/parser.cc', 'src/core/lib/iomgr/call_combiner.cc', - 'src/core/lib/iomgr/closure.cc', 'src/core/lib/iomgr/combiner.cc', 'src/core/lib/iomgr/endpoint.cc', 'src/core/lib/iomgr/endpoint_pair_posix.cc', @@ -758,6 +761,8 @@ 'src/core/lib/iomgr/ev_windows.cc', 'src/core/lib/iomgr/exec_ctx.cc', 'src/core/lib/iomgr/executor.cc', + 'src/core/lib/iomgr/fork_posix.cc', + 'src/core/lib/iomgr/fork_windows.cc', 'src/core/lib/iomgr/gethostname_fallback.cc', 'src/core/lib/iomgr/gethostname_host_name_max.cc', 'src/core/lib/iomgr/gethostname_sysconf.cc', @@ -936,7 +941,6 @@ 'src/core/lib/http/httpcli.cc', 'src/core/lib/http/parser.cc', 'src/core/lib/iomgr/call_combiner.cc', - 'src/core/lib/iomgr/closure.cc', 'src/core/lib/iomgr/combiner.cc', 'src/core/lib/iomgr/endpoint.cc', 'src/core/lib/iomgr/endpoint_pair_posix.cc', @@ -951,6 +955,8 @@ 'src/core/lib/iomgr/ev_windows.cc', 'src/core/lib/iomgr/exec_ctx.cc', 'src/core/lib/iomgr/executor.cc', + 'src/core/lib/iomgr/fork_posix.cc', + 'src/core/lib/iomgr/fork_windows.cc', 'src/core/lib/iomgr/gethostname_fallback.cc', 'src/core/lib/iomgr/gethostname_host_name_max.cc', 'src/core/lib/iomgr/gethostname_sysconf.cc', @@ -1147,7 +1153,7 @@ 'gpr', ], 'sources': [ - 'test/core/util/reconnect_server.c', + 'test/core/util/reconnect_server.cc', ], }, { @@ -1160,7 +1166,7 @@ 'gpr', ], 'sources': [ - 'test/core/util/test_tcp_server.c', + 'test/core/util/test_tcp_server.cc', ], }, { @@ -2337,7 +2343,7 @@ 'gpr', ], 'sources': [ - 'test/core/bad_client/bad_client.c', + 'test/core/bad_client/bad_client.cc', ], }, { @@ -2350,67 +2356,67 @@ 'gpr', ], 'sources': [ - 'test/core/end2end/end2end_tests.c', - 'test/core/end2end/end2end_test_utils.c', - 'test/core/end2end/tests/authority_not_supported.c', - 'test/core/end2end/tests/bad_hostname.c', - 'test/core/end2end/tests/bad_ping.c', - 'test/core/end2end/tests/binary_metadata.c', - 'test/core/end2end/tests/call_creds.c', - 'test/core/end2end/tests/cancel_after_accept.c', - 'test/core/end2end/tests/cancel_after_client_done.c', - 'test/core/end2end/tests/cancel_after_invoke.c', - 'test/core/end2end/tests/cancel_after_round_trip.c', - 'test/core/end2end/tests/cancel_before_invoke.c', - 'test/core/end2end/tests/cancel_in_a_vacuum.c', - 'test/core/end2end/tests/cancel_with_status.c', - 'test/core/end2end/tests/compressed_payload.c', - 'test/core/end2end/tests/connectivity.c', - 'test/core/end2end/tests/default_host.c', - 'test/core/end2end/tests/disappearing_server.c', - 'test/core/end2end/tests/empty_batch.c', - 'test/core/end2end/tests/filter_call_init_fails.c', - 'test/core/end2end/tests/filter_causes_close.c', - 'test/core/end2end/tests/filter_latency.c', - 'test/core/end2end/tests/graceful_server_shutdown.c', - 'test/core/end2end/tests/high_initial_seqno.c', - 'test/core/end2end/tests/hpack_size.c', - 'test/core/end2end/tests/idempotent_request.c', - 'test/core/end2end/tests/invoke_large_request.c', - 'test/core/end2end/tests/keepalive_timeout.c', - 'test/core/end2end/tests/large_metadata.c', - 'test/core/end2end/tests/load_reporting_hook.c', - 'test/core/end2end/tests/max_concurrent_streams.c', - 'test/core/end2end/tests/max_connection_age.c', - 'test/core/end2end/tests/max_connection_idle.c', - 'test/core/end2end/tests/max_message_length.c', - 'test/core/end2end/tests/negative_deadline.c', - 'test/core/end2end/tests/network_status_change.c', - 'test/core/end2end/tests/no_logging.c', - 'test/core/end2end/tests/no_op.c', - 'test/core/end2end/tests/payload.c', - 'test/core/end2end/tests/ping.c', - 'test/core/end2end/tests/ping_pong_streaming.c', - 'test/core/end2end/tests/proxy_auth.c', - 'test/core/end2end/tests/registered_call.c', - 'test/core/end2end/tests/request_with_flags.c', - 'test/core/end2end/tests/request_with_payload.c', - 'test/core/end2end/tests/resource_quota_server.c', - 'test/core/end2end/tests/server_finishes_request.c', - 'test/core/end2end/tests/shutdown_finishes_calls.c', - 'test/core/end2end/tests/shutdown_finishes_tags.c', - 'test/core/end2end/tests/simple_cacheable_request.c', - 'test/core/end2end/tests/simple_delayed_request.c', - 'test/core/end2end/tests/simple_metadata.c', - 'test/core/end2end/tests/simple_request.c', - 'test/core/end2end/tests/stream_compression_compressed_payload.c', - 'test/core/end2end/tests/stream_compression_payload.c', - 'test/core/end2end/tests/stream_compression_ping_pong_streaming.c', - 'test/core/end2end/tests/streaming_error_response.c', - 'test/core/end2end/tests/trailing_metadata.c', - 'test/core/end2end/tests/workaround_cronet_compression.c', - 'test/core/end2end/tests/write_buffering.c', - 'test/core/end2end/tests/write_buffering_at_end.c', + 'test/core/end2end/end2end_tests.cc', + 'test/core/end2end/end2end_test_utils.cc', + 'test/core/end2end/tests/authority_not_supported.cc', + 'test/core/end2end/tests/bad_hostname.cc', + 'test/core/end2end/tests/bad_ping.cc', + 'test/core/end2end/tests/binary_metadata.cc', + 'test/core/end2end/tests/call_creds.cc', + 'test/core/end2end/tests/cancel_after_accept.cc', + 'test/core/end2end/tests/cancel_after_client_done.cc', + 'test/core/end2end/tests/cancel_after_invoke.cc', + 'test/core/end2end/tests/cancel_after_round_trip.cc', + 'test/core/end2end/tests/cancel_before_invoke.cc', + 'test/core/end2end/tests/cancel_in_a_vacuum.cc', + 'test/core/end2end/tests/cancel_with_status.cc', + 'test/core/end2end/tests/compressed_payload.cc', + 'test/core/end2end/tests/connectivity.cc', + 'test/core/end2end/tests/default_host.cc', + 'test/core/end2end/tests/disappearing_server.cc', + 'test/core/end2end/tests/empty_batch.cc', + 'test/core/end2end/tests/filter_call_init_fails.cc', + 'test/core/end2end/tests/filter_causes_close.cc', + 'test/core/end2end/tests/filter_latency.cc', + 'test/core/end2end/tests/graceful_server_shutdown.cc', + 'test/core/end2end/tests/high_initial_seqno.cc', + 'test/core/end2end/tests/hpack_size.cc', + 'test/core/end2end/tests/idempotent_request.cc', + 'test/core/end2end/tests/invoke_large_request.cc', + 'test/core/end2end/tests/keepalive_timeout.cc', + 'test/core/end2end/tests/large_metadata.cc', + 'test/core/end2end/tests/load_reporting_hook.cc', + 'test/core/end2end/tests/max_concurrent_streams.cc', + 'test/core/end2end/tests/max_connection_age.cc', + 'test/core/end2end/tests/max_connection_idle.cc', + 'test/core/end2end/tests/max_message_length.cc', + 'test/core/end2end/tests/negative_deadline.cc', + 'test/core/end2end/tests/network_status_change.cc', + 'test/core/end2end/tests/no_logging.cc', + 'test/core/end2end/tests/no_op.cc', + 'test/core/end2end/tests/payload.cc', + 'test/core/end2end/tests/ping.cc', + 'test/core/end2end/tests/ping_pong_streaming.cc', + 'test/core/end2end/tests/proxy_auth.cc', + 'test/core/end2end/tests/registered_call.cc', + 'test/core/end2end/tests/request_with_flags.cc', + 'test/core/end2end/tests/request_with_payload.cc', + 'test/core/end2end/tests/resource_quota_server.cc', + 'test/core/end2end/tests/server_finishes_request.cc', + 'test/core/end2end/tests/shutdown_finishes_calls.cc', + 'test/core/end2end/tests/shutdown_finishes_tags.cc', + 'test/core/end2end/tests/simple_cacheable_request.cc', + 'test/core/end2end/tests/simple_delayed_request.cc', + 'test/core/end2end/tests/simple_metadata.cc', + 'test/core/end2end/tests/simple_request.cc', + 'test/core/end2end/tests/stream_compression_compressed_payload.cc', + 'test/core/end2end/tests/stream_compression_payload.cc', + 'test/core/end2end/tests/stream_compression_ping_pong_streaming.cc', + 'test/core/end2end/tests/streaming_error_response.cc', + 'test/core/end2end/tests/trailing_metadata.cc', + 'test/core/end2end/tests/workaround_cronet_compression.cc', + 'test/core/end2end/tests/write_buffering.cc', + 'test/core/end2end/tests/write_buffering_at_end.cc', ], }, { @@ -2423,66 +2429,66 @@ 'gpr', ], 'sources': [ - 'test/core/end2end/end2end_nosec_tests.c', - 'test/core/end2end/end2end_test_utils.c', - 'test/core/end2end/tests/authority_not_supported.c', - 'test/core/end2end/tests/bad_hostname.c', - 'test/core/end2end/tests/bad_ping.c', - 'test/core/end2end/tests/binary_metadata.c', - 'test/core/end2end/tests/cancel_after_accept.c', - 'test/core/end2end/tests/cancel_after_client_done.c', - 'test/core/end2end/tests/cancel_after_invoke.c', - 'test/core/end2end/tests/cancel_after_round_trip.c', - 'test/core/end2end/tests/cancel_before_invoke.c', - 'test/core/end2end/tests/cancel_in_a_vacuum.c', - 'test/core/end2end/tests/cancel_with_status.c', - 'test/core/end2end/tests/compressed_payload.c', - 'test/core/end2end/tests/connectivity.c', - 'test/core/end2end/tests/default_host.c', - 'test/core/end2end/tests/disappearing_server.c', - 'test/core/end2end/tests/empty_batch.c', - 'test/core/end2end/tests/filter_call_init_fails.c', - 'test/core/end2end/tests/filter_causes_close.c', - 'test/core/end2end/tests/filter_latency.c', - 'test/core/end2end/tests/graceful_server_shutdown.c', - 'test/core/end2end/tests/high_initial_seqno.c', - 'test/core/end2end/tests/hpack_size.c', - 'test/core/end2end/tests/idempotent_request.c', - 'test/core/end2end/tests/invoke_large_request.c', - 'test/core/end2end/tests/keepalive_timeout.c', - 'test/core/end2end/tests/large_metadata.c', - 'test/core/end2end/tests/load_reporting_hook.c', - 'test/core/end2end/tests/max_concurrent_streams.c', - 'test/core/end2end/tests/max_connection_age.c', - 'test/core/end2end/tests/max_connection_idle.c', - 'test/core/end2end/tests/max_message_length.c', - 'test/core/end2end/tests/negative_deadline.c', - 'test/core/end2end/tests/network_status_change.c', - 'test/core/end2end/tests/no_logging.c', - 'test/core/end2end/tests/no_op.c', - 'test/core/end2end/tests/payload.c', - 'test/core/end2end/tests/ping.c', - 'test/core/end2end/tests/ping_pong_streaming.c', - 'test/core/end2end/tests/proxy_auth.c', - 'test/core/end2end/tests/registered_call.c', - 'test/core/end2end/tests/request_with_flags.c', - 'test/core/end2end/tests/request_with_payload.c', - 'test/core/end2end/tests/resource_quota_server.c', - 'test/core/end2end/tests/server_finishes_request.c', - 'test/core/end2end/tests/shutdown_finishes_calls.c', - 'test/core/end2end/tests/shutdown_finishes_tags.c', - 'test/core/end2end/tests/simple_cacheable_request.c', - 'test/core/end2end/tests/simple_delayed_request.c', - 'test/core/end2end/tests/simple_metadata.c', - 'test/core/end2end/tests/simple_request.c', - 'test/core/end2end/tests/stream_compression_compressed_payload.c', - 'test/core/end2end/tests/stream_compression_payload.c', - 'test/core/end2end/tests/stream_compression_ping_pong_streaming.c', - 'test/core/end2end/tests/streaming_error_response.c', - 'test/core/end2end/tests/trailing_metadata.c', - 'test/core/end2end/tests/workaround_cronet_compression.c', - 'test/core/end2end/tests/write_buffering.c', - 'test/core/end2end/tests/write_buffering_at_end.c', + 'test/core/end2end/end2end_nosec_tests.cc', + 'test/core/end2end/end2end_test_utils.cc', + 'test/core/end2end/tests/authority_not_supported.cc', + 'test/core/end2end/tests/bad_hostname.cc', + 'test/core/end2end/tests/bad_ping.cc', + 'test/core/end2end/tests/binary_metadata.cc', + 'test/core/end2end/tests/cancel_after_accept.cc', + 'test/core/end2end/tests/cancel_after_client_done.cc', + 'test/core/end2end/tests/cancel_after_invoke.cc', + 'test/core/end2end/tests/cancel_after_round_trip.cc', + 'test/core/end2end/tests/cancel_before_invoke.cc', + 'test/core/end2end/tests/cancel_in_a_vacuum.cc', + 'test/core/end2end/tests/cancel_with_status.cc', + 'test/core/end2end/tests/compressed_payload.cc', + 'test/core/end2end/tests/connectivity.cc', + 'test/core/end2end/tests/default_host.cc', + 'test/core/end2end/tests/disappearing_server.cc', + 'test/core/end2end/tests/empty_batch.cc', + 'test/core/end2end/tests/filter_call_init_fails.cc', + 'test/core/end2end/tests/filter_causes_close.cc', + 'test/core/end2end/tests/filter_latency.cc', + 'test/core/end2end/tests/graceful_server_shutdown.cc', + 'test/core/end2end/tests/high_initial_seqno.cc', + 'test/core/end2end/tests/hpack_size.cc', + 'test/core/end2end/tests/idempotent_request.cc', + 'test/core/end2end/tests/invoke_large_request.cc', + 'test/core/end2end/tests/keepalive_timeout.cc', + 'test/core/end2end/tests/large_metadata.cc', + 'test/core/end2end/tests/load_reporting_hook.cc', + 'test/core/end2end/tests/max_concurrent_streams.cc', + 'test/core/end2end/tests/max_connection_age.cc', + 'test/core/end2end/tests/max_connection_idle.cc', + 'test/core/end2end/tests/max_message_length.cc', + 'test/core/end2end/tests/negative_deadline.cc', + 'test/core/end2end/tests/network_status_change.cc', + 'test/core/end2end/tests/no_logging.cc', + 'test/core/end2end/tests/no_op.cc', + 'test/core/end2end/tests/payload.cc', + 'test/core/end2end/tests/ping.cc', + 'test/core/end2end/tests/ping_pong_streaming.cc', + 'test/core/end2end/tests/proxy_auth.cc', + 'test/core/end2end/tests/registered_call.cc', + 'test/core/end2end/tests/request_with_flags.cc', + 'test/core/end2end/tests/request_with_payload.cc', + 'test/core/end2end/tests/resource_quota_server.cc', + 'test/core/end2end/tests/server_finishes_request.cc', + 'test/core/end2end/tests/shutdown_finishes_calls.cc', + 'test/core/end2end/tests/shutdown_finishes_tags.cc', + 'test/core/end2end/tests/simple_cacheable_request.cc', + 'test/core/end2end/tests/simple_delayed_request.cc', + 'test/core/end2end/tests/simple_metadata.cc', + 'test/core/end2end/tests/simple_request.cc', + 'test/core/end2end/tests/stream_compression_compressed_payload.cc', + 'test/core/end2end/tests/stream_compression_payload.cc', + 'test/core/end2end/tests/stream_compression_ping_pong_streaming.cc', + 'test/core/end2end/tests/streaming_error_response.cc', + 'test/core/end2end/tests/trailing_metadata.cc', + 'test/core/end2end/tests/workaround_cronet_compression.cc', + 'test/core/end2end/tests/write_buffering.cc', + 'test/core/end2end/tests/write_buffering_at_end.cc', ], }, ] diff --git a/include/grpc++/impl/channel_argument_option.h b/include/grpc++/impl/channel_argument_option.h index e918f57e929..f157ec1d7e5 100644 --- a/include/grpc++/impl/channel_argument_option.h +++ b/include/grpc++/impl/channel_argument_option.h @@ -28,9 +28,9 @@ namespace grpc { std::unique_ptr MakeChannelArgumentOption( - const grpc::string &name, const grpc::string &value); + const grpc::string& name, const grpc::string& value); std::unique_ptr MakeChannelArgumentOption( - const grpc::string &name, int value); + const grpc::string& name, int value); } // namespace grpc diff --git a/include/grpc++/impl/codegen/async_unary_call.h b/include/grpc++/impl/codegen/async_unary_call.h index 6d51c78d5cc..b9ea5fd19c2 100644 --- a/include/grpc++/impl/codegen/async_unary_call.h +++ b/include/grpc++/impl/codegen/async_unary_call.h @@ -297,6 +297,6 @@ class default_delete> { public: void operator()(void* p) {} }; -} +} // namespace std #endif // GRPCXX_IMPL_CODEGEN_ASYNC_UNARY_CALL_H diff --git a/include/grpc++/impl/codegen/call.h b/include/grpc++/impl/codegen/call.h index 1a988297dc4..af2c2b510c1 100644 --- a/include/grpc++/impl/codegen/call.h +++ b/include/grpc++/impl/codegen/call.h @@ -313,11 +313,6 @@ class CallOpSendMessage { WriteOptions write_options_; }; -namespace internal { -template -T Example(); -} // namespace internal - template Status CallOpSendMessage::SendMessage(const M& message, WriteOptions options) { write_options_ = options; @@ -579,6 +574,7 @@ class CallOpClientRecvStatus { op->data.recv_status_on_client.trailing_metadata = metadata_map_->arr(); op->data.recv_status_on_client.status = &status_code_; op->data.recv_status_on_client.status_details = &error_message_; + op->data.recv_status_on_client.error_string = nullptr; op->flags = 0; op->reserved = NULL; } diff --git a/include/grpc++/impl/codegen/client_unary_call.h b/include/grpc++/impl/codegen/client_unary_call.h index 170c562cf3b..256dd859d3b 100644 --- a/include/grpc++/impl/codegen/client_unary_call.h +++ b/include/grpc++/impl/codegen/client_unary_call.h @@ -41,7 +41,7 @@ Status BlockingUnaryCall(ChannelInterface* channel, const RpcMethod& method, return BlockingUnaryCallImpl( channel, method, context, request, result) .status(); -}; +} template class BlockingUnaryCallImpl { diff --git a/include/grpc++/impl/codegen/completion_queue.h b/include/grpc++/impl/codegen/completion_queue.h index 14de30a62e6..b8a78625782 100644 --- a/include/grpc++/impl/codegen/completion_queue.h +++ b/include/grpc++/impl/codegen/completion_queue.h @@ -65,6 +65,7 @@ class CompletionQueue; class Server; class ServerBuilder; class ServerContext; +class ServerInterface; namespace internal { class CompletionQueueTag; @@ -164,8 +165,9 @@ class CompletionQueue : private GrpcLibraryCodegen { /// /// \return true if read a regular event, false if the queue is shutting down. bool Next(void** tag, bool* ok) { - return (AsyncNextInternal(tag, ok, g_core_codegen_interface->gpr_inf_future( - GPR_CLOCK_REALTIME)) != SHUTDOWN); + return (AsyncNextInternal(tag, ok, + g_core_codegen_interface->gpr_inf_future( + GPR_CLOCK_REALTIME)) != SHUTDOWN); } /// Request the shutdown of the queue. @@ -186,21 +188,6 @@ class CompletionQueue : private GrpcLibraryCodegen { /// owership is performed. grpc_completion_queue* cq() { return cq_; } - /// Manage state of avalanching operations : completion queue tags that - /// trigger other completion queue operations. The underlying core completion - /// queue should not really shutdown until all avalanching operations have - /// been finalized. Note that we maintain the requirement that an avalanche - /// registration must take place before CQ shutdown (which must be maintained - /// elsehwere) - void InitialAvalanching() { - gpr_atm_rel_store(&avalanches_in_flight_, static_cast(1)); - } - void RegisterAvalanching() { - gpr_atm_no_barrier_fetch_add(&avalanches_in_flight_, - static_cast(1)); - } - void CompleteAvalanching(); - protected: /// Private constructor of CompletionQueue only visible to friend classes CompletionQueue(const grpc_completion_queue_attributes& attributes) { @@ -237,6 +224,7 @@ class CompletionQueue : private GrpcLibraryCodegen { friend class ::grpc::internal::UnknownMethodHandler; friend class ::grpc::Server; friend class ::grpc::ServerContext; + friend class ::grpc::ServerInterface; template friend class ::grpc::internal::BlockingUnaryCallImpl; @@ -308,6 +296,21 @@ class CompletionQueue : private GrpcLibraryCodegen { GPR_CODEGEN_ASSERT(!tag->FinalizeResult(&ignored, &ok)); } + /// Manage state of avalanching operations : completion queue tags that + /// trigger other completion queue operations. The underlying core completion + /// queue should not really shutdown until all avalanching operations have + /// been finalized. Note that we maintain the requirement that an avalanche + /// registration must take place before CQ shutdown (which must be maintained + /// elsehwere) + void InitialAvalanching() { + gpr_atm_rel_store(&avalanches_in_flight_, static_cast(1)); + } + void RegisterAvalanching() { + gpr_atm_no_barrier_fetch_add(&avalanches_in_flight_, + static_cast(1)); + } + void CompleteAvalanching(); + grpc_completion_queue* cq_; // owned gpr_atm avalanches_in_flight_; diff --git a/include/grpc++/impl/codegen/config_protobuf.h b/include/grpc++/impl/codegen/config_protobuf.h index c5e5bdf0dbc..7387fa25c66 100644 --- a/include/grpc++/impl/codegen/config_protobuf.h +++ b/include/grpc++/impl/codegen/config_protobuf.h @@ -19,6 +19,8 @@ #ifndef GRPCXX_IMPL_CODEGEN_CONFIG_PROTOBUF_H #define GRPCXX_IMPL_CODEGEN_CONFIG_PROTOBUF_H +#define GRPC_OPEN_SOURCE_PROTO + #ifndef GRPC_CUSTOM_PROTOBUF_INT64 #include #define GRPC_CUSTOM_PROTOBUF_INT64 ::google::protobuf::int64 diff --git a/include/grpc++/impl/codegen/core_codegen.h b/include/grpc++/impl/codegen/core_codegen.h index c751c1e7347..d7c57bebb91 100644 --- a/include/grpc++/impl/codegen/core_codegen.h +++ b/include/grpc++/impl/codegen/core_codegen.h @@ -50,6 +50,9 @@ class CoreCodegen final : public CoreCodegenInterface { void* gpr_malloc(size_t size) override; void gpr_free(void* p) override; + void grpc_init() override; + void grpc_shutdown() override; + void gpr_mu_init(gpr_mu* mu) override; void gpr_mu_destroy(gpr_mu* mu) override; void gpr_mu_lock(gpr_mu* mu) override; @@ -89,6 +92,7 @@ class CoreCodegen final : public CoreCodegenInterface { grpc_slice grpc_slice_ref(grpc_slice slice) override; grpc_slice grpc_slice_split_tail(grpc_slice* s, size_t split) override; grpc_slice grpc_slice_split_head(grpc_slice* s, size_t split) override; + grpc_slice grpc_slice_sub(grpc_slice s, size_t begin, size_t end) override; void grpc_slice_buffer_add(grpc_slice_buffer* sb, grpc_slice slice) override; void grpc_slice_buffer_pop(grpc_slice_buffer* sb) override; grpc_slice grpc_slice_from_static_buffer(const void* buffer, diff --git a/include/grpc++/impl/codegen/core_codegen_interface.h b/include/grpc++/impl/codegen/core_codegen_interface.h index a4c50dab873..d7ad7a4b573 100644 --- a/include/grpc++/impl/codegen/core_codegen_interface.h +++ b/include/grpc++/impl/codegen/core_codegen_interface.h @@ -25,10 +25,6 @@ #include #include -extern "C" { -struct grpc_byte_buffer; -} - namespace grpc { /// Interface between the codegen library and the minimal subset of core @@ -63,6 +59,13 @@ class CoreCodegenInterface { virtual void* gpr_malloc(size_t size) = 0; virtual void gpr_free(void* p) = 0; + // These are only to be used to fix edge cases involving grpc_init and + // grpc_shutdown. Calling grpc_init from the codegen interface before + // the real grpc_init is called will cause a crash, so if you use this + // function, ensure that it is not the first call to grpc_init. + virtual void grpc_init() = 0; + virtual void grpc_shutdown() = 0; + virtual void gpr_mu_init(gpr_mu* mu) = 0; virtual void gpr_mu_destroy(gpr_mu* mu) = 0; virtual void gpr_mu_lock(gpr_mu* mu) = 0; @@ -103,6 +106,7 @@ class CoreCodegenInterface { virtual grpc_slice grpc_slice_ref(grpc_slice slice) = 0; virtual grpc_slice grpc_slice_split_tail(grpc_slice* s, size_t split) = 0; virtual grpc_slice grpc_slice_split_head(grpc_slice* s, size_t split) = 0; + virtual grpc_slice grpc_slice_sub(grpc_slice s, size_t begin, size_t end) = 0; virtual void grpc_slice_buffer_add(grpc_slice_buffer* sb, grpc_slice slice) = 0; virtual void grpc_slice_buffer_pop(grpc_slice_buffer* sb) = 0; diff --git a/include/grpc++/impl/codegen/metadata_map.h b/include/grpc++/impl/codegen/metadata_map.h index fd4750efdd1..8dc7211ba8e 100644 --- a/include/grpc++/impl/codegen/metadata_map.h +++ b/include/grpc++/impl/codegen/metadata_map.h @@ -1,20 +1,20 @@ /* -* -* Copyright 2015 gRPC authors. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -*/ + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ #ifndef GRPCXX_IMPL_CODEGEN_METADATA_MAP_H #define GRPCXX_IMPL_CODEGEN_METADATA_MAP_H @@ -41,11 +41,11 @@ class MetadataMap { } } - std::multimap *map() { return &map_; } - const std::multimap *map() const { + std::multimap* map() { return &map_; } + const std::multimap* map() const { return &map_; } - grpc_metadata_array *arr() { return &arr_; } + grpc_metadata_array* arr() { return &arr_; } private: grpc_metadata_array arr_; diff --git a/include/grpc++/impl/codegen/proto_utils.h b/include/grpc++/impl/codegen/proto_utils.h index 67e8f71a899..b7636034d4f 100644 --- a/include/grpc++/impl/codegen/proto_utils.h +++ b/include/grpc++/impl/codegen/proto_utils.h @@ -39,11 +39,13 @@ class GrpcBufferWriterPeer; const int kGrpcBufferWriterMaxBufferLength = 1024 * 1024; -class GrpcBufferWriter final - : public ::grpc::protobuf::io::ZeroCopyOutputStream { +class GrpcBufferWriter : public ::grpc::protobuf::io::ZeroCopyOutputStream { public: - explicit GrpcBufferWriter(grpc_byte_buffer** bp, int block_size) - : block_size_(block_size), byte_count_(0), have_backup_(false) { + GrpcBufferWriter(grpc_byte_buffer** bp, int block_size, int total_size) + : block_size_(block_size), + total_size_(total_size), + byte_count_(0), + have_backup_(false) { *bp = g_core_codegen_interface->grpc_raw_byte_buffer_create(NULL, 0); slice_buffer_ = &(*bp)->data.raw.slice_buffer; } @@ -55,11 +57,20 @@ class GrpcBufferWriter final } bool Next(void** data, int* size) override { + // Protobuf should not ask for more memory than total_size_. + GPR_CODEGEN_ASSERT(byte_count_ < total_size_); if (have_backup_) { slice_ = backup_slice_; have_backup_ = false; } else { - slice_ = g_core_codegen_interface->grpc_slice_malloc(block_size_); + // When less than a whole block is needed, only allocate that much. + // But make sure the allocated slice is not inlined. + size_t remain = total_size_ - byte_count_ > block_size_ + ? block_size_ + : total_size_ - byte_count_; + slice_ = g_core_codegen_interface->grpc_slice_malloc( + remain > GRPC_SLICE_INLINED_SIZE ? remain + : GRPC_SLICE_INLINED_SIZE + 1); } *data = GRPC_SLICE_START_PTR(slice_); // On win x64, int is only 32bit @@ -71,7 +82,7 @@ class GrpcBufferWriter final void BackUp(int count) override { g_core_codegen_interface->grpc_slice_buffer_pop(slice_buffer_); - if (count == block_size_) { + if ((size_t)count == GRPC_SLICE_LENGTH(slice_)) { backup_slice_ = slice_; } else { backup_slice_ = g_core_codegen_interface->grpc_slice_split_tail( @@ -88,9 +99,10 @@ class GrpcBufferWriter final grpc::protobuf::int64 ByteCount() const override { return byte_count_; } - private: + protected: friend class GrpcBufferWriterPeer; const int block_size_; + const int total_size_; int64_t byte_count_; grpc_slice_buffer* slice_buffer_; bool have_backup_; @@ -98,8 +110,7 @@ class GrpcBufferWriter final grpc_slice slice_; }; -class GrpcBufferReader final - : public ::grpc::protobuf::io::ZeroCopyInputStream { +class GrpcBufferReader : public ::grpc::protobuf::io::ZeroCopyInputStream { public: explicit GrpcBufferReader(grpc_byte_buffer* buffer) : byte_count_(0), backup_count_(0), status_() { @@ -160,7 +171,7 @@ class GrpcBufferReader final return byte_count_ - backup_count_; } - private: + protected: int64_t byte_count_; int64_t backup_count_; grpc_byte_buffer_reader reader_; @@ -168,57 +179,85 @@ class GrpcBufferReader final Status status_; }; +// BufferWriter must be a subclass of io::ZeroCopyOutputStream. +template +Status GenericSerialize(const grpc::protobuf::Message& msg, + grpc_byte_buffer** bp, bool* own_buffer) { + static_assert( + std::is_base_of::value, + "BufferWriter must be a subclass of io::ZeroCopyOutputStream"); + *own_buffer = true; + int byte_size = msg.ByteSize(); + if ((size_t)byte_size <= GRPC_SLICE_INLINED_SIZE) { + grpc_slice slice = g_core_codegen_interface->grpc_slice_malloc(byte_size); + GPR_CODEGEN_ASSERT( + GRPC_SLICE_END_PTR(slice) == + msg.SerializeWithCachedSizesToArray(GRPC_SLICE_START_PTR(slice))); + *bp = g_core_codegen_interface->grpc_raw_byte_buffer_create(&slice, 1); + g_core_codegen_interface->grpc_slice_unref(slice); + + return g_core_codegen_interface->ok(); + } + BufferWriter writer(bp, kGrpcBufferWriterMaxBufferLength, byte_size); + return msg.SerializeToZeroCopyStream(&writer) + ? g_core_codegen_interface->ok() + : Status(StatusCode::INTERNAL, "Failed to serialize message"); +} + +// BufferReader must be a subclass of io::ZeroCopyInputStream. +template +Status GenericDeserialize(grpc_byte_buffer* buffer, + grpc::protobuf::Message* msg) { + static_assert( + std::is_base_of::value, + "BufferReader must be a subclass of io::ZeroCopyInputStream"); + if (buffer == nullptr) { + return Status(StatusCode::INTERNAL, "No payload"); + } + Status result = g_core_codegen_interface->ok(); + { + BufferReader reader(buffer); + if (!reader.status().ok()) { + return reader.status(); + } + ::grpc::protobuf::io::CodedInputStream decoder(&reader); + decoder.SetTotalBytesLimit(INT_MAX, INT_MAX); + if (!msg->ParseFromCodedStream(&decoder)) { + result = Status(StatusCode::INTERNAL, msg->InitializationErrorString()); + } + if (!decoder.ConsumedEntireMessage()) { + result = Status(StatusCode::INTERNAL, "Did not read entire message"); + } + } + g_core_codegen_interface->grpc_byte_buffer_destroy(buffer); + return result; +} + } // namespace internal +// this is needed so the following class does not conflict with protobuf +// serializers that utilize internal-only tools. +#ifdef GRPC_OPEN_SOURCE_PROTO +// This class provides a protobuf serializer. It translates between protobuf +// objects and grpc_byte_buffers. More information about SerializationTraits can +// be found in include/grpc++/impl/codegen/serialization_traits.h. template class SerializationTraits::value>::type> { public: static Status Serialize(const grpc::protobuf::Message& msg, grpc_byte_buffer** bp, bool* own_buffer) { - *own_buffer = true; - int byte_size = msg.ByteSize(); - if (byte_size <= internal::kGrpcBufferWriterMaxBufferLength) { - grpc_slice slice = g_core_codegen_interface->grpc_slice_malloc(byte_size); - GPR_CODEGEN_ASSERT( - GRPC_SLICE_END_PTR(slice) == - msg.SerializeWithCachedSizesToArray(GRPC_SLICE_START_PTR(slice))); - *bp = g_core_codegen_interface->grpc_raw_byte_buffer_create(&slice, 1); - g_core_codegen_interface->grpc_slice_unref(slice); - return g_core_codegen_interface->ok(); - } else { - internal::GrpcBufferWriter writer( - bp, internal::kGrpcBufferWriterMaxBufferLength); - return msg.SerializeToZeroCopyStream(&writer) - ? g_core_codegen_interface->ok() - : Status(StatusCode::INTERNAL, "Failed to serialize message"); - } + return internal::GenericSerialize( + msg, bp, own_buffer); } static Status Deserialize(grpc_byte_buffer* buffer, grpc::protobuf::Message* msg) { - if (buffer == nullptr) { - return Status(StatusCode::INTERNAL, "No payload"); - } - Status result = g_core_codegen_interface->ok(); - { - internal::GrpcBufferReader reader(buffer); - if (!reader.status().ok()) { - return reader.status(); - } - ::grpc::protobuf::io::CodedInputStream decoder(&reader); - decoder.SetTotalBytesLimit(INT_MAX, INT_MAX); - if (!msg->ParseFromCodedStream(&decoder)) { - result = Status(StatusCode::INTERNAL, msg->InitializationErrorString()); - } - if (!decoder.ConsumedEntireMessage()) { - result = Status(StatusCode::INTERNAL, "Did not read entire message"); - } - } - g_core_codegen_interface->grpc_byte_buffer_destroy(buffer); - return result; + return internal::GenericDeserialize(buffer, + msg); } }; +#endif } // namespace grpc diff --git a/include/grpc++/server_builder.h b/include/grpc++/server_builder.h index 0888bef0d95..e2bae4b41fa 100644 --- a/include/grpc++/server_builder.h +++ b/include/grpc++/server_builder.h @@ -55,13 +55,18 @@ class ServerBuilder { ServerBuilder(); ~ServerBuilder(); - /// Options for synchronous servers. - enum SyncServerOption { - NUM_CQS, ///< Number of completion queues. - MIN_POLLERS, ///< Minimum number of polling threads. - MAX_POLLERS, ///< Maximum number of polling threads. - CQ_TIMEOUT_MSEC ///< Completion queue timeout in milliseconds. - }; + ////////////////////////////////////////////////////////////////////////////// + // Primary API's + + /// Return a running server which is ready for processing calls. + /// Before calling, one typically needs to ensure that: + /// 1. a service is registered - so that the server knows what to serve + /// (via RegisterService, or RegisterAsyncGenericService) + /// 2. a listening port has been added - so the server knows where to receive + /// traffic (via AddListeningPort) + /// 3. [for async api only] completion queues have been added via + /// AddCompletionQueue + std::unique_ptr BuildAndStart(); /// Register a service. This call does not take ownership of the service. /// The service must exist for the lifetime of the \a Server instance returned @@ -69,9 +74,60 @@ class ServerBuilder { /// Matches requests with any :authority ServerBuilder& RegisterService(Service* service); - /// Register a generic service. - /// Matches requests with any :authority - ServerBuilder& RegisterAsyncGenericService(AsyncGenericService* service); + /// Enlists an endpoint \a addr (port with an optional IP address) to + /// bind the \a grpc::Server object to be created to. + /// + /// It can be invoked multiple times. + /// + /// \param addr_uri The address to try to bind to the server in URI form. If + /// the scheme name is omitted, "dns:///" is assumed. To bind to any address, + /// please use IPv6 any, i.e., [::]:, which also accepts IPv4 + /// connections. Valid values include dns:///localhost:1234, / + /// 192.168.1.1:31416, dns:///[::1]:27182, etc.). + /// \param creds The credentials associated with the server. + /// \param selected_port[out] If not `nullptr`, gets populated with the port + /// number bound to the \a grpc::Server for the corresponding endpoint after + /// it is successfully bound, 0 otherwise. + /// + ServerBuilder& AddListeningPort(const grpc::string& addr_uri, + std::shared_ptr creds, + int* selected_port = nullptr); + + /// Add a completion queue for handling asynchronous services. + /// + /// Best performance is typically obtained by using one thread per polling + /// completion queue. + /// + /// Caller is required to shutdown the server prior to shutting down the + /// returned completion queue. Caller is also required to drain the + /// completion queue after shutting it down. A typical usage scenario: + /// + /// // While building the server: + /// ServerBuilder builder; + /// ... + /// cq_ = builder.AddCompletionQueue(); + /// server_ = builder.BuildAndStart(); + /// + /// // While shutting down the server; + /// server_->Shutdown(); + /// cq_->Shutdown(); // Always *after* the associated server's Shutdown()! + /// // Drain the cq_ that was created + /// void* ignored_tag; + /// bool ignored_ok; + /// while (cq_->Next(&ignored_tag, &ignored_ok)) { } + /// + /// \param is_frequently_polled This is an optional parameter to inform gRPC + /// library about whether this completion queue would be frequently polled + /// (i.e. by calling \a Next() or \a AsyncNext()). The default value is + /// 'true' and is the recommended setting. Setting this to 'false' (i.e. + /// not polling the completion queue frequently) will have a significantly + /// negative performance impact and hence should not be used in production + /// use cases. + std::unique_ptr AddCompletionQueue( + bool is_frequently_polled = true); + + ////////////////////////////////////////////////////////////////////////////// + // Less commonly used RegisterService variants /// Register a service. This call does not take ownership of the service. /// The service must exist for the lifetime of the \a Server instance returned @@ -79,6 +135,15 @@ class ServerBuilder { /// Only matches requests with :authority \a host ServerBuilder& RegisterService(const grpc::string& host, Service* service); + /// Register a generic service. + /// Matches requests with any :authority + /// This is mostly useful for writing generic gRPC Proxies where the exact + /// serialization format is unknown + ServerBuilder& RegisterAsyncGenericService(AsyncGenericService* service); + + ////////////////////////////////////////////////////////////////////////////// + // Fine control knobs + /// Set max receive message size in bytes. ServerBuilder& SetMaxReceiveMessageSize(int max_receive_message_size) { max_receive_message_size_ = max_receive_message_size; @@ -119,6 +184,14 @@ class ServerBuilder { ServerBuilder& SetOption(std::unique_ptr option); + /// Options for synchronous servers. + enum SyncServerOption { + NUM_CQS, ///< Number of completion queues. + MIN_POLLERS, ///< Minimum number of polling threads. + MAX_POLLERS, ///< Maximum number of polling threads. + CQ_TIMEOUT_MSEC ///< Completion queue timeout in milliseconds. + }; + /// Only useful if this is a Synchronous server. ServerBuilder& SetSyncServerOption(SyncServerOption option, int value); @@ -129,59 +202,6 @@ class ServerBuilder { return SetOption(MakeChannelArgumentOption(arg, value)); } - /// Enlists an endpoint \a addr (port with an optional IP address) to - /// bind the \a grpc::Server object to be created to. - /// - /// It can be invoked multiple times. - /// - /// \param addr_uri The address to try to bind to the server in URI form. If - /// the scheme name is omitted, "dns:///" is assumed. To bind to any address, - /// please use IPv6 any, i.e., [::]:, which also accepts IPv4 - /// connections. Valid values include dns:///localhost:1234, / - /// 192.168.1.1:31416, dns:///[::1]:27182, etc.). - /// \param creds The credentials associated with the server. - /// \param selected_port[out] If not `nullptr`, gets populated with the port - /// number bound to the \a grpc::Server for the corresponding endpoint after - /// it is successfully bound, 0 otherwise. - /// - // TODO(dgq): the "port" part seems to be a misnomer. - ServerBuilder& AddListeningPort(const grpc::string& addr_uri, - std::shared_ptr creds, - int* selected_port = nullptr); - - /// Add a completion queue for handling asynchronous services. - /// - /// Caller is required to shutdown the server prior to shutting down the - /// returned completion queue. Caller is also required to drain the - /// completion queue after shutting it down. A typical usage scenario: - /// - /// // While building the server: - /// ServerBuilder builder; - /// ... - /// cq_ = builder.AddCompletionQueue(); - /// server_ = builder.BuildAndStart(); - /// - /// // While shutting down the server; - /// server_->Shutdown(); - /// cq_->Shutdown(); // Always *after* the associated server's Shutdown()! - /// // Drain the cq_ that was created - /// void* ignored_tag; - /// bool ignored_ok; - /// while (cq_->Next(&ignored_tag, &ignored_ok)) { } - /// - /// \param is_frequently_polled This is an optional parameter to inform gRPC - /// library about whether this completion queue would be frequently polled - /// (i.e. by calling \a Next() or \a AsyncNext()). The default value is - /// 'true' and is the recommended setting. Setting this to 'false' (i.e. - /// not polling the completion queue frequently) will have a significantly - /// negative performance impact and hence should not be used in production - /// use cases. - std::unique_ptr AddCompletionQueue( - bool is_frequently_polled = true); - - /// Return a running server which is ready for processing calls. - std::unique_ptr BuildAndStart(); - /// For internal use only: Register a ServerBuilderPlugin factory function. static void InternalAddPluginFactory( std::unique_ptr (*CreatePlugin)()); diff --git a/include/grpc/compression.h b/include/grpc/compression.h index 13a8dd66ad9..b42f428d7de 100644 --- a/include/grpc/compression.h +++ b/include/grpc/compression.h @@ -33,24 +33,24 @@ extern "C" { /** Parses the \a slice as a grpc_compression_algorithm instance and updating \a * algorithm. Returns 1 upon success, 0 otherwise. */ GRPCAPI int grpc_compression_algorithm_parse( - grpc_slice value, grpc_compression_algorithm *algorithm); + grpc_slice value, grpc_compression_algorithm* algorithm); /** Parses the \a slice as a grpc_stream_compression_algorithm instance and * updating \a algorithm. Returns 1 upon success, 0 otherwise. */ int grpc_stream_compression_algorithm_parse( - grpc_slice name, grpc_stream_compression_algorithm *algorithm); + grpc_slice name, grpc_stream_compression_algorithm* algorithm); /** Updates \a name with the encoding name corresponding to a valid \a * algorithm. Note that \a name is statically allocated and must *not* be freed. * Returns 1 upon success, 0 otherwise. */ GRPCAPI int grpc_compression_algorithm_name( - grpc_compression_algorithm algorithm, const char **name); + grpc_compression_algorithm algorithm, const char** name); /** Updates \a name with the encoding name corresponding to a valid \a * algorithm. Note that \a name is statically allocated and must *not* be freed. * Returns 1 upon success, 0 otherwise. */ GRPCAPI int grpc_stream_compression_algorithm_name( - grpc_stream_compression_algorithm algorithm, const char **name); + grpc_stream_compression_algorithm algorithm, const char** name); /** Returns the compression algorithm corresponding to \a level for the * compression algorithms encoded in the \a accepted_encodings bitset. @@ -66,23 +66,23 @@ GRPCAPI grpc_stream_compression_algorithm grpc_stream_compression_algorithm_for_level(grpc_stream_compression_level level, uint32_t accepted_stream_encodings); -GRPCAPI void grpc_compression_options_init(grpc_compression_options *opts); +GRPCAPI void grpc_compression_options_init(grpc_compression_options* opts); /** Mark \a algorithm as enabled in \a opts. */ GRPCAPI void grpc_compression_options_enable_algorithm( - grpc_compression_options *opts, grpc_compression_algorithm algorithm); + grpc_compression_options* opts, grpc_compression_algorithm algorithm); /** Mark \a algorithm as disabled in \a opts. */ GRPCAPI void grpc_compression_options_disable_algorithm( - grpc_compression_options *opts, grpc_compression_algorithm algorithm); + grpc_compression_options* opts, grpc_compression_algorithm algorithm); /** Returns true if \a algorithm is marked as enabled in \a opts. */ GRPCAPI int grpc_compression_options_is_algorithm_enabled( - const grpc_compression_options *opts, grpc_compression_algorithm algorithm); + const grpc_compression_options* opts, grpc_compression_algorithm algorithm); /** Returns true if \a algorithm is marked as enabled in \a opts. */ GRPCAPI int grpc_compression_options_is_stream_compression_algorithm_enabled( - const grpc_compression_options *opts, + const grpc_compression_options* opts, grpc_stream_compression_algorithm algorithm); #ifdef __cplusplus diff --git a/src/node/health_check/node_modules/grpc.js b/include/grpc/fork.h similarity index 76% rename from src/node/health_check/node_modules/grpc.js rename to include/grpc/fork.h index 83f19821073..ca45e1139c0 100644 --- a/src/node/health_check/node_modules/grpc.js +++ b/include/grpc/fork.h @@ -1,6 +1,6 @@ /* * - * Copyright 2016 gRPC authors. + * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,9 @@ * */ -/* This exists solely to allow the generated code to import the grpc module - * without using a relative path */ +#ifndef GRPC_FORK_H +#define GRPC_FORK_H -module.exports = require('../..'); +#include + +#endif /* GRPC_FORK_H */ diff --git a/include/grpc/grpc.h b/include/grpc/grpc.h index 6df3b8086e8..f083bc591e6 100644 --- a/include/grpc/grpc.h +++ b/include/grpc/grpc.h @@ -40,11 +40,11 @@ extern "C" { * functionality lives in grpc_security.h. */ -GRPCAPI void grpc_metadata_array_init(grpc_metadata_array *array); -GRPCAPI void grpc_metadata_array_destroy(grpc_metadata_array *array); +GRPCAPI void grpc_metadata_array_init(grpc_metadata_array* array); +GRPCAPI void grpc_metadata_array_destroy(grpc_metadata_array* array); -GRPCAPI void grpc_call_details_init(grpc_call_details *details); -GRPCAPI void grpc_call_details_destroy(grpc_call_details *details); +GRPCAPI void grpc_call_details_init(grpc_call_details* details); +GRPCAPI void grpc_call_details_destroy(grpc_call_details* details); /** Registers a plugin to be initialized and destroyed with the library. @@ -73,31 +73,31 @@ GRPCAPI void grpc_init(void); GRPCAPI void grpc_shutdown(void); /** Return a string representing the current version of grpc */ -GRPCAPI const char *grpc_version_string(void); +GRPCAPI const char* grpc_version_string(void); /** Return a string specifying what the 'g' in gRPC stands for */ -GRPCAPI const char *grpc_g_stands_for(void); +GRPCAPI const char* grpc_g_stands_for(void); /** Returns the completion queue factory based on the attributes. MAY return a NULL if no factory can be found */ -GRPCAPI const grpc_completion_queue_factory * +GRPCAPI const grpc_completion_queue_factory* grpc_completion_queue_factory_lookup( - const grpc_completion_queue_attributes *attributes); + const grpc_completion_queue_attributes* attributes); /** Helper function to create a completion queue with grpc_cq_completion_type of GRPC_CQ_NEXT and grpc_cq_polling_type of GRPC_CQ_DEFAULT_POLLING */ -GRPCAPI grpc_completion_queue *grpc_completion_queue_create_for_next( - void *reserved); +GRPCAPI grpc_completion_queue* grpc_completion_queue_create_for_next( + void* reserved); /** Helper function to create a completion queue with grpc_cq_completion_type of GRPC_CQ_PLUCK and grpc_cq_polling_type of GRPC_CQ_DEFAULT_POLLING */ -GRPCAPI grpc_completion_queue *grpc_completion_queue_create_for_pluck( - void *reserved); +GRPCAPI grpc_completion_queue* grpc_completion_queue_create_for_pluck( + void* reserved); /** Create a completion queue */ -GRPCAPI grpc_completion_queue *grpc_completion_queue_create( - const grpc_completion_queue_factory *factory, - const grpc_completion_queue_attributes *attributes, void *reserved); +GRPCAPI grpc_completion_queue* grpc_completion_queue_create( + const grpc_completion_queue_factory* factory, + const grpc_completion_queue_attributes* attributes, void* reserved); /** Blocks until an event is available, the completion queue is being shut down, or deadline is reached. @@ -107,9 +107,9 @@ GRPCAPI grpc_completion_queue *grpc_completion_queue_create( Callers must not call grpc_completion_queue_next and grpc_completion_queue_pluck simultaneously on the same completion queue. */ -GRPCAPI grpc_event grpc_completion_queue_next(grpc_completion_queue *cq, +GRPCAPI grpc_event grpc_completion_queue_next(grpc_completion_queue* cq, gpr_timespec deadline, - void *reserved); + void* reserved); /** Blocks until an event with tag 'tag' is available, the completion queue is being shutdown or deadline is reached. @@ -122,9 +122,9 @@ GRPCAPI grpc_event grpc_completion_queue_next(grpc_completion_queue *cq, Completion queues support a maximum of GRPC_MAX_COMPLETION_QUEUE_PLUCKERS concurrently executing plucks at any time. */ -GRPCAPI grpc_event grpc_completion_queue_pluck(grpc_completion_queue *cq, - void *tag, gpr_timespec deadline, - void *reserved); +GRPCAPI grpc_event grpc_completion_queue_pluck(grpc_completion_queue* cq, + void* tag, gpr_timespec deadline, + void* reserved); /** Maximum number of outstanding grpc_completion_queue_pluck executions per completion queue */ @@ -137,31 +137,31 @@ GRPCAPI grpc_event grpc_completion_queue_pluck(grpc_completion_queue *cq, After calling this function applications should ensure that no NEW work is added to be published on this completion queue. */ -GRPCAPI void grpc_completion_queue_shutdown(grpc_completion_queue *cq); +GRPCAPI void grpc_completion_queue_shutdown(grpc_completion_queue* cq); /** Destroy a completion queue. The caller must ensure that the queue is drained and no threads are executing grpc_completion_queue_next */ -GRPCAPI void grpc_completion_queue_destroy(grpc_completion_queue *cq); +GRPCAPI void grpc_completion_queue_destroy(grpc_completion_queue* cq); /*********** EXPERIMENTAL API ************/ /** Initializes a thread local cache for \a cq. - * grpc_flush_cq_tls_cache() MUST be called on the same thread, - * with the same cq. - */ + * grpc_flush_cq_tls_cache() MUST be called on the same thread, + * with the same cq. + */ GRPCAPI void grpc_completion_queue_thread_local_cache_init( - grpc_completion_queue *cq); + grpc_completion_queue* cq); /*********** EXPERIMENTAL API ************/ /** Flushes the thread local cache for \a cq. - * Returns 1 if there was contents in the cache. If there was an event - * in \a cq tls cache, its tag is placed in tag, and ok is set to the - * event success. - */ + * Returns 1 if there was contents in the cache. If there was an event + * in \a cq tls cache, its tag is placed in tag, and ok is set to the + * event success. + */ GRPCAPI int grpc_completion_queue_thread_local_cache_flush( - grpc_completion_queue *cq, void **tag, int *ok); + grpc_completion_queue* cq, void** tag, int* ok); /** Create a completion queue alarm instance */ -GRPCAPI grpc_alarm *grpc_alarm_create(void *reserved); +GRPCAPI grpc_alarm* grpc_alarm_create(void* reserved); /** Set a completion queue alarm instance associated to \a cq. * @@ -169,25 +169,25 @@ GRPCAPI grpc_alarm *grpc_alarm_create(void *reserved); * grpc_alarm_cancel), an event with tag \a tag will be added to \a cq. If the * alarm expired, the event's success bit will be true, false otherwise (ie, * upon cancellation). */ -GRPCAPI void grpc_alarm_set(grpc_alarm *alarm, grpc_completion_queue *cq, - gpr_timespec deadline, void *tag, void *reserved); +GRPCAPI void grpc_alarm_set(grpc_alarm* alarm, grpc_completion_queue* cq, + gpr_timespec deadline, void* tag, void* reserved); /** Cancel a completion queue alarm. Calling this function over an alarm that * has already fired has no effect. */ -GRPCAPI void grpc_alarm_cancel(grpc_alarm *alarm, void *reserved); +GRPCAPI void grpc_alarm_cancel(grpc_alarm* alarm, void* reserved); /** Destroy the given completion queue alarm, cancelling it in the process. */ -GRPCAPI void grpc_alarm_destroy(grpc_alarm *alarm, void *reserved); +GRPCAPI void grpc_alarm_destroy(grpc_alarm* alarm, void* reserved); /** Check the connectivity state of a channel. */ GRPCAPI grpc_connectivity_state grpc_channel_check_connectivity_state( - grpc_channel *channel, int try_to_connect); + grpc_channel* channel, int try_to_connect); /** Number of active "external connectivity state watchers" attached to a * channel. * Useful for testing. **/ GRPCAPI int grpc_channel_num_external_connectivity_watchers( - grpc_channel *channel); + grpc_channel* channel); /** Watch for a change in connectivity state. Once the channel connectivity state is different from last_observed_state, @@ -195,11 +195,11 @@ GRPCAPI int grpc_channel_num_external_connectivity_watchers( If deadline expires BEFORE the state is changed, tag will be enqueued on cq with success=0. */ GRPCAPI void grpc_channel_watch_connectivity_state( - grpc_channel *channel, grpc_connectivity_state last_observed_state, - gpr_timespec deadline, grpc_completion_queue *cq, void *tag); + grpc_channel* channel, grpc_connectivity_state last_observed_state, + gpr_timespec deadline, grpc_completion_queue* cq, void* tag); /** Check whether a grpc channel supports connectivity watcher */ -GRPCAPI int grpc_channel_support_connectivity_watcher(grpc_channel *channel); +GRPCAPI int grpc_channel_support_connectivity_watcher(grpc_channel* channel); /** Create a call given a grpc_channel, in order to call 'method'. All completions are sent to 'completion_queue'. 'method' and 'host' need only @@ -208,31 +208,31 @@ GRPCAPI int grpc_channel_support_connectivity_watcher(grpc_channel *channel); to propagate properties from the server call to this new client call, depending on the value of \a propagation_mask (see propagation_bits.h for possible values). */ -GRPCAPI grpc_call *grpc_channel_create_call( - grpc_channel *channel, grpc_call *parent_call, uint32_t propagation_mask, - grpc_completion_queue *completion_queue, grpc_slice method, - const grpc_slice *host, gpr_timespec deadline, void *reserved); +GRPCAPI grpc_call* grpc_channel_create_call( + grpc_channel* channel, grpc_call* parent_call, uint32_t propagation_mask, + grpc_completion_queue* completion_queue, grpc_slice method, + const grpc_slice* host, gpr_timespec deadline, void* reserved); /** Ping the channels peer (load balanced channels will select one sub-channel to ping); if the channel is not connected, posts a failed. */ -GRPCAPI void grpc_channel_ping(grpc_channel *channel, grpc_completion_queue *cq, - void *tag, void *reserved); +GRPCAPI void grpc_channel_ping(grpc_channel* channel, grpc_completion_queue* cq, + void* tag, void* reserved); /** Pre-register a method/host pair on a channel. */ -GRPCAPI void *grpc_channel_register_call(grpc_channel *channel, - const char *method, const char *host, - void *reserved); +GRPCAPI void* grpc_channel_register_call(grpc_channel* channel, + const char* method, const char* host, + void* reserved); /** Create a call given a handle returned from grpc_channel_register_call. \sa grpc_channel_create_call. */ -GRPCAPI grpc_call *grpc_channel_create_registered_call( - grpc_channel *channel, grpc_call *parent_call, uint32_t propagation_mask, - grpc_completion_queue *completion_queue, void *registered_call_handle, - gpr_timespec deadline, void *reserved); +GRPCAPI grpc_call* grpc_channel_create_registered_call( + grpc_channel* channel, grpc_call* parent_call, uint32_t propagation_mask, + grpc_completion_queue* completion_queue, void* registered_call_handle, + gpr_timespec deadline, void* reserved); /** Allocate memory in the grpc_call arena: this memory is automatically discarded at call completion */ -GRPCAPI void *grpc_call_arena_alloc(grpc_call *call, size_t size); +GRPCAPI void* grpc_call_arena_alloc(grpc_call* call, size_t size); /** Start a batch of operations defined in the array ops; when complete, post a completion of type 'tag' to the completion queue bound to the call. @@ -251,9 +251,9 @@ GRPCAPI void *grpc_call_arena_alloc(grpc_call *call, size_t size); needs to be synchronized. As an optimization, you may synchronize batches containing just send operations independently from batches containing just receive operations. */ -GRPCAPI grpc_call_error grpc_call_start_batch(grpc_call *call, - const grpc_op *ops, size_t nops, - void *tag, void *reserved); +GRPCAPI grpc_call_error grpc_call_start_batch(grpc_call* call, + const grpc_op* ops, size_t nops, + void* tag, void* reserved); /** Returns a newly allocated string representing the endpoint to which this call is communicating with. The string is in the uri format accepted by @@ -263,43 +263,43 @@ GRPCAPI grpc_call_error grpc_call_start_batch(grpc_call *call, WARNING: this value is never authenticated or subject to any security related code. It must not be used for any authentication related functionality. Instead, use grpc_auth_context. */ -GRPCAPI char *grpc_call_get_peer(grpc_call *call); +GRPCAPI char* grpc_call_get_peer(grpc_call* call); struct census_context; /** Set census context for a call; Must be called before first call to grpc_call_start_batch(). */ -GRPCAPI void grpc_census_call_set_context(grpc_call *call, - struct census_context *context); +GRPCAPI void grpc_census_call_set_context(grpc_call* call, + struct census_context* context); /** Retrieve the calls current census context. */ -GRPCAPI struct census_context *grpc_census_call_get_context(grpc_call *call); +GRPCAPI struct census_context* grpc_census_call_get_context(grpc_call* call); /** Return a newly allocated string representing the target a channel was created for. */ -GRPCAPI char *grpc_channel_get_target(grpc_channel *channel); +GRPCAPI char* grpc_channel_get_target(grpc_channel* channel); /** Request info about the channel. \a channel_info indicates what information is being requested and how that information will be returned. \a channel_info is owned by the caller. */ -GRPCAPI void grpc_channel_get_info(grpc_channel *channel, - const grpc_channel_info *channel_info); +GRPCAPI void grpc_channel_get_info(grpc_channel* channel, + const grpc_channel_info* channel_info); /** Create a client channel to 'target'. Additional channel level configuration MAY be provided by grpc_channel_args, though the expectation is that most clients will want to simply pass NULL. See grpc_channel_args definition for more on this. The data in 'args' need only live through the invocation of this function. */ -GRPCAPI grpc_channel *grpc_insecure_channel_create( - const char *target, const grpc_channel_args *args, void *reserved); +GRPCAPI grpc_channel* grpc_insecure_channel_create( + const char* target, const grpc_channel_args* args, void* reserved); /** Create a lame client: this client fails every operation attempted on it. */ -GRPCAPI grpc_channel *grpc_lame_client_channel_create( - const char *target, grpc_status_code error_code, const char *error_message); +GRPCAPI grpc_channel* grpc_lame_client_channel_create( + const char* target, grpc_status_code error_code, const char* error_message); /** Close and destroy a grpc channel */ -GRPCAPI void grpc_channel_destroy(grpc_channel *channel); +GRPCAPI void grpc_channel_destroy(grpc_channel* channel); /** Error handling for grpc_call Most grpc_call functions return a grpc_error. If the error is not GRPC_OK @@ -312,7 +312,7 @@ GRPCAPI void grpc_channel_destroy(grpc_channel *channel); THREAD-SAFETY grpc_call_cancel and grpc_call_cancel_with_status are thread-safe, and can be called at any point before grpc_call_unref is called.*/ -GRPCAPI grpc_call_error grpc_call_cancel(grpc_call *call, void *reserved); +GRPCAPI grpc_call_error grpc_call_cancel(grpc_call* call, void* reserved); /** Called by clients to cancel an RPC on the server. Can be called multiple times, from any thread. @@ -324,18 +324,18 @@ GRPCAPI grpc_call_error grpc_call_cancel(grpc_call *call, void *reserved); It doesn't need to be alive after the call to grpc_call_cancel_with_status completes. */ -GRPCAPI grpc_call_error grpc_call_cancel_with_status(grpc_call *call, +GRPCAPI grpc_call_error grpc_call_cancel_with_status(grpc_call* call, grpc_status_code status, - const char *description, - void *reserved); + const char* description, + void* reserved); /** Ref a call. THREAD SAFETY: grpc_call_ref is thread-compatible */ -GRPCAPI void grpc_call_ref(grpc_call *call); +GRPCAPI void grpc_call_ref(grpc_call* call); /** Unref a call. THREAD SAFETY: grpc_call_unref is thread-compatible */ -GRPCAPI void grpc_call_unref(grpc_call *call); +GRPCAPI void grpc_call_unref(grpc_call* call); /** Request notification of a new call. Once a call is received, a notification tagged with \a tag_new is added to @@ -346,10 +346,10 @@ GRPCAPI void grpc_call_unref(grpc_call *call); Note that \a cq_for_notification must have been registered to the server via \a grpc_server_register_completion_queue. */ GRPCAPI grpc_call_error grpc_server_request_call( - grpc_server *server, grpc_call **call, grpc_call_details *details, - grpc_metadata_array *request_metadata, - grpc_completion_queue *cq_bound_to_call, - grpc_completion_queue *cq_for_notification, void *tag_new); + grpc_server* server, grpc_call** call, grpc_call_details* details, + grpc_metadata_array* request_metadata, + grpc_completion_queue* cq_bound_to_call, + grpc_completion_queue* cq_for_notification, void* tag_new); /** How to handle payloads for a registered method */ typedef enum { @@ -366,8 +366,8 @@ typedef enum { registered_method (as returned by this function). Must be called before grpc_server_start. Returns NULL on failure. */ -GRPCAPI void *grpc_server_register_method( - grpc_server *server, const char *method, const char *host, +GRPCAPI void* grpc_server_register_method( + grpc_server* server, const char* method, const char* host, grpc_server_register_method_payload_handling payload_handling, uint32_t flags); @@ -375,35 +375,35 @@ GRPCAPI void *grpc_server_register_method( must have been registered to the server via grpc_server_register_completion_queue. */ GRPCAPI grpc_call_error grpc_server_request_registered_call( - grpc_server *server, void *registered_method, grpc_call **call, - gpr_timespec *deadline, grpc_metadata_array *request_metadata, - grpc_byte_buffer **optional_payload, - grpc_completion_queue *cq_bound_to_call, - grpc_completion_queue *cq_for_notification, void *tag_new); + grpc_server* server, void* registered_method, grpc_call** call, + gpr_timespec* deadline, grpc_metadata_array* request_metadata, + grpc_byte_buffer** optional_payload, + grpc_completion_queue* cq_bound_to_call, + grpc_completion_queue* cq_for_notification, void* tag_new); /** Create a server. Additional configuration for each incoming channel can be specified with args. If no additional configuration is needed, args can be NULL. See grpc_channel_args for more. The data in 'args' need only live through the invocation of this function. */ -GRPCAPI grpc_server *grpc_server_create(const grpc_channel_args *args, - void *reserved); +GRPCAPI grpc_server* grpc_server_create(const grpc_channel_args* args, + void* reserved); /** Register a completion queue with the server. Must be done for any notification completion queue that is passed to grpc_server_request_*_call and to grpc_server_shutdown_and_notify. Must be performed prior to grpc_server_start. */ -GRPCAPI void grpc_server_register_completion_queue(grpc_server *server, - grpc_completion_queue *cq, - void *reserved); +GRPCAPI void grpc_server_register_completion_queue(grpc_server* server, + grpc_completion_queue* cq, + void* reserved); /** Add a HTTP2 over plaintext over tcp listener. Returns bound port number on success, 0 on failure. REQUIRES: server not started */ -GRPCAPI int grpc_server_add_insecure_http2_port(grpc_server *server, - const char *addr); +GRPCAPI int grpc_server_add_insecure_http2_port(grpc_server* server, + const char* addr); /** Start a server - tells all listeners to start listening */ -GRPCAPI void grpc_server_start(grpc_server *server); +GRPCAPI void grpc_server_start(grpc_server* server); /** Begin shutting down a server. After completion, no new calls or connections will be admitted. @@ -412,19 +412,19 @@ GRPCAPI void grpc_server_start(grpc_server *server); Shutdown is idempotent, and all tags will be notified at once if multiple grpc_server_shutdown_and_notify calls are made. 'cq' must have been registered to this server via grpc_server_register_completion_queue. */ -GRPCAPI void grpc_server_shutdown_and_notify(grpc_server *server, - grpc_completion_queue *cq, - void *tag); +GRPCAPI void grpc_server_shutdown_and_notify(grpc_server* server, + grpc_completion_queue* cq, + void* tag); /** Cancel all in-progress calls. Only usable after shutdown. */ -GRPCAPI void grpc_server_cancel_all_calls(grpc_server *server); +GRPCAPI void grpc_server_cancel_all_calls(grpc_server* server); /** Destroy a server. Shutdown must have completed beforehand (i.e. all tags generated by grpc_server_shutdown_and_notify must have been received, and at least one call to grpc_server_shutdown_and_notify must have been made). */ -GRPCAPI void grpc_server_destroy(grpc_server *server); +GRPCAPI void grpc_server_destroy(grpc_server* server); /** Enable or disable a tracer. @@ -434,7 +434,7 @@ GRPCAPI void grpc_server_destroy(grpc_server *server); Use of this function is not strictly thread-safe, but the thread-safety issues raised by it should not be of concern. */ -GRPCAPI int grpc_tracer_set_enabled(const char *name, int enabled); +GRPCAPI int grpc_tracer_set_enabled(const char* name, int enabled); /** Check whether a metadata key is legal (will be accepted by core) */ GRPCAPI int grpc_header_key_is_legal(grpc_slice slice); @@ -447,24 +447,24 @@ GRPCAPI int grpc_header_nonbin_value_is_legal(grpc_slice slice); GRPCAPI int grpc_is_binary_header(grpc_slice slice); /** Convert grpc_call_error values to a string */ -GRPCAPI const char *grpc_call_error_to_string(grpc_call_error error); +GRPCAPI const char* grpc_call_error_to_string(grpc_call_error error); /** Create a buffer pool */ -GRPCAPI grpc_resource_quota *grpc_resource_quota_create(const char *trace_name); +GRPCAPI grpc_resource_quota* grpc_resource_quota_create(const char* trace_name); /** Add a reference to a buffer pool */ -GRPCAPI void grpc_resource_quota_ref(grpc_resource_quota *resource_quota); +GRPCAPI void grpc_resource_quota_ref(grpc_resource_quota* resource_quota); /** Drop a reference to a buffer pool */ -GRPCAPI void grpc_resource_quota_unref(grpc_resource_quota *resource_quota); +GRPCAPI void grpc_resource_quota_unref(grpc_resource_quota* resource_quota); /** Update the size of a buffer pool */ -GRPCAPI void grpc_resource_quota_resize(grpc_resource_quota *resource_quota, +GRPCAPI void grpc_resource_quota_resize(grpc_resource_quota* resource_quota, size_t new_size); /** Fetch a vtable for a grpc_channel_arg that points to a grpc_resource_quota */ -GRPCAPI const grpc_arg_pointer_vtable *grpc_resource_quota_arg_vtable(void); +GRPCAPI const grpc_arg_pointer_vtable* grpc_resource_quota_arg_vtable(void); #ifdef __cplusplus } diff --git a/include/grpc/grpc_cronet.h b/include/grpc/grpc_cronet.h index 44330c6e116..127d5d038d0 100644 --- a/include/grpc/grpc_cronet.h +++ b/include/grpc/grpc_cronet.h @@ -25,9 +25,9 @@ extern "C" { #endif -GRPCAPI grpc_channel *grpc_cronet_secure_channel_create( - void *engine, const char *target, const grpc_channel_args *args, - void *reserved); +GRPCAPI grpc_channel* grpc_cronet_secure_channel_create( + void* engine, const char* target, const grpc_channel_args* args, + void* reserved); #ifdef __cplusplus } diff --git a/include/grpc/grpc_posix.h b/include/grpc/grpc_posix.h index c7429eaea0b..fa7ebced3f3 100644 --- a/include/grpc/grpc_posix.h +++ b/include/grpc/grpc_posix.h @@ -37,8 +37,8 @@ extern "C" { /** Create a client channel to 'target' using file descriptor 'fd'. The 'target' argument will be used to indicate the name for this channel. See the comment for grpc_insecure_channel_create for description of 'args' argument. */ -GRPCAPI grpc_channel *grpc_insecure_channel_create_from_fd( - const char *target, int fd, const grpc_channel_args *args); +GRPCAPI grpc_channel* grpc_insecure_channel_create_from_fd( + const char* target, int fd, const grpc_channel_args* args); /** Add the connected communication channel based on file descriptor 'fd' to the 'server'. The 'fd' must be an open file descriptor corresponding to a @@ -48,8 +48,8 @@ GRPCAPI grpc_channel *grpc_insecure_channel_create_from_fd( The 'reserved' pointer MUST be NULL. */ -GRPCAPI void grpc_server_add_insecure_channel_from_fd(grpc_server *server, - void *reserved, int fd); +GRPCAPI void grpc_server_add_insecure_channel_from_fd(grpc_server* server, + void* reserved, int fd); /** GRPC Core POSIX library may internally use signals to optimize some work. The library uses (SIGRTMIN + 6) signal by default. Use this API to instruct diff --git a/include/grpc/grpc_security.h b/include/grpc/grpc_security.h index 758aaf5b6cc..bae07ac3098 100644 --- a/include/grpc/grpc_security.h +++ b/include/grpc/grpc_security.h @@ -32,51 +32,51 @@ extern "C" { typedef struct grpc_auth_context grpc_auth_context; typedef struct grpc_auth_property_iterator { - const grpc_auth_context *ctx; + const grpc_auth_context* ctx; size_t index; - const char *name; + const char* name; } grpc_auth_property_iterator; /** value, if not NULL, is guaranteed to be NULL terminated. */ typedef struct grpc_auth_property { - char *name; - char *value; + char* name; + char* value; size_t value_length; } grpc_auth_property; /** Returns NULL when the iterator is at the end. */ -GRPCAPI const grpc_auth_property *grpc_auth_property_iterator_next( - grpc_auth_property_iterator *it); +GRPCAPI const grpc_auth_property* grpc_auth_property_iterator_next( + grpc_auth_property_iterator* it); /** Iterates over the auth context. */ GRPCAPI grpc_auth_property_iterator -grpc_auth_context_property_iterator(const grpc_auth_context *ctx); +grpc_auth_context_property_iterator(const grpc_auth_context* ctx); /** Gets the peer identity. Returns an empty iterator (first _next will return NULL) if the peer is not authenticated. */ GRPCAPI grpc_auth_property_iterator -grpc_auth_context_peer_identity(const grpc_auth_context *ctx); +grpc_auth_context_peer_identity(const grpc_auth_context* ctx); /** Finds a property in the context. May return an empty iterator (first _next will return NULL) if no property with this name was found in the context. */ GRPCAPI grpc_auth_property_iterator grpc_auth_context_find_properties_by_name( - const grpc_auth_context *ctx, const char *name); + const grpc_auth_context* ctx, const char* name); /** Gets the name of the property that indicates the peer identity. Will return NULL if the peer is not authenticated. */ -GRPCAPI const char *grpc_auth_context_peer_identity_property_name( - const grpc_auth_context *ctx); +GRPCAPI const char* grpc_auth_context_peer_identity_property_name( + const grpc_auth_context* ctx); /** Returns 1 if the peer is authenticated, 0 otherwise. */ GRPCAPI int grpc_auth_context_peer_is_authenticated( - const grpc_auth_context *ctx); + const grpc_auth_context* ctx); /** Gets the auth context from the call. Caller needs to call grpc_auth_context_release on the returned context. */ -GRPCAPI grpc_auth_context *grpc_call_auth_context(grpc_call *call); +GRPCAPI grpc_auth_context* grpc_call_auth_context(grpc_call* call); /** Releases the auth context returned from grpc_call_auth_context. */ -GRPCAPI void grpc_auth_context_release(grpc_auth_context *context); +GRPCAPI void grpc_auth_context_release(grpc_auth_context* context); /** -- The following auth context methods should only be called by a server metadata @@ -84,19 +84,19 @@ GRPCAPI void grpc_auth_context_release(grpc_auth_context *context); -- */ /** Add a property. */ -GRPCAPI void grpc_auth_context_add_property(grpc_auth_context *ctx, - const char *name, const char *value, +GRPCAPI void grpc_auth_context_add_property(grpc_auth_context* ctx, + const char* name, const char* value, size_t value_length); /** Add a C string property. */ -GRPCAPI void grpc_auth_context_add_cstring_property(grpc_auth_context *ctx, - const char *name, - const char *value); +GRPCAPI void grpc_auth_context_add_cstring_property(grpc_auth_context* ctx, + const char* name, + const char* value); /** Sets the property name. Returns 1 if successful or 0 in case of failure (which means that no property with this name exists). */ GRPCAPI int grpc_auth_context_set_peer_identity_property_name( - grpc_auth_context *ctx, const char *name); + grpc_auth_context* ctx, const char* name); /** --- grpc_channel_credentials object. --- @@ -107,12 +107,12 @@ typedef struct grpc_channel_credentials grpc_channel_credentials; /** Releases a channel credentials object. The creator of the credentials object is responsible for its release. */ -GRPCAPI void grpc_channel_credentials_release(grpc_channel_credentials *creds); +GRPCAPI void grpc_channel_credentials_release(grpc_channel_credentials* creds); /** Creates default credentials to connect to a google gRPC service. WARNING: Do NOT use this credentials to connect to a non-google service as this could result in an oauth2 token leak. */ -GRPCAPI grpc_channel_credentials *grpc_google_default_credentials_create(void); +GRPCAPI grpc_channel_credentials* grpc_google_default_credentials_create(void); /** Callback for getting the SSL roots override from the application. In case of success, *pem_roots_certs must be set to a NULL terminated string @@ -121,7 +121,7 @@ GRPCAPI grpc_channel_credentials *grpc_google_default_credentials_create(void); If this function fails and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH environment is set to a valid path, it will override the roots specified this func */ typedef grpc_ssl_roots_override_result (*grpc_ssl_roots_override_callback)( - char **pem_root_certs); + char** pem_root_certs); /** Setup a callback to override the default TLS/SSL roots. This function is not thread-safe and must be called at initialization time @@ -135,11 +135,11 @@ GRPCAPI void grpc_set_ssl_roots_override_callback( typedef struct { /** private_key is the NULL-terminated string containing the PEM encoding of the client's private key. */ - const char *private_key; + const char* private_key; /** cert_chain is the NULL-terminated string containing the PEM encoding of the client's certificate chain. */ - const char *cert_chain; + const char* cert_chain; } grpc_ssl_pem_key_cert_pair; /** Creates an SSL credentials object. @@ -153,9 +153,9 @@ typedef struct { - pem_key_cert_pair is a pointer on the object containing client's private key and certificate chain. This parameter can be NULL if the client does not have such a key/cert pair. */ -GRPCAPI grpc_channel_credentials *grpc_ssl_credentials_create( - const char *pem_root_certs, grpc_ssl_pem_key_cert_pair *pem_key_cert_pair, - void *reserved); +GRPCAPI grpc_channel_credentials* grpc_ssl_credentials_create( + const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, + void* reserved); /** --- grpc_call_credentials object. @@ -167,35 +167,35 @@ typedef struct grpc_call_credentials grpc_call_credentials; /** Releases a call credentials object. The creator of the credentials object is responsible for its release. */ -GRPCAPI void grpc_call_credentials_release(grpc_call_credentials *creds); +GRPCAPI void grpc_call_credentials_release(grpc_call_credentials* creds); /** Creates a composite channel credentials object. */ -GRPCAPI grpc_channel_credentials *grpc_composite_channel_credentials_create( - grpc_channel_credentials *channel_creds, grpc_call_credentials *call_creds, - void *reserved); +GRPCAPI grpc_channel_credentials* grpc_composite_channel_credentials_create( + grpc_channel_credentials* channel_creds, grpc_call_credentials* call_creds, + void* reserved); /** Creates a composite call credentials object. */ -GRPCAPI grpc_call_credentials *grpc_composite_call_credentials_create( - grpc_call_credentials *creds1, grpc_call_credentials *creds2, - void *reserved); +GRPCAPI grpc_call_credentials* grpc_composite_call_credentials_create( + grpc_call_credentials* creds1, grpc_call_credentials* creds2, + void* reserved); /** Creates a compute engine credentials object for connecting to Google. WARNING: Do NOT use this credentials to connect to a non-google service as this could result in an oauth2 token leak. */ -GRPCAPI grpc_call_credentials *grpc_google_compute_engine_credentials_create( - void *reserved); +GRPCAPI grpc_call_credentials* grpc_google_compute_engine_credentials_create( + void* reserved); -GRPCAPI gpr_timespec grpc_max_auth_token_lifetime(); +GRPCAPI gpr_timespec grpc_max_auth_token_lifetime(void); /** Creates a JWT credentials object. May return NULL if the input is invalid. - json_key is the JSON key string containing the client's private key. - token_lifetime is the lifetime of each Json Web Token (JWT) created with this credentials. It should not exceed grpc_max_auth_token_lifetime or will be cropped to this value. */ -GRPCAPI grpc_call_credentials * -grpc_service_account_jwt_access_credentials_create(const char *json_key, +GRPCAPI grpc_call_credentials* +grpc_service_account_jwt_access_credentials_create(const char* json_key, gpr_timespec token_lifetime, - void *reserved); + void* reserved); /** Creates an Oauth2 Refresh Token credentials object for connecting to Google. May return NULL if the input is invalid. @@ -203,18 +203,18 @@ grpc_service_account_jwt_access_credentials_create(const char *json_key, this could result in an oauth2 token leak. - json_refresh_token is the JSON string containing the refresh token itself along with a client_id and client_secret. */ -GRPCAPI grpc_call_credentials *grpc_google_refresh_token_credentials_create( - const char *json_refresh_token, void *reserved); +GRPCAPI grpc_call_credentials* grpc_google_refresh_token_credentials_create( + const char* json_refresh_token, void* reserved); /** Creates an Oauth2 Access Token credentials with an access token that was aquired by an out of band mechanism. */ -GRPCAPI grpc_call_credentials *grpc_access_token_credentials_create( - const char *access_token, void *reserved); +GRPCAPI grpc_call_credentials* grpc_access_token_credentials_create( + const char* access_token, void* reserved); /** Creates an IAM credentials object for connecting to Google. */ -GRPCAPI grpc_call_credentials *grpc_google_iam_credentials_create( - const char *authorization_token, const char *authority_selector, - void *reserved); +GRPCAPI grpc_call_credentials* grpc_google_iam_credentials_create( + const char* authorization_token, const char* authority_selector, + void* reserved); /** Callback function to be called by the metadata credentials plugin implementation when the metadata is ready. @@ -228,25 +228,25 @@ GRPCAPI grpc_call_credentials *grpc_google_iam_credentials_create( - error_details contains details about the error if any. In case of success it should be NULL and will be otherwise ignored. */ typedef void (*grpc_credentials_plugin_metadata_cb)( - void *user_data, const grpc_metadata *creds_md, size_t num_creds_md, - grpc_status_code status, const char *error_details); + void* user_data, const grpc_metadata* creds_md, size_t num_creds_md, + grpc_status_code status, const char* error_details); /** Context that can be used by metadata credentials plugin in order to create auth related metadata. */ typedef struct { /** The fully qualifed service url. */ - const char *service_url; + const char* service_url; /** The method name of the RPC being called (not fully qualified). The fully qualified method name can be built from the service_url: full_qualified_method_name = ctx->service_url + '/' + ctx->method_name. */ - const char *method_name; + const char* method_name; /** The auth_context of the channel which gives the server's identity. */ - const grpc_auth_context *channel_auth_context; + const grpc_auth_context* channel_auth_context; /** Reserved for future use. */ - void *reserved; + void* reserved; } grpc_auth_metadata_context; /** Maximum number of metadata entries returnable by a credentials plugin via @@ -278,32 +278,32 @@ typedef struct { \a context is the information that can be used by the plugin to create auth metadata. */ int (*get_metadata)( - void *state, grpc_auth_metadata_context context, - grpc_credentials_plugin_metadata_cb cb, void *user_data, + void* state, grpc_auth_metadata_context context, + grpc_credentials_plugin_metadata_cb cb, void* user_data, grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], - size_t *num_creds_md, grpc_status_code *status, - const char **error_details); + size_t* num_creds_md, grpc_status_code* status, + const char** error_details); /** Destroys the plugin state. */ - void (*destroy)(void *state); + void (*destroy)(void* state); /** State that will be set as the first parameter of the methods above. */ - void *state; + void* state; /** Type of credentials that this plugin is implementing. */ - const char *type; + const char* type; } grpc_metadata_credentials_plugin; /** Creates a credentials object from a plugin. */ -GRPCAPI grpc_call_credentials *grpc_metadata_credentials_create_from_plugin( - grpc_metadata_credentials_plugin plugin, void *reserved); +GRPCAPI grpc_call_credentials* grpc_metadata_credentials_create_from_plugin( + grpc_metadata_credentials_plugin plugin, void* reserved); /** --- Secure channel creation. --- */ /** Creates a secure channel using the passed-in credentials. */ -GRPCAPI grpc_channel *grpc_secure_channel_create( - grpc_channel_credentials *creds, const char *target, - const grpc_channel_args *args, void *reserved); +GRPCAPI grpc_channel* grpc_secure_channel_create( + grpc_channel_credentials* creds, const char* target, + const grpc_channel_args* args, void* reserved); /** --- grpc_server_credentials object. --- @@ -314,7 +314,7 @@ typedef struct grpc_server_credentials grpc_server_credentials; /** Releases a server_credentials object. The creator of the server_credentials object is responsible for its release. */ -GRPCAPI void grpc_server_credentials_release(grpc_server_credentials *creds); +GRPCAPI void grpc_server_credentials_release(grpc_server_credentials* creds); /** Server certificate config object holds the server's public certificates and associated private keys, as well as any CA certificates needed for client @@ -333,15 +333,15 @@ typedef struct grpc_ssl_server_certificate_config and cert_chain_files parameters. It must be at least 1. - It is the caller's responsibility to free this object via grpc_ssl_server_certificate_config_destroy(). */ -GRPCAPI grpc_ssl_server_certificate_config * +GRPCAPI grpc_ssl_server_certificate_config* grpc_ssl_server_certificate_config_create( - const char *pem_root_certs, - const grpc_ssl_pem_key_cert_pair *pem_key_cert_pairs, + const char* pem_root_certs, + const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs); /** Destroys a grpc_ssl_server_certificate_config object. */ GRPCAPI void grpc_ssl_server_certificate_config_destroy( - grpc_ssl_server_certificate_config *config); + grpc_ssl_server_certificate_config* config); /** Callback to retrieve updated SSL server certificates, private keys, and trusted CAs (for client authentication). @@ -351,7 +351,7 @@ GRPCAPI void grpc_ssl_server_certificate_config_destroy( - The caller assumes ownership of the config. */ typedef grpc_ssl_certificate_config_reload_status ( *grpc_ssl_server_certificate_config_callback)( - void *user_data, grpc_ssl_server_certificate_config **config); + void* user_data, grpc_ssl_server_certificate_config** config); /** Deprecated in favor of grpc_ssl_server_credentials_create_ex. Creates an SSL server_credentials object. @@ -365,19 +365,19 @@ typedef grpc_ssl_certificate_config_reload_status ( - force_client_auth, if set to non-zero will force the client to authenticate with an SSL cert. Note that this option is ignored if pem_root_certs is NULL. */ -GRPCAPI grpc_server_credentials *grpc_ssl_server_credentials_create( - const char *pem_root_certs, grpc_ssl_pem_key_cert_pair *pem_key_cert_pairs, - size_t num_key_cert_pairs, int force_client_auth, void *reserved); +GRPCAPI grpc_server_credentials* grpc_ssl_server_credentials_create( + const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, + size_t num_key_cert_pairs, int force_client_auth, void* reserved); /** Deprecated in favor of grpc_ssl_server_credentials_create_with_options. Same as grpc_ssl_server_credentials_create method except uses grpc_ssl_client_certificate_request_type enum to support more ways to authenticate client cerificates.*/ -GRPCAPI grpc_server_credentials *grpc_ssl_server_credentials_create_ex( - const char *pem_root_certs, grpc_ssl_pem_key_cert_pair *pem_key_cert_pairs, +GRPCAPI grpc_server_credentials* grpc_ssl_server_credentials_create_ex( + const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs, grpc_ssl_client_certificate_request_type client_certificate_request, - void *reserved); + void* reserved); typedef struct grpc_ssl_server_credentials_options grpc_ssl_server_credentials_options; @@ -386,10 +386,10 @@ typedef struct grpc_ssl_server_credentials_options the certificates and keys of the SSL server will not change during the server's lifetime. - Takes ownership of the certificate_config parameter. */ -GRPCAPI grpc_ssl_server_credentials_options * +GRPCAPI grpc_ssl_server_credentials_options* grpc_ssl_server_credentials_create_options_using_config( grpc_ssl_client_certificate_request_type client_certificate_request, - grpc_ssl_server_certificate_config *certificate_config); + grpc_ssl_server_certificate_config* certificate_config); /** Creates an options object using a certificate config fetcher. Use this method to reload the certificates and keys of the SSL server without @@ -398,36 +398,36 @@ grpc_ssl_server_credentials_create_options_using_config( - user_data parameter, if not NULL, contains opaque data which will be passed to the fetcher (see definition of grpc_ssl_server_certificate_config_callback). */ -GRPCAPI grpc_ssl_server_credentials_options * +GRPCAPI grpc_ssl_server_credentials_options* grpc_ssl_server_credentials_create_options_using_config_fetcher( grpc_ssl_client_certificate_request_type client_certificate_request, - grpc_ssl_server_certificate_config_callback cb, void *user_data); + grpc_ssl_server_certificate_config_callback cb, void* user_data); /** Destroys a grpc_ssl_server_credentials_options object. */ GRPCAPI void grpc_ssl_server_credentials_options_destroy( - grpc_ssl_server_credentials_options *options); + grpc_ssl_server_credentials_options* options); /** Creates an SSL server_credentials object using the provided options struct. - Takes ownership of the options parameter. */ -GRPCAPI grpc_server_credentials * +GRPCAPI grpc_server_credentials* grpc_ssl_server_credentials_create_with_options( - grpc_ssl_server_credentials_options *options); + grpc_ssl_server_credentials_options* options); /** --- Server-side secure ports. --- */ /** Add a HTTP2 over an encrypted link over tcp listener. Returns bound port number on success, 0 on failure. REQUIRES: server not started */ -GRPCAPI int grpc_server_add_secure_http2_port(grpc_server *server, - const char *addr, - grpc_server_credentials *creds); +GRPCAPI int grpc_server_add_secure_http2_port(grpc_server* server, + const char* addr, + grpc_server_credentials* creds); /** --- Call specific credentials. --- */ /** Sets a credentials to a call. Can only be called on the client side before grpc_call_start_batch. */ -GRPCAPI grpc_call_error grpc_call_set_credentials(grpc_call *call, - grpc_call_credentials *creds); +GRPCAPI grpc_call_error grpc_call_set_credentials(grpc_call* call, + grpc_call_credentials* creds); /** --- Auth Metadata Processing --- */ @@ -441,9 +441,9 @@ GRPCAPI grpc_call_error grpc_call_set_credentials(grpc_call *call, GRPC_STATUS PERMISSION_DENIED in case of an authorization failure. - error_details gives details about the error. May be NULL. */ typedef void (*grpc_process_auth_metadata_done_cb)( - void *user_data, const grpc_metadata *consumed_md, size_t num_consumed_md, - const grpc_metadata *response_md, size_t num_response_md, - grpc_status_code status, const char *error_details); + void* user_data, const grpc_metadata* consumed_md, size_t num_consumed_md, + const grpc_metadata* response_md, size_t num_response_md, + grpc_status_code status, const char* error_details); /** Pluggable server-side metadata processor object. */ typedef struct { @@ -451,15 +451,15 @@ typedef struct { channel peer and it is the job of the process function to augment it with properties derived from the passed-in metadata. The lifetime of these objects is guaranteed until cb is invoked. */ - void (*process)(void *state, grpc_auth_context *context, - const grpc_metadata *md, size_t num_md, - grpc_process_auth_metadata_done_cb cb, void *user_data); - void (*destroy)(void *state); - void *state; + void (*process)(void* state, grpc_auth_context* context, + const grpc_metadata* md, size_t num_md, + grpc_process_auth_metadata_done_cb cb, void* user_data); + void (*destroy)(void* state); + void* state; } grpc_auth_metadata_processor; GRPCAPI void grpc_server_credentials_set_auth_metadata_processor( - grpc_server_credentials *creds, grpc_auth_metadata_processor processor); + grpc_server_credentials* creds, grpc_auth_metadata_processor processor); #ifdef __cplusplus } diff --git a/include/grpc/impl/codegen/atm.h b/include/grpc/impl/codegen/atm.h index 764bee52726..00d83f0604f 100644 --- a/include/grpc/impl/codegen/atm.h +++ b/include/grpc/impl/codegen/atm.h @@ -79,9 +79,17 @@ #error could not determine platform for atm #endif +#ifdef __cplusplus +extern "C" { +#endif + /** Adds \a delta to \a *value, clamping the result to the range specified by \a min and \a max. Returns the new value. */ -gpr_atm gpr_atm_no_barrier_clamped_add(gpr_atm *value, gpr_atm delta, +gpr_atm gpr_atm_no_barrier_clamped_add(gpr_atm* value, gpr_atm delta, gpr_atm min, gpr_atm max); +#ifdef __cplusplus +} +#endif + #endif /* GRPC_IMPL_CODEGEN_ATM_H */ diff --git a/include/grpc/impl/codegen/atm_gcc_atomic.h b/include/grpc/impl/codegen/atm_gcc_atomic.h index 76ce8639141..58797085482 100644 --- a/include/grpc/impl/codegen/atm_gcc_atomic.h +++ b/include/grpc/impl/codegen/atm_gcc_atomic.h @@ -23,6 +23,10 @@ __atomic_* interface. */ #include +#ifdef __cplusplus +extern "C" { +#endif + typedef intptr_t gpr_atm; #define GPR_ATM_MAX INTPTR_MAX #define GPR_ATM_MIN INTPTR_MIN @@ -57,22 +61,22 @@ extern gpr_atm gpr_counter_atm_add; GPR_ATM_INC_ADD_THEN( \ __atomic_fetch_add((p), (intptr_t)(delta), __ATOMIC_ACQ_REL)) -static __inline int gpr_atm_no_barrier_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { +static __inline int gpr_atm_no_barrier_cas(gpr_atm* p, gpr_atm o, gpr_atm n) { return GPR_ATM_INC_CAS_THEN(__atomic_compare_exchange_n( p, &o, n, 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED)); } -static __inline int gpr_atm_acq_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { +static __inline int gpr_atm_acq_cas(gpr_atm* p, gpr_atm o, gpr_atm n) { return GPR_ATM_INC_CAS_THEN(__atomic_compare_exchange_n( p, &o, n, 0, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)); } -static __inline int gpr_atm_rel_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { +static __inline int gpr_atm_rel_cas(gpr_atm* p, gpr_atm o, gpr_atm n) { return GPR_ATM_INC_CAS_THEN(__atomic_compare_exchange_n( p, &o, n, 0, __ATOMIC_RELEASE, __ATOMIC_RELAXED)); } -static __inline int gpr_atm_full_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { +static __inline int gpr_atm_full_cas(gpr_atm* p, gpr_atm o, gpr_atm n) { return GPR_ATM_INC_CAS_THEN(__atomic_compare_exchange_n( p, &o, n, 0, __ATOMIC_ACQ_REL, __ATOMIC_RELAXED)); } @@ -80,4 +84,8 @@ static __inline int gpr_atm_full_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { #define gpr_atm_full_xchg(p, n) \ GPR_ATM_INC_CAS_THEN(__atomic_exchange_n((p), (n), __ATOMIC_ACQ_REL)) +#ifdef __cplusplus +} +#endif + #endif /* GRPC_IMPL_CODEGEN_ATM_GCC_ATOMIC_H */ diff --git a/include/grpc/impl/codegen/atm_gcc_sync.h b/include/grpc/impl/codegen/atm_gcc_sync.h index a9e4da3a0fe..c0010a3469d 100644 --- a/include/grpc/impl/codegen/atm_gcc_sync.h +++ b/include/grpc/impl/codegen/atm_gcc_sync.h @@ -38,24 +38,24 @@ typedef intptr_t gpr_atm; #define gpr_atm_full_barrier() (__sync_synchronize()) -static __inline gpr_atm gpr_atm_acq_load(const gpr_atm *p) { +static __inline gpr_atm gpr_atm_acq_load(const gpr_atm* p) { gpr_atm value = *p; GPR_ATM_LS_BARRIER_(); return value; } -static __inline gpr_atm gpr_atm_no_barrier_load(const gpr_atm *p) { +static __inline gpr_atm gpr_atm_no_barrier_load(const gpr_atm* p) { gpr_atm value = *p; GPR_ATM_COMPILE_BARRIER_(); return value; } -static __inline void gpr_atm_rel_store(gpr_atm *p, gpr_atm value) { +static __inline void gpr_atm_rel_store(gpr_atm* p, gpr_atm value) { GPR_ATM_LS_BARRIER_(); *p = value; } -static __inline void gpr_atm_no_barrier_store(gpr_atm *p, gpr_atm value) { +static __inline void gpr_atm_no_barrier_store(gpr_atm* p, gpr_atm value) { GPR_ATM_COMPILE_BARRIER_(); *p = value; } @@ -72,7 +72,7 @@ static __inline void gpr_atm_no_barrier_store(gpr_atm *p, gpr_atm value) { #define gpr_atm_rel_cas(p, o, n) gpr_atm_acq_cas((p), (o), (n)) #define gpr_atm_full_cas(p, o, n) gpr_atm_acq_cas((p), (o), (n)) -static __inline gpr_atm gpr_atm_full_xchg(gpr_atm *p, gpr_atm n) { +static __inline gpr_atm gpr_atm_full_xchg(gpr_atm* p, gpr_atm n) { gpr_atm cur; do { cur = gpr_atm_acq_load(p); diff --git a/include/grpc/impl/codegen/atm_windows.h b/include/grpc/impl/codegen/atm_windows.h index b868d79aef7..f6b27e5df70 100644 --- a/include/grpc/impl/codegen/atm_windows.h +++ b/include/grpc/impl/codegen/atm_windows.h @@ -28,70 +28,70 @@ typedef intptr_t gpr_atm; #define gpr_atm_full_barrier MemoryBarrier -static __inline gpr_atm gpr_atm_acq_load(const gpr_atm *p) { +static __inline gpr_atm gpr_atm_acq_load(const gpr_atm* p) { gpr_atm result = *p; gpr_atm_full_barrier(); return result; } -static __inline gpr_atm gpr_atm_no_barrier_load(const gpr_atm *p) { +static __inline gpr_atm gpr_atm_no_barrier_load(const gpr_atm* p) { /* TODO(dklempner): Can we implement something better here? */ return gpr_atm_acq_load(p); } -static __inline void gpr_atm_rel_store(gpr_atm *p, gpr_atm value) { +static __inline void gpr_atm_rel_store(gpr_atm* p, gpr_atm value) { gpr_atm_full_barrier(); *p = value; } -static __inline void gpr_atm_no_barrier_store(gpr_atm *p, gpr_atm value) { +static __inline void gpr_atm_no_barrier_store(gpr_atm* p, gpr_atm value) { /* TODO(ctiller): Can we implement something better here? */ gpr_atm_rel_store(p, value); } -static __inline int gpr_atm_no_barrier_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { +static __inline int gpr_atm_no_barrier_cas(gpr_atm* p, gpr_atm o, gpr_atm n) { /** InterlockedCompareExchangePointerNoFence() not available on vista or windows7 */ #ifdef GPR_ARCH_64 return o == (gpr_atm)InterlockedCompareExchangeAcquire64( - (volatile LONGLONG *)p, (LONGLONG)n, (LONGLONG)o); + (volatile LONGLONG*)p, (LONGLONG)n, (LONGLONG)o); #else - return o == (gpr_atm)InterlockedCompareExchangeAcquire((volatile LONG *)p, + return o == (gpr_atm)InterlockedCompareExchangeAcquire((volatile LONG*)p, (LONG)n, (LONG)o); #endif } -static __inline int gpr_atm_acq_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { +static __inline int gpr_atm_acq_cas(gpr_atm* p, gpr_atm o, gpr_atm n) { #ifdef GPR_ARCH_64 return o == (gpr_atm)InterlockedCompareExchangeAcquire64( - (volatile LONGLONG *)p, (LONGLONG)n, (LONGLONG)o); + (volatile LONGLONG*)p, (LONGLONG)n, (LONGLONG)o); #else - return o == (gpr_atm)InterlockedCompareExchangeAcquire((volatile LONG *)p, + return o == (gpr_atm)InterlockedCompareExchangeAcquire((volatile LONG*)p, (LONG)n, (LONG)o); #endif } -static __inline int gpr_atm_rel_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { +static __inline int gpr_atm_rel_cas(gpr_atm* p, gpr_atm o, gpr_atm n) { #ifdef GPR_ARCH_64 return o == (gpr_atm)InterlockedCompareExchangeRelease64( - (volatile LONGLONG *)p, (LONGLONG)n, (LONGLONG)o); + (volatile LONGLONG*)p, (LONGLONG)n, (LONGLONG)o); #else - return o == (gpr_atm)InterlockedCompareExchangeRelease((volatile LONG *)p, + return o == (gpr_atm)InterlockedCompareExchangeRelease((volatile LONG*)p, (LONG)n, (LONG)o); #endif } -static __inline int gpr_atm_full_cas(gpr_atm *p, gpr_atm o, gpr_atm n) { +static __inline int gpr_atm_full_cas(gpr_atm* p, gpr_atm o, gpr_atm n) { #ifdef GPR_ARCH_64 - return o == (gpr_atm)InterlockedCompareExchange64((volatile LONGLONG *)p, + return o == (gpr_atm)InterlockedCompareExchange64((volatile LONGLONG*)p, (LONGLONG)n, (LONGLONG)o); #else - return o == (gpr_atm)InterlockedCompareExchange((volatile LONG *)p, (LONG)n, + return o == (gpr_atm)InterlockedCompareExchange((volatile LONG*)p, (LONG)n, (LONG)o); #endif } -static __inline gpr_atm gpr_atm_no_barrier_fetch_add(gpr_atm *p, +static __inline gpr_atm gpr_atm_no_barrier_fetch_add(gpr_atm* p, gpr_atm delta) { /** Use the CAS operation to get pointer-sized fetch and add */ gpr_atm old; @@ -101,26 +101,26 @@ static __inline gpr_atm gpr_atm_no_barrier_fetch_add(gpr_atm *p, return old; } -static __inline gpr_atm gpr_atm_full_fetch_add(gpr_atm *p, gpr_atm delta) { +static __inline gpr_atm gpr_atm_full_fetch_add(gpr_atm* p, gpr_atm delta) { /** Use a CAS operation to get pointer-sized fetch and add */ gpr_atm old; #ifdef GPR_ARCH_64 do { old = *p; - } while (old != (gpr_atm)InterlockedCompareExchange64((volatile LONGLONG *)p, + } while (old != (gpr_atm)InterlockedCompareExchange64((volatile LONGLONG*)p, (LONGLONG)old + delta, (LONGLONG)old)); #else do { old = *p; } while (old != (gpr_atm)InterlockedCompareExchange( - (volatile LONG *)p, (LONG)old + delta, (LONG)old)); + (volatile LONG*)p, (LONG)old + delta, (LONG)old)); #endif return old; } -static __inline gpr_atm gpr_atm_full_xchg(gpr_atm *p, gpr_atm n) { - return (gpr_atm)InterlockedExchangePointer((PVOID *)p, (PVOID)n); +static __inline gpr_atm gpr_atm_full_xchg(gpr_atm* p, gpr_atm n) { + return (gpr_atm)InterlockedExchangePointer((PVOID*)p, (PVOID)n); } #endif /* GRPC_IMPL_CODEGEN_ATM_WINDOWS_H */ diff --git a/include/grpc/impl/codegen/byte_buffer.h b/include/grpc/impl/codegen/byte_buffer.h index fc333057134..f8dfbd1d7dc 100644 --- a/include/grpc/impl/codegen/byte_buffer.h +++ b/include/grpc/impl/codegen/byte_buffer.h @@ -29,7 +29,7 @@ extern "C" { * * Increases the reference count for all \a slices processed. The user is * responsible for invoking grpc_byte_buffer_destroy on the returned instance.*/ -GRPCAPI grpc_byte_buffer *grpc_raw_byte_buffer_create(grpc_slice *slices, +GRPCAPI grpc_byte_buffer* grpc_raw_byte_buffer_create(grpc_slice* slices, size_t nslices); /** Returns a *compressed* RAW byte buffer instance over the given slices (up to @@ -38,20 +38,20 @@ GRPCAPI grpc_byte_buffer *grpc_raw_byte_buffer_create(grpc_slice *slices, * * Increases the reference count for all \a slices processed. The user is * responsible for invoking grpc_byte_buffer_destroy on the returned instance.*/ -GRPCAPI grpc_byte_buffer *grpc_raw_compressed_byte_buffer_create( - grpc_slice *slices, size_t nslices, grpc_compression_algorithm compression); +GRPCAPI grpc_byte_buffer* grpc_raw_compressed_byte_buffer_create( + grpc_slice* slices, size_t nslices, grpc_compression_algorithm compression); /** Copies input byte buffer \a bb. * * Increases the reference count of all the source slices. The user is * responsible for calling grpc_byte_buffer_destroy over the returned copy. */ -GRPCAPI grpc_byte_buffer *grpc_byte_buffer_copy(grpc_byte_buffer *bb); +GRPCAPI grpc_byte_buffer* grpc_byte_buffer_copy(grpc_byte_buffer* bb); /** Returns the size of the given byte buffer, in bytes. */ -GRPCAPI size_t grpc_byte_buffer_length(grpc_byte_buffer *bb); +GRPCAPI size_t grpc_byte_buffer_length(grpc_byte_buffer* bb); /** Destroys \a byte_buffer deallocating all its memory. */ -GRPCAPI void grpc_byte_buffer_destroy(grpc_byte_buffer *byte_buffer); +GRPCAPI void grpc_byte_buffer_destroy(grpc_byte_buffer* byte_buffer); /** Reader for byte buffers. Iterates over slices in the byte buffer */ struct grpc_byte_buffer_reader; @@ -59,25 +59,25 @@ typedef struct grpc_byte_buffer_reader grpc_byte_buffer_reader; /** Initialize \a reader to read over \a buffer. * Returns 1 upon success, 0 otherwise. */ -GRPCAPI int grpc_byte_buffer_reader_init(grpc_byte_buffer_reader *reader, - grpc_byte_buffer *buffer); +GRPCAPI int grpc_byte_buffer_reader_init(grpc_byte_buffer_reader* reader, + grpc_byte_buffer* buffer); /** Cleanup and destroy \a reader */ -GRPCAPI void grpc_byte_buffer_reader_destroy(grpc_byte_buffer_reader *reader); +GRPCAPI void grpc_byte_buffer_reader_destroy(grpc_byte_buffer_reader* reader); /** Updates \a slice with the next piece of data from from \a reader and returns * 1. Returns 0 at the end of the stream. Caller is responsible for calling * grpc_slice_unref on the result. */ -GRPCAPI int grpc_byte_buffer_reader_next(grpc_byte_buffer_reader *reader, - grpc_slice *slice); +GRPCAPI int grpc_byte_buffer_reader_next(grpc_byte_buffer_reader* reader, + grpc_slice* slice); /** Merge all data from \a reader into single slice */ GRPCAPI grpc_slice -grpc_byte_buffer_reader_readall(grpc_byte_buffer_reader *reader); +grpc_byte_buffer_reader_readall(grpc_byte_buffer_reader* reader); /** Returns a RAW byte buffer instance from the output of \a reader. */ -GRPCAPI grpc_byte_buffer *grpc_raw_byte_buffer_from_reader( - grpc_byte_buffer_reader *reader); +GRPCAPI grpc_byte_buffer* grpc_raw_byte_buffer_from_reader( + grpc_byte_buffer_reader* reader); #ifdef __cplusplus } diff --git a/include/grpc/impl/codegen/byte_buffer_reader.h b/include/grpc/impl/codegen/byte_buffer_reader.h index dc0f15496fd..e06e19558a1 100644 --- a/include/grpc/impl/codegen/byte_buffer_reader.h +++ b/include/grpc/impl/codegen/byte_buffer_reader.h @@ -26,8 +26,8 @@ extern "C" { struct grpc_byte_buffer; struct grpc_byte_buffer_reader { - struct grpc_byte_buffer *buffer_in; - struct grpc_byte_buffer *buffer_out; + struct grpc_byte_buffer* buffer_in; + struct grpc_byte_buffer* buffer_out; /** Different current objects correspond to different types of byte buffers */ union grpc_byte_buffer_reader_current { /** Index into a slice buffer's array of slices */ diff --git a/include/grpc/impl/codegen/fork.h b/include/grpc/impl/codegen/fork.h new file mode 100644 index 00000000000..baec7a2f101 --- /dev/null +++ b/include/grpc/impl/codegen/fork.h @@ -0,0 +1,48 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_IMPL_CODEGEN_FORK_H +#define GRPC_IMPL_CODEGEN_FORK_H + +/** + * gRPC applications should call this before calling fork(). There should be no + * active gRPC function calls between calling grpc_prefork() and + * grpc_postfork_parent()/grpc_postfork_child(). + * + * + * Typical use: + * grpc_prefork(); + * int pid = fork(); + * if (pid) { + * grpc_postfork_parent(); + * // Parent process.. + * } else { + * grpc_postfork_child(); + * // Child process... + * } + */ + +void grpc_prefork(); + +void grpc_postfork_parent(); + +void grpc_postfork_child(); + +void grpc_fork_handlers_auto_register(); + +#endif /* GRPC_IMPL_CODEGEN_FORK_H */ diff --git a/include/grpc/impl/codegen/grpc_types.h b/include/grpc/impl/codegen/grpc_types.h index 65463bb33b6..77844aa2afe 100644 --- a/include/grpc/impl/codegen/grpc_types.h +++ b/include/grpc/impl/codegen/grpc_types.h @@ -39,11 +39,11 @@ typedef enum { } grpc_byte_buffer_type; typedef struct grpc_byte_buffer { - void *reserved; + void* reserved; grpc_byte_buffer_type type; union grpc_byte_buffer_data { struct /* internal */ { - void *reserved[8]; + void* reserved[8]; } reserved; struct grpc_compressed_buffer { grpc_compression_algorithm compression; @@ -84,9 +84,9 @@ typedef enum { } grpc_arg_type; typedef struct grpc_arg_pointer_vtable { - void *(*copy)(void *p); - void (*destroy)(grpc_exec_ctx *exec_ctx, void *p); - int (*cmp)(void *p, void *q); + void* (*copy)(void* p); + void (*destroy)(grpc_exec_ctx* exec_ctx, void* p); + int (*cmp)(void* p, void* q); } grpc_arg_pointer_vtable; /** A single argument... each argument has a key and a value @@ -103,13 +103,13 @@ typedef struct grpc_arg_pointer_vtable { their keys so that it's possible to change them in the future. */ typedef struct { grpc_arg_type type; - char *key; + char* key; union grpc_arg_value { - char *string; + char* string; int integer; struct grpc_arg_pointer { - void *p; - const grpc_arg_pointer_vtable *vtable; + void* p; + const grpc_arg_pointer_vtable* vtable; } pointer; } value; } grpc_arg; @@ -127,7 +127,7 @@ typedef struct { details. */ typedef struct { size_t num_args; - grpc_arg *args; + grpc_arg* args; } grpc_channel_args; /** \defgroup grpc_arg_keys @@ -240,6 +240,9 @@ typedef struct { /** The time between the first and second connection attempts, in ms */ #define GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS \ "grpc.initial_reconnect_backoff_ms" +/** The timeout used on servers for finishing handshaking on an incoming + connection. Defaults to 120 seconds. */ +#define GRPC_ARG_SERVER_HANDSHAKE_TIMEOUT_MS "grpc.server_handshake_timeout_ms" /** This *should* be used for testing only. The caller of the secure_channel_create functions may override the target name used for SSL host name checking using this channel argument which is of @@ -400,7 +403,7 @@ typedef struct grpc_metadata { There is no need to initialize them, and they will be set to garbage during calls to grpc. */ struct /* internal */ { - void *obfuscated[4]; + void* obfuscated[4]; } internal_data; } grpc_metadata; @@ -428,13 +431,13 @@ typedef struct grpc_event { int success; /** The tag passed to grpc_call_start_batch etc to start this operation. Only GRPC_OP_COMPLETE has a tag. */ - void *tag; + void* tag; } grpc_event; typedef struct { size_t count; size_t capacity; - grpc_metadata *metadata; + grpc_metadata* metadata; } grpc_metadata_array; typedef struct { @@ -442,7 +445,7 @@ typedef struct { grpc_slice host; gpr_timespec deadline; uint32_t flags; - void *reserved; + void* reserved; } grpc_call_details; typedef enum { @@ -498,15 +501,15 @@ typedef struct grpc_op { /** Write flags bitset for grpc_begin_messages */ uint32_t flags; /** Reserved for future usage */ - void *reserved; + void* reserved; union grpc_op_data { /** Reserved for future usage */ struct /* internal */ { - void *reserved[8]; + void* reserved[8]; } reserved; struct grpc_op_send_initial_metadata { size_t count; - grpc_metadata *metadata; + grpc_metadata* metadata; /** If \a is_set, \a compression_level will be used for the call. * Otherwise, \a compression_level won't be considered */ struct grpc_op_send_initial_metadata_maybe_compression_level { @@ -524,16 +527,16 @@ typedef struct grpc_op { * and likely empty. The original owner should still call * grpc_byte_buffer_destroy() on this object however. */ - struct grpc_byte_buffer *send_message; + struct grpc_byte_buffer* send_message; } send_message; struct grpc_op_send_status_from_server { size_t trailing_metadata_count; - grpc_metadata *trailing_metadata; + grpc_metadata* trailing_metadata; grpc_status_code status; /** optional: set to NULL if no details need sending, non-NULL if they do * pointer will not be retained past the start_batch call */ - grpc_slice *status_details; + grpc_slice* status_details; } send_status_from_server; /** ownership of the array is with the caller, but ownership of the elements stays with the call object (ie key, value members are owned by the call @@ -541,13 +544,13 @@ typedef struct grpc_op { After the operation completes, call grpc_metadata_array_destroy on this value, or reuse it in a future op. */ struct grpc_op_recv_initial_metadata { - grpc_metadata_array *recv_initial_metadata; + grpc_metadata_array* recv_initial_metadata; } recv_initial_metadata; /** ownership of the byte buffer is moved to the caller; the caller must call grpc_byte_buffer_destroy on this value, or reuse it in a future op. */ struct grpc_op_recv_message { - struct grpc_byte_buffer **recv_message; + struct grpc_byte_buffer** recv_message; } recv_message; struct grpc_op_recv_status_on_client { /** ownership of the array is with the caller, but ownership of the @@ -555,14 +558,18 @@ typedef struct grpc_op { by the call object, trailing_metadata->array is owned by the caller). After the operation completes, call grpc_metadata_array_destroy on this value, or reuse it in a future op. */ - grpc_metadata_array *trailing_metadata; - grpc_status_code *status; - grpc_slice *status_details; + grpc_metadata_array* trailing_metadata; + grpc_status_code* status; + grpc_slice* status_details; + /** If this is not nullptr, it will be populated with the full fidelity + * error string for debugging purposes. The application is responsible + * for freeing the data by using gpr_free(). */ + const char** error_string; } recv_status_on_client; struct grpc_op_recv_close_on_server { /** out argument, set to 1 if the call failed in any way (seen as a cancellation on the server), or 0 if the call succeeded */ - int *cancelled; + int* cancelled; } recv_close_on_server; } data; } grpc_op; @@ -571,10 +578,10 @@ typedef struct grpc_op { typedef struct { /** If non-NULL, will be set to point to a string indicating the LB * policy name. Caller takes ownership. */ - char **lb_policy_name; + char** lb_policy_name; /** If non-NULL, will be set to point to a string containing the * service config used by the channel in JSON form. */ - char **service_config_json; + char** service_config_json; } grpc_channel_info; typedef struct grpc_resource_quota grpc_resource_quota; diff --git a/include/grpc/impl/codegen/port_platform.h b/include/grpc/impl/codegen/port_platform.h index fb4bfc3162f..1906886d5e2 100644 --- a/include/grpc/impl/codegen/port_platform.h +++ b/include/grpc/impl/codegen/port_platform.h @@ -297,6 +297,27 @@ #endif #endif /* GPR_NO_AUTODETECT_PLATFORM */ +/* + * There are platforms for which TLS should not be used even though the + * compiler makes it seem like it's supported (Android NDK < r12b for example). + * This is primarily because of linker problems and toolchain misconfiguration: + * TLS isn't supported until NDK r12b per + * https://developer.android.com/ndk/downloads/revision_history.html + * Since NDK r16, `__NDK_MAJOR__` and `__NDK_MINOR__` are defined in + * . For NDK < r16, users should define these macros, + * e.g. `-D__NDK_MAJOR__=11 -D__NKD_MINOR__=0` for NDK r11. */ +#if defined(__ANDROID__) && defined(__clang__) && defined(GPR_GCC_TLS) +#if __has_include() +#include +#endif /* __has_include() */ +#if defined(__ANDROID__) && defined(__clang__) && defined(__NDK_MAJOR__) && \ + defined(__NDK_MINOR__) && \ + ((__NDK_MAJOR__ < 12) || ((__NDK_MAJOR__ == 12) && (__NDK_MINOR__ < 1))) +#undef GPR_GCC_TLS +#define GPR_PTHREAD_TLS 1 +#endif +#endif /*defined(__ANDROID__) && defined(__clang__) && defined(GPR_GCC_TLS) */ + #if defined(__has_include) #if __has_include() #define GRPC_HAS_CXX11_ATOMIC diff --git a/include/grpc/impl/codegen/slice.h b/include/grpc/impl/codegen/slice.h index 128fa8e1216..11997fcb563 100644 --- a/include/grpc/impl/codegen/slice.h +++ b/include/grpc/impl/codegen/slice.h @@ -42,8 +42,8 @@ typedef struct grpc_slice grpc_slice; constraints (is the callee allowed to modify the slice?) */ typedef struct grpc_slice_refcount_vtable { - void (*ref)(void *); - void (*unref)(grpc_exec_ctx *exec_ctx, void *); + void (*ref)(void*); + void (*unref)(grpc_exec_ctx* exec_ctx, void*); int (*eq)(grpc_slice a, grpc_slice b); uint32_t (*hash)(grpc_slice slice); } grpc_slice_refcount_vtable; @@ -54,20 +54,20 @@ typedef struct grpc_slice_refcount_vtable { Typically client code should not touch this, and use grpc_slice_malloc, grpc_slice_new, or grpc_slice_new_with_len instead. */ typedef struct grpc_slice_refcount { - const grpc_slice_refcount_vtable *vtable; + const grpc_slice_refcount_vtable* vtable; /** If a subset of this slice is taken, use this pointer for the refcount. Typically points back to the refcount itself, however iterning implementations can use this to avoid a verification step on each hash or equality check */ - struct grpc_slice_refcount *sub_refcount; + struct grpc_slice_refcount* sub_refcount; } grpc_slice_refcount; /* Inlined half of grpc_slice is allowed to expand the size of the overall type by this many bytes */ -#define GRPC_SLICE_INLINE_EXTRA_SIZE sizeof(void *) +#define GRPC_SLICE_INLINE_EXTRA_SIZE sizeof(void*) #define GRPC_SLICE_INLINED_SIZE \ - (sizeof(size_t) + sizeof(uint8_t *) - 1 + GRPC_SLICE_INLINE_EXTRA_SIZE) + (sizeof(size_t) + sizeof(uint8_t*) - 1 + GRPC_SLICE_INLINE_EXTRA_SIZE) /** A grpc_slice s, if initialized, represents the byte range s.bytes[0..s.length-1]. @@ -79,10 +79,10 @@ typedef struct grpc_slice_refcount { If the slice does not have a refcount, it represents an inlined small piece of data that is copied by value. */ struct grpc_slice { - struct grpc_slice_refcount *refcount; + struct grpc_slice_refcount* refcount; union grpc_slice_data { struct grpc_slice_refcounted { - uint8_t *bytes; + uint8_t* bytes; size_t length; } refcounted; struct grpc_slice_inlined { @@ -99,10 +99,10 @@ struct grpc_slice { typedef struct { /** This is for internal use only. External users (i.e any code outside grpc * core) MUST NOT use this field */ - grpc_slice *base_slices; + grpc_slice* base_slices; /** slices in the array (Points to the first valid grpc_slice in the array) */ - grpc_slice *slices; + grpc_slice* slices; /** the number of slices in the array */ size_t count; /** the number of slices allocated in the array. External users (i.e any code diff --git a/include/grpc/impl/codegen/sync_generic.h b/include/grpc/impl/codegen/sync_generic.h index e1eea542982..83f905e120f 100644 --- a/include/grpc/impl/codegen/sync_generic.h +++ b/include/grpc/impl/codegen/sync_generic.h @@ -23,16 +23,22 @@ #include /* gpr_event */ -typedef struct { gpr_atm state; } gpr_event; +typedef struct { + gpr_atm state; +} gpr_event; #define GPR_EVENT_INIT \ { 0 } /* gpr_refcount */ -typedef struct { gpr_atm count; } gpr_refcount; +typedef struct { + gpr_atm count; +} gpr_refcount; /* gpr_stats_counter */ -typedef struct { gpr_atm value; } gpr_stats_counter; +typedef struct { + gpr_atm value; +} gpr_stats_counter; #define GPR_STATS_INIT \ { 0 } diff --git a/include/grpc/module.modulemap b/include/grpc/module.modulemap index 342adc0dc93..67136cba8ad 100644 --- a/include/grpc/module.modulemap +++ b/include/grpc/module.modulemap @@ -7,7 +7,6 @@ framework module grpc { header "support/avl.h" header "support/cmdline.h" header "support/cpu.h" - header "support/histogram.h" header "support/host_port.h" header "support/log.h" header "support/log_windows.h" @@ -21,6 +20,7 @@ framework module grpc { header "support/tls.h" header "support/useful.h" header "impl/codegen/atm.h" + header "impl/codegen/fork.h" header "impl/codegen/gpr_slice.h" header "impl/codegen/gpr_types.h" header "impl/codegen/port_platform.h" @@ -36,6 +36,7 @@ framework module grpc { header "impl/codegen/slice.h" header "impl/codegen/status.h" header "impl/codegen/atm.h" + header "impl/codegen/fork.h" header "impl/codegen/gpr_slice.h" header "impl/codegen/gpr_types.h" header "impl/codegen/port_platform.h" @@ -45,6 +46,7 @@ framework module grpc { header "byte_buffer.h" header "byte_buffer_reader.h" header "compression.h" + header "fork.h" header "grpc.h" header "grpc_posix.h" header "grpc_security_constants.h" diff --git a/include/grpc/slice.h b/include/grpc/slice.h index 3f3cff14086..10b6a624b32 100644 --- a/include/grpc/slice.h +++ b/include/grpc/slice.h @@ -44,20 +44,20 @@ GPRAPI grpc_slice grpc_slice_copy(grpc_slice s); /** Create a slice pointing at some data. Calls malloc to allocate a refcount for the object, and arranges that destroy will be called with the pointer passed in at destruction. */ -GPRAPI grpc_slice grpc_slice_new(void *p, size_t len, void (*destroy)(void *)); +GPRAPI grpc_slice grpc_slice_new(void* p, size_t len, void (*destroy)(void*)); /** Equivalent to grpc_slice_new, but with a separate pointer that is passed to the destroy function. This function can be useful when the data is part of a larger structure that must be destroyed when the data is no longer needed. */ -GPRAPI grpc_slice grpc_slice_new_with_user_data(void *p, size_t len, - void (*destroy)(void *), - void *user_data); +GPRAPI grpc_slice grpc_slice_new_with_user_data(void* p, size_t len, + void (*destroy)(void*), + void* user_data); /** Equivalent to grpc_slice_new, but with a two argument destroy function that also takes the slice length. */ -GPRAPI grpc_slice grpc_slice_new_with_len(void *p, size_t len, - void (*destroy)(void *, size_t)); +GPRAPI grpc_slice grpc_slice_new_with_len(void* p, size_t len, + void (*destroy)(void*, size_t)); /** Equivalent to grpc_slice_new(malloc(len), len, free), but saves one malloc() call. @@ -79,19 +79,19 @@ GPRAPI grpc_slice grpc_slice_intern(grpc_slice slice); size_t len = strlen(source); grpc_slice slice = grpc_slice_malloc(len); memcpy(slice->data, source, len); */ -GPRAPI grpc_slice grpc_slice_from_copied_string(const char *source); +GPRAPI grpc_slice grpc_slice_from_copied_string(const char* source); /** Create a slice by copying a buffer. Equivalent to: grpc_slice slice = grpc_slice_malloc(len); memcpy(slice->data, source, len); */ -GPRAPI grpc_slice grpc_slice_from_copied_buffer(const char *source, size_t len); +GPRAPI grpc_slice grpc_slice_from_copied_buffer(const char* source, size_t len); /** Create a slice pointing to constant memory */ -GPRAPI grpc_slice grpc_slice_from_static_string(const char *source); +GPRAPI grpc_slice grpc_slice_from_static_string(const char* source); /** Create a slice pointing to constant memory */ -GPRAPI grpc_slice grpc_slice_from_static_buffer(const void *source, size_t len); +GPRAPI grpc_slice grpc_slice_from_static_buffer(const void* source, size_t len); /** Return a result slice derived from s, which shares a ref count with \a s, where result.data==s.data+begin, and result.length==end-begin. The ref count @@ -106,7 +106,7 @@ GPRAPI grpc_slice grpc_slice_sub_no_ref(grpc_slice s, size_t begin, size_t end); /** Splits s into two: modifies s to be s[0:split], and returns a new slice, sharing a refcount with s, that contains s[split:s.length]. Requires s intialized, split <= s.length */ -GPRAPI grpc_slice grpc_slice_split_tail(grpc_slice *s, size_t split); +GPRAPI grpc_slice grpc_slice_split_tail(grpc_slice* s, size_t split); typedef enum { GRPC_SLICE_REF_TAIL = 1, @@ -117,13 +117,13 @@ typedef enum { /** The same as grpc_slice_split_tail, but with an option to skip altering * refcounts (grpc_slice_split_tail_maybe_ref(..., true) is equivalent to * grpc_slice_split_tail(...)) */ -GPRAPI grpc_slice grpc_slice_split_tail_maybe_ref(grpc_slice *s, size_t split, +GPRAPI grpc_slice grpc_slice_split_tail_maybe_ref(grpc_slice* s, size_t split, grpc_slice_ref_whom ref_whom); /** Splits s into two: modifies s to be s[split:s.length], and returns a new slice, sharing a refcount with s, that contains s[0:split]. Requires s intialized, split <= s.length */ -GPRAPI grpc_slice grpc_slice_split_head(grpc_slice *s, size_t split); +GPRAPI grpc_slice grpc_slice_split_head(grpc_slice* s, size_t split); GPRAPI grpc_slice grpc_empty_slice(void); @@ -136,11 +136,10 @@ GPRAPI int grpc_slice_eq(grpc_slice a, grpc_slice b); The order is arbitrary, and is not guaranteed to be stable across different versions of the API. */ GPRAPI int grpc_slice_cmp(grpc_slice a, grpc_slice b); -GPRAPI int grpc_slice_str_cmp(grpc_slice a, const char *b); -GPRAPI int grpc_slice_buf_cmp(grpc_slice a, const void *b, size_t blen); +GPRAPI int grpc_slice_str_cmp(grpc_slice a, const char* b); /** return non-zero if the first blen bytes of a are equal to b */ -GPRAPI int grpc_slice_buf_start_eq(grpc_slice a, const void *b, size_t blen); +GPRAPI int grpc_slice_buf_start_eq(grpc_slice a, const void* b, size_t blen); /** return the index of the last instance of \a c in \a s, or -1 if not found */ GPRAPI int grpc_slice_rchr(grpc_slice s, char c); @@ -162,7 +161,7 @@ GPRAPI grpc_slice grpc_slice_dup(grpc_slice a); /** Return a copy of slice as a C string. Offers no protection against embedded NULL's. Returned string must be freed with gpr_free. */ -GPRAPI char *grpc_slice_to_c_string(grpc_slice s); +GPRAPI char* grpc_slice_to_c_string(grpc_slice s); #ifdef __cplusplus } diff --git a/include/grpc/slice_buffer.h b/include/grpc/slice_buffer.h index de4b86f777d..6510c151b3c 100644 --- a/include/grpc/slice_buffer.h +++ b/include/grpc/slice_buffer.h @@ -26,13 +26,13 @@ extern "C" { #endif /** initialize a slice buffer */ -GPRAPI void grpc_slice_buffer_init(grpc_slice_buffer *sb); +GPRAPI void grpc_slice_buffer_init(grpc_slice_buffer* sb); /** destroy a slice buffer - unrefs any held elements */ -GPRAPI void grpc_slice_buffer_destroy(grpc_slice_buffer *sb); +GPRAPI void grpc_slice_buffer_destroy(grpc_slice_buffer* sb); /** Add an element to a slice buffer - takes ownership of the slice. This function is allowed to concatenate the passed in slice to the end of some other slice if desired by the slice buffer. */ -GPRAPI void grpc_slice_buffer_add(grpc_slice_buffer *sb, grpc_slice slice); +GPRAPI void grpc_slice_buffer_add(grpc_slice_buffer* sb, grpc_slice slice); /** add an element to a slice buffer - takes ownership of the slice and returns the index of the slice. Guarantees that the slice will not be concatenated at the end of another @@ -40,40 +40,40 @@ GPRAPI void grpc_slice_buffer_add(grpc_slice_buffer *sb, grpc_slice slice); slice at the returned index in sb->slices) The implementation MAY decide to concatenate data at the end of a small slice added in this fashion. */ -GPRAPI size_t grpc_slice_buffer_add_indexed(grpc_slice_buffer *sb, +GPRAPI size_t grpc_slice_buffer_add_indexed(grpc_slice_buffer* sb, grpc_slice slice); -GPRAPI void grpc_slice_buffer_addn(grpc_slice_buffer *sb, grpc_slice *slices, +GPRAPI void grpc_slice_buffer_addn(grpc_slice_buffer* sb, grpc_slice* slices, size_t n); /** add a very small (less than 8 bytes) amount of data to the end of a slice buffer: returns a pointer into which to add the data */ -GPRAPI uint8_t *grpc_slice_buffer_tiny_add(grpc_slice_buffer *sb, size_t len); +GPRAPI uint8_t* grpc_slice_buffer_tiny_add(grpc_slice_buffer* sb, size_t len); /** pop the last buffer, but don't unref it */ -GPRAPI void grpc_slice_buffer_pop(grpc_slice_buffer *sb); +GPRAPI void grpc_slice_buffer_pop(grpc_slice_buffer* sb); /** clear a slice buffer, unref all elements */ -GPRAPI void grpc_slice_buffer_reset_and_unref(grpc_slice_buffer *sb); +GPRAPI void grpc_slice_buffer_reset_and_unref(grpc_slice_buffer* sb); /** swap the contents of two slice buffers */ -GPRAPI void grpc_slice_buffer_swap(grpc_slice_buffer *a, grpc_slice_buffer *b); +GPRAPI void grpc_slice_buffer_swap(grpc_slice_buffer* a, grpc_slice_buffer* b); /** move all of the elements of src into dst */ -GPRAPI void grpc_slice_buffer_move_into(grpc_slice_buffer *src, - grpc_slice_buffer *dst); +GPRAPI void grpc_slice_buffer_move_into(grpc_slice_buffer* src, + grpc_slice_buffer* dst); /** remove n bytes from the end of a slice buffer */ -GPRAPI void grpc_slice_buffer_trim_end(grpc_slice_buffer *src, size_t n, - grpc_slice_buffer *garbage); +GPRAPI void grpc_slice_buffer_trim_end(grpc_slice_buffer* src, size_t n, + grpc_slice_buffer* garbage); /** move the first n bytes of src into dst */ -GPRAPI void grpc_slice_buffer_move_first(grpc_slice_buffer *src, size_t n, - grpc_slice_buffer *dst); +GPRAPI void grpc_slice_buffer_move_first(grpc_slice_buffer* src, size_t n, + grpc_slice_buffer* dst); /** move the first n bytes of src into dst without adding references */ -GPRAPI void grpc_slice_buffer_move_first_no_ref(grpc_slice_buffer *src, +GPRAPI void grpc_slice_buffer_move_first_no_ref(grpc_slice_buffer* src, size_t n, - grpc_slice_buffer *dst); + grpc_slice_buffer* dst); /** move the first n bytes of src into dst (copying them) */ -GPRAPI void grpc_slice_buffer_move_first_into_buffer(grpc_exec_ctx *exec_ctx, - grpc_slice_buffer *src, - size_t n, void *dst); +GPRAPI void grpc_slice_buffer_move_first_into_buffer(grpc_exec_ctx* exec_ctx, + grpc_slice_buffer* src, + size_t n, void* dst); /** take the first slice in the slice buffer */ -GPRAPI grpc_slice grpc_slice_buffer_take_first(grpc_slice_buffer *src); +GPRAPI grpc_slice grpc_slice_buffer_take_first(grpc_slice_buffer* src); /** undo the above with (a possibly different) \a slice */ -GPRAPI void grpc_slice_buffer_undo_take_first(grpc_slice_buffer *src, +GPRAPI void grpc_slice_buffer_undo_take_first(grpc_slice_buffer* src, grpc_slice slice); #ifdef __cplusplus diff --git a/include/grpc/support/alloc.h b/include/grpc/support/alloc.h index 4b59e137f25..c5591982372 100644 --- a/include/grpc/support/alloc.h +++ b/include/grpc/support/alloc.h @@ -28,10 +28,10 @@ extern "C" { #endif typedef struct gpr_allocation_functions { - void *(*malloc_fn)(size_t size); - 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* (*malloc_fn)(size_t size); + 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); } gpr_allocation_functions; /** malloc. @@ -39,17 +39,17 @@ typedef struct gpr_allocation_functions { * The pointer returned is suitably aligned for any kind of variable it could * contain. */ -GPRAPI void *gpr_malloc(size_t size); +GPRAPI void* gpr_malloc(size_t size); /** like malloc, but zero all bytes before returning them */ -GPRAPI void *gpr_zalloc(size_t size); +GPRAPI void* gpr_zalloc(size_t size); /** free */ -GPRAPI void gpr_free(void *ptr); +GPRAPI void gpr_free(void* ptr); /** realloc, never returns NULL */ -GPRAPI void *gpr_realloc(void *p, size_t size); +GPRAPI void* gpr_realloc(void* p, size_t size); /** aligned malloc, never returns NULL, will align to 1 << alignment_log */ -GPRAPI void *gpr_malloc_aligned(size_t size, size_t alignment_log); +GPRAPI void* gpr_malloc_aligned(size_t size, size_t alignment_log); /** free memory allocated by gpr_malloc_aligned */ -GPRAPI void gpr_free_aligned(void *ptr); +GPRAPI void gpr_free_aligned(void* ptr); /** Request the family of allocation functions in \a functions be used. NOTE * that this request will be honored in a *best effort* basis and that no @@ -58,7 +58,7 @@ GPRAPI void gpr_free_aligned(void *ptr); GPRAPI void gpr_set_allocation_functions(gpr_allocation_functions functions); /** Return the family of allocation functions currently in effect. */ -GPRAPI gpr_allocation_functions gpr_get_allocation_functions(); +GPRAPI gpr_allocation_functions gpr_get_allocation_functions(void); #ifdef __cplusplus } diff --git a/include/grpc/support/avl.h b/include/grpc/support/avl.h index d8a5efd2ad5..b5a8c0ffa1c 100644 --- a/include/grpc/support/avl.h +++ b/include/grpc/support/avl.h @@ -28,10 +28,10 @@ extern "C" { /** internal node of an AVL tree */ typedef struct gpr_avl_node { gpr_refcount refs; - void *key; - void *value; - struct gpr_avl_node *left; - struct gpr_avl_node *right; + void* key; + void* value; + struct gpr_avl_node* left; + struct gpr_avl_node* right; long height; } gpr_avl_node; @@ -42,56 +42,56 @@ typedef struct gpr_avl_node { */ typedef struct gpr_avl_vtable { /** destroy a key */ - void (*destroy_key)(void *key, void *user_data); + void (*destroy_key)(void* key, void* user_data); /** copy a key, returning new value */ - void *(*copy_key)(void *key, void *user_data); + void* (*copy_key)(void* key, void* user_data); /** compare key1, key2; return <0 if key1 < key2, >0 if key1 > key2, 0 if key1 == key2 */ - long (*compare_keys)(void *key1, void *key2, void *user_data); + long (*compare_keys)(void* key1, void* key2, void* user_data); /** destroy a value */ - void (*destroy_value)(void *value, void *user_data); + void (*destroy_value)(void* value, void* user_data); /** copy a value */ - void *(*copy_value)(void *value, void *user_data); + void* (*copy_value)(void* value, void* user_data); } gpr_avl_vtable; /** "pointer" to an AVL tree - this is a reference counted object - use gpr_avl_ref to add a reference, gpr_avl_unref when done with a reference */ typedef struct gpr_avl { - const gpr_avl_vtable *vtable; - gpr_avl_node *root; + const gpr_avl_vtable* vtable; + gpr_avl_node* root; } gpr_avl; /** Create an immutable AVL tree. */ -GPRAPI gpr_avl gpr_avl_create(const gpr_avl_vtable *vtable); +GPRAPI gpr_avl gpr_avl_create(const gpr_avl_vtable* vtable); /** Add a reference to an existing tree - returns the tree as a convenience. The optional user_data will be passed to vtable functions. */ -GPRAPI gpr_avl gpr_avl_ref(gpr_avl avl, void *user_data); +GPRAPI gpr_avl gpr_avl_ref(gpr_avl avl, void* user_data); /** Remove a reference to a tree - destroying it if there are no references left. The optional user_data will be passed to vtable functions. */ -GPRAPI void gpr_avl_unref(gpr_avl avl, void *user_data); +GPRAPI void gpr_avl_unref(gpr_avl avl, void* user_data); /** Return a new tree with (key, value) added to avl. implicitly unrefs avl to allow easy chaining. if key exists in avl, the new tree's key entry updated (i.e. a duplicate is not created). The optional user_data will be passed to vtable functions. */ -GPRAPI gpr_avl gpr_avl_add(gpr_avl avl, void *key, void *value, - void *user_data); +GPRAPI gpr_avl gpr_avl_add(gpr_avl avl, void* key, void* value, + void* user_data); /** Return a new tree with key deleted implicitly unrefs avl to allow easy chaining. The optional user_data will be passed to vtable functions. */ -GPRAPI gpr_avl gpr_avl_remove(gpr_avl avl, void *key, void *user_data); +GPRAPI gpr_avl gpr_avl_remove(gpr_avl avl, void* key, void* user_data); /** Lookup key, and return the associated value. Does not mutate avl. Returns NULL if key is not found. The optional user_data will be passed to vtable functions.*/ -GPRAPI void *gpr_avl_get(gpr_avl avl, void *key, void *user_data); +GPRAPI void* gpr_avl_get(gpr_avl avl, void* key, void* user_data); /** Return 1 if avl contains key, 0 otherwise; if it has the key, sets *value to its value. THe optional user_data will be passed to vtable functions. */ -GPRAPI int gpr_avl_maybe_get(gpr_avl avl, void *key, void **value, - void *user_data); +GPRAPI int gpr_avl_maybe_get(gpr_avl avl, void* key, void** value, + void* user_data); /** Return 1 if avl is empty, 0 otherwise */ GPRAPI int gpr_avl_is_empty(gpr_avl avl); diff --git a/include/grpc/support/cmdline.h b/include/grpc/support/cmdline.h index 9f46491b38c..c34a109fbd9 100644 --- a/include/grpc/support/cmdline.h +++ b/include/grpc/support/cmdline.h @@ -55,31 +55,31 @@ typedef struct gpr_cmdline gpr_cmdline; /** Construct a command line parser: takes a short description of the tool doing the parsing */ -GPRAPI gpr_cmdline *gpr_cmdline_create(const char *description); +GPRAPI gpr_cmdline* gpr_cmdline_create(const char* description); /** Add an integer parameter, with a name (used on the command line) and some helpful text (used in the command usage) */ -GPRAPI void gpr_cmdline_add_int(gpr_cmdline *cl, const char *name, - const char *help, int *value); +GPRAPI void gpr_cmdline_add_int(gpr_cmdline* cl, const char* name, + const char* help, int* value); /** The same, for a boolean flag */ -GPRAPI void gpr_cmdline_add_flag(gpr_cmdline *cl, const char *name, - const char *help, int *value); +GPRAPI void gpr_cmdline_add_flag(gpr_cmdline* cl, const char* name, + const char* help, int* value); /** And for a string */ -GPRAPI void gpr_cmdline_add_string(gpr_cmdline *cl, const char *name, - const char *help, char **value); +GPRAPI void gpr_cmdline_add_string(gpr_cmdline* cl, const char* name, + const char* help, const char** value); /** Set a callback for non-named arguments */ GPRAPI void gpr_cmdline_on_extra_arg( - gpr_cmdline *cl, const char *name, const char *help, - void (*on_extra_arg)(void *user_data, const char *arg), void *user_data); + gpr_cmdline* cl, const char* name, const char* help, + void (*on_extra_arg)(void* user_data, const char* arg), void* user_data); /** Enable surviving failure: default behavior is to exit the process */ -GPRAPI void gpr_cmdline_set_survive_failure(gpr_cmdline *cl); +GPRAPI void gpr_cmdline_set_survive_failure(gpr_cmdline* cl); /** Parse the command line; returns 1 on success, on failure either dies (by default) or returns 0 if gpr_cmdline_set_survive_failure() has been called */ -GPRAPI int gpr_cmdline_parse(gpr_cmdline *cl, int argc, char **argv); +GPRAPI int gpr_cmdline_parse(gpr_cmdline* cl, int argc, char** argv); /** Destroy the parser */ -GPRAPI void gpr_cmdline_destroy(gpr_cmdline *cl); +GPRAPI void gpr_cmdline_destroy(gpr_cmdline* cl); /** Get a string describing usage */ -GPRAPI char *gpr_cmdline_usage_string(gpr_cmdline *cl, const char *argv0); +GPRAPI char* gpr_cmdline_usage_string(gpr_cmdline* cl, const char* argv0); #ifdef __cplusplus } diff --git a/include/grpc/support/histogram.h b/include/grpc/support/histogram.h deleted file mode 100644 index 8489daa27e9..00000000000 --- a/include/grpc/support/histogram.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_SUPPORT_HISTOGRAM_H -#define GRPC_SUPPORT_HISTOGRAM_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct gpr_histogram gpr_histogram; - -GPRAPI gpr_histogram *gpr_histogram_create(double resolution, - double max_bucket_start); -GPRAPI void gpr_histogram_destroy(gpr_histogram *h); -GPRAPI void gpr_histogram_add(gpr_histogram *h, double x); - -/** The following merges the second histogram into the first. It only works - if they have the same buckets and resolution. Returns 0 on failure, 1 - on success */ -GPRAPI int gpr_histogram_merge(gpr_histogram *dst, const gpr_histogram *src); - -GPRAPI double gpr_histogram_percentile(gpr_histogram *histogram, - double percentile); -GPRAPI double gpr_histogram_mean(gpr_histogram *histogram); -GPRAPI double gpr_histogram_stddev(gpr_histogram *histogram); -GPRAPI double gpr_histogram_variance(gpr_histogram *histogram); -GPRAPI double gpr_histogram_maximum(gpr_histogram *histogram); -GPRAPI double gpr_histogram_minimum(gpr_histogram *histogram); -GPRAPI double gpr_histogram_count(gpr_histogram *histogram); -GPRAPI double gpr_histogram_sum(gpr_histogram *histogram); -GPRAPI double gpr_histogram_sum_of_squares(gpr_histogram *histogram); - -GPRAPI const uint32_t *gpr_histogram_get_contents(gpr_histogram *histogram, - size_t *count); -GPRAPI void gpr_histogram_merge_contents(gpr_histogram *histogram, - const uint32_t *data, - size_t data_count, double min_seen, - double max_seen, double sum, - double sum_of_squares, double count); - -#ifdef __cplusplus -} -#endif - -#endif /* GRPC_SUPPORT_HISTOGRAM_H */ diff --git a/include/grpc/support/host_port.h b/include/grpc/support/host_port.h index 41592dfe26e..9805811bfb6 100644 --- a/include/grpc/support/host_port.h +++ b/include/grpc/support/host_port.h @@ -35,14 +35,14 @@ extern "C" { destroyed using gpr_free(). In the unlikely event of an error, returns -1 and sets *out to NULL. */ -GPRAPI int gpr_join_host_port(char **out, const char *host, int port); +GPRAPI int gpr_join_host_port(char** out, const char* host, int port); /** Given a name in the form "host:port" or "[ho:st]:port", split into hostname and port number, into newly allocated strings, which must later be destroyed using gpr_free(). Return 1 on success, 0 on failure. Guarantees *host and *port == NULL on failure. */ -GPRAPI int gpr_split_host_port(const char *name, char **host, char **port); +GPRAPI int gpr_split_host_port(const char* name, char** host, char** port); #ifdef __cplusplus } diff --git a/include/grpc/support/log.h b/include/grpc/support/log.h index a22fb6a6e26..9cce4b1ae79 100644 --- a/include/grpc/support/log.h +++ b/include/grpc/support/log.h @@ -50,7 +50,7 @@ typedef enum gpr_log_severity { #define GPR_LOG_VERBOSITY_UNSET -1 /** Returns a string representation of the log severity */ -GPRAPI const char *gpr_log_severity_string(gpr_log_severity severity); +GPRAPI const char* gpr_log_severity_string(gpr_log_severity severity); /** Macros to build log contexts at various severity levels */ #define GPR_DEBUG __FILE__, __LINE__, GPR_LOG_SEVERITY_DEBUG @@ -59,28 +59,28 @@ GPRAPI const char *gpr_log_severity_string(gpr_log_severity severity); /** Log a message. It's advised to use GPR_xxx above to generate the context * for each message */ -GPRAPI void gpr_log(const char *file, int line, gpr_log_severity severity, - const char *format, ...) GPR_PRINT_FORMAT_CHECK(4, 5); +GPRAPI void gpr_log(const char* file, int line, gpr_log_severity severity, + const char* format, ...) GPR_PRINT_FORMAT_CHECK(4, 5); -GPRAPI void gpr_log_message(const char *file, int line, - gpr_log_severity severity, const char *message); +GPRAPI void gpr_log_message(const char* file, int line, + gpr_log_severity severity, const char* message); /** Set global log verbosity */ GPRAPI void gpr_set_log_verbosity(gpr_log_severity min_severity_to_print); -GPRAPI void gpr_log_verbosity_init(); +GPRAPI void gpr_log_verbosity_init(void); /** Log overrides: applications can use this API to intercept logging calls and use their own implementations */ typedef struct { - const char *file; + const char* file; int line; gpr_log_severity severity; - const char *message; + const char* message; } gpr_log_func_args; -typedef void (*gpr_log_func)(gpr_log_func_args *args); +typedef void (*gpr_log_func)(gpr_log_func_args* args); GPRAPI void gpr_set_log_function(gpr_log_func func); /** abort() the process if x is zero, having written a line to the log. diff --git a/include/grpc/support/log_windows.h b/include/grpc/support/log_windows.h index b530fd50d63..e833f9d9dfd 100644 --- a/include/grpc/support/log_windows.h +++ b/include/grpc/support/log_windows.h @@ -29,7 +29,7 @@ extern "C" { * formatted error message, corresponding to the error messageid. * Use in conjunction with GetLastError() et al. */ -GPRAPI char *gpr_format_message(int messageid); +GPRAPI char* gpr_format_message(int messageid); #ifdef __cplusplus } diff --git a/include/grpc/support/string_util.h b/include/grpc/support/string_util.h index c4fc159d059..2c7460fa157 100644 --- a/include/grpc/support/string_util.h +++ b/include/grpc/support/string_util.h @@ -29,7 +29,7 @@ extern "C" { /** Returns a copy of src that can be passed to gpr_free(). If allocation fails or if src is NULL, returns NULL. */ -GPRAPI char *gpr_strdup(const char *src); +GPRAPI char* gpr_strdup(const char* src); /** printf to a newly-allocated string. The set of supported formats may vary between platforms. @@ -39,7 +39,7 @@ GPRAPI char *gpr_strdup(const char *src); On error, returns -1 and sets *strp to NULL. If the format string is bad, the result is undefined. */ -GPRAPI int gpr_asprintf(char **strp, const char *format, ...) +GPRAPI int gpr_asprintf(char** strp, const char* format, ...) GPR_PRINT_FORMAT_CHECK(2, 3); #ifdef __cplusplus diff --git a/include/grpc/support/subprocess.h b/include/grpc/support/subprocess.h index c06e6296372..175f7b50eba 100644 --- a/include/grpc/support/subprocess.h +++ b/include/grpc/support/subprocess.h @@ -28,14 +28,14 @@ extern "C" { typedef struct gpr_subprocess gpr_subprocess; /** .exe on windows, empty on unices */ -GPRAPI const char *gpr_subprocess_binary_extension(); +GPRAPI const char* gpr_subprocess_binary_extension(); -GPRAPI gpr_subprocess *gpr_subprocess_create(int argc, const char **argv); +GPRAPI gpr_subprocess* gpr_subprocess_create(int argc, const char** argv); /** if subprocess has not been joined, kill it */ -GPRAPI void gpr_subprocess_destroy(gpr_subprocess *p); +GPRAPI void gpr_subprocess_destroy(gpr_subprocess* p); /** returns exit status; can be called at most once */ -GPRAPI int gpr_subprocess_join(gpr_subprocess *p); -GPRAPI void gpr_subprocess_interrupt(gpr_subprocess *p); +GPRAPI int gpr_subprocess_join(gpr_subprocess* p); +GPRAPI void gpr_subprocess_interrupt(gpr_subprocess* p); #ifdef __cplusplus } // extern "C" diff --git a/include/grpc/support/sync.h b/include/grpc/support/sync.h index ddb85808c71..75192673a6f 100644 --- a/include/grpc/support/sync.h +++ b/include/grpc/support/sync.h @@ -34,26 +34,26 @@ extern "C" { gpr_mu are uninitialized when first declared. */ /** Initialize *mu. Requires: *mu uninitialized. */ -GPRAPI void gpr_mu_init(gpr_mu *mu); +GPRAPI void gpr_mu_init(gpr_mu* mu); /** Cause *mu no longer to be initialized, freeing any memory in use. Requires: - *mu initialized; no other concurrent operation on *mu. */ -GPRAPI void gpr_mu_destroy(gpr_mu *mu); + *mu initialized; no other concurrent operation on *mu. */ +GPRAPI void gpr_mu_destroy(gpr_mu* mu); /** Wait until no thread has a lock on *mu, cause the calling thread to own an exclusive lock on *mu, then return. May block indefinitely or crash if the calling thread has a lock on *mu. Requires: *mu initialized. */ -GPRAPI void gpr_mu_lock(gpr_mu *mu); +GPRAPI void gpr_mu_lock(gpr_mu* mu); /** Release an exclusive lock on *mu held by the calling thread. Requires: *mu initialized; the calling thread holds an exclusive lock on *mu. */ -GPRAPI void gpr_mu_unlock(gpr_mu *mu); +GPRAPI void gpr_mu_unlock(gpr_mu* mu); /** Without blocking, attempt to acquire an exclusive lock on *mu for the calling thread, then return non-zero iff success. Fail, if any thread holds the lock; succeeds with high probability if no thread holds the lock. Requires: *mu initialized. */ -GPRAPI int gpr_mu_trylock(gpr_mu *mu); +GPRAPI int gpr_mu_trylock(gpr_mu* mu); /** --- Condition variable interface --- @@ -62,11 +62,11 @@ GPRAPI int gpr_mu_trylock(gpr_mu *mu); uninitialized when first declared. */ /** Initialize *cv. Requires: *cv uninitialized. */ -GPRAPI void gpr_cv_init(gpr_cv *cv); +GPRAPI void gpr_cv_init(gpr_cv* cv); /** Cause *cv no longer to be initialized, freeing any memory in use. Requires: - *cv initialized; no other concurrent operation on *cv.*/ -GPRAPI void gpr_cv_destroy(gpr_cv *cv); + *cv initialized; no other concurrent operation on *cv.*/ +GPRAPI void gpr_cv_destroy(gpr_cv* cv); /** Atomically release *mu and wait on *cv. When the calling thread is woken from *cv or the deadline abs_deadline is exceeded, execute gpr_mu_lock(mu) @@ -75,16 +75,16 @@ GPRAPI void gpr_cv_destroy(gpr_cv *cv); an absolute deadline, or a GPR_TIMESPAN. May return even when not woken explicitly. Requires: *mu and *cv initialized; the calling thread holds an exclusive lock on *mu. */ -GPRAPI int gpr_cv_wait(gpr_cv *cv, gpr_mu *mu, gpr_timespec abs_deadline); +GPRAPI int gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline); /** If any threads are waiting on *cv, wake at least one. Clients may treat this as an optimization of gpr_cv_broadcast() for use in the case where waking more than one waiter is not useful. Requires: *cv initialized. */ -GPRAPI void gpr_cv_signal(gpr_cv *cv); +GPRAPI void gpr_cv_signal(gpr_cv* cv); /** Wake all threads waiting on *cv. Requires: *cv initialized. */ -GPRAPI void gpr_cv_broadcast(gpr_cv *cv); +GPRAPI void gpr_cv_broadcast(gpr_cv* cv); /** --- One-time initialization --- @@ -97,7 +97,7 @@ GPRAPI void gpr_cv_broadcast(gpr_cv *cv); If multiple threads call gpr_once() on the same gpr_once instance, one of them will call (*init_routine)(), and the others will block until that call finishes.*/ -GPRAPI void gpr_once_init(gpr_once *once, void (*init_routine)(void)); +GPRAPI void gpr_once_init(gpr_once* once, void (*init_routine)(void)); /** --- One-time event notification --- @@ -107,51 +107,51 @@ GPRAPI void gpr_once_init(gpr_once *once, void (*init_routine)(void)); It requires no destruction. */ /** Initialize *ev. */ -GPRAPI void gpr_event_init(gpr_event *ev); +GPRAPI void gpr_event_init(gpr_event* ev); /** Set *ev so that gpr_event_get() and gpr_event_wait() will return value. Requires: *ev initialized; value != NULL; no prior or concurrent calls to gpr_event_set(ev, ...) since initialization. */ -GPRAPI void gpr_event_set(gpr_event *ev, void *value); +GPRAPI void gpr_event_set(gpr_event* ev, void* value); /** Return the value set by gpr_event_set(ev, ...), or NULL if no such call has completed. If the result is non-NULL, all operations that occurred prior to the gpr_event_set(ev, ...) set will be visible after this call returns. Requires: *ev initialized. This operation is faster than acquiring a mutex on most platforms. */ -GPRAPI void *gpr_event_get(gpr_event *ev); +GPRAPI void* gpr_event_get(gpr_event* ev); /** Wait until *ev is set by gpr_event_set(ev, ...), or abs_deadline is exceeded, then return gpr_event_get(ev). Requires: *ev initialized. Use abs_deadline==gpr_inf_future for no deadline. When the event has been signalled before the call, this operation is faster than acquiring a mutex on most platforms. */ -GPRAPI void *gpr_event_wait(gpr_event *ev, gpr_timespec abs_deadline); +GPRAPI void* gpr_event_wait(gpr_event* ev, gpr_timespec abs_deadline); /** --- Reference counting --- These calls act on the type gpr_refcount. It requires no destruction. */ /** Initialize *r to value n. */ -GPRAPI void gpr_ref_init(gpr_refcount *r, int n); +GPRAPI void gpr_ref_init(gpr_refcount* r, int n); /** Increment the reference count *r. Requires *r initialized. */ -GPRAPI void gpr_ref(gpr_refcount *r); +GPRAPI void gpr_ref(gpr_refcount* r); /** Increment the reference count *r. Requires *r initialized. Crashes if refcount is zero */ -GPRAPI void gpr_ref_non_zero(gpr_refcount *r); +GPRAPI void gpr_ref_non_zero(gpr_refcount* r); /** Increment the reference count *r by n. Requires *r initialized, n > 0. */ -GPRAPI void gpr_refn(gpr_refcount *r, int n); +GPRAPI void gpr_refn(gpr_refcount* r, int n); /** Decrement the reference count *r and return non-zero iff it has reached zero. . Requires *r initialized. */ -GPRAPI int gpr_unref(gpr_refcount *r); +GPRAPI int gpr_unref(gpr_refcount* r); /** Return non-zero iff the reference count of *r is one, and thus is owned by exactly one object. */ -GPRAPI int gpr_ref_is_unique(gpr_refcount *r); +GPRAPI int gpr_ref_is_unique(gpr_refcount* r); /** --- Stats counters --- @@ -162,13 +162,13 @@ GPRAPI int gpr_ref_is_unique(gpr_refcount *r); synchronize other events. */ /** Initialize *c to the value n. */ -GPRAPI void gpr_stats_init(gpr_stats_counter *c, intptr_t n); +GPRAPI void gpr_stats_init(gpr_stats_counter* c, intptr_t n); /** *c += inc. Requires: *c initialized. */ -GPRAPI void gpr_stats_inc(gpr_stats_counter *c, intptr_t inc); +GPRAPI void gpr_stats_inc(gpr_stats_counter* c, intptr_t inc); /** Return *c. Requires: *c initialized. */ -GPRAPI intptr_t gpr_stats_read(const gpr_stats_counter *c); +GPRAPI intptr_t gpr_stats_read(const gpr_stats_counter* c); /** ==================Example use of interface=================== A producer-consumer queue of up to N integers, @@ -280,14 +280,14 @@ namespace grpc_core { class mu_guard { public: - mu_guard(gpr_mu *mu) : mu_(mu) { gpr_mu_lock(mu); } + mu_guard(gpr_mu* mu) : mu_(mu) { gpr_mu_lock(mu); } ~mu_guard() { gpr_mu_unlock(mu_); } - mu_guard(const mu_guard &) = delete; - mu_guard &operator=(const mu_guard &) = delete; + mu_guard(const mu_guard&) = delete; + mu_guard& operator=(const mu_guard&) = delete; private: - gpr_mu *const mu_; + gpr_mu* const mu_; }; } // namespace grpc_core diff --git a/include/grpc/support/thd.h b/include/grpc/support/thd.h index 25bd8f1238a..225d9d6c755 100644 --- a/include/grpc/support/thd.h +++ b/include/grpc/support/thd.h @@ -44,23 +44,23 @@ typedef struct { in *t, and return true. If there are insufficient resources, return false. If options==NULL, default options are used. The thread is immediately runnable, and exits when (*thd_body)() returns. */ -GPRAPI int gpr_thd_new(gpr_thd_id *t, void (*thd_body)(void *arg), void *arg, - const gpr_thd_options *options); +GPRAPI int gpr_thd_new(gpr_thd_id* t, void (*thd_body)(void* arg), void* arg, + const gpr_thd_options* options); /** Return a gpr_thd_options struct with all fields set to defaults. */ GPRAPI gpr_thd_options gpr_thd_options_default(void); /** Set the thread to become detached on startup - this is the default. */ -GPRAPI void gpr_thd_options_set_detached(gpr_thd_options *options); +GPRAPI void gpr_thd_options_set_detached(gpr_thd_options* options); /** Set the thread to become joinable - mutually exclusive with detached. */ -GPRAPI void gpr_thd_options_set_joinable(gpr_thd_options *options); +GPRAPI void gpr_thd_options_set_joinable(gpr_thd_options* options); /** Returns non-zero if the option detached is set. */ -GPRAPI int gpr_thd_options_is_detached(const gpr_thd_options *options); +GPRAPI int gpr_thd_options_is_detached(const gpr_thd_options* options); /** Returns non-zero if the option joinable is set. */ -GPRAPI int gpr_thd_options_is_joinable(const gpr_thd_options *options); +GPRAPI int gpr_thd_options_is_joinable(const gpr_thd_options* options); /** Returns the identifier of the current thread. */ GPRAPI gpr_thd_id gpr_thd_currentid(void); diff --git a/include/grpc/support/tls_gcc.h b/include/grpc/support/tls_gcc.h index e6d8c014472..1b91d22be12 100644 --- a/include/grpc/support/tls_gcc.h +++ b/include/grpc/support/tls_gcc.h @@ -26,44 +26,6 @@ /** Thread local storage based on gcc compiler primitives. #include tls.h to use this - and see that file for documentation */ -#ifndef NDEBUG - -struct gpr_gcc_thread_local { - intptr_t value; - bool *inited; -}; - -#define GPR_TLS_DECL(name) \ - static bool name##_inited = false; \ - static __thread struct gpr_gcc_thread_local name = {0, &(name##_inited)} - -#define gpr_tls_init(tls) \ - do { \ - GPR_ASSERT(*((tls)->inited) == false); \ - *((tls)->inited) = true; \ - } while (0) - -/** It is allowed to call gpr_tls_init after gpr_tls_destroy is called. */ -#define gpr_tls_destroy(tls) \ - do { \ - GPR_ASSERT(*((tls)->inited)); \ - *((tls)->inited) = false; \ - } while (0) - -#define gpr_tls_set(tls, new_value) \ - do { \ - GPR_ASSERT(*((tls)->inited)); \ - (tls)->value = (new_value); \ - } while (0) - -#define gpr_tls_get(tls) \ - ({ \ - GPR_ASSERT(*((tls)->inited)); \ - (tls)->value; \ - }) - -#else /* NDEBUG */ - struct gpr_gcc_thread_local { intptr_t value; }; @@ -80,6 +42,4 @@ struct gpr_gcc_thread_local { #define gpr_tls_set(tls, new_value) (((tls)->value) = (new_value)) #define gpr_tls_get(tls) ((tls)->value) -#endif /* NDEBUG */ - #endif /* GRPC_SUPPORT_TLS_GCC_H */ diff --git a/include/grpc/support/tls_pthread.h b/include/grpc/support/tls_pthread.h index a68b45569ac..fb0edd8e744 100644 --- a/include/grpc/support/tls_pthread.h +++ b/include/grpc/support/tls_pthread.h @@ -37,7 +37,7 @@ struct gpr_pthread_thread_local { #ifdef __cplusplus extern "C" { #endif -intptr_t gpr_tls_set(struct gpr_pthread_thread_local *tls, intptr_t value); +intptr_t gpr_tls_set(struct gpr_pthread_thread_local* tls, intptr_t value); #ifdef __cplusplus } #endif diff --git a/package.json b/package.json index a0f0ff1710d..2b7930ce70c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "grpc", - "version": "1.8.0-dev", + "version": "1.7.2", "author": "Google Inc.", "description": "gRPC Library for Node", "homepage": "https://grpc.io/", diff --git a/package.xml b/package.xml index 9dee62f871c..b4d8c886930 100644 --- a/package.xml +++ b/package.xml @@ -13,8 +13,8 @@ 2017-08-24 - 1.8.0dev - 1.8.0dev + 1.9.0dev + 1.9.0dev beta @@ -64,7 +64,6 @@ - @@ -87,6 +86,7 @@ + @@ -96,19 +96,21 @@ + + - + @@ -125,7 +127,7 @@ - + @@ -134,7 +136,6 @@ - @@ -169,6 +170,7 @@ + @@ -181,6 +183,7 @@ + @@ -355,7 +358,9 @@ - + + + @@ -425,7 +430,6 @@ - @@ -440,6 +444,8 @@ + + diff --git a/requirements.txt b/requirements.txt index 12969958aee..c976cef4cb8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,6 +3,6 @@ coverage>=4.0 cython>=0.23 enum34>=1.0.4 futures>=2.2.0 -protobuf>=3.2.0 +protobuf>=3.5.0.post1 six>=1.10 wheel>=0.29 diff --git a/setup.py b/setup.py index bf8aea6b6f2..73af9ebc4af 100644 --- a/setup.py +++ b/setup.py @@ -173,7 +173,7 @@ if "win32" in sys.platform: # on msvc, but only for 32 bits DEFINE_MACROS += (('NTDDI_VERSION', 0x06000000),) else: - DEFINE_MACROS += (('HAVE_CONFIG_H', 1),) + DEFINE_MACROS += (('HAVE_CONFIG_H', 1), ('GRPC_ENABLE_FORK_SUPPORT', 1),) LDFLAGS = tuple(EXTRA_LINK_ARGS) CFLAGS = tuple(EXTRA_COMPILE_ARGS) @@ -181,6 +181,7 @@ if "linux" in sys.platform or "darwin" in sys.platform: pymodinit_type = 'PyObject*' if PY3 else 'void' pymodinit = '__attribute__((visibility ("default"))) {}'.format(pymodinit_type) DEFINE_MACROS += (('PyMODINIT_FUNC', pymodinit),) + DEFINE_MACROS += (('GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK', 1),) # By default, Python3 distutils enforces compatibility of # c plugins (.so files) with the OSX version Python3 was built with. @@ -237,7 +238,7 @@ INSTALL_REQUIRES = ( 'six>=1.5.2', # TODO(atash): eventually split the grpcio package into a metapackage # depending on protobuf and the runtime component (independent of protobuf) - 'protobuf>=3.3.0', + 'protobuf>=3.5.0.post1', ) if not PY3: diff --git a/src/compiler/cpp_generator.cc b/src/compiler/cpp_generator.cc index 253280bd244..dec8cd0f25f 100644 --- a/src/compiler/cpp_generator.cc +++ b/src/compiler/cpp_generator.cc @@ -32,15 +32,15 @@ grpc::string as_string(T x) { return out.str(); } -inline bool ClientOnlyStreaming(const grpc_generator::Method *method) { +inline bool ClientOnlyStreaming(const grpc_generator::Method* method) { return method->ClientStreaming() && !method->ServerStreaming(); } -inline bool ServerOnlyStreaming(const grpc_generator::Method *method) { +inline bool ServerOnlyStreaming(const grpc_generator::Method* method) { return !method->ClientStreaming() && method->ServerStreaming(); } -grpc::string FilenameIdentifier(const grpc::string &filename) { +grpc::string FilenameIdentifier(const grpc::string& filename) { grpc::string result; for (unsigned i = 0; i < filename.size(); i++) { char c = filename[i]; @@ -58,19 +58,19 @@ grpc::string FilenameIdentifier(const grpc::string &filename) { } // namespace template -T *array_end(T (&array)[N]) { +T* array_end(T (&array)[N]) { return array + N; } -void PrintIncludes(grpc_generator::Printer *printer, - const std::vector &headers, - const Parameters ¶ms) { +void PrintIncludes(grpc_generator::Printer* printer, + const std::vector& headers, + const Parameters& params) { std::map vars; vars["l"] = params.use_system_headers ? '<' : '"'; vars["r"] = params.use_system_headers ? '>' : '"'; - auto &s = params.grpc_search_path; + auto& s = params.grpc_search_path; if (!s.empty()) { vars["l"] += s; if (s[s.size() - 1] != '/') { @@ -84,8 +84,8 @@ void PrintIncludes(grpc_generator::Printer *printer, } } -grpc::string GetHeaderPrologue(grpc_generator::File *file, - const Parameters & /*params*/) { +grpc::string GetHeaderPrologue(grpc_generator::File* file, + const Parameters& /*params*/) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. @@ -104,7 +104,7 @@ grpc::string GetHeaderPrologue(grpc_generator::File *file, grpc::string leading_comments = file->GetLeadingComments("//"); if (!leading_comments.empty()) { printer->Print(vars, "// Original file comments:\n"); - printer->Print(leading_comments.c_str()); + printer->PrintRaw(leading_comments.c_str()); } printer->Print(vars, "#ifndef GRPC_$filename_identifier$__INCLUDED\n"); printer->Print(vars, "#define GRPC_$filename_identifier$__INCLUDED\n"); @@ -116,15 +116,15 @@ grpc::string GetHeaderPrologue(grpc_generator::File *file, return output; } -grpc::string GetHeaderIncludes(grpc_generator::File *file, - const Parameters ¶ms) { +grpc::string GetHeaderIncludes(grpc_generator::File* file, + const Parameters& params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. auto printer = file->CreatePrinter(&output); std::map vars; - static const char *headers_strs[] = { + static const char* headers_strs[] = { "grpc++/impl/codegen/async_stream.h", "grpc++/impl/codegen/async_unary_call.h", "grpc++/impl/codegen/method_handler_impl.h", @@ -158,8 +158,8 @@ grpc::string GetHeaderIncludes(grpc_generator::File *file, } void PrintHeaderClientMethodInterfaces( - grpc_generator::Printer *printer, const grpc_generator::Method *method, - std::map *vars, bool is_public) { + grpc_generator::Printer* printer, const grpc_generator::Method* method, + std::map* vars, bool is_public) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -355,9 +355,9 @@ void PrintHeaderClientMethodInterfaces( } } -void PrintHeaderClientMethod(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars, +void PrintHeaderClientMethod(grpc_generator::Printer* printer, + const grpc_generator::Method* method, + std::map* vars, bool is_public) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); @@ -542,17 +542,17 @@ void PrintHeaderClientMethod(grpc_generator::Printer *printer, } } -void PrintHeaderClientMethodData(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { +void PrintHeaderClientMethodData(grpc_generator::Printer* printer, + const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); printer->Print(*vars, "const ::grpc::internal::RpcMethod rpcmethod_$Method$_;\n"); } -void PrintHeaderServerMethodSync(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { +void PrintHeaderServerMethodSync(grpc_generator::Printer* printer, + const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -584,9 +584,9 @@ void PrintHeaderServerMethodSync(grpc_generator::Printer *printer, printer->Print(method->GetTrailingComments("//").c_str()); } -void PrintHeaderServerMethodAsync(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { +void PrintHeaderServerMethodAsync(grpc_generator::Printer* printer, + const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -700,8 +700,8 @@ void PrintHeaderServerMethodAsync(grpc_generator::Printer *printer, } void PrintHeaderServerMethodStreamedUnary( - grpc_generator::Printer *printer, const grpc_generator::Method *method, - std::map *vars) { + grpc_generator::Printer* printer, const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -751,8 +751,8 @@ void PrintHeaderServerMethodStreamedUnary( } void PrintHeaderServerMethodSplitStreaming( - grpc_generator::Printer *printer, const grpc_generator::Method *method, - std::map *vars) { + grpc_generator::Printer* printer, const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -804,8 +804,8 @@ void PrintHeaderServerMethodSplitStreaming( } void PrintHeaderServerMethodGeneric( - grpc_generator::Printer *printer, const grpc_generator::Method *method, - std::map *vars) { + grpc_generator::Printer* printer, const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -873,9 +873,9 @@ void PrintHeaderServerMethodGeneric( printer->Print(*vars, "};\n"); } -void PrintHeaderService(grpc_generator::Printer *printer, - const grpc_generator::Service *service, - std::map *vars) { +void PrintHeaderService(grpc_generator::Printer* printer, + const grpc_generator::Service* service, + std::map* vars) { (*vars)["Service"] = service->name(); printer->Print(service->GetLeadingComments("//").c_str()); @@ -1050,8 +1050,8 @@ void PrintHeaderService(grpc_generator::Printer *printer, printer->Print(service->GetTrailingComments("//").c_str()); } -grpc::string GetHeaderServices(grpc_generator::File *file, - const Parameters ¶ms) { +grpc::string GetHeaderServices(grpc_generator::File* file, + const Parameters& params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. @@ -1081,8 +1081,8 @@ grpc::string GetHeaderServices(grpc_generator::File *file, return output; } -grpc::string GetHeaderEpilogue(grpc_generator::File *file, - const Parameters & /*params*/) { +grpc::string GetHeaderEpilogue(grpc_generator::File* file, + const Parameters& /*params*/) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. @@ -1110,8 +1110,8 @@ grpc::string GetHeaderEpilogue(grpc_generator::File *file, return output; } -grpc::string GetSourcePrologue(grpc_generator::File *file, - const Parameters & /*params*/) { +grpc::string GetSourcePrologue(grpc_generator::File* file, + const Parameters& /*params*/) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. @@ -1135,15 +1135,15 @@ grpc::string GetSourcePrologue(grpc_generator::File *file, return output; } -grpc::string GetSourceIncludes(grpc_generator::File *file, - const Parameters ¶ms) { +grpc::string GetSourceIncludes(grpc_generator::File* file, + const Parameters& params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. auto printer = file->CreatePrinter(&output); std::map vars; - static const char *headers_strs[] = { + static const char* headers_strs[] = { "grpc++/impl/codegen/async_stream.h", "grpc++/impl/codegen/async_unary_call.h", "grpc++/impl/codegen/channel_interface.h", @@ -1169,9 +1169,9 @@ grpc::string GetSourceIncludes(grpc_generator::File *file, return output; } -void PrintSourceClientMethod(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { +void PrintSourceClientMethod(grpc_generator::Printer* printer, + const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -1305,9 +1305,9 @@ void PrintSourceClientMethod(grpc_generator::Printer *printer, } } -void PrintSourceServerMethod(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { +void PrintSourceServerMethod(grpc_generator::Printer* printer, + const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -1364,9 +1364,9 @@ void PrintSourceServerMethod(grpc_generator::Printer *printer, } } -void PrintSourceService(grpc_generator::Printer *printer, - const grpc_generator::Service *service, - std::map *vars) { +void PrintSourceService(grpc_generator::Printer* printer, + const grpc_generator::Service* service, + std::map* vars) { (*vars)["Service"] = service->name(); if (service->method_count() > 0) { @@ -1481,8 +1481,8 @@ void PrintSourceService(grpc_generator::Printer *printer, } } -grpc::string GetSourceServices(grpc_generator::File *file, - const Parameters ¶ms) { +grpc::string GetSourceServices(grpc_generator::File* file, + const Parameters& params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. @@ -1510,8 +1510,8 @@ grpc::string GetSourceServices(grpc_generator::File *file, return output; } -grpc::string GetSourceEpilogue(grpc_generator::File *file, - const Parameters & /*params*/) { +grpc::string GetSourceEpilogue(grpc_generator::File* file, + const Parameters& /*params*/) { grpc::string temp; if (!file->package().empty()) { @@ -1529,8 +1529,8 @@ grpc::string GetSourceEpilogue(grpc_generator::File *file, } // TODO(mmukhi): Make sure we need parameters or not. -grpc::string GetMockPrologue(grpc_generator::File *file, - const Parameters & /*params*/) { +grpc::string GetMockPrologue(grpc_generator::File* file, + const Parameters& /*params*/) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. @@ -1556,17 +1556,18 @@ grpc::string GetMockPrologue(grpc_generator::File *file, } // TODO(mmukhi): Add client-stream and completion-queue headers. -grpc::string GetMockIncludes(grpc_generator::File *file, - const Parameters ¶ms) { +grpc::string GetMockIncludes(grpc_generator::File* file, + const Parameters& params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. auto printer = file->CreatePrinter(&output); std::map vars; - static const char *headers_strs[] = { + static const char* headers_strs[] = { "grpc++/impl/codegen/async_stream.h", - "grpc++/impl/codegen/sync_stream.h", "gmock/gmock.h", + "grpc++/impl/codegen/sync_stream.h", + "gmock/gmock.h", }; std::vector headers(headers_strs, array_end(headers_strs)); PrintIncludes(printer.get(), headers, params); @@ -1585,9 +1586,9 @@ grpc::string GetMockIncludes(grpc_generator::File *file, return output; } -void PrintMockClientMethods(grpc_generator::Printer *printer, - const grpc_generator::Method *method, - std::map *vars) { +void PrintMockClientMethods(grpc_generator::Printer* printer, + const grpc_generator::Method* method, + std::map* vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = method->input_type_name(); (*vars)["Response"] = method->output_type_name(); @@ -1668,9 +1669,9 @@ void PrintMockClientMethods(grpc_generator::Printer *printer, } } -void PrintMockService(grpc_generator::Printer *printer, - const grpc_generator::Service *service, - std::map *vars) { +void PrintMockService(grpc_generator::Printer* printer, + const grpc_generator::Service* service, + std::map* vars) { (*vars)["Service"] = service->name(); printer->Print(*vars, @@ -1684,8 +1685,8 @@ void PrintMockService(grpc_generator::Printer *printer, printer->Print("};\n"); } -grpc::string GetMockServices(grpc_generator::File *file, - const Parameters ¶ms) { +grpc::string GetMockServices(grpc_generator::File* file, + const Parameters& params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. @@ -1715,8 +1716,8 @@ grpc::string GetMockServices(grpc_generator::File *file, return output; } -grpc::string GetMockEpilogue(grpc_generator::File *file, - const Parameters & /*params*/) { +grpc::string GetMockEpilogue(grpc_generator::File* file, + const Parameters& /*params*/) { grpc::string temp; if (!file->package().empty()) { diff --git a/src/compiler/cpp_generator.h b/src/compiler/cpp_generator.h index 73f9fc662c1..a93376acef3 100644 --- a/src/compiler/cpp_generator.h +++ b/src/compiler/cpp_generator.h @@ -55,68 +55,68 @@ struct Parameters { }; // Return the prologue of the generated header file. -grpc::string GetHeaderPrologue(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetHeaderPrologue(grpc_generator::File* file, + const Parameters& params); // Return the includes needed for generated header file. -grpc::string GetHeaderIncludes(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetHeaderIncludes(grpc_generator::File* file, + const Parameters& params); // Return the includes needed for generated source file. -grpc::string GetSourceIncludes(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetSourceIncludes(grpc_generator::File* file, + const Parameters& params); // Return the epilogue of the generated header file. -grpc::string GetHeaderEpilogue(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetHeaderEpilogue(grpc_generator::File* file, + const Parameters& params); // Return the prologue of the generated source file. -grpc::string GetSourcePrologue(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetSourcePrologue(grpc_generator::File* file, + const Parameters& params); // Return the services for generated header file. -grpc::string GetHeaderServices(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetHeaderServices(grpc_generator::File* file, + const Parameters& params); // Return the services for generated source file. -grpc::string GetSourceServices(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetSourceServices(grpc_generator::File* file, + const Parameters& params); // Return the epilogue of the generated source file. -grpc::string GetSourceEpilogue(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetSourceEpilogue(grpc_generator::File* file, + const Parameters& params); // Return the prologue of the generated mock file. -grpc::string GetMockPrologue(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetMockPrologue(grpc_generator::File* file, + const Parameters& params); // Return the includes needed for generated mock file. -grpc::string GetMockIncludes(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetMockIncludes(grpc_generator::File* file, + const Parameters& params); // Return the services for generated mock file. -grpc::string GetMockServices(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetMockServices(grpc_generator::File* file, + const Parameters& params); // Return the epilogue of generated mock file. -grpc::string GetMockEpilogue(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetMockEpilogue(grpc_generator::File* file, + const Parameters& params); // Return the prologue of the generated mock file. -grpc::string GetMockPrologue(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetMockPrologue(grpc_generator::File* file, + const Parameters& params); // Return the includes needed for generated mock file. -grpc::string GetMockIncludes(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetMockIncludes(grpc_generator::File* file, + const Parameters& params); // Return the services for generated mock file. -grpc::string GetMockServices(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetMockServices(grpc_generator::File* file, + const Parameters& params); // Return the epilogue of generated mock file. -grpc::string GetMockEpilogue(grpc_generator::File *file, - const Parameters ¶ms); +grpc::string GetMockEpilogue(grpc_generator::File* file, + const Parameters& params); } // namespace grpc_cpp_generator diff --git a/src/compiler/cpp_generator_helpers.h b/src/compiler/cpp_generator_helpers.h index 28606d46b8e..b8efcbdb843 100644 --- a/src/compiler/cpp_generator_helpers.h +++ b/src/compiler/cpp_generator_helpers.h @@ -26,22 +26,22 @@ namespace grpc_cpp_generator { -inline grpc::string DotsToColons(const grpc::string &name) { +inline grpc::string DotsToColons(const grpc::string& name) { return grpc_generator::StringReplace(name, ".", "::"); } -inline grpc::string DotsToUnderscores(const grpc::string &name) { +inline grpc::string DotsToUnderscores(const grpc::string& name) { return grpc_generator::StringReplace(name, ".", "_"); } -inline grpc::string ClassName(const grpc::protobuf::Descriptor *descriptor, +inline grpc::string ClassName(const grpc::protobuf::Descriptor* descriptor, bool qualified) { // Find "outer", the descriptor of the top-level message in which // "descriptor" is embedded. - const grpc::protobuf::Descriptor *outer = descriptor; + const grpc::protobuf::Descriptor* outer = descriptor; while (outer->containing_type() != NULL) outer = outer->containing_type(); - const grpc::string &outer_name = outer->full_name(); + const grpc::string& outer_name = outer->full_name(); grpc::string inner_name = descriptor->full_name().substr(outer_name.size()); if (qualified) { @@ -54,7 +54,7 @@ inline grpc::string ClassName(const grpc::protobuf::Descriptor *descriptor, // Get leading or trailing comments in a string. Comment lines start with "// ". // Leading detached comments are put in in front of leading comments. template -inline grpc::string GetCppComments(const DescriptorType *desc, bool leading) { +inline grpc::string GetCppComments(const DescriptorType* desc, bool leading) { return grpc_generator::GetPrefixedComments(desc, leading, "//"); } diff --git a/src/compiler/cpp_plugin.cc b/src/compiler/cpp_plugin.cc index ebe3aa3860a..adac0e23d3d 100644 --- a/src/compiler/cpp_plugin.cc +++ b/src/compiler/cpp_plugin.cc @@ -33,10 +33,10 @@ class CppGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { CppGrpcGenerator() {} virtual ~CppGrpcGenerator() {} - virtual bool Generate(const grpc::protobuf::FileDescriptor *file, - const grpc::string ¶meter, - grpc::protobuf::compiler::GeneratorContext *context, - grpc::string *error) const { + virtual bool Generate(const grpc::protobuf::FileDescriptor* file, + const grpc::string& parameter, + grpc::protobuf::compiler::GeneratorContext* context, + grpc::string* error) const { if (file->options().cc_generic_services()) { *error = "cpp grpc proto compiler plugin does not work with generic " @@ -125,9 +125,9 @@ class CppGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { private: // Insert the given code into the given file at the given insertion point. - void Insert(grpc::protobuf::compiler::GeneratorContext *context, - const grpc::string &filename, const grpc::string &insertion_point, - const grpc::string &code) const { + void Insert(grpc::protobuf::compiler::GeneratorContext* context, + const grpc::string& filename, const grpc::string& insertion_point, + const grpc::string& code) const { std::unique_ptr output( context->OpenForInsert(filename, insertion_point)); grpc::protobuf::io::CodedOutputStream coded_out(output.get()); @@ -135,7 +135,7 @@ class CppGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { } }; -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { CppGrpcGenerator generator; return grpc::protobuf::compiler::PluginMain(argc, argv, &generator); } diff --git a/src/compiler/csharp_generator.cc b/src/compiler/csharp_generator.cc index bc3b0f24cdd..40fe0b054a5 100644 --- a/src/compiler/csharp_generator.cc +++ b/src/compiler/csharp_generator.cc @@ -23,24 +23,23 @@ #include "src/compiler/config.h" #include "src/compiler/csharp_generator.h" -#include "src/compiler/csharp_generator.h" #include "src/compiler/csharp_generator_helpers.h" -using google::protobuf::compiler::csharp::GetFileNamespace; using google::protobuf::compiler::csharp::GetClassName; +using google::protobuf::compiler::csharp::GetFileNamespace; using google::protobuf::compiler::csharp::GetReflectionClassName; -using grpc::protobuf::FileDescriptor; using grpc::protobuf::Descriptor; -using grpc::protobuf::ServiceDescriptor; +using grpc::protobuf::FileDescriptor; using grpc::protobuf::MethodDescriptor; +using grpc::protobuf::ServiceDescriptor; using grpc::protobuf::io::Printer; using grpc::protobuf::io::StringOutputStream; -using grpc_generator::MethodType; using grpc_generator::GetMethodType; -using grpc_generator::METHODTYPE_NO_STREAMING; +using grpc_generator::METHODTYPE_BIDI_STREAMING; using grpc_generator::METHODTYPE_CLIENT_STREAMING; +using grpc_generator::METHODTYPE_NO_STREAMING; using grpc_generator::METHODTYPE_SERVER_STREAMING; -using grpc_generator::METHODTYPE_BIDI_STREAMING; +using grpc_generator::MethodType; using grpc_generator::StringReplace; using std::map; using std::vector; @@ -53,7 +52,7 @@ namespace { // Currently, we cannot easily reuse the functionality as // google/protobuf/compiler/csharp/csharp_doc_comment.h is not a public header. // TODO(jtattermusch): reuse the functionality from google/protobuf. -bool GenerateDocCommentBodyImpl(grpc::protobuf::io::Printer *printer, +bool GenerateDocCommentBodyImpl(grpc::protobuf::io::Printer* printer, grpc::protobuf::SourceLocation location) { grpc::string comments = location.leading_comments.empty() ? location.trailing_comments @@ -100,8 +99,8 @@ bool GenerateDocCommentBodyImpl(grpc::protobuf::io::Printer *printer, } template -bool GenerateDocCommentBody(grpc::protobuf::io::Printer *printer, - const DescriptorType *descriptor) { +bool GenerateDocCommentBody(grpc::protobuf::io::Printer* printer, + const DescriptorType* descriptor) { grpc::protobuf::SourceLocation location; if (!descriptor->GetSourceLocation(&location)) { return false; @@ -109,8 +108,8 @@ bool GenerateDocCommentBody(grpc::protobuf::io::Printer *printer, return GenerateDocCommentBodyImpl(printer, location); } -void GenerateDocCommentServerMethod(grpc::protobuf::io::Printer *printer, - const MethodDescriptor *method) { +void GenerateDocCommentServerMethod(grpc::protobuf::io::Printer* printer, + const MethodDescriptor* method) { if (GenerateDocCommentBody(printer, method)) { if (method->client_streaming()) { printer->Print( @@ -141,8 +140,8 @@ void GenerateDocCommentServerMethod(grpc::protobuf::io::Printer *printer, } } -void GenerateDocCommentClientMethod(grpc::protobuf::io::Printer *printer, - const MethodDescriptor *method, +void GenerateDocCommentClientMethod(grpc::protobuf::io::Printer* printer, + const MethodDescriptor* method, bool is_sync, bool use_call_options) { if (GenerateDocCommentBody(printer, method)) { if (!method->client_streaming()) { @@ -173,15 +172,15 @@ void GenerateDocCommentClientMethod(grpc::protobuf::io::Printer *printer, } } -std::string GetServiceClassName(const ServiceDescriptor *service) { +std::string GetServiceClassName(const ServiceDescriptor* service) { return service->name(); } -std::string GetClientClassName(const ServiceDescriptor *service) { +std::string GetClientClassName(const ServiceDescriptor* service) { return service->name() + "Client"; } -std::string GetServerClassName(const ServiceDescriptor *service) { +std::string GetServerClassName(const ServiceDescriptor* service) { return service->name() + "Base"; } @@ -202,15 +201,15 @@ std::string GetCSharpMethodType(MethodType method_type) { std::string GetServiceNameFieldName() { return "__ServiceName"; } -std::string GetMarshallerFieldName(const Descriptor *message) { +std::string GetMarshallerFieldName(const Descriptor* message) { return "__Marshaller_" + message->name(); } -std::string GetMethodFieldName(const MethodDescriptor *method) { +std::string GetMethodFieldName(const MethodDescriptor* method) { return "__Method_" + method->name(); } -std::string GetMethodRequestParamMaybe(const MethodDescriptor *method, +std::string GetMethodRequestParamMaybe(const MethodDescriptor* method, bool invocation_param = false) { if (method->client_streaming()) { return ""; @@ -225,7 +224,7 @@ std::string GetAccessLevel(bool internal_access) { return internal_access ? "internal" : "public"; } -std::string GetMethodReturnTypeClient(const MethodDescriptor *method) { +std::string GetMethodReturnTypeClient(const MethodDescriptor* method) { switch (GetMethodType(method)) { case METHODTYPE_NO_STREAMING: return "grpc::AsyncUnaryCall<" + GetClassName(method->output_type()) + @@ -246,7 +245,7 @@ std::string GetMethodReturnTypeClient(const MethodDescriptor *method) { return ""; } -std::string GetMethodRequestParamServer(const MethodDescriptor *method) { +std::string GetMethodRequestParamServer(const MethodDescriptor* method) { switch (GetMethodType(method)) { case METHODTYPE_NO_STREAMING: case METHODTYPE_SERVER_STREAMING: @@ -260,7 +259,7 @@ std::string GetMethodRequestParamServer(const MethodDescriptor *method) { return ""; } -std::string GetMethodReturnTypeServer(const MethodDescriptor *method) { +std::string GetMethodReturnTypeServer(const MethodDescriptor* method) { switch (GetMethodType(method)) { case METHODTYPE_NO_STREAMING: case METHODTYPE_CLIENT_STREAMING: @@ -274,7 +273,7 @@ std::string GetMethodReturnTypeServer(const MethodDescriptor *method) { return ""; } -std::string GetMethodResponseStreamMaybe(const MethodDescriptor *method) { +std::string GetMethodResponseStreamMaybe(const MethodDescriptor* method) { switch (GetMethodType(method)) { case METHODTYPE_NO_STREAMING: case METHODTYPE_CLIENT_STREAMING: @@ -289,13 +288,13 @@ std::string GetMethodResponseStreamMaybe(const MethodDescriptor *method) { } // Gets vector of all messages used as input or output types. -std::vector GetUsedMessages( - const ServiceDescriptor *service) { - std::set descriptor_set; - std::vector +std::vector GetUsedMessages( + const ServiceDescriptor* service) { + std::set descriptor_set; + std::vector result; // vector is to maintain stable ordering for (int i = 0; i < service->method_count(); i++) { - const MethodDescriptor *method = service->method(i); + const MethodDescriptor* method = service->method(i); if (descriptor_set.find(method->input_type()) == descriptor_set.end()) { descriptor_set.insert(method->input_type()); result.push_back(method->input_type()); @@ -308,10 +307,10 @@ std::vector GetUsedMessages( return result; } -void GenerateMarshallerFields(Printer *out, const ServiceDescriptor *service) { - std::vector used_messages = GetUsedMessages(service); +void GenerateMarshallerFields(Printer* out, const ServiceDescriptor* service) { + std::vector used_messages = GetUsedMessages(service); for (size_t i = 0; i < used_messages.size(); i++) { - const Descriptor *message = used_messages[i]; + const Descriptor* message = used_messages[i]; out->Print( "static readonly grpc::Marshaller<$type$> $fieldname$ = " "grpc::Marshallers.Create((arg) => " @@ -323,7 +322,7 @@ void GenerateMarshallerFields(Printer *out, const ServiceDescriptor *service) { out->Print("\n"); } -void GenerateStaticMethodField(Printer *out, const MethodDescriptor *method) { +void GenerateStaticMethodField(Printer* out, const MethodDescriptor* method) { out->Print( "static readonly grpc::Method<$request$, $response$> $fieldname$ = new " "grpc::Method<$request$, $response$>(\n", @@ -346,8 +345,8 @@ void GenerateStaticMethodField(Printer *out, const MethodDescriptor *method) { out->Outdent(); } -void GenerateServiceDescriptorProperty(Printer *out, - const ServiceDescriptor *service) { +void GenerateServiceDescriptorProperty(Printer* out, + const ServiceDescriptor* service) { std::ostringstream index; index << service->index(); out->Print("/// Service descriptor\n"); @@ -362,7 +361,7 @@ void GenerateServiceDescriptorProperty(Printer *out, out->Print("\n"); } -void GenerateServerClass(Printer *out, const ServiceDescriptor *service) { +void GenerateServerClass(Printer* out, const ServiceDescriptor* service) { out->Print( "/// Base class for server-side implementations of " "$servicename$\n", @@ -372,7 +371,7 @@ void GenerateServerClass(Printer *out, const ServiceDescriptor *service) { out->Print("{\n"); out->Indent(); for (int i = 0; i < service->method_count(); i++) { - const MethodDescriptor *method = service->method(i); + const MethodDescriptor* method = service->method(i); GenerateDocCommentServerMethod(out, method); out->Print( "public virtual $returntype$ " @@ -395,7 +394,7 @@ void GenerateServerClass(Printer *out, const ServiceDescriptor *service) { out->Print("\n"); } -void GenerateClientStub(Printer *out, const ServiceDescriptor *service) { +void GenerateClientStub(Printer* out, const ServiceDescriptor* service) { out->Print("/// Client for $servicename$\n", "servicename", GetServiceClassName(service)); out->Print("public partial class $name$ : grpc::ClientBase<$name$>\n", "name", @@ -443,7 +442,7 @@ void GenerateClientStub(Printer *out, const ServiceDescriptor *service) { out->Print("}\n\n"); for (int i = 0; i < service->method_count(); i++) { - const MethodDescriptor *method = service->method(i); + const MethodDescriptor* method = service->method(i); MethodType method_type = GetMethodType(method); if (method_type == METHODTYPE_NO_STREAMING) { @@ -573,7 +572,7 @@ void GenerateClientStub(Printer *out, const ServiceDescriptor *service) { out->Print("\n"); } -void GenerateBindServiceMethod(Printer *out, const ServiceDescriptor *service) { +void GenerateBindServiceMethod(Printer* out, const ServiceDescriptor* service) { out->Print( "/// Creates service definition that can be registered with a " "server\n"); @@ -591,7 +590,7 @@ void GenerateBindServiceMethod(Printer *out, const ServiceDescriptor *service) { out->Indent(); out->Indent(); for (int i = 0; i < service->method_count(); i++) { - const MethodDescriptor *method = service->method(i); + const MethodDescriptor* method = service->method(i); out->Print(".AddMethod($methodfield$, serviceImpl.$methodname$)", "methodfield", GetMethodFieldName(method), "methodname", method->name()); @@ -608,7 +607,7 @@ void GenerateBindServiceMethod(Printer *out, const ServiceDescriptor *service) { out->Print("\n"); } -void GenerateService(Printer *out, const ServiceDescriptor *service, +void GenerateService(Printer* out, const ServiceDescriptor* service, bool generate_client, bool generate_server, bool internal_access) { GenerateDocCommentBody(out, service); @@ -644,7 +643,7 @@ void GenerateService(Printer *out, const ServiceDescriptor *service, } // anonymous namespace -grpc::string GetServices(const FileDescriptor *file, bool generate_client, +grpc::string GetServices(const FileDescriptor* file, bool generate_client, bool generate_server, bool internal_access) { grpc::string output; { @@ -667,7 +666,7 @@ grpc::string GetServices(const FileDescriptor *file, bool generate_client, grpc::string leading_comments = GetCsharpComments(file, true); if (!leading_comments.empty()) { out.Print("// Original file comments:\n"); - out.Print(leading_comments.c_str()); + out.PrintRaw(leading_comments.c_str()); } out.Print("#pragma warning disable 1591\n"); diff --git a/src/compiler/csharp_generator.h b/src/compiler/csharp_generator.h index 0eca2928703..fd36e11851b 100644 --- a/src/compiler/csharp_generator.h +++ b/src/compiler/csharp_generator.h @@ -25,7 +25,7 @@ namespace grpc_csharp_generator { -grpc::string GetServices(const grpc::protobuf::FileDescriptor *file, +grpc::string GetServices(const grpc::protobuf::FileDescriptor* file, bool generate_client, bool generate_server, bool internal_access); diff --git a/src/compiler/csharp_generator_helpers.h b/src/compiler/csharp_generator_helpers.h index bdf10dfc74c..8c89925551c 100644 --- a/src/compiler/csharp_generator_helpers.h +++ b/src/compiler/csharp_generator_helpers.h @@ -24,8 +24,8 @@ namespace grpc_csharp_generator { -inline bool ServicesFilename(const grpc::protobuf::FileDescriptor *file, - grpc::string *file_name_or_error) { +inline bool ServicesFilename(const grpc::protobuf::FileDescriptor* file, + grpc::string* file_name_or_error) { *file_name_or_error = grpc_generator::FileNameInUpperCamel(file, false) + "Grpc.cs"; return true; @@ -34,7 +34,7 @@ inline bool ServicesFilename(const grpc::protobuf::FileDescriptor *file, // Get leading or trailing comments in a string. Comment lines start with "// ". // Leading detached comments are put in in front of leading comments. template -inline grpc::string GetCsharpComments(const DescriptorType *desc, +inline grpc::string GetCsharpComments(const DescriptorType* desc, bool leading) { return grpc_generator::GetPrefixedComments(desc, leading, "//"); } diff --git a/src/compiler/csharp_plugin.cc b/src/compiler/csharp_plugin.cc index 224a89c0d9b..5f13aa6749e 100644 --- a/src/compiler/csharp_plugin.cc +++ b/src/compiler/csharp_plugin.cc @@ -29,10 +29,10 @@ class CSharpGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { CSharpGrpcGenerator() {} ~CSharpGrpcGenerator() {} - bool Generate(const grpc::protobuf::FileDescriptor *file, - const grpc::string ¶meter, - grpc::protobuf::compiler::GeneratorContext *context, - grpc::string *error) const { + bool Generate(const grpc::protobuf::FileDescriptor* file, + const grpc::string& parameter, + grpc::protobuf::compiler::GeneratorContext* context, + grpc::string* error) const { std::vector > options; grpc::protobuf::compiler::ParseGeneratorParameter(parameter, &options); @@ -71,7 +71,7 @@ class CSharpGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { } }; -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { CSharpGrpcGenerator generator; return grpc::protobuf::compiler::PluginMain(argc, argv, &generator); } diff --git a/src/compiler/generator_helpers.h b/src/compiler/generator_helpers.h index e7005d84b03..747096f0657 100644 --- a/src/compiler/generator_helpers.h +++ b/src/compiler/generator_helpers.h @@ -29,7 +29,7 @@ namespace grpc_generator { -inline bool StripSuffix(grpc::string *filename, const grpc::string &suffix) { +inline bool StripSuffix(grpc::string* filename, const grpc::string& suffix) { if (filename->length() >= suffix.length()) { size_t suffix_pos = filename->length() - suffix.length(); if (filename->compare(suffix_pos, grpc::string::npos, suffix) == 0) { @@ -41,7 +41,7 @@ inline bool StripSuffix(grpc::string *filename, const grpc::string &suffix) { return false; } -inline bool StripPrefix(grpc::string *name, const grpc::string &prefix) { +inline bool StripPrefix(grpc::string* name, const grpc::string& prefix) { if (name->length() >= prefix.length()) { if (name->substr(0, prefix.size()) == prefix) { *name = name->substr(prefix.size()); @@ -58,8 +58,8 @@ inline grpc::string StripProto(grpc::string filename) { return filename; } -inline grpc::string StringReplace(grpc::string str, const grpc::string &from, - const grpc::string &to, bool replace_all) { +inline grpc::string StringReplace(grpc::string str, const grpc::string& from, + const grpc::string& to, bool replace_all) { size_t pos = 0; do { @@ -74,13 +74,13 @@ inline grpc::string StringReplace(grpc::string str, const grpc::string &from, return str; } -inline grpc::string StringReplace(grpc::string str, const grpc::string &from, - const grpc::string &to) { +inline grpc::string StringReplace(grpc::string str, const grpc::string& from, + const grpc::string& to) { return StringReplace(str, from, to, true); } -inline std::vector tokenize(const grpc::string &input, - const grpc::string &delimiters) { +inline std::vector tokenize(const grpc::string& input, + const grpc::string& delimiters) { std::vector tokens; size_t pos, last_pos = 0; @@ -125,7 +125,7 @@ inline grpc::string LowerUnderscoreToUpperCamel(grpc::string str) { } inline grpc::string FileNameInUpperCamel( - const grpc::protobuf::FileDescriptor *file, bool include_package_path) { + const grpc::protobuf::FileDescriptor* file, bool include_package_path) { std::vector tokens = tokenize(StripProto(file->name()), "/"); grpc::string result = ""; if (include_package_path) { @@ -138,7 +138,7 @@ inline grpc::string FileNameInUpperCamel( } inline grpc::string FileNameInUpperCamel( - const grpc::protobuf::FileDescriptor *file) { + const grpc::protobuf::FileDescriptor* file) { return FileNameInUpperCamel(file, true); } @@ -150,7 +150,7 @@ enum MethodType { }; inline MethodType GetMethodType( - const grpc::protobuf::MethodDescriptor *method) { + const grpc::protobuf::MethodDescriptor* method) { if (method->client_streaming()) { if (method->server_streaming()) { return METHODTYPE_BIDI_STREAMING; @@ -166,8 +166,8 @@ inline MethodType GetMethodType( } } -inline void Split(const grpc::string &s, char delim, - std::vector *append_to) { +inline void Split(const grpc::string& s, char delim, + std::vector* append_to) { std::istringstream iss(s); grpc::string piece; while (std::getline(iss, piece)) { @@ -183,14 +183,14 @@ enum CommentType { // Get all the raw comments and append each line without newline to out. template -inline void GetComment(const DescriptorType *desc, CommentType type, - std::vector *out) { +inline void GetComment(const DescriptorType* desc, CommentType type, + std::vector* out) { grpc::protobuf::SourceLocation location; if (!desc->GetSourceLocation(&location)) { return; } if (type == COMMENTTYPE_LEADING || type == COMMENTTYPE_TRAILING) { - const grpc::string &comments = type == COMMENTTYPE_LEADING + const grpc::string& comments = type == COMMENTTYPE_LEADING ? location.leading_comments : location.trailing_comments; Split(comments, '\n', out); @@ -210,8 +210,8 @@ inline void GetComment(const DescriptorType *desc, CommentType type, // For file level leading and detached leading comments, we return comments // above syntax line. Return nothing for trailing comments. template <> -inline void GetComment(const grpc::protobuf::FileDescriptor *desc, - CommentType type, std::vector *out) { +inline void GetComment(const grpc::protobuf::FileDescriptor* desc, + CommentType type, std::vector* out) { if (type == COMMENTTYPE_TRAILING) { return; } @@ -238,10 +238,10 @@ inline void GetComment(const grpc::protobuf::FileDescriptor *desc, // Add prefix and newline to each comment line and concatenate them together. // Make sure there is a space after the prefix unless the line is empty. inline grpc::string GenerateCommentsWithPrefix( - const std::vector &in, const grpc::string &prefix) { + const std::vector& in, const grpc::string& prefix) { std::ostringstream oss; for (auto it = in.begin(); it != in.end(); it++) { - const grpc::string &elem = *it; + const grpc::string& elem = *it; if (elem.empty()) { oss << prefix << "\n"; } else if (elem[0] == ' ') { @@ -254,9 +254,9 @@ inline grpc::string GenerateCommentsWithPrefix( } template -inline grpc::string GetPrefixedComments(const DescriptorType *desc, +inline grpc::string GetPrefixedComments(const DescriptorType* desc, bool leading, - const grpc::string &prefix) { + const grpc::string& prefix) { std::vector out; if (leading) { grpc_generator::GetComment( diff --git a/src/compiler/node_generator.cc b/src/compiler/node_generator.cc index c0fef9128f1..661587cbd63 100644 --- a/src/compiler/node_generator.cc +++ b/src/compiler/node_generator.cc @@ -22,10 +22,10 @@ #include "src/compiler/generator_helpers.h" #include "src/compiler/node_generator_helpers.h" +using grpc::protobuf::Descriptor; using grpc::protobuf::FileDescriptor; -using grpc::protobuf::ServiceDescriptor; using grpc::protobuf::MethodDescriptor; -using grpc::protobuf::Descriptor; +using grpc::protobuf::ServiceDescriptor; using grpc::protobuf::io::Printer; using grpc::protobuf::io::StringOutputStream; using std::map; @@ -53,15 +53,15 @@ grpc::string ModuleAlias(const grpc::string filename) { // Given a filename like foo/bar/baz.proto, returns the corresponding JavaScript // message file foo/bar/baz.js -grpc::string GetJSMessageFilename(const grpc::string &filename) { +grpc::string GetJSMessageFilename(const grpc::string& filename) { grpc::string name = filename; return grpc_generator::StripProto(name) + "_pb.js"; } // Given a filename like foo/bar/baz.proto, returns the root directory // path ../../ -grpc::string GetRootPath(const grpc::string &from_filename, - const grpc::string &to_filename) { +grpc::string GetRootPath(const grpc::string& from_filename, + const grpc::string& to_filename) { if (to_filename.find("google/protobuf") == 0) { // Well-known types (.proto files in the google/protobuf directory) are // assumed to come from the 'google-protobuf' npm package. We may want to @@ -82,24 +82,24 @@ grpc::string GetRootPath(const grpc::string &from_filename, // Return the relative path to load to_file from the directory containing // from_file, assuming that both paths are relative to the same directory -grpc::string GetRelativePath(const grpc::string &from_file, - const grpc::string &to_file) { +grpc::string GetRelativePath(const grpc::string& from_file, + const grpc::string& to_file) { return GetRootPath(from_file, to_file) + to_file; } /* Finds all message types used in all services in the file, and returns them * as a map of fully qualified message type name to message descriptor */ -map GetAllMessages( - const FileDescriptor *file) { - map message_types; +map GetAllMessages( + const FileDescriptor* file) { + map message_types; for (int service_num = 0; service_num < file->service_count(); service_num++) { - const ServiceDescriptor *service = file->service(service_num); + const ServiceDescriptor* service = file->service(service_num); for (int method_num = 0; method_num < service->method_count(); method_num++) { - const MethodDescriptor *method = service->method(method_num); - const Descriptor *input_type = method->input_type(); - const Descriptor *output_type = method->output_type(); + const MethodDescriptor* method = service->method(method_num); + const Descriptor* input_type = method->input_type(); + const Descriptor* output_type = method->output_type(); message_types[input_type->full_name()] = input_type; message_types[output_type->full_name()] = output_type; } @@ -107,11 +107,11 @@ map GetAllMessages( return message_types; } -grpc::string MessageIdentifierName(const grpc::string &name) { +grpc::string MessageIdentifierName(const grpc::string& name) { return grpc_generator::StringReplace(name, ".", "_"); } -grpc::string NodeObjectPath(const Descriptor *descriptor) { +grpc::string NodeObjectPath(const Descriptor* descriptor) { grpc::string module_alias = ModuleAlias(descriptor->file()->name()); grpc::string name = descriptor->full_name(); grpc_generator::StripPrefix(&name, descriptor->file()->package() + "."); @@ -119,7 +119,7 @@ grpc::string NodeObjectPath(const Descriptor *descriptor) { } // Prints out the message serializer and deserializer functions -void PrintMessageTransformer(const Descriptor *descriptor, Printer *out) { +void PrintMessageTransformer(const Descriptor* descriptor, Printer* out) { map template_vars; grpc::string full_name = descriptor->full_name(); template_vars["identifier_name"] = MessageIdentifierName(full_name); @@ -149,9 +149,9 @@ void PrintMessageTransformer(const Descriptor *descriptor, Printer *out) { out->Print("}\n\n"); } -void PrintMethod(const MethodDescriptor *method, Printer *out) { - const Descriptor *input_type = method->input_type(); - const Descriptor *output_type = method->output_type(); +void PrintMethod(const MethodDescriptor* method, Printer* out) { + const Descriptor* input_type = method->input_type(); + const Descriptor* output_type = method->output_type(); map vars; vars["service_name"] = method->service()->full_name(); vars["name"] = method->name(); @@ -177,7 +177,7 @@ void PrintMethod(const MethodDescriptor *method, Printer *out) { } // Prints out the service descriptor object -void PrintService(const ServiceDescriptor *service, Printer *out) { +void PrintService(const ServiceDescriptor* service, Printer* out) { map template_vars; out->Print(GetNodeComments(service, true).c_str()); template_vars["name"] = service->name(); @@ -200,7 +200,7 @@ void PrintService(const ServiceDescriptor *service, Printer *out) { out->Print(GetNodeComments(service, false).c_str()); } -void PrintImports(const FileDescriptor *file, Printer *out) { +void PrintImports(const FileDescriptor* file, Printer* out) { out->Print("var grpc = require('grpc');\n"); if (file->message_type_count() > 0) { grpc::string file_path = @@ -219,9 +219,9 @@ void PrintImports(const FileDescriptor *file, Printer *out) { out->Print("\n"); } -void PrintTransformers(const FileDescriptor *file, Printer *out) { - map messages = GetAllMessages(file); - for (std::map::iterator it = +void PrintTransformers(const FileDescriptor* file, Printer* out) { + map messages = GetAllMessages(file); + for (std::map::iterator it = messages.begin(); it != messages.end(); it++) { PrintMessageTransformer(it->second, out); @@ -229,14 +229,14 @@ void PrintTransformers(const FileDescriptor *file, Printer *out) { out->Print("\n"); } -void PrintServices(const FileDescriptor *file, Printer *out) { +void PrintServices(const FileDescriptor* file, Printer* out) { for (int i = 0; i < file->service_count(); i++) { PrintService(file->service(i), out); } } -} +} // namespace -grpc::string GenerateFile(const FileDescriptor *file) { +grpc::string GenerateFile(const FileDescriptor* file) { grpc::string output; { StringOutputStream output_stream(&output); @@ -250,7 +250,7 @@ grpc::string GenerateFile(const FileDescriptor *file) { grpc::string leading_comments = GetNodeComments(file, true); if (!leading_comments.empty()) { out.Print("// Original file comments:\n"); - out.Print(leading_comments.c_str()); + out.PrintRaw(leading_comments.c_str()); } out.Print("'use strict';\n"); diff --git a/src/compiler/node_generator.h b/src/compiler/node_generator.h index 7b0335b8d29..a9ffe75fc86 100644 --- a/src/compiler/node_generator.h +++ b/src/compiler/node_generator.h @@ -23,7 +23,7 @@ namespace grpc_node_generator { -grpc::string GenerateFile(const grpc::protobuf::FileDescriptor *file); +grpc::string GenerateFile(const grpc::protobuf::FileDescriptor* file); } // namespace grpc_node_generator diff --git a/src/compiler/node_plugin.cc b/src/compiler/node_plugin.cc index f4334c96ab1..bc38e9018a2 100644 --- a/src/compiler/node_plugin.cc +++ b/src/compiler/node_plugin.cc @@ -32,10 +32,10 @@ class NodeGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { NodeGrpcGenerator() {} ~NodeGrpcGenerator() {} - bool Generate(const grpc::protobuf::FileDescriptor *file, - const grpc::string ¶meter, - grpc::protobuf::compiler::GeneratorContext *context, - grpc::string *error) const { + bool Generate(const grpc::protobuf::FileDescriptor* file, + const grpc::string& parameter, + grpc::protobuf::compiler::GeneratorContext* context, + grpc::string* error) const { grpc::string code = GenerateFile(file); if (code.size() == 0) { return true; @@ -52,7 +52,7 @@ class NodeGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { } }; -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { NodeGrpcGenerator generator; return grpc::protobuf::compiler::PluginMain(argc, argv, &generator); } diff --git a/src/compiler/objective_c_generator.cc b/src/compiler/objective_c_generator.cc index 33b5fedd5c8..ab7d8697589 100644 --- a/src/compiler/objective_c_generator.cc +++ b/src/compiler/objective_c_generator.cc @@ -27,10 +27,11 @@ #include using ::google::protobuf::compiler::objectivec::ClassName; -using ::grpc::protobuf::io::Printer; +using ::grpc::protobuf::FileDescriptor; +using ::grpc::protobuf::FileDescriptor; using ::grpc::protobuf::MethodDescriptor; using ::grpc::protobuf::ServiceDescriptor; -using ::grpc::protobuf::FileDescriptor; +using ::grpc::protobuf::io::Printer; using ::std::map; using ::std::set; @@ -38,7 +39,7 @@ namespace grpc_objective_c_generator { namespace { void PrintProtoRpcDeclarationAsPragma( - Printer *printer, const MethodDescriptor *method, + Printer* printer, const MethodDescriptor* method, map< ::grpc::string, ::grpc::string> vars) { vars["client_stream"] = method->client_streaming() ? "stream " : ""; vars["server_stream"] = method->server_streaming() ? "stream " : ""; @@ -49,7 +50,7 @@ void PrintProtoRpcDeclarationAsPragma( } template -static void PrintAllComments(const DescriptorType *desc, Printer *printer) { +static void PrintAllComments(const DescriptorType* desc, Printer* printer) { std::vector comments; grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_LEADING_DETACHED, &comments); @@ -65,15 +66,15 @@ static void PrintAllComments(const DescriptorType *desc, Printer *printer) { printer->Print(" * "); size_t start_pos = it->find_first_not_of(' '); if (start_pos != grpc::string::npos) { - printer->Print(it->c_str() + start_pos); + printer->PrintRaw(it->c_str() + start_pos); } printer->Print("\n"); } printer->Print(" */\n"); } -void PrintMethodSignature(Printer *printer, const MethodDescriptor *method, - const map< ::grpc::string, ::grpc::string> &vars) { +void PrintMethodSignature(Printer* printer, const MethodDescriptor* method, + const map< ::grpc::string, ::grpc::string>& vars) { // Print comment PrintAllComments(method, printer); @@ -97,7 +98,7 @@ void PrintMethodSignature(Printer *printer, const MethodDescriptor *method, } } -void PrintSimpleSignature(Printer *printer, const MethodDescriptor *method, +void PrintSimpleSignature(Printer* printer, const MethodDescriptor* method, map< ::grpc::string, ::grpc::string> vars) { vars["method_name"] = grpc_generator::LowercaseFirstLetter(vars["method_name"]); @@ -105,7 +106,7 @@ void PrintSimpleSignature(Printer *printer, const MethodDescriptor *method, PrintMethodSignature(printer, method, vars); } -void PrintAdvancedSignature(Printer *printer, const MethodDescriptor *method, +void PrintAdvancedSignature(Printer* printer, const MethodDescriptor* method, map< ::grpc::string, ::grpc::string> vars) { vars["method_name"] = "RPCTo" + vars["method_name"]; vars["return_type"] = "GRPCProtoCall *"; @@ -113,7 +114,7 @@ void PrintAdvancedSignature(Printer *printer, const MethodDescriptor *method, } inline map< ::grpc::string, ::grpc::string> GetMethodVars( - const MethodDescriptor *method) { + const MethodDescriptor* method) { map< ::grpc::string, ::grpc::string> res; res["method_name"] = method->name(); res["request_type"] = method->input_type()->name(); @@ -123,7 +124,7 @@ inline map< ::grpc::string, ::grpc::string> GetMethodVars( return res; } -void PrintMethodDeclarations(Printer *printer, const MethodDescriptor *method) { +void PrintMethodDeclarations(Printer* printer, const MethodDescriptor* method) { map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method); PrintProtoRpcDeclarationAsPragma(printer, method, vars); @@ -134,7 +135,7 @@ void PrintMethodDeclarations(Printer *printer, const MethodDescriptor *method) { printer->Print(";\n\n\n"); } -void PrintSimpleImplementation(Printer *printer, const MethodDescriptor *method, +void PrintSimpleImplementation(Printer* printer, const MethodDescriptor* method, map< ::grpc::string, ::grpc::string> vars) { printer->Print("{\n"); printer->Print(vars, " [[self RPCTo$method_name$With"); @@ -151,8 +152,8 @@ void PrintSimpleImplementation(Printer *printer, const MethodDescriptor *method, printer->Print("}\n"); } -void PrintAdvancedImplementation(Printer *printer, - const MethodDescriptor *method, +void PrintAdvancedImplementation(Printer* printer, + const MethodDescriptor* method, map< ::grpc::string, ::grpc::string> vars) { printer->Print("{\n"); printer->Print(vars, " return [self RPCToMethod:@\"$method_name$\"\n"); @@ -176,8 +177,8 @@ void PrintAdvancedImplementation(Printer *printer, printer->Print("}\n"); } -void PrintMethodImplementations(Printer *printer, - const MethodDescriptor *method) { +void PrintMethodImplementations(Printer* printer, + const MethodDescriptor* method) { map< ::grpc::string, ::grpc::string> vars = GetMethodVars(method); PrintProtoRpcDeclarationAsPragma(printer, method, vars); @@ -193,7 +194,7 @@ void PrintMethodImplementations(Printer *printer, } // namespace -::grpc::string GetAllMessageClasses(const FileDescriptor *file) { +::grpc::string GetAllMessageClasses(const FileDescriptor* file) { ::grpc::string output; set< ::grpc::string> classes; for (int i = 0; i < file->service_count(); i++) { @@ -211,7 +212,7 @@ void PrintMethodImplementations(Printer *printer, return output; } -::grpc::string GetHeader(const ServiceDescriptor *service) { +::grpc::string GetHeader(const ServiceDescriptor* service) { ::grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. @@ -245,7 +246,7 @@ void PrintMethodImplementations(Printer *printer, return output; } -::grpc::string GetSource(const ServiceDescriptor *service) { +::grpc::string GetSource(const ServiceDescriptor* service) { ::grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. diff --git a/src/compiler/objective_c_generator.h b/src/compiler/objective_c_generator.h index e912a52415f..d3aed76c4f4 100644 --- a/src/compiler/objective_c_generator.h +++ b/src/compiler/objective_c_generator.h @@ -23,20 +23,21 @@ namespace grpc_objective_c_generator { -using ::grpc::protobuf::ServiceDescriptor; using ::grpc::protobuf::FileDescriptor; +using ::grpc::protobuf::FileDescriptor; +using ::grpc::protobuf::ServiceDescriptor; using ::grpc::string; // Returns forward declaration of classes in the generated header file. -string GetAllMessageClasses(const FileDescriptor *file); +string GetAllMessageClasses(const FileDescriptor* file); // Returns the content to be included in the "global_scope" insertion point of // the generated header file. -string GetHeader(const ServiceDescriptor *service); +string GetHeader(const ServiceDescriptor* service); // Returns the content to be included in the "global_scope" insertion point of // the generated implementation file. -string GetSource(const ServiceDescriptor *service); +string GetSource(const ServiceDescriptor* service); } // namespace grpc_objective_c_generator diff --git a/src/compiler/objective_c_generator_helpers.h b/src/compiler/objective_c_generator_helpers.h index 9c9589e1db9..4004e6aef8f 100644 --- a/src/compiler/objective_c_generator_helpers.h +++ b/src/compiler/objective_c_generator_helpers.h @@ -31,14 +31,14 @@ using ::grpc::protobuf::FileDescriptor; using ::grpc::protobuf::ServiceDescriptor; using ::grpc::string; -inline string MessageHeaderName(const FileDescriptor *file) { +inline string MessageHeaderName(const FileDescriptor* file) { return google::protobuf::compiler::objectivec::FilePath(file) + ".pbobjc.h"; } -inline string ServiceClassName(const ServiceDescriptor *service) { - const FileDescriptor *file = service->file(); +inline string ServiceClassName(const ServiceDescriptor* service) { + const FileDescriptor* file = service->file(); string prefix = file->options().objc_class_prefix(); return prefix + service->name(); } -} +} // namespace grpc_objective_c_generator #endif // GRPC_INTERNAL_COMPILER_OBJECTIVE_C_GENERATOR_HELPERS_H diff --git a/src/compiler/objective_c_plugin.cc b/src/compiler/objective_c_plugin.cc index e751d0562e2..d5d488e84d4 100644 --- a/src/compiler/objective_c_plugin.cc +++ b/src/compiler/objective_c_plugin.cc @@ -26,19 +26,19 @@ #include -using ::google::protobuf::compiler::objectivec::ProtobufLibraryFrameworkName; using ::google::protobuf::compiler::objectivec:: IsProtobufLibraryBundledProtoFile; +using ::google::protobuf::compiler::objectivec::ProtobufLibraryFrameworkName; class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { public: ObjectiveCGrpcGenerator() {} virtual ~ObjectiveCGrpcGenerator() {} - virtual bool Generate(const grpc::protobuf::FileDescriptor *file, - const ::grpc::string ¶meter, - grpc::protobuf::compiler::GeneratorContext *context, - ::grpc::string *error) const { + virtual bool Generate(const grpc::protobuf::FileDescriptor* file, + const ::grpc::string& parameter, + grpc::protobuf::compiler::GeneratorContext* context, + ::grpc::string* error) const { if (file->service_count() == 0) { // No services. Do nothing. return true; @@ -51,12 +51,15 @@ class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { { // Generate .pbrpc.h - ::grpc::string imports = ::grpc::string("#import \"") + file_name + - ".pbobjc.h\"\n\n" - "#import \n" - "#import \n" - "#import \n" - "#import \n"; + ::grpc::string imports = + ::grpc::string("#if !GPB_GRPC_FORWARD_DECLARE_MESSAGE_PROTO\n") + + "#import \"" + file_name + + ".pbobjc.h\"\n" + "#endif\n\n" + "#import \n" + "#import \n" + "#import \n" + "#import \n"; ::grpc::string proto_imports; proto_imports += "#if GPB_GRPC_FORWARD_DECLARE_MESSAGE_PROTO\n" + @@ -65,7 +68,7 @@ class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { for (int i = 0; i < file->dependency_count(); i++) { ::grpc::string header = grpc_objective_c_generator::MessageHeaderName(file->dependency(i)); - const grpc::protobuf::FileDescriptor *dependency = file->dependency(i); + const grpc::protobuf::FileDescriptor* dependency = file->dependency(i); if (IsProtobufLibraryBundledProtoFile(dependency)) { ::grpc::string base_name = header; grpc_generator::StripPrefix(&base_name, "google/protobuf/"); @@ -88,7 +91,7 @@ class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { ::grpc::string declarations; for (int i = 0; i < file->service_count(); i++) { - const grpc::protobuf::ServiceDescriptor *service = file->service(i); + const grpc::protobuf::ServiceDescriptor* service = file->service(i); declarations += grpc_objective_c_generator::GetHeader(service); } @@ -96,22 +99,25 @@ class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { "\nNS_ASSUME_NONNULL_BEGIN\n\n"; static const ::grpc::string kNonNullEnd = "\nNS_ASSUME_NONNULL_END\n"; - Write(context, file_name + ".pbrpc.h", imports + '\n' + proto_imports + - '\n' + kNonNullBegin + - declarations + kNonNullEnd); + Write(context, file_name + ".pbrpc.h", + imports + '\n' + proto_imports + '\n' + kNonNullBegin + + declarations + kNonNullEnd); } { // Generate .pbrpc.m ::grpc::string imports = ::grpc::string("#import \"") + file_name + - ".pbrpc.h\"\n\n" + ".pbrpc.h\"\n" + "#import \"" + + file_name + + ".pbobjc.h\"\n\n" "#import \n" "#import \n"; for (int i = 0; i < file->dependency_count(); i++) { ::grpc::string header = grpc_objective_c_generator::MessageHeaderName(file->dependency(i)); - const grpc::protobuf::FileDescriptor *dependency = file->dependency(i); + const grpc::protobuf::FileDescriptor* dependency = file->dependency(i); if (IsProtobufLibraryBundledProtoFile(dependency)) { ::grpc::string base_name = header; grpc_generator::StripPrefix(&base_name, "google/protobuf/"); @@ -133,7 +139,7 @@ class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { ::grpc::string definitions; for (int i = 0; i < file->service_count(); i++) { - const grpc::protobuf::ServiceDescriptor *service = file->service(i); + const grpc::protobuf::ServiceDescriptor* service = file->service(i); definitions += grpc_objective_c_generator::GetSource(service); } @@ -145,8 +151,8 @@ class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { private: // Write the given code into the given file. - void Write(grpc::protobuf::compiler::GeneratorContext *context, - const ::grpc::string &filename, const ::grpc::string &code) const { + void Write(grpc::protobuf::compiler::GeneratorContext* context, + const ::grpc::string& filename, const ::grpc::string& code) const { std::unique_ptr output( context->Open(filename)); grpc::protobuf::io::CodedOutputStream coded_out(output.get()); @@ -154,7 +160,7 @@ class ObjectiveCGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { } }; -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { ObjectiveCGrpcGenerator generator; return grpc::protobuf::compiler::PluginMain(argc, argv, &generator); } diff --git a/src/compiler/php_generator.cc b/src/compiler/php_generator.cc index 6d9ff3a29c4..d9705e80778 100644 --- a/src/compiler/php_generator.cc +++ b/src/compiler/php_generator.cc @@ -22,10 +22,10 @@ #include "src/compiler/generator_helpers.h" #include "src/compiler/php_generator_helpers.h" +using grpc::protobuf::Descriptor; using grpc::protobuf::FileDescriptor; -using grpc::protobuf::ServiceDescriptor; using grpc::protobuf::MethodDescriptor; -using grpc::protobuf::Descriptor; +using grpc::protobuf::ServiceDescriptor; using grpc::protobuf::io::Printer; using grpc::protobuf::io::StringOutputStream; using std::map; @@ -33,7 +33,7 @@ using std::map; namespace grpc_php_generator { namespace { -grpc::string ConvertToPhpNamespace(const grpc::string &name) { +grpc::string ConvertToPhpNamespace(const grpc::string& name) { std::vector tokens = grpc_generator::tokenize(name, "."); std::ostringstream oss; for (unsigned int i = 0; i < tokens.size(); i++) { @@ -43,7 +43,7 @@ grpc::string ConvertToPhpNamespace(const grpc::string &name) { return oss.str(); } -grpc::string PackageName(const FileDescriptor *file) { +grpc::string PackageName(const FileDescriptor* file) { if (file->options().has_php_namespace()) { return file->options().php_namespace(); } else { @@ -51,8 +51,8 @@ grpc::string PackageName(const FileDescriptor *file) { } } -grpc::string MessageIdentifierName(const grpc::string &name, - const FileDescriptor *file) { +grpc::string MessageIdentifierName(const grpc::string& name, + const FileDescriptor* file) { std::vector tokens = grpc_generator::tokenize(name, "."); std::ostringstream oss; oss << PackageName(file) << "\\" @@ -60,9 +60,9 @@ grpc::string MessageIdentifierName(const grpc::string &name, return oss.str(); } -void PrintMethod(const MethodDescriptor *method, Printer *out) { - const Descriptor *input_type = method->input_type(); - const Descriptor *output_type = method->output_type(); +void PrintMethod(const MethodDescriptor* method, Printer* out) { + const Descriptor* input_type = method->input_type(); + const Descriptor* output_type = method->output_type(); map vars; vars["service_name"] = method->service()->full_name(); vars["name"] = method->name(); @@ -116,8 +116,8 @@ void PrintMethod(const MethodDescriptor *method, Printer *out) { } // Prints out the service descriptor object -void PrintService(const ServiceDescriptor *service, - const grpc::string &class_suffix, Printer *out) { +void PrintService(const ServiceDescriptor* service, + const grpc::string& class_suffix, Printer* out) { map vars; out->Print("/**\n"); out->Print(GetPHPComments(service, " *").c_str()); @@ -148,11 +148,11 @@ void PrintService(const ServiceDescriptor *service, out->Outdent(); out->Print("}\n"); } -} +} // namespace -grpc::string GenerateFile(const FileDescriptor *file, - const ServiceDescriptor *service, - const grpc::string &class_suffix) { +grpc::string GenerateFile(const FileDescriptor* file, + const ServiceDescriptor* service, + const grpc::string& class_suffix) { grpc::string output; { StringOutputStream output_stream(&output); @@ -164,7 +164,7 @@ grpc::string GenerateFile(const FileDescriptor *file, grpc::string leading_comments = GetPHPComments(file, "//"); if (!leading_comments.empty()) { out.Print("// Original file comments:\n"); - out.Print(leading_comments.c_str()); + out.PrintRaw(leading_comments.c_str()); } map vars; diff --git a/src/compiler/php_generator.h b/src/compiler/php_generator.h index 5412d774a99..46222b3d8e7 100644 --- a/src/compiler/php_generator.h +++ b/src/compiler/php_generator.h @@ -23,9 +23,9 @@ namespace grpc_php_generator { -grpc::string GenerateFile(const grpc::protobuf::FileDescriptor *file, - const grpc::protobuf::ServiceDescriptor *service, - const grpc::string &class_suffix); +grpc::string GenerateFile(const grpc::protobuf::FileDescriptor* file, + const grpc::protobuf::ServiceDescriptor* service, + const grpc::string& class_suffix); } // namespace grpc_php_generator diff --git a/src/compiler/php_generator_helpers.h b/src/compiler/php_generator_helpers.h index 3c886794b8f..3ad19977641 100644 --- a/src/compiler/php_generator_helpers.h +++ b/src/compiler/php_generator_helpers.h @@ -27,14 +27,14 @@ namespace grpc_php_generator { inline grpc::string GetPHPServiceClassname( - const grpc::protobuf::ServiceDescriptor *service, - const grpc::string &class_suffix) { + const grpc::protobuf::ServiceDescriptor* service, + const grpc::string& class_suffix) { return service->name() + (class_suffix == "" ? "Client" : class_suffix); } // ReplaceAll replaces all instances of search with replace in s. -inline grpc::string ReplaceAll(grpc::string s, const grpc::string &search, - const grpc::string &replace) { +inline grpc::string ReplaceAll(grpc::string s, const grpc::string& search, + const grpc::string& replace) { size_t pos = 0; while ((pos = s.find(search, pos)) != grpc::string::npos) { s.replace(pos, search.length(), replace); @@ -44,9 +44,9 @@ inline grpc::string ReplaceAll(grpc::string s, const grpc::string &search, } inline grpc::string GetPHPServiceFilename( - const grpc::protobuf::FileDescriptor *file, - const grpc::protobuf::ServiceDescriptor *service, - const grpc::string &class_suffix) { + const grpc::protobuf::FileDescriptor* file, + const grpc::protobuf::ServiceDescriptor* service, + const grpc::string& class_suffix) { std::ostringstream oss; if (file->options().has_php_namespace()) { oss << ReplaceAll(file->options().php_namespace(), "\\", "/"); @@ -65,7 +65,7 @@ inline grpc::string GetPHPServiceFilename( // Get leading or trailing comments in a string. Comment lines start with "// ". // Leading detached comments are put in in front of leading comments. template -inline grpc::string GetPHPComments(const DescriptorType *desc, +inline grpc::string GetPHPComments(const DescriptorType* desc, grpc::string prefix) { return ReplaceAll(grpc_generator::GetPrefixedComments(desc, true, prefix), "*/", "*/"); diff --git a/src/compiler/php_plugin.cc b/src/compiler/php_plugin.cc index 7b0da87eb2d..d01cbf87a0f 100644 --- a/src/compiler/php_plugin.cc +++ b/src/compiler/php_plugin.cc @@ -24,19 +24,19 @@ #include "src/compiler/php_generator.h" #include "src/compiler/php_generator_helpers.h" +using google::protobuf::compiler::ParseGeneratorParameter; using grpc_php_generator::GenerateFile; using grpc_php_generator::GetPHPServiceFilename; -using google::protobuf::compiler::ParseGeneratorParameter; class PHPGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { public: PHPGrpcGenerator() {} ~PHPGrpcGenerator() {} - bool Generate(const grpc::protobuf::FileDescriptor *file, - const grpc::string ¶meter, - grpc::protobuf::compiler::GeneratorContext *context, - grpc::string *error) const { + bool Generate(const grpc::protobuf::FileDescriptor* file, + const grpc::string& parameter, + grpc::protobuf::compiler::GeneratorContext* context, + grpc::string* error) const { if (file->service_count() == 0) { return true; } @@ -71,7 +71,7 @@ class PHPGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { } }; -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { PHPGrpcGenerator generator; return grpc::protobuf::compiler::PluginMain(argc, argv, &generator); } diff --git a/src/compiler/protobuf_plugin.h b/src/compiler/protobuf_plugin.h index e14740cc0c6..b971af13109 100644 --- a/src/compiler/protobuf_plugin.h +++ b/src/compiler/protobuf_plugin.h @@ -29,14 +29,14 @@ // Get leading or trailing comments in a string. template -inline grpc::string GetCommentsHelper(const DescriptorType *desc, bool leading, - const grpc::string &prefix) { +inline grpc::string GetCommentsHelper(const DescriptorType* desc, bool leading, + const grpc::string& prefix) { return grpc_generator::GetPrefixedComments(desc, leading, prefix); } class ProtoBufMethod : public grpc_generator::Method { public: - ProtoBufMethod(const grpc::protobuf::MethodDescriptor *method) + ProtoBufMethod(const grpc::protobuf::MethodDescriptor* method) : method_(method) {} grpc::string name() const { return method_->name(); } @@ -55,7 +55,7 @@ class ProtoBufMethod : public grpc_generator::Method { return method_->output_type()->file()->name(); } - bool get_module_and_message_path_input(grpc::string *str, + bool get_module_and_message_path_input(grpc::string* str, grpc::string generator_file_name, bool generate_in_pb2_grpc, grpc::string import_prefix) const { @@ -64,7 +64,7 @@ class ProtoBufMethod : public grpc_generator::Method { import_prefix); } - bool get_module_and_message_path_output(grpc::string *str, + bool get_module_and_message_path_output(grpc::string* str, grpc::string generator_file_name, bool generate_in_pb2_grpc, grpc::string import_prefix) const { @@ -98,12 +98,12 @@ class ProtoBufMethod : public grpc_generator::Method { } private: - const grpc::protobuf::MethodDescriptor *method_; + const grpc::protobuf::MethodDescriptor* method_; }; class ProtoBufService : public grpc_generator::Service { public: - ProtoBufService(const grpc::protobuf::ServiceDescriptor *service) + ProtoBufService(const grpc::protobuf::ServiceDescriptor* service) : service_(service) {} grpc::string name() const { return service_->name(); } @@ -127,20 +127,21 @@ class ProtoBufService : public grpc_generator::Service { } private: - const grpc::protobuf::ServiceDescriptor *service_; + const grpc::protobuf::ServiceDescriptor* service_; }; class ProtoBufPrinter : public grpc_generator::Printer { public: - ProtoBufPrinter(grpc::string *str) + ProtoBufPrinter(grpc::string* str) : output_stream_(str), printer_(&output_stream_, '$') {} - void Print(const std::map &vars, - const char *string_template) { + void Print(const std::map& vars, + const char* string_template) { printer_.Print(vars, string_template); } - void Print(const char *string) { printer_.Print(string); } + void Print(const char* string) { printer_.Print(string); } + void PrintRaw(const char* string) { printer_.PrintRaw(string); } void Indent() { printer_.Indent(); } void Outdent() { printer_.Outdent(); } @@ -151,7 +152,7 @@ class ProtoBufPrinter : public grpc_generator::Printer { class ProtoBufFile : public grpc_generator::File { public: - ProtoBufFile(const grpc::protobuf::FileDescriptor *file) : file_(file) {} + ProtoBufFile(const grpc::protobuf::FileDescriptor* file) : file_(file) {} grpc::string filename() const { return file_->name(); } grpc::string filename_without_ext() const { @@ -172,7 +173,7 @@ class ProtoBufFile : public grpc_generator::File { } std::unique_ptr CreatePrinter( - grpc::string *str) const { + grpc::string* str) const { return std::unique_ptr(new ProtoBufPrinter(str)); } @@ -189,7 +190,7 @@ class ProtoBufFile : public grpc_generator::File { } private: - const grpc::protobuf::FileDescriptor *file_; + const grpc::protobuf::FileDescriptor* file_; }; #endif // GRPC_INTERNAL_COMPILER_PROTOBUF_PLUGIN_H diff --git a/src/compiler/python_generator.cc b/src/compiler/python_generator.cc index ef2d90de9e9..8a0b8894549 100644 --- a/src/compiler/python_generator.cc +++ b/src/compiler/python_generator.cc @@ -45,9 +45,9 @@ using std::make_pair; using std::map; using std::pair; using std::replace; +using std::set; using std::tuple; using std::vector; -using std::set; namespace grpc_python_generator { @@ -101,7 +101,7 @@ void PrivateGenerator::PrintAllComments(StringVector comments, ++it) { size_t start_pos = it->find_first_not_of(' '); if (start_pos != grpc::string::npos) { - out->Print(it->c_str() + start_pos); + out->PrintRaw(it->c_str() + start_pos); } out->Print("\n"); } diff --git a/src/compiler/python_generator_helpers.h b/src/compiler/python_generator_helpers.h index fb3e860d3ed..b1b58befdf4 100644 --- a/src/compiler/python_generator_helpers.h +++ b/src/compiler/python_generator_helpers.h @@ -29,9 +29,6 @@ #include "src/compiler/python_generator.h" #include "src/compiler/python_private_generator.h" -using std::vector; -using grpc_generator::StringReplace; -using grpc_generator::StripProto; using grpc::protobuf::Descriptor; using grpc::protobuf::FileDescriptor; using grpc::protobuf::MethodDescriptor; @@ -41,6 +38,9 @@ using grpc::protobuf::io::CodedOutputStream; using grpc::protobuf::io::Printer; using grpc::protobuf::io::StringOutputStream; using grpc::protobuf::io::ZeroCopyOutputStream; +using grpc_generator::StringReplace; +using grpc_generator::StripProto; +using std::vector; namespace grpc_python_generator { diff --git a/src/compiler/ruby_generator.cc b/src/compiler/ruby_generator.cc index 54d8a425976..e81dea603ba 100644 --- a/src/compiler/ruby_generator.cc +++ b/src/compiler/ruby_generator.cc @@ -27,8 +27,8 @@ #include "src/compiler/ruby_generator_string-inl.h" using grpc::protobuf::FileDescriptor; -using grpc::protobuf::ServiceDescriptor; using grpc::protobuf::MethodDescriptor; +using grpc::protobuf::ServiceDescriptor; using grpc::protobuf::io::Printer; using grpc::protobuf::io::StringOutputStream; using std::map; @@ -38,8 +38,8 @@ namespace grpc_ruby_generator { namespace { // Prints out the method using the ruby gRPC DSL. -void PrintMethod(const MethodDescriptor *method, const grpc::string &package, - Printer *out) { +void PrintMethod(const MethodDescriptor* method, const grpc::string& package, + Printer* out) { grpc::string input_type = RubyTypeOf(method->input_type()->full_name(), package); if (method->client_streaming()) { @@ -51,7 +51,11 @@ void PrintMethod(const MethodDescriptor *method, const grpc::string &package, output_type = "stream(" + output_type + ")"; } std::map method_vars = ListToDict({ - "mth.name", method->name(), "input.type", input_type, "output.type", + "mth.name", + method->name(), + "input.type", + input_type, + "output.type", output_type, }); out->Print(GetRubyComments(method, true).c_str()); @@ -60,15 +64,16 @@ void PrintMethod(const MethodDescriptor *method, const grpc::string &package, } // Prints out the service using the ruby gRPC DSL. -void PrintService(const ServiceDescriptor *service, const grpc::string &package, - Printer *out) { +void PrintService(const ServiceDescriptor* service, const grpc::string& package, + Printer* out) { if (service->method_count() == 0) { return; } // Begin the service module std::map module_vars = ListToDict({ - "module.name", CapitalizeFirst(service->name()), + "module.name", + CapitalizeFirst(service->name()), }); out->Print(module_vars, "module $module.name$\n"); out->Indent(); @@ -119,7 +124,7 @@ char ToUpper(char ch) { return IsLower(ch) ? (ch - 'a' + 'A') : ch; } // names must be PascalCased. // // foo_bar_baz -> FooBarBaz -grpc::string PackageToModule(const grpc::string &name) { +grpc::string PackageToModule(const grpc::string& name) { bool next_upper = true; grpc::string result; result.reserve(name.size()); @@ -141,7 +146,7 @@ grpc::string PackageToModule(const grpc::string &name) { } // end copying of protoc generator for ruby code -grpc::string GetServices(const FileDescriptor *file) { +grpc::string GetServices(const FileDescriptor* file) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. @@ -157,7 +162,10 @@ grpc::string GetServices(const FileDescriptor *file) { // Write out a file header. std::map header_comment_vars = ListToDict({ - "file.name", file->name(), "file.package", file->package(), + "file.name", + file->name(), + "file.package", + file->package(), }); out.Print("# Generated by the protocol buffer compiler. DO NOT EDIT!\n"); out.Print(header_comment_vars, @@ -166,7 +174,7 @@ grpc::string GetServices(const FileDescriptor *file) { grpc::string leading_comments = GetRubyComments(file, true); if (!leading_comments.empty()) { out.Print("# Original file comments:\n"); - out.Print(leading_comments.c_str()); + out.PrintRaw(leading_comments.c_str()); } out.Print("\n"); @@ -175,7 +183,8 @@ grpc::string GetServices(const FileDescriptor *file) { // that defines the messages used by the service. This is generated by the // main ruby plugin. std::map dep_vars = ListToDict({ - "dep.name", MessagesRequireName(file), + "dep.name", + MessagesRequireName(file), }); out.Print(dep_vars, "require '$dep.name$'\n"); @@ -184,7 +193,8 @@ grpc::string GetServices(const FileDescriptor *file) { std::vector modules = Split(file->package(), '.'); for (size_t i = 0; i < modules.size(); ++i) { std::map module_vars = ListToDict({ - "module.name", PackageToModule(modules[i]), + "module.name", + PackageToModule(modules[i]), }); out.Print(module_vars, "module $module.name$\n"); out.Indent(); diff --git a/src/compiler/ruby_generator.h b/src/compiler/ruby_generator.h index cdc03aa0d45..9a03e0d1396 100644 --- a/src/compiler/ruby_generator.h +++ b/src/compiler/ruby_generator.h @@ -23,7 +23,7 @@ namespace grpc_ruby_generator { -grpc::string GetServices(const grpc::protobuf::FileDescriptor *file); +grpc::string GetServices(const grpc::protobuf::FileDescriptor* file); } // namespace grpc_ruby_generator diff --git a/src/compiler/ruby_generator_helpers-inl.h b/src/compiler/ruby_generator_helpers-inl.h index ac09f8dcdbb..2323770425a 100644 --- a/src/compiler/ruby_generator_helpers-inl.h +++ b/src/compiler/ruby_generator_helpers-inl.h @@ -25,8 +25,8 @@ namespace grpc_ruby_generator { -inline bool ServicesFilename(const grpc::protobuf::FileDescriptor *file, - grpc::string *file_name_or_error) { +inline bool ServicesFilename(const grpc::protobuf::FileDescriptor* file, + grpc::string* file_name_or_error) { // Get output file name. static const unsigned proto_suffix_length = 6; // length of ".proto" if (file->name().size() > proto_suffix_length && @@ -42,14 +42,14 @@ inline bool ServicesFilename(const grpc::protobuf::FileDescriptor *file, } inline grpc::string MessagesRequireName( - const grpc::protobuf::FileDescriptor *file) { + const grpc::protobuf::FileDescriptor* file) { return Replace(file->name(), ".proto", "_pb"); } // Get leading or trailing comments in a string. Comment lines start with "# ". // Leading detached comments are put in in front of leading comments. template -inline grpc::string GetRubyComments(const DescriptorType *desc, bool leading) { +inline grpc::string GetRubyComments(const DescriptorType* desc, bool leading) { return grpc_generator::GetPrefixedComments(desc, leading, "#"); } diff --git a/src/compiler/ruby_generator_map-inl.h b/src/compiler/ruby_generator_map-inl.h index 12973e4fb4e..89a74b1d410 100644 --- a/src/compiler/ruby_generator_map-inl.h +++ b/src/compiler/ruby_generator_map-inl.h @@ -36,7 +36,7 @@ namespace grpc_ruby_generator { // Converts an initializer list of the form { key0, value0, key1, value1, ... } // into a map of key* to value*. Is merely a readability helper for later code. inline std::map ListToDict( - const initializer_list &values) { + const initializer_list& values) { if (values.size() % 2 != 0) { std::cerr << "Not every 'key' has a value in `values`." << std::endl; } diff --git a/src/compiler/ruby_generator_string-inl.h b/src/compiler/ruby_generator_string-inl.h index def92edec69..fb429784bb7 100644 --- a/src/compiler/ruby_generator_string-inl.h +++ b/src/compiler/ruby_generator_string-inl.h @@ -31,8 +31,8 @@ using std::transform; namespace grpc_ruby_generator { // Split splits a string using char into elems. -inline std::vector &Split(const grpc::string &s, char delim, - std::vector *elems) { +inline std::vector& Split(const grpc::string& s, char delim, + std::vector* elems) { std::stringstream ss(s); grpc::string item; while (getline(ss, item, delim)) { @@ -42,15 +42,15 @@ inline std::vector &Split(const grpc::string &s, char delim, } // Split splits a string using char, returning the result in a vector. -inline std::vector Split(const grpc::string &s, char delim) { +inline std::vector Split(const grpc::string& s, char delim) { std::vector elems; Split(s, delim, &elems); return elems; } // Replace replaces from with to in s. -inline grpc::string Replace(grpc::string s, const grpc::string &from, - const grpc::string &to) { +inline grpc::string Replace(grpc::string s, const grpc::string& from, + const grpc::string& to) { size_t start_pos = s.find(from); if (start_pos == grpc::string::npos) { return s; @@ -60,8 +60,8 @@ inline grpc::string Replace(grpc::string s, const grpc::string &from, } // ReplaceAll replaces all instances of search with replace in s. -inline grpc::string ReplaceAll(grpc::string s, const grpc::string &search, - const grpc::string &replace) { +inline grpc::string ReplaceAll(grpc::string s, const grpc::string& search, + const grpc::string& replace) { size_t pos = 0; while ((pos = s.find(search, pos)) != grpc::string::npos) { s.replace(pos, search.length(), replace); @@ -71,8 +71,8 @@ inline grpc::string ReplaceAll(grpc::string s, const grpc::string &search, } // ReplacePrefix replaces from with to in s if search is a prefix of s. -inline bool ReplacePrefix(grpc::string *s, const grpc::string &from, - const grpc::string &to) { +inline bool ReplacePrefix(grpc::string* s, const grpc::string& from, + const grpc::string& to) { size_t start_pos = s->find(from); if (start_pos == grpc::string::npos || start_pos != 0) { return false; @@ -91,8 +91,8 @@ inline grpc::string CapitalizeFirst(grpc::string s) { } // RubyTypeOf updates a proto type to the required ruby equivalent. -inline grpc::string RubyTypeOf(const grpc::string &a_type, - const grpc::string &package) { +inline grpc::string RubyTypeOf(const grpc::string& a_type, + const grpc::string& package) { grpc::string res(a_type); ReplacePrefix(&res, package, ""); // remove the leading package if present ReplacePrefix(&res, ".", ""); // remove the leading . (no package) diff --git a/src/compiler/ruby_plugin.cc b/src/compiler/ruby_plugin.cc index f1b1d0182ad..9c234bd7cbc 100644 --- a/src/compiler/ruby_plugin.cc +++ b/src/compiler/ruby_plugin.cc @@ -29,10 +29,10 @@ class RubyGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { RubyGrpcGenerator() {} ~RubyGrpcGenerator() {} - bool Generate(const grpc::protobuf::FileDescriptor *file, - const grpc::string ¶meter, - grpc::protobuf::compiler::GeneratorContext *context, - grpc::string *error) const { + bool Generate(const grpc::protobuf::FileDescriptor* file, + const grpc::string& parameter, + grpc::protobuf::compiler::GeneratorContext* context, + grpc::string* error) const { grpc::string code = grpc_ruby_generator::GetServices(file); if (code.size() == 0) { return true; // don't generate a file if there are no services @@ -51,7 +51,7 @@ class RubyGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { } }; -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { RubyGrpcGenerator generator; return grpc::protobuf::compiler::PluginMain(argc, argv, &generator); } diff --git a/src/compiler/schema_interface.h b/src/compiler/schema_interface.h index 828c7753df5..c000478e681 100644 --- a/src/compiler/schema_interface.h +++ b/src/compiler/schema_interface.h @@ -56,10 +56,10 @@ struct Method : public CommentHolder { virtual grpc::string output_type_name() const = 0; virtual bool get_module_and_message_path_input( - grpc::string *str, grpc::string generator_file_name, + grpc::string* str, grpc::string generator_file_name, bool generate_in_pb2_grpc, grpc::string import_prefix) const = 0; virtual bool get_module_and_message_path_output( - grpc::string *str, grpc::string generator_file_name, + grpc::string* str, grpc::string generator_file_name, bool generate_in_pb2_grpc, grpc::string import_prefix) const = 0; virtual grpc::string get_input_type_name() const = 0; @@ -83,9 +83,10 @@ struct Service : public CommentHolder { struct Printer { virtual ~Printer() {} - virtual void Print(const std::map &vars, - const char *template_string) = 0; - virtual void Print(const char *string) = 0; + virtual void Print(const std::map& vars, + const char* template_string) = 0; + virtual void Print(const char* string) = 0; + virtual void PrintRaw(const char* string) = 0; virtual void Indent() = 0; virtual void Outdent() = 0; }; @@ -104,7 +105,7 @@ struct File : public CommentHolder { virtual int service_count() const = 0; virtual std::unique_ptr service(int i) const = 0; - virtual std::unique_ptr CreatePrinter(grpc::string *str) const = 0; + virtual std::unique_ptr CreatePrinter(grpc::string* str) const = 0; }; } // namespace grpc_generator diff --git a/src/core/ext/census/grpc_context.cc b/src/core/ext/census/grpc_context.cc index 34eafcab8e7..ffe7c51ff89 100644 --- a/src/core/ext/census/grpc_context.cc +++ b/src/core/ext/census/grpc_context.cc @@ -21,15 +21,15 @@ #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/call.h" -void grpc_census_call_set_context(grpc_call *call, census_context *context) { +void grpc_census_call_set_context(grpc_call* call, census_context* context) { GRPC_API_TRACE("grpc_census_call_set_context(call=%p, census_context=%p)", 2, (call, context)); - if (context != NULL) { - grpc_call_context_set(call, GRPC_CONTEXT_TRACING, context, NULL); + if (context != nullptr) { + grpc_call_context_set(call, GRPC_CONTEXT_TRACING, context, nullptr); } } -census_context *grpc_census_call_get_context(grpc_call *call) { +census_context* grpc_census_call_get_context(grpc_call* call) { GRPC_API_TRACE("grpc_census_call_get_context(call=%p)", 1, (call)); - return (census_context *)grpc_call_context_get(call, GRPC_CONTEXT_TRACING); + return (census_context*)grpc_call_context_get(call, GRPC_CONTEXT_TRACING); } diff --git a/src/core/ext/filters/client_channel/backup_poller.cc b/src/core/ext/filters/client_channel/backup_poller.cc index 466bf86bc00..ed437d255c9 100644 --- a/src/core/ext/filters/client_channel/backup_poller.cc +++ b/src/core/ext/filters/client_channel/backup_poller.cc @@ -46,7 +46,7 @@ typedef struct backup_poller { static gpr_once g_once = GPR_ONCE_INIT; static gpr_mu g_poller_mu; -static backup_poller* g_poller = NULL; // guarded by g_poller_mu +static backup_poller* g_poller = nullptr; // guarded by g_poller_mu // g_poll_interval_ms is set only once at the first time // grpc_client_channel_start_backup_polling() is called, after that it is // treated as const. @@ -55,7 +55,7 @@ static int g_poll_interval_ms = DEFAULT_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 != NULL) { + if (env != nullptr) { int poll_interval_ms = gpr_parse_nonnegative_int(env); if (poll_interval_ms == -1) { gpr_log(GPR_ERROR, @@ -86,7 +86,7 @@ static void g_poller_unref(grpc_exec_ctx* exec_ctx) { if (gpr_unref(&g_poller->refs)) { gpr_mu_lock(&g_poller_mu); backup_poller* p = g_poller; - g_poller = NULL; + g_poller = nullptr; gpr_mu_unlock(&g_poller_mu); gpr_mu_lock(p->pollset_mu); p->shutting_down = true; @@ -113,7 +113,7 @@ static void run_poller(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { backup_poller_shutdown_unref(exec_ctx, p); return; } - grpc_error* err = grpc_pollset_work(exec_ctx, p->pollset, NULL, + grpc_error* err = grpc_pollset_work(exec_ctx, p->pollset, nullptr, grpc_exec_ctx_now(exec_ctx)); gpr_mu_unlock(p->pollset_mu); GRPC_LOG_IF_ERROR("Run client channel backup poller", err); @@ -129,7 +129,7 @@ void grpc_client_channel_start_backup_polling( return; } gpr_mu_lock(&g_poller_mu); - if (g_poller == NULL) { + if (g_poller == nullptr) { g_poller = (backup_poller*)gpr_zalloc(sizeof(backup_poller)); g_poller->pollset = (grpc_pollset*)gpr_zalloc(grpc_pollset_size()); g_poller->shutting_down = false; @@ -143,9 +143,16 @@ void grpc_client_channel_start_backup_polling( grpc_exec_ctx_now(exec_ctx) + g_poll_interval_ms, &g_poller->run_poller_closure); } + gpr_ref(&g_poller->refs); + /* Get a reference to g_poller->pollset before releasing g_poller_mu to make + * TSAN happy. Otherwise, reading from g_poller (i.e g_poller->pollset) after + * releasing the lock and setting g_poller to NULL in g_poller_unref() is + * being flagged as a data-race by TSAN */ + grpc_pollset* pollset = g_poller->pollset; gpr_mu_unlock(&g_poller_mu); - grpc_pollset_set_add_pollset(exec_ctx, interested_parties, g_poller->pollset); + + grpc_pollset_set_add_pollset(exec_ctx, interested_parties, pollset); } void grpc_client_channel_stop_backup_polling( diff --git a/src/core/ext/filters/client_channel/channel_connectivity.cc b/src/core/ext/filters/client_channel/channel_connectivity.cc index 31a8fc39ce6..7eaf5d98cd8 100644 --- a/src/core/ext/filters/client_channel/channel_connectivity.cc +++ b/src/core/ext/filters/client_channel/channel_connectivity.cc @@ -29,9 +29,9 @@ #include "src/core/lib/surface/completion_queue.h" grpc_connectivity_state grpc_channel_check_connectivity_state( - grpc_channel *channel, int try_to_connect) { + grpc_channel* channel, int try_to_connect) { /* forward through to the underlying client channel */ - grpc_channel_element *client_channel_elem = + grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(grpc_channel_get_channel_stack(channel)); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_connectivity_state state; @@ -66,15 +66,15 @@ typedef struct { grpc_closure watcher_timer_init; grpc_timer alarm; grpc_connectivity_state state; - grpc_completion_queue *cq; + grpc_completion_queue* cq; grpc_cq_completion completion_storage; - grpc_channel *channel; - grpc_error *error; - void *tag; + grpc_channel* channel; + grpc_error* error; + void* tag; } state_watcher; -static void delete_state_watcher(grpc_exec_ctx *exec_ctx, state_watcher *w) { - grpc_channel_element *client_channel_elem = grpc_channel_stack_last_element( +static void delete_state_watcher(grpc_exec_ctx* exec_ctx, state_watcher* w) { + grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element( grpc_channel_get_channel_stack(w->channel)); if (client_channel_elem->filter == &grpc_client_channel_filter) { GRPC_CHANNEL_INTERNAL_UNREF(exec_ctx, w->channel, @@ -86,10 +86,10 @@ static void delete_state_watcher(grpc_exec_ctx *exec_ctx, state_watcher *w) { gpr_free(w); } -static void finished_completion(grpc_exec_ctx *exec_ctx, void *pw, - grpc_cq_completion *ignored) { +static void finished_completion(grpc_exec_ctx* exec_ctx, void* pw, + grpc_cq_completion* ignored) { bool should_delete = false; - state_watcher *w = (state_watcher *)pw; + state_watcher* w = (state_watcher*)pw; gpr_mu_lock(&w->mu); switch (w->phase) { case WAITING: @@ -106,23 +106,23 @@ static void finished_completion(grpc_exec_ctx *exec_ctx, void *pw, } } -static void partly_done(grpc_exec_ctx *exec_ctx, state_watcher *w, - bool due_to_completion, grpc_error *error) { +static void partly_done(grpc_exec_ctx* exec_ctx, state_watcher* w, + bool due_to_completion, grpc_error* error) { if (due_to_completion) { grpc_timer_cancel(exec_ctx, &w->alarm); } else { - grpc_channel_element *client_channel_elem = grpc_channel_stack_last_element( + grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element( grpc_channel_get_channel_stack(w->channel)); grpc_client_channel_watch_connectivity_state( exec_ctx, client_channel_elem, - grpc_polling_entity_create_from_pollset(grpc_cq_pollset(w->cq)), NULL, - &w->on_complete, NULL); + grpc_polling_entity_create_from_pollset(grpc_cq_pollset(w->cq)), + nullptr, &w->on_complete, nullptr); } gpr_mu_lock(&w->mu); if (due_to_completion) { - if (GRPC_TRACER_ON(grpc_trace_operation_failures)) { + if (grpc_trace_operation_failures.enabled()) { GRPC_LOG_IF_ERROR("watch_completion_error", GRPC_ERROR_REF(error)); } GRPC_ERROR_UNREF(error); @@ -161,31 +161,31 @@ static void partly_done(grpc_exec_ctx *exec_ctx, state_watcher *w, GRPC_ERROR_UNREF(error); } -static void watch_complete(grpc_exec_ctx *exec_ctx, void *pw, - grpc_error *error) { - partly_done(exec_ctx, (state_watcher *)pw, true, GRPC_ERROR_REF(error)); +static void watch_complete(grpc_exec_ctx* exec_ctx, void* pw, + grpc_error* error) { + partly_done(exec_ctx, (state_watcher*)pw, true, GRPC_ERROR_REF(error)); } -static void timeout_complete(grpc_exec_ctx *exec_ctx, void *pw, - grpc_error *error) { - partly_done(exec_ctx, (state_watcher *)pw, false, GRPC_ERROR_REF(error)); +static void timeout_complete(grpc_exec_ctx* exec_ctx, void* pw, + grpc_error* error) { + partly_done(exec_ctx, (state_watcher*)pw, false, GRPC_ERROR_REF(error)); } -int grpc_channel_num_external_connectivity_watchers(grpc_channel *channel) { - grpc_channel_element *client_channel_elem = +int grpc_channel_num_external_connectivity_watchers(grpc_channel* channel) { + grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(grpc_channel_get_channel_stack(channel)); return grpc_client_channel_num_external_connectivity_watchers( client_channel_elem); } typedef struct watcher_timer_init_arg { - state_watcher *w; + state_watcher* w; gpr_timespec deadline; } watcher_timer_init_arg; -static void watcher_timer_init(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error_ignored) { - watcher_timer_init_arg *wa = (watcher_timer_init_arg *)arg; +static void watcher_timer_init(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error_ignored) { + watcher_timer_init_arg* wa = (watcher_timer_init_arg*)arg; grpc_timer_init(exec_ctx, &wa->w->alarm, grpc_timespec_to_millis_round_up(wa->deadline), @@ -193,19 +193,19 @@ static void watcher_timer_init(grpc_exec_ctx *exec_ctx, void *arg, gpr_free(wa); } -int grpc_channel_support_connectivity_watcher(grpc_channel *channel) { - grpc_channel_element *client_channel_elem = +int grpc_channel_support_connectivity_watcher(grpc_channel* channel) { + grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(grpc_channel_get_channel_stack(channel)); return client_channel_elem->filter != &grpc_client_channel_filter ? 0 : 1; } void grpc_channel_watch_connectivity_state( - grpc_channel *channel, grpc_connectivity_state last_observed_state, - gpr_timespec deadline, grpc_completion_queue *cq, void *tag) { - grpc_channel_element *client_channel_elem = + grpc_channel* channel, grpc_connectivity_state last_observed_state, + gpr_timespec deadline, grpc_completion_queue* cq, void* tag) { + grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(grpc_channel_get_channel_stack(channel)); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - state_watcher *w = (state_watcher *)gpr_malloc(sizeof(*w)); + state_watcher* w = (state_watcher*)gpr_malloc(sizeof(*w)); GRPC_API_TRACE( "grpc_channel_watch_connectivity_state(" @@ -213,8 +213,9 @@ void grpc_channel_watch_connectivity_state( "deadline=gpr_timespec { tv_sec: %" PRId64 ", tv_nsec: %d, clock_type: %d }, " "cq=%p, tag=%p)", - 7, (channel, (int)last_observed_state, deadline.tv_sec, deadline.tv_nsec, - (int)deadline.clock_type, cq, tag)); + 7, + (channel, (int)last_observed_state, deadline.tv_sec, deadline.tv_nsec, + (int)deadline.clock_type, cq, tag)); GPR_ASSERT(grpc_cq_begin_op(cq, tag)); @@ -228,10 +229,10 @@ void grpc_channel_watch_connectivity_state( w->cq = cq; w->tag = tag; w->channel = channel; - w->error = NULL; + w->error = nullptr; - watcher_timer_init_arg *wa = - (watcher_timer_init_arg *)gpr_malloc(sizeof(watcher_timer_init_arg)); + watcher_timer_init_arg* wa = + (watcher_timer_init_arg*)gpr_malloc(sizeof(watcher_timer_init_arg)); wa->w = w; wa->deadline = deadline; GRPC_CLOSURE_INIT(&w->watcher_timer_init, watcher_timer_init, wa, diff --git a/src/core/ext/filters/client_channel/client_channel.cc b/src/core/ext/filters/client_channel/client_channel.cc index 00c51ba543f..aced9adf9f1 100644 --- a/src/core/ext/filters/client_channel/client_channel.cc +++ b/src/core/ext/filters/client_channel/client_channel.cc @@ -56,8 +56,7 @@ /* Client channel implementation */ -grpc_tracer_flag grpc_client_channel_trace = - GRPC_TRACER_INITIALIZER(false, "client_channel"); +grpc_core::TraceFlag grpc_client_channel_trace(false, "client_channel"); /************************************************************************* * METHOD-CONFIG TABLE @@ -76,24 +75,29 @@ typedef struct { wait_for_ready_value wait_for_ready; } method_parameters; -static method_parameters *method_parameters_ref( - method_parameters *method_params) { +static method_parameters* method_parameters_ref( + method_parameters* method_params) { gpr_ref(&method_params->refs); return method_params; } -static void method_parameters_unref(method_parameters *method_params) { +static void method_parameters_unref(method_parameters* method_params) { if (gpr_unref(&method_params->refs)) { gpr_free(method_params); } } -static void method_parameters_free(grpc_exec_ctx *exec_ctx, void *value) { - method_parameters_unref((method_parameters *)value); +// Wrappers to pass to grpc_service_config_create_method_config_table(). +static void* method_parameters_ref_wrapper(void* value) { + return method_parameters_ref((method_parameters*)value); +} +static void method_parameters_unref_wrapper(grpc_exec_ctx* exec_ctx, + void* value) { + method_parameters_unref((method_parameters*)value); } -static bool parse_wait_for_ready(grpc_json *field, - wait_for_ready_value *wait_for_ready) { +static bool parse_wait_for_ready(grpc_json* field, + wait_for_ready_value* wait_for_ready) { if (field->type != GRPC_JSON_TRUE && field->type != GRPC_JSON_FALSE) { return false; } @@ -102,60 +106,52 @@ static bool parse_wait_for_ready(grpc_json *field, return true; } -static bool parse_timeout(grpc_json *field, grpc_millis *timeout) { +static bool parse_timeout(grpc_json* field, grpc_millis* timeout) { if (field->type != GRPC_JSON_STRING) return false; size_t len = strlen(field->value); if (field->value[len - 1] != 's') return false; - char *buf = gpr_strdup(field->value); + char* buf = gpr_strdup(field->value); buf[len - 1] = '\0'; // Remove trailing 's'. - char *decimal_point = strchr(buf, '.'); + char* decimal_point = strchr(buf, '.'); int nanos = 0; - if (decimal_point != NULL) { + if (decimal_point != nullptr) { *decimal_point = '\0'; nanos = gpr_parse_nonnegative_int(decimal_point + 1); if (nanos == -1) { gpr_free(buf); return false; } - // There should always be exactly 3, 6, or 9 fractional digits. - int multiplier = 1; - switch (strlen(decimal_point + 1)) { - case 9: - break; - case 6: - multiplier *= 1000; - break; - case 3: - multiplier *= 1000000; - break; - default: // Unsupported number of digits. - gpr_free(buf); - return false; + int num_digits = (int)strlen(decimal_point + 1); + if (num_digits > 9) { // We don't accept greater precision than nanos. + gpr_free(buf); + return false; + } + for (int i = 0; i < (9 - num_digits); ++i) { + nanos *= 10; } - nanos *= multiplier; } - int seconds = gpr_parse_nonnegative_int(buf); + int seconds = decimal_point == buf ? 0 : gpr_parse_nonnegative_int(buf); gpr_free(buf); if (seconds == -1) return false; *timeout = seconds * GPR_MS_PER_SEC + nanos / GPR_NS_PER_MS; return true; } -static void *method_parameters_create_from_json(const grpc_json *json) { +static void* method_parameters_create_from_json(const grpc_json* json) { wait_for_ready_value wait_for_ready = WAIT_FOR_READY_UNSET; grpc_millis timeout = 0; - for (grpc_json *field = json->child; field != NULL; field = field->next) { - if (field->key == NULL) continue; + for (grpc_json* field = json->child; field != nullptr; field = field->next) { + if (field->key == nullptr) continue; if (strcmp(field->key, "waitForReady") == 0) { - if (wait_for_ready != WAIT_FOR_READY_UNSET) return NULL; // Duplicate. - if (!parse_wait_for_ready(field, &wait_for_ready)) return NULL; + if (wait_for_ready != WAIT_FOR_READY_UNSET) return nullptr; // Duplicate. + if (!parse_wait_for_ready(field, &wait_for_ready)) return nullptr; } else if (strcmp(field->key, "timeout") == 0) { - if (timeout > 0) return NULL; // Duplicate. - if (!parse_timeout(field, &timeout)) return NULL; + if (timeout > 0) return nullptr; // Duplicate. + if (!parse_timeout(field, &timeout)) return nullptr; } } - method_parameters *value = - (method_parameters *)gpr_malloc(sizeof(method_parameters)); + method_parameters* value = + (method_parameters*)gpr_malloc(sizeof(method_parameters)); gpr_ref_init(&value->refs, 1); value->timeout = timeout; value->wait_for_ready = wait_for_ready; @@ -170,24 +166,24 @@ struct external_connectivity_watcher; typedef struct client_channel_channel_data { /** resolver for this channel */ - grpc_resolver *resolver; + grpc_resolver* resolver; /** have we started resolving this channel */ bool started_resolving; /** is deadline checking enabled? */ bool deadline_checking_enabled; /** client channel factory */ - grpc_client_channel_factory *client_channel_factory; + grpc_client_channel_factory* client_channel_factory; /** combiner protecting all variables below in this data structure */ - grpc_combiner *combiner; + grpc_combiner* combiner; /** currently active load balancer */ - grpc_lb_policy *lb_policy; + grpc_lb_policy* lb_policy; /** retry throttle data */ - grpc_server_retry_throttle_data *retry_throttle_data; + grpc_server_retry_throttle_data* retry_throttle_data; /** maps method names to method_parameters structs */ - grpc_slice_hash_table *method_params_table; + grpc_slice_hash_table* method_params_table; /** incoming resolver result - set by resolver.next() */ - grpc_channel_args *resolver_result; + grpc_channel_args* resolver_result; /** a list of closures that are all waiting for resolver result to come in */ grpc_closure_list waiting_for_resolver_result_closures; /** resolver callback */ @@ -197,47 +193,55 @@ typedef struct client_channel_channel_data { /** when an lb_policy arrives, should we try to exit idle */ bool exit_idle_when_lb_policy_arrives; /** owning stack */ - grpc_channel_stack *owning_stack; + grpc_channel_stack* owning_stack; /** interested parties (owned) */ - grpc_pollset_set *interested_parties; + grpc_pollset_set* interested_parties; /* external_connectivity_watcher_list head is guarded by its own mutex, since * counts need to be grabbed immediately without polling on a cq */ gpr_mu external_connectivity_watcher_list_mu; - struct external_connectivity_watcher *external_connectivity_watcher_list_head; + struct external_connectivity_watcher* external_connectivity_watcher_list_head; /* the following properties are guarded by a mutex since API's require them to be instantaneously available */ gpr_mu info_mu; - char *info_lb_policy_name; + char* info_lb_policy_name; /** service config in JSON form */ - char *info_service_config_json; + char* info_service_config_json; } channel_data; +typedef struct { + channel_data* chand; + /** used as an identifier, don't dereference it because the LB policy may be + * non-existing when the callback is run */ + grpc_lb_policy* lb_policy; + grpc_closure closure; +} reresolution_request_args; + /** We create one watcher for each new lb_policy that is returned from a resolver, to watch for state changes from the lb_policy. When a state change is seen, we update the channel, and create a new watcher. */ typedef struct { - channel_data *chand; + channel_data* chand; grpc_closure on_changed; grpc_connectivity_state state; - grpc_lb_policy *lb_policy; + grpc_lb_policy* lb_policy; } lb_policy_connectivity_watcher; -static void watch_lb_policy_locked(grpc_exec_ctx *exec_ctx, channel_data *chand, - grpc_lb_policy *lb_policy, +static void watch_lb_policy_locked(grpc_exec_ctx* exec_ctx, channel_data* chand, + grpc_lb_policy* lb_policy, grpc_connectivity_state current_state); -static void set_channel_connectivity_state_locked(grpc_exec_ctx *exec_ctx, - channel_data *chand, +static void set_channel_connectivity_state_locked(grpc_exec_ctx* exec_ctx, + channel_data* chand, grpc_connectivity_state state, - grpc_error *error, - const char *reason) { + grpc_error* error, + const char* reason) { /* TODO: Improve failure handling: * - Make it possible for policies to return GRPC_CHANNEL_TRANSIENT_FAILURE. * - Hand over pending picks from old policies during the switch that happens * when resolver provides an update. */ - if (chand->lb_policy != NULL) { + if (chand->lb_policy != nullptr) { if (state == GRPC_CHANNEL_TRANSIENT_FAILURE) { /* cancel picks with wait_for_ready=false */ grpc_lb_policy_cancel_picks_locked( @@ -251,7 +255,7 @@ static void set_channel_connectivity_state_locked(grpc_exec_ctx *exec_ctx, GRPC_ERROR_REF(error)); } } - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p: setting connectivity state to %s", chand, grpc_connectivity_state_name(state)); } @@ -259,23 +263,16 @@ static void set_channel_connectivity_state_locked(grpc_exec_ctx *exec_ctx, reason); } -static void on_lb_policy_state_changed_locked(grpc_exec_ctx *exec_ctx, - void *arg, grpc_error *error) { - lb_policy_connectivity_watcher *w = (lb_policy_connectivity_watcher *)arg; - grpc_connectivity_state publish_state = w->state; +static void on_lb_policy_state_changed_locked(grpc_exec_ctx* exec_ctx, + void* arg, grpc_error* error) { + lb_policy_connectivity_watcher* w = (lb_policy_connectivity_watcher*)arg; /* check if the notification is for the latest policy */ if (w->lb_policy == w->chand->lb_policy) { - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p: lb_policy=%p state changed to %s", w->chand, w->lb_policy, grpc_connectivity_state_name(w->state)); } - if (publish_state == GRPC_CHANNEL_SHUTDOWN && w->chand->resolver != NULL) { - publish_state = GRPC_CHANNEL_TRANSIENT_FAILURE; - grpc_resolver_channel_saw_error_locked(exec_ctx, w->chand->resolver); - GRPC_LB_POLICY_UNREF(exec_ctx, w->chand->lb_policy, "channel"); - w->chand->lb_policy = NULL; - } - set_channel_connectivity_state_locked(exec_ctx, w->chand, publish_state, + set_channel_connectivity_state_locked(exec_ctx, w->chand, w->state, GRPC_ERROR_REF(error), "lb_changed"); if (w->state != GRPC_CHANNEL_SHUTDOWN) { watch_lb_policy_locked(exec_ctx, w->chand, w->lb_policy, w->state); @@ -285,11 +282,11 @@ static void on_lb_policy_state_changed_locked(grpc_exec_ctx *exec_ctx, gpr_free(w); } -static void watch_lb_policy_locked(grpc_exec_ctx *exec_ctx, channel_data *chand, - grpc_lb_policy *lb_policy, +static void watch_lb_policy_locked(grpc_exec_ctx* exec_ctx, channel_data* chand, + grpc_lb_policy* lb_policy, grpc_connectivity_state current_state) { - lb_policy_connectivity_watcher *w = - (lb_policy_connectivity_watcher *)gpr_malloc(sizeof(*w)); + lb_policy_connectivity_watcher* w = + (lb_policy_connectivity_watcher*)gpr_malloc(sizeof(*w)); GRPC_CHANNEL_STACK_REF(chand->owning_stack, "watch_lb_policy"); w->chand = chand; GRPC_CLOSURE_INIT(&w->on_changed, on_lb_policy_state_changed_locked, w, @@ -300,9 +297,9 @@ static void watch_lb_policy_locked(grpc_exec_ctx *exec_ctx, channel_data *chand, &w->on_changed); } -static void start_resolving_locked(grpc_exec_ctx *exec_ctx, - channel_data *chand) { - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { +static void start_resolving_locked(grpc_exec_ctx* exec_ctx, + channel_data* chand) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p: starting name resolution", chand); } GPR_ASSERT(!chand->started_resolving); @@ -313,21 +310,21 @@ static void start_resolving_locked(grpc_exec_ctx *exec_ctx, } typedef struct { - char *server_name; - grpc_server_retry_throttle_data *retry_throttle_data; + char* server_name; + grpc_server_retry_throttle_data* retry_throttle_data; } service_config_parsing_state; -static void parse_retry_throttle_params(const grpc_json *field, void *arg) { - service_config_parsing_state *parsing_state = - (service_config_parsing_state *)arg; +static void parse_retry_throttle_params(const grpc_json* field, void* arg) { + service_config_parsing_state* parsing_state = + (service_config_parsing_state*)arg; if (strcmp(field->key, "retryThrottling") == 0) { - if (parsing_state->retry_throttle_data != NULL) return; // Duplicate. + if (parsing_state->retry_throttle_data != nullptr) return; // Duplicate. if (field->type != GRPC_JSON_OBJECT) return; int max_milli_tokens = 0; int milli_token_ratio = 0; - for (grpc_json *sub_field = field->child; sub_field != NULL; + for (grpc_json* sub_field = field->child; sub_field != nullptr; sub_field = sub_field->next) { - if (sub_field->key == NULL) return; + if (sub_field->key == nullptr) return; if (strcmp(sub_field->key, "maxTokens") == 0) { if (max_milli_tokens != 0) return; // Duplicate. if (sub_field->type != GRPC_JSON_NUMBER) return; @@ -341,8 +338,8 @@ static void parse_retry_throttle_params(const grpc_json *field, void *arg) { size_t whole_len = strlen(sub_field->value); uint32_t multiplier = 1; uint32_t decimal_value = 0; - const char *decimal_point = strchr(sub_field->value, '.'); - if (decimal_point != NULL) { + const char* decimal_point = strchr(sub_field->value, '.'); + if (decimal_point != nullptr) { whole_len = (size_t)(decimal_point - sub_field->value); multiplier = 1000; size_t decimal_len = strlen(decimal_point + 1); @@ -372,119 +369,155 @@ static void parse_retry_throttle_params(const grpc_json *field, void *arg) { } } -static void on_resolver_result_changed_locked(grpc_exec_ctx *exec_ctx, - void *arg, grpc_error *error) { - channel_data *chand = (channel_data *)arg; - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { +static void request_reresolution_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + reresolution_request_args* args = (reresolution_request_args*)arg; + channel_data* chand = args->chand; + // If this invocation is for a stale LB policy, treat it as an LB shutdown + // signal. + if (args->lb_policy != chand->lb_policy || error != GRPC_ERROR_NONE || + chand->resolver == nullptr) { + GRPC_CHANNEL_STACK_UNREF(exec_ctx, chand->owning_stack, "re-resolution"); + gpr_free(args); + return; + } + if (grpc_client_channel_trace.enabled()) { + gpr_log(GPR_DEBUG, "chand=%p: started name re-resolving", chand); + } + grpc_resolver_channel_saw_error_locked(exec_ctx, chand->resolver); + // Give back the closure to the LB policy. + grpc_lb_policy_set_reresolve_closure_locked(exec_ctx, chand->lb_policy, + &args->closure); +} + +static void on_resolver_result_changed_locked(grpc_exec_ctx* exec_ctx, + void* arg, grpc_error* error) { + channel_data* chand = (channel_data*)arg; + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p: got resolver result: error=%s", chand, grpc_error_string(error)); } // Extract the following fields from the resolver result, if non-NULL. bool lb_policy_updated = false; - char *lb_policy_name_dup = NULL; + char* lb_policy_name_dup = nullptr; bool lb_policy_name_changed = false; - grpc_lb_policy *new_lb_policy = NULL; - char *service_config_json = NULL; - grpc_server_retry_throttle_data *retry_throttle_data = NULL; - grpc_slice_hash_table *method_params_table = NULL; - if (chand->resolver_result != NULL) { - // Find LB policy name. - const char *lb_policy_name = NULL; - const grpc_arg *channel_arg = - grpc_channel_args_find(chand->resolver_result, GRPC_ARG_LB_POLICY_NAME); - if (channel_arg != NULL) { - GPR_ASSERT(channel_arg->type == GRPC_ARG_STRING); - lb_policy_name = channel_arg->value.string; - } - // Special case: If at least one balancer address is present, we use - // the grpclb policy, regardless of what the resolver actually specified. - channel_arg = - grpc_channel_args_find(chand->resolver_result, GRPC_ARG_LB_ADDRESSES); - if (channel_arg != NULL && channel_arg->type == GRPC_ARG_POINTER) { - grpc_lb_addresses *addresses = - (grpc_lb_addresses *)channel_arg->value.pointer.p; - bool found_balancer_address = false; - for (size_t i = 0; i < addresses->num_addresses; ++i) { - if (addresses->addresses[i].is_balancer) { - found_balancer_address = true; - break; + grpc_lb_policy* new_lb_policy = nullptr; + char* service_config_json = nullptr; + grpc_server_retry_throttle_data* retry_throttle_data = nullptr; + grpc_slice_hash_table* method_params_table = nullptr; + if (chand->resolver_result != nullptr) { + if (chand->resolver != nullptr) { + // Find LB policy name. + const char* lb_policy_name = nullptr; + const grpc_arg* channel_arg = grpc_channel_args_find( + chand->resolver_result, GRPC_ARG_LB_POLICY_NAME); + if (channel_arg != nullptr) { + GPR_ASSERT(channel_arg->type == GRPC_ARG_STRING); + lb_policy_name = channel_arg->value.string; + } + // Special case: If at least one balancer address is present, we use + // the grpclb policy, regardless of what the resolver actually specified. + channel_arg = + grpc_channel_args_find(chand->resolver_result, GRPC_ARG_LB_ADDRESSES); + if (channel_arg != nullptr && channel_arg->type == GRPC_ARG_POINTER) { + grpc_lb_addresses* addresses = + (grpc_lb_addresses*)channel_arg->value.pointer.p; + bool found_balancer_address = false; + for (size_t i = 0; i < addresses->num_addresses; ++i) { + if (addresses->addresses[i].is_balancer) { + found_balancer_address = true; + break; + } + } + if (found_balancer_address) { + if (lb_policy_name != nullptr && + strcmp(lb_policy_name, "grpclb") != 0) { + gpr_log(GPR_INFO, + "resolver requested LB policy %s but provided at least one " + "balancer address -- forcing use of grpclb LB policy", + lb_policy_name); + } + lb_policy_name = "grpclb"; } } - if (found_balancer_address) { - if (lb_policy_name != NULL && strcmp(lb_policy_name, "grpclb") != 0) { - gpr_log(GPR_INFO, - "resolver requested LB policy %s but provided at least one " - "balancer address -- forcing use of grpclb LB policy", + // Use pick_first if nothing was specified and we didn't select grpclb + // above. + if (lb_policy_name == nullptr) lb_policy_name = "pick_first"; + grpc_lb_policy_args lb_policy_args; + lb_policy_args.args = chand->resolver_result; + lb_policy_args.client_channel_factory = chand->client_channel_factory; + lb_policy_args.combiner = chand->combiner; + // Check to see if we're already using the right LB policy. + // Note: It's safe to use chand->info_lb_policy_name here without + // taking a lock on chand->info_mu, because this function is the + // only thing that modifies its value, and it can only be invoked + // once at any given time. + lb_policy_name_changed = + chand->info_lb_policy_name == nullptr || + gpr_stricmp(chand->info_lb_policy_name, lb_policy_name) != 0; + if (chand->lb_policy != nullptr && !lb_policy_name_changed) { + // Continue using the same LB policy. Update with new addresses. + lb_policy_updated = true; + grpc_lb_policy_update_locked(exec_ctx, chand->lb_policy, + &lb_policy_args); + } else { + // Instantiate new LB policy. + new_lb_policy = + grpc_lb_policy_create(exec_ctx, lb_policy_name, &lb_policy_args); + if (new_lb_policy == nullptr) { + gpr_log(GPR_ERROR, "could not create LB policy \"%s\"", lb_policy_name); + } else { + reresolution_request_args* args = + (reresolution_request_args*)gpr_zalloc(sizeof(*args)); + args->chand = chand; + args->lb_policy = new_lb_policy; + GRPC_CLOSURE_INIT(&args->closure, request_reresolution_locked, args, + grpc_combiner_scheduler(chand->combiner)); + GRPC_CHANNEL_STACK_REF(chand->owning_stack, "re-resolution"); + grpc_lb_policy_set_reresolve_closure_locked(exec_ctx, new_lb_policy, + &args->closure); } - lb_policy_name = "grpclb"; - } - } - // Use pick_first if nothing was specified and we didn't select grpclb - // above. - if (lb_policy_name == NULL) lb_policy_name = "pick_first"; - grpc_lb_policy_args lb_policy_args; - lb_policy_args.args = chand->resolver_result; - lb_policy_args.client_channel_factory = chand->client_channel_factory; - lb_policy_args.combiner = chand->combiner; - // Check to see if we're already using the right LB policy. - // Note: It's safe to use chand->info_lb_policy_name here without - // taking a lock on chand->info_mu, because this function is the - // only thing that modifies its value, and it can only be invoked - // once at any given time. - lb_policy_name_changed = - chand->info_lb_policy_name == NULL || - strcmp(chand->info_lb_policy_name, lb_policy_name) != 0; - if (chand->lb_policy != NULL && !lb_policy_name_changed) { - // Continue using the same LB policy. Update with new addresses. - lb_policy_updated = true; - grpc_lb_policy_update_locked(exec_ctx, chand->lb_policy, &lb_policy_args); - } else { - // Instantiate new LB policy. - new_lb_policy = - grpc_lb_policy_create(exec_ctx, lb_policy_name, &lb_policy_args); - if (new_lb_policy == NULL) { - gpr_log(GPR_ERROR, "could not create LB policy \"%s\"", lb_policy_name); } - } - // Find service config. - channel_arg = - grpc_channel_args_find(chand->resolver_result, GRPC_ARG_SERVICE_CONFIG); - if (channel_arg != NULL) { - GPR_ASSERT(channel_arg->type == GRPC_ARG_STRING); - service_config_json = gpr_strdup(channel_arg->value.string); - grpc_service_config *service_config = - grpc_service_config_create(service_config_json); - if (service_config != NULL) { - channel_arg = - grpc_channel_args_find(chand->resolver_result, GRPC_ARG_SERVER_URI); - GPR_ASSERT(channel_arg != NULL); + // Find service config. + channel_arg = grpc_channel_args_find(chand->resolver_result, + GRPC_ARG_SERVICE_CONFIG); + if (channel_arg != nullptr) { GPR_ASSERT(channel_arg->type == GRPC_ARG_STRING); - grpc_uri *uri = - grpc_uri_parse(exec_ctx, channel_arg->value.string, true); - GPR_ASSERT(uri->path[0] != '\0'); - service_config_parsing_state parsing_state; - memset(&parsing_state, 0, sizeof(parsing_state)); - parsing_state.server_name = - uri->path[0] == '/' ? uri->path + 1 : uri->path; - grpc_service_config_parse_global_params( - service_config, parse_retry_throttle_params, &parsing_state); - grpc_uri_destroy(uri); - retry_throttle_data = parsing_state.retry_throttle_data; - method_params_table = grpc_service_config_create_method_config_table( - exec_ctx, service_config, method_parameters_create_from_json, - method_parameters_free); - grpc_service_config_destroy(service_config); + service_config_json = gpr_strdup(channel_arg->value.string); + grpc_service_config* service_config = + grpc_service_config_create(service_config_json); + if (service_config != nullptr) { + channel_arg = grpc_channel_args_find(chand->resolver_result, + GRPC_ARG_SERVER_URI); + GPR_ASSERT(channel_arg != nullptr); + GPR_ASSERT(channel_arg->type == GRPC_ARG_STRING); + grpc_uri* uri = + grpc_uri_parse(exec_ctx, channel_arg->value.string, true); + GPR_ASSERT(uri->path[0] != '\0'); + service_config_parsing_state parsing_state; + memset(&parsing_state, 0, sizeof(parsing_state)); + parsing_state.server_name = + uri->path[0] == '/' ? uri->path + 1 : uri->path; + grpc_service_config_parse_global_params( + service_config, parse_retry_throttle_params, &parsing_state); + grpc_uri_destroy(uri); + retry_throttle_data = parsing_state.retry_throttle_data; + method_params_table = grpc_service_config_create_method_config_table( + exec_ctx, service_config, method_parameters_create_from_json, + method_parameters_ref_wrapper, method_parameters_unref_wrapper); + grpc_service_config_destroy(service_config); + } } + // Before we clean up, save a copy of lb_policy_name, since it might + // be pointing to data inside chand->resolver_result. + // The copy will be saved in chand->lb_policy_name below. + lb_policy_name_dup = gpr_strdup(lb_policy_name); } - // Before we clean up, save a copy of lb_policy_name, since it might - // be pointing to data inside chand->resolver_result. - // The copy will be saved in chand->lb_policy_name below. - lb_policy_name_dup = gpr_strdup(lb_policy_name); grpc_channel_args_destroy(exec_ctx, chand->resolver_result); - chand->resolver_result = NULL; + chand->resolver_result = nullptr; } - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p: resolver result: lb_policy_name=\"%s\"%s, " "service_config=\"%s\"", @@ -497,35 +530,35 @@ static void on_resolver_result_changed_locked(grpc_exec_ctx *exec_ctx, // // First, swap out the data used by cc_get_channel_info(). gpr_mu_lock(&chand->info_mu); - if (lb_policy_name_dup != NULL) { + if (lb_policy_name_dup != nullptr) { gpr_free(chand->info_lb_policy_name); chand->info_lb_policy_name = lb_policy_name_dup; } - if (service_config_json != NULL) { + if (service_config_json != nullptr) { gpr_free(chand->info_service_config_json); chand->info_service_config_json = service_config_json; } gpr_mu_unlock(&chand->info_mu); // Swap out the retry throttle data. - if (chand->retry_throttle_data != NULL) { + if (chand->retry_throttle_data != nullptr) { grpc_server_retry_throttle_data_unref(chand->retry_throttle_data); } chand->retry_throttle_data = retry_throttle_data; // Swap out the method params table. - if (chand->method_params_table != NULL) { + if (chand->method_params_table != nullptr) { grpc_slice_hash_table_unref(exec_ctx, chand->method_params_table); } chand->method_params_table = method_params_table; // If we have a new LB policy or are shutting down (in which case - // new_lb_policy will be NULL), swap out the LB policy, unreffing the - // old one and removing its fds from chand->interested_parties. - // Note that we do NOT do this if either (a) we updated the existing - // LB policy above or (b) we failed to create the new LB policy (in - // which case we want to continue using the most recent one we had). - if (new_lb_policy != NULL || error != GRPC_ERROR_NONE || - chand->resolver == NULL) { - if (chand->lb_policy != NULL) { - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + // new_lb_policy will be NULL), swap out the LB policy, unreffing the old one + // and removing its fds from chand->interested_parties. Note that we do NOT do + // this if either (a) we updated the existing LB policy above or (b) we failed + // to create the new LB policy (in which case we want to continue using the + // most recent one we had). + if (new_lb_policy != nullptr || error != GRPC_ERROR_NONE || + chand->resolver == nullptr) { + if (chand->lb_policy != nullptr) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p: unreffing lb_policy=%p", chand, chand->lb_policy); } @@ -538,17 +571,17 @@ static void on_resolver_result_changed_locked(grpc_exec_ctx *exec_ctx, } // Now that we've swapped out the relevant fields of chand, check for // error or shutdown. - if (error != GRPC_ERROR_NONE || chand->resolver == NULL) { - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (error != GRPC_ERROR_NONE || chand->resolver == nullptr) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p: shutting down", chand); } - if (chand->resolver != NULL) { - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (chand->resolver != nullptr) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p: shutting down resolver", chand); } grpc_resolver_shutdown_locked(exec_ctx, chand->resolver); GRPC_RESOLVER_UNREF(exec_ctx, chand->resolver, "channel"); - chand->resolver = NULL; + chand->resolver = nullptr; } set_channel_connectivity_state_locked( exec_ctx, chand, GRPC_CHANNEL_SHUTDOWN, @@ -563,10 +596,10 @@ static void on_resolver_result_changed_locked(grpc_exec_ctx *exec_ctx, &chand->waiting_for_resolver_result_closures); } else { // Not shutting down. grpc_connectivity_state state = GRPC_CHANNEL_TRANSIENT_FAILURE; - grpc_error *state_error = + grpc_error* state_error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("No load balancing policy"); - if (new_lb_policy != NULL) { - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (new_lb_policy != nullptr) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p: initializing new LB policy", chand); } GRPC_ERROR_UNREF(state_error); @@ -595,53 +628,53 @@ static void on_resolver_result_changed_locked(grpc_exec_ctx *exec_ctx, } } -static void start_transport_op_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error_ignored) { - grpc_transport_op *op = (grpc_transport_op *)arg; - grpc_channel_element *elem = - (grpc_channel_element *)op->handler_private.extra_arg; - channel_data *chand = (channel_data *)elem->channel_data; +static void start_transport_op_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error_ignored) { + grpc_transport_op* op = (grpc_transport_op*)arg; + grpc_channel_element* elem = + (grpc_channel_element*)op->handler_private.extra_arg; + channel_data* chand = (channel_data*)elem->channel_data; - if (op->on_connectivity_state_change != NULL) { + if (op->on_connectivity_state_change != nullptr) { grpc_connectivity_state_notify_on_state_change( exec_ctx, &chand->state_tracker, op->connectivity_state, op->on_connectivity_state_change); - op->on_connectivity_state_change = NULL; - op->connectivity_state = NULL; + op->on_connectivity_state_change = nullptr; + op->connectivity_state = nullptr; } - if (op->send_ping != NULL) { - if (chand->lb_policy == NULL) { + if (op->send_ping != nullptr) { + if (chand->lb_policy == nullptr) { GRPC_CLOSURE_SCHED( exec_ctx, op->send_ping, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Ping with no load balancing")); } else { grpc_lb_policy_ping_one_locked(exec_ctx, chand->lb_policy, op->send_ping); - op->bind_pollset = NULL; + op->bind_pollset = nullptr; } - op->send_ping = NULL; + op->send_ping = nullptr; } if (op->disconnect_with_error != GRPC_ERROR_NONE) { - if (chand->resolver != NULL) { + if (chand->resolver != nullptr) { set_channel_connectivity_state_locked( exec_ctx, chand, GRPC_CHANNEL_SHUTDOWN, GRPC_ERROR_REF(op->disconnect_with_error), "disconnect"); grpc_resolver_shutdown_locked(exec_ctx, chand->resolver); GRPC_RESOLVER_UNREF(exec_ctx, chand->resolver, "channel"); - chand->resolver = NULL; + chand->resolver = nullptr; if (!chand->started_resolving) { grpc_closure_list_fail_all(&chand->waiting_for_resolver_result_closures, GRPC_ERROR_REF(op->disconnect_with_error)); GRPC_CLOSURE_LIST_SCHED(exec_ctx, &chand->waiting_for_resolver_result_closures); } - if (chand->lb_policy != NULL) { + if (chand->lb_policy != nullptr) { grpc_pollset_set_del_pollset_set(exec_ctx, chand->lb_policy->interested_parties, chand->interested_parties); GRPC_LB_POLICY_UNREF(exec_ctx, chand->lb_policy, "channel"); - chand->lb_policy = NULL; + chand->lb_policy = nullptr; } } GRPC_ERROR_UNREF(op->disconnect_with_error); @@ -651,13 +684,13 @@ static void start_transport_op_locked(grpc_exec_ctx *exec_ctx, void *arg, GRPC_CLOSURE_SCHED(exec_ctx, op->on_consumed, GRPC_ERROR_NONE); } -static void cc_start_transport_op(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_transport_op *op) { - channel_data *chand = (channel_data *)elem->channel_data; +static void cc_start_transport_op(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_transport_op* op) { + channel_data* chand = (channel_data*)elem->channel_data; GPR_ASSERT(op->set_accept_stream == false); - if (op->bind_pollset != NULL) { + if (op->bind_pollset != nullptr) { grpc_pollset_set_add_pollset(exec_ctx, chand->interested_parties, op->bind_pollset); } @@ -671,30 +704,30 @@ static void cc_start_transport_op(grpc_exec_ctx *exec_ctx, GRPC_ERROR_NONE); } -static void cc_get_channel_info(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - const grpc_channel_info *info) { - channel_data *chand = (channel_data *)elem->channel_data; +static void cc_get_channel_info(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + const grpc_channel_info* info) { + channel_data* chand = (channel_data*)elem->channel_data; gpr_mu_lock(&chand->info_mu); - if (info->lb_policy_name != NULL) { - *info->lb_policy_name = chand->info_lb_policy_name == NULL - ? NULL + if (info->lb_policy_name != nullptr) { + *info->lb_policy_name = chand->info_lb_policy_name == nullptr + ? nullptr : gpr_strdup(chand->info_lb_policy_name); } - if (info->service_config_json != NULL) { + if (info->service_config_json != nullptr) { *info->service_config_json = - chand->info_service_config_json == NULL - ? NULL + chand->info_service_config_json == nullptr + ? nullptr : gpr_strdup(chand->info_service_config_json); } gpr_mu_unlock(&chand->info_mu); } /* Constructor for channel_data */ -static grpc_error *cc_init_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_channel_element_args *args) { - channel_data *chand = (channel_data *)elem->channel_data; +static grpc_error* cc_init_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_channel_element_args* args) { + channel_data* chand = (channel_data*)elem->channel_data; GPR_ASSERT(args->is_last); GPR_ASSERT(elem->filter == &grpc_client_channel_filter); // Initialize data members. @@ -703,7 +736,7 @@ static grpc_error *cc_init_channel_elem(grpc_exec_ctx *exec_ctx, gpr_mu_init(&chand->external_connectivity_watcher_list_mu); gpr_mu_lock(&chand->external_connectivity_watcher_list_mu); - chand->external_connectivity_watcher_list_head = NULL; + chand->external_connectivity_watcher_list_head = nullptr; gpr_mu_unlock(&chand->external_connectivity_watcher_list_mu); chand->owning_stack = args->channel_stack; @@ -715,9 +748,9 @@ static grpc_error *cc_init_channel_elem(grpc_exec_ctx *exec_ctx, "client_channel"); grpc_client_channel_start_backup_polling(exec_ctx, chand->interested_parties); // Record client channel factory. - const grpc_arg *arg = grpc_channel_args_find(args->channel_args, + const grpc_arg* arg = grpc_channel_args_find(args->channel_args, GRPC_ARG_CLIENT_CHANNEL_FACTORY); - if (arg == NULL) { + if (arg == nullptr) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Missing client channel factory in args for client channel filter"); } @@ -726,12 +759,12 @@ static grpc_error *cc_init_channel_elem(grpc_exec_ctx *exec_ctx, "client channel factory arg must be a pointer"); } grpc_client_channel_factory_ref( - (grpc_client_channel_factory *)arg->value.pointer.p); + (grpc_client_channel_factory*)arg->value.pointer.p); chand->client_channel_factory = - (grpc_client_channel_factory *)arg->value.pointer.p; + (grpc_client_channel_factory*)arg->value.pointer.p; // Get server name to resolve, using proxy mapper if needed. arg = grpc_channel_args_find(args->channel_args, GRPC_ARG_SERVER_URI); - if (arg == NULL) { + if (arg == nullptr) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Missing server uri in args for client channel filter"); } @@ -739,18 +772,18 @@ static grpc_error *cc_init_channel_elem(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_CREATE_FROM_STATIC_STRING( "server uri arg must be a string"); } - char *proxy_name = NULL; - grpc_channel_args *new_args = NULL; + char* proxy_name = nullptr; + grpc_channel_args* new_args = nullptr; grpc_proxy_mappers_map_name(exec_ctx, arg->value.string, args->channel_args, &proxy_name, &new_args); // Instantiate resolver. chand->resolver = grpc_resolver_create( - exec_ctx, proxy_name != NULL ? proxy_name : arg->value.string, - new_args != NULL ? new_args : args->channel_args, + exec_ctx, proxy_name != nullptr ? proxy_name : arg->value.string, + new_args != nullptr ? new_args : args->channel_args, chand->interested_parties, chand->combiner); - if (proxy_name != NULL) gpr_free(proxy_name); - if (new_args != NULL) grpc_channel_args_destroy(exec_ctx, new_args); - if (chand->resolver == NULL) { + if (proxy_name != nullptr) gpr_free(proxy_name); + if (new_args != nullptr) grpc_channel_args_destroy(exec_ctx, new_args); + if (chand->resolver == nullptr) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("resolver creation failed"); } chand->deadline_checking_enabled = @@ -758,27 +791,28 @@ static grpc_error *cc_init_channel_elem(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static void shutdown_resolver_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_resolver *resolver = (grpc_resolver *)arg; +static void shutdown_resolver_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_resolver* resolver = (grpc_resolver*)arg; grpc_resolver_shutdown_locked(exec_ctx, resolver); GRPC_RESOLVER_UNREF(exec_ctx, resolver, "channel"); } /* Destructor for channel_data */ -static void cc_destroy_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem) { - channel_data *chand = (channel_data *)elem->channel_data; - if (chand->resolver != NULL) { +static void cc_destroy_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem) { + channel_data* chand = (channel_data*)elem->channel_data; + if (chand->resolver != nullptr) { GRPC_CLOSURE_SCHED( - exec_ctx, GRPC_CLOSURE_CREATE(shutdown_resolver_locked, chand->resolver, - grpc_combiner_scheduler(chand->combiner)), + exec_ctx, + GRPC_CLOSURE_CREATE(shutdown_resolver_locked, chand->resolver, + grpc_combiner_scheduler(chand->combiner)), GRPC_ERROR_NONE); } - if (chand->client_channel_factory != NULL) { + if (chand->client_channel_factory != nullptr) { grpc_client_channel_factory_unref(exec_ctx, chand->client_channel_factory); } - if (chand->lb_policy != NULL) { + if (chand->lb_policy != nullptr) { grpc_pollset_set_del_pollset_set(exec_ctx, chand->lb_policy->interested_parties, chand->interested_parties); @@ -786,10 +820,10 @@ static void cc_destroy_channel_elem(grpc_exec_ctx *exec_ctx, } gpr_free(chand->info_lb_policy_name); gpr_free(chand->info_service_config_json); - if (chand->retry_throttle_data != NULL) { + if (chand->retry_throttle_data != nullptr) { grpc_server_retry_throttle_data_unref(chand->retry_throttle_data); } - if (chand->method_params_table != NULL) { + if (chand->method_params_table != nullptr) { grpc_slice_hash_table_unref(exec_ctx, chand->method_params_table); } grpc_client_channel_stop_backup_polling(exec_ctx, chand->interested_parties); @@ -832,47 +866,47 @@ typedef struct client_channel_call_data { grpc_slice path; // Request path. gpr_timespec call_start_time; grpc_millis deadline; - gpr_arena *arena; - grpc_call_stack *owning_call; - grpc_call_combiner *call_combiner; + gpr_arena* arena; + grpc_call_stack* owning_call; + grpc_call_combiner* call_combiner; - grpc_server_retry_throttle_data *retry_throttle_data; - method_parameters *method_params; + grpc_server_retry_throttle_data* retry_throttle_data; + method_parameters* method_params; - grpc_subchannel_call *subchannel_call; - grpc_error *error; + grpc_subchannel_call* subchannel_call; + grpc_error* error; - grpc_lb_policy *lb_policy; // Holds ref while LB pick is pending. + grpc_lb_policy* lb_policy; // Holds ref while LB pick is pending. grpc_closure lb_pick_closure; grpc_closure lb_pick_cancel_closure; - grpc_connected_subchannel *connected_subchannel; + grpc_connected_subchannel* connected_subchannel; grpc_call_context_element subchannel_call_context[GRPC_CONTEXT_COUNT]; - grpc_polling_entity *pollent; + grpc_polling_entity* pollent; - grpc_transport_stream_op_batch *waiting_for_pick_batches[MAX_WAITING_BATCHES]; + grpc_transport_stream_op_batch* waiting_for_pick_batches[MAX_WAITING_BATCHES]; size_t waiting_for_pick_batches_count; grpc_closure handle_pending_batch_in_call_combiner[MAX_WAITING_BATCHES]; - grpc_transport_stream_op_batch *initial_metadata_batch; + grpc_transport_stream_op_batch* initial_metadata_batch; grpc_linked_mdelem lb_token_mdelem; grpc_closure on_complete; - grpc_closure *original_on_complete; + grpc_closure* original_on_complete; } call_data; -grpc_subchannel_call *grpc_client_channel_get_subchannel_call( - grpc_call_element *elem) { - call_data *calld = (call_data *)elem->call_data; +grpc_subchannel_call* grpc_client_channel_get_subchannel_call( + grpc_call_element* elem) { + call_data* calld = (call_data*)elem->call_data; return calld->subchannel_call; } // This is called via the call combiner, so access to calld is synchronized. static void waiting_for_pick_batches_add( - call_data *calld, grpc_transport_stream_op_batch *batch) { + call_data* calld, grpc_transport_stream_op_batch* batch) { if (batch->send_initial_metadata) { - GPR_ASSERT(calld->initial_metadata_batch == NULL); + GPR_ASSERT(calld->initial_metadata_batch == nullptr); calld->initial_metadata_batch = batch; } else { GPR_ASSERT(calld->waiting_for_pick_batches_count < MAX_WAITING_BATCHES); @@ -882,9 +916,9 @@ static void waiting_for_pick_batches_add( } // This is called via the call combiner, so access to calld is synchronized. -static void fail_pending_batch_in_call_combiner(grpc_exec_ctx *exec_ctx, - void *arg, grpc_error *error) { - call_data *calld = (call_data *)arg; +static void fail_pending_batch_in_call_combiner(grpc_exec_ctx* exec_ctx, + void* arg, grpc_error* error) { + call_data* calld = (call_data*)arg; if (calld->waiting_for_pick_batches_count > 0) { --calld->waiting_for_pick_batches_count; grpc_transport_stream_op_batch_finish_with_failure( @@ -895,11 +929,11 @@ static void fail_pending_batch_in_call_combiner(grpc_exec_ctx *exec_ctx, } // This is called via the call combiner, so access to calld is synchronized. -static void waiting_for_pick_batches_fail(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_error *error) { - call_data *calld = (call_data *)elem->call_data; - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { +static void waiting_for_pick_batches_fail(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_error* error) { + call_data* calld = (call_data*)elem->call_data; + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: failing %" PRIuPTR " pending batches: %s", elem->channel_data, calld, calld->waiting_for_pick_batches_count, @@ -914,7 +948,7 @@ static void waiting_for_pick_batches_fail(grpc_exec_ctx *exec_ctx, GRPC_ERROR_REF(error), "waiting_for_pick_batches_fail"); } - if (calld->initial_metadata_batch != NULL) { + if (calld->initial_metadata_batch != nullptr) { grpc_transport_stream_op_batch_finish_with_failure( exec_ctx, calld->initial_metadata_batch, GRPC_ERROR_REF(error), calld->call_combiner); @@ -926,9 +960,9 @@ static void waiting_for_pick_batches_fail(grpc_exec_ctx *exec_ctx, } // This is called via the call combiner, so access to calld is synchronized. -static void run_pending_batch_in_call_combiner(grpc_exec_ctx *exec_ctx, - void *arg, grpc_error *ignored) { - call_data *calld = (call_data *)arg; +static void run_pending_batch_in_call_combiner(grpc_exec_ctx* exec_ctx, + void* arg, grpc_error* ignored) { + call_data* calld = (call_data*)arg; if (calld->waiting_for_pick_batches_count > 0) { --calld->waiting_for_pick_batches_count; grpc_subchannel_call_process_op( @@ -938,13 +972,14 @@ static void run_pending_batch_in_call_combiner(grpc_exec_ctx *exec_ctx, } // This is called via the call combiner, so access to calld is synchronized. -static void waiting_for_pick_batches_resume(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem) { - channel_data *chand = (channel_data *)elem->channel_data; - call_data *calld = (call_data *)elem->call_data; - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { - gpr_log(GPR_DEBUG, "chand=%p calld=%p: sending %" PRIuPTR - " pending batches to subchannel_call=%p", +static void waiting_for_pick_batches_resume(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem) { + channel_data* chand = (channel_data*)elem->channel_data; + call_data* calld = (call_data*)elem->call_data; + if (grpc_client_channel_trace.enabled()) { + gpr_log(GPR_DEBUG, + "chand=%p calld=%p: sending %" PRIuPTR + " pending batches to subchannel_call=%p", chand, calld, calld->waiting_for_pick_batches_count, calld->subchannel_call); } @@ -957,29 +992,29 @@ static void waiting_for_pick_batches_resume(grpc_exec_ctx *exec_ctx, GRPC_ERROR_NONE, "waiting_for_pick_batches_resume"); } - GPR_ASSERT(calld->initial_metadata_batch != NULL); + GPR_ASSERT(calld->initial_metadata_batch != nullptr); grpc_subchannel_call_process_op(exec_ctx, calld->subchannel_call, calld->initial_metadata_batch); } // Applies service config to the call. Must be invoked once we know // that the resolver has returned results to the channel. -static void apply_service_config_to_call_locked(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem) { - channel_data *chand = (channel_data *)elem->channel_data; - call_data *calld = (call_data *)elem->call_data; - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { +static void apply_service_config_to_call_locked(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem) { + channel_data* chand = (channel_data*)elem->channel_data; + call_data* calld = (call_data*)elem->call_data; + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: applying service config to call", chand, calld); } - if (chand->retry_throttle_data != NULL) { + if (chand->retry_throttle_data != nullptr) { calld->retry_throttle_data = grpc_server_retry_throttle_data_ref(chand->retry_throttle_data); } - if (chand->method_params_table != NULL) { - calld->method_params = (method_parameters *)grpc_method_config_table_get( + if (chand->method_params_table != nullptr) { + calld->method_params = (method_parameters*)grpc_method_config_table_get( exec_ctx, chand->method_params_table, calld->path); - if (calld->method_params != NULL) { + if (calld->method_params != nullptr) { method_parameters_ref(calld->method_params); // If the deadline from the service config is shorter than the one // from the client API, reset the deadline timer. @@ -997,11 +1032,11 @@ static void apply_service_config_to_call_locked(grpc_exec_ctx *exec_ctx, } } -static void create_subchannel_call_locked(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_error *error) { - channel_data *chand = (channel_data *)elem->channel_data; - call_data *calld = (call_data *)elem->call_data; +static void create_subchannel_call_locked(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_error* error) { + channel_data* chand = (channel_data*)elem->channel_data; + call_data* calld = (call_data*)elem->call_data; const grpc_connected_subchannel_call_args call_args = { calld->pollent, // pollent calld->path, // path @@ -1011,10 +1046,10 @@ static void create_subchannel_call_locked(grpc_exec_ctx *exec_ctx, calld->subchannel_call_context, // context calld->call_combiner // call_combiner }; - grpc_error *new_error = grpc_connected_subchannel_create_call( + grpc_error* new_error = grpc_connected_subchannel_create_call( exec_ctx, calld->connected_subchannel, &call_args, &calld->subchannel_call); - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: create subchannel_call=%p: error=%s", chand, calld, calld->subchannel_call, grpc_error_string(new_error)); } @@ -1028,11 +1063,11 @@ static void create_subchannel_call_locked(grpc_exec_ctx *exec_ctx, } // Invoked when a pick is completed, on both success or failure. -static void pick_done_locked(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_error *error) { - call_data *calld = (call_data *)elem->call_data; - channel_data *chand = (channel_data *)elem->channel_data; - if (calld->connected_subchannel == NULL) { +static void pick_done_locked(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_error* error) { + call_data* calld = (call_data*)elem->call_data; + channel_data* chand = (channel_data*)elem->channel_data; + if (calld->connected_subchannel == nullptr) { // Failed to create subchannel. GRPC_ERROR_UNREF(calld->error); calld->error = error == GRPC_ERROR_NONE @@ -1040,7 +1075,7 @@ static void pick_done_locked(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, "Call dropped by load balancing policy") : GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Failed to create subchannel", &error, 1); - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: failed to create subchannel: error=%s", chand, calld, grpc_error_string(calld->error)); @@ -1057,10 +1092,10 @@ static void pick_done_locked(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, // either (a) the pick was deferred pending a resolver result or (b) the // pick was done asynchronously. Removes the call's polling entity from // chand->interested_parties before invoking pick_done_locked(). -static void async_pick_done_locked(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, grpc_error *error) { - channel_data *chand = (channel_data *)elem->channel_data; - call_data *calld = (call_data *)elem->call_data; +static void async_pick_done_locked(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, grpc_error* error) { + channel_data* chand = (channel_data*)elem->channel_data; + call_data* calld = (call_data*)elem->call_data; grpc_polling_entity_del_from_pollset_set(exec_ctx, calld->pollent, chand->interested_parties); pick_done_locked(exec_ctx, elem, error); @@ -1068,13 +1103,13 @@ static void async_pick_done_locked(grpc_exec_ctx *exec_ctx, // Note: This runs under the client_channel combiner, but will NOT be // holding the call combiner. -static void pick_callback_cancel_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_call_element *elem = (grpc_call_element *)arg; - channel_data *chand = (channel_data *)elem->channel_data; - call_data *calld = (call_data *)elem->call_data; - if (calld->lb_policy != NULL) { - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { +static void pick_callback_cancel_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_call_element* elem = (grpc_call_element*)arg; + channel_data* chand = (channel_data*)elem->channel_data; + call_data* calld = (call_data*)elem->call_data; + if (calld->lb_policy != nullptr) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: cancelling pick from LB policy %p", chand, calld, calld->lb_policy); } @@ -1087,29 +1122,29 @@ static void pick_callback_cancel_locked(grpc_exec_ctx *exec_ctx, void *arg, // Callback invoked by grpc_lb_policy_pick_locked() for async picks. // Unrefs the LB policy and invokes async_pick_done_locked(). -static void pick_callback_done_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_call_element *elem = (grpc_call_element *)arg; - channel_data *chand = (channel_data *)elem->channel_data; - call_data *calld = (call_data *)elem->call_data; - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { +static void pick_callback_done_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_call_element* elem = (grpc_call_element*)arg; + channel_data* chand = (channel_data*)elem->channel_data; + call_data* calld = (call_data*)elem->call_data; + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: pick completed asynchronously", chand, calld); } - GPR_ASSERT(calld->lb_policy != NULL); + GPR_ASSERT(calld->lb_policy != nullptr); GRPC_LB_POLICY_UNREF(exec_ctx, calld->lb_policy, "pick_subchannel"); - calld->lb_policy = NULL; + calld->lb_policy = nullptr; async_pick_done_locked(exec_ctx, elem, GRPC_ERROR_REF(error)); } // Takes a ref to chand->lb_policy and calls grpc_lb_policy_pick_locked(). // If the pick was completed synchronously, unrefs the LB policy and // returns true. -static bool pick_callback_start_locked(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem) { - channel_data *chand = (channel_data *)elem->channel_data; - call_data *calld = (call_data *)elem->call_data; - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { +static bool pick_callback_start_locked(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem) { + channel_data* chand = (channel_data*)elem->channel_data; + call_data* calld = (call_data*)elem->call_data; + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: starting pick on lb_policy=%p", chand, calld, chand->lb_policy); } @@ -1124,7 +1159,7 @@ static bool pick_callback_start_locked(grpc_exec_ctx *exec_ctx, initial_metadata_flags & GRPC_INITIAL_METADATA_WAIT_FOR_READY_EXPLICITLY_SET; const bool wait_for_ready_set_from_service_config = - calld->method_params != NULL && + calld->method_params != nullptr && calld->method_params->wait_for_ready != WAIT_FOR_READY_UNSET; if (!wait_for_ready_set_from_api && wait_for_ready_set_from_service_config) { if (calld->method_params->wait_for_ready == WAIT_FOR_READY_TRUE) { @@ -1144,15 +1179,15 @@ static bool pick_callback_start_locked(grpc_exec_ctx *exec_ctx, grpc_combiner_scheduler(chand->combiner)); const bool pick_done = grpc_lb_policy_pick_locked( exec_ctx, chand->lb_policy, &inputs, &calld->connected_subchannel, - calld->subchannel_call_context, NULL, &calld->lb_pick_closure); + calld->subchannel_call_context, nullptr, &calld->lb_pick_closure); if (pick_done) { /* synchronous grpc_lb_policy_pick call. Unref the LB policy. */ - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: pick completed synchronously", chand, calld); } GRPC_LB_POLICY_UNREF(exec_ctx, calld->lb_policy, "pick_subchannel"); - calld->lb_policy = NULL; + calld->lb_policy = nullptr; } else { GRPC_CALL_STACK_REF(calld->owning_call, "pick_callback_cancel"); grpc_call_combiner_set_notify_on_cancel( @@ -1165,7 +1200,7 @@ static bool pick_callback_start_locked(grpc_exec_ctx *exec_ctx, } typedef struct { - grpc_call_element *elem; + grpc_call_element* elem; bool finished; grpc_closure closure; grpc_closure cancel_closure; @@ -1173,11 +1208,10 @@ typedef struct { // Note: This runs under the client_channel combiner, but will NOT be // holding the call combiner. -static void pick_after_resolver_result_cancel_locked(grpc_exec_ctx *exec_ctx, - void *arg, - grpc_error *error) { - pick_after_resolver_result_args *args = - (pick_after_resolver_result_args *)arg; +static void pick_after_resolver_result_cancel_locked(grpc_exec_ctx* exec_ctx, + void* arg, + grpc_error* error) { + pick_after_resolver_result_args* args = (pick_after_resolver_result_args*)arg; if (args->finished) { gpr_free(args); return; @@ -1190,10 +1224,10 @@ static void pick_after_resolver_result_cancel_locked(grpc_exec_ctx *exec_ctx, // is called, it will be a no-op. We also immediately invoke // async_pick_done_locked() to propagate the error back to the caller. args->finished = true; - grpc_call_element *elem = args->elem; - channel_data *chand = (channel_data *)elem->channel_data; - call_data *calld = (call_data *)elem->call_data; - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + grpc_call_element* elem = args->elem; + channel_data* chand = (channel_data*)elem->channel_data; + call_data* calld = (call_data*)elem->call_data; + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: cancelling pick waiting for resolver result", chand, calld); @@ -1208,34 +1242,33 @@ static void pick_after_resolver_result_cancel_locked(grpc_exec_ctx *exec_ctx, "Pick cancelled", &error, 1)); } -static void pick_after_resolver_result_start_locked(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem); +static void pick_after_resolver_result_start_locked(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem); -static void pick_after_resolver_result_done_locked(grpc_exec_ctx *exec_ctx, - void *arg, - grpc_error *error) { - pick_after_resolver_result_args *args = - (pick_after_resolver_result_args *)arg; +static void pick_after_resolver_result_done_locked(grpc_exec_ctx* exec_ctx, + void* arg, + grpc_error* error) { + pick_after_resolver_result_args* args = (pick_after_resolver_result_args*)arg; if (args->finished) { /* cancelled, do nothing */ - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "call cancelled before resolver result"); } gpr_free(args); return; } args->finished = true; - grpc_call_element *elem = args->elem; - channel_data *chand = (channel_data *)elem->channel_data; - call_data *calld = (call_data *)elem->call_data; + grpc_call_element* elem = args->elem; + channel_data* chand = (channel_data*)elem->channel_data; + call_data* calld = (call_data*)elem->call_data; if (error != GRPC_ERROR_NONE) { - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: resolver failed to return data", chand, calld); } async_pick_done_locked(exec_ctx, elem, GRPC_ERROR_REF(error)); - } else if (chand->lb_policy != NULL) { - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + } else if (chand->lb_policy != nullptr) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: resolver returned, doing pick", chand, calld); } @@ -1255,9 +1288,9 @@ static void pick_after_resolver_result_done_locked(grpc_exec_ctx *exec_ctx, // removed in https://github.com/grpc/grpc/pull/12297. Need to figure // out what is actually causing this to occur and then figure out the // right way to deal with it. - else if (chand->resolver != NULL) { + else if (chand->resolver != nullptr) { // No LB policy, so try again. - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: resolver returned but no LB policy, " "trying again", @@ -1265,7 +1298,7 @@ static void pick_after_resolver_result_done_locked(grpc_exec_ctx *exec_ctx, } pick_after_resolver_result_start_locked(exec_ctx, elem); } else { - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: resolver disconnected", chand, calld); } @@ -1274,17 +1307,17 @@ static void pick_after_resolver_result_done_locked(grpc_exec_ctx *exec_ctx, } } -static void pick_after_resolver_result_start_locked(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem) { - channel_data *chand = (channel_data *)elem->channel_data; - call_data *calld = (call_data *)elem->call_data; - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { +static void pick_after_resolver_result_start_locked(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem) { + channel_data* chand = (channel_data*)elem->channel_data; + call_data* calld = (call_data*)elem->call_data; + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: deferring pick pending resolver result", chand, calld); } - pick_after_resolver_result_args *args = - (pick_after_resolver_result_args *)gpr_zalloc(sizeof(*args)); + pick_after_resolver_result_args* args = + (pick_after_resolver_result_args*)gpr_zalloc(sizeof(*args)); args->elem = elem; GRPC_CLOSURE_INIT(&args->closure, pick_after_resolver_result_done_locked, args, grpc_combiner_scheduler(chand->combiner)); @@ -1297,13 +1330,13 @@ static void pick_after_resolver_result_start_locked(grpc_exec_ctx *exec_ctx, grpc_combiner_scheduler(chand->combiner))); } -static void start_pick_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *ignored) { - grpc_call_element *elem = (grpc_call_element *)arg; - call_data *calld = (call_data *)elem->call_data; - channel_data *chand = (channel_data *)elem->channel_data; - GPR_ASSERT(calld->connected_subchannel == NULL); - if (chand->lb_policy != NULL) { +static void start_pick_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* ignored) { + grpc_call_element* elem = (grpc_call_element*)arg; + call_data* calld = (call_data*)elem->call_data; + channel_data* chand = (channel_data*)elem->channel_data; + GPR_ASSERT(calld->connected_subchannel == nullptr); + if (chand->lb_policy != nullptr) { // We already have an LB policy, so ask it for a pick. if (pick_callback_start_locked(exec_ctx, elem)) { // Pick completed synchronously. @@ -1312,7 +1345,7 @@ static void start_pick_locked(grpc_exec_ctx *exec_ctx, void *arg, } } else { // We do not yet have an LB policy, so wait for a resolver result. - if (chand->resolver == NULL) { + if (chand->resolver == nullptr) { pick_done_locked(exec_ctx, elem, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Disconnected")); return; @@ -1331,10 +1364,10 @@ static void start_pick_locked(grpc_exec_ctx *exec_ctx, void *arg, chand->interested_parties); } -static void on_complete(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { - grpc_call_element *elem = (grpc_call_element *)arg; - call_data *calld = (call_data *)elem->call_data; - if (calld->retry_throttle_data != NULL) { +static void on_complete(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { + grpc_call_element* elem = (grpc_call_element*)arg; + call_data* calld = (call_data*)elem->call_data; + if (calld->retry_throttle_data != nullptr) { if (error == GRPC_ERROR_NONE) { grpc_server_retry_throttle_data_record_success( calld->retry_throttle_data); @@ -1352,10 +1385,10 @@ static void on_complete(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { } static void cc_start_transport_stream_op_batch( - grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_transport_stream_op_batch *batch) { - call_data *calld = (call_data *)elem->call_data; - channel_data *chand = (channel_data *)elem->channel_data; + grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_transport_stream_op_batch* batch) { + call_data* calld = (call_data*)elem->call_data; + channel_data* chand = (channel_data*)elem->channel_data; if (chand->deadline_checking_enabled) { grpc_deadline_state_client_start_transport_stream_op_batch(exec_ctx, elem, batch); @@ -1363,7 +1396,7 @@ static void cc_start_transport_stream_op_batch( GPR_TIMER_BEGIN("cc_start_transport_stream_op_batch", 0); // If we've previously been cancelled, immediately fail any new batches. if (calld->error != GRPC_ERROR_NONE) { - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: failing batch with error: %s", chand, calld, grpc_error_string(calld->error)); } @@ -1379,13 +1412,13 @@ static void cc_start_transport_stream_op_batch( // error to the caller when the first batch does get passed down. GRPC_ERROR_UNREF(calld->error); calld->error = GRPC_ERROR_REF(batch->payload->cancel_stream.cancel_error); - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: recording cancel_error=%s", chand, calld, grpc_error_string(calld->error)); } // If we have a subchannel call, send the cancellation batch down. // Otherwise, fail all pending batches. - if (calld->subchannel_call != NULL) { + if (calld->subchannel_call != nullptr) { grpc_subchannel_call_process_op(exec_ctx, calld->subchannel_call, batch); } else { waiting_for_pick_batches_add(calld, batch); @@ -1397,7 +1430,7 @@ static void cc_start_transport_stream_op_batch( // Intercept on_complete for recv_trailing_metadata so that we can // check retry throttle status. if (batch->recv_trailing_metadata) { - GPR_ASSERT(batch->on_complete != NULL); + GPR_ASSERT(batch->on_complete != nullptr); calld->original_on_complete = batch->on_complete; GRPC_CLOSURE_INIT(&calld->on_complete, on_complete, elem, grpc_schedule_on_exec_ctx); @@ -1407,8 +1440,8 @@ static void cc_start_transport_stream_op_batch( // Note that once we have completed the pick, we do not need to enter // the channel combiner, which is more efficient (especially for // streaming calls). - if (calld->subchannel_call != NULL) { - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (calld->subchannel_call != nullptr) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: sending batch to subchannel_call=%p", chand, calld, calld->subchannel_call); @@ -1422,7 +1455,7 @@ static void cc_start_transport_stream_op_batch( // For batches containing a send_initial_metadata op, enter the channel // combiner to start a pick. if (batch->send_initial_metadata) { - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: entering client_channel combiner", chand, calld); } @@ -1433,7 +1466,7 @@ static void cc_start_transport_stream_op_batch( GRPC_ERROR_NONE); } else { // For all other batches, release the call combiner. - if (GRPC_TRACER_ON(grpc_client_channel_trace)) { + if (grpc_client_channel_trace.enabled()) { gpr_log(GPR_DEBUG, "chand=%p calld=%p: saved batch, yeilding call combiner", chand, calld); @@ -1446,11 +1479,11 @@ done: } /* Constructor for call_data */ -static grpc_error *cc_init_call_elem(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - const grpc_call_element_args *args) { - call_data *calld = (call_data *)elem->call_data; - channel_data *chand = (channel_data *)elem->channel_data; +static grpc_error* cc_init_call_elem(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + const grpc_call_element_args* args) { + call_data* calld = (call_data*)elem->call_data; + channel_data* chand = (channel_data*)elem->channel_data; // Initialize data members. calld->path = grpc_slice_ref_internal(args->path); calld->call_start_time = args->start_time; @@ -1466,35 +1499,35 @@ static grpc_error *cc_init_call_elem(grpc_exec_ctx *exec_ctx, } /* Destructor for call_data */ -static void cc_destroy_call_elem(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - const grpc_call_final_info *final_info, - grpc_closure *then_schedule_closure) { - call_data *calld = (call_data *)elem->call_data; - channel_data *chand = (channel_data *)elem->channel_data; +static void cc_destroy_call_elem(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + const grpc_call_final_info* final_info, + grpc_closure* then_schedule_closure) { + call_data* calld = (call_data*)elem->call_data; + channel_data* chand = (channel_data*)elem->channel_data; if (chand->deadline_checking_enabled) { grpc_deadline_state_destroy(exec_ctx, elem); } grpc_slice_unref_internal(exec_ctx, calld->path); - if (calld->method_params != NULL) { + if (calld->method_params != nullptr) { method_parameters_unref(calld->method_params); } GRPC_ERROR_UNREF(calld->error); - if (calld->subchannel_call != NULL) { + if (calld->subchannel_call != nullptr) { grpc_subchannel_call_set_cleanup_closure(calld->subchannel_call, then_schedule_closure); - then_schedule_closure = NULL; + then_schedule_closure = nullptr; GRPC_SUBCHANNEL_CALL_UNREF(exec_ctx, calld->subchannel_call, "client_channel_destroy_call"); } - GPR_ASSERT(calld->lb_policy == NULL); + GPR_ASSERT(calld->lb_policy == nullptr); GPR_ASSERT(calld->waiting_for_pick_batches_count == 0); - if (calld->connected_subchannel != NULL) { + if (calld->connected_subchannel != nullptr) { GRPC_CONNECTED_SUBCHANNEL_UNREF(exec_ctx, calld->connected_subchannel, "picked"); } for (size_t i = 0; i < GRPC_CONTEXT_COUNT; ++i) { - if (calld->subchannel_call_context[i].value != NULL) { + if (calld->subchannel_call_context[i].value != nullptr) { calld->subchannel_call_context[i].destroy( calld->subchannel_call_context[i].value); } @@ -1502,10 +1535,10 @@ static void cc_destroy_call_elem(grpc_exec_ctx *exec_ctx, GRPC_CLOSURE_SCHED(exec_ctx, then_schedule_closure, GRPC_ERROR_NONE); } -static void cc_set_pollset_or_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_polling_entity *pollent) { - call_data *calld = (call_data *)elem->call_data; +static void cc_set_pollset_or_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_polling_entity* pollent) { + call_data* calld = (call_data*)elem->call_data; calld->pollent = pollent; } @@ -1527,14 +1560,14 @@ const grpc_channel_filter grpc_client_channel_filter = { "client-channel", }; -static void try_to_connect_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error_ignored) { - channel_data *chand = (channel_data *)arg; - if (chand->lb_policy != NULL) { +static void try_to_connect_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error_ignored) { + channel_data* chand = (channel_data*)arg; + if (chand->lb_policy != nullptr) { grpc_lb_policy_exit_idle_locked(exec_ctx, chand->lb_policy); } else { chand->exit_idle_when_lb_policy_arrives = true; - if (!chand->started_resolving && chand->resolver != NULL) { + if (!chand->started_resolving && chand->resolver != nullptr) { start_resolving_locked(exec_ctx, chand); } } @@ -1542,36 +1575,37 @@ static void try_to_connect_locked(grpc_exec_ctx *exec_ctx, void *arg, } grpc_connectivity_state grpc_client_channel_check_connectivity_state( - grpc_exec_ctx *exec_ctx, grpc_channel_element *elem, int try_to_connect) { - channel_data *chand = (channel_data *)elem->channel_data; + grpc_exec_ctx* exec_ctx, grpc_channel_element* elem, int try_to_connect) { + channel_data* chand = (channel_data*)elem->channel_data; grpc_connectivity_state out = grpc_connectivity_state_check(&chand->state_tracker); if (out == GRPC_CHANNEL_IDLE && try_to_connect) { GRPC_CHANNEL_STACK_REF(chand->owning_stack, "try_to_connect"); GRPC_CLOSURE_SCHED( - exec_ctx, GRPC_CLOSURE_CREATE(try_to_connect_locked, chand, - grpc_combiner_scheduler(chand->combiner)), + exec_ctx, + GRPC_CLOSURE_CREATE(try_to_connect_locked, chand, + grpc_combiner_scheduler(chand->combiner)), GRPC_ERROR_NONE); } return out; } typedef struct external_connectivity_watcher { - channel_data *chand; + channel_data* chand; grpc_polling_entity pollent; - grpc_closure *on_complete; - grpc_closure *watcher_timer_init; - grpc_connectivity_state *state; + grpc_closure* on_complete; + grpc_closure* watcher_timer_init; + grpc_connectivity_state* state; grpc_closure my_closure; - struct external_connectivity_watcher *next; + struct external_connectivity_watcher* next; } external_connectivity_watcher; -static external_connectivity_watcher *lookup_external_connectivity_watcher( - channel_data *chand, grpc_closure *on_complete) { +static external_connectivity_watcher* lookup_external_connectivity_watcher( + channel_data* chand, grpc_closure* on_complete) { gpr_mu_lock(&chand->external_connectivity_watcher_list_mu); - external_connectivity_watcher *w = + external_connectivity_watcher* w = chand->external_connectivity_watcher_list_head; - while (w != NULL && w->on_complete != on_complete) { + while (w != nullptr && w->on_complete != on_complete) { w = w->next; } gpr_mu_unlock(&chand->external_connectivity_watcher_list_mu); @@ -1579,7 +1613,7 @@ static external_connectivity_watcher *lookup_external_connectivity_watcher( } static void external_connectivity_watcher_list_append( - channel_data *chand, external_connectivity_watcher *w) { + channel_data* chand, external_connectivity_watcher* w) { GPR_ASSERT(!lookup_external_connectivity_watcher(chand, w->on_complete)); gpr_mu_lock(&w->chand->external_connectivity_watcher_list_mu); @@ -1590,7 +1624,7 @@ static void external_connectivity_watcher_list_append( } static void external_connectivity_watcher_list_remove( - channel_data *chand, external_connectivity_watcher *too_remove) { + channel_data* chand, external_connectivity_watcher* too_remove) { GPR_ASSERT( lookup_external_connectivity_watcher(chand, too_remove->on_complete)); gpr_mu_lock(&chand->external_connectivity_watcher_list_mu); @@ -1599,9 +1633,9 @@ static void external_connectivity_watcher_list_remove( gpr_mu_unlock(&chand->external_connectivity_watcher_list_mu); return; } - external_connectivity_watcher *w = + external_connectivity_watcher* w = chand->external_connectivity_watcher_list_head; - while (w != NULL) { + while (w != nullptr) { if (w->next == too_remove) { w->next = w->next->next; gpr_mu_unlock(&chand->external_connectivity_watcher_list_mu); @@ -1613,14 +1647,14 @@ static void external_connectivity_watcher_list_remove( } int grpc_client_channel_num_external_connectivity_watchers( - grpc_channel_element *elem) { - channel_data *chand = (channel_data *)elem->channel_data; + grpc_channel_element* elem) { + channel_data* chand = (channel_data*)elem->channel_data; int count = 0; gpr_mu_lock(&chand->external_connectivity_watcher_list_mu); - external_connectivity_watcher *w = + external_connectivity_watcher* w = chand->external_connectivity_watcher_list_head; - while (w != NULL) { + while (w != nullptr) { count++; w = w->next; } @@ -1629,10 +1663,10 @@ int grpc_client_channel_num_external_connectivity_watchers( return count; } -static void on_external_watch_complete_locked(grpc_exec_ctx *exec_ctx, - void *arg, grpc_error *error) { - external_connectivity_watcher *w = (external_connectivity_watcher *)arg; - grpc_closure *follow_up = w->on_complete; +static void on_external_watch_complete_locked(grpc_exec_ctx* exec_ctx, + void* arg, grpc_error* error) { + external_connectivity_watcher* w = (external_connectivity_watcher*)arg; + grpc_closure* follow_up = w->on_complete; grpc_polling_entity_del_from_pollset_set(exec_ctx, &w->pollent, w->chand->interested_parties); GRPC_CHANNEL_STACK_UNREF(exec_ctx, w->chand->owning_stack, @@ -1642,11 +1676,11 @@ static void on_external_watch_complete_locked(grpc_exec_ctx *exec_ctx, GRPC_CLOSURE_RUN(exec_ctx, follow_up, GRPC_ERROR_REF(error)); } -static void watch_connectivity_state_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error_ignored) { - external_connectivity_watcher *w = (external_connectivity_watcher *)arg; - external_connectivity_watcher *found = NULL; - if (w->state != NULL) { +static void watch_connectivity_state_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error_ignored) { + external_connectivity_watcher* w = (external_connectivity_watcher*)arg; + external_connectivity_watcher* found = nullptr; + if (w->state != nullptr) { external_connectivity_watcher_list_append(w->chand, w); GRPC_CLOSURE_RUN(exec_ctx, w->watcher_timer_init, GRPC_ERROR_NONE); GRPC_CLOSURE_INIT(&w->my_closure, on_external_watch_complete_locked, w, @@ -1654,12 +1688,12 @@ static void watch_connectivity_state_locked(grpc_exec_ctx *exec_ctx, void *arg, grpc_connectivity_state_notify_on_state_change( exec_ctx, &w->chand->state_tracker, w->state, &w->my_closure); } else { - GPR_ASSERT(w->watcher_timer_init == NULL); + GPR_ASSERT(w->watcher_timer_init == nullptr); found = lookup_external_connectivity_watcher(w->chand, w->on_complete); if (found) { GPR_ASSERT(found->on_complete == w->on_complete); grpc_connectivity_state_notify_on_state_change( - exec_ctx, &found->chand->state_tracker, NULL, &found->my_closure); + exec_ctx, &found->chand->state_tracker, nullptr, &found->my_closure); } grpc_polling_entity_del_from_pollset_set(exec_ctx, &w->pollent, w->chand->interested_parties); @@ -1670,12 +1704,12 @@ static void watch_connectivity_state_locked(grpc_exec_ctx *exec_ctx, void *arg, } void grpc_client_channel_watch_connectivity_state( - grpc_exec_ctx *exec_ctx, grpc_channel_element *elem, - grpc_polling_entity pollent, grpc_connectivity_state *state, - grpc_closure *closure, grpc_closure *watcher_timer_init) { - channel_data *chand = (channel_data *)elem->channel_data; - external_connectivity_watcher *w = - (external_connectivity_watcher *)gpr_zalloc(sizeof(*w)); + grpc_exec_ctx* exec_ctx, grpc_channel_element* elem, + grpc_polling_entity pollent, grpc_connectivity_state* state, + grpc_closure* closure, grpc_closure* watcher_timer_init) { + channel_data* chand = (channel_data*)elem->channel_data; + external_connectivity_watcher* w = + (external_connectivity_watcher*)gpr_zalloc(sizeof(*w)); w->chand = chand; w->pollent = pollent; w->on_complete = closure; diff --git a/src/core/ext/filters/client_channel/client_channel.h b/src/core/ext/filters/client_channel/client_channel.h index 152fe2365af..48e4637a82b 100644 --- a/src/core/ext/filters/client_channel/client_channel.h +++ b/src/core/ext/filters/client_channel/client_channel.h @@ -23,15 +23,11 @@ #include "src/core/ext/filters/client_channel/resolver.h" #include "src/core/lib/channel/channel_stack.h" -extern grpc_tracer_flag grpc_client_channel_trace; +extern grpc_core::TraceFlag grpc_client_channel_trace; // Channel arg key for server URI string. #define GRPC_ARG_SERVER_URI "grpc.server_uri" -#ifdef __cplusplus -extern "C" { -#endif - /* A client channel is a channel that begins disconnected, and can connect to some endpoint on demand. If that endpoint disconnects, it will be connected to again later. @@ -42,22 +38,18 @@ extern "C" { extern const grpc_channel_filter grpc_client_channel_filter; grpc_connectivity_state grpc_client_channel_check_connectivity_state( - grpc_exec_ctx *exec_ctx, grpc_channel_element *elem, int try_to_connect); + grpc_exec_ctx* exec_ctx, grpc_channel_element* elem, int try_to_connect); int grpc_client_channel_num_external_connectivity_watchers( - grpc_channel_element *elem); + grpc_channel_element* elem); void grpc_client_channel_watch_connectivity_state( - grpc_exec_ctx *exec_ctx, grpc_channel_element *elem, - grpc_polling_entity pollent, grpc_connectivity_state *state, - grpc_closure *on_complete, grpc_closure *watcher_timer_init); + grpc_exec_ctx* exec_ctx, grpc_channel_element* elem, + grpc_polling_entity pollent, grpc_connectivity_state* state, + grpc_closure* on_complete, grpc_closure* watcher_timer_init); /* Debug helper: pull the subchannel call from a call stack element */ -grpc_subchannel_call *grpc_client_channel_get_subchannel_call( - grpc_call_element *elem); - -#ifdef __cplusplus -} -#endif +grpc_subchannel_call* grpc_client_channel_get_subchannel_call( + grpc_call_element* elem); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_H */ diff --git a/src/core/ext/filters/client_channel/client_channel_factory.h b/src/core/ext/filters/client_channel/client_channel_factory.h index 4273c900583..db82b733cee 100644 --- a/src/core/ext/filters/client_channel/client_channel_factory.h +++ b/src/core/ext/filters/client_channel/client_channel_factory.h @@ -27,10 +27,6 @@ // Channel arg key for client channel factory. #define GRPC_ARG_CLIENT_CHANNEL_FACTORY "grpc.client_channel_factory" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_client_channel_factory grpc_client_channel_factory; typedef struct grpc_client_channel_factory_vtable grpc_client_channel_factory_vtable; @@ -44,42 +40,38 @@ typedef enum { /** Constructor for new configured channels. Creating decorators around this type is encouraged to adapt behavior. */ struct grpc_client_channel_factory { - const grpc_client_channel_factory_vtable *vtable; + const grpc_client_channel_factory_vtable* vtable; }; struct grpc_client_channel_factory_vtable { - void (*ref)(grpc_client_channel_factory *factory); - void (*unref)(grpc_exec_ctx *exec_ctx, grpc_client_channel_factory *factory); - grpc_subchannel *(*create_subchannel)(grpc_exec_ctx *exec_ctx, - grpc_client_channel_factory *factory, - const grpc_subchannel_args *args); - grpc_channel *(*create_client_channel)(grpc_exec_ctx *exec_ctx, - grpc_client_channel_factory *factory, - const char *target, + void (*ref)(grpc_client_channel_factory* factory); + void (*unref)(grpc_exec_ctx* exec_ctx, grpc_client_channel_factory* factory); + grpc_subchannel* (*create_subchannel)(grpc_exec_ctx* exec_ctx, + grpc_client_channel_factory* factory, + const grpc_subchannel_args* args); + grpc_channel* (*create_client_channel)(grpc_exec_ctx* exec_ctx, + grpc_client_channel_factory* factory, + const char* target, grpc_client_channel_type type, - const grpc_channel_args *args); + const grpc_channel_args* args); }; -void grpc_client_channel_factory_ref(grpc_client_channel_factory *factory); -void grpc_client_channel_factory_unref(grpc_exec_ctx *exec_ctx, - grpc_client_channel_factory *factory); +void grpc_client_channel_factory_ref(grpc_client_channel_factory* factory); +void grpc_client_channel_factory_unref(grpc_exec_ctx* exec_ctx, + grpc_client_channel_factory* factory); /** Create a new grpc_subchannel */ -grpc_subchannel *grpc_client_channel_factory_create_subchannel( - grpc_exec_ctx *exec_ctx, grpc_client_channel_factory *factory, - const grpc_subchannel_args *args); +grpc_subchannel* grpc_client_channel_factory_create_subchannel( + grpc_exec_ctx* exec_ctx, grpc_client_channel_factory* factory, + const grpc_subchannel_args* args); /** Create a new grpc_channel */ -grpc_channel *grpc_client_channel_factory_create_channel( - grpc_exec_ctx *exec_ctx, grpc_client_channel_factory *factory, - const char *target, grpc_client_channel_type type, - const grpc_channel_args *args); +grpc_channel* grpc_client_channel_factory_create_channel( + grpc_exec_ctx* exec_ctx, grpc_client_channel_factory* factory, + const char* target, grpc_client_channel_type type, + const grpc_channel_args* args); grpc_arg grpc_client_channel_factory_create_channel_arg( - grpc_client_channel_factory *factory); - -#ifdef __cplusplus -} -#endif + grpc_client_channel_factory* factory); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_FACTORY_H */ diff --git a/src/core/ext/filters/client_channel/client_channel_plugin.cc b/src/core/ext/filters/client_channel/client_channel_plugin.cc index 4431d115198..7a5bb181578 100644 --- a/src/core/ext/filters/client_channel/client_channel_plugin.cc +++ b/src/core/ext/filters/client_channel/client_channel_plugin.cc @@ -34,16 +34,16 @@ #include "src/core/ext/filters/client_channel/subchannel_index.h" #include "src/core/lib/surface/channel_init.h" -static bool append_filter(grpc_exec_ctx *exec_ctx, - grpc_channel_stack_builder *builder, void *arg) { +static bool append_filter(grpc_exec_ctx* exec_ctx, + grpc_channel_stack_builder* builder, void* arg) { return grpc_channel_stack_builder_append_filter( - builder, (const grpc_channel_filter *)arg, NULL, NULL); + builder, (const grpc_channel_filter*)arg, nullptr, nullptr); } -static bool set_default_host_if_unset(grpc_exec_ctx *exec_ctx, - grpc_channel_stack_builder *builder, - void *unused) { - const grpc_channel_args *args = +static bool set_default_host_if_unset(grpc_exec_ctx* exec_ctx, + grpc_channel_stack_builder* builder, + void* unused) { + const grpc_channel_args* args = grpc_channel_stack_builder_get_channel_arguments(builder); for (size_t i = 0; i < args->num_args; i++) { if (0 == strcmp(args->args[i].key, GRPC_ARG_DEFAULT_AUTHORITY) || @@ -51,12 +51,12 @@ static bool set_default_host_if_unset(grpc_exec_ctx *exec_ctx, return true; } } - char *default_authority = grpc_get_default_authority( + char* default_authority = grpc_get_default_authority( exec_ctx, grpc_channel_stack_builder_get_target(builder)); - if (default_authority != NULL) { + if (default_authority != nullptr) { grpc_arg arg = grpc_channel_arg_string_create( - (char *)GRPC_ARG_DEFAULT_AUTHORITY, default_authority); - grpc_channel_args *new_args = grpc_channel_args_copy_and_add(args, &arg, 1); + (char*)GRPC_ARG_DEFAULT_AUTHORITY, default_authority); + grpc_channel_args* new_args = grpc_channel_args_copy_and_add(args, &arg, 1); grpc_channel_stack_builder_set_channel_arguments(exec_ctx, builder, new_args); gpr_free(default_authority); @@ -65,7 +65,7 @@ static bool set_default_host_if_unset(grpc_exec_ctx *exec_ctx, return true; } -extern "C" void grpc_client_channel_init(void) { +void grpc_client_channel_init(void) { grpc_lb_policy_registry_init(); grpc_resolver_registry_init(); grpc_retry_throttle_map_init(); @@ -73,18 +73,14 @@ extern "C" void grpc_client_channel_init(void) { grpc_register_http_proxy_mapper(); grpc_subchannel_index_init(); grpc_channel_init_register_stage(GRPC_CLIENT_CHANNEL, INT_MIN, - set_default_host_if_unset, NULL); + set_default_host_if_unset, nullptr); grpc_channel_init_register_stage( GRPC_CLIENT_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, append_filter, - (void *)&grpc_client_channel_filter); + (void*)&grpc_client_channel_filter); grpc_http_connect_register_handshaker_factory(); - grpc_register_tracer(&grpc_client_channel_trace); -#ifndef NDEBUG - grpc_register_tracer(&grpc_trace_resolver_refcount); -#endif } -extern "C" void grpc_client_channel_shutdown(void) { +void grpc_client_channel_shutdown(void) { grpc_subchannel_index_shutdown(); grpc_channel_init_shutdown(); grpc_proxy_mapper_registry_shutdown(); diff --git a/src/core/ext/filters/client_channel/connector.h b/src/core/ext/filters/client_channel/connector.h index b71e0aab004..239ed8a8bd1 100644 --- a/src/core/ext/filters/client_channel/connector.h +++ b/src/core/ext/filters/client_channel/connector.h @@ -23,59 +23,51 @@ #include "src/core/lib/iomgr/resolve_address.h" #include "src/core/lib/transport/transport.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_connector grpc_connector; typedef struct grpc_connector_vtable grpc_connector_vtable; struct grpc_connector { - const grpc_connector_vtable *vtable; + const grpc_connector_vtable* vtable; }; typedef struct { /** set of pollsets interested in this connection */ - grpc_pollset_set *interested_parties; + grpc_pollset_set* interested_parties; /** deadline for connection */ grpc_millis deadline; /** channel arguments (to be passed to transport) */ - const grpc_channel_args *channel_args; + const grpc_channel_args* channel_args; } grpc_connect_in_args; typedef struct { /** the connected transport */ - grpc_transport *transport; + grpc_transport* transport; /** channel arguments (to be passed to the filters) */ - grpc_channel_args *channel_args; + grpc_channel_args* channel_args; } grpc_connect_out_args; struct grpc_connector_vtable { - void (*ref)(grpc_connector *connector); - void (*unref)(grpc_exec_ctx *exec_ctx, grpc_connector *connector); + void (*ref)(grpc_connector* connector); + void (*unref)(grpc_exec_ctx* exec_ctx, grpc_connector* connector); /** Implementation of grpc_connector_shutdown */ - void (*shutdown)(grpc_exec_ctx *exec_ctx, grpc_connector *connector, - grpc_error *why); + void (*shutdown)(grpc_exec_ctx* exec_ctx, grpc_connector* connector, + grpc_error* why); /** Implementation of grpc_connector_connect */ - void (*connect)(grpc_exec_ctx *exec_ctx, grpc_connector *connector, - const grpc_connect_in_args *in_args, - grpc_connect_out_args *out_args, grpc_closure *notify); + void (*connect)(grpc_exec_ctx* exec_ctx, grpc_connector* connector, + const grpc_connect_in_args* in_args, + grpc_connect_out_args* out_args, grpc_closure* notify); }; -grpc_connector *grpc_connector_ref(grpc_connector *connector); -void grpc_connector_unref(grpc_exec_ctx *exec_ctx, grpc_connector *connector); +grpc_connector* grpc_connector_ref(grpc_connector* connector); +void grpc_connector_unref(grpc_exec_ctx* exec_ctx, grpc_connector* connector); /** Connect using the connector: max one outstanding call at a time */ -void grpc_connector_connect(grpc_exec_ctx *exec_ctx, grpc_connector *connector, - const grpc_connect_in_args *in_args, - grpc_connect_out_args *out_args, - grpc_closure *notify); +void grpc_connector_connect(grpc_exec_ctx* exec_ctx, grpc_connector* connector, + const grpc_connect_in_args* in_args, + grpc_connect_out_args* out_args, + grpc_closure* notify); /** Cancel any pending connection */ -void grpc_connector_shutdown(grpc_exec_ctx *exec_ctx, grpc_connector *connector, - grpc_error *why); - -#ifdef __cplusplus -} -#endif +void grpc_connector_shutdown(grpc_exec_ctx* exec_ctx, grpc_connector* connector, + grpc_error* why); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CONNECTOR_H */ diff --git a/src/core/ext/filters/client_channel/http_connect_handshaker.cc b/src/core/ext/filters/client_channel/http_connect_handshaker.cc index 418bb41ef6a..b7cb2e3eba7 100644 --- a/src/core/ext/filters/client_channel/http_connect_handshaker.cc +++ b/src/core/ext/filters/client_channel/http_connect_handshaker.cc @@ -65,10 +65,10 @@ static void http_connect_handshaker_unref(grpc_exec_ctx* exec_ctx, http_connect_handshaker* handshaker) { if (gpr_unref(&handshaker->refcount)) { gpr_mu_destroy(&handshaker->mu); - if (handshaker->endpoint_to_destroy != NULL) { + if (handshaker->endpoint_to_destroy != nullptr) { grpc_endpoint_destroy(exec_ctx, handshaker->endpoint_to_destroy); } - if (handshaker->read_buffer_to_destroy != NULL) { + if (handshaker->read_buffer_to_destroy != nullptr) { grpc_slice_buffer_destroy_internal(exec_ctx, handshaker->read_buffer_to_destroy); gpr_free(handshaker->read_buffer_to_destroy); @@ -85,11 +85,11 @@ static void http_connect_handshaker_unref(grpc_exec_ctx* exec_ctx, static void cleanup_args_for_failure_locked( grpc_exec_ctx* exec_ctx, http_connect_handshaker* handshaker) { handshaker->endpoint_to_destroy = handshaker->args->endpoint; - handshaker->args->endpoint = NULL; + handshaker->args->endpoint = nullptr; handshaker->read_buffer_to_destroy = handshaker->args->read_buffer; - handshaker->args->read_buffer = NULL; + handshaker->args->read_buffer = nullptr; grpc_channel_args_destroy(exec_ctx, handshaker->args->args); - handshaker->args->args = NULL; + handshaker->args->args = nullptr; } // If the handshake failed or we're shutting down, clean up and invoke the @@ -260,7 +260,7 @@ static void http_connect_handshaker_do_handshake( // If not found, invoke on_handshake_done without doing anything. const grpc_arg* arg = grpc_channel_args_find(args->args, GRPC_ARG_HTTP_CONNECT_SERVER); - if (arg == NULL) { + if (arg == nullptr) { // Set shutdown to true so that subsequent calls to // http_connect_handshaker_shutdown() do nothing. gpr_mu_lock(&handshaker->mu); @@ -273,11 +273,11 @@ static void http_connect_handshaker_do_handshake( char* server_name = arg->value.string; // Get headers from channel args. arg = grpc_channel_args_find(args->args, GRPC_ARG_HTTP_CONNECT_HEADERS); - grpc_http_header* headers = NULL; + grpc_http_header* headers = nullptr; size_t num_headers = 0; - char** header_strings = NULL; + char** header_strings = nullptr; size_t num_header_strings = 0; - if (arg != NULL) { + if (arg != nullptr) { GPR_ASSERT(arg->type == GRPC_ARG_STRING); gpr_string_split(arg->value.string, "\n", &header_strings, &num_header_strings); @@ -285,7 +285,7 @@ static void http_connect_handshaker_do_handshake( num_header_strings); for (size_t i = 0; i < num_header_strings; ++i) { char* sep = strchr(header_strings[i], ':'); - if (sep == NULL) { + if (sep == nullptr) { gpr_log(GPR_ERROR, "skipping unparseable HTTP CONNECT header: %s", header_strings[i]); continue; diff --git a/src/core/ext/filters/client_channel/http_connect_handshaker.h b/src/core/ext/filters/client_channel/http_connect_handshaker.h index 05a23cdba34..928a23dc936 100644 --- a/src/core/ext/filters/client_channel/http_connect_handshaker.h +++ b/src/core/ext/filters/client_channel/http_connect_handshaker.h @@ -28,15 +28,7 @@ /// seperated by colons. #define GRPC_ARG_HTTP_CONNECT_HEADERS "grpc.http_connect_headers" -#ifdef __cplusplus -extern "C" { -#endif - /// Registers handshaker factory. void grpc_http_connect_register_handshaker_factory(); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HTTP_CONNECT_HANDSHAKER_H */ diff --git a/src/core/ext/filters/client_channel/http_proxy.cc b/src/core/ext/filters/client_channel/http_proxy.cc index a16b44d3dc3..405d8c0e559 100644 --- a/src/core/ext/filters/client_channel/http_proxy.cc +++ b/src/core/ext/filters/client_channel/http_proxy.cc @@ -41,15 +41,15 @@ * responsibility to gpr_free user_cred. */ static char* get_http_proxy_server(grpc_exec_ctx* exec_ctx, char** user_cred) { - GPR_ASSERT(user_cred != NULL); - char* proxy_name = NULL; + GPR_ASSERT(user_cred != nullptr); + char* proxy_name = nullptr; char* uri_str = gpr_getenv("http_proxy"); - char** authority_strs = NULL; + char** authority_strs = nullptr; size_t authority_nstrs; - if (uri_str == NULL) return NULL; + if (uri_str == nullptr) return nullptr; grpc_uri* uri = grpc_uri_parse(exec_ctx, uri_str, false /* suppress_errors */); - if (uri == NULL || uri->authority == NULL) { + if (uri == nullptr || uri->authority == nullptr) { gpr_log(GPR_ERROR, "cannot parse value of 'http_proxy' env var"); goto done; } @@ -73,7 +73,7 @@ static char* get_http_proxy_server(grpc_exec_ctx* exec_ctx, char** user_cred) { for (size_t i = 0; i < authority_nstrs; i++) { gpr_free(authority_strs[i]); } - proxy_name = NULL; + proxy_name = nullptr; } gpr_free(authority_strs); done: @@ -88,13 +88,13 @@ static bool proxy_mapper_map_name(grpc_exec_ctx* exec_ctx, const grpc_channel_args* args, char** name_to_resolve, grpc_channel_args** new_args) { - char* user_cred = NULL; + char* user_cred = nullptr; *name_to_resolve = get_http_proxy_server(exec_ctx, &user_cred); - if (*name_to_resolve == NULL) return false; - char* no_proxy_str = NULL; + if (*name_to_resolve == nullptr) return false; + char* no_proxy_str = nullptr; grpc_uri* uri = grpc_uri_parse(exec_ctx, server_uri, false /* suppress_errors */); - if (uri == NULL || uri->path[0] == '\0') { + if (uri == nullptr || uri->path[0] == '\0') { gpr_log(GPR_ERROR, "'http_proxy' environment variable set, but cannot " "parse server URI '%s' -- not using proxy", @@ -107,7 +107,7 @@ static bool proxy_mapper_map_name(grpc_exec_ctx* exec_ctx, goto no_use_proxy; } no_proxy_str = gpr_getenv("no_proxy"); - if (no_proxy_str != NULL) { + if (no_proxy_str != nullptr) { static const char* NO_PROXY_SEPARATOR = ","; bool use_proxy = true; char* server_host; @@ -149,7 +149,7 @@ static bool proxy_mapper_map_name(grpc_exec_ctx* exec_ctx, args_to_add[0] = grpc_channel_arg_string_create( (char*)GRPC_ARG_HTTP_CONNECT_SERVER, uri->path[0] == '/' ? uri->path + 1 : uri->path); - if (user_cred != NULL) { + if (user_cred != nullptr) { /* Use base64 encoding for user credentials as stated in RFC 7617 */ char* encoded_user_cred = grpc_base64_encode(user_cred, strlen(user_cred), 0, 0); @@ -167,9 +167,9 @@ static bool proxy_mapper_map_name(grpc_exec_ctx* exec_ctx, gpr_free(user_cred); return true; no_use_proxy: - if (uri != NULL) grpc_uri_destroy(uri); + if (uri != nullptr) grpc_uri_destroy(uri); gpr_free(*name_to_resolve); - *name_to_resolve = NULL; + *name_to_resolve = nullptr; gpr_free(user_cred); return false; } diff --git a/src/core/ext/filters/client_channel/http_proxy.h b/src/core/ext/filters/client_channel/http_proxy.h index bdad03def31..34694931d04 100644 --- a/src/core/ext/filters/client_channel/http_proxy.h +++ b/src/core/ext/filters/client_channel/http_proxy.h @@ -19,14 +19,6 @@ #ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HTTP_PROXY_H #define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HTTP_PROXY_H -#ifdef __cplusplus -extern "C" { -#endif - void grpc_register_http_proxy_mapper(); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HTTP_PROXY_H */ diff --git a/src/core/ext/filters/client_channel/lb_policy.cc b/src/core/ext/filters/client_channel/lb_policy.cc index 8e6673d737e..db566f1b562 100644 --- a/src/core/ext/filters/client_channel/lb_policy.cc +++ b/src/core/ext/filters/client_channel/lb_policy.cc @@ -21,14 +21,12 @@ #define WEAK_REF_BITS 16 -#ifndef NDEBUG -grpc_tracer_flag grpc_trace_lb_policy_refcount = - GRPC_TRACER_INITIALIZER(false, "lb_policy_refcount"); -#endif +grpc_core::DebugOnlyTraceFlag grpc_trace_lb_policy_refcount( + false, "lb_policy_refcount"); -void grpc_lb_policy_init(grpc_lb_policy *policy, - const grpc_lb_policy_vtable *vtable, - grpc_combiner *combiner) { +void grpc_lb_policy_init(grpc_lb_policy* policy, + const grpc_lb_policy_vtable* vtable, + grpc_combiner* combiner) { policy->vtable = vtable; gpr_atm_no_barrier_store(&policy->ref_pair, 1 << WEAK_REF_BITS); policy->interested_parties = grpc_pollset_set_create(); @@ -37,7 +35,7 @@ void grpc_lb_policy_init(grpc_lb_policy *policy, #ifndef NDEBUG #define REF_FUNC_EXTRA_ARGS , const char *file, int line, const char *reason -#define REF_MUTATE_EXTRA_ARGS REF_FUNC_EXTRA_ARGS, const char *purpose +#define REF_MUTATE_EXTRA_ARGS REF_FUNC_EXTRA_ARGS, const char* purpose #define REF_FUNC_PASS_ARGS(new_reason) , file, line, new_reason #define REF_MUTATE_PASS_ARGS(purpose) , file, line, reason, purpose #else @@ -47,12 +45,12 @@ void grpc_lb_policy_init(grpc_lb_policy *policy, #define REF_MUTATE_PASS_ARGS(x) #endif -static gpr_atm ref_mutate(grpc_lb_policy *c, gpr_atm delta, +static gpr_atm ref_mutate(grpc_lb_policy* c, gpr_atm delta, int barrier REF_MUTATE_EXTRA_ARGS) { gpr_atm old_val = barrier ? gpr_atm_full_fetch_add(&c->ref_pair, delta) : gpr_atm_no_barrier_fetch_add(&c->ref_pair, delta); #ifndef NDEBUG - if (GRPC_TRACER_ON(grpc_trace_lb_policy_refcount)) { + if (grpc_trace_lb_policy_refcount.enabled()) { gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "LB_POLICY: %p %12s 0x%" PRIxPTR " -> 0x%" PRIxPTR " [%s]", c, purpose, old_val, old_val + delta, reason); @@ -61,104 +59,132 @@ static gpr_atm ref_mutate(grpc_lb_policy *c, gpr_atm delta, return old_val; } -void grpc_lb_policy_ref(grpc_lb_policy *policy REF_FUNC_EXTRA_ARGS) { +void grpc_lb_policy_ref(grpc_lb_policy* policy REF_FUNC_EXTRA_ARGS) { ref_mutate(policy, 1 << WEAK_REF_BITS, 0 REF_MUTATE_PASS_ARGS("STRONG_REF")); } -static void shutdown_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_lb_policy *policy = (grpc_lb_policy *)arg; +static void shutdown_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_lb_policy* policy = (grpc_lb_policy*)arg; policy->vtable->shutdown_locked(exec_ctx, policy); GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, policy, "strong-unref"); } -void grpc_lb_policy_unref(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *policy REF_FUNC_EXTRA_ARGS) { +void grpc_lb_policy_unref(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* policy REF_FUNC_EXTRA_ARGS) { gpr_atm old_val = ref_mutate(policy, (gpr_atm)1 - (gpr_atm)(1 << WEAK_REF_BITS), 1 REF_MUTATE_PASS_ARGS("STRONG_UNREF")); gpr_atm mask = ~(gpr_atm)((1 << WEAK_REF_BITS) - 1); gpr_atm check = 1 << WEAK_REF_BITS; if ((old_val & mask) == check) { - GRPC_CLOSURE_SCHED(exec_ctx, GRPC_CLOSURE_CREATE( - shutdown_locked, policy, - grpc_combiner_scheduler(policy->combiner)), - GRPC_ERROR_NONE); + GRPC_CLOSURE_SCHED( + exec_ctx, + GRPC_CLOSURE_CREATE(shutdown_locked, policy, + grpc_combiner_scheduler(policy->combiner)), + GRPC_ERROR_NONE); } else { grpc_lb_policy_weak_unref(exec_ctx, policy REF_FUNC_PASS_ARGS("strong-unref")); } } -void grpc_lb_policy_weak_ref(grpc_lb_policy *policy REF_FUNC_EXTRA_ARGS) { +void grpc_lb_policy_weak_ref(grpc_lb_policy* policy REF_FUNC_EXTRA_ARGS) { ref_mutate(policy, 1, 0 REF_MUTATE_PASS_ARGS("WEAK_REF")); } -void grpc_lb_policy_weak_unref(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *policy REF_FUNC_EXTRA_ARGS) { +void grpc_lb_policy_weak_unref(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* policy REF_FUNC_EXTRA_ARGS) { gpr_atm old_val = ref_mutate(policy, -(gpr_atm)1, 1 REF_MUTATE_PASS_ARGS("WEAK_UNREF")); if (old_val == 1) { grpc_pollset_set_destroy(exec_ctx, policy->interested_parties); - grpc_combiner *combiner = policy->combiner; + grpc_combiner* combiner = policy->combiner; policy->vtable->destroy(exec_ctx, policy); GRPC_COMBINER_UNREF(exec_ctx, combiner, "lb_policy"); } } -int grpc_lb_policy_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, - const grpc_lb_policy_pick_args *pick_args, - grpc_connected_subchannel **target, - grpc_call_context_element *context, - void **user_data, grpc_closure *on_complete) { +int grpc_lb_policy_pick_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + const grpc_lb_policy_pick_args* pick_args, + grpc_connected_subchannel** target, + grpc_call_context_element* context, + void** user_data, grpc_closure* on_complete) { return policy->vtable->pick_locked(exec_ctx, policy, pick_args, target, context, user_data, on_complete); } -void grpc_lb_policy_cancel_pick_locked(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *policy, - grpc_connected_subchannel **target, - grpc_error *error) { +void grpc_lb_policy_cancel_pick_locked(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* policy, + grpc_connected_subchannel** target, + grpc_error* error) { policy->vtable->cancel_pick_locked(exec_ctx, policy, target, error); } -void grpc_lb_policy_cancel_picks_locked(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *policy, +void grpc_lb_policy_cancel_picks_locked(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* policy, uint32_t initial_metadata_flags_mask, uint32_t initial_metadata_flags_eq, - grpc_error *error) { + grpc_error* error) { policy->vtable->cancel_picks_locked(exec_ctx, policy, initial_metadata_flags_mask, initial_metadata_flags_eq, error); } -void grpc_lb_policy_exit_idle_locked(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *policy) { +void grpc_lb_policy_exit_idle_locked(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* policy) { policy->vtable->exit_idle_locked(exec_ctx, policy); } -void grpc_lb_policy_ping_one_locked(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *policy, - grpc_closure *closure) { +void grpc_lb_policy_ping_one_locked(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* policy, + grpc_closure* closure) { policy->vtable->ping_one_locked(exec_ctx, policy, closure); } void grpc_lb_policy_notify_on_state_change_locked( - grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, - grpc_connectivity_state *state, grpc_closure *closure) { + grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + grpc_connectivity_state* state, grpc_closure* closure) { policy->vtable->notify_on_state_change_locked(exec_ctx, policy, state, closure); } grpc_connectivity_state grpc_lb_policy_check_connectivity_locked( - grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, - grpc_error **connectivity_error) { + grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + grpc_error** connectivity_error) { return policy->vtable->check_connectivity_locked(exec_ctx, policy, connectivity_error); } -void grpc_lb_policy_update_locked(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *policy, - const grpc_lb_policy_args *lb_policy_args) { +void grpc_lb_policy_update_locked(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* policy, + const grpc_lb_policy_args* lb_policy_args) { policy->vtable->update_locked(exec_ctx, policy, lb_policy_args); } + +void grpc_lb_policy_set_reresolve_closure_locked( + grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + grpc_closure* request_reresolution) { + policy->vtable->set_reresolve_closure_locked(exec_ctx, policy, + request_reresolution); +} + +void grpc_lb_policy_try_reresolve(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* policy, + grpc_core::TraceFlag* grpc_lb_trace, + grpc_error* error) { + if (policy->request_reresolution != nullptr) { + GRPC_CLOSURE_SCHED(exec_ctx, policy->request_reresolution, error); + policy->request_reresolution = nullptr; + if (grpc_lb_trace->enabled()) { + gpr_log(GPR_DEBUG, + "%s %p: scheduling re-resolution closure with error=%s.", + grpc_lb_trace->name(), policy, grpc_error_string(error)); + } + } else { + if (grpc_lb_trace->enabled() && error == GRPC_ERROR_NONE) { + gpr_log(GPR_DEBUG, "%s %p: re-resolution already in progress.", + grpc_lb_trace->name(), policy); + } + } +} diff --git a/src/core/ext/filters/client_channel/lb_policy.h b/src/core/ext/filters/client_channel/lb_policy.h index 010299c2f4c..d3159eebf3b 100644 --- a/src/core/ext/filters/client_channel/lb_policy.h +++ b/src/core/ext/filters/client_channel/lb_policy.h @@ -23,85 +23,86 @@ #include "src/core/lib/iomgr/polling_entity.h" #include "src/core/lib/transport/connectivity_state.h" -#ifdef __cplusplus -extern "C" { -#endif - /** A load balancing policy: specified by a vtable and a struct (which is expected to be extended to contain some parameters) */ typedef struct grpc_lb_policy grpc_lb_policy; typedef struct grpc_lb_policy_vtable grpc_lb_policy_vtable; typedef struct grpc_lb_policy_args grpc_lb_policy_args; -#ifndef NDEBUG -extern grpc_tracer_flag grpc_trace_lb_policy_refcount; -#endif +extern grpc_core::DebugOnlyTraceFlag grpc_trace_lb_policy_refcount; struct grpc_lb_policy { - const grpc_lb_policy_vtable *vtable; + const grpc_lb_policy_vtable* vtable; gpr_atm ref_pair; /* owned pointer to interested parties in load balancing decisions */ - grpc_pollset_set *interested_parties; + grpc_pollset_set* interested_parties; /* combiner under which lb_policy actions take place */ - grpc_combiner *combiner; + grpc_combiner* combiner; + /* callback to force a re-resolution */ + grpc_closure* request_reresolution; }; /** Extra arguments for an LB pick */ typedef struct grpc_lb_policy_pick_args { /** Initial metadata associated with the picking call. */ - grpc_metadata_batch *initial_metadata; + grpc_metadata_batch* initial_metadata; /** Bitmask used for selective cancelling. See \a * grpc_lb_policy_cancel_picks() and \a GRPC_INITIAL_METADATA_* in * grpc_types.h */ uint32_t initial_metadata_flags; /** Storage for LB token in \a initial_metadata, or NULL if not used */ - grpc_linked_mdelem *lb_token_mdelem_storage; + grpc_linked_mdelem* lb_token_mdelem_storage; } grpc_lb_policy_pick_args; struct grpc_lb_policy_vtable { - void (*destroy)(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy); - void (*shutdown_locked)(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy); + void (*destroy)(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy); + void (*shutdown_locked)(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy); /** \see grpc_lb_policy_pick */ - int (*pick_locked)(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, - const grpc_lb_policy_pick_args *pick_args, - grpc_connected_subchannel **target, - grpc_call_context_element *context, void **user_data, - grpc_closure *on_complete); + int (*pick_locked)(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + const grpc_lb_policy_pick_args* pick_args, + grpc_connected_subchannel** target, + grpc_call_context_element* context, void** user_data, + grpc_closure* on_complete); /** \see grpc_lb_policy_cancel_pick */ - void (*cancel_pick_locked)(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, - grpc_connected_subchannel **target, - grpc_error *error); + void (*cancel_pick_locked)(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + grpc_connected_subchannel** target, + grpc_error* error); /** \see grpc_lb_policy_cancel_picks */ - void (*cancel_picks_locked)(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, + void (*cancel_picks_locked)(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, uint32_t initial_metadata_flags_mask, uint32_t initial_metadata_flags_eq, - grpc_error *error); + grpc_error* error); /** \see grpc_lb_policy_ping_one */ - void (*ping_one_locked)(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, - grpc_closure *closure); + void (*ping_one_locked)(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + grpc_closure* closure); /** Try to enter a READY connectivity state */ - void (*exit_idle_locked)(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy); + void (*exit_idle_locked)(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy); /** check the current connectivity of the lb_policy */ grpc_connectivity_state (*check_connectivity_locked)( - grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, - grpc_error **connectivity_error); + grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + grpc_error** connectivity_error); /** call notify when the connectivity state of a channel changes from *state. Updates *state with the new state of the policy. Calling with a NULL \a state cancels the subscription. */ - void (*notify_on_state_change_locked)(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *policy, - grpc_connectivity_state *state, - grpc_closure *closure); - - void (*update_locked)(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, - const grpc_lb_policy_args *args); + void (*notify_on_state_change_locked)(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* policy, + grpc_connectivity_state* state, + grpc_closure* closure); + + void (*update_locked)(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + const grpc_lb_policy_args* args); + + /** \see grpc_lb_policy_set_reresolve_closure */ + void (*set_reresolve_closure_locked)(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* policy, + grpc_closure* request_reresolution); }; #ifndef NDEBUG @@ -119,29 +120,29 @@ struct grpc_lb_policy_vtable { grpc_lb_policy_weak_ref((p), __FILE__, __LINE__, (r)) #define GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, p, r) \ grpc_lb_policy_weak_unref((exec_ctx), (p), __FILE__, __LINE__, (r)) -void grpc_lb_policy_ref(grpc_lb_policy *policy, const char *file, int line, - const char *reason); -void grpc_lb_policy_unref(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, - const char *file, int line, const char *reason); -void grpc_lb_policy_weak_ref(grpc_lb_policy *policy, const char *file, int line, - const char *reason); -void grpc_lb_policy_weak_unref(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, - const char *file, int line, const char *reason); +void grpc_lb_policy_ref(grpc_lb_policy* policy, const char* file, int line, + const char* reason); +void grpc_lb_policy_unref(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + const char* file, int line, const char* reason); +void grpc_lb_policy_weak_ref(grpc_lb_policy* policy, const char* file, int line, + const char* reason); +void grpc_lb_policy_weak_unref(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + const char* file, int line, const char* reason); #else #define GRPC_LB_POLICY_REF(p, r) grpc_lb_policy_ref((p)) #define GRPC_LB_POLICY_UNREF(cl, p, r) grpc_lb_policy_unref((cl), (p)) #define GRPC_LB_POLICY_WEAK_REF(p, r) grpc_lb_policy_weak_ref((p)) #define GRPC_LB_POLICY_WEAK_UNREF(cl, p, r) grpc_lb_policy_weak_unref((cl), (p)) -void grpc_lb_policy_ref(grpc_lb_policy *policy); -void grpc_lb_policy_unref(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy); -void grpc_lb_policy_weak_ref(grpc_lb_policy *policy); -void grpc_lb_policy_weak_unref(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy); +void grpc_lb_policy_ref(grpc_lb_policy* policy); +void grpc_lb_policy_unref(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy); +void grpc_lb_policy_weak_ref(grpc_lb_policy* policy); +void grpc_lb_policy_weak_unref(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy); #endif /** called by concrete implementations to initialize the base struct */ -void grpc_lb_policy_init(grpc_lb_policy *policy, - const grpc_lb_policy_vtable *vtable, - grpc_combiner *combiner); +void grpc_lb_policy_init(grpc_lb_policy* policy, + const grpc_lb_policy_vtable* vtable, + grpc_combiner* combiner); /** Finds an appropriate subchannel for a call, based on \a pick_args. @@ -160,56 +161,64 @@ void grpc_lb_policy_init(grpc_lb_policy *policy, Any IO should be done under the \a interested_parties \a grpc_pollset_set in the \a grpc_lb_policy struct. */ -int grpc_lb_policy_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, - const grpc_lb_policy_pick_args *pick_args, - grpc_connected_subchannel **target, - grpc_call_context_element *context, - void **user_data, grpc_closure *on_complete); +int grpc_lb_policy_pick_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + const grpc_lb_policy_pick_args* pick_args, + grpc_connected_subchannel** target, + grpc_call_context_element* context, + void** user_data, grpc_closure* on_complete); /** Perform a connected subchannel ping (see \a grpc_connected_subchannel_ping) against one of the connected subchannels managed by \a policy. */ -void grpc_lb_policy_ping_one_locked(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *policy, - grpc_closure *closure); +void grpc_lb_policy_ping_one_locked(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* policy, + grpc_closure* closure); /** Cancel picks for \a target. The \a on_complete callback of the pending picks will be invoked with \a *target set to NULL. */ -void grpc_lb_policy_cancel_pick_locked(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *policy, - grpc_connected_subchannel **target, - grpc_error *error); +void grpc_lb_policy_cancel_pick_locked(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* policy, + grpc_connected_subchannel** target, + grpc_error* error); /** Cancel all pending picks for which their \a initial_metadata_flags (as given in the call to \a grpc_lb_policy_pick) matches \a initial_metadata_flags_eq when AND'd with \a initial_metadata_flags_mask */ -void grpc_lb_policy_cancel_picks_locked(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *policy, +void grpc_lb_policy_cancel_picks_locked(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* policy, uint32_t initial_metadata_flags_mask, uint32_t initial_metadata_flags_eq, - grpc_error *error); + grpc_error* error); /** Try to enter a READY connectivity state */ -void grpc_lb_policy_exit_idle_locked(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *policy); +void grpc_lb_policy_exit_idle_locked(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* policy); /* Call notify when the connectivity state of a channel changes from \a *state. * Updates \a *state with the new state of the policy */ void grpc_lb_policy_notify_on_state_change_locked( - grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, - grpc_connectivity_state *state, grpc_closure *closure); + grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + grpc_connectivity_state* state, grpc_closure* closure); grpc_connectivity_state grpc_lb_policy_check_connectivity_locked( - grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, - grpc_error **connectivity_error); + grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + grpc_error** connectivity_error); /** Update \a policy with \a lb_policy_args. */ -void grpc_lb_policy_update_locked(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *policy, - const grpc_lb_policy_args *lb_policy_args); - -#ifdef __cplusplus -} -#endif +void grpc_lb_policy_update_locked(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* policy, + const grpc_lb_policy_args* lb_policy_args); + +/** Set the re-resolution closure to \a request_reresolution. */ +void grpc_lb_policy_set_reresolve_closure_locked( + grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + grpc_closure* request_reresolution); + +/** Try to request a re-resolution. It's NOT a public API; it's only for use by + the LB policy implementations. */ +void grpc_lb_policy_try_reresolve(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* policy, + grpc_core::TraceFlag* grpc_lb_trace, + grpc_error* error); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_H */ diff --git a/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc b/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc index 7ad322902bd..6d9fadaf306 100644 --- a/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc +++ b/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc @@ -25,31 +25,31 @@ #include "src/core/lib/iomgr/error.h" #include "src/core/lib/profiling/timers.h" -static grpc_error *init_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_channel_element_args *args) { +static grpc_error* init_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_channel_element_args* args) { return GRPC_ERROR_NONE; } -static void destroy_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem) {} +static void destroy_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem) {} typedef struct { // Stats object to update. - grpc_grpclb_client_stats *client_stats; + grpc_grpclb_client_stats* client_stats; // State for intercepting send_initial_metadata. grpc_closure on_complete_for_send; - grpc_closure *original_on_complete_for_send; + grpc_closure* original_on_complete_for_send; bool send_initial_metadata_succeeded; // State for intercepting recv_initial_metadata. grpc_closure recv_initial_metadata_ready; - grpc_closure *original_recv_initial_metadata_ready; + grpc_closure* original_recv_initial_metadata_ready; bool recv_initial_metadata_succeeded; } call_data; -static void on_complete_for_send(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - call_data *calld = (call_data *)arg; +static void on_complete_for_send(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + call_data* calld = (call_data*)arg; if (error == GRPC_ERROR_NONE) { calld->send_initial_metadata_succeeded = true; } @@ -57,9 +57,9 @@ static void on_complete_for_send(grpc_exec_ctx *exec_ctx, void *arg, GRPC_ERROR_REF(error)); } -static void recv_initial_metadata_ready(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - call_data *calld = (call_data *)arg; +static void recv_initial_metadata_ready(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + call_data* calld = (call_data*)arg; if (error == GRPC_ERROR_NONE) { calld->recv_initial_metadata_succeeded = true; } @@ -67,25 +67,24 @@ static void recv_initial_metadata_ready(grpc_exec_ctx *exec_ctx, void *arg, GRPC_ERROR_REF(error)); } -static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - const grpc_call_element_args *args) { - call_data *calld = (call_data *)elem->call_data; +static grpc_error* init_call_elem(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + const grpc_call_element_args* args) { + call_data* calld = (call_data*)elem->call_data; // Get stats object from context and take a ref. - GPR_ASSERT(args->context != NULL); - GPR_ASSERT(args->context[GRPC_GRPCLB_CLIENT_STATS].value != NULL); + GPR_ASSERT(args->context != nullptr); + GPR_ASSERT(args->context[GRPC_GRPCLB_CLIENT_STATS].value != nullptr); calld->client_stats = grpc_grpclb_client_stats_ref( - (grpc_grpclb_client_stats *)args->context[GRPC_GRPCLB_CLIENT_STATS] - .value); + (grpc_grpclb_client_stats*)args->context[GRPC_GRPCLB_CLIENT_STATS].value); // Record call started. grpc_grpclb_client_stats_add_call_started(calld->client_stats); return GRPC_ERROR_NONE; } -static void destroy_call_elem(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - const grpc_call_final_info *final_info, - grpc_closure *ignored) { - call_data *calld = (call_data *)elem->call_data; +static void destroy_call_elem(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + const grpc_call_final_info* final_info, + grpc_closure* ignored) { + call_data* calld = (call_data*)elem->call_data; // Record call finished, optionally setting client_failed_to_send and // received. grpc_grpclb_client_stats_add_call_finished( @@ -97,9 +96,9 @@ static void destroy_call_elem(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, } static void start_transport_stream_op_batch( - grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_transport_stream_op_batch *batch) { - call_data *calld = (call_data *)elem->call_data; + grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_transport_stream_op_batch* batch) { + call_data* calld = (call_data*)elem->call_data; GPR_TIMER_BEGIN("clr_start_transport_stream_op_batch", 0); // Intercept send_initial_metadata. if (batch->send_initial_metadata) { diff --git a/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h b/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h index c6a0d69c3f2..04de7a04df6 100644 --- a/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h +++ b/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h @@ -21,15 +21,7 @@ #include "src/core/lib/channel/channel_stack.h" -#ifdef __cplusplus -extern "C" { -#endif - extern const grpc_channel_filter grpc_client_load_reporting_filter; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_CLIENT_LOAD_REPORTING_FILTER_H \ - */ + */ diff --git a/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc b/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc index 85e76e68b5a..db06fc20b60 100644 --- a/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc +++ b/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc @@ -126,21 +126,21 @@ #define GRPC_GRPCLB_RECONNECT_JITTER 0.2 #define GRPC_GRPCLB_DEFAULT_FALLBACK_TIMEOUT_MS 10000 -grpc_tracer_flag grpc_lb_glb_trace = GRPC_TRACER_INITIALIZER(false, "glb"); +grpc_core::TraceFlag grpc_lb_glb_trace(false, "glb"); /* add lb_token of selected subchannel (address) to the call's initial * metadata */ -static grpc_error *initial_metadata_add_lb_token( - grpc_exec_ctx *exec_ctx, grpc_metadata_batch *initial_metadata, - grpc_linked_mdelem *lb_token_mdelem_storage, grpc_mdelem lb_token) { - GPR_ASSERT(lb_token_mdelem_storage != NULL); +static grpc_error* initial_metadata_add_lb_token( + grpc_exec_ctx* exec_ctx, grpc_metadata_batch* initial_metadata, + grpc_linked_mdelem* lb_token_mdelem_storage, grpc_mdelem lb_token) { + GPR_ASSERT(lb_token_mdelem_storage != nullptr); GPR_ASSERT(!GRPC_MDISNULL(lb_token)); return grpc_metadata_batch_add_tail(exec_ctx, initial_metadata, lb_token_mdelem_storage, lb_token); } -static void destroy_client_stats(void *arg) { - grpc_grpclb_client_stats_unref((grpc_grpclb_client_stats *)arg); +static void destroy_client_stats(void* arg) { + grpc_grpclb_client_stats_unref((grpc_grpclb_client_stats*)arg); } typedef struct wrapped_rr_closure_arg { @@ -149,75 +149,81 @@ typedef struct wrapped_rr_closure_arg { /* the original closure. Usually a on_complete/notify cb for pick() and ping() * calls against the internal RR instance, respectively. */ - grpc_closure *wrapped_closure; + grpc_closure* wrapped_closure; /* the pick's initial metadata, kept in order to append the LB token for the * pick */ - grpc_metadata_batch *initial_metadata; + grpc_metadata_batch* initial_metadata; /* the picked target, used to determine which LB token to add to the pick's * initial metadata */ - grpc_connected_subchannel **target; + grpc_connected_subchannel** target; /* the context to be populated for the subchannel call */ - grpc_call_context_element *context; + grpc_call_context_element* context; /* Stats for client-side load reporting. Note that this holds a * reference, which must be either passed on via context or unreffed. */ - grpc_grpclb_client_stats *client_stats; + grpc_grpclb_client_stats* client_stats; /* the LB token associated with the pick */ grpc_mdelem lb_token; /* storage for the lb token initial metadata mdelem */ - grpc_linked_mdelem *lb_token_mdelem_storage; + grpc_linked_mdelem* lb_token_mdelem_storage; /* The RR instance related to the closure */ - grpc_lb_policy *rr_policy; + grpc_lb_policy* rr_policy; + + /* The grpclb instance that created the wrapping. This instance is not owned, + * reference counts are untouched. It's used only for logging purposes. */ + grpc_lb_policy* glb_policy; /* heap memory to be freed upon closure execution. */ - void *free_when_done; + void* free_when_done; } wrapped_rr_closure_arg; /* The \a on_complete closure passed as part of the pick requires keeping a * reference to its associated round robin instance. We wrap this closure in * order to unref the round robin instance upon its invocation */ -static void wrapped_rr_closure(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - wrapped_rr_closure_arg *wc_arg = (wrapped_rr_closure_arg *)arg; +static void wrapped_rr_closure(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + wrapped_rr_closure_arg* wc_arg = (wrapped_rr_closure_arg*)arg; - GPR_ASSERT(wc_arg->wrapped_closure != NULL); + GPR_ASSERT(wc_arg->wrapped_closure != nullptr); GRPC_CLOSURE_SCHED(exec_ctx, wc_arg->wrapped_closure, GRPC_ERROR_REF(error)); - if (wc_arg->rr_policy != NULL) { + if (wc_arg->rr_policy != nullptr) { /* if *target is NULL, no pick has been made by the RR policy (eg, all * addresses failed to connect). There won't be any user_data/token * available */ - if (*wc_arg->target != NULL) { + if (*wc_arg->target != nullptr) { if (!GRPC_MDISNULL(wc_arg->lb_token)) { initial_metadata_add_lb_token(exec_ctx, wc_arg->initial_metadata, wc_arg->lb_token_mdelem_storage, GRPC_MDELEM_REF(wc_arg->lb_token)); } else { - gpr_log(GPR_ERROR, - "No LB token for connected subchannel pick %p (from RR " - "instance %p).", - (void *)*wc_arg->target, (void *)wc_arg->rr_policy); + gpr_log( + GPR_ERROR, + "[grpclb %p] No LB token for connected subchannel pick %p (from RR " + "instance %p).", + wc_arg->glb_policy, *wc_arg->target, wc_arg->rr_policy); abort(); } // Pass on client stats via context. Passes ownership of the reference. - GPR_ASSERT(wc_arg->client_stats != NULL); + GPR_ASSERT(wc_arg->client_stats != nullptr); wc_arg->context[GRPC_GRPCLB_CLIENT_STATS].value = wc_arg->client_stats; wc_arg->context[GRPC_GRPCLB_CLIENT_STATS].destroy = destroy_client_stats; } else { grpc_grpclb_client_stats_unref(wc_arg->client_stats); } - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { - gpr_log(GPR_INFO, "Unreffing RR %p", (void *)wc_arg->rr_policy); + if (grpc_lb_glb_trace.enabled()) { + gpr_log(GPR_INFO, "[grpclb %p] Unreffing RR %p", wc_arg->glb_policy, + wc_arg->rr_policy); } GRPC_LB_POLICY_UNREF(exec_ctx, wc_arg->rr_policy, "wrapped_rr_closure"); } - GPR_ASSERT(wc_arg->free_when_done != NULL); + GPR_ASSERT(wc_arg->free_when_done != nullptr); gpr_free(wc_arg->free_when_done); } @@ -230,25 +236,25 @@ static void wrapped_rr_closure(grpc_exec_ctx *exec_ctx, void *arg, * order to correctly unref the RR policy instance upon completion of the pick. * See \a wrapped_rr_closure for details. */ typedef struct pending_pick { - struct pending_pick *next; + struct pending_pick* next; /* original pick()'s arguments */ grpc_lb_policy_pick_args pick_args; /* output argument where to store the pick()ed connected subchannel, or NULL * upon error. */ - grpc_connected_subchannel **target; + grpc_connected_subchannel** target; /* args for wrapped_on_complete */ wrapped_rr_closure_arg wrapped_on_complete_arg; } pending_pick; -static void add_pending_pick(pending_pick **root, - const grpc_lb_policy_pick_args *pick_args, - grpc_connected_subchannel **target, - grpc_call_context_element *context, - grpc_closure *on_complete) { - pending_pick *pp = (pending_pick *)gpr_zalloc(sizeof(*pp)); +static void add_pending_pick(pending_pick** root, + const grpc_lb_policy_pick_args* pick_args, + grpc_connected_subchannel** target, + grpc_call_context_element* context, + grpc_closure* on_complete) { + pending_pick* pp = (pending_pick*)gpr_zalloc(sizeof(*pp)); pp->next = *root; pp->pick_args = *pick_args; pp->target = target; @@ -267,14 +273,14 @@ static void add_pending_pick(pending_pick **root, /* Same as the \a pending_pick struct but for ping operations */ typedef struct pending_ping { - struct pending_ping *next; + struct pending_ping* next; /* args for wrapped_notify */ wrapped_rr_closure_arg wrapped_notify_arg; } pending_ping; -static void add_pending_ping(pending_ping **root, grpc_closure *notify) { - pending_ping *pping = (pending_ping *)gpr_zalloc(sizeof(*pping)); +static void add_pending_ping(pending_ping** root, grpc_closure* notify) { + pending_ping* pping = (pending_ping*)gpr_zalloc(sizeof(*pping)); pping->wrapped_notify_arg.wrapped_closure = notify; pping->wrapped_notify_arg.free_when_done = pping; pping->next = *root; @@ -294,9 +300,9 @@ typedef struct glb_lb_policy { grpc_lb_policy base; /** who the client is trying to communicate with */ - const char *server_name; - grpc_client_channel_factory *cc_factory; - grpc_channel_args *args; + const char* server_name; + grpc_client_channel_factory* cc_factory; + grpc_channel_args* args; /** timeout in milliseconds for the LB call. 0 means no deadline. */ int lb_call_timeout_ms; @@ -306,13 +312,13 @@ typedef struct glb_lb_policy { int lb_fallback_timeout_ms; /** for communicating with the LB server */ - grpc_channel *lb_channel; + grpc_channel* lb_channel; /** response generator to inject address updates into \a lb_channel */ - grpc_fake_resolver_response_generator *response_generator; + grpc_fake_resolver_response_generator* response_generator; /** the RR policy to use of the backend servers returned by the LB server */ - grpc_lb_policy *rr_policy; + grpc_lb_policy* rr_policy; bool started_picking; @@ -324,7 +330,7 @@ typedef struct glb_lb_policy { /** stores the deserialized response from the LB. May be NULL until one such * response has arrived. */ - grpc_grpclb_serverlist *serverlist; + grpc_grpclb_serverlist* serverlist; /** Index into serverlist for next pick. * If the server at this index is a drop, we return a drop. @@ -332,13 +338,13 @@ typedef struct glb_lb_policy { size_t serverlist_index; /** stores the backend addresses from the resolver */ - grpc_lb_addresses *fallback_backend_addresses; + grpc_lb_addresses* fallback_backend_addresses; /** list of picks that are waiting on RR's policy connectivity */ - pending_pick *pending_picks; + pending_pick* pending_picks; /** list of pings that are waiting on RR's policy connectivity */ - pending_ping *pending_pings; + pending_ping* pending_pings; bool shutting_down; @@ -373,7 +379,7 @@ typedef struct glb_lb_policy { /* LB fallback timer callback. */ grpc_closure lb_on_fallback; - grpc_call *lb_call; /* streaming call to the LB server, */ + grpc_call* lb_call; /* streaming call to the LB server, */ grpc_metadata_array lb_initial_metadata_recv; /* initial MD from LB server */ grpc_metadata_array @@ -381,10 +387,10 @@ typedef struct glb_lb_policy { /* what's being sent to the LB server. Note that its value may vary if the LB * server indicates a redirect. */ - grpc_byte_buffer *lb_request_payload; + grpc_byte_buffer* lb_request_payload; /* response the LB server, if any. Processed in lb_on_response_received() */ - grpc_byte_buffer *lb_response_payload; + grpc_byte_buffer* lb_response_payload; /* call status code and details, set in lb_on_server_status_received() */ grpc_status_code lb_call_status; @@ -403,7 +409,7 @@ typedef struct glb_lb_policy { /* Stats for client-side load reporting. Should be unreffed and * recreated whenever lb_call is replaced. */ - grpc_grpclb_client_stats *client_stats; + grpc_grpclb_client_stats* client_stats; /* Interval and timer for next client load report. */ grpc_millis client_stats_report_interval; grpc_timer client_load_report_timer; @@ -413,20 +419,20 @@ typedef struct glb_lb_policy { * completion of sending the load report. */ grpc_closure client_load_report_closure; /* Client load report message payload. */ - grpc_byte_buffer *client_load_report_payload; + grpc_byte_buffer* client_load_report_payload; } glb_lb_policy; /* Keeps track and reacts to changes in connectivity of the RR instance */ struct rr_connectivity_data { grpc_closure on_change; grpc_connectivity_state state; - glb_lb_policy *glb_policy; + glb_lb_policy* glb_policy; }; -static bool is_server_valid(const grpc_grpclb_server *server, size_t idx, +static bool is_server_valid(const grpc_grpclb_server* server, size_t idx, bool log) { if (server->drop) return false; - const grpc_grpclb_ip_address *ip = &server->ip_address; + const grpc_grpclb_ip_address* ip = &server->ip_address; if (server->port >> 16 != 0) { if (log) { gpr_log(GPR_ERROR, @@ -448,17 +454,17 @@ static bool is_server_valid(const grpc_grpclb_server *server, size_t idx, } /* vtable for LB tokens in grpc_lb_addresses. */ -static void *lb_token_copy(void *token) { - return token == NULL - ? NULL - : (void *)GRPC_MDELEM_REF(grpc_mdelem{(uintptr_t)token}).payload; +static void* lb_token_copy(void* token) { + return token == nullptr + ? nullptr + : (void*)GRPC_MDELEM_REF(grpc_mdelem{(uintptr_t)token}).payload; } -static void lb_token_destroy(grpc_exec_ctx *exec_ctx, void *token) { - if (token != NULL) { +static void lb_token_destroy(grpc_exec_ctx* exec_ctx, void* token) { + if (token != nullptr) { GRPC_MDELEM_UNREF(exec_ctx, grpc_mdelem{(uintptr_t)token}); } } -static int lb_token_cmp(void *token1, void *token2) { +static int lb_token_cmp(void* token1, void* token2) { if (token1 > token2) return 1; if (token1 < token2) return -1; return 0; @@ -466,23 +472,23 @@ static int lb_token_cmp(void *token1, void *token2) { static const grpc_lb_user_data_vtable lb_token_vtable = { lb_token_copy, lb_token_destroy, lb_token_cmp}; -static void parse_server(const grpc_grpclb_server *server, - grpc_resolved_address *addr) { +static void parse_server(const grpc_grpclb_server* server, + grpc_resolved_address* addr) { memset(addr, 0, sizeof(*addr)); if (server->drop) return; const uint16_t netorder_port = htons((uint16_t)server->port); /* the addresses are given in binary format (a in(6)_addr struct) in * server->ip_address.bytes. */ - const grpc_grpclb_ip_address *ip = &server->ip_address; + const grpc_grpclb_ip_address* ip = &server->ip_address; if (ip->size == 4) { addr->len = sizeof(struct sockaddr_in); - struct sockaddr_in *addr4 = (struct sockaddr_in *)&addr->addr; + struct sockaddr_in* addr4 = (struct sockaddr_in*)&addr->addr; addr4->sin_family = AF_INET; memcpy(&addr4->sin_addr, ip->bytes, ip->size); addr4->sin_port = netorder_port; } else if (ip->size == 16) { addr->len = sizeof(struct sockaddr_in6); - struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&addr->addr; + struct sockaddr_in6* addr6 = (struct sockaddr_in6*)&addr->addr; addr6->sin6_family = AF_INET6; memcpy(&addr6->sin6_addr, ip->bytes, ip->size); addr6->sin6_port = netorder_port; @@ -490,15 +496,15 @@ static void parse_server(const grpc_grpclb_server *server, } /* Returns addresses extracted from \a serverlist. */ -static grpc_lb_addresses *process_serverlist_locked( - grpc_exec_ctx *exec_ctx, const grpc_grpclb_serverlist *serverlist) { +static grpc_lb_addresses* process_serverlist_locked( + grpc_exec_ctx* exec_ctx, const grpc_grpclb_serverlist* serverlist) { size_t num_valid = 0; /* first pass: count how many are valid in order to allocate the necessary * memory in a single block */ for (size_t i = 0; i < serverlist->num_servers; ++i) { if (is_server_valid(serverlist->servers[i], i, true)) ++num_valid; } - grpc_lb_addresses *lb_addresses = + grpc_lb_addresses* lb_addresses = grpc_lb_addresses_create(num_valid, &lb_token_vtable); /* second pass: actually populate the addresses and LB tokens (aka user data * to the outside world) to be read by the RR policy during its creation. @@ -507,14 +513,14 @@ static grpc_lb_addresses *process_serverlist_locked( * incurr in an allocation due to the arbitrary number of server */ size_t addr_idx = 0; for (size_t sl_idx = 0; sl_idx < serverlist->num_servers; ++sl_idx) { - const grpc_grpclb_server *server = serverlist->servers[sl_idx]; + const grpc_grpclb_server* server = serverlist->servers[sl_idx]; if (!is_server_valid(serverlist->servers[sl_idx], sl_idx, false)) continue; GPR_ASSERT(addr_idx < num_valid); /* address processing */ grpc_resolved_address addr; parse_server(server, &addr); /* lb token processing */ - void *user_data; + void* user_data; if (server->has_load_balance_token) { const size_t lb_token_max_length = GPR_ARRAY_SIZE(server->load_balance_token); @@ -522,22 +528,22 @@ static grpc_lb_addresses *process_serverlist_locked( strnlen(server->load_balance_token, lb_token_max_length); grpc_slice lb_token_mdstr = grpc_slice_from_copied_buffer( server->load_balance_token, lb_token_length); - user_data = (void *)grpc_mdelem_from_slices(exec_ctx, GRPC_MDSTR_LB_TOKEN, - lb_token_mdstr) + user_data = (void*)grpc_mdelem_from_slices(exec_ctx, GRPC_MDSTR_LB_TOKEN, + lb_token_mdstr) .payload; } else { - char *uri = grpc_sockaddr_to_uri(&addr); + char* uri = grpc_sockaddr_to_uri(&addr); gpr_log(GPR_INFO, "Missing LB token for backend address '%s'. The empty token will " "be used instead", uri); gpr_free(uri); - user_data = (void *)GRPC_MDELEM_LB_TOKEN_EMPTY.payload; + user_data = (void*)GRPC_MDELEM_LB_TOKEN_EMPTY.payload; } grpc_lb_addresses_set_address(lb_addresses, addr_idx, &addr.addr, addr.len, false /* is_balancer */, - NULL /* balancer_name */, user_data); + nullptr /* balancer_name */, user_data); ++addr_idx; } GPR_ASSERT(addr_idx == num_valid); @@ -545,8 +551,8 @@ static grpc_lb_addresses *process_serverlist_locked( } /* Returns the backend addresses extracted from the given addresses */ -static grpc_lb_addresses *extract_backend_addresses_locked( - grpc_exec_ctx *exec_ctx, const grpc_lb_addresses *addresses) { +static grpc_lb_addresses* extract_backend_addresses_locked( + grpc_exec_ctx* exec_ctx, const grpc_lb_addresses* addresses) { /* first pass: count the number of backend addresses */ size_t num_backends = 0; for (size_t i = 0; i < addresses->num_addresses; ++i) { @@ -555,24 +561,24 @@ static grpc_lb_addresses *extract_backend_addresses_locked( } } /* second pass: actually populate the addresses and (empty) LB tokens */ - grpc_lb_addresses *backend_addresses = + grpc_lb_addresses* backend_addresses = grpc_lb_addresses_create(num_backends, &lb_token_vtable); size_t num_copied = 0; for (size_t i = 0; i < addresses->num_addresses; ++i) { if (addresses->addresses[i].is_balancer) continue; - const grpc_resolved_address *addr = &addresses->addresses[i].address; + const grpc_resolved_address* addr = &addresses->addresses[i].address; grpc_lb_addresses_set_address(backend_addresses, num_copied, &addr->addr, addr->len, false /* is_balancer */, - NULL /* balancer_name */, - (void *)GRPC_MDELEM_LB_TOKEN_EMPTY.payload); + nullptr /* balancer_name */, + (void*)GRPC_MDELEM_LB_TOKEN_EMPTY.payload); ++num_copied; } return backend_addresses; } static void update_lb_connectivity_status_locked( - grpc_exec_ctx *exec_ctx, glb_lb_policy *glb_policy, - grpc_connectivity_state rr_state, grpc_error *rr_state_error) { + grpc_exec_ctx* exec_ctx, glb_lb_policy* glb_policy, + grpc_connectivity_state rr_state, grpc_error* rr_state_error) { const grpc_connectivity_state curr_glb_state = grpc_connectivity_state_check(&glb_policy->state_tracker); @@ -617,10 +623,12 @@ static void update_lb_connectivity_status_locked( GPR_ASSERT(rr_state_error == GRPC_ERROR_NONE); } - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { + if (grpc_lb_glb_trace.enabled()) { gpr_log( - GPR_INFO, "Setting grpclb's state to %s from new RR policy %p state.", - grpc_connectivity_state_name(rr_state), (void *)glb_policy->rr_policy); + GPR_INFO, + "[grpclb %p] Setting grpclb's state to %s from new RR policy %p state.", + glb_policy, grpc_connectivity_state_name(rr_state), + glb_policy->rr_policy); } grpc_connectivity_state_set(exec_ctx, &glb_policy->state_tracker, rr_state, rr_state_error, @@ -629,26 +637,26 @@ static void update_lb_connectivity_status_locked( /* Perform a pick over \a glb_policy->rr_policy. Given that a pick can return * immediately (ignoring its completion callback), we need to perform the - * cleanups this callback would otherwise be resposible for. + * cleanups this callback would otherwise be responsible for. * If \a force_async is true, then we will manually schedule the * completion callback even if the pick is available immediately. */ static bool pick_from_internal_rr_locked( - grpc_exec_ctx *exec_ctx, glb_lb_policy *glb_policy, - const grpc_lb_policy_pick_args *pick_args, bool force_async, - grpc_connected_subchannel **target, wrapped_rr_closure_arg *wc_arg) { + grpc_exec_ctx* exec_ctx, glb_lb_policy* glb_policy, + const grpc_lb_policy_pick_args* pick_args, bool force_async, + grpc_connected_subchannel** target, wrapped_rr_closure_arg* wc_arg) { // Check for drops if we are not using fallback backend addresses. - if (glb_policy->serverlist != NULL) { + if (glb_policy->serverlist != nullptr) { // Look at the index into the serverlist to see if we should drop this call. - grpc_grpclb_server *server = + grpc_grpclb_server* server = glb_policy->serverlist->servers[glb_policy->serverlist_index++]; if (glb_policy->serverlist_index == glb_policy->serverlist->num_servers) { glb_policy->serverlist_index = 0; // Wrap-around. } if (server->drop) { // Not using the RR policy, so unref it. - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { - gpr_log(GPR_INFO, "Unreffing RR for drop (0x%" PRIxPTR ")", - (intptr_t)wc_arg->rr_policy); + if (grpc_lb_glb_trace.enabled()) { + gpr_log(GPR_INFO, "[grpclb %p] Unreffing RR %p for drop", glb_policy, + wc_arg->rr_policy); } GRPC_LB_POLICY_UNREF(exec_ctx, wc_arg->rr_policy, "glb_pick_sync"); // Update client load reporting stats to indicate the number of @@ -656,11 +664,12 @@ static bool pick_from_internal_rr_locked( // the client_load_reporting filter, because we do not create a // subchannel call (and therefore no client_load_reporting filter) // for dropped calls. + GPR_ASSERT(wc_arg->client_stats != nullptr); grpc_grpclb_client_stats_add_call_dropped_locked( server->load_balance_token, wc_arg->client_stats); grpc_grpclb_client_stats_unref(wc_arg->client_stats); if (force_async) { - GPR_ASSERT(wc_arg->wrapped_closure != NULL); + GPR_ASSERT(wc_arg->wrapped_closure != nullptr); GRPC_CLOSURE_SCHED(exec_ctx, wc_arg->wrapped_closure, GRPC_ERROR_NONE); gpr_free(wc_arg->free_when_done); return false; @@ -672,12 +681,12 @@ static bool pick_from_internal_rr_locked( // Pick via the RR policy. const bool pick_done = grpc_lb_policy_pick_locked( exec_ctx, wc_arg->rr_policy, pick_args, target, wc_arg->context, - (void **)&wc_arg->lb_token, &wc_arg->wrapper_closure); + (void**)&wc_arg->lb_token, &wc_arg->wrapper_closure); if (pick_done) { /* synchronous grpc_lb_policy_pick call. Unref the RR policy. */ - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { - gpr_log(GPR_INFO, "Unreffing RR (0x%" PRIxPTR ")", - (intptr_t)wc_arg->rr_policy); + if (grpc_lb_glb_trace.enabled()) { + gpr_log(GPR_INFO, "[grpclb %p] Unreffing RR %p", glb_policy, + wc_arg->rr_policy); } GRPC_LB_POLICY_UNREF(exec_ctx, wc_arg->rr_policy, "glb_pick_sync"); /* add the load reporting initial metadata */ @@ -685,11 +694,11 @@ static bool pick_from_internal_rr_locked( pick_args->lb_token_mdelem_storage, GRPC_MDELEM_REF(wc_arg->lb_token)); // Pass on client stats via context. Passes ownership of the reference. - GPR_ASSERT(wc_arg->client_stats != NULL); + GPR_ASSERT(wc_arg->client_stats != nullptr); wc_arg->context[GRPC_GRPCLB_CLIENT_STATS].value = wc_arg->client_stats; wc_arg->context[GRPC_GRPCLB_CLIENT_STATS].destroy = destroy_client_stats; if (force_async) { - GPR_ASSERT(wc_arg->wrapped_closure != NULL); + GPR_ASSERT(wc_arg->wrapped_closure != nullptr); GRPC_CLOSURE_SCHED(exec_ctx, wc_arg->wrapped_closure, GRPC_ERROR_NONE); gpr_free(wc_arg->free_when_done); return false; @@ -703,10 +712,10 @@ static bool pick_from_internal_rr_locked( return pick_done; } -static grpc_lb_policy_args *lb_policy_args_create(grpc_exec_ctx *exec_ctx, - glb_lb_policy *glb_policy) { - grpc_lb_addresses *addresses; - if (glb_policy->serverlist != NULL) { +static grpc_lb_policy_args* lb_policy_args_create(grpc_exec_ctx* exec_ctx, + glb_lb_policy* glb_policy) { + grpc_lb_addresses* addresses; + if (glb_policy->serverlist != nullptr) { GPR_ASSERT(glb_policy->serverlist->num_servers > 0); addresses = process_serverlist_locked(exec_ctx, glb_policy->serverlist); } else { @@ -714,16 +723,16 @@ static grpc_lb_policy_args *lb_policy_args_create(grpc_exec_ctx *exec_ctx, // serverlist from the balancer, we use the fallback backends returned by // the resolver. Note that the fallback backend list may be empty, in which // case the new round_robin policy will keep the requested picks pending. - GPR_ASSERT(glb_policy->fallback_backend_addresses != NULL); + GPR_ASSERT(glb_policy->fallback_backend_addresses != nullptr); addresses = grpc_lb_addresses_copy(glb_policy->fallback_backend_addresses); } - GPR_ASSERT(addresses != NULL); - grpc_lb_policy_args *args = (grpc_lb_policy_args *)gpr_zalloc(sizeof(*args)); + GPR_ASSERT(addresses != nullptr); + grpc_lb_policy_args* args = (grpc_lb_policy_args*)gpr_zalloc(sizeof(*args)); args->client_channel_factory = glb_policy->cc_factory; args->combiner = glb_policy->base.combiner; // Replace the LB addresses in the channel args that we pass down to // the subchannel. - static const char *keys_to_remove[] = {GRPC_ARG_LB_ADDRESSES}; + static const char* keys_to_remove[] = {GRPC_ARG_LB_ADDRESSES}; const grpc_arg arg = grpc_lb_addresses_create_channel_arg(addresses); args->args = grpc_channel_args_copy_and_add_and_remove( glb_policy->args, keys_to_remove, GPR_ARRAY_SIZE(keys_to_remove), &arg, @@ -732,32 +741,36 @@ static grpc_lb_policy_args *lb_policy_args_create(grpc_exec_ctx *exec_ctx, return args; } -static void lb_policy_args_destroy(grpc_exec_ctx *exec_ctx, - grpc_lb_policy_args *args) { +static void lb_policy_args_destroy(grpc_exec_ctx* exec_ctx, + grpc_lb_policy_args* args) { grpc_channel_args_destroy(exec_ctx, args->args); gpr_free(args); } -static void glb_rr_connectivity_changed_locked(grpc_exec_ctx *exec_ctx, - void *arg, grpc_error *error); -static void create_rr_locked(grpc_exec_ctx *exec_ctx, glb_lb_policy *glb_policy, - grpc_lb_policy_args *args) { - GPR_ASSERT(glb_policy->rr_policy == NULL); +static void glb_rr_connectivity_changed_locked(grpc_exec_ctx* exec_ctx, + void* arg, grpc_error* error); +static void create_rr_locked(grpc_exec_ctx* exec_ctx, glb_lb_policy* glb_policy, + grpc_lb_policy_args* args) { + GPR_ASSERT(glb_policy->rr_policy == nullptr); - grpc_lb_policy *new_rr_policy = + grpc_lb_policy* new_rr_policy = grpc_lb_policy_create(exec_ctx, "round_robin", args); - if (new_rr_policy == NULL) { + if (new_rr_policy == nullptr) { gpr_log(GPR_ERROR, - "Failure creating a RoundRobin policy for serverlist update with " - "%lu entries. The previous RR instance (%p), if any, will continue " - "to be used. Future updates from the LB will attempt to create new " + "[grpclb %p] Failure creating a RoundRobin policy for serverlist " + "update with %" PRIuPTR + " entries. The previous RR instance (%p), if any, will continue to " + "be used. Future updates from the LB will attempt to create new " "instances.", - (unsigned long)glb_policy->serverlist->num_servers, - (void *)glb_policy->rr_policy); + glb_policy, glb_policy->serverlist->num_servers, + glb_policy->rr_policy); return; } + grpc_lb_policy_set_reresolve_closure_locked( + exec_ctx, new_rr_policy, glb_policy->base.request_reresolution); + glb_policy->base.request_reresolution = nullptr; glb_policy->rr_policy = new_rr_policy; - grpc_error *rr_state_error = NULL; + grpc_error* rr_state_error = nullptr; const grpc_connectivity_state rr_state = grpc_lb_policy_check_connectivity_locked(exec_ctx, glb_policy->rr_policy, &rr_state_error); @@ -773,8 +786,8 @@ static void create_rr_locked(grpc_exec_ctx *exec_ctx, glb_lb_policy *glb_policy, /* Allocate the data for the tracking of the new RR policy's connectivity. * It'll be deallocated in glb_rr_connectivity_changed() */ - rr_connectivity_data *rr_connectivity = - (rr_connectivity_data *)gpr_zalloc(sizeof(rr_connectivity_data)); + rr_connectivity_data* rr_connectivity = + (rr_connectivity_data*)gpr_zalloc(sizeof(rr_connectivity_data)); GRPC_CLOSURE_INIT(&rr_connectivity->on_change, glb_rr_connectivity_changed_locked, rr_connectivity, grpc_combiner_scheduler(glb_policy->base.combiner)); @@ -789,30 +802,31 @@ static void create_rr_locked(grpc_exec_ctx *exec_ctx, glb_lb_policy *glb_policy, grpc_lb_policy_exit_idle_locked(exec_ctx, glb_policy->rr_policy); /* Update picks and pings in wait */ - pending_pick *pp; + pending_pick* pp; while ((pp = glb_policy->pending_picks)) { glb_policy->pending_picks = pp->next; GRPC_LB_POLICY_REF(glb_policy->rr_policy, "rr_handover_pending_pick"); pp->wrapped_on_complete_arg.rr_policy = glb_policy->rr_policy; pp->wrapped_on_complete_arg.client_stats = grpc_grpclb_client_stats_ref(glb_policy->client_stats); - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { - gpr_log(GPR_INFO, "Pending pick about to (async) PICK from %p", - (void *)glb_policy->rr_policy); + if (grpc_lb_glb_trace.enabled()) { + gpr_log(GPR_INFO, + "[grpclb %p] Pending pick about to (async) PICK from RR %p", + glb_policy, glb_policy->rr_policy); } pick_from_internal_rr_locked(exec_ctx, glb_policy, &pp->pick_args, true /* force_async */, pp->target, &pp->wrapped_on_complete_arg); } - pending_ping *pping; + pending_ping* pping; while ((pping = glb_policy->pending_pings)) { glb_policy->pending_pings = pping->next; GRPC_LB_POLICY_REF(glb_policy->rr_policy, "rr_handover_pending_ping"); pping->wrapped_notify_arg.rr_policy = glb_policy->rr_policy; - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { - gpr_log(GPR_INFO, "Pending ping about to PING from 0x%" PRIxPTR "", - (intptr_t)glb_policy->rr_policy); + if (grpc_lb_glb_trace.enabled()) { + gpr_log(GPR_INFO, "[grpclb %p] Pending ping about to PING from RR %p", + glb_policy, glb_policy->rr_policy); } grpc_lb_policy_ping_one_locked(exec_ctx, glb_policy->rr_policy, &pping->wrapped_notify_arg.wrapper_closure); @@ -820,31 +834,31 @@ static void create_rr_locked(grpc_exec_ctx *exec_ctx, glb_lb_policy *glb_policy, } /* glb_policy->rr_policy may be NULL (initial handover) */ -static void rr_handover_locked(grpc_exec_ctx *exec_ctx, - glb_lb_policy *glb_policy) { +static void rr_handover_locked(grpc_exec_ctx* exec_ctx, + glb_lb_policy* glb_policy) { if (glb_policy->shutting_down) return; - grpc_lb_policy_args *args = lb_policy_args_create(exec_ctx, glb_policy); - GPR_ASSERT(args != NULL); - if (glb_policy->rr_policy != NULL) { - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { - gpr_log(GPR_DEBUG, "Updating Round Robin policy (%p)", - (void *)glb_policy->rr_policy); + grpc_lb_policy_args* args = lb_policy_args_create(exec_ctx, glb_policy); + GPR_ASSERT(args != nullptr); + if (glb_policy->rr_policy != nullptr) { + if (grpc_lb_glb_trace.enabled()) { + gpr_log(GPR_DEBUG, "[grpclb %p] Updating RR policy %p", glb_policy, + glb_policy->rr_policy); } grpc_lb_policy_update_locked(exec_ctx, glb_policy->rr_policy, args); } else { create_rr_locked(exec_ctx, glb_policy, args); - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { - gpr_log(GPR_DEBUG, "Created new Round Robin policy (%p)", - (void *)glb_policy->rr_policy); + if (grpc_lb_glb_trace.enabled()) { + gpr_log(GPR_DEBUG, "[grpclb %p] Created new RR policy %p", glb_policy, + glb_policy->rr_policy); } } lb_policy_args_destroy(exec_ctx, args); } -static void glb_rr_connectivity_changed_locked(grpc_exec_ctx *exec_ctx, - void *arg, grpc_error *error) { - rr_connectivity_data *rr_connectivity = (rr_connectivity_data *)arg; - glb_lb_policy *glb_policy = rr_connectivity->glb_policy; +static void glb_rr_connectivity_changed_locked(grpc_exec_ctx* exec_ctx, + void* arg, grpc_error* error) { + rr_connectivity_data* rr_connectivity = (rr_connectivity_data*)arg; + glb_lb_policy* glb_policy = rr_connectivity->glb_policy; if (glb_policy->shutting_down) { GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base, "glb_rr_connectivity_cb"); @@ -857,7 +871,7 @@ static void glb_rr_connectivity_changed_locked(grpc_exec_ctx *exec_ctx, * sink, policies can't transition back from it. .*/ GRPC_LB_POLICY_UNREF(exec_ctx, glb_policy->rr_policy, "rr_connectivity_shutdown"); - glb_policy->rr_policy = NULL; + glb_policy->rr_policy = nullptr; GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base, "glb_rr_connectivity_cb"); gpr_free(rr_connectivity); @@ -872,22 +886,22 @@ static void glb_rr_connectivity_changed_locked(grpc_exec_ctx *exec_ctx, &rr_connectivity->on_change); } -static void destroy_balancer_name(grpc_exec_ctx *exec_ctx, - void *balancer_name) { +static void destroy_balancer_name(grpc_exec_ctx* exec_ctx, + void* balancer_name) { gpr_free(balancer_name); } static grpc_slice_hash_table_entry targets_info_entry_create( - const char *address, const char *balancer_name) { + const char* address, const char* balancer_name) { grpc_slice_hash_table_entry entry; entry.key = grpc_slice_from_copied_string(address); entry.value = gpr_strdup(balancer_name); return entry; } -static int balancer_name_cmp_fn(void *a, void *b) { - const char *a_str = (const char *)a; - const char *b_str = (const char *)b; +static int balancer_name_cmp_fn(void* a, void* b) { + const char* a_str = (const char*)a; + const char* b_str = (const char*)b; return strcmp(a_str, b_str); } @@ -899,10 +913,10 @@ static int balancer_name_cmp_fn(void *a, void *b) { * - \a response_generator: in order to propagate updates from the resolver * above the grpclb policy. * - \a args: other args inherited from the grpclb policy. */ -static grpc_channel_args *build_lb_channel_args( - grpc_exec_ctx *exec_ctx, const grpc_lb_addresses *addresses, - grpc_fake_resolver_response_generator *response_generator, - const grpc_channel_args *args) { +static grpc_channel_args* build_lb_channel_args( + grpc_exec_ctx* exec_ctx, const grpc_lb_addresses* addresses, + grpc_fake_resolver_response_generator* response_generator, + const grpc_channel_args* args) { size_t num_grpclb_addrs = 0; for (size_t i = 0; i < addresses->num_addresses; ++i) { if (addresses->addresses[i].is_balancer) ++num_grpclb_addrs; @@ -911,20 +925,20 @@ static grpc_channel_args *build_lb_channel_args( * It's the resolver's responsibility to make sure this policy is only * instantiated and used in that case. Otherwise, something has gone wrong. */ GPR_ASSERT(num_grpclb_addrs > 0); - grpc_lb_addresses *lb_addresses = - grpc_lb_addresses_create(num_grpclb_addrs, NULL); - grpc_slice_hash_table_entry *targets_info_entries = - (grpc_slice_hash_table_entry *)gpr_zalloc(sizeof(*targets_info_entries) * - num_grpclb_addrs); + grpc_lb_addresses* lb_addresses = + grpc_lb_addresses_create(num_grpclb_addrs, nullptr); + grpc_slice_hash_table_entry* targets_info_entries = + (grpc_slice_hash_table_entry*)gpr_zalloc(sizeof(*targets_info_entries) * + num_grpclb_addrs); size_t lb_addresses_idx = 0; for (size_t i = 0; i < addresses->num_addresses; ++i) { if (!addresses->addresses[i].is_balancer) continue; - if (addresses->addresses[i].user_data != NULL) { + if (addresses->addresses[i].user_data != nullptr) { gpr_log(GPR_ERROR, "This LB policy doesn't support user data. It will be ignored"); } - char *addr_str; + char* addr_str; GPR_ASSERT(grpc_sockaddr_to_string( &addr_str, &addresses->addresses[i].address, true) > 0); targets_info_entries[lb_addresses_idx] = targets_info_entry_create( @@ -934,22 +948,22 @@ static grpc_channel_args *build_lb_channel_args( grpc_lb_addresses_set_address( lb_addresses, lb_addresses_idx++, addresses->addresses[i].address.addr, addresses->addresses[i].address.len, false /* is balancer */, - addresses->addresses[i].balancer_name, NULL /* user data */); + addresses->addresses[i].balancer_name, nullptr /* user data */); } GPR_ASSERT(num_grpclb_addrs == lb_addresses_idx); - grpc_slice_hash_table *targets_info = + grpc_slice_hash_table* targets_info = grpc_slice_hash_table_create(num_grpclb_addrs, targets_info_entries, destroy_balancer_name, balancer_name_cmp_fn); gpr_free(targets_info_entries); - grpc_channel_args *lb_channel_args = + grpc_channel_args* lb_channel_args = grpc_lb_policy_grpclb_build_lb_channel_args(exec_ctx, targets_info, response_generator, args); grpc_arg lb_channel_addresses_arg = grpc_lb_addresses_create_channel_arg(lb_addresses); - grpc_channel_args *result = grpc_channel_args_copy_and_add( + grpc_channel_args* result = grpc_channel_args_copy_and_add( lb_channel_args, &lb_channel_addresses_arg, 1); grpc_slice_hash_table_unref(exec_ctx, targets_info); grpc_channel_args_destroy(exec_ctx, lb_channel_args); @@ -957,20 +971,20 @@ static grpc_channel_args *build_lb_channel_args( return result; } -static void glb_destroy(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { - glb_lb_policy *glb_policy = (glb_lb_policy *)pol; - GPR_ASSERT(glb_policy->pending_picks == NULL); - GPR_ASSERT(glb_policy->pending_pings == NULL); - gpr_free((void *)glb_policy->server_name); +static void glb_destroy(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol) { + glb_lb_policy* glb_policy = (glb_lb_policy*)pol; + GPR_ASSERT(glb_policy->pending_picks == nullptr); + GPR_ASSERT(glb_policy->pending_pings == nullptr); + gpr_free((void*)glb_policy->server_name); grpc_channel_args_destroy(exec_ctx, glb_policy->args); - if (glb_policy->client_stats != NULL) { + if (glb_policy->client_stats != nullptr) { grpc_grpclb_client_stats_unref(glb_policy->client_stats); } grpc_connectivity_state_destroy(exec_ctx, &glb_policy->state_tracker); - if (glb_policy->serverlist != NULL) { + if (glb_policy->serverlist != nullptr) { grpc_grpclb_destroy_serverlist(glb_policy->serverlist); } - if (glb_policy->fallback_backend_addresses != NULL) { + if (glb_policy->fallback_backend_addresses != nullptr) { grpc_lb_addresses_destroy(exec_ctx, glb_policy->fallback_backend_addresses); } grpc_fake_resolver_response_generator_unref(glb_policy->response_generator); @@ -978,21 +992,22 @@ static void glb_destroy(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { gpr_free(glb_policy); } -static void glb_shutdown_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { - glb_lb_policy *glb_policy = (glb_lb_policy *)pol; +static void glb_shutdown_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol) { + glb_lb_policy* glb_policy = (glb_lb_policy*)pol; + grpc_error* error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Channel shutdown"); glb_policy->shutting_down = true; /* We need a copy of the lb_call pointer because we can't cancell the call * while holding glb_policy->mu: lb_on_server_status_received, invoked due to * the cancel, needs to acquire that same lock */ - grpc_call *lb_call = glb_policy->lb_call; + grpc_call* lb_call = glb_policy->lb_call; /* glb_policy->lb_call and this local lb_call must be consistent at this point * because glb_policy->lb_call is only assigned in lb_call_init_locked as part * of query_for_backends_locked, which can only be invoked while * glb_policy->shutting_down is false. */ - if (lb_call != NULL) { - grpc_call_cancel(lb_call, NULL); + if (lb_call != nullptr) { + grpc_call_cancel(lb_call, nullptr); /* lb_on_server_status_received will pick up the cancel and clean up */ } if (glb_policy->retry_timer_active) { @@ -1004,43 +1019,45 @@ static void glb_shutdown_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { glb_policy->fallback_timer_active = false; } - pending_pick *pp = glb_policy->pending_picks; - glb_policy->pending_picks = NULL; - pending_ping *pping = glb_policy->pending_pings; - glb_policy->pending_pings = NULL; - if (glb_policy->rr_policy != NULL) { + pending_pick* pp = glb_policy->pending_picks; + glb_policy->pending_picks = nullptr; + pending_ping* pping = glb_policy->pending_pings; + glb_policy->pending_pings = nullptr; + if (glb_policy->rr_policy != nullptr) { GRPC_LB_POLICY_UNREF(exec_ctx, glb_policy->rr_policy, "glb_shutdown"); + } else { + grpc_lb_policy_try_reresolve(exec_ctx, pol, &grpc_lb_glb_trace, + GRPC_ERROR_CANCELLED); } // We destroy the LB channel here because // glb_lb_channel_on_connectivity_changed_cb needs a valid glb_policy // instance. Destroying the lb channel in glb_destroy would likely result in // a callback invocation without a valid glb_policy arg. - if (glb_policy->lb_channel != NULL) { + if (glb_policy->lb_channel != nullptr) { grpc_channel_destroy(glb_policy->lb_channel); - glb_policy->lb_channel = NULL; - } - grpc_connectivity_state_set( - exec_ctx, &glb_policy->state_tracker, GRPC_CHANNEL_SHUTDOWN, - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Channel Shutdown"), "glb_shutdown"); - - while (pp != NULL) { - pending_pick *next = pp->next; - *pp->target = NULL; - GRPC_CLOSURE_SCHED( - exec_ctx, &pp->wrapped_on_complete_arg.wrapper_closure, - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Channel Shutdown")); + glb_policy->lb_channel = nullptr; + } + grpc_connectivity_state_set(exec_ctx, &glb_policy->state_tracker, + GRPC_CHANNEL_SHUTDOWN, GRPC_ERROR_REF(error), + "glb_shutdown"); + + while (pp != nullptr) { + pending_pick* next = pp->next; + *pp->target = nullptr; + GRPC_CLOSURE_SCHED(exec_ctx, &pp->wrapped_on_complete_arg.wrapper_closure, + GRPC_ERROR_REF(error)); gpr_free(pp); pp = next; } - while (pping != NULL) { - pending_ping *next = pping->next; - GRPC_CLOSURE_SCHED( - exec_ctx, &pping->wrapped_notify_arg.wrapper_closure, - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Channel Shutdown")); + while (pping != nullptr) { + pending_ping* next = pping->next; + GRPC_CLOSURE_SCHED(exec_ctx, &pping->wrapped_notify_arg.wrapper_closure, + GRPC_ERROR_REF(error)); gpr_free(pping); pping = next; } + GRPC_ERROR_UNREF(error); } // Cancel a specific pending pick. @@ -1053,16 +1070,16 @@ static void glb_shutdown_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { // - Otherwise, without an RR instance, picks stay pending at this policy's // level (grpclb), inside the glb_policy->pending_picks list. To cancel these, // we invoke the completion closure and set *target to NULL right here. -static void glb_cancel_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, - grpc_connected_subchannel **target, - grpc_error *error) { - glb_lb_policy *glb_policy = (glb_lb_policy *)pol; - pending_pick *pp = glb_policy->pending_picks; - glb_policy->pending_picks = NULL; - while (pp != NULL) { - pending_pick *next = pp->next; +static void glb_cancel_pick_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol, + grpc_connected_subchannel** target, + grpc_error* error) { + glb_lb_policy* glb_policy = (glb_lb_policy*)pol; + pending_pick* pp = glb_policy->pending_picks; + glb_policy->pending_picks = nullptr; + while (pp != nullptr) { + pending_pick* next = pp->next; if (pp->target == target) { - *target = NULL; + *target = nullptr; GRPC_CLOSURE_SCHED(exec_ctx, &pp->wrapped_on_complete_arg.wrapper_closure, GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Pick Cancelled", &error, 1)); @@ -1072,7 +1089,7 @@ static void glb_cancel_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, } pp = next; } - if (glb_policy->rr_policy != NULL) { + if (glb_policy->rr_policy != nullptr) { grpc_lb_policy_cancel_pick_locked(exec_ctx, glb_policy->rr_policy, target, GRPC_ERROR_REF(error)); } @@ -1089,16 +1106,16 @@ static void glb_cancel_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, // - Otherwise, without an RR instance, picks stay pending at this policy's // level (grpclb), inside the glb_policy->pending_picks list. To cancel these, // we invoke the completion closure and set *target to NULL right here. -static void glb_cancel_picks_locked(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *pol, +static void glb_cancel_picks_locked(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* pol, uint32_t initial_metadata_flags_mask, uint32_t initial_metadata_flags_eq, - grpc_error *error) { - glb_lb_policy *glb_policy = (glb_lb_policy *)pol; - pending_pick *pp = glb_policy->pending_picks; - glb_policy->pending_picks = NULL; - while (pp != NULL) { - pending_pick *next = pp->next; + grpc_error* error) { + glb_lb_policy* glb_policy = (glb_lb_policy*)pol; + pending_pick* pp = glb_policy->pending_picks; + glb_policy->pending_picks = nullptr; + while (pp != nullptr) { + pending_pick* next = pp->next; if ((pp->pick_args.initial_metadata_flags & initial_metadata_flags_mask) == initial_metadata_flags_eq) { GRPC_CLOSURE_SCHED(exec_ctx, &pp->wrapped_on_complete_arg.wrapper_closure, @@ -1110,7 +1127,7 @@ static void glb_cancel_picks_locked(grpc_exec_ctx *exec_ctx, } pp = next; } - if (glb_policy->rr_policy != NULL) { + if (glb_policy->rr_policy != nullptr) { grpc_lb_policy_cancel_picks_locked( exec_ctx, glb_policy->rr_policy, initial_metadata_flags_mask, initial_metadata_flags_eq, GRPC_ERROR_REF(error)); @@ -1118,15 +1135,15 @@ static void glb_cancel_picks_locked(grpc_exec_ctx *exec_ctx, GRPC_ERROR_UNREF(error); } -static void lb_on_fallback_timer_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error); -static void query_for_backends_locked(grpc_exec_ctx *exec_ctx, - glb_lb_policy *glb_policy); -static void start_picking_locked(grpc_exec_ctx *exec_ctx, - glb_lb_policy *glb_policy) { +static void lb_on_fallback_timer_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error); +static void query_for_backends_locked(grpc_exec_ctx* exec_ctx, + glb_lb_policy* glb_policy); +static void start_picking_locked(grpc_exec_ctx* exec_ctx, + glb_lb_policy* glb_policy) { /* start a timer to fall back */ if (glb_policy->lb_fallback_timeout_ms > 0 && - glb_policy->serverlist == NULL && !glb_policy->fallback_timer_active) { + glb_policy->serverlist == nullptr && !glb_policy->fallback_timer_active) { grpc_millis deadline = grpc_exec_ctx_now(exec_ctx) + glb_policy->lb_fallback_timeout_ms; GRPC_LB_POLICY_WEAK_REF(&glb_policy->base, "grpclb_fallback_timer"); @@ -1143,65 +1160,80 @@ static void start_picking_locked(grpc_exec_ctx *exec_ctx, query_for_backends_locked(exec_ctx, glb_policy); } -static void glb_exit_idle_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { - glb_lb_policy *glb_policy = (glb_lb_policy *)pol; +static void glb_exit_idle_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol) { + glb_lb_policy* glb_policy = (glb_lb_policy*)pol; if (!glb_policy->started_picking) { start_picking_locked(exec_ctx, glb_policy); } } -static int glb_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, - const grpc_lb_policy_pick_args *pick_args, - grpc_connected_subchannel **target, - grpc_call_context_element *context, void **user_data, - grpc_closure *on_complete) { - if (pick_args->lb_token_mdelem_storage == NULL) { - *target = NULL; +static int glb_pick_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol, + const grpc_lb_policy_pick_args* pick_args, + grpc_connected_subchannel** target, + grpc_call_context_element* context, void** user_data, + grpc_closure* on_complete) { + if (pick_args->lb_token_mdelem_storage == nullptr) { + *target = nullptr; GRPC_CLOSURE_SCHED(exec_ctx, on_complete, GRPC_ERROR_CREATE_FROM_STATIC_STRING( "No mdelem storage for the LB token. Load reporting " "won't work without it. Failing")); return 0; } - - glb_lb_policy *glb_policy = (glb_lb_policy *)pol; - bool pick_done; - - if (glb_policy->rr_policy != NULL) { - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { - gpr_log(GPR_INFO, "grpclb %p about to PICK from RR %p", - (void *)glb_policy, (void *)glb_policy->rr_policy); + glb_lb_policy* glb_policy = (glb_lb_policy*)pol; + bool pick_done = false; + if (glb_policy->rr_policy != nullptr) { + const grpc_connectivity_state rr_connectivity_state = + grpc_lb_policy_check_connectivity_locked( + exec_ctx, glb_policy->rr_policy, nullptr); + // The glb_policy->rr_policy may have transitioned to SHUTDOWN but the + // callback registered to capture this event + // (glb_rr_connectivity_changed_locked) may not have been invoked yet. We + // need to make sure we aren't trying to pick from a RR policy instance + // that's in shutdown. + if (rr_connectivity_state == GRPC_CHANNEL_SHUTDOWN) { + if (grpc_lb_glb_trace.enabled()) { + gpr_log(GPR_INFO, + "[grpclb %p] NOT picking from from RR %p: RR conn state=%s", + glb_policy, glb_policy->rr_policy, + grpc_connectivity_state_name(rr_connectivity_state)); + } + add_pending_pick(&glb_policy->pending_picks, pick_args, target, context, + on_complete); + pick_done = false; + } else { // RR not in shutdown + if (grpc_lb_glb_trace.enabled()) { + gpr_log(GPR_INFO, "[grpclb %p] about to PICK from RR %p", glb_policy, + glb_policy->rr_policy); + } + GRPC_LB_POLICY_REF(glb_policy->rr_policy, "glb_pick"); + wrapped_rr_closure_arg* wc_arg = + (wrapped_rr_closure_arg*)gpr_zalloc(sizeof(wrapped_rr_closure_arg)); + GRPC_CLOSURE_INIT(&wc_arg->wrapper_closure, wrapped_rr_closure, wc_arg, + grpc_schedule_on_exec_ctx); + wc_arg->rr_policy = glb_policy->rr_policy; + wc_arg->target = target; + wc_arg->context = context; + GPR_ASSERT(glb_policy->client_stats != nullptr); + wc_arg->client_stats = + grpc_grpclb_client_stats_ref(glb_policy->client_stats); + wc_arg->wrapped_closure = on_complete; + wc_arg->lb_token_mdelem_storage = pick_args->lb_token_mdelem_storage; + wc_arg->initial_metadata = pick_args->initial_metadata; + wc_arg->free_when_done = wc_arg; + wc_arg->glb_policy = pol; + pick_done = + pick_from_internal_rr_locked(exec_ctx, glb_policy, pick_args, + false /* force_async */, target, wc_arg); } - GRPC_LB_POLICY_REF(glb_policy->rr_policy, "glb_pick"); - - wrapped_rr_closure_arg *wc_arg = - (wrapped_rr_closure_arg *)gpr_zalloc(sizeof(wrapped_rr_closure_arg)); - - GRPC_CLOSURE_INIT(&wc_arg->wrapper_closure, wrapped_rr_closure, wc_arg, - grpc_schedule_on_exec_ctx); - wc_arg->rr_policy = glb_policy->rr_policy; - wc_arg->target = target; - wc_arg->context = context; - GPR_ASSERT(glb_policy->client_stats != NULL); - wc_arg->client_stats = - grpc_grpclb_client_stats_ref(glb_policy->client_stats); - wc_arg->wrapped_closure = on_complete; - wc_arg->lb_token_mdelem_storage = pick_args->lb_token_mdelem_storage; - wc_arg->initial_metadata = pick_args->initial_metadata; - wc_arg->free_when_done = wc_arg; - pick_done = - pick_from_internal_rr_locked(exec_ctx, glb_policy, pick_args, - false /* force_async */, target, wc_arg); - } else { - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { + } else { // glb_policy->rr_policy == NULL + if (grpc_lb_glb_trace.enabled()) { gpr_log(GPR_DEBUG, - "No RR policy in grpclb instance %p. Adding to grpclb's pending " - "picks", - (void *)(glb_policy)); + "[grpclb %p] No RR policy. Adding to grpclb's pending picks", + glb_policy); } add_pending_pick(&glb_policy->pending_picks, pick_args, target, context, on_complete); - if (!glb_policy->started_picking) { start_picking_locked(exec_ctx, glb_policy); } @@ -1211,16 +1243,16 @@ static int glb_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, } static grpc_connectivity_state glb_check_connectivity_locked( - grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, - grpc_error **connectivity_error) { - glb_lb_policy *glb_policy = (glb_lb_policy *)pol; + grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol, + grpc_error** connectivity_error) { + glb_lb_policy* glb_policy = (glb_lb_policy*)pol; return grpc_connectivity_state_get(&glb_policy->state_tracker, connectivity_error); } -static void glb_ping_one_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, - grpc_closure *closure) { - glb_lb_policy *glb_policy = (glb_lb_policy *)pol; +static void glb_ping_one_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol, + grpc_closure* closure) { + glb_lb_policy* glb_policy = (glb_lb_policy*)pol; if (glb_policy->rr_policy) { grpc_lb_policy_ping_one_locked(exec_ctx, glb_policy->rr_policy, closure); } else { @@ -1231,32 +1263,31 @@ static void glb_ping_one_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, } } -static void glb_notify_on_state_change_locked(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *pol, - grpc_connectivity_state *current, - grpc_closure *notify) { - glb_lb_policy *glb_policy = (glb_lb_policy *)pol; +static void glb_notify_on_state_change_locked(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* pol, + grpc_connectivity_state* current, + grpc_closure* notify) { + glb_lb_policy* glb_policy = (glb_lb_policy*)pol; grpc_connectivity_state_notify_on_state_change( exec_ctx, &glb_policy->state_tracker, current, notify); } -static void lb_call_on_retry_timer_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - glb_lb_policy *glb_policy = (glb_lb_policy *)arg; +static void lb_call_on_retry_timer_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + glb_lb_policy* glb_policy = (glb_lb_policy*)arg; glb_policy->retry_timer_active = false; - if (!glb_policy->shutting_down && error == GRPC_ERROR_NONE) { - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { - gpr_log(GPR_INFO, "Restaring call to LB server (grpclb %p)", - (void *)glb_policy); + if (!glb_policy->shutting_down && glb_policy->lb_call == nullptr && + error == GRPC_ERROR_NONE) { + if (grpc_lb_glb_trace.enabled()) { + gpr_log(GPR_INFO, "[grpclb %p] Restarting call to LB server", glb_policy); } - GPR_ASSERT(glb_policy->lb_call == NULL); query_for_backends_locked(exec_ctx, glb_policy); } GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base, "grpclb_retry_timer"); } -static void maybe_restart_lb_call(grpc_exec_ctx *exec_ctx, - glb_lb_policy *glb_policy) { +static void maybe_restart_lb_call(grpc_exec_ctx* exec_ctx, + glb_lb_policy* glb_policy) { if (glb_policy->started_picking && glb_policy->updating_lb_call) { if (glb_policy->retry_timer_active) { grpc_timer_cancel(exec_ctx, &glb_policy->lb_call_retry_timer); @@ -1266,16 +1297,19 @@ static void maybe_restart_lb_call(grpc_exec_ctx *exec_ctx, } else if (!glb_policy->shutting_down) { /* if we aren't shutting down, restart the LB client call after some time */ grpc_millis next_try = - grpc_backoff_step(exec_ctx, &glb_policy->lb_call_backoff_state); - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { - gpr_log(GPR_DEBUG, "Connection to LB server lost (grpclb: %p)...", - (void *)glb_policy); + grpc_backoff_step(exec_ctx, &glb_policy->lb_call_backoff_state) + .next_attempt_start_time; + if (grpc_lb_glb_trace.enabled()) { + gpr_log(GPR_DEBUG, "[grpclb %p] Connection to LB server lost...", + glb_policy); grpc_millis timeout = next_try - grpc_exec_ctx_now(exec_ctx); if (timeout > 0) { - gpr_log(GPR_DEBUG, "... retry_timer_active in %" PRIdPTR "ms.", - timeout); + gpr_log(GPR_DEBUG, + "[grpclb %p] ... retry_timer_active in %" PRIuPTR "ms.", + glb_policy, timeout); } else { - gpr_log(GPR_DEBUG, "... retry_timer_active immediately."); + gpr_log(GPR_DEBUG, "[grpclb %p] ... retry_timer_active immediately.", + glb_policy); } } GRPC_LB_POLICY_WEAK_REF(&glb_policy->base, "grpclb_retry_timer"); @@ -1290,11 +1324,11 @@ static void maybe_restart_lb_call(grpc_exec_ctx *exec_ctx, "lb_on_server_status_received_locked"); } -static void send_client_load_report_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error); +static void send_client_load_report_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error); -static void schedule_next_client_load_report(grpc_exec_ctx *exec_ctx, - glb_lb_policy *glb_policy) { +static void schedule_next_client_load_report(grpc_exec_ctx* exec_ctx, + glb_lb_policy* glb_policy) { const grpc_millis next_client_load_report_time = grpc_exec_ctx_now(exec_ctx) + glb_policy->client_stats_report_interval; GRPC_CLOSURE_INIT(&glb_policy->client_load_report_closure, @@ -1305,47 +1339,50 @@ static void schedule_next_client_load_report(grpc_exec_ctx *exec_ctx, &glb_policy->client_load_report_closure); } -static void client_load_report_done_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - glb_lb_policy *glb_policy = (glb_lb_policy *)arg; +static void client_load_report_done_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + glb_lb_policy* glb_policy = (glb_lb_policy*)arg; grpc_byte_buffer_destroy(glb_policy->client_load_report_payload); - glb_policy->client_load_report_payload = NULL; - if (error != GRPC_ERROR_NONE || glb_policy->lb_call == NULL) { + glb_policy->client_load_report_payload = nullptr; + if (error != GRPC_ERROR_NONE || glb_policy->lb_call == nullptr) { glb_policy->client_load_report_timer_pending = false; GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base, "client_load_report"); + if (glb_policy->lb_call == nullptr) { + maybe_restart_lb_call(exec_ctx, glb_policy); + } return; } schedule_next_client_load_report(exec_ctx, glb_policy); } -static bool load_report_counters_are_zero(grpc_grpclb_request *request) { - grpc_grpclb_dropped_call_counts *drop_entries = - (grpc_grpclb_dropped_call_counts *) +static bool load_report_counters_are_zero(grpc_grpclb_request* request) { + grpc_grpclb_dropped_call_counts* drop_entries = + (grpc_grpclb_dropped_call_counts*) request->client_stats.calls_finished_with_drop.arg; return request->client_stats.num_calls_started == 0 && request->client_stats.num_calls_finished == 0 && request->client_stats.num_calls_finished_with_client_failed_to_send == 0 && request->client_stats.num_calls_finished_known_received == 0 && - (drop_entries == NULL || drop_entries->num_entries == 0); + (drop_entries == nullptr || drop_entries->num_entries == 0); } -static void send_client_load_report_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - glb_lb_policy *glb_policy = (glb_lb_policy *)arg; - if (error == GRPC_ERROR_CANCELLED || glb_policy->lb_call == NULL) { +static void send_client_load_report_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + glb_lb_policy* glb_policy = (glb_lb_policy*)arg; + if (error == GRPC_ERROR_CANCELLED || glb_policy->lb_call == nullptr) { glb_policy->client_load_report_timer_pending = false; GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base, "client_load_report"); - if (glb_policy->lb_call == NULL) { + if (glb_policy->lb_call == nullptr) { maybe_restart_lb_call(exec_ctx, glb_policy); } return; } // Construct message payload. - GPR_ASSERT(glb_policy->client_load_report_payload == NULL); - grpc_grpclb_request *request = + GPR_ASSERT(glb_policy->client_load_report_payload == nullptr); + grpc_grpclb_request* request = grpc_grpclb_load_report_request_create_locked(glb_policy->client_stats); // Skip client load report if the counters were all zero in the last // report and they are still zero in this one. @@ -1376,20 +1413,20 @@ static void send_client_load_report_locked(grpc_exec_ctx *exec_ctx, void *arg, exec_ctx, glb_policy->lb_call, &op, 1, &glb_policy->client_load_report_closure); if (call_error != GRPC_CALL_OK) { - gpr_log(GPR_ERROR, "call_error=%d", call_error); + gpr_log(GPR_ERROR, "[grpclb %p] call_error=%d", glb_policy, call_error); GPR_ASSERT(GRPC_CALL_OK == call_error); } } -static void lb_on_server_status_received_locked(grpc_exec_ctx *exec_ctx, - void *arg, grpc_error *error); -static void lb_on_response_received_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error); -static void lb_call_init_locked(grpc_exec_ctx *exec_ctx, - glb_lb_policy *glb_policy) { - GPR_ASSERT(glb_policy->server_name != NULL); +static void lb_on_server_status_received_locked(grpc_exec_ctx* exec_ctx, + void* arg, grpc_error* error); +static void lb_on_response_received_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error); +static void lb_call_init_locked(grpc_exec_ctx* exec_ctx, + glb_lb_policy* glb_policy) { + GPR_ASSERT(glb_policy->server_name != nullptr); GPR_ASSERT(glb_policy->server_name[0] != '\0'); - GPR_ASSERT(glb_policy->lb_call == NULL); + GPR_ASSERT(glb_policy->lb_call == nullptr); GPR_ASSERT(!glb_policy->shutting_down); /* Note the following LB call progresses every time there's activity in \a @@ -1401,13 +1438,13 @@ static void lb_call_init_locked(grpc_exec_ctx *exec_ctx, ? GRPC_MILLIS_INF_FUTURE : grpc_exec_ctx_now(exec_ctx) + glb_policy->lb_call_timeout_ms; glb_policy->lb_call = grpc_channel_create_pollset_set_call( - exec_ctx, glb_policy->lb_channel, NULL, GRPC_PROPAGATE_DEFAULTS, + exec_ctx, glb_policy->lb_channel, nullptr, GRPC_PROPAGATE_DEFAULTS, glb_policy->base.interested_parties, GRPC_MDSTR_SLASH_GRPC_DOT_LB_DOT_V1_DOT_LOADBALANCER_SLASH_BALANCELOAD, - &host, deadline, NULL); + &host, deadline, nullptr); grpc_slice_unref_internal(exec_ctx, host); - if (glb_policy->client_stats != NULL) { + if (glb_policy->client_stats != nullptr) { grpc_grpclb_client_stats_unref(glb_policy->client_stats); } glb_policy->client_stats = grpc_grpclb_client_stats_create(); @@ -1415,7 +1452,7 @@ static void lb_call_init_locked(grpc_exec_ctx *exec_ctx, grpc_metadata_array_init(&glb_policy->lb_initial_metadata_recv); grpc_metadata_array_init(&glb_policy->lb_trailing_metadata_recv); - grpc_grpclb_request *request = + grpc_grpclb_request* request = grpc_grpclb_request_create(glb_policy->server_name); grpc_slice request_payload_slice = grpc_grpclb_request_encode(request); glb_policy->lb_request_payload = @@ -1431,7 +1468,7 @@ static void lb_call_init_locked(grpc_exec_ctx *exec_ctx, grpc_combiner_scheduler(glb_policy->base.combiner)); grpc_backoff_init(&glb_policy->lb_call_backoff_state, - GRPC_GRPCLB_INITIAL_CONNECT_BACKOFF_SECONDS, + GRPC_GRPCLB_INITIAL_CONNECT_BACKOFF_SECONDS * 1000, GRPC_GRPCLB_RECONNECT_BACKOFF_MULTIPLIER, GRPC_GRPCLB_RECONNECT_JITTER, GRPC_GRPCLB_MIN_CONNECT_TIMEOUT_SECONDS * 1000, @@ -1441,11 +1478,11 @@ static void lb_call_init_locked(grpc_exec_ctx *exec_ctx, glb_policy->last_client_load_report_counters_were_zero = false; } -static void lb_call_destroy_locked(grpc_exec_ctx *exec_ctx, - glb_lb_policy *glb_policy) { - GPR_ASSERT(glb_policy->lb_call != NULL); +static void lb_call_destroy_locked(grpc_exec_ctx* exec_ctx, + glb_lb_policy* glb_policy) { + GPR_ASSERT(glb_policy->lb_call != nullptr); grpc_call_unref(glb_policy->lb_call); - glb_policy->lb_call = NULL; + glb_policy->lb_call = nullptr; grpc_metadata_array_destroy(&glb_policy->lb_initial_metadata_recv); grpc_metadata_array_destroy(&glb_policy->lb_trailing_metadata_recv); @@ -1461,45 +1498,44 @@ static void lb_call_destroy_locked(grpc_exec_ctx *exec_ctx, /* * Auxiliary functions and LB client callbacks. */ -static void query_for_backends_locked(grpc_exec_ctx *exec_ctx, - glb_lb_policy *glb_policy) { - GPR_ASSERT(glb_policy->lb_channel != NULL); +static void query_for_backends_locked(grpc_exec_ctx* exec_ctx, + glb_lb_policy* glb_policy) { + GPR_ASSERT(glb_policy->lb_channel != nullptr); if (glb_policy->shutting_down) return; lb_call_init_locked(exec_ctx, glb_policy); - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { + if (grpc_lb_glb_trace.enabled()) { gpr_log(GPR_INFO, - "Query for backends (grpclb: %p, lb_channel: %p, lb_call: %p)", - (void *)glb_policy, (void *)glb_policy->lb_channel, - (void *)glb_policy->lb_call); + "[grpclb %p] Query for backends (lb_channel: %p, lb_call: %p)", + glb_policy, glb_policy->lb_channel, glb_policy->lb_call); } - GPR_ASSERT(glb_policy->lb_call != NULL); + GPR_ASSERT(glb_policy->lb_call != nullptr); grpc_call_error call_error; grpc_op ops[3]; memset(ops, 0, sizeof(ops)); - grpc_op *op = ops; + grpc_op* op = ops; op->op = GRPC_OP_SEND_INITIAL_METADATA; op->data.send_initial_metadata.count = 0; op->flags = 0; - op->reserved = NULL; + op->reserved = nullptr; op++; op->op = GRPC_OP_RECV_INITIAL_METADATA; op->data.recv_initial_metadata.recv_initial_metadata = &glb_policy->lb_initial_metadata_recv; op->flags = 0; - op->reserved = NULL; + op->reserved = nullptr; op++; - GPR_ASSERT(glb_policy->lb_request_payload != NULL); + GPR_ASSERT(glb_policy->lb_request_payload != nullptr); op->op = GRPC_OP_SEND_MESSAGE; op->data.send_message.send_message = glb_policy->lb_request_payload; op->flags = 0; - op->reserved = NULL; + op->reserved = nullptr; op++; - call_error = grpc_call_start_batch_and_execute(exec_ctx, glb_policy->lb_call, - ops, (size_t)(op - ops), NULL); + call_error = grpc_call_start_batch_and_execute( + exec_ctx, glb_policy->lb_call, ops, (size_t)(op - ops), nullptr); GPR_ASSERT(GRPC_CALL_OK == call_error); op = ops; @@ -1510,7 +1546,7 @@ static void query_for_backends_locked(grpc_exec_ctx *exec_ctx, op->data.recv_status_on_client.status_details = &glb_policy->lb_call_status_details; op->flags = 0; - op->reserved = NULL; + op->reserved = nullptr; op++; /* take a weak ref (won't prevent calling of \a glb_shutdown if the strong ref * count goes to zero) to be unref'd in lb_on_server_status_received_locked */ @@ -1525,7 +1561,7 @@ static void query_for_backends_locked(grpc_exec_ctx *exec_ctx, op->op = GRPC_OP_RECV_MESSAGE; op->data.recv_message.recv_message = &glb_policy->lb_response_payload; op->flags = 0; - op->reserved = NULL; + op->reserved = nullptr; op++; /* take another weak ref to be unref'd/reused in * lb_on_response_received_locked */ @@ -1536,13 +1572,13 @@ static void query_for_backends_locked(grpc_exec_ctx *exec_ctx, GPR_ASSERT(GRPC_CALL_OK == call_error); } -static void lb_on_response_received_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - glb_lb_policy *glb_policy = (glb_lb_policy *)arg; +static void lb_on_response_received_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + glb_lb_policy* glb_policy = (glb_lb_policy*)arg; grpc_op ops[2]; memset(ops, 0, sizeof(ops)); - grpc_op *op = ops; - if (glb_policy->lb_response_payload != NULL) { + grpc_op* op = ops; + if (glb_policy->lb_response_payload != nullptr) { grpc_backoff_reset(&glb_policy->lb_call_backoff_state); /* Received data from the LB server. Look inside * glb_policy->lb_response_payload, for a serverlist. */ @@ -1552,19 +1588,19 @@ static void lb_on_response_received_locked(grpc_exec_ctx *exec_ctx, void *arg, grpc_byte_buffer_reader_destroy(&bbr); grpc_byte_buffer_destroy(glb_policy->lb_response_payload); - grpc_grpclb_initial_response *response = NULL; + grpc_grpclb_initial_response* response = nullptr; if (!glb_policy->seen_initial_response && (response = grpc_grpclb_initial_response_parse(response_slice)) != - NULL) { + nullptr) { if (response->has_client_stats_report_interval) { glb_policy->client_stats_report_interval = GPR_MAX( GPR_MS_PER_SEC, grpc_grpclb_duration_to_millis( &response->client_stats_report_interval)); - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { + if (grpc_lb_glb_trace.enabled()) { gpr_log(GPR_INFO, - "received initial LB response message; " + "[grpclb %p] Received initial LB response message; " "client load reporting interval = %" PRIdPTR " milliseconds", - glb_policy->client_stats_report_interval); + glb_policy, glb_policy->client_stats_report_interval); } /* take a weak ref (won't prevent calling of \a glb_shutdown() if the * strong ref count goes to zero) to be unref'd in @@ -1572,27 +1608,30 @@ static void lb_on_response_received_locked(grpc_exec_ctx *exec_ctx, void *arg, glb_policy->client_load_report_timer_pending = true; GRPC_LB_POLICY_WEAK_REF(&glb_policy->base, "client_load_report"); schedule_next_client_load_report(exec_ctx, glb_policy); - } else if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { + } else if (grpc_lb_glb_trace.enabled()) { gpr_log(GPR_INFO, - "received initial LB response message; " - "client load reporting NOT enabled"); + "[grpclb %p] Received initial LB response message; client load " + "reporting NOT enabled", + glb_policy); } grpc_grpclb_initial_response_destroy(response); glb_policy->seen_initial_response = true; } else { - grpc_grpclb_serverlist *serverlist = + grpc_grpclb_serverlist* serverlist = grpc_grpclb_response_parse_serverlist(response_slice); - if (serverlist != NULL) { - GPR_ASSERT(glb_policy->lb_call != NULL); - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { - gpr_log(GPR_INFO, "Serverlist with %lu servers received", - (unsigned long)serverlist->num_servers); + if (serverlist != nullptr) { + GPR_ASSERT(glb_policy->lb_call != nullptr); + if (grpc_lb_glb_trace.enabled()) { + gpr_log(GPR_INFO, + "[grpclb %p] Serverlist with %" PRIuPTR " servers received", + glb_policy, serverlist->num_servers); for (size_t i = 0; i < serverlist->num_servers; ++i) { grpc_resolved_address addr; parse_server(serverlist->servers[i], &addr); - char *ipport; + char* ipport; grpc_sockaddr_to_string(&ipport, &addr, false); - gpr_log(GPR_INFO, "Serverlist[%lu]: %s", (unsigned long)i, ipport); + gpr_log(GPR_INFO, "[grpclb %p] Serverlist[%" PRIuPTR "]: %s", + glb_policy, i, ipport); gpr_free(ipport); } } @@ -1600,20 +1639,22 @@ static void lb_on_response_received_locked(grpc_exec_ctx *exec_ctx, void *arg, if (serverlist->num_servers > 0) { if (grpc_grpclb_serverlist_equals(glb_policy->serverlist, serverlist)) { - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { + if (grpc_lb_glb_trace.enabled()) { gpr_log(GPR_INFO, - "Incoming server list identical to current, ignoring."); + "[grpclb %p] Incoming server list identical to current, " + "ignoring.", + glb_policy); } grpc_grpclb_destroy_serverlist(serverlist); } else { /* new serverlist */ - if (glb_policy->serverlist != NULL) { + if (glb_policy->serverlist != nullptr) { /* dispose of the old serverlist */ grpc_grpclb_destroy_serverlist(glb_policy->serverlist); } else { /* or dispose of the fallback */ grpc_lb_addresses_destroy(exec_ctx, glb_policy->fallback_backend_addresses); - glb_policy->fallback_backend_addresses = NULL; + glb_policy->fallback_backend_addresses = nullptr; if (glb_policy->fallback_timer_active) { grpc_timer_cancel(exec_ctx, &glb_policy->lb_fallback_timer); glb_policy->fallback_timer_active = false; @@ -1627,13 +1668,17 @@ static void lb_on_response_received_locked(grpc_exec_ctx *exec_ctx, void *arg, rr_handover_locked(exec_ctx, glb_policy); } } else { - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { - gpr_log(GPR_INFO, "Received empty server list, ignoring."); + if (grpc_lb_glb_trace.enabled()) { + gpr_log(GPR_INFO, + "[grpclb %p] Received empty server list, ignoring.", + glb_policy); } grpc_grpclb_destroy_serverlist(serverlist); } } else { /* serverlist == NULL */ - gpr_log(GPR_ERROR, "Invalid LB response received: '%s'. Ignoring.", + gpr_log(GPR_ERROR, + "[grpclb %p] Invalid LB response received: '%s'. Ignoring.", + glb_policy, grpc_dump_slice(response_slice, GPR_DUMP_ASCII | GPR_DUMP_HEX)); } } @@ -1643,7 +1688,7 @@ static void lb_on_response_received_locked(grpc_exec_ctx *exec_ctx, void *arg, op->op = GRPC_OP_RECV_MESSAGE; op->data.recv_message.recv_message = &glb_policy->lb_response_payload; op->flags = 0; - op->reserved = NULL; + op->reserved = nullptr; op++; /* reuse the "lb_on_response_received_locked" weak ref taken in * query_for_backends_locked() */ @@ -1663,20 +1708,20 @@ static void lb_on_response_received_locked(grpc_exec_ctx *exec_ctx, void *arg, } } -static void lb_on_fallback_timer_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - glb_lb_policy *glb_policy = (glb_lb_policy *)arg; +static void lb_on_fallback_timer_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + glb_lb_policy* glb_policy = (glb_lb_policy*)arg; glb_policy->fallback_timer_active = false; /* If we receive a serverlist after the timer fires but before this callback * actually runs, don't fall back. */ - if (glb_policy->serverlist == NULL) { + if (glb_policy->serverlist == nullptr) { if (!glb_policy->shutting_down && error == GRPC_ERROR_NONE) { - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { + if (grpc_lb_glb_trace.enabled()) { gpr_log(GPR_INFO, - "Falling back to use backends from resolver (grpclb %p)", - (void *)glb_policy); + "[grpclb %p] Falling back to use backends from resolver", + glb_policy); } - GPR_ASSERT(glb_policy->fallback_backend_addresses != NULL); + GPR_ASSERT(glb_policy->fallback_backend_addresses != nullptr); rr_handover_locked(exec_ctx, glb_policy); } } @@ -1684,18 +1729,18 @@ static void lb_on_fallback_timer_locked(grpc_exec_ctx *exec_ctx, void *arg, "grpclb_fallback_timer"); } -static void lb_on_server_status_received_locked(grpc_exec_ctx *exec_ctx, - void *arg, grpc_error *error) { - glb_lb_policy *glb_policy = (glb_lb_policy *)arg; - GPR_ASSERT(glb_policy->lb_call != NULL); - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { - char *status_details = +static void lb_on_server_status_received_locked(grpc_exec_ctx* exec_ctx, + void* arg, grpc_error* error) { + glb_lb_policy* glb_policy = (glb_lb_policy*)arg; + GPR_ASSERT(glb_policy->lb_call != nullptr); + if (grpc_lb_glb_trace.enabled()) { + char* status_details = grpc_slice_to_c_string(glb_policy->lb_call_status_details); gpr_log(GPR_INFO, - "Status from LB server received. Status = %d, Details = '%s', " - "(call: %p), error %p", - glb_policy->lb_call_status, status_details, - (void *)glb_policy->lb_call, (void *)error); + "[grpclb %p] Status from LB server received. Status = %d, Details " + "= '%s', (call: %p), error '%s'", + glb_policy, glb_policy->lb_call_status, status_details, + glb_policy->lb_call, grpc_error_string(error)); gpr_free(status_details); } /* We need to perform cleanups no matter what. */ @@ -1708,26 +1753,26 @@ static void lb_on_server_status_received_locked(grpc_exec_ctx *exec_ctx, } } -static void fallback_update_locked(grpc_exec_ctx *exec_ctx, - glb_lb_policy *glb_policy, - const grpc_lb_addresses *addresses) { - GPR_ASSERT(glb_policy->fallback_backend_addresses != NULL); +static void fallback_update_locked(grpc_exec_ctx* exec_ctx, + glb_lb_policy* glb_policy, + const grpc_lb_addresses* addresses) { + GPR_ASSERT(glb_policy->fallback_backend_addresses != nullptr); grpc_lb_addresses_destroy(exec_ctx, glb_policy->fallback_backend_addresses); glb_policy->fallback_backend_addresses = extract_backend_addresses_locked(exec_ctx, addresses); if (glb_policy->lb_fallback_timeout_ms > 0 && - !glb_policy->fallback_timer_active) { + glb_policy->rr_policy != nullptr) { rr_handover_locked(exec_ctx, glb_policy); } } -static void glb_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, - const grpc_lb_policy_args *args) { - glb_lb_policy *glb_policy = (glb_lb_policy *)policy; - const grpc_arg *arg = +static void glb_update_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + const grpc_lb_policy_args* args) { + glb_lb_policy* glb_policy = (glb_lb_policy*)policy; + const grpc_arg* arg = grpc_channel_args_find(args->args, GRPC_ARG_LB_ADDRESSES); - if (arg == NULL || arg->type != GRPC_ARG_POINTER) { - if (glb_policy->lb_channel == NULL) { + if (arg == nullptr || arg->type != GRPC_ARG_POINTER) { + if (glb_policy->lb_channel == nullptr) { // If we don't have a current channel to the LB, go into TRANSIENT // FAILURE. grpc_connectivity_state_set( @@ -1736,24 +1781,24 @@ static void glb_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, "glb_update_missing"); } else { // otherwise, keep using the current LB channel (ignore this update). - gpr_log(GPR_ERROR, - "No valid LB addresses channel arg for grpclb %p update, " - "ignoring.", - (void *)glb_policy); + gpr_log( + GPR_ERROR, + "[grpclb %p] No valid LB addresses channel arg in update, ignoring.", + glb_policy); } return; } - const grpc_lb_addresses *addresses = - (const grpc_lb_addresses *)arg->value.pointer.p; + const grpc_lb_addresses* addresses = + (const grpc_lb_addresses*)arg->value.pointer.p; // If a non-empty serverlist hasn't been received from the balancer, // propagate the update to fallback_backend_addresses. - if (glb_policy->serverlist == NULL) { + if (glb_policy->serverlist == nullptr) { fallback_update_locked(exec_ctx, glb_policy, addresses); } - GPR_ASSERT(glb_policy->lb_channel != NULL); + GPR_ASSERT(glb_policy->lb_channel != nullptr); // Propagate updates to the LB channel (pick_first) through the fake // resolver. - grpc_channel_args *lb_channel_args = build_lb_channel_args( + grpc_channel_args* lb_channel_args = build_lb_channel_args( exec_ctx, addresses, glb_policy->response_generator, args->args); grpc_fake_resolver_response_generator_set_response( exec_ctx, glb_policy->response_generator, lb_channel_args); @@ -1763,7 +1808,7 @@ static void glb_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, if (!glb_policy->watching_lb_channel) { glb_policy->lb_channel_connectivity = grpc_channel_check_connectivity_state( glb_policy->lb_channel, true /* try to connect */); - grpc_channel_element *client_channel_elem = grpc_channel_stack_last_element( + grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element( grpc_channel_get_channel_stack(glb_policy->lb_channel)); GPR_ASSERT(client_channel_elem->filter == &grpc_client_channel_filter); glb_policy->watching_lb_channel = true; @@ -1773,17 +1818,17 @@ static void glb_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, grpc_polling_entity_create_from_pollset_set( glb_policy->base.interested_parties), &glb_policy->lb_channel_connectivity, - &glb_policy->lb_channel_on_connectivity_changed, NULL); + &glb_policy->lb_channel_on_connectivity_changed, nullptr); } } // Invoked as part of the update process. It continues watching the LB channel // until it shuts down or becomes READY. It's invoked even if the LB channel // stayed READY throughout the update (for example if the update is identical). -static void glb_lb_channel_on_connectivity_changed_cb(grpc_exec_ctx *exec_ctx, - void *arg, - grpc_error *error) { - glb_lb_policy *glb_policy = (glb_lb_policy *)arg; +static void glb_lb_channel_on_connectivity_changed_cb(grpc_exec_ctx* exec_ctx, + void* arg, + grpc_error* error) { + glb_lb_policy* glb_policy = (glb_lb_policy*)arg; if (glb_policy->shutting_down) goto done; // Re-initialize the lb_call. This should also take care of updating the // embedded RR policy. Note that the current RR policy, if any, will stay in @@ -1792,7 +1837,7 @@ static void glb_lb_channel_on_connectivity_changed_cb(grpc_exec_ctx *exec_ctx, case GRPC_CHANNEL_CONNECTING: case GRPC_CHANNEL_TRANSIENT_FAILURE: { /* resub. */ - grpc_channel_element *client_channel_elem = + grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element( grpc_channel_get_channel_stack(glb_policy->lb_channel)); GPR_ASSERT(client_channel_elem->filter == &grpc_client_channel_filter); @@ -1801,7 +1846,7 @@ static void glb_lb_channel_on_connectivity_changed_cb(grpc_exec_ctx *exec_ctx, grpc_polling_entity_create_from_pollset_set( glb_policy->base.interested_parties), &glb_policy->lb_channel_connectivity, - &glb_policy->lb_channel_on_connectivity_changed, NULL); + &glb_policy->lb_channel_on_connectivity_changed, nullptr); break; } case GRPC_CHANNEL_IDLE: @@ -1809,12 +1854,12 @@ static void glb_lb_channel_on_connectivity_changed_cb(grpc_exec_ctx *exec_ctx, // call to kick the lb channel into gear. /* fallthrough */ case GRPC_CHANNEL_READY: - if (glb_policy->lb_call != NULL) { + if (glb_policy->lb_call != nullptr) { glb_policy->updating_lb_call = true; - grpc_call_cancel(glb_policy->lb_call, NULL); + grpc_call_cancel(glb_policy->lb_call, nullptr); // lb_on_server_status_received() will pick up the cancel and reinit // lb_call. - } else if (glb_policy->started_picking && !glb_policy->shutting_down) { + } else if (glb_policy->started_picking) { if (glb_policy->retry_timer_active) { grpc_timer_cancel(exec_ctx, &glb_policy->lb_call_retry_timer); glb_policy->retry_timer_active = false; @@ -1831,6 +1876,20 @@ static void glb_lb_channel_on_connectivity_changed_cb(grpc_exec_ctx *exec_ctx, } } +static void glb_set_reresolve_closure_locked( + grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + grpc_closure* request_reresolution) { + glb_lb_policy* glb_policy = (glb_lb_policy*)policy; + GPR_ASSERT(!glb_policy->shutting_down); + GPR_ASSERT(glb_policy->base.request_reresolution == nullptr); + if (glb_policy->rr_policy != nullptr) { + grpc_lb_policy_set_reresolve_closure_locked(exec_ctx, glb_policy->rr_policy, + request_reresolution); + } else { + glb_policy->base.request_reresolution = request_reresolution; + } +} + /* Code wiring the policy with the rest of the core */ static const grpc_lb_policy_vtable glb_lb_policy_vtable = { glb_destroy, @@ -1842,42 +1901,44 @@ static const grpc_lb_policy_vtable glb_lb_policy_vtable = { glb_exit_idle_locked, glb_check_connectivity_locked, glb_notify_on_state_change_locked, - glb_update_locked}; + glb_update_locked, + glb_set_reresolve_closure_locked}; -static grpc_lb_policy *glb_create(grpc_exec_ctx *exec_ctx, - grpc_lb_policy_factory *factory, - grpc_lb_policy_args *args) { +static grpc_lb_policy* glb_create(grpc_exec_ctx* exec_ctx, + grpc_lb_policy_factory* factory, + grpc_lb_policy_args* args) { /* Count the number of gRPC-LB addresses. There must be at least one. */ - const grpc_arg *arg = + const grpc_arg* arg = grpc_channel_args_find(args->args, GRPC_ARG_LB_ADDRESSES); - if (arg == NULL || arg->type != GRPC_ARG_POINTER) { - return NULL; + if (arg == nullptr || arg->type != GRPC_ARG_POINTER) { + return nullptr; } - grpc_lb_addresses *addresses = (grpc_lb_addresses *)arg->value.pointer.p; + grpc_lb_addresses* addresses = (grpc_lb_addresses*)arg->value.pointer.p; size_t num_grpclb_addrs = 0; for (size_t i = 0; i < addresses->num_addresses; ++i) { if (addresses->addresses[i].is_balancer) ++num_grpclb_addrs; } - if (num_grpclb_addrs == 0) return NULL; + if (num_grpclb_addrs == 0) return nullptr; - glb_lb_policy *glb_policy = (glb_lb_policy *)gpr_zalloc(sizeof(*glb_policy)); + glb_lb_policy* glb_policy = (glb_lb_policy*)gpr_zalloc(sizeof(*glb_policy)); /* Get server name. */ arg = grpc_channel_args_find(args->args, GRPC_ARG_SERVER_URI); - GPR_ASSERT(arg != NULL); + GPR_ASSERT(arg != nullptr); GPR_ASSERT(arg->type == GRPC_ARG_STRING); - grpc_uri *uri = grpc_uri_parse(exec_ctx, arg->value.string, true); + grpc_uri* uri = grpc_uri_parse(exec_ctx, arg->value.string, true); GPR_ASSERT(uri->path[0] != '\0'); glb_policy->server_name = gpr_strdup(uri->path[0] == '/' ? uri->path + 1 : uri->path); - if (GRPC_TRACER_ON(grpc_lb_glb_trace)) { - gpr_log(GPR_INFO, "Will use '%s' as the server name for LB request.", - glb_policy->server_name); + if (grpc_lb_glb_trace.enabled()) { + gpr_log(GPR_INFO, + "[grpclb %p] Will use '%s' as the server name for LB request.", + glb_policy, glb_policy->server_name); } grpc_uri_destroy(uri); glb_policy->cc_factory = args->client_channel_factory; - GPR_ASSERT(glb_policy->cc_factory != NULL); + GPR_ASSERT(glb_policy->cc_factory != nullptr); arg = grpc_channel_args_find(args->args, GRPC_ARG_GRPCLB_CALL_TIMEOUT_MS); glb_policy->lb_call_timeout_ms = @@ -1890,8 +1951,8 @@ static grpc_lb_policy *glb_create(grpc_exec_ctx *exec_ctx, // Make sure that GRPC_ARG_LB_POLICY_NAME is set in channel args, // since we use this to trigger the client_load_reporting filter. grpc_arg new_arg = grpc_channel_arg_string_create( - (char *)GRPC_ARG_LB_POLICY_NAME, (char *)"grpclb"); - static const char *args_to_remove[] = {GRPC_ARG_LB_POLICY_NAME}; + (char*)GRPC_ARG_LB_POLICY_NAME, (char*)"grpclb"); + static const char* args_to_remove[] = {GRPC_ARG_LB_POLICY_NAME}; glb_policy->args = grpc_channel_args_copy_and_add_and_remove( args->args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove), &new_arg, 1); @@ -1903,9 +1964,9 @@ static grpc_lb_policy *glb_create(grpc_exec_ctx *exec_ctx, /* Create a client channel over them to communicate with a LB service */ glb_policy->response_generator = grpc_fake_resolver_response_generator_create(); - grpc_channel_args *lb_channel_args = build_lb_channel_args( + grpc_channel_args* lb_channel_args = build_lb_channel_args( exec_ctx, addresses, glb_policy->response_generator, args->args); - char *uri_str; + char* uri_str; gpr_asprintf(&uri_str, "fake:///%s", glb_policy->server_name); glb_policy->lb_channel = grpc_lb_policy_grpclb_create_lb_channel( exec_ctx, uri_str, args->client_channel_factory, lb_channel_args); @@ -1915,11 +1976,11 @@ static grpc_lb_policy *glb_create(grpc_exec_ctx *exec_ctx, exec_ctx, glb_policy->response_generator, lb_channel_args); grpc_channel_args_destroy(exec_ctx, lb_channel_args); gpr_free(uri_str); - if (glb_policy->lb_channel == NULL) { - gpr_free((void *)glb_policy->server_name); + if (glb_policy->lb_channel == nullptr) { + gpr_free((void*)glb_policy->server_name); grpc_channel_args_destroy(exec_ctx, glb_policy->args); gpr_free(glb_policy); - return NULL; + return nullptr; } grpc_subchannel_index_ref(); GRPC_CLOSURE_INIT(&glb_policy->lb_channel_on_connectivity_changed, @@ -1931,16 +1992,16 @@ static grpc_lb_policy *glb_create(grpc_exec_ctx *exec_ctx, return &glb_policy->base; } -static void glb_factory_ref(grpc_lb_policy_factory *factory) {} +static void glb_factory_ref(grpc_lb_policy_factory* factory) {} -static void glb_factory_unref(grpc_lb_policy_factory *factory) {} +static void glb_factory_unref(grpc_lb_policy_factory* factory) {} static const grpc_lb_policy_factory_vtable glb_factory_vtable = { glb_factory_ref, glb_factory_unref, glb_create, "grpclb"}; static grpc_lb_policy_factory glb_lb_policy_factory = {&glb_factory_vtable}; -grpc_lb_policy_factory *grpc_glb_lb_factory_create() { +grpc_lb_policy_factory* grpc_glb_lb_factory_create() { return &glb_lb_policy_factory; } @@ -1948,29 +2009,25 @@ grpc_lb_policy_factory *grpc_glb_lb_factory_create() { // Only add client_load_reporting filter if the grpclb LB policy is used. static bool maybe_add_client_load_reporting_filter( - grpc_exec_ctx *exec_ctx, grpc_channel_stack_builder *builder, void *arg) { - const grpc_channel_args *args = + grpc_exec_ctx* exec_ctx, grpc_channel_stack_builder* builder, void* arg) { + const grpc_channel_args* args = grpc_channel_stack_builder_get_channel_arguments(builder); - const grpc_arg *channel_arg = + const grpc_arg* channel_arg = grpc_channel_args_find(args, GRPC_ARG_LB_POLICY_NAME); - if (channel_arg != NULL && channel_arg->type == GRPC_ARG_STRING && + if (channel_arg != nullptr && channel_arg->type == GRPC_ARG_STRING && strcmp(channel_arg->value.string, "grpclb") == 0) { return grpc_channel_stack_builder_append_filter( - builder, (const grpc_channel_filter *)arg, NULL, NULL); + builder, (const grpc_channel_filter*)arg, nullptr, nullptr); } return true; } -extern "C" void grpc_lb_policy_grpclb_init() { +void grpc_lb_policy_grpclb_init() { grpc_register_lb_policy(grpc_glb_lb_factory_create()); - grpc_register_tracer(&grpc_lb_glb_trace); -#ifndef NDEBUG - grpc_register_tracer(&grpc_trace_lb_policy_refcount); -#endif grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, maybe_add_client_load_reporting_filter, - (void *)&grpc_client_load_reporting_filter); + (void*)&grpc_client_load_reporting_filter); } -extern "C" void grpc_lb_policy_grpclb_shutdown() {} +void grpc_lb_policy_grpclb_shutdown() {} diff --git a/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h b/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h index 15c8a680b73..0a2edb0e3da 100644 --- a/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h +++ b/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h @@ -21,17 +21,9 @@ #include "src/core/ext/filters/client_channel/lb_policy_factory.h" -#ifdef __cplusplus -extern "C" { -#endif - /** Returns a load balancing factory for the glb policy, which tries to connect * to a load balancing server to decide the next successfully connected * subchannel to pick. */ -grpc_lb_policy_factory *grpc_glb_lb_factory_create(); - -#ifdef __cplusplus -} -#endif +grpc_lb_policy_factory* grpc_glb_lb_factory_create(); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_H */ diff --git a/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.cc b/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.cc index f2967182e2d..aacaec197dc 100644 --- a/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.cc +++ b/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.cc @@ -25,20 +25,20 @@ #include "src/core/lib/iomgr/sockaddr_utils.h" #include "src/core/lib/support/string.h" -grpc_channel *grpc_lb_policy_grpclb_create_lb_channel( - grpc_exec_ctx *exec_ctx, const char *lb_service_target_addresses, - grpc_client_channel_factory *client_channel_factory, - grpc_channel_args *args) { - grpc_channel *lb_channel = grpc_client_channel_factory_create_channel( +grpc_channel* grpc_lb_policy_grpclb_create_lb_channel( + grpc_exec_ctx* exec_ctx, const char* lb_service_target_addresses, + grpc_client_channel_factory* client_channel_factory, + grpc_channel_args* args) { + grpc_channel* lb_channel = grpc_client_channel_factory_create_channel( exec_ctx, client_channel_factory, lb_service_target_addresses, GRPC_CLIENT_CHANNEL_TYPE_LOAD_BALANCING, args); return lb_channel; } -grpc_channel_args *grpc_lb_policy_grpclb_build_lb_channel_args( - grpc_exec_ctx *exec_ctx, grpc_slice_hash_table *targets_info, - grpc_fake_resolver_response_generator *response_generator, - const grpc_channel_args *args) { +grpc_channel_args* grpc_lb_policy_grpclb_build_lb_channel_args( + grpc_exec_ctx* exec_ctx, grpc_slice_hash_table* targets_info, + grpc_fake_resolver_response_generator* response_generator, + const grpc_channel_args* args) { const grpc_arg to_add[] = { grpc_fake_resolver_response_generator_arg(response_generator)}; /* We remove: @@ -62,7 +62,7 @@ grpc_channel_args *grpc_lb_policy_grpclb_build_lb_channel_args( * * - The fake resolver generator, because we are replacing it with the one * from the grpclb policy, used to propagate updates to the LB channel. */ - static const char *keys_to_remove[] = { + static const char* keys_to_remove[] = { GRPC_ARG_LB_POLICY_NAME, GRPC_ARG_LB_ADDRESSES, GRPC_ARG_SERVER_URI, GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR}; return grpc_channel_args_copy_and_add_and_remove( diff --git a/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h b/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h index e8599d1f51c..70b1c28b0da 100644 --- a/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h +++ b/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h @@ -23,10 +23,6 @@ #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h" #include "src/core/lib/slice/slice_hash_table.h" -#ifdef __cplusplus -extern "C" { -#endif - /** Create the channel used for communicating with an LB service. * Note that an LB *service* may be comprised of several LB *servers*. * @@ -34,19 +30,15 @@ extern "C" { * from resolving the LB service's name (eg, ipv4:10.0.0.1:1234,10.2.3.4:9876). * \a client_channel_factory will be used for the creation of the LB channel, * alongside the channel args passed in \a args. */ -grpc_channel *grpc_lb_policy_grpclb_create_lb_channel( - grpc_exec_ctx *exec_ctx, const char *lb_service_target_addresses, - grpc_client_channel_factory *client_channel_factory, - grpc_channel_args *args); - -grpc_channel_args *grpc_lb_policy_grpclb_build_lb_channel_args( - grpc_exec_ctx *exec_ctx, grpc_slice_hash_table *targets_info, - grpc_fake_resolver_response_generator *response_generator, - const grpc_channel_args *args); +grpc_channel* grpc_lb_policy_grpclb_create_lb_channel( + grpc_exec_ctx* exec_ctx, const char* lb_service_target_addresses, + grpc_client_channel_factory* client_channel_factory, + grpc_channel_args* args); -#ifdef __cplusplus -} -#endif +grpc_channel_args* grpc_lb_policy_grpclb_build_lb_channel_args( + grpc_exec_ctx* exec_ctx, grpc_slice_hash_table* targets_info, + grpc_fake_resolver_response_generator* response_generator, + const grpc_channel_args* args); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_CHANNEL_H \ - */ + */ diff --git a/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc b/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc index 2681b2a079c..8eaa90e97b6 100644 --- a/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc +++ b/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc @@ -28,22 +28,22 @@ #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/support/string.h" -grpc_channel *grpc_lb_policy_grpclb_create_lb_channel( - grpc_exec_ctx *exec_ctx, const char *lb_service_target_addresses, - grpc_client_channel_factory *client_channel_factory, - grpc_channel_args *args) { - grpc_channel_args *new_args = args; - grpc_channel_credentials *channel_credentials = +grpc_channel* grpc_lb_policy_grpclb_create_lb_channel( + grpc_exec_ctx* exec_ctx, const char* lb_service_target_addresses, + grpc_client_channel_factory* client_channel_factory, + grpc_channel_args* args) { + grpc_channel_args* new_args = args; + grpc_channel_credentials* channel_credentials = grpc_channel_credentials_find_in_args(args); - if (channel_credentials != NULL) { + if (channel_credentials != nullptr) { /* Substitute the channel credentials with a version without call * credentials: the load balancer is not necessarily trusted to handle * bearer token credentials */ - static const char *keys_to_remove[] = {GRPC_ARG_CHANNEL_CREDENTIALS}; - grpc_channel_credentials *creds_sans_call_creds = + static const char* keys_to_remove[] = {GRPC_ARG_CHANNEL_CREDENTIALS}; + grpc_channel_credentials* creds_sans_call_creds = grpc_channel_credentials_duplicate_without_call_credentials( channel_credentials); - GPR_ASSERT(creds_sans_call_creds != NULL); + GPR_ASSERT(creds_sans_call_creds != nullptr); grpc_arg args_to_add[] = { grpc_channel_credentials_to_arg(creds_sans_call_creds)}; /* Create the new set of channel args */ @@ -52,19 +52,19 @@ grpc_channel *grpc_lb_policy_grpclb_create_lb_channel( GPR_ARRAY_SIZE(args_to_add)); grpc_channel_credentials_unref(exec_ctx, creds_sans_call_creds); } - grpc_channel *lb_channel = grpc_client_channel_factory_create_channel( + grpc_channel* lb_channel = grpc_client_channel_factory_create_channel( exec_ctx, client_channel_factory, lb_service_target_addresses, GRPC_CLIENT_CHANNEL_TYPE_LOAD_BALANCING, new_args); - if (channel_credentials != NULL) { + if (channel_credentials != nullptr) { grpc_channel_args_destroy(exec_ctx, new_args); } return lb_channel; } -grpc_channel_args *grpc_lb_policy_grpclb_build_lb_channel_args( - grpc_exec_ctx *exec_ctx, grpc_slice_hash_table *targets_info, - grpc_fake_resolver_response_generator *response_generator, - const grpc_channel_args *args) { +grpc_channel_args* grpc_lb_policy_grpclb_build_lb_channel_args( + grpc_exec_ctx* exec_ctx, grpc_slice_hash_table* targets_info, + grpc_fake_resolver_response_generator* response_generator, + const grpc_channel_args* args) { const grpc_arg to_add[] = { grpc_lb_targets_info_create_channel_arg(targets_info), grpc_fake_resolver_response_generator_arg(response_generator)}; @@ -89,7 +89,7 @@ grpc_channel_args *grpc_lb_policy_grpclb_build_lb_channel_args( * * - The fake resolver generator, because we are replacing it with the one * from the grpclb policy, used to propagate updates to the LB channel. */ - static const char *keys_to_remove[] = { + static const char* keys_to_remove[] = { GRPC_ARG_LB_POLICY_NAME, GRPC_ARG_LB_ADDRESSES, GRPC_ARG_SERVER_URI, GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR}; /* Add the targets info table to be used for secure naming */ diff --git a/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc b/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc index 903120ca7d0..e19a6a71aa3 100644 --- a/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc +++ b/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc @@ -87,7 +87,7 @@ void grpc_grpclb_client_stats_add_call_dropped_locked( gpr_atm_full_fetch_add(&client_stats->num_calls_started, (gpr_atm)1); gpr_atm_full_fetch_add(&client_stats->num_calls_finished, (gpr_atm)1); // Record the drop. - if (client_stats->drop_token_counts == NULL) { + if (client_stats->drop_token_counts == nullptr) { client_stats->drop_token_counts = (grpc_grpclb_dropped_call_counts*)gpr_zalloc( sizeof(grpc_grpclb_dropped_call_counts)); @@ -136,12 +136,12 @@ void grpc_grpclb_client_stats_get_locked( num_calls_finished_known_received, &client_stats->num_calls_finished_known_received); *drop_token_counts = client_stats->drop_token_counts; - client_stats->drop_token_counts = NULL; + client_stats->drop_token_counts = nullptr; } void grpc_grpclb_dropped_call_counts_destroy( grpc_grpclb_dropped_call_counts* drop_entries) { - if (drop_entries != NULL) { + if (drop_entries != nullptr) { for (size_t i = 0; i < drop_entries->num_entries; ++i) { gpr_free(drop_entries->token_counts[i].token); } diff --git a/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h b/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h index b38c076f389..d4b9d068488 100644 --- a/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h +++ b/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h @@ -23,10 +23,6 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_grpclb_client_stats grpc_grpclb_client_stats; typedef struct { @@ -65,9 +61,5 @@ void grpc_grpclb_client_stats_get_locked( void grpc_grpclb_dropped_call_counts_destroy( grpc_grpclb_dropped_call_counts* drop_entries); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_CLIENT_STATS_H \ - */ + */ diff --git a/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc b/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc index 4d5fb2081cc..2c8d7f42910 100644 --- a/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc +++ b/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc @@ -23,9 +23,9 @@ #include /* invoked once for every Server in ServerList */ -static bool count_serverlist(pb_istream_t *stream, const pb_field_t *field, - void **arg) { - grpc_grpclb_serverlist *sl = (grpc_grpclb_serverlist *)*arg; +static bool count_serverlist(pb_istream_t* stream, const pb_field_t* field, + void** arg) { + grpc_grpclb_serverlist* sl = (grpc_grpclb_serverlist*)*arg; grpc_grpclb_server server; if (!pb_decode(stream, grpc_lb_v1_Server_fields, &server)) { gpr_log(GPR_ERROR, "nanopb error: %s", PB_GET_ERROR(stream)); @@ -40,16 +40,16 @@ typedef struct decode_serverlist_arg { * which index of the serverlist are we currently decoding */ size_t decoding_idx; /* The decoded serverlist */ - grpc_grpclb_serverlist *serverlist; + grpc_grpclb_serverlist* serverlist; } decode_serverlist_arg; /* invoked once for every Server in ServerList */ -static bool decode_serverlist(pb_istream_t *stream, const pb_field_t *field, - void **arg) { - decode_serverlist_arg *dec_arg = (decode_serverlist_arg *)*arg; +static bool decode_serverlist(pb_istream_t* stream, const pb_field_t* field, + void** arg) { + decode_serverlist_arg* dec_arg = (decode_serverlist_arg*)*arg; GPR_ASSERT(dec_arg->serverlist->num_servers >= dec_arg->decoding_idx); - grpc_grpclb_server *server = - (grpc_grpclb_server *)gpr_zalloc(sizeof(grpc_grpclb_server)); + grpc_grpclb_server* server = + (grpc_grpclb_server*)gpr_zalloc(sizeof(grpc_grpclb_server)); if (!pb_decode(stream, grpc_lb_v1_Server_fields, server)) { gpr_free(server); gpr_log(GPR_ERROR, "nanopb error: %s", PB_GET_ERROR(stream)); @@ -59,9 +59,9 @@ static bool decode_serverlist(pb_istream_t *stream, const pb_field_t *field, return true; } -grpc_grpclb_request *grpc_grpclb_request_create(const char *lb_service_name) { - grpc_grpclb_request *req = - (grpc_grpclb_request *)gpr_malloc(sizeof(grpc_grpclb_request)); +grpc_grpclb_request* grpc_grpclb_request_create(const char* lb_service_name) { + grpc_grpclb_request* req = + (grpc_grpclb_request*)gpr_malloc(sizeof(grpc_grpclb_request)); req->has_client_stats = false; req->has_initial_request = true; req->initial_request.has_name = true; @@ -71,25 +71,25 @@ grpc_grpclb_request *grpc_grpclb_request_create(const char *lb_service_name) { } static void populate_timestamp(gpr_timespec timestamp, - struct _grpc_lb_v1_Timestamp *timestamp_pb) { + struct _grpc_lb_v1_Timestamp* timestamp_pb) { timestamp_pb->has_seconds = true; timestamp_pb->seconds = timestamp.tv_sec; timestamp_pb->has_nanos = true; timestamp_pb->nanos = timestamp.tv_nsec; } -static bool encode_string(pb_ostream_t *stream, const pb_field_t *field, - void *const *arg) { - char *str = (char *)*arg; +static bool encode_string(pb_ostream_t* stream, const pb_field_t* field, + void* const* arg) { + char* str = (char*)*arg; if (!pb_encode_tag_for_field(stream, field)) return false; - return pb_encode_string(stream, (uint8_t *)str, strlen(str)); + return pb_encode_string(stream, (uint8_t*)str, strlen(str)); } -static bool encode_drops(pb_ostream_t *stream, const pb_field_t *field, - void *const *arg) { - grpc_grpclb_dropped_call_counts *drop_entries = - (grpc_grpclb_dropped_call_counts *)*arg; - if (drop_entries == NULL) return true; +static bool encode_drops(pb_ostream_t* stream, const pb_field_t* field, + void* const* arg) { + grpc_grpclb_dropped_call_counts* drop_entries = + (grpc_grpclb_dropped_call_counts*)*arg; + if (drop_entries == nullptr) return true; for (size_t i = 0; i < drop_entries->num_entries; ++i) { if (!pb_encode_tag_for_field(stream, field)) return false; grpc_lb_v1_ClientStatsPerToken drop_message; @@ -105,10 +105,10 @@ static bool encode_drops(pb_ostream_t *stream, const pb_field_t *field, return true; } -grpc_grpclb_request *grpc_grpclb_load_report_request_create_locked( - grpc_grpclb_client_stats *client_stats) { - grpc_grpclb_request *req = - (grpc_grpclb_request *)gpr_zalloc(sizeof(grpc_grpclb_request)); +grpc_grpclb_request* grpc_grpclb_load_report_request_create_locked( + grpc_grpclb_client_stats* client_stats) { + grpc_grpclb_request* req = + (grpc_grpclb_request*)gpr_zalloc(sizeof(grpc_grpclb_request)); req->has_client_stats = true; req->client_stats.has_timestamp = true; populate_timestamp(gpr_now(GPR_CLOCK_REALTIME), &req->client_stats.timestamp); @@ -123,12 +123,12 @@ grpc_grpclb_request *grpc_grpclb_load_report_request_create_locked( &req->client_stats.num_calls_finished, &req->client_stats.num_calls_finished_with_client_failed_to_send, &req->client_stats.num_calls_finished_known_received, - (grpc_grpclb_dropped_call_counts **)&req->client_stats + (grpc_grpclb_dropped_call_counts**)&req->client_stats .calls_finished_with_drop.arg); return req; } -grpc_slice grpc_grpclb_request_encode(const grpc_grpclb_request *request) { +grpc_slice grpc_grpclb_request_encode(const grpc_grpclb_request* request) { size_t encoded_length; pb_ostream_t sizestream; pb_ostream_t outputstream; @@ -145,10 +145,10 @@ grpc_slice grpc_grpclb_request_encode(const grpc_grpclb_request *request) { return slice; } -void grpc_grpclb_request_destroy(grpc_grpclb_request *request) { +void grpc_grpclb_request_destroy(grpc_grpclb_request* request) { if (request->has_client_stats) { - grpc_grpclb_dropped_call_counts *drop_entries = - (grpc_grpclb_dropped_call_counts *) + grpc_grpclb_dropped_call_counts* drop_entries = + (grpc_grpclb_dropped_call_counts*) request->client_stats.calls_finished_with_drop.arg; grpc_grpclb_dropped_call_counts_destroy(drop_entries); } @@ -156,7 +156,7 @@ void grpc_grpclb_request_destroy(grpc_grpclb_request *request) { } typedef grpc_lb_v1_LoadBalanceResponse grpc_grpclb_response; -grpc_grpclb_initial_response *grpc_grpclb_initial_response_parse( +grpc_grpclb_initial_response* grpc_grpclb_initial_response_parse( grpc_slice encoded_grpc_grpclb_response) { pb_istream_t stream = pb_istream_from_buffer(GRPC_SLICE_START_PTR(encoded_grpc_grpclb_response), @@ -165,13 +165,13 @@ grpc_grpclb_initial_response *grpc_grpclb_initial_response_parse( memset(&res, 0, sizeof(grpc_grpclb_response)); if (!pb_decode(&stream, grpc_lb_v1_LoadBalanceResponse_fields, &res)) { gpr_log(GPR_ERROR, "nanopb error: %s", PB_GET_ERROR(&stream)); - return NULL; + return nullptr; } - if (!res.has_initial_response) return NULL; + if (!res.has_initial_response) return nullptr; - grpc_grpclb_initial_response *initial_res = - (grpc_grpclb_initial_response *)gpr_malloc( + grpc_grpclb_initial_response* initial_res = + (grpc_grpclb_initial_response*)gpr_malloc( sizeof(grpc_grpclb_initial_response)); memcpy(initial_res, &res.initial_response, sizeof(grpc_grpclb_initial_response)); @@ -179,14 +179,14 @@ grpc_grpclb_initial_response *grpc_grpclb_initial_response_parse( return initial_res; } -grpc_grpclb_serverlist *grpc_grpclb_response_parse_serverlist( +grpc_grpclb_serverlist* grpc_grpclb_response_parse_serverlist( grpc_slice encoded_grpc_grpclb_response) { pb_istream_t stream = pb_istream_from_buffer(GRPC_SLICE_START_PTR(encoded_grpc_grpclb_response), GRPC_SLICE_LENGTH(encoded_grpc_grpclb_response)); pb_istream_t stream_at_start = stream; - grpc_grpclb_serverlist *sl = - (grpc_grpclb_serverlist *)gpr_zalloc(sizeof(grpc_grpclb_serverlist)); + grpc_grpclb_serverlist* sl = + (grpc_grpclb_serverlist*)gpr_zalloc(sizeof(grpc_grpclb_serverlist)); grpc_grpclb_response res; memset(&res, 0, sizeof(grpc_grpclb_response)); // First pass: count number of servers. @@ -196,12 +196,12 @@ grpc_grpclb_serverlist *grpc_grpclb_response_parse_serverlist( if (!status) { gpr_free(sl); gpr_log(GPR_ERROR, "nanopb error: %s", PB_GET_ERROR(&stream)); - return NULL; + return nullptr; } // Second pass: populate servers. if (sl->num_servers > 0) { - sl->servers = (grpc_grpclb_server **)gpr_zalloc( - sizeof(grpc_grpclb_server *) * sl->num_servers); + sl->servers = (grpc_grpclb_server**)gpr_zalloc(sizeof(grpc_grpclb_server*) * + sl->num_servers); decode_serverlist_arg decode_arg; memset(&decode_arg, 0, sizeof(decode_arg)); decode_arg.serverlist = sl; @@ -212,7 +212,7 @@ grpc_grpclb_serverlist *grpc_grpclb_response_parse_serverlist( if (!status) { grpc_grpclb_destroy_serverlist(sl); gpr_log(GPR_ERROR, "nanopb error: %s", PB_GET_ERROR(&stream)); - return NULL; + return nullptr; } } if (res.server_list.has_expiration_interval) { @@ -221,8 +221,8 @@ grpc_grpclb_serverlist *grpc_grpclb_response_parse_serverlist( return sl; } -void grpc_grpclb_destroy_serverlist(grpc_grpclb_serverlist *serverlist) { - if (serverlist == NULL) { +void grpc_grpclb_destroy_serverlist(grpc_grpclb_serverlist* serverlist) { + if (serverlist == nullptr) { return; } for (size_t i = 0; i < serverlist->num_servers; i++) { @@ -232,26 +232,26 @@ void grpc_grpclb_destroy_serverlist(grpc_grpclb_serverlist *serverlist) { gpr_free(serverlist); } -grpc_grpclb_serverlist *grpc_grpclb_serverlist_copy( - const grpc_grpclb_serverlist *sl) { - grpc_grpclb_serverlist *copy = - (grpc_grpclb_serverlist *)gpr_zalloc(sizeof(grpc_grpclb_serverlist)); +grpc_grpclb_serverlist* grpc_grpclb_serverlist_copy( + const grpc_grpclb_serverlist* sl) { + grpc_grpclb_serverlist* copy = + (grpc_grpclb_serverlist*)gpr_zalloc(sizeof(grpc_grpclb_serverlist)); copy->num_servers = sl->num_servers; memcpy(©->expiration_interval, &sl->expiration_interval, sizeof(grpc_grpclb_duration)); - copy->servers = (grpc_grpclb_server **)gpr_malloc( - sizeof(grpc_grpclb_server *) * sl->num_servers); + copy->servers = (grpc_grpclb_server**)gpr_malloc(sizeof(grpc_grpclb_server*) * + sl->num_servers); for (size_t i = 0; i < sl->num_servers; i++) { copy->servers[i] = - (grpc_grpclb_server *)gpr_malloc(sizeof(grpc_grpclb_server)); + (grpc_grpclb_server*)gpr_malloc(sizeof(grpc_grpclb_server)); memcpy(copy->servers[i], sl->servers[i], sizeof(grpc_grpclb_server)); } return copy; } -bool grpc_grpclb_serverlist_equals(const grpc_grpclb_serverlist *lhs, - const grpc_grpclb_serverlist *rhs) { - if (lhs == NULL || rhs == NULL) { +bool grpc_grpclb_serverlist_equals(const grpc_grpclb_serverlist* lhs, + const grpc_grpclb_serverlist* rhs) { + if (lhs == nullptr || rhs == nullptr) { return false; } if (lhs->num_servers != rhs->num_servers) { @@ -269,13 +269,13 @@ bool grpc_grpclb_serverlist_equals(const grpc_grpclb_serverlist *lhs, return true; } -bool grpc_grpclb_server_equals(const grpc_grpclb_server *lhs, - const grpc_grpclb_server *rhs) { +bool grpc_grpclb_server_equals(const grpc_grpclb_server* lhs, + const grpc_grpclb_server* rhs) { return memcmp(lhs, rhs, sizeof(grpc_grpclb_server)) == 0; } -int grpc_grpclb_duration_compare(const grpc_grpclb_duration *lhs, - const grpc_grpclb_duration *rhs) { +int grpc_grpclb_duration_compare(const grpc_grpclb_duration* lhs, + const grpc_grpclb_duration* rhs) { GPR_ASSERT(lhs && rhs); if (lhs->has_seconds && rhs->has_seconds) { if (lhs->seconds < rhs->seconds) return -1; @@ -299,13 +299,13 @@ int grpc_grpclb_duration_compare(const grpc_grpclb_duration *lhs, return 0; } -grpc_millis grpc_grpclb_duration_to_millis(grpc_grpclb_duration *duration_pb) { +grpc_millis grpc_grpclb_duration_to_millis(grpc_grpclb_duration* duration_pb) { return (grpc_millis)( (duration_pb->has_seconds ? duration_pb->seconds : 0) * GPR_MS_PER_SEC + (duration_pb->has_nanos ? duration_pb->nanos : 0) / GPR_NS_PER_MS); } void grpc_grpclb_initial_response_destroy( - grpc_grpclb_initial_response *response) { + grpc_grpclb_initial_response* response) { gpr_free(response); } diff --git a/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h b/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h index 56b9c096d06..017c40ec1a3 100644 --- a/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h +++ b/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h @@ -25,10 +25,6 @@ #include "src/core/ext/filters/client_channel/lb_policy/grpclb/proto/grpc/lb/v1/load_balancer.pb.h" #include "src/core/ext/filters/client_channel/lb_policy_factory.h" -#ifdef __cplusplus -extern "C" { -#endif - #define GRPC_GRPCLB_SERVICE_NAME_MAX_LENGTH 128 typedef grpc_lb_v1_Server_ip_address_t grpc_grpclb_ip_address; @@ -37,59 +33,55 @@ typedef grpc_lb_v1_InitialLoadBalanceResponse grpc_grpclb_initial_response; typedef grpc_lb_v1_Server grpc_grpclb_server; typedef grpc_lb_v1_Duration grpc_grpclb_duration; typedef struct { - grpc_grpclb_server **servers; + grpc_grpclb_server** servers; size_t num_servers; grpc_grpclb_duration expiration_interval; } grpc_grpclb_serverlist; /** Create a request for a gRPC LB service under \a lb_service_name */ -grpc_grpclb_request *grpc_grpclb_request_create(const char *lb_service_name); -grpc_grpclb_request *grpc_grpclb_load_report_request_create_locked( - grpc_grpclb_client_stats *client_stats); +grpc_grpclb_request* grpc_grpclb_request_create(const char* lb_service_name); +grpc_grpclb_request* grpc_grpclb_load_report_request_create_locked( + grpc_grpclb_client_stats* client_stats); /** Protocol Buffers v3-encode \a request */ -grpc_slice grpc_grpclb_request_encode(const grpc_grpclb_request *request); +grpc_slice grpc_grpclb_request_encode(const grpc_grpclb_request* request); /** Destroy \a request */ -void grpc_grpclb_request_destroy(grpc_grpclb_request *request); +void grpc_grpclb_request_destroy(grpc_grpclb_request* request); /** Parse (ie, decode) the bytes in \a encoded_grpc_grpclb_response as a \a * grpc_grpclb_initial_response */ -grpc_grpclb_initial_response *grpc_grpclb_initial_response_parse( +grpc_grpclb_initial_response* grpc_grpclb_initial_response_parse( grpc_slice encoded_grpc_grpclb_response); /** Parse the list of servers from an encoded \a grpc_grpclb_response */ -grpc_grpclb_serverlist *grpc_grpclb_response_parse_serverlist( +grpc_grpclb_serverlist* grpc_grpclb_response_parse_serverlist( grpc_slice encoded_grpc_grpclb_response); /** Return a copy of \a sl. The caller is responsible for calling \a * grpc_grpclb_destroy_serverlist on the returned copy. */ -grpc_grpclb_serverlist *grpc_grpclb_serverlist_copy( - const grpc_grpclb_serverlist *sl); +grpc_grpclb_serverlist* grpc_grpclb_serverlist_copy( + const grpc_grpclb_serverlist* sl); -bool grpc_grpclb_serverlist_equals(const grpc_grpclb_serverlist *lhs, - const grpc_grpclb_serverlist *rhs); +bool grpc_grpclb_serverlist_equals(const grpc_grpclb_serverlist* lhs, + const grpc_grpclb_serverlist* rhs); -bool grpc_grpclb_server_equals(const grpc_grpclb_server *lhs, - const grpc_grpclb_server *rhs); +bool grpc_grpclb_server_equals(const grpc_grpclb_server* lhs, + const grpc_grpclb_server* rhs); /** Destroy \a serverlist */ -void grpc_grpclb_destroy_serverlist(grpc_grpclb_serverlist *serverlist); +void grpc_grpclb_destroy_serverlist(grpc_grpclb_serverlist* serverlist); /** Compare \a lhs against \a rhs and return 0 if \a lhs and \a rhs are equal, * < 0 if \a lhs represents a duration shorter than \a rhs and > 0 otherwise */ -int grpc_grpclb_duration_compare(const grpc_grpclb_duration *lhs, - const grpc_grpclb_duration *rhs); +int grpc_grpclb_duration_compare(const grpc_grpclb_duration* lhs, + const grpc_grpclb_duration* rhs); -grpc_millis grpc_grpclb_duration_to_millis(grpc_grpclb_duration *duration_pb); +grpc_millis grpc_grpclb_duration_to_millis(grpc_grpclb_duration* duration_pb); /** Destroy \a initial_response */ void grpc_grpclb_initial_response_destroy( - grpc_grpclb_initial_response *response); - -#ifdef __cplusplus -} -#endif + grpc_grpclb_initial_response* response); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_LOAD_BALANCER_API_H \ - */ + */ diff --git a/src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc b/src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc index f0c66c68e1f..228a77d9db7 100644 --- a/src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc +++ b/src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc @@ -29,92 +29,89 @@ #include "src/core/lib/iomgr/sockaddr_utils.h" #include "src/core/lib/transport/connectivity_state.h" -grpc_tracer_flag grpc_lb_pick_first_trace = - GRPC_TRACER_INITIALIZER(false, "pick_first"); +grpc_core::TraceFlag grpc_lb_pick_first_trace(false, "pick_first"); typedef struct pending_pick { - struct pending_pick *next; + struct pending_pick* next; uint32_t initial_metadata_flags; - grpc_connected_subchannel **target; - grpc_closure *on_complete; + grpc_connected_subchannel** target; + grpc_closure* on_complete; } pending_pick; typedef struct { /** base policy: must be first */ grpc_lb_policy base; /** all our subchannels */ - grpc_lb_subchannel_list *subchannel_list; + grpc_lb_subchannel_list* subchannel_list; /** latest pending subchannel list */ - grpc_lb_subchannel_list *latest_pending_subchannel_list; + grpc_lb_subchannel_list* latest_pending_subchannel_list; /** selected subchannel in \a subchannel_list */ - grpc_lb_subchannel_data *selected; + grpc_lb_subchannel_data* selected; /** have we started picking? */ bool started_picking; /** are we shut down? */ bool shutdown; /** list of picks that are waiting on connectivity */ - pending_pick *pending_picks; + pending_pick* pending_picks; /** our connectivity state tracker */ grpc_connectivity_state_tracker state_tracker; } pick_first_lb_policy; -static void pf_destroy(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { - pick_first_lb_policy *p = (pick_first_lb_policy *)pol; - GPR_ASSERT(p->subchannel_list == NULL); - GPR_ASSERT(p->latest_pending_subchannel_list == NULL); - GPR_ASSERT(p->pending_picks == NULL); +static void pf_destroy(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol) { + pick_first_lb_policy* p = (pick_first_lb_policy*)pol; + GPR_ASSERT(p->subchannel_list == nullptr); + GPR_ASSERT(p->latest_pending_subchannel_list == nullptr); + GPR_ASSERT(p->pending_picks == nullptr); grpc_connectivity_state_destroy(exec_ctx, &p->state_tracker); gpr_free(p); grpc_subchannel_index_unref(); - if (GRPC_TRACER_ON(grpc_lb_pick_first_trace)) { - gpr_log(GPR_DEBUG, "Pick First %p destroyed.", (void *)p); + if (grpc_lb_pick_first_trace.enabled()) { + gpr_log(GPR_DEBUG, "Pick First %p destroyed.", (void*)p); } } -static void shutdown_locked(grpc_exec_ctx *exec_ctx, pick_first_lb_policy *p, - grpc_error *error) { - if (GRPC_TRACER_ON(grpc_lb_pick_first_trace)) { +static void pf_shutdown_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol) { + pick_first_lb_policy* p = (pick_first_lb_policy*)pol; + grpc_error* error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Channel shutdown"); + if (grpc_lb_pick_first_trace.enabled()) { gpr_log(GPR_DEBUG, "Pick First %p Shutting down", p); } p->shutdown = true; - pending_pick *pp; - while ((pp = p->pending_picks) != NULL) { + pending_pick* pp; + while ((pp = p->pending_picks) != nullptr) { p->pending_picks = pp->next; - *pp->target = NULL; + *pp->target = nullptr; GRPC_CLOSURE_SCHED(exec_ctx, pp->on_complete, GRPC_ERROR_REF(error)); gpr_free(pp); } grpc_connectivity_state_set(exec_ctx, &p->state_tracker, GRPC_CHANNEL_SHUTDOWN, GRPC_ERROR_REF(error), "shutdown"); - if (p->subchannel_list != NULL) { + if (p->subchannel_list != nullptr) { grpc_lb_subchannel_list_shutdown_and_unref(exec_ctx, p->subchannel_list, "pf_shutdown"); - p->subchannel_list = NULL; + p->subchannel_list = nullptr; } - if (p->latest_pending_subchannel_list != NULL) { + if (p->latest_pending_subchannel_list != nullptr) { grpc_lb_subchannel_list_shutdown_and_unref( exec_ctx, p->latest_pending_subchannel_list, "pf_shutdown"); - p->latest_pending_subchannel_list = NULL; + p->latest_pending_subchannel_list = nullptr; } + grpc_lb_policy_try_reresolve(exec_ctx, &p->base, &grpc_lb_pick_first_trace, + GRPC_ERROR_CANCELLED); GRPC_ERROR_UNREF(error); } -static void pf_shutdown_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { - shutdown_locked(exec_ctx, (pick_first_lb_policy *)pol, - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Channel shutdown")); -} - -static void pf_cancel_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, - grpc_connected_subchannel **target, - grpc_error *error) { - pick_first_lb_policy *p = (pick_first_lb_policy *)pol; - pending_pick *pp = p->pending_picks; - p->pending_picks = NULL; - while (pp != NULL) { - pending_pick *next = pp->next; +static void pf_cancel_pick_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol, + grpc_connected_subchannel** target, + grpc_error* error) { + pick_first_lb_policy* p = (pick_first_lb_policy*)pol; + pending_pick* pp = p->pending_picks; + p->pending_picks = nullptr; + while (pp != nullptr) { + pending_pick* next = pp->next; if (pp->target == target) { - *target = NULL; + *target = nullptr; GRPC_CLOSURE_SCHED(exec_ctx, pp->on_complete, GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Pick Cancelled", &error, 1)); @@ -128,15 +125,15 @@ static void pf_cancel_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, GRPC_ERROR_UNREF(error); } -static void pf_cancel_picks_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, +static void pf_cancel_picks_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol, uint32_t initial_metadata_flags_mask, uint32_t initial_metadata_flags_eq, - grpc_error *error) { - pick_first_lb_policy *p = (pick_first_lb_policy *)pol; - pending_pick *pp = p->pending_picks; - p->pending_picks = NULL; - while (pp != NULL) { - pending_pick *next = pp->next; + grpc_error* error) { + pick_first_lb_policy* p = (pick_first_lb_policy*)pol; + pending_pick* pp = p->pending_picks; + p->pending_picks = nullptr; + while (pp != nullptr) { + pending_pick* next = pp->next; if ((pp->initial_metadata_flags & initial_metadata_flags_mask) == initial_metadata_flags_eq) { GRPC_CLOSURE_SCHED(exec_ctx, pp->on_complete, @@ -152,33 +149,39 @@ static void pf_cancel_picks_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, GRPC_ERROR_UNREF(error); } -static void start_picking_locked(grpc_exec_ctx *exec_ctx, - pick_first_lb_policy *p) { +static void start_picking_locked(grpc_exec_ctx* exec_ctx, + pick_first_lb_policy* p) { p->started_picking = true; - if (p->subchannel_list != NULL && p->subchannel_list->num_subchannels > 0) { + if (p->subchannel_list != nullptr && + p->subchannel_list->num_subchannels > 0) { p->subchannel_list->checking_subchannel = 0; - grpc_lb_subchannel_list_ref_for_connectivity_watch( - p->subchannel_list, "connectivity_watch+start_picking"); - grpc_lb_subchannel_data_start_connectivity_watch( - exec_ctx, &p->subchannel_list->subchannels[0]); + for (size_t i = 0; i < p->subchannel_list->num_subchannels; ++i) { + if (p->subchannel_list->subchannels[i].subchannel != nullptr) { + grpc_lb_subchannel_list_ref_for_connectivity_watch( + p->subchannel_list, "connectivity_watch+start_picking"); + grpc_lb_subchannel_data_start_connectivity_watch( + exec_ctx, &p->subchannel_list->subchannels[i]); + break; + } + } } } -static void pf_exit_idle_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { - pick_first_lb_policy *p = (pick_first_lb_policy *)pol; +static void pf_exit_idle_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol) { + pick_first_lb_policy* p = (pick_first_lb_policy*)pol; if (!p->started_picking) { start_picking_locked(exec_ctx, p); } } -static int pf_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, - const grpc_lb_policy_pick_args *pick_args, - grpc_connected_subchannel **target, - grpc_call_context_element *context, void **user_data, - grpc_closure *on_complete) { - pick_first_lb_policy *p = (pick_first_lb_policy *)pol; +static int pf_pick_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol, + const grpc_lb_policy_pick_args* pick_args, + grpc_connected_subchannel** target, + grpc_call_context_element* context, void** user_data, + grpc_closure* on_complete) { + pick_first_lb_policy* p = (pick_first_lb_policy*)pol; // If we have a selected subchannel already, return synchronously. - if (p->selected != NULL) { + if (p->selected != nullptr) { *target = GRPC_CONNECTED_SUBCHANNEL_REF(p->selected->connected_subchannel, "picked"); return 1; @@ -187,7 +190,7 @@ static int pf_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, if (!p->started_picking) { start_picking_locked(exec_ctx, p); } - pending_pick *pp = (pending_pick *)gpr_malloc(sizeof(*pp)); + pending_pick* pp = (pending_pick*)gpr_malloc(sizeof(*pp)); pp->next = p->pending_picks; pp->target = target; pp->initial_metadata_flags = pick_args->initial_metadata_flags; @@ -196,10 +199,10 @@ static int pf_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, return 0; } -static void destroy_unselected_subchannels_locked(grpc_exec_ctx *exec_ctx, - pick_first_lb_policy *p) { +static void destroy_unselected_subchannels_locked(grpc_exec_ctx* exec_ctx, + pick_first_lb_policy* p) { for (size_t i = 0; i < p->subchannel_list->num_subchannels; ++i) { - grpc_lb_subchannel_data *sd = &p->subchannel_list->subchannels[i]; + grpc_lb_subchannel_data* sd = &p->subchannel_list->subchannels[i]; if (p->selected != sd) { grpc_lb_subchannel_data_unref_subchannel(exec_ctx, sd, "selected_different_subchannel"); @@ -208,23 +211,23 @@ static void destroy_unselected_subchannels_locked(grpc_exec_ctx *exec_ctx, } static grpc_connectivity_state pf_check_connectivity_locked( - grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, grpc_error **error) { - pick_first_lb_policy *p = (pick_first_lb_policy *)pol; + grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol, grpc_error** error) { + pick_first_lb_policy* p = (pick_first_lb_policy*)pol; return grpc_connectivity_state_get(&p->state_tracker, error); } -static void pf_notify_on_state_change_locked(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *pol, - grpc_connectivity_state *current, - grpc_closure *notify) { - pick_first_lb_policy *p = (pick_first_lb_policy *)pol; +static void pf_notify_on_state_change_locked(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* pol, + grpc_connectivity_state* current, + grpc_closure* notify) { + pick_first_lb_policy* p = (pick_first_lb_policy*)pol; grpc_connectivity_state_notify_on_state_change(exec_ctx, &p->state_tracker, current, notify); } -static void pf_ping_one_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, - grpc_closure *closure) { - pick_first_lb_policy *p = (pick_first_lb_policy *)pol; +static void pf_ping_one_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol, + grpc_closure* closure) { + pick_first_lb_policy* p = (pick_first_lb_policy*)pol; if (p->selected) { grpc_connected_subchannel_ping(exec_ctx, p->selected->connected_subchannel, closure); @@ -234,16 +237,16 @@ static void pf_ping_one_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, } } -static void pf_connectivity_changed_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error); +static void pf_connectivity_changed_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error); -static void pf_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, - const grpc_lb_policy_args *args) { - pick_first_lb_policy *p = (pick_first_lb_policy *)policy; - const grpc_arg *arg = +static void pf_update_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + const grpc_lb_policy_args* args) { + pick_first_lb_policy* p = (pick_first_lb_policy*)policy; + const grpc_arg* arg = grpc_channel_args_find(args->args, GRPC_ARG_LB_ADDRESSES); - if (arg == NULL || arg->type != GRPC_ARG_POINTER) { - if (p->subchannel_list == NULL) { + if (arg == nullptr || arg->type != GRPC_ARG_POINTER) { + if (p->subchannel_list == nullptr) { // If we don't have a current subchannel list, go into TRANSIENT FAILURE. grpc_connectivity_state_set( exec_ctx, &p->state_tracker, GRPC_CHANNEL_TRANSIENT_FAILURE, @@ -254,17 +257,17 @@ static void pf_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, gpr_log(GPR_ERROR, "No valid LB addresses channel arg for Pick First %p update, " "ignoring.", - (void *)p); + (void*)p); } return; } - const grpc_lb_addresses *addresses = - (const grpc_lb_addresses *)arg->value.pointer.p; - if (GRPC_TRACER_ON(grpc_lb_pick_first_trace)) { + const grpc_lb_addresses* addresses = + (const grpc_lb_addresses*)arg->value.pointer.p; + if (grpc_lb_pick_first_trace.enabled()) { gpr_log(GPR_INFO, "Pick First %p received update with %lu addresses", - (void *)p, (unsigned long)addresses->num_addresses); + (void*)p, (unsigned long)addresses->num_addresses); } - grpc_lb_subchannel_list *subchannel_list = grpc_lb_subchannel_list_create( + grpc_lb_subchannel_list* subchannel_list = grpc_lb_subchannel_list_create( exec_ctx, &p->base, &grpc_lb_pick_first_trace, addresses, args, pf_connectivity_changed_locked); if (subchannel_list->num_subchannels == 0) { @@ -274,18 +277,18 @@ static void pf_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, exec_ctx, &p->state_tracker, GRPC_CHANNEL_TRANSIENT_FAILURE, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Empty update"), "pf_update_empty"); - if (p->subchannel_list != NULL) { + if (p->subchannel_list != nullptr) { grpc_lb_subchannel_list_shutdown_and_unref(exec_ctx, p->subchannel_list, "sl_shutdown_empty_update"); } p->subchannel_list = subchannel_list; // Empty list. - p->selected = NULL; + p->selected = nullptr; return; } - if (p->selected == NULL) { + if (p->selected == nullptr) { // We don't yet have a selected subchannel, so replace the current // subchannel list immediately. - if (p->subchannel_list != NULL) { + if (p->subchannel_list != nullptr) { grpc_lb_subchannel_list_shutdown_and_unref(exec_ctx, p->subchannel_list, "pf_update_before_selected"); } @@ -294,38 +297,38 @@ static void pf_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, // We do have a selected subchannel. // Check if it's present in the new list. If so, we're done. for (size_t i = 0; i < subchannel_list->num_subchannels; ++i) { - grpc_lb_subchannel_data *sd = &subchannel_list->subchannels[i]; + grpc_lb_subchannel_data* sd = &subchannel_list->subchannels[i]; if (sd->subchannel == p->selected->subchannel) { // The currently selected subchannel is in the update: we are done. - if (GRPC_TRACER_ON(grpc_lb_pick_first_trace)) { + if (grpc_lb_pick_first_trace.enabled()) { gpr_log(GPR_INFO, "Pick First %p found already selected subchannel %p " "at update index %" PRIuPTR " of %" PRIuPTR "; update done", p, p->selected->subchannel, i, subchannel_list->num_subchannels); } - grpc_lb_subchannel_list_ref_for_connectivity_watch( - subchannel_list, "connectivity_watch+replace_selected"); - grpc_lb_subchannel_data_start_connectivity_watch(exec_ctx, sd); - if (p->subchannel_list != NULL) { - grpc_lb_subchannel_list_shutdown_and_unref( - exec_ctx, p->subchannel_list, "pf_update_includes_selected"); - } - p->subchannel_list = subchannel_list; - if (p->selected->connected_subchannel != NULL) { + if (p->selected->connected_subchannel != nullptr) { sd->connected_subchannel = GRPC_CONNECTED_SUBCHANNEL_REF( p->selected->connected_subchannel, "pf_update_includes_selected"); } p->selected = sd; + if (p->subchannel_list != nullptr) { + grpc_lb_subchannel_list_shutdown_and_unref( + exec_ctx, p->subchannel_list, "pf_update_includes_selected"); + } + p->subchannel_list = subchannel_list; destroy_unselected_subchannels_locked(exec_ctx, p); + grpc_lb_subchannel_list_ref_for_connectivity_watch( + subchannel_list, "connectivity_watch+replace_selected"); + grpc_lb_subchannel_data_start_connectivity_watch(exec_ctx, sd); // If there was a previously pending update (which may or may // not have contained the currently selected subchannel), drop // it, so that it doesn't override what we've done here. - if (p->latest_pending_subchannel_list != NULL) { + if (p->latest_pending_subchannel_list != nullptr) { grpc_lb_subchannel_list_shutdown_and_unref( exec_ctx, p->latest_pending_subchannel_list, "pf_update_includes_selected+outdated"); - p->latest_pending_subchannel_list = NULL; + p->latest_pending_subchannel_list = nullptr; } return; } @@ -334,13 +337,13 @@ static void pf_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, // pending subchannel list to the new subchannel list. We will wait // for it to report READY before swapping it into the current // subchannel list. - if (p->latest_pending_subchannel_list != NULL) { - if (GRPC_TRACER_ON(grpc_lb_pick_first_trace)) { + if (p->latest_pending_subchannel_list != nullptr) { + if (grpc_lb_pick_first_trace.enabled()) { gpr_log(GPR_DEBUG, "Pick First %p Shutting down latest pending subchannel list " "%p, about to be replaced by newer latest %p", - (void *)p, (void *)p->latest_pending_subchannel_list, - (void *)subchannel_list); + (void*)p, (void*)p->latest_pending_subchannel_list, + (void*)subchannel_list); } grpc_lb_subchannel_list_shutdown_and_unref( exec_ctx, p->latest_pending_subchannel_list, @@ -358,19 +361,19 @@ static void pf_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, } } -static void pf_connectivity_changed_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_lb_subchannel_data *sd = (grpc_lb_subchannel_data *)arg; - pick_first_lb_policy *p = (pick_first_lb_policy *)sd->subchannel_list->policy; - if (GRPC_TRACER_ON(grpc_lb_pick_first_trace)) { +static void pf_connectivity_changed_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_lb_subchannel_data* sd = (grpc_lb_subchannel_data*)arg; + pick_first_lb_policy* p = (pick_first_lb_policy*)sd->subchannel_list->policy; + if (grpc_lb_pick_first_trace.enabled()) { gpr_log(GPR_DEBUG, "Pick First %p connectivity changed for subchannel %p (%" PRIuPTR " of %" PRIuPTR "), subchannel_list %p: state=%s p->shutdown=%d " "sd->subchannel_list->shutting_down=%d error=%s", - (void *)p, (void *)sd->subchannel, + (void*)p, (void*)sd->subchannel, sd->subchannel_list->checking_subchannel, - sd->subchannel_list->num_subchannels, (void *)sd->subchannel_list, + sd->subchannel_list->num_subchannels, (void*)sd->subchannel_list, grpc_connectivity_state_name(sd->pending_connectivity_state_unsafe), p->shutdown, sd->subchannel_list->shutting_down, grpc_error_string(error)); @@ -402,31 +405,48 @@ static void pf_connectivity_changed_locked(grpc_exec_ctx *exec_ctx, void *arg, // If the new state is anything other than READY and there is a // pending update, switch to the pending update. if (sd->curr_connectivity_state != GRPC_CHANNEL_READY && - p->latest_pending_subchannel_list != NULL) { - p->selected = NULL; + p->latest_pending_subchannel_list != nullptr) { + p->selected = nullptr; + grpc_lb_subchannel_data_stop_connectivity_watch(exec_ctx, sd); + grpc_lb_subchannel_list_unref_for_connectivity_watch( + exec_ctx, sd->subchannel_list, "selected_not_ready+switch_to_update"); grpc_lb_subchannel_list_shutdown_and_unref( exec_ctx, p->subchannel_list, "selected_not_ready+switch_to_update"); p->subchannel_list = p->latest_pending_subchannel_list; - p->latest_pending_subchannel_list = NULL; + p->latest_pending_subchannel_list = nullptr; grpc_connectivity_state_set( exec_ctx, &p->state_tracker, GRPC_CHANNEL_TRANSIENT_FAILURE, GRPC_ERROR_REF(error), "selected_not_ready+switch_to_update"); } else { - if (sd->curr_connectivity_state == GRPC_CHANNEL_TRANSIENT_FAILURE) { - /* if the selected channel goes bad, we're done */ - sd->curr_connectivity_state = GRPC_CHANNEL_SHUTDOWN; + // TODO(juanlishen): we re-resolve when the selected subchannel goes to + // TRANSIENT_FAILURE because we used to shut down in this case before + // re-resolution is introduced. But we need to investigate whether we + // really want to take any action instead of waiting for the selected + // subchannel reconnecting. + if (sd->curr_connectivity_state == GRPC_CHANNEL_SHUTDOWN || + sd->curr_connectivity_state == GRPC_CHANNEL_TRANSIENT_FAILURE) { + // If the selected channel goes bad, request a re-resolution. + grpc_connectivity_state_set(exec_ctx, &p->state_tracker, + GRPC_CHANNEL_IDLE, GRPC_ERROR_NONE, + "selected_changed+reresolve"); + p->started_picking = false; + grpc_lb_policy_try_reresolve( + exec_ctx, &p->base, &grpc_lb_pick_first_trace, GRPC_ERROR_NONE); + } else { + grpc_connectivity_state_set(exec_ctx, &p->state_tracker, + sd->curr_connectivity_state, + GRPC_ERROR_REF(error), "selected_changed"); } - grpc_connectivity_state_set(exec_ctx, &p->state_tracker, - sd->curr_connectivity_state, - GRPC_ERROR_REF(error), "selected_changed"); if (sd->curr_connectivity_state != GRPC_CHANNEL_SHUTDOWN) { // Renew notification. grpc_lb_subchannel_data_start_connectivity_watch(exec_ctx, sd); } else { + p->selected = nullptr; grpc_lb_subchannel_data_stop_connectivity_watch(exec_ctx, sd); grpc_lb_subchannel_list_unref_for_connectivity_watch( exec_ctx, sd->subchannel_list, "pf_selected_shutdown"); - shutdown_locked(exec_ctx, p, GRPC_ERROR_REF(error)); + grpc_lb_subchannel_data_unref_subchannel(exec_ctx, sd, + "pf_selected_shutdown"); } } return; @@ -440,132 +460,128 @@ static void pf_connectivity_changed_locked(grpc_exec_ctx *exec_ctx, void *arg, // for a subchannel in p->latest_pending_subchannel_list. The // goal here is to find a subchannel from the update that we can // select in place of the current one. - if (sd->curr_connectivity_state == GRPC_CHANNEL_TRANSIENT_FAILURE || - sd->curr_connectivity_state == GRPC_CHANNEL_SHUTDOWN) { - grpc_lb_subchannel_data_stop_connectivity_watch(exec_ctx, sd); - } - while (true) { - switch (sd->curr_connectivity_state) { - case GRPC_CHANNEL_READY: { - // Case 2. Promote p->latest_pending_subchannel_list to - // p->subchannel_list. - if (sd->subchannel_list == p->latest_pending_subchannel_list) { - GPR_ASSERT(p->subchannel_list != NULL); - grpc_lb_subchannel_list_shutdown_and_unref( - exec_ctx, p->subchannel_list, "finish_update"); - p->subchannel_list = p->latest_pending_subchannel_list; - p->latest_pending_subchannel_list = NULL; - } - // Cases 1 and 2. - grpc_connectivity_state_set(exec_ctx, &p->state_tracker, - GRPC_CHANNEL_READY, GRPC_ERROR_NONE, - "connecting_ready"); - sd->connected_subchannel = GRPC_CONNECTED_SUBCHANNEL_REF( - grpc_subchannel_get_connected_subchannel(sd->subchannel), - "connected"); - p->selected = sd; - if (GRPC_TRACER_ON(grpc_lb_pick_first_trace)) { - gpr_log(GPR_INFO, "Pick First %p selected subchannel %p", (void *)p, - (void *)sd->subchannel); - } - // Drop all other subchannels, since we are now connected. - destroy_unselected_subchannels_locked(exec_ctx, p); - // Update any calls that were waiting for a pick. - pending_pick *pp; - while ((pp = p->pending_picks)) { - p->pending_picks = pp->next; - *pp->target = GRPC_CONNECTED_SUBCHANNEL_REF( - p->selected->connected_subchannel, "picked"); - if (GRPC_TRACER_ON(grpc_lb_pick_first_trace)) { - gpr_log(GPR_INFO, - "Servicing pending pick with selected subchannel %p", - (void *)p->selected); - } - GRPC_CLOSURE_SCHED(exec_ctx, pp->on_complete, GRPC_ERROR_NONE); - gpr_free(pp); - } - // Renew notification. - grpc_lb_subchannel_data_start_connectivity_watch(exec_ctx, sd); - return; + switch (sd->curr_connectivity_state) { + case GRPC_CHANNEL_READY: { + // Case 2. Promote p->latest_pending_subchannel_list to + // p->subchannel_list. + if (sd->subchannel_list == p->latest_pending_subchannel_list) { + GPR_ASSERT(p->subchannel_list != nullptr); + grpc_lb_subchannel_list_shutdown_and_unref(exec_ctx, p->subchannel_list, + "finish_update"); + p->subchannel_list = p->latest_pending_subchannel_list; + p->latest_pending_subchannel_list = nullptr; } - case GRPC_CHANNEL_TRANSIENT_FAILURE: { - do { - sd->subchannel_list->checking_subchannel = - (sd->subchannel_list->checking_subchannel + 1) % - sd->subchannel_list->num_subchannels; - sd = &sd->subchannel_list - ->subchannels[sd->subchannel_list->checking_subchannel]; - } while (sd->subchannel == NULL); - // Case 1: Only set state to TRANSIENT_FAILURE if we've tried - // all subchannels. - if (sd->subchannel_list->checking_subchannel == 0 && - sd->subchannel_list == p->subchannel_list) { - grpc_connectivity_state_set( - exec_ctx, &p->state_tracker, GRPC_CHANNEL_TRANSIENT_FAILURE, - GRPC_ERROR_REF(error), "connecting_transient_failure"); - } - sd->curr_connectivity_state = - grpc_subchannel_check_connectivity(sd->subchannel, &error); - GRPC_ERROR_UNREF(error); - if (sd->curr_connectivity_state == GRPC_CHANNEL_TRANSIENT_FAILURE) { - // Reuses the connectivity refs from the previous watch. - grpc_lb_subchannel_data_start_connectivity_watch(exec_ctx, sd); - return; - } - break; // Go back to top of loop. + // Cases 1 and 2. + grpc_connectivity_state_set(exec_ctx, &p->state_tracker, + GRPC_CHANNEL_READY, GRPC_ERROR_NONE, + "connecting_ready"); + sd->connected_subchannel = GRPC_CONNECTED_SUBCHANNEL_REF( + grpc_subchannel_get_connected_subchannel(sd->subchannel), + "connected"); + p->selected = sd; + if (grpc_lb_pick_first_trace.enabled()) { + gpr_log(GPR_INFO, "Pick First %p selected subchannel %p", (void*)p, + (void*)sd->subchannel); } - case GRPC_CHANNEL_CONNECTING: - case GRPC_CHANNEL_IDLE: { - // Only update connectivity state in case 1. - if (sd->subchannel_list == p->subchannel_list) { - grpc_connectivity_state_set( - exec_ctx, &p->state_tracker, GRPC_CHANNEL_CONNECTING, - GRPC_ERROR_REF(error), "connecting_changed"); + // Drop all other subchannels, since we are now connected. + destroy_unselected_subchannels_locked(exec_ctx, p); + // Update any calls that were waiting for a pick. + pending_pick* pp; + while ((pp = p->pending_picks)) { + p->pending_picks = pp->next; + *pp->target = GRPC_CONNECTED_SUBCHANNEL_REF( + p->selected->connected_subchannel, "picked"); + if (grpc_lb_pick_first_trace.enabled()) { + gpr_log(GPR_INFO, + "Servicing pending pick with selected subchannel %p", + (void*)p->selected); } - // Renew notification. - grpc_lb_subchannel_data_start_connectivity_watch(exec_ctx, sd); - return; + GRPC_CLOSURE_SCHED(exec_ctx, pp->on_complete, GRPC_ERROR_NONE); + gpr_free(pp); } - case GRPC_CHANNEL_SHUTDOWN: { - grpc_lb_subchannel_data_unref_subchannel(exec_ctx, sd, - "pf_candidate_shutdown"); - // Advance to next subchannel and check its state. - grpc_lb_subchannel_data *original_sd = sd; - do { - sd->subchannel_list->checking_subchannel = - (sd->subchannel_list->checking_subchannel + 1) % - sd->subchannel_list->num_subchannels; - sd = &sd->subchannel_list - ->subchannels[sd->subchannel_list->checking_subchannel]; - } while (sd->subchannel == NULL && sd != original_sd); - if (sd == original_sd) { - grpc_lb_subchannel_list_unref_for_connectivity_watch( - exec_ctx, sd->subchannel_list, "pf_candidate_shutdown"); - shutdown_locked(exec_ctx, p, - GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( - "Pick first exhausted channels", &error, 1)); - return; + // Renew notification. + grpc_lb_subchannel_data_start_connectivity_watch(exec_ctx, sd); + break; + } + case GRPC_CHANNEL_TRANSIENT_FAILURE: { + grpc_lb_subchannel_data_stop_connectivity_watch(exec_ctx, sd); + do { + sd->subchannel_list->checking_subchannel = + (sd->subchannel_list->checking_subchannel + 1) % + sd->subchannel_list->num_subchannels; + sd = &sd->subchannel_list + ->subchannels[sd->subchannel_list->checking_subchannel]; + } while (sd->subchannel == nullptr); + // Case 1: Only set state to TRANSIENT_FAILURE if we've tried + // all subchannels. + if (sd->subchannel_list->checking_subchannel == 0 && + sd->subchannel_list == p->subchannel_list) { + grpc_connectivity_state_set( + exec_ctx, &p->state_tracker, GRPC_CHANNEL_TRANSIENT_FAILURE, + GRPC_ERROR_REF(error), "connecting_transient_failure"); + } + // Reuses the connectivity refs from the previous watch. + grpc_lb_subchannel_data_start_connectivity_watch(exec_ctx, sd); + break; + } + case GRPC_CHANNEL_CONNECTING: + case GRPC_CHANNEL_IDLE: { + // Only update connectivity state in case 1. + if (sd->subchannel_list == p->subchannel_list) { + grpc_connectivity_state_set( + exec_ctx, &p->state_tracker, GRPC_CHANNEL_CONNECTING, + GRPC_ERROR_REF(error), "connecting_changed"); + } + // Renew notification. + grpc_lb_subchannel_data_start_connectivity_watch(exec_ctx, sd); + break; + } + case GRPC_CHANNEL_SHUTDOWN: { + grpc_lb_subchannel_data_stop_connectivity_watch(exec_ctx, sd); + grpc_lb_subchannel_data_unref_subchannel(exec_ctx, sd, + "pf_candidate_shutdown"); + // Advance to next subchannel and check its state. + grpc_lb_subchannel_data* original_sd = sd; + do { + sd->subchannel_list->checking_subchannel = + (sd->subchannel_list->checking_subchannel + 1) % + sd->subchannel_list->num_subchannels; + sd = &sd->subchannel_list + ->subchannels[sd->subchannel_list->checking_subchannel]; + } while (sd->subchannel == nullptr && sd != original_sd); + if (sd == original_sd) { + grpc_lb_subchannel_list_unref_for_connectivity_watch( + exec_ctx, sd->subchannel_list, "pf_exhausted_subchannels"); + if (sd->subchannel_list == p->subchannel_list) { + grpc_connectivity_state_set(exec_ctx, &p->state_tracker, + GRPC_CHANNEL_IDLE, GRPC_ERROR_NONE, + "exhausted_subchannels+reresolve"); + p->started_picking = false; + grpc_lb_policy_try_reresolve( + exec_ctx, &p->base, &grpc_lb_pick_first_trace, GRPC_ERROR_NONE); } + } else { if (sd->subchannel_list == p->subchannel_list) { grpc_connectivity_state_set( exec_ctx, &p->state_tracker, GRPC_CHANNEL_TRANSIENT_FAILURE, GRPC_ERROR_REF(error), "subchannel_failed"); } - sd->curr_connectivity_state = - grpc_subchannel_check_connectivity(sd->subchannel, &error); - GRPC_ERROR_UNREF(error); - if (sd->curr_connectivity_state == GRPC_CHANNEL_TRANSIENT_FAILURE) { - // Reuses the connectivity refs from the previous watch. - grpc_lb_subchannel_data_start_connectivity_watch(exec_ctx, sd); - return; - } - // For any other state, go back to top of loop. - // We will reuse the connectivity refs from the previous watch. + // Reuses the connectivity refs from the previous watch. + grpc_lb_subchannel_data_start_connectivity_watch(exec_ctx, sd); } } } } +static void pf_set_reresolve_closure_locked( + grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + grpc_closure* request_reresolution) { + pick_first_lb_policy* p = (pick_first_lb_policy*)policy; + GPR_ASSERT(!p->shutdown); + GPR_ASSERT(policy->request_reresolution == nullptr); + policy->request_reresolution = request_reresolution; +} + static const grpc_lb_policy_vtable pick_first_lb_policy_vtable = { pf_destroy, pf_shutdown_locked, @@ -576,19 +592,20 @@ static const grpc_lb_policy_vtable pick_first_lb_policy_vtable = { pf_exit_idle_locked, pf_check_connectivity_locked, pf_notify_on_state_change_locked, - pf_update_locked}; + pf_update_locked, + pf_set_reresolve_closure_locked}; -static void pick_first_factory_ref(grpc_lb_policy_factory *factory) {} +static void pick_first_factory_ref(grpc_lb_policy_factory* factory) {} -static void pick_first_factory_unref(grpc_lb_policy_factory *factory) {} +static void pick_first_factory_unref(grpc_lb_policy_factory* factory) {} -static grpc_lb_policy *create_pick_first(grpc_exec_ctx *exec_ctx, - grpc_lb_policy_factory *factory, - grpc_lb_policy_args *args) { - GPR_ASSERT(args->client_channel_factory != NULL); - pick_first_lb_policy *p = (pick_first_lb_policy *)gpr_zalloc(sizeof(*p)); - if (GRPC_TRACER_ON(grpc_lb_pick_first_trace)) { - gpr_log(GPR_DEBUG, "Pick First %p created.", (void *)p); +static grpc_lb_policy* create_pick_first(grpc_exec_ctx* exec_ctx, + grpc_lb_policy_factory* factory, + grpc_lb_policy_args* args) { + GPR_ASSERT(args->client_channel_factory != nullptr); + pick_first_lb_policy* p = (pick_first_lb_policy*)gpr_zalloc(sizeof(*p)); + if (grpc_lb_pick_first_trace.enabled()) { + gpr_log(GPR_DEBUG, "Pick First %p created.", (void*)p); } pf_update_locked(exec_ctx, &p->base, args); grpc_lb_policy_init(&p->base, &pick_first_lb_policy_vtable, args->combiner); @@ -603,15 +620,14 @@ static const grpc_lb_policy_factory_vtable pick_first_factory_vtable = { static grpc_lb_policy_factory pick_first_lb_policy_factory = { &pick_first_factory_vtable}; -static grpc_lb_policy_factory *pick_first_lb_factory_create() { +static grpc_lb_policy_factory* pick_first_lb_factory_create() { return &pick_first_lb_policy_factory; } /* Plugin registration */ -extern "C" void grpc_lb_policy_pick_first_init() { +void grpc_lb_policy_pick_first_init() { grpc_register_lb_policy(pick_first_lb_factory_create()); - grpc_register_tracer(&grpc_lb_pick_first_trace); } -extern "C" void grpc_lb_policy_pick_first_shutdown() {} +void grpc_lb_policy_pick_first_shutdown() {} diff --git a/src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc b/src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc index 8f29c80130c..f68daba474c 100644 --- a/src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc +++ b/src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc @@ -20,9 +20,9 @@ * * Before every pick, the \a get_next_ready_subchannel_index_locked function * returns the p->subchannel_list->subchannels index for next subchannel, - * respecting the relative - * order of the addresses provided upon creation or updates. Note however that - * updates will start picking from the beginning of the updated list. */ + * respecting the relative order of the addresses provided upon creation or + * updates. Note however that updates will start picking from the beginning of + * the updated list. */ #include @@ -39,19 +39,18 @@ #include "src/core/lib/transport/connectivity_state.h" #include "src/core/lib/transport/static_metadata.h" -grpc_tracer_flag grpc_lb_round_robin_trace = - GRPC_TRACER_INITIALIZER(false, "round_robin"); +grpc_core::TraceFlag grpc_lb_round_robin_trace(false, "round_robin"); /** List of entities waiting for a pick. * * Once a pick is available, \a target is updated and \a on_complete called. */ typedef struct pending_pick { - struct pending_pick *next; + struct pending_pick* next; /* output argument where to store the pick()ed user_data. It'll be NULL if no * such data is present or there's an error (the definite test for errors is * \a target being NULL). */ - void **user_data; + void** user_data; /* bitmask passed to pick() and used for selective cancelling. See * grpc_lb_policy_cancel_picks() */ @@ -59,24 +58,24 @@ typedef struct pending_pick { /* output argument where to store the pick()ed connected subchannel, or NULL * upon error. */ - grpc_connected_subchannel **target; + grpc_connected_subchannel** target; /* to be invoked once the pick() has completed (regardless of success) */ - grpc_closure *on_complete; + grpc_closure* on_complete; } pending_pick; typedef struct round_robin_lb_policy { /** base policy: must be first */ grpc_lb_policy base; - grpc_lb_subchannel_list *subchannel_list; + grpc_lb_subchannel_list* subchannel_list; /** have we started picking? */ bool started_picking; /** are we shutting down? */ bool shutdown; /** List of picks that are waiting on connectivity */ - pending_pick *pending_picks; + pending_pick* pending_picks; /** our connectivity state tracker */ grpc_connectivity_state_tracker state_tracker; @@ -89,7 +88,7 @@ typedef struct round_robin_lb_policy { * lists if they equal \a latest_pending_subchannel_list. In other words, * racing callbacks that reference outdated subchannel lists won't perform any * update. */ - grpc_lb_subchannel_list *latest_pending_subchannel_list; + grpc_lb_subchannel_list* latest_pending_subchannel_list; } round_robin_lb_policy; /** Returns the index into p->subchannel_list->subchannels of the next @@ -99,122 +98,118 @@ typedef struct round_robin_lb_policy { * Note that this function does *not* update p->last_ready_subchannel_index. * The caller must do that if it returns a pick. */ static size_t get_next_ready_subchannel_index_locked( - const round_robin_lb_policy *p) { - GPR_ASSERT(p->subchannel_list != NULL); - if (GRPC_TRACER_ON(grpc_lb_round_robin_trace)) { + const round_robin_lb_policy* p) { + GPR_ASSERT(p->subchannel_list != nullptr); + if (grpc_lb_round_robin_trace.enabled()) { gpr_log(GPR_INFO, "[RR %p] getting next ready subchannel (out of %lu), " "last_ready_subchannel_index=%lu", - (void *)p, (unsigned long)p->subchannel_list->num_subchannels, + (void*)p, (unsigned long)p->subchannel_list->num_subchannels, (unsigned long)p->last_ready_subchannel_index); } for (size_t i = 0; i < p->subchannel_list->num_subchannels; ++i) { const size_t index = (i + p->last_ready_subchannel_index + 1) % p->subchannel_list->num_subchannels; - if (GRPC_TRACER_ON(grpc_lb_round_robin_trace)) { + if (grpc_lb_round_robin_trace.enabled()) { gpr_log( GPR_DEBUG, "[RR %p] checking subchannel %p, subchannel_list %p, index %lu: " "state=%s", - (void *)p, (void *)p->subchannel_list->subchannels[index].subchannel, - (void *)p->subchannel_list, (unsigned long)index, + (void*)p, (void*)p->subchannel_list->subchannels[index].subchannel, + (void*)p->subchannel_list, (unsigned long)index, grpc_connectivity_state_name( p->subchannel_list->subchannels[index].curr_connectivity_state)); } if (p->subchannel_list->subchannels[index].curr_connectivity_state == GRPC_CHANNEL_READY) { - if (GRPC_TRACER_ON(grpc_lb_round_robin_trace)) { + if (grpc_lb_round_robin_trace.enabled()) { gpr_log(GPR_DEBUG, "[RR %p] found next ready subchannel (%p) at index %lu of " "subchannel_list %p", - (void *)p, - (void *)p->subchannel_list->subchannels[index].subchannel, - (unsigned long)index, (void *)p->subchannel_list); + (void*)p, + (void*)p->subchannel_list->subchannels[index].subchannel, + (unsigned long)index, (void*)p->subchannel_list); } return index; } } - if (GRPC_TRACER_ON(grpc_lb_round_robin_trace)) { - gpr_log(GPR_DEBUG, "[RR %p] no subchannels in ready state", (void *)p); + if (grpc_lb_round_robin_trace.enabled()) { + gpr_log(GPR_DEBUG, "[RR %p] no subchannels in ready state", (void*)p); } return p->subchannel_list->num_subchannels; } // Sets p->last_ready_subchannel_index to last_ready_index. -static void update_last_ready_subchannel_index_locked(round_robin_lb_policy *p, +static void update_last_ready_subchannel_index_locked(round_robin_lb_policy* p, size_t last_ready_index) { GPR_ASSERT(last_ready_index < p->subchannel_list->num_subchannels); p->last_ready_subchannel_index = last_ready_index; - if (GRPC_TRACER_ON(grpc_lb_round_robin_trace)) { - gpr_log( - GPR_DEBUG, - "[RR %p] setting last_ready_subchannel_index=%lu (SC %p, CSC %p)", - (void *)p, (unsigned long)last_ready_index, - (void *)p->subchannel_list->subchannels[last_ready_index].subchannel, - (void *)p->subchannel_list->subchannels[last_ready_index] - .connected_subchannel); + if (grpc_lb_round_robin_trace.enabled()) { + gpr_log(GPR_DEBUG, + "[RR %p] setting last_ready_subchannel_index=%lu (SC %p, CSC %p)", + (void*)p, (unsigned long)last_ready_index, + (void*)p->subchannel_list->subchannels[last_ready_index].subchannel, + (void*)p->subchannel_list->subchannels[last_ready_index] + .connected_subchannel); } } -static void rr_destroy(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { - round_robin_lb_policy *p = (round_robin_lb_policy *)pol; - if (GRPC_TRACER_ON(grpc_lb_round_robin_trace)) { +static void rr_destroy(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol) { + round_robin_lb_policy* p = (round_robin_lb_policy*)pol; + if (grpc_lb_round_robin_trace.enabled()) { gpr_log(GPR_DEBUG, "[RR %p] Destroying Round Robin policy at %p", - (void *)pol, (void *)pol); + (void*)pol, (void*)pol); } - GPR_ASSERT(p->subchannel_list == NULL); - GPR_ASSERT(p->latest_pending_subchannel_list == NULL); + GPR_ASSERT(p->subchannel_list == nullptr); + GPR_ASSERT(p->latest_pending_subchannel_list == nullptr); grpc_connectivity_state_destroy(exec_ctx, &p->state_tracker); grpc_subchannel_index_unref(); gpr_free(p); } -static void shutdown_locked(grpc_exec_ctx *exec_ctx, round_robin_lb_policy *p, - grpc_error *error) { - if (GRPC_TRACER_ON(grpc_lb_round_robin_trace)) { +static void rr_shutdown_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol) { + round_robin_lb_policy* p = (round_robin_lb_policy*)pol; + grpc_error* error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Channel shutdown"); + if (grpc_lb_round_robin_trace.enabled()) { gpr_log(GPR_DEBUG, "[RR %p] Shutting down", p); } p->shutdown = true; - pending_pick *pp; - while ((pp = p->pending_picks) != NULL) { + pending_pick* pp; + while ((pp = p->pending_picks) != nullptr) { p->pending_picks = pp->next; - *pp->target = NULL; + *pp->target = nullptr; GRPC_CLOSURE_SCHED(exec_ctx, pp->on_complete, GRPC_ERROR_REF(error)); gpr_free(pp); } grpc_connectivity_state_set(exec_ctx, &p->state_tracker, GRPC_CHANNEL_SHUTDOWN, GRPC_ERROR_REF(error), "rr_shutdown"); - if (p->subchannel_list != NULL) { + if (p->subchannel_list != nullptr) { grpc_lb_subchannel_list_shutdown_and_unref(exec_ctx, p->subchannel_list, "sl_shutdown_rr_shutdown"); - p->subchannel_list = NULL; + p->subchannel_list = nullptr; } - if (p->latest_pending_subchannel_list != NULL) { + if (p->latest_pending_subchannel_list != nullptr) { grpc_lb_subchannel_list_shutdown_and_unref( exec_ctx, p->latest_pending_subchannel_list, "sl_shutdown_pending_rr_shutdown"); - p->latest_pending_subchannel_list = NULL; + p->latest_pending_subchannel_list = nullptr; } + grpc_lb_policy_try_reresolve(exec_ctx, &p->base, &grpc_lb_round_robin_trace, + GRPC_ERROR_CANCELLED); GRPC_ERROR_UNREF(error); } -static void rr_shutdown_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { - round_robin_lb_policy *p = (round_robin_lb_policy *)pol; - shutdown_locked(exec_ctx, p, - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Channel Shutdown")); -} - -static void rr_cancel_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, - grpc_connected_subchannel **target, - grpc_error *error) { - round_robin_lb_policy *p = (round_robin_lb_policy *)pol; - pending_pick *pp = p->pending_picks; - p->pending_picks = NULL; - while (pp != NULL) { - pending_pick *next = pp->next; +static void rr_cancel_pick_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol, + grpc_connected_subchannel** target, + grpc_error* error) { + round_robin_lb_policy* p = (round_robin_lb_policy*)pol; + pending_pick* pp = p->pending_picks; + p->pending_picks = nullptr; + while (pp != nullptr) { + pending_pick* next = pp->next; if (pp->target == target) { - *target = NULL; + *target = nullptr; GRPC_CLOSURE_SCHED(exec_ctx, pp->on_complete, GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Pick cancelled", &error, 1)); @@ -228,18 +223,18 @@ static void rr_cancel_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, GRPC_ERROR_UNREF(error); } -static void rr_cancel_picks_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, +static void rr_cancel_picks_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol, uint32_t initial_metadata_flags_mask, uint32_t initial_metadata_flags_eq, - grpc_error *error) { - round_robin_lb_policy *p = (round_robin_lb_policy *)pol; - pending_pick *pp = p->pending_picks; - p->pending_picks = NULL; - while (pp != NULL) { - pending_pick *next = pp->next; + grpc_error* error) { + round_robin_lb_policy* p = (round_robin_lb_policy*)pol; + pending_pick* pp = p->pending_picks; + p->pending_picks = nullptr; + while (pp != nullptr) { + pending_pick* next = pp->next; if ((pp->initial_metadata_flags & initial_metadata_flags_mask) == initial_metadata_flags_eq) { - *pp->target = NULL; + *pp->target = nullptr; GRPC_CLOSURE_SCHED(exec_ctx, pp->on_complete, GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Pick cancelled", &error, 1)); @@ -253,52 +248,55 @@ static void rr_cancel_picks_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, GRPC_ERROR_UNREF(error); } -static void start_picking_locked(grpc_exec_ctx *exec_ctx, - round_robin_lb_policy *p) { +static void start_picking_locked(grpc_exec_ctx* exec_ctx, + round_robin_lb_policy* p) { p->started_picking = true; for (size_t i = 0; i < p->subchannel_list->num_subchannels; i++) { - grpc_lb_subchannel_list_ref_for_connectivity_watch(p->subchannel_list, - "connectivity_watch"); - grpc_lb_subchannel_data_start_connectivity_watch( - exec_ctx, &p->subchannel_list->subchannels[i]); + if (p->subchannel_list->subchannels[i].subchannel != nullptr) { + grpc_lb_subchannel_list_ref_for_connectivity_watch(p->subchannel_list, + "connectivity_watch"); + grpc_lb_subchannel_data_start_connectivity_watch( + exec_ctx, &p->subchannel_list->subchannels[i]); + } } } -static void rr_exit_idle_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { - round_robin_lb_policy *p = (round_robin_lb_policy *)pol; +static void rr_exit_idle_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol) { + round_robin_lb_policy* p = (round_robin_lb_policy*)pol; if (!p->started_picking) { start_picking_locked(exec_ctx, p); } } -static int rr_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, - const grpc_lb_policy_pick_args *pick_args, - grpc_connected_subchannel **target, - grpc_call_context_element *context, void **user_data, - grpc_closure *on_complete) { - round_robin_lb_policy *p = (round_robin_lb_policy *)pol; - GPR_ASSERT(!p->shutdown); - if (GRPC_TRACER_ON(grpc_lb_round_robin_trace)) { - gpr_log(GPR_INFO, "[RR %p] Trying to pick", (void *)pol); +static int rr_pick_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol, + const grpc_lb_policy_pick_args* pick_args, + grpc_connected_subchannel** target, + grpc_call_context_element* context, void** user_data, + grpc_closure* on_complete) { + round_robin_lb_policy* p = (round_robin_lb_policy*)pol; + if (grpc_lb_round_robin_trace.enabled()) { + gpr_log(GPR_INFO, "[RR %p] Trying to pick (shutdown: %d)", (void*)pol, + p->shutdown); } - if (p->subchannel_list != NULL) { + GPR_ASSERT(!p->shutdown); + if (p->subchannel_list != nullptr) { const size_t next_ready_index = get_next_ready_subchannel_index_locked(p); if (next_ready_index < p->subchannel_list->num_subchannels) { /* readily available, report right away */ - grpc_lb_subchannel_data *sd = + grpc_lb_subchannel_data* sd = &p->subchannel_list->subchannels[next_ready_index]; *target = GRPC_CONNECTED_SUBCHANNEL_REF(sd->connected_subchannel, "rr_picked"); - if (user_data != NULL) { + if (user_data != nullptr) { *user_data = sd->user_data; } - if (GRPC_TRACER_ON(grpc_lb_round_robin_trace)) { + if (grpc_lb_round_robin_trace.enabled()) { gpr_log( GPR_DEBUG, "[RR %p] Picked target <-- Subchannel %p (connected %p) (sl %p, " "index %lu)", - (void *)p, (void *)sd->subchannel, (void *)*target, - (void *)sd->subchannel_list, (unsigned long)next_ready_index); + (void*)p, (void*)sd->subchannel, (void*)*target, + (void*)sd->subchannel_list, (unsigned long)next_ready_index); } /* only advance the last picked pointer if the selection was used */ update_last_ready_subchannel_index_locked(p, next_ready_index); @@ -309,7 +307,7 @@ static int rr_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, if (!p->started_picking) { start_picking_locked(exec_ctx, p); } - pending_pick *pp = (pending_pick *)gpr_malloc(sizeof(*pp)); + pending_pick* pp = (pending_pick*)gpr_malloc(sizeof(*pp)); pp->next = p->pending_picks; pp->target = target; pp->on_complete = on_complete; @@ -319,8 +317,8 @@ static int rr_pick_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, return 0; } -static void update_state_counters_locked(grpc_lb_subchannel_data *sd) { - grpc_lb_subchannel_list *subchannel_list = sd->subchannel_list; +static void update_state_counters_locked(grpc_lb_subchannel_data* sd) { + grpc_lb_subchannel_list* subchannel_list = sd->subchannel_list; if (sd->prev_connectivity_state == GRPC_CHANNEL_READY) { GPR_ASSERT(subchannel_list->num_ready > 0); --subchannel_list->num_ready; @@ -347,80 +345,85 @@ static void update_state_counters_locked(grpc_lb_subchannel_data *sd) { } /** Sets the policy's connectivity status based on that of the passed-in \a sd - * (the grpc_lb_subchannel_data associted with the updated subchannel) and the - * subchannel list \a sd belongs to (sd->subchannel_list). \a error will only be - * used upon policy transition to TRANSIENT_FAILURE or SHUTDOWN. Returns the - * connectivity status set. */ -static grpc_connectivity_state update_lb_connectivity_status_locked( - grpc_exec_ctx *exec_ctx, grpc_lb_subchannel_data *sd, grpc_error *error) { + * (the grpc_lb_subchannel_data associated with the updated subchannel) and the + * subchannel list \a sd belongs to (sd->subchannel_list). \a error will be used + * only if the policy transitions to state TRANSIENT_FAILURE. */ +static void update_lb_connectivity_status_locked(grpc_exec_ctx* exec_ctx, + grpc_lb_subchannel_data* sd, + grpc_error* error) { /* In priority order. The first rule to match terminates the search (ie, if we * are on rule n, all previous rules were unfulfilled). * * 1) RULE: ANY subchannel is READY => policy is READY. - * CHECK: At least one subchannel is ready iff p->ready_list is NOT empty. + * CHECK: subchannel_list->num_ready > 0. * * 2) RULE: ANY subchannel is CONNECTING => policy is CONNECTING. * CHECK: sd->curr_connectivity_state == CONNECTING. * - * 3) RULE: ALL subchannels are SHUTDOWN => policy is SHUTDOWN. - * CHECK: p->subchannel_list->num_shutdown == - * p->subchannel_list->num_subchannels. + * 3) RULE: ALL subchannels are SHUTDOWN => policy is IDLE (and requests + * re-resolution). + * CHECK: subchannel_list->num_shutdown == + * subchannel_list->num_subchannels. * * 4) RULE: ALL subchannels are TRANSIENT_FAILURE => policy is - * TRANSIENT_FAILURE. - * CHECK: p->num_transient_failures == p->subchannel_list->num_subchannels. + * TRANSIENT_FAILURE. + * CHECK: subchannel_list->num_transient_failures == + * subchannel_list->num_subchannels. * * 5) RULE: ALL subchannels are IDLE => policy is IDLE. - * CHECK: p->num_idle == p->subchannel_list->num_subchannels. + * CHECK: subchannel_list->num_idle == subchannel_list->num_subchannels. + * (Note that all the subchannels will transition from IDLE to CONNECTING + * in batch when we start trying to connect.) */ - grpc_connectivity_state new_state = sd->curr_connectivity_state; - grpc_lb_subchannel_list *subchannel_list = sd->subchannel_list; - round_robin_lb_policy *p = (round_robin_lb_policy *)subchannel_list->policy; - if (subchannel_list->num_ready > 0) { /* 1) READY */ + // TODO(juanlishen): if the subchannel states are mixed by {SHUTDOWN, + // TRANSIENT_FAILURE}, we don't change the state. We may want to improve on + // this. + grpc_lb_subchannel_list* subchannel_list = sd->subchannel_list; + round_robin_lb_policy* p = (round_robin_lb_policy*)subchannel_list->policy; + if (subchannel_list->num_ready > 0) { + /* 1) READY */ grpc_connectivity_state_set(exec_ctx, &p->state_tracker, GRPC_CHANNEL_READY, GRPC_ERROR_NONE, "rr_ready"); - new_state = GRPC_CHANNEL_READY; - } else if (sd->curr_connectivity_state == - GRPC_CHANNEL_CONNECTING) { /* 2) CONNECTING */ + } else if (sd->curr_connectivity_state == GRPC_CHANNEL_CONNECTING) { + /* 2) CONNECTING */ grpc_connectivity_state_set(exec_ctx, &p->state_tracker, GRPC_CHANNEL_CONNECTING, GRPC_ERROR_NONE, "rr_connecting"); - new_state = GRPC_CHANNEL_CONNECTING; - } else if (p->subchannel_list->num_shutdown == - p->subchannel_list->num_subchannels) { /* 3) SHUTDOWN */ - grpc_connectivity_state_set(exec_ctx, &p->state_tracker, - GRPC_CHANNEL_SHUTDOWN, GRPC_ERROR_REF(error), - "rr_shutdown"); - p->shutdown = true; - new_state = GRPC_CHANNEL_SHUTDOWN; + } else if (subchannel_list->num_shutdown == + subchannel_list->num_subchannels) { + /* 3) IDLE and re-resolve */ + grpc_connectivity_state_set(exec_ctx, &p->state_tracker, GRPC_CHANNEL_IDLE, + GRPC_ERROR_NONE, + "rr_exhausted_subchannels+reresolve"); + p->started_picking = false; + grpc_lb_policy_try_reresolve(exec_ctx, &p->base, &grpc_lb_round_robin_trace, + GRPC_ERROR_NONE); } else if (subchannel_list->num_transient_failures == - p->subchannel_list->num_subchannels) { /* 4) TRANSIENT_FAILURE */ + subchannel_list->num_subchannels) { + /* 4) TRANSIENT_FAILURE */ grpc_connectivity_state_set(exec_ctx, &p->state_tracker, GRPC_CHANNEL_TRANSIENT_FAILURE, GRPC_ERROR_REF(error), "rr_transient_failure"); - new_state = GRPC_CHANNEL_TRANSIENT_FAILURE; - } else if (subchannel_list->num_idle == - p->subchannel_list->num_subchannels) { /* 5) IDLE */ + } else if (subchannel_list->num_idle == subchannel_list->num_subchannels) { + /* 5) IDLE */ grpc_connectivity_state_set(exec_ctx, &p->state_tracker, GRPC_CHANNEL_IDLE, GRPC_ERROR_NONE, "rr_idle"); - new_state = GRPC_CHANNEL_IDLE; } GRPC_ERROR_UNREF(error); - return new_state; } -static void rr_connectivity_changed_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_lb_subchannel_data *sd = (grpc_lb_subchannel_data *)arg; - round_robin_lb_policy *p = - (round_robin_lb_policy *)sd->subchannel_list->policy; - if (GRPC_TRACER_ON(grpc_lb_round_robin_trace)) { +static void rr_connectivity_changed_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_lb_subchannel_data* sd = (grpc_lb_subchannel_data*)arg; + round_robin_lb_policy* p = + (round_robin_lb_policy*)sd->subchannel_list->policy; + if (grpc_lb_round_robin_trace.enabled()) { gpr_log( GPR_DEBUG, "[RR %p] connectivity changed for subchannel %p, subchannel_list %p: " "prev_state=%s new_state=%s p->shutdown=%d " "sd->subchannel_list->shutting_down=%d error=%s", - (void *)p, (void *)sd->subchannel, (void *)sd->subchannel_list, + (void*)p, (void*)sd->subchannel, (void*)sd->subchannel_list, grpc_connectivity_state_name(sd->prev_connectivity_state), grpc_connectivity_state_name(sd->pending_connectivity_state_unsafe), p->shutdown, sd->subchannel_list->shutting_down, @@ -450,24 +453,19 @@ static void rr_connectivity_changed_locked(grpc_exec_ctx *exec_ctx, void *arg, // state (which was set by the connectivity state watcher) to // curr_connectivity_state, which is what we use inside of the combiner. sd->curr_connectivity_state = sd->pending_connectivity_state_unsafe; - // Update state counters and determine new overall state. + // Update state counters and new overall state. update_state_counters_locked(sd); - const grpc_connectivity_state new_policy_connectivity_state = - update_lb_connectivity_status_locked(exec_ctx, sd, GRPC_ERROR_REF(error)); - // If the sd's new state is SHUTDOWN, unref the subchannel, and if the new - // policy's state is SHUTDOWN, clean up. + update_lb_connectivity_status_locked(exec_ctx, sd, GRPC_ERROR_REF(error)); + // If the sd's new state is SHUTDOWN, unref the subchannel. if (sd->curr_connectivity_state == GRPC_CHANNEL_SHUTDOWN) { grpc_lb_subchannel_data_stop_connectivity_watch(exec_ctx, sd); grpc_lb_subchannel_data_unref_subchannel(exec_ctx, sd, "rr_connectivity_shutdown"); grpc_lb_subchannel_list_unref_for_connectivity_watch( exec_ctx, sd->subchannel_list, "rr_connectivity_shutdown"); - if (new_policy_connectivity_state == GRPC_CHANNEL_SHUTDOWN) { - shutdown_locked(exec_ctx, p, GRPC_ERROR_REF(error)); - } } else { // sd not in SHUTDOWN if (sd->curr_connectivity_state == GRPC_CHANNEL_READY) { - if (sd->connected_subchannel == NULL) { + if (sd->connected_subchannel == nullptr) { sd->connected_subchannel = GRPC_CONNECTED_SUBCHANNEL_REF( grpc_subchannel_get_connected_subchannel(sd->subchannel), "connected"); @@ -479,51 +477,51 @@ static void rr_connectivity_changed_locked(grpc_exec_ctx *exec_ctx, void *arg, // for sds belonging to outdated subchannel lists. GPR_ASSERT(sd->subchannel_list == p->latest_pending_subchannel_list); GPR_ASSERT(!sd->subchannel_list->shutting_down); - if (GRPC_TRACER_ON(grpc_lb_round_robin_trace)) { + if (grpc_lb_round_robin_trace.enabled()) { const unsigned long num_subchannels = - p->subchannel_list != NULL + p->subchannel_list != nullptr ? (unsigned long)p->subchannel_list->num_subchannels : 0; gpr_log(GPR_DEBUG, "[RR %p] phasing out subchannel list %p (size %lu) in favor " "of %p (size %lu)", - (void *)p, (void *)p->subchannel_list, num_subchannels, - (void *)sd->subchannel_list, num_subchannels); + (void*)p, (void*)p->subchannel_list, num_subchannels, + (void*)sd->subchannel_list, num_subchannels); } - if (p->subchannel_list != NULL) { + if (p->subchannel_list != nullptr) { // dispose of the current subchannel_list grpc_lb_subchannel_list_shutdown_and_unref( exec_ctx, p->subchannel_list, "sl_phase_out_shutdown"); } p->subchannel_list = p->latest_pending_subchannel_list; - p->latest_pending_subchannel_list = NULL; + p->latest_pending_subchannel_list = nullptr; } /* at this point we know there's at least one suitable subchannel. Go * ahead and pick one and notify the pending suitors in - * p->pending_picks. This preemtively replicates rr_pick()'s actions. */ + * p->pending_picks. This preemptively replicates rr_pick()'s actions. */ const size_t next_ready_index = get_next_ready_subchannel_index_locked(p); GPR_ASSERT(next_ready_index < p->subchannel_list->num_subchannels); - grpc_lb_subchannel_data *selected = + grpc_lb_subchannel_data* selected = &p->subchannel_list->subchannels[next_ready_index]; - if (p->pending_picks != NULL) { + if (p->pending_picks != nullptr) { // if the selected subchannel is going to be used for the pending // picks, update the last picked pointer update_last_ready_subchannel_index_locked(p, next_ready_index); } - pending_pick *pp; + pending_pick* pp; while ((pp = p->pending_picks)) { p->pending_picks = pp->next; *pp->target = GRPC_CONNECTED_SUBCHANNEL_REF( selected->connected_subchannel, "rr_picked"); - if (pp->user_data != NULL) { + if (pp->user_data != nullptr) { *pp->user_data = selected->user_data; } - if (GRPC_TRACER_ON(grpc_lb_round_robin_trace)) { + if (grpc_lb_round_robin_trace.enabled()) { gpr_log(GPR_DEBUG, "[RR %p] Fulfilling pending pick. Target <-- subchannel %p " "(subchannel_list %p, index %lu)", - (void *)p, (void *)selected->subchannel, - (void *)p->subchannel_list, (unsigned long)next_ready_index); + (void*)p, (void*)selected->subchannel, + (void*)p->subchannel_list, (unsigned long)next_ready_index); } GRPC_CLOSURE_SCHED(exec_ctx, pp->on_complete, GRPC_ERROR_NONE); gpr_free(pp); @@ -535,47 +533,48 @@ static void rr_connectivity_changed_locked(grpc_exec_ctx *exec_ctx, void *arg, } static grpc_connectivity_state rr_check_connectivity_locked( - grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, grpc_error **error) { - round_robin_lb_policy *p = (round_robin_lb_policy *)pol; + grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol, grpc_error** error) { + round_robin_lb_policy* p = (round_robin_lb_policy*)pol; return grpc_connectivity_state_get(&p->state_tracker, error); } -static void rr_notify_on_state_change_locked(grpc_exec_ctx *exec_ctx, - grpc_lb_policy *pol, - grpc_connectivity_state *current, - grpc_closure *notify) { - round_robin_lb_policy *p = (round_robin_lb_policy *)pol; +static void rr_notify_on_state_change_locked(grpc_exec_ctx* exec_ctx, + grpc_lb_policy* pol, + grpc_connectivity_state* current, + grpc_closure* notify) { + round_robin_lb_policy* p = (round_robin_lb_policy*)pol; grpc_connectivity_state_notify_on_state_change(exec_ctx, &p->state_tracker, current, notify); } -static void rr_ping_one_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, - grpc_closure *closure) { - round_robin_lb_policy *p = (round_robin_lb_policy *)pol; +static void rr_ping_one_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* pol, + grpc_closure* closure) { + round_robin_lb_policy* p = (round_robin_lb_policy*)pol; const size_t next_ready_index = get_next_ready_subchannel_index_locked(p); if (next_ready_index < p->subchannel_list->num_subchannels) { - grpc_lb_subchannel_data *selected = + grpc_lb_subchannel_data* selected = &p->subchannel_list->subchannels[next_ready_index]; - grpc_connected_subchannel *target = GRPC_CONNECTED_SUBCHANNEL_REF( + grpc_connected_subchannel* target = GRPC_CONNECTED_SUBCHANNEL_REF( selected->connected_subchannel, "rr_ping"); grpc_connected_subchannel_ping(exec_ctx, target, closure); GRPC_CONNECTED_SUBCHANNEL_UNREF(exec_ctx, target, "rr_ping"); } else { - GRPC_CLOSURE_SCHED(exec_ctx, closure, GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "Round Robin not connected")); + GRPC_CLOSURE_SCHED( + exec_ctx, closure, + GRPC_ERROR_CREATE_FROM_STATIC_STRING("Round Robin not connected")); } } -static void rr_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, - const grpc_lb_policy_args *args) { - round_robin_lb_policy *p = (round_robin_lb_policy *)policy; - const grpc_arg *arg = +static void rr_update_locked(grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + const grpc_lb_policy_args* args) { + round_robin_lb_policy* p = (round_robin_lb_policy*)policy; + const grpc_arg* arg = grpc_channel_args_find(args->args, GRPC_ARG_LB_ADDRESSES); - if (arg == NULL || arg->type != GRPC_ARG_POINTER) { + if (arg == nullptr || arg->type != GRPC_ARG_POINTER) { gpr_log(GPR_ERROR, "[RR %p] update provided no addresses; ignoring", p); // If we don't have a current subchannel list, go into TRANSIENT_FAILURE. // Otherwise, keep using the current subchannel list (ignore this update). - if (p->subchannel_list == NULL) { + if (p->subchannel_list == nullptr) { grpc_connectivity_state_set( exec_ctx, &p->state_tracker, GRPC_CHANNEL_TRANSIENT_FAILURE, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing update in args"), @@ -583,12 +582,12 @@ static void rr_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, } return; } - grpc_lb_addresses *addresses = (grpc_lb_addresses *)arg->value.pointer.p; - if (GRPC_TRACER_ON(grpc_lb_round_robin_trace)) { + grpc_lb_addresses* addresses = (grpc_lb_addresses*)arg->value.pointer.p; + if (grpc_lb_round_robin_trace.enabled()) { gpr_log(GPR_DEBUG, "[RR %p] received update with %" PRIuPTR " addresses", p, addresses->num_addresses); } - grpc_lb_subchannel_list *subchannel_list = grpc_lb_subchannel_list_create( + grpc_lb_subchannel_list* subchannel_list = grpc_lb_subchannel_list_create( exec_ctx, &p->base, &grpc_lb_round_robin_trace, addresses, args, rr_connectivity_changed_locked); if (subchannel_list->num_subchannels == 0) { @@ -596,7 +595,7 @@ static void rr_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, exec_ctx, &p->state_tracker, GRPC_CHANNEL_TRANSIENT_FAILURE, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Empty update"), "rr_update_empty"); - if (p->subchannel_list != NULL) { + if (p->subchannel_list != nullptr) { grpc_lb_subchannel_list_shutdown_and_unref(exec_ctx, p->subchannel_list, "sl_shutdown_empty_update"); } @@ -604,13 +603,13 @@ static void rr_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, return; } if (p->started_picking) { - if (p->latest_pending_subchannel_list != NULL) { - if (GRPC_TRACER_ON(grpc_lb_round_robin_trace)) { + if (p->latest_pending_subchannel_list != nullptr) { + if (grpc_lb_round_robin_trace.enabled()) { gpr_log(GPR_DEBUG, "[RR %p] Shutting down latest pending subchannel list %p, " "about to be replaced by newer latest %p", - (void *)p, (void *)p->latest_pending_subchannel_list, - (void *)subchannel_list); + (void*)p, (void*)p->latest_pending_subchannel_list, + (void*)subchannel_list); } grpc_lb_subchannel_list_shutdown_and_unref( exec_ctx, p->latest_pending_subchannel_list, "sl_outdated"); @@ -629,7 +628,7 @@ static void rr_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, } else { // The policy isn't picking yet. Save the update for later, disposing of // previous version if any. - if (p->subchannel_list != NULL) { + if (p->subchannel_list != nullptr) { grpc_lb_subchannel_list_shutdown_and_unref( exec_ctx, p->subchannel_list, "rr_update_before_started_picking"); } @@ -637,6 +636,15 @@ static void rr_update_locked(grpc_exec_ctx *exec_ctx, grpc_lb_policy *policy, } } +static void rr_set_reresolve_closure_locked( + grpc_exec_ctx* exec_ctx, grpc_lb_policy* policy, + grpc_closure* request_reresolution) { + round_robin_lb_policy* p = (round_robin_lb_policy*)policy; + GPR_ASSERT(!p->shutdown); + GPR_ASSERT(policy->request_reresolution == nullptr); + policy->request_reresolution = request_reresolution; +} + static const grpc_lb_policy_vtable round_robin_lb_policy_vtable = { rr_destroy, rr_shutdown_locked, @@ -647,24 +655,25 @@ static const grpc_lb_policy_vtable round_robin_lb_policy_vtable = { rr_exit_idle_locked, rr_check_connectivity_locked, rr_notify_on_state_change_locked, - rr_update_locked}; + rr_update_locked, + rr_set_reresolve_closure_locked}; -static void round_robin_factory_ref(grpc_lb_policy_factory *factory) {} +static void round_robin_factory_ref(grpc_lb_policy_factory* factory) {} -static void round_robin_factory_unref(grpc_lb_policy_factory *factory) {} +static void round_robin_factory_unref(grpc_lb_policy_factory* factory) {} -static grpc_lb_policy *round_robin_create(grpc_exec_ctx *exec_ctx, - grpc_lb_policy_factory *factory, - grpc_lb_policy_args *args) { - GPR_ASSERT(args->client_channel_factory != NULL); - round_robin_lb_policy *p = (round_robin_lb_policy *)gpr_zalloc(sizeof(*p)); +static grpc_lb_policy* round_robin_create(grpc_exec_ctx* exec_ctx, + grpc_lb_policy_factory* factory, + grpc_lb_policy_args* args) { + GPR_ASSERT(args->client_channel_factory != nullptr); + round_robin_lb_policy* p = (round_robin_lb_policy*)gpr_zalloc(sizeof(*p)); grpc_lb_policy_init(&p->base, &round_robin_lb_policy_vtable, args->combiner); grpc_subchannel_index_ref(); grpc_connectivity_state_init(&p->state_tracker, GRPC_CHANNEL_IDLE, "round_robin"); rr_update_locked(exec_ctx, &p->base, args); - if (GRPC_TRACER_ON(grpc_lb_round_robin_trace)) { - gpr_log(GPR_DEBUG, "[RR %p] Created with %lu subchannels", (void *)p, + if (grpc_lb_round_robin_trace.enabled()) { + gpr_log(GPR_DEBUG, "[RR %p] Created with %lu subchannels", (void*)p, (unsigned long)p->subchannel_list->num_subchannels); } return &p->base; @@ -677,15 +686,14 @@ static const grpc_lb_policy_factory_vtable round_robin_factory_vtable = { static grpc_lb_policy_factory round_robin_lb_policy_factory = { &round_robin_factory_vtable}; -static grpc_lb_policy_factory *round_robin_lb_factory_create() { +static grpc_lb_policy_factory* round_robin_lb_factory_create() { return &round_robin_lb_policy_factory; } /* Plugin registration */ -extern "C" void grpc_lb_policy_round_robin_init() { +void grpc_lb_policy_round_robin_init() { grpc_register_lb_policy(round_robin_lb_factory_create()); - grpc_register_tracer(&grpc_lb_round_robin_trace); } -extern "C" void grpc_lb_policy_round_robin_shutdown() {} +void grpc_lb_policy_round_robin_shutdown() {} diff --git a/src/core/ext/filters/client_channel/lb_policy/subchannel_list.cc b/src/core/ext/filters/client_channel/lb_policy/subchannel_list.cc index 08ea4f480b5..b6fce4d2075 100644 --- a/src/core/ext/filters/client_channel/lb_policy/subchannel_list.cc +++ b/src/core/ext/filters/client_channel/lb_policy/subchannel_list.cc @@ -28,40 +28,41 @@ #include "src/core/lib/iomgr/sockaddr_utils.h" #include "src/core/lib/transport/connectivity_state.h" -void grpc_lb_subchannel_data_unref_subchannel(grpc_exec_ctx *exec_ctx, - grpc_lb_subchannel_data *sd, - const char *reason) { - if (sd->subchannel != NULL) { - if (GRPC_TRACER_ON(*sd->subchannel_list->tracer)) { - gpr_log( - GPR_DEBUG, "[%s %p] subchannel list %p index %" PRIuPTR - " of %" PRIuPTR " (subchannel %p): unreffing subchannel", - sd->subchannel_list->tracer->name, sd->subchannel_list->policy, - sd->subchannel_list, (size_t)(sd - sd->subchannel_list->subchannels), - sd->subchannel_list->num_subchannels, sd->subchannel); +void grpc_lb_subchannel_data_unref_subchannel(grpc_exec_ctx* exec_ctx, + grpc_lb_subchannel_data* sd, + const char* reason) { + if (sd->subchannel != nullptr) { + if (sd->subchannel_list->tracer->enabled()) { + gpr_log(GPR_DEBUG, + "[%s %p] subchannel list %p index %" PRIuPTR " of %" PRIuPTR + " (subchannel %p): unreffing subchannel", + sd->subchannel_list->tracer->name(), sd->subchannel_list->policy, + sd->subchannel_list, + (size_t)(sd - sd->subchannel_list->subchannels), + sd->subchannel_list->num_subchannels, sd->subchannel); } GRPC_SUBCHANNEL_UNREF(exec_ctx, sd->subchannel, reason); - sd->subchannel = NULL; - if (sd->connected_subchannel != NULL) { + sd->subchannel = nullptr; + if (sd->connected_subchannel != nullptr) { GRPC_CONNECTED_SUBCHANNEL_UNREF(exec_ctx, sd->connected_subchannel, reason); - sd->connected_subchannel = NULL; + sd->connected_subchannel = nullptr; } - if (sd->user_data != NULL) { - GPR_ASSERT(sd->user_data_vtable != NULL); + if (sd->user_data != nullptr) { + GPR_ASSERT(sd->user_data_vtable != nullptr); sd->user_data_vtable->destroy(exec_ctx, sd->user_data); - sd->user_data = NULL; + sd->user_data = nullptr; } } } void grpc_lb_subchannel_data_start_connectivity_watch( - grpc_exec_ctx *exec_ctx, grpc_lb_subchannel_data *sd) { - if (GRPC_TRACER_ON(*sd->subchannel_list->tracer)) { + grpc_exec_ctx* exec_ctx, grpc_lb_subchannel_data* sd) { + if (sd->subchannel_list->tracer->enabled()) { gpr_log(GPR_DEBUG, "[%s %p] subchannel list %p index %" PRIuPTR " of %" PRIuPTR " (subchannel %p): requesting connectivity change notification", - sd->subchannel_list->tracer->name, sd->subchannel_list->policy, + sd->subchannel_list->tracer->name(), sd->subchannel_list->policy, sd->subchannel_list, (size_t)(sd - sd->subchannel_list->subchannels), sd->subchannel_list->num_subchannels, sd->subchannel); @@ -74,38 +75,39 @@ void grpc_lb_subchannel_data_start_connectivity_watch( } void grpc_lb_subchannel_data_stop_connectivity_watch( - grpc_exec_ctx *exec_ctx, grpc_lb_subchannel_data *sd) { - if (GRPC_TRACER_ON(*sd->subchannel_list->tracer)) { - gpr_log( - GPR_DEBUG, "[%s %p] subchannel list %p index %" PRIuPTR " of %" PRIuPTR - " (subchannel %p): stopping connectivity watch", - sd->subchannel_list->tracer->name, sd->subchannel_list->policy, - sd->subchannel_list, (size_t)(sd - sd->subchannel_list->subchannels), - sd->subchannel_list->num_subchannels, sd->subchannel); + grpc_exec_ctx* exec_ctx, grpc_lb_subchannel_data* sd) { + if (sd->subchannel_list->tracer->enabled()) { + gpr_log(GPR_DEBUG, + "[%s %p] subchannel list %p index %" PRIuPTR " of %" PRIuPTR + " (subchannel %p): stopping connectivity watch", + sd->subchannel_list->tracer->name(), sd->subchannel_list->policy, + sd->subchannel_list, + (size_t)(sd - sd->subchannel_list->subchannels), + sd->subchannel_list->num_subchannels, sd->subchannel); } GPR_ASSERT(sd->connectivity_notification_pending); sd->connectivity_notification_pending = false; } -grpc_lb_subchannel_list *grpc_lb_subchannel_list_create( - grpc_exec_ctx *exec_ctx, grpc_lb_policy *p, grpc_tracer_flag *tracer, - const grpc_lb_addresses *addresses, const grpc_lb_policy_args *args, +grpc_lb_subchannel_list* grpc_lb_subchannel_list_create( + grpc_exec_ctx* exec_ctx, grpc_lb_policy* p, grpc_core::TraceFlag* tracer, + const grpc_lb_addresses* addresses, const grpc_lb_policy_args* args, grpc_iomgr_cb_func connectivity_changed_cb) { - grpc_lb_subchannel_list *subchannel_list = - (grpc_lb_subchannel_list *)gpr_zalloc(sizeof(*subchannel_list)); - if (GRPC_TRACER_ON(*tracer)) { + grpc_lb_subchannel_list* subchannel_list = + (grpc_lb_subchannel_list*)gpr_zalloc(sizeof(*subchannel_list)); + if (tracer->enabled()) { gpr_log(GPR_DEBUG, "[%s %p] Creating subchannel list %p for %" PRIuPTR " subchannels", - tracer->name, p, subchannel_list, addresses->num_addresses); + tracer->name(), p, subchannel_list, addresses->num_addresses); } subchannel_list->policy = p; subchannel_list->tracer = tracer; gpr_ref_init(&subchannel_list->refcount, 1); - subchannel_list->subchannels = (grpc_lb_subchannel_data *)gpr_zalloc( + subchannel_list->subchannels = (grpc_lb_subchannel_data*)gpr_zalloc( sizeof(grpc_lb_subchannel_data) * addresses->num_addresses); // We need to remove the LB addresses in order to be able to compare the // subchannel keys of subchannels from a different batch of addresses. - static const char *keys_to_remove[] = {GRPC_ARG_SUBCHANNEL_ADDRESS, + static const char* keys_to_remove[] = {GRPC_ARG_SUBCHANNEL_ADDRESS, GRPC_ARG_LB_ADDRESSES}; // Create a subchannel for each address. grpc_subchannel_args sc_args; @@ -116,37 +118,38 @@ grpc_lb_subchannel_list *grpc_lb_subchannel_list_create( memset(&sc_args, 0, sizeof(grpc_subchannel_args)); grpc_arg addr_arg = grpc_create_subchannel_address_arg(&addresses->addresses[i].address); - grpc_channel_args *new_args = grpc_channel_args_copy_and_add_and_remove( + grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove( args->args, keys_to_remove, GPR_ARRAY_SIZE(keys_to_remove), &addr_arg, 1); gpr_free(addr_arg.value.string); sc_args.args = new_args; - grpc_subchannel *subchannel = grpc_client_channel_factory_create_subchannel( + grpc_subchannel* subchannel = grpc_client_channel_factory_create_subchannel( exec_ctx, args->client_channel_factory, &sc_args); grpc_channel_args_destroy(exec_ctx, new_args); - if (subchannel == NULL) { + if (subchannel == nullptr) { // Subchannel could not be created. - if (GRPC_TRACER_ON(*tracer)) { - char *address_uri = + if (tracer->enabled()) { + char* address_uri = grpc_sockaddr_to_uri(&addresses->addresses[i].address); gpr_log(GPR_DEBUG, "[%s %p] could not create subchannel for address uri %s, " "ignoring", - tracer->name, subchannel_list->policy, address_uri); + tracer->name(), subchannel_list->policy, address_uri); gpr_free(address_uri); } continue; } - if (GRPC_TRACER_ON(*tracer)) { - char *address_uri = + if (tracer->enabled()) { + char* address_uri = grpc_sockaddr_to_uri(&addresses->addresses[i].address); - gpr_log(GPR_DEBUG, "[%s %p] subchannel list %p index %" PRIuPTR - ": Created subchannel %p for address uri %s", - tracer->name, p, subchannel_list, subchannel_index, subchannel, + gpr_log(GPR_DEBUG, + "[%s %p] subchannel list %p index %" PRIuPTR + ": Created subchannel %p for address uri %s", + tracer->name(), p, subchannel_list, subchannel_index, subchannel, address_uri); gpr_free(address_uri); } - grpc_lb_subchannel_data *sd = + grpc_lb_subchannel_data* sd = &subchannel_list->subchannels[subchannel_index++]; sd->subchannel_list = subchannel_list; sd->subchannel = subchannel; @@ -159,7 +162,7 @@ grpc_lb_subchannel_list *grpc_lb_subchannel_list_create( sd->curr_connectivity_state = GRPC_CHANNEL_IDLE; sd->pending_connectivity_state_unsafe = GRPC_CHANNEL_IDLE; sd->user_data_vtable = addresses->user_data_vtable; - if (sd->user_data_vtable != NULL) { + if (sd->user_data_vtable != nullptr) { sd->user_data = sd->user_data_vtable->copy(addresses->addresses[i].user_data); } @@ -169,15 +172,15 @@ grpc_lb_subchannel_list *grpc_lb_subchannel_list_create( return subchannel_list; } -static void subchannel_list_destroy(grpc_exec_ctx *exec_ctx, - grpc_lb_subchannel_list *subchannel_list) { - if (GRPC_TRACER_ON(*subchannel_list->tracer)) { +static void subchannel_list_destroy(grpc_exec_ctx* exec_ctx, + grpc_lb_subchannel_list* subchannel_list) { + if (subchannel_list->tracer->enabled()) { gpr_log(GPR_DEBUG, "[%s %p] Destroying subchannel_list %p", - subchannel_list->tracer->name, subchannel_list->policy, + subchannel_list->tracer->name(), subchannel_list->policy, subchannel_list); } for (size_t i = 0; i < subchannel_list->num_subchannels; i++) { - grpc_lb_subchannel_data *sd = &subchannel_list->subchannels[i]; + grpc_lb_subchannel_data* sd = &subchannel_list->subchannels[i]; grpc_lb_subchannel_data_unref_subchannel(exec_ctx, sd, "subchannel_list_destroy"); } @@ -185,26 +188,26 @@ static void subchannel_list_destroy(grpc_exec_ctx *exec_ctx, gpr_free(subchannel_list); } -void grpc_lb_subchannel_list_ref(grpc_lb_subchannel_list *subchannel_list, - const char *reason) { +void grpc_lb_subchannel_list_ref(grpc_lb_subchannel_list* subchannel_list, + const char* reason) { gpr_ref_non_zero(&subchannel_list->refcount); - if (GRPC_TRACER_ON(*subchannel_list->tracer)) { + if (subchannel_list->tracer->enabled()) { const gpr_atm count = gpr_atm_acq_load(&subchannel_list->refcount.count); gpr_log(GPR_DEBUG, "[%s %p] subchannel_list %p REF %lu->%lu (%s)", - subchannel_list->tracer->name, subchannel_list->policy, + subchannel_list->tracer->name(), subchannel_list->policy, subchannel_list, (unsigned long)(count - 1), (unsigned long)count, reason); } } -void grpc_lb_subchannel_list_unref(grpc_exec_ctx *exec_ctx, - grpc_lb_subchannel_list *subchannel_list, - const char *reason) { +void grpc_lb_subchannel_list_unref(grpc_exec_ctx* exec_ctx, + grpc_lb_subchannel_list* subchannel_list, + const char* reason) { const bool done = gpr_unref(&subchannel_list->refcount); - if (GRPC_TRACER_ON(*subchannel_list->tracer)) { + if (subchannel_list->tracer->enabled()) { const gpr_atm count = gpr_atm_acq_load(&subchannel_list->refcount.count); gpr_log(GPR_DEBUG, "[%s %p] subchannel_list %p UNREF %lu->%lu (%s)", - subchannel_list->tracer->name, subchannel_list->policy, + subchannel_list->tracer->name(), subchannel_list->policy, subchannel_list, (unsigned long)(count + 1), (unsigned long)count, reason); } @@ -214,50 +217,52 @@ void grpc_lb_subchannel_list_unref(grpc_exec_ctx *exec_ctx, } void grpc_lb_subchannel_list_ref_for_connectivity_watch( - grpc_lb_subchannel_list *subchannel_list, const char *reason) { + grpc_lb_subchannel_list* subchannel_list, const char* reason) { GRPC_LB_POLICY_WEAK_REF(subchannel_list->policy, reason); grpc_lb_subchannel_list_ref(subchannel_list, reason); } void grpc_lb_subchannel_list_unref_for_connectivity_watch( - grpc_exec_ctx *exec_ctx, grpc_lb_subchannel_list *subchannel_list, - const char *reason) { + grpc_exec_ctx* exec_ctx, grpc_lb_subchannel_list* subchannel_list, + const char* reason) { GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, subchannel_list->policy, reason); grpc_lb_subchannel_list_unref(exec_ctx, subchannel_list, reason); } static void subchannel_data_cancel_connectivity_watch( - grpc_exec_ctx *exec_ctx, grpc_lb_subchannel_data *sd, const char *reason) { - if (GRPC_TRACER_ON(*sd->subchannel_list->tracer)) { - gpr_log( - GPR_DEBUG, "[%s %p] subchannel list %p index %" PRIuPTR " of %" PRIuPTR - " (subchannel %p): canceling connectivity watch (%s)", - sd->subchannel_list->tracer->name, sd->subchannel_list->policy, - sd->subchannel_list, (size_t)(sd - sd->subchannel_list->subchannels), - sd->subchannel_list->num_subchannels, sd->subchannel, reason); + grpc_exec_ctx* exec_ctx, grpc_lb_subchannel_data* sd, const char* reason) { + if (sd->subchannel_list->tracer->enabled()) { + gpr_log(GPR_DEBUG, + "[%s %p] subchannel list %p index %" PRIuPTR " of %" PRIuPTR + " (subchannel %p): canceling connectivity watch (%s)", + sd->subchannel_list->tracer->name(), sd->subchannel_list->policy, + sd->subchannel_list, + (size_t)(sd - sd->subchannel_list->subchannels), + sd->subchannel_list->num_subchannels, sd->subchannel, reason); } - grpc_subchannel_notify_on_state_change(exec_ctx, sd->subchannel, NULL, NULL, + grpc_subchannel_notify_on_state_change(exec_ctx, sd->subchannel, nullptr, + nullptr, &sd->connectivity_changed_closure); } void grpc_lb_subchannel_list_shutdown_and_unref( - grpc_exec_ctx *exec_ctx, grpc_lb_subchannel_list *subchannel_list, - const char *reason) { - if (GRPC_TRACER_ON(*subchannel_list->tracer)) { + grpc_exec_ctx* exec_ctx, grpc_lb_subchannel_list* subchannel_list, + const char* reason) { + if (subchannel_list->tracer->enabled()) { gpr_log(GPR_DEBUG, "[%s %p] Shutting down subchannel_list %p (%s)", - subchannel_list->tracer->name, subchannel_list->policy, + subchannel_list->tracer->name(), subchannel_list->policy, subchannel_list, reason); } GPR_ASSERT(!subchannel_list->shutting_down); subchannel_list->shutting_down = true; for (size_t i = 0; i < subchannel_list->num_subchannels; i++) { - grpc_lb_subchannel_data *sd = &subchannel_list->subchannels[i]; + grpc_lb_subchannel_data* sd = &subchannel_list->subchannels[i]; // If there's a pending notification for this subchannel, cancel it; // the callback is responsible for unreffing the subchannel. // Otherwise, unref the subchannel directly. if (sd->connectivity_notification_pending) { subchannel_data_cancel_connectivity_watch(exec_ctx, sd, reason); - } else if (sd->subchannel != NULL) { + } else if (sd->subchannel != nullptr) { grpc_lb_subchannel_data_unref_subchannel(exec_ctx, sd, reason); } } diff --git a/src/core/ext/filters/client_channel/lb_policy/subchannel_list.h b/src/core/ext/filters/client_channel/lb_policy/subchannel_list.h index 9d5984260f8..e3e5eba56a5 100644 --- a/src/core/ext/filters/client_channel/lb_policy/subchannel_list.h +++ b/src/core/ext/filters/client_channel/lb_policy/subchannel_list.h @@ -36,18 +36,14 @@ // round_robin that could be refactored and moved here. In a future PR, // need to clean this up. -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_lb_subchannel_list grpc_lb_subchannel_list; typedef struct { /** backpointer to owning subchannel list */ - grpc_lb_subchannel_list *subchannel_list; + grpc_lb_subchannel_list* subchannel_list; /** subchannel itself */ - grpc_subchannel *subchannel; - grpc_connected_subchannel *connected_subchannel; + grpc_subchannel* subchannel; + grpc_connected_subchannel* connected_subchannel; /** Is a connectivity notification pending? */ bool connectivity_notification_pending; /** notification that connectivity has changed on subchannel */ @@ -63,36 +59,36 @@ typedef struct { * \a connectivity_changed_closure. */ grpc_connectivity_state pending_connectivity_state_unsafe; /** the subchannel's target user data */ - void *user_data; + void* user_data; /** vtable to operate over \a user_data */ - const grpc_lb_user_data_vtable *user_data_vtable; + const grpc_lb_user_data_vtable* user_data_vtable; } grpc_lb_subchannel_data; /// Unrefs the subchannel contained in sd. -void grpc_lb_subchannel_data_unref_subchannel(grpc_exec_ctx *exec_ctx, - grpc_lb_subchannel_data *sd, - const char *reason); +void grpc_lb_subchannel_data_unref_subchannel(grpc_exec_ctx* exec_ctx, + grpc_lb_subchannel_data* sd, + const char* reason); /// Starts watching the connectivity state of the subchannel. /// The connectivity_changed_cb callback must invoke either /// grpc_lb_subchannel_data_stop_connectivity_watch() or again call /// grpc_lb_subchannel_data_start_connectivity_watch(). void grpc_lb_subchannel_data_start_connectivity_watch( - grpc_exec_ctx *exec_ctx, grpc_lb_subchannel_data *sd); + grpc_exec_ctx* exec_ctx, grpc_lb_subchannel_data* sd); /// Stops watching the connectivity state of the subchannel. void grpc_lb_subchannel_data_stop_connectivity_watch( - grpc_exec_ctx *exec_ctx, grpc_lb_subchannel_data *sd); + grpc_exec_ctx* exec_ctx, grpc_lb_subchannel_data* sd); struct grpc_lb_subchannel_list { /** backpointer to owning policy */ - grpc_lb_policy *policy; + grpc_lb_policy* policy; - grpc_tracer_flag *tracer; + grpc_core::TraceFlag* tracer; /** all our subchannels */ size_t num_subchannels; - grpc_lb_subchannel_data *subchannels; + grpc_lb_subchannel_data* subchannels; /** Index into subchannels of the one we're currently checking. * Used when connecting to subchannels serially instead of in parallel. */ @@ -120,34 +116,30 @@ struct grpc_lb_subchannel_list { bool shutting_down; }; -grpc_lb_subchannel_list *grpc_lb_subchannel_list_create( - grpc_exec_ctx *exec_ctx, grpc_lb_policy *p, grpc_tracer_flag *tracer, - const grpc_lb_addresses *addresses, const grpc_lb_policy_args *args, +grpc_lb_subchannel_list* grpc_lb_subchannel_list_create( + grpc_exec_ctx* exec_ctx, grpc_lb_policy* p, grpc_core::TraceFlag* tracer, + const grpc_lb_addresses* addresses, const grpc_lb_policy_args* args, grpc_iomgr_cb_func connectivity_changed_cb); -void grpc_lb_subchannel_list_ref(grpc_lb_subchannel_list *subchannel_list, - const char *reason); +void grpc_lb_subchannel_list_ref(grpc_lb_subchannel_list* subchannel_list, + const char* reason); -void grpc_lb_subchannel_list_unref(grpc_exec_ctx *exec_ctx, - grpc_lb_subchannel_list *subchannel_list, - const char *reason); +void grpc_lb_subchannel_list_unref(grpc_exec_ctx* exec_ctx, + grpc_lb_subchannel_list* subchannel_list, + const char* reason); /// Takes and releases refs needed for a connectivity notification. /// This includes a ref to subchannel_list and a weak ref to the LB policy. void grpc_lb_subchannel_list_ref_for_connectivity_watch( - grpc_lb_subchannel_list *subchannel_list, const char *reason); + grpc_lb_subchannel_list* subchannel_list, const char* reason); void grpc_lb_subchannel_list_unref_for_connectivity_watch( - grpc_exec_ctx *exec_ctx, grpc_lb_subchannel_list *subchannel_list, - const char *reason); + grpc_exec_ctx* exec_ctx, grpc_lb_subchannel_list* subchannel_list, + const char* reason); /// Mark subchannel_list as discarded. Unsubscribes all its subchannels. The /// connectivity state notification callback will ultimately unref it. void grpc_lb_subchannel_list_shutdown_and_unref( - grpc_exec_ctx *exec_ctx, grpc_lb_subchannel_list *subchannel_list, - const char *reason); - -#ifdef __cplusplus -} -#endif + grpc_exec_ctx* exec_ctx, grpc_lb_subchannel_list* subchannel_list, + const char* reason); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_SUBCHANNEL_LIST_H */ diff --git a/src/core/ext/filters/client_channel/lb_policy_factory.cc b/src/core/ext/filters/client_channel/lb_policy_factory.cc index 05ab43d0b69..d43f9fd1b92 100644 --- a/src/core/ext/filters/client_channel/lb_policy_factory.cc +++ b/src/core/ext/filters/client_channel/lb_policy_factory.cc @@ -43,11 +43,11 @@ grpc_lb_addresses* grpc_lb_addresses_copy(const grpc_lb_addresses* addresses) { memcpy(new_addresses->addresses, addresses->addresses, sizeof(grpc_lb_address) * addresses->num_addresses); for (size_t i = 0; i < addresses->num_addresses; ++i) { - if (new_addresses->addresses[i].balancer_name != NULL) { + if (new_addresses->addresses[i].balancer_name != nullptr) { new_addresses->addresses[i].balancer_name = gpr_strdup(new_addresses->addresses[i].balancer_name); } - if (new_addresses->addresses[i].user_data != NULL) { + if (new_addresses->addresses[i].user_data != nullptr) { new_addresses->addresses[i].user_data = addresses->user_data_vtable->copy( new_addresses->addresses[i].user_data); } @@ -60,7 +60,7 @@ void grpc_lb_addresses_set_address(grpc_lb_addresses* addresses, size_t index, bool is_balancer, const char* balancer_name, void* user_data) { GPR_ASSERT(index < addresses->num_addresses); - if (user_data != NULL) GPR_ASSERT(addresses->user_data_vtable != NULL); + if (user_data != nullptr) GPR_ASSERT(addresses->user_data_vtable != nullptr); grpc_lb_address* target = &addresses->addresses[index]; memcpy(target->address.addr, address, address_len); target->address.len = address_len; @@ -98,12 +98,12 @@ int grpc_lb_addresses_cmp(const grpc_lb_addresses* addresses1, if (target1->is_balancer > target2->is_balancer) return 1; if (target1->is_balancer < target2->is_balancer) return -1; const char* balancer_name1 = - target1->balancer_name != NULL ? target1->balancer_name : ""; + target1->balancer_name != nullptr ? target1->balancer_name : ""; const char* balancer_name2 = - target2->balancer_name != NULL ? target2->balancer_name : ""; + target2->balancer_name != nullptr ? target2->balancer_name : ""; retval = strcmp(balancer_name1, balancer_name2); if (retval != 0) return retval; - if (addresses1->user_data_vtable != NULL) { + if (addresses1->user_data_vtable != nullptr) { retval = addresses1->user_data_vtable->cmp(target1->user_data, target2->user_data); if (retval != 0) return retval; @@ -116,7 +116,7 @@ void grpc_lb_addresses_destroy(grpc_exec_ctx* exec_ctx, grpc_lb_addresses* addresses) { for (size_t i = 0; i < addresses->num_addresses; ++i) { gpr_free(addresses->addresses[i].balancer_name); - if (addresses->addresses[i].user_data != NULL) { + if (addresses->addresses[i].user_data != nullptr) { addresses->user_data_vtable->destroy(exec_ctx, addresses->addresses[i].user_data); } @@ -148,8 +148,8 @@ grpc_lb_addresses* grpc_lb_addresses_find_channel_arg( const grpc_channel_args* channel_args) { const grpc_arg* lb_addresses_arg = grpc_channel_args_find(channel_args, GRPC_ARG_LB_ADDRESSES); - if (lb_addresses_arg == NULL || lb_addresses_arg->type != GRPC_ARG_POINTER) - return NULL; + if (lb_addresses_arg == nullptr || lb_addresses_arg->type != GRPC_ARG_POINTER) + return nullptr; return (grpc_lb_addresses*)lb_addresses_arg->value.pointer.p; } @@ -164,6 +164,6 @@ void grpc_lb_policy_factory_unref(grpc_lb_policy_factory* factory) { grpc_lb_policy* grpc_lb_policy_factory_create_lb_policy( grpc_exec_ctx* exec_ctx, grpc_lb_policy_factory* factory, grpc_lb_policy_args* args) { - if (factory == NULL) return NULL; + if (factory == nullptr) return nullptr; return factory->vtable->create_lb_policy(exec_ctx, factory, args); } diff --git a/src/core/ext/filters/client_channel/lb_policy_factory.h b/src/core/ext/filters/client_channel/lb_policy_factory.h index 8790ffdda31..8f6d8c1b082 100644 --- a/src/core/ext/filters/client_channel/lb_policy_factory.h +++ b/src/core/ext/filters/client_channel/lb_policy_factory.h @@ -29,15 +29,11 @@ // Channel arg key for grpc_lb_addresses. #define GRPC_ARG_LB_ADDRESSES "grpc.lb_addresses" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_lb_policy_factory grpc_lb_policy_factory; typedef struct grpc_lb_policy_factory_vtable grpc_lb_policy_factory_vtable; struct grpc_lb_policy_factory { - const grpc_lb_policy_factory_vtable *vtable; + const grpc_lb_policy_factory_vtable* vtable; }; /** A resolved address alongside any LB related information associated with it. @@ -48,94 +44,90 @@ struct grpc_lb_policy_factory { typedef struct grpc_lb_address { grpc_resolved_address address; bool is_balancer; - char *balancer_name; /* For secure naming. */ - void *user_data; + char* balancer_name; /* For secure naming. */ + void* user_data; } grpc_lb_address; typedef struct grpc_lb_user_data_vtable { - void *(*copy)(void *); - void (*destroy)(grpc_exec_ctx *exec_ctx, void *); - int (*cmp)(void *, void *); + void* (*copy)(void*); + void (*destroy)(grpc_exec_ctx* exec_ctx, void*); + int (*cmp)(void*, void*); } grpc_lb_user_data_vtable; typedef struct grpc_lb_addresses { size_t num_addresses; - grpc_lb_address *addresses; - const grpc_lb_user_data_vtable *user_data_vtable; + grpc_lb_address* addresses; + const grpc_lb_user_data_vtable* user_data_vtable; } grpc_lb_addresses; /** Returns a grpc_addresses struct with enough space for \a num_addresses addresses. The \a user_data_vtable argument may be NULL if no user data will be added. */ -grpc_lb_addresses *grpc_lb_addresses_create( - size_t num_addresses, const grpc_lb_user_data_vtable *user_data_vtable); +grpc_lb_addresses* grpc_lb_addresses_create( + size_t num_addresses, const grpc_lb_user_data_vtable* user_data_vtable); /** Creates a copy of \a addresses. */ -grpc_lb_addresses *grpc_lb_addresses_copy(const grpc_lb_addresses *addresses); +grpc_lb_addresses* grpc_lb_addresses_copy(const grpc_lb_addresses* addresses); /** Sets the value of the address at index \a index of \a addresses. * \a address is a socket address of length \a address_len. * Takes ownership of \a balancer_name. */ -void grpc_lb_addresses_set_address(grpc_lb_addresses *addresses, size_t index, - const void *address, size_t address_len, - bool is_balancer, const char *balancer_name, - void *user_data); +void grpc_lb_addresses_set_address(grpc_lb_addresses* addresses, size_t index, + const void* address, size_t address_len, + bool is_balancer, const char* balancer_name, + void* user_data); /** Sets the value of the address at index \a index of \a addresses from \a uri. * Returns true upon success, false otherwise. Takes ownership of \a * balancer_name. */ -bool grpc_lb_addresses_set_address_from_uri(grpc_lb_addresses *addresses, - size_t index, const grpc_uri *uri, +bool grpc_lb_addresses_set_address_from_uri(grpc_lb_addresses* addresses, + size_t index, const grpc_uri* uri, bool is_balancer, - const char *balancer_name, - void *user_data); + const char* balancer_name, + void* user_data); /** Compares \a addresses1 and \a addresses2. */ -int grpc_lb_addresses_cmp(const grpc_lb_addresses *addresses1, - const grpc_lb_addresses *addresses2); +int grpc_lb_addresses_cmp(const grpc_lb_addresses* addresses1, + const grpc_lb_addresses* addresses2); /** Destroys \a addresses. */ -void grpc_lb_addresses_destroy(grpc_exec_ctx *exec_ctx, - grpc_lb_addresses *addresses); +void grpc_lb_addresses_destroy(grpc_exec_ctx* exec_ctx, + grpc_lb_addresses* addresses); /** Returns a channel arg containing \a addresses. */ grpc_arg grpc_lb_addresses_create_channel_arg( - const grpc_lb_addresses *addresses); + const grpc_lb_addresses* addresses); /** Returns the \a grpc_lb_addresses instance in \a channel_args or NULL */ -grpc_lb_addresses *grpc_lb_addresses_find_channel_arg( - const grpc_channel_args *channel_args); +grpc_lb_addresses* grpc_lb_addresses_find_channel_arg( + const grpc_channel_args* channel_args); /** Arguments passed to LB policies. */ struct grpc_lb_policy_args { - grpc_client_channel_factory *client_channel_factory; - grpc_channel_args *args; - grpc_combiner *combiner; + grpc_client_channel_factory* client_channel_factory; + grpc_channel_args* args; + grpc_combiner* combiner; }; struct grpc_lb_policy_factory_vtable { - void (*ref)(grpc_lb_policy_factory *factory); - void (*unref)(grpc_lb_policy_factory *factory); + void (*ref)(grpc_lb_policy_factory* factory); + void (*unref)(grpc_lb_policy_factory* factory); /** Implementation of grpc_lb_policy_factory_create_lb_policy */ - grpc_lb_policy *(*create_lb_policy)(grpc_exec_ctx *exec_ctx, - grpc_lb_policy_factory *factory, - grpc_lb_policy_args *args); + grpc_lb_policy* (*create_lb_policy)(grpc_exec_ctx* exec_ctx, + grpc_lb_policy_factory* factory, + grpc_lb_policy_args* args); /** Name for the LB policy this factory implements */ - const char *name; + const char* name; }; -void grpc_lb_policy_factory_ref(grpc_lb_policy_factory *factory); -void grpc_lb_policy_factory_unref(grpc_lb_policy_factory *factory); +void grpc_lb_policy_factory_ref(grpc_lb_policy_factory* factory); +void grpc_lb_policy_factory_unref(grpc_lb_policy_factory* factory); /** Create a lb_policy instance. */ -grpc_lb_policy *grpc_lb_policy_factory_create_lb_policy( - grpc_exec_ctx *exec_ctx, grpc_lb_policy_factory *factory, - grpc_lb_policy_args *args); - -#ifdef __cplusplus -} -#endif +grpc_lb_policy* grpc_lb_policy_factory_create_lb_policy( + grpc_exec_ctx* exec_ctx, grpc_lb_policy_factory* factory, + grpc_lb_policy_args* args); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_FACTORY_H */ diff --git a/src/core/ext/filters/client_channel/lb_policy_registry.cc b/src/core/ext/filters/client_channel/lb_policy_registry.cc index f2460f83045..6e710e86d95 100644 --- a/src/core/ext/filters/client_channel/lb_policy_registry.cc +++ b/src/core/ext/filters/client_channel/lb_policy_registry.cc @@ -24,7 +24,7 @@ #define MAX_POLICIES 10 -static grpc_lb_policy_factory *g_all_of_the_lb_policies[MAX_POLICIES]; +static grpc_lb_policy_factory* g_all_of_the_lb_policies[MAX_POLICIES]; static int g_number_of_lb_policies = 0; void grpc_lb_policy_registry_init(void) { g_number_of_lb_policies = 0; } @@ -36,7 +36,7 @@ void grpc_lb_policy_registry_shutdown(void) { } } -void grpc_register_lb_policy(grpc_lb_policy_factory *factory) { +void grpc_register_lb_policy(grpc_lb_policy_factory* factory) { int i; for (i = 0; i < g_number_of_lb_policies; i++) { GPR_ASSERT(0 != gpr_stricmp(factory->vtable->name, @@ -47,10 +47,10 @@ void grpc_register_lb_policy(grpc_lb_policy_factory *factory) { g_all_of_the_lb_policies[g_number_of_lb_policies++] = factory; } -static grpc_lb_policy_factory *lookup_factory(const char *name) { +static grpc_lb_policy_factory* lookup_factory(const char* name) { int i; - if (name == NULL) return NULL; + if (name == nullptr) return nullptr; for (i = 0; i < g_number_of_lb_policies; i++) { if (0 == gpr_stricmp(name, g_all_of_the_lb_policies[i]->vtable->name)) { @@ -58,13 +58,13 @@ static grpc_lb_policy_factory *lookup_factory(const char *name) { } } - return NULL; + return nullptr; } -grpc_lb_policy *grpc_lb_policy_create(grpc_exec_ctx *exec_ctx, const char *name, - grpc_lb_policy_args *args) { - grpc_lb_policy_factory *factory = lookup_factory(name); - grpc_lb_policy *lb_policy = +grpc_lb_policy* grpc_lb_policy_create(grpc_exec_ctx* exec_ctx, const char* name, + grpc_lb_policy_args* args) { + grpc_lb_policy_factory* factory = lookup_factory(name); + grpc_lb_policy* lb_policy = grpc_lb_policy_factory_create_lb_policy(exec_ctx, factory, args); return lb_policy; } diff --git a/src/core/ext/filters/client_channel/lb_policy_registry.h b/src/core/ext/filters/client_channel/lb_policy_registry.h index 55154cb02a1..acddc90fddc 100644 --- a/src/core/ext/filters/client_channel/lb_policy_registry.h +++ b/src/core/ext/filters/client_channel/lb_policy_registry.h @@ -22,27 +22,19 @@ #include "src/core/ext/filters/client_channel/lb_policy_factory.h" #include "src/core/lib/iomgr/exec_ctx.h" -#ifdef __cplusplus -extern "C" { -#endif - /** Initialize the registry and set \a default_factory as the factory to be * returned when no name is provided in a lookup */ void grpc_lb_policy_registry_init(void); void grpc_lb_policy_registry_shutdown(void); /** Register a LB policy factory. */ -void grpc_register_lb_policy(grpc_lb_policy_factory *factory); +void grpc_register_lb_policy(grpc_lb_policy_factory* factory); /** Create a \a grpc_lb_policy instance. * * If \a name is NULL, the default factory from \a grpc_lb_policy_registry_init * will be returned. */ -grpc_lb_policy *grpc_lb_policy_create(grpc_exec_ctx *exec_ctx, const char *name, - grpc_lb_policy_args *args); - -#ifdef __cplusplus -} -#endif +grpc_lb_policy* grpc_lb_policy_create(grpc_exec_ctx* exec_ctx, const char* name, + grpc_lb_policy_args* args); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_REGISTRY_H */ diff --git a/src/core/ext/filters/client_channel/parse_address.cc b/src/core/ext/filters/client_channel/parse_address.cc index 2152b5a1e9f..39b1237c770 100644 --- a/src/core/ext/filters/client_channel/parse_address.cc +++ b/src/core/ext/filters/client_channel/parse_address.cc @@ -33,13 +33,13 @@ #ifdef GRPC_HAVE_UNIX_SOCKET -bool grpc_parse_unix(const grpc_uri *uri, - grpc_resolved_address *resolved_addr) { +bool grpc_parse_unix(const grpc_uri* uri, + grpc_resolved_address* resolved_addr) { if (strcmp("unix", uri->scheme) != 0) { gpr_log(GPR_ERROR, "Expected 'unix' scheme, got '%s'", uri->scheme); return false; } - struct sockaddr_un *un = (struct sockaddr_un *)resolved_addr->addr; + struct sockaddr_un* un = (struct sockaddr_un*)resolved_addr->addr; const size_t maxlen = sizeof(un->sun_path); const size_t path_len = strnlen(uri->path, maxlen); if (path_len == maxlen) return false; @@ -51,31 +51,31 @@ bool grpc_parse_unix(const grpc_uri *uri, #else /* GRPC_HAVE_UNIX_SOCKET */ -bool grpc_parse_unix(const grpc_uri *uri, - grpc_resolved_address *resolved_addr) { +bool grpc_parse_unix(const grpc_uri* uri, + grpc_resolved_address* resolved_addr) { abort(); } #endif /* GRPC_HAVE_UNIX_SOCKET */ -bool grpc_parse_ipv4_hostport(const char *hostport, grpc_resolved_address *addr, +bool grpc_parse_ipv4_hostport(const char* hostport, grpc_resolved_address* addr, bool log_errors) { bool success = false; // Split host and port. - char *host; - char *port; + char* host; + char* port; if (!gpr_split_host_port(hostport, &host, &port)) return false; // Parse IP address. memset(addr, 0, sizeof(*addr)); addr->len = sizeof(struct sockaddr_in); - struct sockaddr_in *in = (struct sockaddr_in *)addr->addr; + struct sockaddr_in* in = (struct sockaddr_in*)addr->addr; in->sin_family = AF_INET; if (inet_pton(AF_INET, host, &in->sin_addr) == 0) { if (log_errors) gpr_log(GPR_ERROR, "invalid ipv4 address: '%s'", host); goto done; } // Parse port. - if (port == NULL) { + if (port == nullptr) { if (log_errors) gpr_log(GPR_ERROR, "no port given for ipv4 scheme"); goto done; } @@ -92,33 +92,33 @@ done: return success; } -bool grpc_parse_ipv4(const grpc_uri *uri, - grpc_resolved_address *resolved_addr) { +bool grpc_parse_ipv4(const grpc_uri* uri, + grpc_resolved_address* resolved_addr) { if (strcmp("ipv4", uri->scheme) != 0) { gpr_log(GPR_ERROR, "Expected 'ipv4' scheme, got '%s'", uri->scheme); return false; } - const char *host_port = uri->path; + const char* host_port = uri->path; if (*host_port == '/') ++host_port; return grpc_parse_ipv4_hostport(host_port, resolved_addr, true /* log_errors */); } -bool grpc_parse_ipv6_hostport(const char *hostport, grpc_resolved_address *addr, +bool grpc_parse_ipv6_hostport(const char* hostport, grpc_resolved_address* addr, bool log_errors) { bool success = false; // Split host and port. - char *host; - char *port; + char* host; + char* port; if (!gpr_split_host_port(hostport, &host, &port)) return false; // Parse IP address. memset(addr, 0, sizeof(*addr)); addr->len = sizeof(struct sockaddr_in6); - struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)addr->addr; + struct sockaddr_in6* in6 = (struct sockaddr_in6*)addr->addr; in6->sin6_family = AF_INET6; // Handle the RFC6874 syntax for IPv6 zone identifiers. - char *host_end = (char *)gpr_memrchr(host, '%', strlen(host)); - if (host_end != NULL) { + char* host_end = (char*)gpr_memrchr(host, '%', strlen(host)); + if (host_end != nullptr) { GPR_ASSERT(host_end >= host); char host_without_scope[INET6_ADDRSTRLEN]; size_t host_without_scope_len = (size_t)(host_end - host); @@ -144,7 +144,7 @@ bool grpc_parse_ipv6_hostport(const char *hostport, grpc_resolved_address *addr, } } // Parse port. - if (port == NULL) { + if (port == nullptr) { if (log_errors) gpr_log(GPR_ERROR, "no port given for ipv6 scheme"); goto done; } @@ -161,19 +161,19 @@ done: return success; } -bool grpc_parse_ipv6(const grpc_uri *uri, - grpc_resolved_address *resolved_addr) { +bool grpc_parse_ipv6(const grpc_uri* uri, + grpc_resolved_address* resolved_addr) { if (strcmp("ipv6", uri->scheme) != 0) { gpr_log(GPR_ERROR, "Expected 'ipv6' scheme, got '%s'", uri->scheme); return false; } - const char *host_port = uri->path; + const char* host_port = uri->path; if (*host_port == '/') ++host_port; return grpc_parse_ipv6_hostport(host_port, resolved_addr, true /* log_errors */); } -bool grpc_parse_uri(const grpc_uri *uri, grpc_resolved_address *resolved_addr) { +bool grpc_parse_uri(const grpc_uri* uri, grpc_resolved_address* resolved_addr) { if (strcmp("unix", uri->scheme) == 0) { return grpc_parse_unix(uri, resolved_addr); } else if (strcmp("ipv4", uri->scheme) == 0) { diff --git a/src/core/ext/filters/client_channel/parse_address.h b/src/core/ext/filters/client_channel/parse_address.h index 27d06a1cb3d..ca0a0d18f03 100644 --- a/src/core/ext/filters/client_channel/parse_address.h +++ b/src/core/ext/filters/client_channel/parse_address.h @@ -24,33 +24,25 @@ #include "src/core/ext/filters/client_channel/uri_parser.h" #include "src/core/lib/iomgr/resolve_address.h" -#ifdef __cplusplus -extern "C" { -#endif - /** Populate \a resolved_addr from \a uri, whose path is expected to contain a * unix socket path. Returns true upon success. */ -bool grpc_parse_unix(const grpc_uri *uri, grpc_resolved_address *resolved_addr); +bool grpc_parse_unix(const grpc_uri* uri, grpc_resolved_address* resolved_addr); /** Populate \a resolved_addr from \a uri, whose path is expected to contain an * IPv4 host:port pair. Returns true upon success. */ -bool grpc_parse_ipv4(const grpc_uri *uri, grpc_resolved_address *resolved_addr); +bool grpc_parse_ipv4(const grpc_uri* uri, grpc_resolved_address* resolved_addr); /** Populate \a resolved_addr from \a uri, whose path is expected to contain an * IPv6 host:port pair. Returns true upon success. */ -bool grpc_parse_ipv6(const grpc_uri *uri, grpc_resolved_address *resolved_addr); +bool grpc_parse_ipv6(const grpc_uri* uri, grpc_resolved_address* resolved_addr); /** Populate \a resolved_addr from \a uri. Returns true upon success. */ -bool grpc_parse_uri(const grpc_uri *uri, grpc_resolved_address *resolved_addr); +bool grpc_parse_uri(const grpc_uri* uri, grpc_resolved_address* resolved_addr); /** Parse bare IPv4 or IPv6 "IP:port" strings. */ -bool grpc_parse_ipv4_hostport(const char *hostport, grpc_resolved_address *addr, +bool grpc_parse_ipv4_hostport(const char* hostport, grpc_resolved_address* addr, bool log_errors); -bool grpc_parse_ipv6_hostport(const char *hostport, grpc_resolved_address *addr, +bool grpc_parse_ipv6_hostport(const char* hostport, grpc_resolved_address* addr, bool log_errors); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_PARSE_ADDRESS_H */ diff --git a/src/core/ext/filters/client_channel/proxy_mapper.h b/src/core/ext/filters/client_channel/proxy_mapper.h index bb8259f8545..a13861ccaf9 100644 --- a/src/core/ext/filters/client_channel/proxy_mapper.h +++ b/src/core/ext/filters/client_channel/proxy_mapper.h @@ -25,10 +25,6 @@ #include "src/core/lib/iomgr/resolve_address.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_proxy_mapper grpc_proxy_mapper; typedef struct { @@ -75,8 +71,4 @@ bool grpc_proxy_mapper_map_address(grpc_exec_ctx* exec_ctx, void grpc_proxy_mapper_destroy(grpc_proxy_mapper* mapper); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_PROXY_MAPPER_H */ diff --git a/src/core/ext/filters/client_channel/proxy_mapper_registry.h b/src/core/ext/filters/client_channel/proxy_mapper_registry.h index 39c607cefcf..99e54d1a78b 100644 --- a/src/core/ext/filters/client_channel/proxy_mapper_registry.h +++ b/src/core/ext/filters/client_channel/proxy_mapper_registry.h @@ -21,10 +21,6 @@ #include "src/core/ext/filters/client_channel/proxy_mapper.h" -#ifdef __cplusplus -extern "C" { -#endif - void grpc_proxy_mapper_registry_init(); void grpc_proxy_mapper_registry_shutdown(); @@ -45,8 +41,4 @@ bool grpc_proxy_mappers_map_address(grpc_exec_ctx* exec_ctx, grpc_resolved_address** new_address, grpc_channel_args** new_args); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_PROXY_MAPPER_REGISTRY_H */ diff --git a/src/core/ext/filters/client_channel/resolver.cc b/src/core/ext/filters/client_channel/resolver.cc index 8401504fcf6..c16b1515c7c 100644 --- a/src/core/ext/filters/client_channel/resolver.cc +++ b/src/core/ext/filters/client_channel/resolver.cc @@ -19,65 +19,63 @@ #include "src/core/ext/filters/client_channel/resolver.h" #include "src/core/lib/iomgr/combiner.h" -#ifndef NDEBUG -grpc_tracer_flag grpc_trace_resolver_refcount = - GRPC_TRACER_INITIALIZER(false, "resolver_refcount"); -#endif +grpc_core::DebugOnlyTraceFlag grpc_trace_resolver_refcount(false, + "resolver_refcount"); -void grpc_resolver_init(grpc_resolver *resolver, - const grpc_resolver_vtable *vtable, - grpc_combiner *combiner) { +void grpc_resolver_init(grpc_resolver* resolver, + const grpc_resolver_vtable* vtable, + grpc_combiner* combiner) { resolver->vtable = vtable; resolver->combiner = GRPC_COMBINER_REF(combiner, "resolver"); gpr_ref_init(&resolver->refs, 1); } #ifndef NDEBUG -void grpc_resolver_ref(grpc_resolver *resolver, const char *file, int line, - const char *reason) { - if (GRPC_TRACER_ON(grpc_trace_resolver_refcount)) { +void grpc_resolver_ref(grpc_resolver* resolver, const char* file, int line, + const char* reason) { + if (grpc_trace_resolver_refcount.enabled()) { gpr_atm old_refs = gpr_atm_no_barrier_load(&resolver->refs.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "RESOLVER:%p ref %" PRIdPTR " -> %" PRIdPTR " %s", resolver, old_refs, old_refs + 1, reason); } #else -void grpc_resolver_ref(grpc_resolver *resolver) { +void grpc_resolver_ref(grpc_resolver* resolver) { #endif gpr_ref(&resolver->refs); } #ifndef NDEBUG -void grpc_resolver_unref(grpc_exec_ctx *exec_ctx, grpc_resolver *resolver, - const char *file, int line, const char *reason) { - if (GRPC_TRACER_ON(grpc_trace_resolver_refcount)) { +void grpc_resolver_unref(grpc_exec_ctx* exec_ctx, grpc_resolver* resolver, + const char* file, int line, const char* reason) { + if (grpc_trace_resolver_refcount.enabled()) { gpr_atm old_refs = gpr_atm_no_barrier_load(&resolver->refs.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "RESOLVER:%p unref %" PRIdPTR " -> %" PRIdPTR " %s", resolver, old_refs, old_refs - 1, reason); } #else -void grpc_resolver_unref(grpc_exec_ctx *exec_ctx, grpc_resolver *resolver) { +void grpc_resolver_unref(grpc_exec_ctx* exec_ctx, grpc_resolver* resolver) { #endif if (gpr_unref(&resolver->refs)) { - grpc_combiner *combiner = resolver->combiner; + grpc_combiner* combiner = resolver->combiner; resolver->vtable->destroy(exec_ctx, resolver); GRPC_COMBINER_UNREF(exec_ctx, combiner, "resolver"); } } -void grpc_resolver_shutdown_locked(grpc_exec_ctx *exec_ctx, - grpc_resolver *resolver) { +void grpc_resolver_shutdown_locked(grpc_exec_ctx* exec_ctx, + grpc_resolver* resolver) { resolver->vtable->shutdown_locked(exec_ctx, resolver); } -void grpc_resolver_channel_saw_error_locked(grpc_exec_ctx *exec_ctx, - grpc_resolver *resolver) { +void grpc_resolver_channel_saw_error_locked(grpc_exec_ctx* exec_ctx, + grpc_resolver* resolver) { resolver->vtable->channel_saw_error_locked(exec_ctx, resolver); } -void grpc_resolver_next_locked(grpc_exec_ctx *exec_ctx, grpc_resolver *resolver, - grpc_channel_args **result, - grpc_closure *on_complete) { +void grpc_resolver_next_locked(grpc_exec_ctx* exec_ctx, grpc_resolver* resolver, + grpc_channel_args** result, + grpc_closure* on_complete) { resolver->vtable->next_locked(exec_ctx, resolver, result, on_complete); } diff --git a/src/core/ext/filters/client_channel/resolver.h b/src/core/ext/filters/client_channel/resolver.h index 73fbbbbc3b1..4e8cfbe4170 100644 --- a/src/core/ext/filters/client_channel/resolver.h +++ b/src/core/ext/filters/client_channel/resolver.h @@ -22,62 +22,56 @@ #include "src/core/ext/filters/client_channel/subchannel.h" #include "src/core/lib/iomgr/iomgr.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_resolver grpc_resolver; typedef struct grpc_resolver_vtable grpc_resolver_vtable; -#ifndef NDEBUG -extern grpc_tracer_flag grpc_trace_resolver_refcount; -#endif +extern grpc_core::DebugOnlyTraceFlag grpc_trace_resolver_refcount; /** \a grpc_resolver provides \a grpc_channel_args objects to its caller */ struct grpc_resolver { - const grpc_resolver_vtable *vtable; + const grpc_resolver_vtable* vtable; gpr_refcount refs; - grpc_combiner *combiner; + grpc_combiner* combiner; }; struct grpc_resolver_vtable { - void (*destroy)(grpc_exec_ctx *exec_ctx, grpc_resolver *resolver); - void (*shutdown_locked)(grpc_exec_ctx *exec_ctx, grpc_resolver *resolver); - void (*channel_saw_error_locked)(grpc_exec_ctx *exec_ctx, - grpc_resolver *resolver); - void (*next_locked)(grpc_exec_ctx *exec_ctx, grpc_resolver *resolver, - grpc_channel_args **result, grpc_closure *on_complete); + void (*destroy)(grpc_exec_ctx* exec_ctx, grpc_resolver* resolver); + void (*shutdown_locked)(grpc_exec_ctx* exec_ctx, grpc_resolver* resolver); + void (*channel_saw_error_locked)(grpc_exec_ctx* exec_ctx, + grpc_resolver* resolver); + void (*next_locked)(grpc_exec_ctx* exec_ctx, grpc_resolver* resolver, + grpc_channel_args** result, grpc_closure* on_complete); }; #ifndef NDEBUG #define GRPC_RESOLVER_REF(p, r) grpc_resolver_ref((p), __FILE__, __LINE__, (r)) #define GRPC_RESOLVER_UNREF(e, p, r) \ grpc_resolver_unref((e), (p), __FILE__, __LINE__, (r)) -void grpc_resolver_ref(grpc_resolver *policy, const char *file, int line, - const char *reason); -void grpc_resolver_unref(grpc_exec_ctx *exec_ctx, grpc_resolver *policy, - const char *file, int line, const char *reason); +void grpc_resolver_ref(grpc_resolver* policy, const char* file, int line, + const char* reason); +void grpc_resolver_unref(grpc_exec_ctx* exec_ctx, grpc_resolver* policy, + const char* file, int line, const char* reason); #else #define GRPC_RESOLVER_REF(p, r) grpc_resolver_ref((p)) #define GRPC_RESOLVER_UNREF(e, p, r) grpc_resolver_unref((e), (p)) -void grpc_resolver_ref(grpc_resolver *policy); -void grpc_resolver_unref(grpc_exec_ctx *exec_ctx, grpc_resolver *policy); +void grpc_resolver_ref(grpc_resolver* policy); +void grpc_resolver_unref(grpc_exec_ctx* exec_ctx, grpc_resolver* policy); #endif -void grpc_resolver_init(grpc_resolver *resolver, - const grpc_resolver_vtable *vtable, - grpc_combiner *combiner); +void grpc_resolver_init(grpc_resolver* resolver, + const grpc_resolver_vtable* vtable, + grpc_combiner* combiner); -void grpc_resolver_shutdown_locked(grpc_exec_ctx *exec_ctx, - grpc_resolver *resolver); +void grpc_resolver_shutdown_locked(grpc_exec_ctx* exec_ctx, + grpc_resolver* resolver); /** Notification that the channel has seen an error on some address. Can be used as a hint that re-resolution is desirable soon. Must be called from the combiner passed as a resolver_arg at construction time.*/ -void grpc_resolver_channel_saw_error_locked(grpc_exec_ctx *exec_ctx, - grpc_resolver *resolver); +void grpc_resolver_channel_saw_error_locked(grpc_exec_ctx* exec_ctx, + grpc_resolver* resolver); /** Get the next result from the resolver. Expected to set \a *result with new channel args and then schedule \a on_complete for execution. @@ -87,12 +81,8 @@ void grpc_resolver_channel_saw_error_locked(grpc_exec_ctx *exec_ctx, Must be called from the combiner passed as a resolver_arg at construction time.*/ -void grpc_resolver_next_locked(grpc_exec_ctx *exec_ctx, grpc_resolver *resolver, - grpc_channel_args **result, - grpc_closure *on_complete); - -#ifdef __cplusplus -} -#endif +void grpc_resolver_next_locked(grpc_exec_ctx* exec_ctx, grpc_resolver* resolver, + grpc_channel_args** result, + grpc_closure* on_complete); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_H */ diff --git a/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc b/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc index 5f7ab987cbd..3a16b3492d1 100644 --- a/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc +++ b/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc @@ -53,38 +53,38 @@ typedef struct { /** base class: must be first */ grpc_resolver base; /** DNS server to use (if not system default) */ - char *dns_server; + char* dns_server; /** name to resolve (usually the same as target_name) */ - char *name_to_resolve; + char* name_to_resolve; /** default port to use */ - char *default_port; + char* default_port; /** channel args. */ - grpc_channel_args *channel_args; + grpc_channel_args* channel_args; /** whether to request the service config */ bool request_service_config; /** pollset_set to drive the name resolution process */ - grpc_pollset_set *interested_parties; + grpc_pollset_set* interested_parties; /** Closures used by the combiner */ grpc_closure dns_ares_on_retry_timer_locked; grpc_closure dns_ares_on_resolved_locked; /** Combiner guarding the rest of the state */ - grpc_combiner *combiner; + grpc_combiner* combiner; /** are we currently resolving? */ bool resolving; /** the pending resolving request */ - grpc_ares_request *pending_request; + grpc_ares_request* pending_request; /** which version of the result have we published? */ int published_version; /** which version of the result is current? */ int resolved_version; /** pending next completion, or NULL */ - grpc_closure *next_completion; + grpc_closure* next_completion; /** target result address for next completion */ - grpc_channel_args **target_result; + grpc_channel_args** target_result; /** current (fully resolved) result */ - grpc_channel_args *resolved_result; + grpc_channel_args* resolved_result; /** retry timer */ bool have_retry_timer; grpc_timer retry_timer; @@ -92,59 +92,59 @@ typedef struct { grpc_backoff backoff_state; /** currently resolving addresses */ - grpc_lb_addresses *lb_addresses; + grpc_lb_addresses* lb_addresses; /** currently resolving service config */ - char *service_config_json; + char* service_config_json; } ares_dns_resolver; -static void dns_ares_destroy(grpc_exec_ctx *exec_ctx, grpc_resolver *r); +static void dns_ares_destroy(grpc_exec_ctx* exec_ctx, grpc_resolver* r); -static void dns_ares_start_resolving_locked(grpc_exec_ctx *exec_ctx, - ares_dns_resolver *r); -static void dns_ares_maybe_finish_next_locked(grpc_exec_ctx *exec_ctx, - ares_dns_resolver *r); +static void dns_ares_start_resolving_locked(grpc_exec_ctx* exec_ctx, + ares_dns_resolver* r); +static void dns_ares_maybe_finish_next_locked(grpc_exec_ctx* exec_ctx, + ares_dns_resolver* r); -static void dns_ares_shutdown_locked(grpc_exec_ctx *exec_ctx, grpc_resolver *r); -static void dns_ares_channel_saw_error_locked(grpc_exec_ctx *exec_ctx, - grpc_resolver *r); -static void dns_ares_next_locked(grpc_exec_ctx *exec_ctx, grpc_resolver *r, - grpc_channel_args **target_result, - grpc_closure *on_complete); +static void dns_ares_shutdown_locked(grpc_exec_ctx* exec_ctx, grpc_resolver* r); +static void dns_ares_channel_saw_error_locked(grpc_exec_ctx* exec_ctx, + grpc_resolver* r); +static void dns_ares_next_locked(grpc_exec_ctx* exec_ctx, grpc_resolver* r, + grpc_channel_args** target_result, + grpc_closure* on_complete); static const grpc_resolver_vtable dns_ares_resolver_vtable = { dns_ares_destroy, dns_ares_shutdown_locked, dns_ares_channel_saw_error_locked, dns_ares_next_locked}; -static void dns_ares_shutdown_locked(grpc_exec_ctx *exec_ctx, - grpc_resolver *resolver) { - ares_dns_resolver *r = (ares_dns_resolver *)resolver; +static void dns_ares_shutdown_locked(grpc_exec_ctx* exec_ctx, + grpc_resolver* resolver) { + ares_dns_resolver* r = (ares_dns_resolver*)resolver; if (r->have_retry_timer) { grpc_timer_cancel(exec_ctx, &r->retry_timer); } - if (r->pending_request != NULL) { + if (r->pending_request != nullptr) { grpc_cancel_ares_request(exec_ctx, r->pending_request); } - if (r->next_completion != NULL) { - *r->target_result = NULL; + if (r->next_completion != nullptr) { + *r->target_result = nullptr; GRPC_CLOSURE_SCHED( exec_ctx, r->next_completion, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Resolver Shutdown")); - r->next_completion = NULL; + r->next_completion = nullptr; } } -static void dns_ares_channel_saw_error_locked(grpc_exec_ctx *exec_ctx, - grpc_resolver *resolver) { - ares_dns_resolver *r = (ares_dns_resolver *)resolver; +static void dns_ares_channel_saw_error_locked(grpc_exec_ctx* exec_ctx, + grpc_resolver* resolver) { + ares_dns_resolver* r = (ares_dns_resolver*)resolver; if (!r->resolving) { grpc_backoff_reset(&r->backoff_state); dns_ares_start_resolving_locked(exec_ctx, r); } } -static void dns_ares_on_retry_timer_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - ares_dns_resolver *r = (ares_dns_resolver *)arg; +static void dns_ares_on_retry_timer_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + ares_dns_resolver* r = (ares_dns_resolver*)arg; r->have_retry_timer = false; if (error == GRPC_ERROR_NONE) { if (!r->resolving) { @@ -154,8 +154,8 @@ static void dns_ares_on_retry_timer_locked(grpc_exec_ctx *exec_ctx, void *arg, GRPC_RESOLVER_UNREF(exec_ctx, &r->base, "retry-timer"); } -static bool value_in_json_array(grpc_json *array, const char *value) { - for (grpc_json *entry = array->child; entry != NULL; entry = entry->next) { +static bool value_in_json_array(grpc_json* array, const char* value) { + for (grpc_json* entry = array->child; entry != nullptr; entry = entry->next) { if (entry->type == GRPC_JSON_STRING && strcmp(entry->value, value) == 0) { return true; } @@ -163,49 +163,50 @@ static bool value_in_json_array(grpc_json *array, const char *value) { return false; } -static char *choose_service_config(char *service_config_choice_json) { - grpc_json *choices_json = grpc_json_parse_string(service_config_choice_json); - if (choices_json == NULL || choices_json->type != GRPC_JSON_ARRAY) { +static char* choose_service_config(char* service_config_choice_json) { + grpc_json* choices_json = grpc_json_parse_string(service_config_choice_json); + if (choices_json == nullptr || choices_json->type != GRPC_JSON_ARRAY) { gpr_log(GPR_ERROR, "cannot parse service config JSON string"); - return NULL; + return nullptr; } - char *service_config = NULL; - for (grpc_json *choice = choices_json->child; choice != NULL; + char* service_config = nullptr; + for (grpc_json* choice = choices_json->child; choice != nullptr; choice = choice->next) { if (choice->type != GRPC_JSON_OBJECT) { gpr_log(GPR_ERROR, "cannot parse service config JSON string"); break; } - grpc_json *service_config_json = NULL; - for (grpc_json *field = choice->child; field != NULL; field = field->next) { + grpc_json* service_config_json = nullptr; + for (grpc_json* field = choice->child; field != nullptr; + field = field->next) { // Check client language, if specified. if (strcmp(field->key, "clientLanguage") == 0) { if (field->type != GRPC_JSON_ARRAY || !value_in_json_array(field, "c++")) { - service_config_json = NULL; + service_config_json = nullptr; break; } } // Check client hostname, if specified. if (strcmp(field->key, "clientHostname") == 0) { - char *hostname = grpc_gethostname(); - if (hostname == NULL || field->type != GRPC_JSON_ARRAY || + char* hostname = grpc_gethostname(); + if (hostname == nullptr || field->type != GRPC_JSON_ARRAY || !value_in_json_array(field, hostname)) { - service_config_json = NULL; + service_config_json = nullptr; break; } } // Check percentage, if specified. if (strcmp(field->key, "percentage") == 0) { if (field->type != GRPC_JSON_NUMBER) { - service_config_json = NULL; + service_config_json = nullptr; break; } int random_pct = rand() % 100; int percentage; if (sscanf(field->value, "%d", &percentage) != 1 || random_pct > percentage || percentage == 0) { - service_config_json = NULL; + service_config_json = nullptr; break; } } @@ -216,7 +217,7 @@ static char *choose_service_config(char *service_config_choice_json) { } } } - if (service_config_json != NULL) { + if (service_config_json != nullptr) { service_config = grpc_json_dump_to_string(service_config_json, 0); break; } @@ -225,39 +226,39 @@ static char *choose_service_config(char *service_config_choice_json) { return service_config; } -static void dns_ares_on_resolved_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - ares_dns_resolver *r = (ares_dns_resolver *)arg; - grpc_channel_args *result = NULL; +static void dns_ares_on_resolved_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + ares_dns_resolver* r = (ares_dns_resolver*)arg; + grpc_channel_args* result = nullptr; GPR_ASSERT(r->resolving); r->resolving = false; - r->pending_request = NULL; - if (r->lb_addresses != NULL) { - static const char *args_to_remove[2]; + r->pending_request = nullptr; + if (r->lb_addresses != nullptr) { + static const char* args_to_remove[2]; size_t num_args_to_remove = 0; grpc_arg new_args[3]; size_t num_args_to_add = 0; new_args[num_args_to_add++] = grpc_lb_addresses_create_channel_arg(r->lb_addresses); - grpc_service_config *service_config = NULL; - char *service_config_string = NULL; - if (r->service_config_json != NULL) { + grpc_service_config* service_config = nullptr; + char* service_config_string = nullptr; + if (r->service_config_json != nullptr) { service_config_string = choose_service_config(r->service_config_json); gpr_free(r->service_config_json); - if (service_config_string != NULL) { + if (service_config_string != nullptr) { gpr_log(GPR_INFO, "selected service config choice: %s", service_config_string); args_to_remove[num_args_to_remove++] = GRPC_ARG_SERVICE_CONFIG; new_args[num_args_to_add++] = grpc_channel_arg_string_create( - (char *)GRPC_ARG_SERVICE_CONFIG, service_config_string); + (char*)GRPC_ARG_SERVICE_CONFIG, service_config_string); service_config = grpc_service_config_create(service_config_string); - if (service_config != NULL) { - const char *lb_policy_name = + if (service_config != nullptr) { + const char* lb_policy_name = grpc_service_config_get_lb_policy_name(service_config); - if (lb_policy_name != NULL) { + if (lb_policy_name != nullptr) { args_to_remove[num_args_to_remove++] = GRPC_ARG_LB_POLICY_NAME; new_args[num_args_to_add++] = grpc_channel_arg_string_create( - (char *)GRPC_ARG_LB_POLICY_NAME, (char *)lb_policy_name); + (char*)GRPC_ARG_LB_POLICY_NAME, (char*)lb_policy_name); } } } @@ -265,13 +266,14 @@ static void dns_ares_on_resolved_locked(grpc_exec_ctx *exec_ctx, void *arg, result = grpc_channel_args_copy_and_add_and_remove( r->channel_args, args_to_remove, num_args_to_remove, new_args, num_args_to_add); - if (service_config != NULL) grpc_service_config_destroy(service_config); + if (service_config != nullptr) grpc_service_config_destroy(service_config); gpr_free(service_config_string); grpc_lb_addresses_destroy(exec_ctx, r->lb_addresses); } else { - const char *msg = grpc_error_string(error); + const char* msg = grpc_error_string(error); gpr_log(GPR_DEBUG, "dns resolution failed: %s", msg); - grpc_millis next_try = grpc_backoff_step(exec_ctx, &r->backoff_state); + grpc_millis next_try = + grpc_backoff_step(exec_ctx, &r->backoff_state).next_attempt_start_time; grpc_millis timeout = next_try - grpc_exec_ctx_now(exec_ctx); gpr_log(GPR_INFO, "dns resolution failed (will retry): %s", grpc_error_string(error)); @@ -286,7 +288,7 @@ static void dns_ares_on_resolved_locked(grpc_exec_ctx *exec_ctx, void *arg, grpc_timer_init(exec_ctx, &r->retry_timer, next_try, &r->dns_ares_on_retry_timer_locked); } - if (r->resolved_result != NULL) { + if (r->resolved_result != nullptr) { grpc_channel_args_destroy(exec_ctx, r->resolved_result); } r->resolved_result = result; @@ -295,12 +297,12 @@ static void dns_ares_on_resolved_locked(grpc_exec_ctx *exec_ctx, void *arg, GRPC_RESOLVER_UNREF(exec_ctx, &r->base, "dns-resolving"); } -static void dns_ares_next_locked(grpc_exec_ctx *exec_ctx, - grpc_resolver *resolver, - grpc_channel_args **target_result, - grpc_closure *on_complete) { +static void dns_ares_next_locked(grpc_exec_ctx* exec_ctx, + grpc_resolver* resolver, + grpc_channel_args** target_result, + grpc_closure* on_complete) { gpr_log(GPR_DEBUG, "dns_ares_next is called."); - ares_dns_resolver *r = (ares_dns_resolver *)resolver; + ares_dns_resolver* r = (ares_dns_resolver*)resolver; GPR_ASSERT(!r->next_completion); r->next_completion = on_complete; r->target_result = target_result; @@ -312,38 +314,38 @@ static void dns_ares_next_locked(grpc_exec_ctx *exec_ctx, } } -static void dns_ares_start_resolving_locked(grpc_exec_ctx *exec_ctx, - ares_dns_resolver *r) { +static void dns_ares_start_resolving_locked(grpc_exec_ctx* exec_ctx, + ares_dns_resolver* r) { GRPC_RESOLVER_REF(&r->base, "dns-resolving"); GPR_ASSERT(!r->resolving); r->resolving = true; - r->lb_addresses = NULL; - r->service_config_json = NULL; + r->lb_addresses = nullptr; + r->service_config_json = nullptr; r->pending_request = grpc_dns_lookup_ares( exec_ctx, r->dns_server, r->name_to_resolve, r->default_port, r->interested_parties, &r->dns_ares_on_resolved_locked, &r->lb_addresses, true /* check_grpclb */, - r->request_service_config ? &r->service_config_json : NULL); + r->request_service_config ? &r->service_config_json : nullptr); } -static void dns_ares_maybe_finish_next_locked(grpc_exec_ctx *exec_ctx, - ares_dns_resolver *r) { - if (r->next_completion != NULL && +static void dns_ares_maybe_finish_next_locked(grpc_exec_ctx* exec_ctx, + ares_dns_resolver* r) { + if (r->next_completion != nullptr && r->resolved_version != r->published_version) { - *r->target_result = r->resolved_result == NULL - ? NULL + *r->target_result = r->resolved_result == nullptr + ? nullptr : grpc_channel_args_copy(r->resolved_result); gpr_log(GPR_DEBUG, "dns_ares_maybe_finish_next_locked"); GRPC_CLOSURE_SCHED(exec_ctx, r->next_completion, GRPC_ERROR_NONE); - r->next_completion = NULL; + r->next_completion = nullptr; r->published_version = r->resolved_version; } } -static void dns_ares_destroy(grpc_exec_ctx *exec_ctx, grpc_resolver *gr) { +static void dns_ares_destroy(grpc_exec_ctx* exec_ctx, grpc_resolver* gr) { gpr_log(GPR_DEBUG, "dns_ares_destroy"); - ares_dns_resolver *r = (ares_dns_resolver *)gr; - if (r->resolved_result != NULL) { + ares_dns_resolver* r = (ares_dns_resolver*)gr; + if (r->resolved_result != nullptr) { grpc_channel_args_destroy(exec_ctx, r->resolved_result); } grpc_pollset_set_destroy(exec_ctx, r->interested_parties); @@ -354,15 +356,15 @@ static void dns_ares_destroy(grpc_exec_ctx *exec_ctx, grpc_resolver *gr) { gpr_free(r); } -static grpc_resolver *dns_ares_create(grpc_exec_ctx *exec_ctx, - grpc_resolver_args *args, - const char *default_port) { +static grpc_resolver* dns_ares_create(grpc_exec_ctx* exec_ctx, + grpc_resolver_args* args, + const char* default_port) { /* Get name from args. */ - const char *path = args->uri->path; + const char* path = args->uri->path; if (path[0] == '/') ++path; /* Create resolver. */ - ares_dns_resolver *r = - (ares_dns_resolver *)gpr_zalloc(sizeof(ares_dns_resolver)); + ares_dns_resolver* r = + (ares_dns_resolver*)gpr_zalloc(sizeof(ares_dns_resolver)); grpc_resolver_init(&r->base, &dns_ares_resolver_vtable, args->combiner); if (0 != strcmp(args->uri->authority, "")) { r->dns_server = gpr_strdup(args->uri->authority); @@ -370,20 +372,20 @@ static grpc_resolver *dns_ares_create(grpc_exec_ctx *exec_ctx, r->name_to_resolve = gpr_strdup(path); r->default_port = gpr_strdup(default_port); r->channel_args = grpc_channel_args_copy(args->args); - const grpc_arg *arg = grpc_channel_args_find( + const grpc_arg* arg = grpc_channel_args_find( r->channel_args, GRPC_ARG_SERVICE_CONFIG_DISABLE_RESOLUTION); r->request_service_config = !grpc_channel_arg_get_integer( arg, (grpc_integer_options){false, false, true}); r->interested_parties = grpc_pollset_set_create(); - if (args->pollset_set != NULL) { + if (args->pollset_set != nullptr) { grpc_pollset_set_add_pollset_set(exec_ctx, r->interested_parties, args->pollset_set); } - grpc_backoff_init(&r->backoff_state, GRPC_DNS_INITIAL_CONNECT_BACKOFF_SECONDS, - GRPC_DNS_RECONNECT_BACKOFF_MULTIPLIER, - GRPC_DNS_RECONNECT_JITTER, - GRPC_DNS_MIN_CONNECT_TIMEOUT_SECONDS * 1000, - GRPC_DNS_RECONNECT_MAX_BACKOFF_SECONDS * 1000); + grpc_backoff_init( + &r->backoff_state, GRPC_DNS_INITIAL_CONNECT_BACKOFF_SECONDS * 1000, + GRPC_DNS_RECONNECT_BACKOFF_MULTIPLIER, GRPC_DNS_RECONNECT_JITTER, + GRPC_DNS_MIN_CONNECT_TIMEOUT_SECONDS * 1000, + GRPC_DNS_RECONNECT_MAX_BACKOFF_SECONDS * 1000); GRPC_CLOSURE_INIT(&r->dns_ares_on_retry_timer_locked, dns_ares_on_retry_timer_locked, r, grpc_combiner_scheduler(r->base.combiner)); @@ -397,19 +399,19 @@ static grpc_resolver *dns_ares_create(grpc_exec_ctx *exec_ctx, * FACTORY */ -static void dns_ares_factory_ref(grpc_resolver_factory *factory) {} +static void dns_ares_factory_ref(grpc_resolver_factory* factory) {} -static void dns_ares_factory_unref(grpc_resolver_factory *factory) {} +static void dns_ares_factory_unref(grpc_resolver_factory* factory) {} -static grpc_resolver *dns_factory_create_resolver( - grpc_exec_ctx *exec_ctx, grpc_resolver_factory *factory, - grpc_resolver_args *args) { +static grpc_resolver* dns_factory_create_resolver( + grpc_exec_ctx* exec_ctx, grpc_resolver_factory* factory, + grpc_resolver_args* args) { return dns_ares_create(exec_ctx, args, "https"); } -static char *dns_ares_factory_get_default_host_name( - grpc_resolver_factory *factory, grpc_uri *uri) { - const char *path = uri->path; +static char* dns_ares_factory_get_default_host_name( + grpc_resolver_factory* factory, grpc_uri* uri) { + const char* path = uri->path; if (path[0] == '/') ++path; return gpr_strdup(path); } @@ -419,16 +421,16 @@ static const grpc_resolver_factory_vtable dns_ares_factory_vtable = { dns_ares_factory_get_default_host_name, "dns"}; static grpc_resolver_factory dns_resolver_factory = {&dns_ares_factory_vtable}; -static grpc_resolver_factory *dns_ares_resolver_factory_create() { +static grpc_resolver_factory* dns_ares_resolver_factory_create() { return &dns_resolver_factory; } -extern "C" void grpc_resolver_dns_ares_init(void) { - char *resolver = gpr_getenv("GRPC_DNS_RESOLVER"); +void grpc_resolver_dns_ares_init(void) { + char* resolver = gpr_getenv("GRPC_DNS_RESOLVER"); /* TODO(zyc): Turn on c-ares based resolver by default after the address sorter and the CNAME support are added. */ - if (resolver != NULL && gpr_stricmp(resolver, "ares") == 0) { - grpc_error *error = grpc_ares_init(); + if (resolver != nullptr && gpr_stricmp(resolver, "ares") == 0) { + grpc_error* error = grpc_ares_init(); if (error != GRPC_ERROR_NONE) { GRPC_LOG_IF_ERROR("ares_library_init() failed", error); return; @@ -439,9 +441,9 @@ extern "C" void grpc_resolver_dns_ares_init(void) { gpr_free(resolver); } -extern "C" void grpc_resolver_dns_ares_shutdown(void) { - char *resolver = gpr_getenv("GRPC_DNS_RESOLVER"); - if (resolver != NULL && gpr_stricmp(resolver, "ares") == 0) { +void grpc_resolver_dns_ares_shutdown(void) { + char* resolver = gpr_getenv("GRPC_DNS_RESOLVER"); + if (resolver != nullptr && gpr_stricmp(resolver, "ares") == 0) { grpc_ares_cleanup(); } gpr_free(resolver); @@ -449,8 +451,8 @@ extern "C" void grpc_resolver_dns_ares_shutdown(void) { #else /* GRPC_ARES == 1 && !defined(GRPC_UV) */ -extern "C" void grpc_resolver_dns_ares_init(void) {} +void grpc_resolver_dns_ares_init(void) {} -extern "C" void grpc_resolver_dns_ares_shutdown(void) {} +void grpc_resolver_dns_ares_shutdown(void) {} #endif /* GRPC_ARES == 1 && !defined(GRPC_UV) */ diff --git a/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h b/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h index 3d4309f2fa3..03ea36bfcc4 100644 --- a/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h +++ b/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h @@ -19,43 +19,36 @@ #ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_EV_DRIVER_H #define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_EV_DRIVER_H +#include #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/iomgr/pollset_set.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_ares_ev_driver grpc_ares_ev_driver; /* Start \a ev_driver. It will keep working until all IO on its ares_channel is done, or grpc_ares_ev_driver_destroy() is called. It may notify the callbacks bound to its ares_channel when necessary. */ -void grpc_ares_ev_driver_start(grpc_exec_ctx *exec_ctx, - grpc_ares_ev_driver *ev_driver); +void grpc_ares_ev_driver_start(grpc_exec_ctx* exec_ctx, + grpc_ares_ev_driver* ev_driver); /* Returns the ares_channel owned by \a ev_driver. To bind a c-ares query to \a ev_driver, use the ares_channel owned by \a ev_driver as the arg of the query. */ -ares_channel *grpc_ares_ev_driver_get_channel(grpc_ares_ev_driver *ev_driver); +ares_channel* grpc_ares_ev_driver_get_channel(grpc_ares_ev_driver* ev_driver); /* Creates a new grpc_ares_ev_driver. Returns GRPC_ERROR_NONE if \a ev_driver is created successfully. */ -grpc_error *grpc_ares_ev_driver_create(grpc_ares_ev_driver **ev_driver, - grpc_pollset_set *pollset_set); +grpc_error* grpc_ares_ev_driver_create(grpc_ares_ev_driver** ev_driver, + grpc_pollset_set* pollset_set); /* Destroys \a ev_driver asynchronously. Pending lookups made on \a ev_driver will be cancelled and their on_done callbacks will be invoked with a status of ARES_ECANCELLED. */ -void grpc_ares_ev_driver_destroy(grpc_ares_ev_driver *ev_driver); +void grpc_ares_ev_driver_destroy(grpc_ares_ev_driver* ev_driver); /* Shutdown all the grpc_fds used by \a ev_driver */ -void grpc_ares_ev_driver_shutdown(grpc_exec_ctx *exec_ctx, - grpc_ares_ev_driver *ev_driver); - -#ifdef __cplusplus -} -#endif +void grpc_ares_ev_driver_shutdown(grpc_exec_ctx* exec_ctx, + grpc_ares_ev_driver* ev_driver); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_EV_DRIVER_H \ - */ + */ diff --git a/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc b/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc index c30cc93b6ff..4cb068a41dd 100644 --- a/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc +++ b/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc @@ -37,7 +37,7 @@ typedef struct fd_node { /** the owner of this fd node */ - grpc_ares_ev_driver *ev_driver; + grpc_ares_ev_driver* ev_driver; /** a closure wrapping on_readable_cb, which should be invoked when the grpc_fd in this node becomes readable. */ grpc_closure read_closure; @@ -45,12 +45,12 @@ typedef struct fd_node { grpc_fd in this node becomes writable. */ grpc_closure write_closure; /** next fd node in the list */ - struct fd_node *next; + struct fd_node* next; /** mutex guarding the rest of the state */ gpr_mu mu; /** the grpc_fd owned by this fd node */ - grpc_fd *fd; + grpc_fd* fd; /** if the readable closure has been registered */ bool readable_registered; /** if the writable closure has been registered */ @@ -63,42 +63,42 @@ struct grpc_ares_ev_driver { /** the ares_channel owned by this event driver */ ares_channel channel; /** pollset set for driving the IO events of the channel */ - grpc_pollset_set *pollset_set; + grpc_pollset_set* pollset_set; /** refcount of the event driver */ gpr_refcount refs; /** mutex guarding the rest of the state */ gpr_mu mu; /** a list of grpc_fd that this event driver is currently using. */ - fd_node *fds; + fd_node* fds; /** is this event driver currently working? */ bool working; /** is this event driver being shut down */ bool shutting_down; }; -static void grpc_ares_notify_on_event_locked(grpc_exec_ctx *exec_ctx, - grpc_ares_ev_driver *ev_driver); +static void grpc_ares_notify_on_event_locked(grpc_exec_ctx* exec_ctx, + grpc_ares_ev_driver* ev_driver); -static grpc_ares_ev_driver *grpc_ares_ev_driver_ref( - grpc_ares_ev_driver *ev_driver) { +static grpc_ares_ev_driver* grpc_ares_ev_driver_ref( + grpc_ares_ev_driver* ev_driver) { gpr_log(GPR_DEBUG, "Ref ev_driver %" PRIuPTR, (uintptr_t)ev_driver); gpr_ref(&ev_driver->refs); return ev_driver; } -static void grpc_ares_ev_driver_unref(grpc_ares_ev_driver *ev_driver) { +static void grpc_ares_ev_driver_unref(grpc_ares_ev_driver* ev_driver) { gpr_log(GPR_DEBUG, "Unref ev_driver %" PRIuPTR, (uintptr_t)ev_driver); if (gpr_unref(&ev_driver->refs)) { gpr_log(GPR_DEBUG, "destroy ev_driver %" PRIuPTR, (uintptr_t)ev_driver); - GPR_ASSERT(ev_driver->fds == NULL); + GPR_ASSERT(ev_driver->fds == nullptr); gpr_mu_destroy(&ev_driver->mu); ares_destroy(ev_driver->channel); gpr_free(ev_driver); } } -static void fd_node_destroy(grpc_exec_ctx *exec_ctx, fd_node *fdn) { +static void fd_node_destroy(grpc_exec_ctx* exec_ctx, fd_node* fdn) { gpr_log(GPR_DEBUG, "delete fd: %d", grpc_fd_wrapped_fd(fdn->fd)); GPR_ASSERT(!fdn->readable_registered); GPR_ASSERT(!fdn->writable_registered); @@ -106,34 +106,35 @@ static void fd_node_destroy(grpc_exec_ctx *exec_ctx, fd_node *fdn) { /* c-ares library has closed the fd inside grpc_fd. This fd may be picked up immediately by another thread, and should not be closed by the following grpc_fd_orphan. */ - grpc_fd_orphan(exec_ctx, fdn->fd, NULL, NULL, true /* already_closed */, + grpc_fd_orphan(exec_ctx, fdn->fd, nullptr, nullptr, true /* already_closed */, "c-ares query finished"); gpr_free(fdn); } -static void fd_node_shutdown(grpc_exec_ctx *exec_ctx, fd_node *fdn) { +static void fd_node_shutdown(grpc_exec_ctx* exec_ctx, fd_node* fdn) { gpr_mu_lock(&fdn->mu); fdn->shutting_down = true; if (!fdn->readable_registered && !fdn->writable_registered) { gpr_mu_unlock(&fdn->mu); fd_node_destroy(exec_ctx, fdn); } else { - grpc_fd_shutdown(exec_ctx, fdn->fd, GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "c-ares fd shutdown")); + grpc_fd_shutdown( + exec_ctx, fdn->fd, + GRPC_ERROR_CREATE_FROM_STATIC_STRING("c-ares fd shutdown")); gpr_mu_unlock(&fdn->mu); } } -grpc_error *grpc_ares_ev_driver_create(grpc_ares_ev_driver **ev_driver, - grpc_pollset_set *pollset_set) { - *ev_driver = (grpc_ares_ev_driver *)gpr_malloc(sizeof(grpc_ares_ev_driver)); +grpc_error* grpc_ares_ev_driver_create(grpc_ares_ev_driver** ev_driver, + grpc_pollset_set* pollset_set) { + *ev_driver = (grpc_ares_ev_driver*)gpr_malloc(sizeof(grpc_ares_ev_driver)); int status = ares_init(&(*ev_driver)->channel); gpr_log(GPR_DEBUG, "grpc_ares_ev_driver_create"); if (status != ARES_SUCCESS) { - char *err_msg; + char* err_msg; gpr_asprintf(&err_msg, "Failed to init ares channel. C-ares error: %s", ares_strerror(status)); - grpc_error *err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(err_msg); + grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(err_msg); gpr_free(err_msg); gpr_free(*ev_driver); return err; @@ -141,13 +142,13 @@ grpc_error *grpc_ares_ev_driver_create(grpc_ares_ev_driver **ev_driver, gpr_mu_init(&(*ev_driver)->mu); gpr_ref_init(&(*ev_driver)->refs, 1); (*ev_driver)->pollset_set = pollset_set; - (*ev_driver)->fds = NULL; + (*ev_driver)->fds = nullptr; (*ev_driver)->working = false; (*ev_driver)->shutting_down = false; return GRPC_ERROR_NONE; } -void grpc_ares_ev_driver_destroy(grpc_ares_ev_driver *ev_driver) { +void grpc_ares_ev_driver_destroy(grpc_ares_ev_driver* ev_driver) { // It's not safe to shut down remaining fds here directly, becauses // ares_host_callback does not provide an exec_ctx. We mark the event driver // as being shut down. If the event driver is working, @@ -159,14 +160,15 @@ void grpc_ares_ev_driver_destroy(grpc_ares_ev_driver *ev_driver) { grpc_ares_ev_driver_unref(ev_driver); } -void grpc_ares_ev_driver_shutdown(grpc_exec_ctx *exec_ctx, - grpc_ares_ev_driver *ev_driver) { +void grpc_ares_ev_driver_shutdown(grpc_exec_ctx* exec_ctx, + grpc_ares_ev_driver* ev_driver) { gpr_mu_lock(&ev_driver->mu); ev_driver->shutting_down = true; - fd_node *fn = ev_driver->fds; - while (fn != NULL) { - grpc_fd_shutdown(exec_ctx, fn->fd, GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "grpc_ares_ev_driver_shutdown")); + fd_node* fn = ev_driver->fds; + while (fn != nullptr) { + grpc_fd_shutdown( + exec_ctx, fn->fd, + GRPC_ERROR_CREATE_FROM_STATIC_STRING("grpc_ares_ev_driver_shutdown")); fn = fn->next; } gpr_mu_unlock(&ev_driver->mu); @@ -174,33 +176,33 @@ void grpc_ares_ev_driver_shutdown(grpc_exec_ctx *exec_ctx, // Search fd in the fd_node list head. This is an O(n) search, the max possible // value of n is ARES_GETSOCK_MAXNUM (16). n is typically 1 - 2 in our tests. -static fd_node *pop_fd_node(fd_node **head, int fd) { +static fd_node* pop_fd_node(fd_node** head, int fd) { fd_node dummy_head; dummy_head.next = *head; - fd_node *node = &dummy_head; - while (node->next != NULL) { + fd_node* node = &dummy_head; + while (node->next != nullptr) { if (grpc_fd_wrapped_fd(node->next->fd) == fd) { - fd_node *ret = node->next; + fd_node* ret = node->next; node->next = node->next->next; *head = dummy_head.next; return ret; } node = node->next; } - return NULL; + return nullptr; } /* Check if \a fd is still readable */ -static bool grpc_ares_is_fd_still_readable(grpc_ares_ev_driver *ev_driver, +static bool grpc_ares_is_fd_still_readable(grpc_ares_ev_driver* ev_driver, int fd) { size_t bytes_available = 0; return ioctl(fd, FIONREAD, &bytes_available) == 0 && bytes_available > 0; } -static void on_readable_cb(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - fd_node *fdn = (fd_node *)arg; - grpc_ares_ev_driver *ev_driver = fdn->ev_driver; +static void on_readable_cb(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + fd_node* fdn = (fd_node*)arg; + grpc_ares_ev_driver* ev_driver = fdn->ev_driver; gpr_mu_lock(&fdn->mu); const int fd = grpc_fd_wrapped_fd(fdn->fd); fdn->readable_registered = false; @@ -232,10 +234,10 @@ static void on_readable_cb(grpc_exec_ctx *exec_ctx, void *arg, grpc_ares_ev_driver_unref(ev_driver); } -static void on_writable_cb(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - fd_node *fdn = (fd_node *)arg; - grpc_ares_ev_driver *ev_driver = fdn->ev_driver; +static void on_writable_cb(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + fd_node* fdn = (fd_node*)arg; + grpc_ares_ev_driver* ev_driver = fdn->ev_driver; gpr_mu_lock(&fdn->mu); const int fd = grpc_fd_wrapped_fd(fdn->fd); fdn->writable_registered = false; @@ -265,15 +267,15 @@ static void on_writable_cb(grpc_exec_ctx *exec_ctx, void *arg, grpc_ares_ev_driver_unref(ev_driver); } -ares_channel *grpc_ares_ev_driver_get_channel(grpc_ares_ev_driver *ev_driver) { +ares_channel* grpc_ares_ev_driver_get_channel(grpc_ares_ev_driver* ev_driver) { return &ev_driver->channel; } // Get the file descriptors used by the ev_driver's ares channel, register // driver_closure with these filedescriptors. -static void grpc_ares_notify_on_event_locked(grpc_exec_ctx *exec_ctx, - grpc_ares_ev_driver *ev_driver) { - fd_node *new_list = NULL; +static void grpc_ares_notify_on_event_locked(grpc_exec_ctx* exec_ctx, + grpc_ares_ev_driver* ev_driver) { + fd_node* new_list = nullptr; if (!ev_driver->shutting_down) { ares_socket_t socks[ARES_GETSOCK_MAXNUM]; int socks_bitmask = @@ -281,12 +283,12 @@ static void grpc_ares_notify_on_event_locked(grpc_exec_ctx *exec_ctx, for (size_t i = 0; i < ARES_GETSOCK_MAXNUM; i++) { if (ARES_GETSOCK_READABLE(socks_bitmask, i) || ARES_GETSOCK_WRITABLE(socks_bitmask, i)) { - fd_node *fdn = pop_fd_node(&ev_driver->fds, socks[i]); + fd_node* fdn = pop_fd_node(&ev_driver->fds, socks[i]); // Create a new fd_node if sock[i] is not in the fd_node list. - if (fdn == NULL) { - char *fd_name; + if (fdn == nullptr) { + char* fd_name; gpr_asprintf(&fd_name, "ares_ev_driver-%" PRIuPTR, i); - fdn = (fd_node *)gpr_malloc(sizeof(fd_node)); + fdn = (fd_node*)gpr_malloc(sizeof(fd_node)); gpr_log(GPR_DEBUG, "new fd: %d", socks[i]); fdn->fd = grpc_fd_create(socks[i], fd_name); fdn->ev_driver = ev_driver; @@ -330,21 +332,21 @@ static void grpc_ares_notify_on_event_locked(grpc_exec_ctx *exec_ctx, // Any remaining fds in ev_driver->fds were not returned by ares_getsock() and // are therefore no longer in use, so they can be shut down and removed from // the list. - while (ev_driver->fds != NULL) { - fd_node *cur = ev_driver->fds; + while (ev_driver->fds != nullptr) { + fd_node* cur = ev_driver->fds; ev_driver->fds = ev_driver->fds->next; fd_node_shutdown(exec_ctx, cur); } ev_driver->fds = new_list; // If the ev driver has no working fd, all the tasks are done. - if (new_list == NULL) { + if (new_list == nullptr) { ev_driver->working = false; gpr_log(GPR_DEBUG, "ev driver stop working"); } } -void grpc_ares_ev_driver_start(grpc_exec_ctx *exec_ctx, - grpc_ares_ev_driver *ev_driver) { +void grpc_ares_ev_driver_start(grpc_exec_ctx* exec_ctx, + grpc_ares_ev_driver* ev_driver) { gpr_mu_lock(&ev_driver->mu); if (!ev_driver->working) { ev_driver->working = true; diff --git a/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc b/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc index 04379975e1c..7846576c116 100644 --- a/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc +++ b/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc @@ -51,13 +51,13 @@ struct grpc_ares_request { struct ares_addr_port_node dns_server_addr; /** following members are set in grpc_resolve_address_ares_impl */ /** closure to call when the request completes */ - grpc_closure *on_done; + grpc_closure* on_done; /** the pointer to receive the resolved addresses */ - grpc_lb_addresses **lb_addrs_out; + grpc_lb_addresses** lb_addrs_out; /** the pointer to receive the service config in JSON */ - char **service_config_json_out; + char** service_config_json_out; /** the evernt driver used by this request */ - grpc_ares_ev_driver *ev_driver; + grpc_ares_ev_driver* ev_driver; /** number of ongoing queries */ gpr_refcount pending_queries; @@ -66,15 +66,15 @@ struct grpc_ares_request { /** is there at least one successful query, set in on_done_cb */ bool success; /** the errors explaining the request failure, set in on_done_cb */ - grpc_error *error; + grpc_error* error; }; typedef struct grpc_ares_hostbyname_request { /** following members are set in create_hostbyname_request */ /** the top-level request instance */ - grpc_ares_request *parent_request; + grpc_ares_request* parent_request; /** host to resolve, parsed from the name to resolve */ - char *host; + char* host; /** port to fill in sockaddr_in, parsed from the name to resolve */ uint16_t port; /** is it a grpclb address */ @@ -83,7 +83,7 @@ typedef struct grpc_ares_hostbyname_request { static void do_basic_init(void) { gpr_mu_init(&g_init_mu); } -static uint16_t strhtons(const char *port) { +static uint16_t strhtons(const char* port) { if (strcmp(port, "http") == 0) { return htons(80); } else if (strcmp(port, "https") == 0) { @@ -92,17 +92,17 @@ static uint16_t strhtons(const char *port) { return htons((unsigned short)atoi(port)); } -static void grpc_ares_request_ref(grpc_ares_request *r) { +static void grpc_ares_request_ref(grpc_ares_request* r) { gpr_ref(&r->pending_queries); } -static void grpc_ares_request_unref(grpc_exec_ctx *exec_ctx, - grpc_ares_request *r) { +static void grpc_ares_request_unref(grpc_exec_ctx* exec_ctx, + grpc_ares_request* r) { /* If there are no pending queries, invoke on_done callback and destroy the request */ if (gpr_unref(&r->pending_queries)) { /* TODO(zyc): Sort results with RFC6724 before invoking on_done. */ - if (exec_ctx == NULL) { + if (exec_ctx == nullptr) { /* A new exec_ctx is created here, as the c-ares interface does not provide one in ares_host_callback. It's safe to schedule on_done with the newly created exec_ctx, since the caller has been warned not to @@ -120,10 +120,10 @@ static void grpc_ares_request_unref(grpc_exec_ctx *exec_ctx, } } -static grpc_ares_hostbyname_request *create_hostbyname_request( - grpc_ares_request *parent_request, char *host, uint16_t port, +static grpc_ares_hostbyname_request* create_hostbyname_request( + grpc_ares_request* parent_request, char* host, uint16_t port, bool is_balancer) { - grpc_ares_hostbyname_request *hr = (grpc_ares_hostbyname_request *)gpr_zalloc( + grpc_ares_hostbyname_request* hr = (grpc_ares_hostbyname_request*)gpr_zalloc( sizeof(grpc_ares_hostbyname_request)); hr->parent_request = parent_request; hr->host = gpr_strdup(host); @@ -133,32 +133,32 @@ static grpc_ares_hostbyname_request *create_hostbyname_request( return hr; } -static void destroy_hostbyname_request(grpc_exec_ctx *exec_ctx, - grpc_ares_hostbyname_request *hr) { +static void destroy_hostbyname_request(grpc_exec_ctx* exec_ctx, + grpc_ares_hostbyname_request* hr) { grpc_ares_request_unref(exec_ctx, hr->parent_request); gpr_free(hr->host); gpr_free(hr); } -static void on_hostbyname_done_cb(void *arg, int status, int timeouts, - struct hostent *hostent) { - grpc_ares_hostbyname_request *hr = (grpc_ares_hostbyname_request *)arg; - grpc_ares_request *r = hr->parent_request; +static void on_hostbyname_done_cb(void* arg, int status, int timeouts, + struct hostent* hostent) { + grpc_ares_hostbyname_request* hr = (grpc_ares_hostbyname_request*)arg; + grpc_ares_request* r = hr->parent_request; gpr_mu_lock(&r->mu); if (status == ARES_SUCCESS) { GRPC_ERROR_UNREF(r->error); r->error = GRPC_ERROR_NONE; r->success = true; - grpc_lb_addresses **lb_addresses = r->lb_addrs_out; - if (*lb_addresses == NULL) { - *lb_addresses = grpc_lb_addresses_create(0, NULL); + grpc_lb_addresses** lb_addresses = r->lb_addrs_out; + if (*lb_addresses == nullptr) { + *lb_addresses = grpc_lb_addresses_create(0, nullptr); } size_t prev_naddr = (*lb_addresses)->num_addresses; size_t i; - for (i = 0; hostent->h_addr_list[i] != NULL; i++) { + for (i = 0; hostent->h_addr_list[i] != nullptr; i++) { } (*lb_addresses)->num_addresses += i; - (*lb_addresses)->addresses = (grpc_lb_address *)gpr_realloc( + (*lb_addresses)->addresses = (grpc_lb_address*)gpr_realloc( (*lb_addresses)->addresses, sizeof(grpc_lb_address) * (*lb_addresses)->num_addresses); for (i = prev_naddr; i < (*lb_addresses)->num_addresses; i++) { @@ -174,8 +174,8 @@ static void on_hostbyname_done_cb(void *arg, int status, int timeouts, grpc_lb_addresses_set_address( *lb_addresses, i, &addr, addr_len, hr->is_balancer /* is_balancer */, - hr->is_balancer ? hr->host : NULL /* balancer_name */, - NULL /* user_data */); + hr->is_balancer ? hr->host : nullptr /* balancer_name */, + nullptr /* user_data */); char output[INET6_ADDRSTRLEN]; ares_inet_ntop(AF_INET6, &addr.sin6_addr, output, INET6_ADDRSTRLEN); gpr_log(GPR_DEBUG, @@ -195,8 +195,8 @@ static void on_hostbyname_done_cb(void *arg, int status, int timeouts, grpc_lb_addresses_set_address( *lb_addresses, i, &addr, addr_len, hr->is_balancer /* is_balancer */, - hr->is_balancer ? hr->host : NULL /* balancer_name */, - NULL /* user_data */); + hr->is_balancer ? hr->host : nullptr /* balancer_name */, + nullptr /* user_data */); char output[INET_ADDRSTRLEN]; ares_inet_ntop(AF_INET, &addr.sin_addr, output, INET_ADDRSTRLEN); gpr_log(GPR_DEBUG, @@ -208,10 +208,10 @@ static void on_hostbyname_done_cb(void *arg, int status, int timeouts, } } } else if (!r->success) { - char *error_msg; + char* error_msg; gpr_asprintf(&error_msg, "C-ares status is not ARES_SUCCESS: %s", ares_strerror(status)); - grpc_error *error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg); + grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg); gpr_free(error_msg); if (r->error == GRPC_ERROR_NONE) { r->error = error; @@ -220,43 +220,43 @@ static void on_hostbyname_done_cb(void *arg, int status, int timeouts, } } gpr_mu_unlock(&r->mu); - destroy_hostbyname_request(NULL, hr); + destroy_hostbyname_request(nullptr, hr); } -static void on_srv_query_done_cb(void *arg, int status, int timeouts, - unsigned char *abuf, int alen) { - grpc_ares_request *r = (grpc_ares_request *)arg; +static void on_srv_query_done_cb(void* arg, int status, int timeouts, + unsigned char* abuf, int alen) { + grpc_ares_request* r = (grpc_ares_request*)arg; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; gpr_log(GPR_DEBUG, "on_query_srv_done_cb"); if (status == ARES_SUCCESS) { gpr_log(GPR_DEBUG, "on_query_srv_done_cb ARES_SUCCESS"); - struct ares_srv_reply *reply; + struct ares_srv_reply* reply; const int parse_status = ares_parse_srv_reply(abuf, alen, &reply); if (parse_status == ARES_SUCCESS) { - ares_channel *channel = grpc_ares_ev_driver_get_channel(r->ev_driver); - for (struct ares_srv_reply *srv_it = reply; srv_it != NULL; + ares_channel* channel = grpc_ares_ev_driver_get_channel(r->ev_driver); + for (struct ares_srv_reply* srv_it = reply; srv_it != nullptr; srv_it = srv_it->next) { if (grpc_ipv6_loopback_available()) { - grpc_ares_hostbyname_request *hr = create_hostbyname_request( + grpc_ares_hostbyname_request* hr = create_hostbyname_request( r, srv_it->host, htons(srv_it->port), true /* is_balancer */); ares_gethostbyname(*channel, hr->host, AF_INET6, on_hostbyname_done_cb, hr); } - grpc_ares_hostbyname_request *hr = create_hostbyname_request( + grpc_ares_hostbyname_request* hr = create_hostbyname_request( r, srv_it->host, htons(srv_it->port), true /* is_balancer */); ares_gethostbyname(*channel, hr->host, AF_INET, on_hostbyname_done_cb, hr); grpc_ares_ev_driver_start(&exec_ctx, r->ev_driver); } } - if (reply != NULL) { + if (reply != nullptr) { ares_free_data(reply); } } else if (!r->success) { - char *error_msg; + char* error_msg; gpr_asprintf(&error_msg, "C-ares status is not ARES_SUCCESS: %s", ares_strerror(status)); - grpc_error *error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg); + grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg); gpr_free(error_msg); if (r->error == GRPC_ERROR_NONE) { r->error = error; @@ -270,21 +270,21 @@ static void on_srv_query_done_cb(void *arg, int status, int timeouts, static const char g_service_config_attribute_prefix[] = "grpc_config="; -static void on_txt_done_cb(void *arg, int status, int timeouts, - unsigned char *buf, int len) { +static void on_txt_done_cb(void* arg, int status, int timeouts, + unsigned char* buf, int len) { gpr_log(GPR_DEBUG, "on_txt_done_cb"); - char *error_msg; - grpc_ares_request *r = (grpc_ares_request *)arg; + char* error_msg; + grpc_ares_request* r = (grpc_ares_request*)arg; const size_t prefix_len = sizeof(g_service_config_attribute_prefix) - 1; - struct ares_txt_ext *result = NULL; - struct ares_txt_ext *reply = NULL; - grpc_error *error = GRPC_ERROR_NONE; + struct ares_txt_ext* result = nullptr; + struct ares_txt_ext* reply = nullptr; + grpc_error* error = GRPC_ERROR_NONE; gpr_mu_lock(&r->mu); if (status != ARES_SUCCESS) goto fail; status = ares_parse_txt_reply_ext(buf, len, &reply); if (status != ARES_SUCCESS) goto fail; // Find service config in TXT record. - for (result = reply; result != NULL; result = result->next) { + for (result = reply; result != nullptr; result = result->next) { if (result->record_start && memcmp(result->txt, g_service_config_attribute_prefix, prefix_len) == 0) { @@ -292,14 +292,14 @@ static void on_txt_done_cb(void *arg, int status, int timeouts, } } // Found a service config record. - if (result != NULL) { + if (result != nullptr) { size_t service_config_len = result->length - prefix_len; - *r->service_config_json_out = (char *)gpr_malloc(service_config_len + 1); + *r->service_config_json_out = (char*)gpr_malloc(service_config_len + 1); memcpy(*r->service_config_json_out, result->txt + prefix_len, service_config_len); - for (result = result->next; result != NULL && !result->record_start; + for (result = result->next; result != nullptr && !result->record_start; result = result->next) { - *r->service_config_json_out = (char *)gpr_realloc( + *r->service_config_json_out = (char*)gpr_realloc( *r->service_config_json_out, service_config_len + result->length + 1); memcpy(*r->service_config_json_out + service_config_len, result->txt, result->length); @@ -323,18 +323,18 @@ fail: } done: gpr_mu_unlock(&r->mu); - grpc_ares_request_unref(NULL, r); + grpc_ares_request_unref(nullptr, r); } -static grpc_ares_request *grpc_dns_lookup_ares_impl( - grpc_exec_ctx *exec_ctx, const char *dns_server, const char *name, - const char *default_port, grpc_pollset_set *interested_parties, - grpc_closure *on_done, grpc_lb_addresses **addrs, bool check_grpclb, - char **service_config_json) { - grpc_error *error = GRPC_ERROR_NONE; - grpc_ares_hostbyname_request *hr = NULL; - grpc_ares_request *r = NULL; - ares_channel *channel = NULL; +static grpc_ares_request* grpc_dns_lookup_ares_impl( + grpc_exec_ctx* exec_ctx, const char* dns_server, const char* name, + const char* default_port, grpc_pollset_set* interested_parties, + grpc_closure* on_done, grpc_lb_addresses** addrs, bool check_grpclb, + char** service_config_json) { + grpc_error* error = GRPC_ERROR_NONE; + grpc_ares_hostbyname_request* hr = nullptr; + grpc_ares_request* r = nullptr; + ares_channel* channel = nullptr; /* TODO(zyc): Enable tracing after #9603 is checked in */ /* if (grpc_dns_trace) { gpr_log(GPR_DEBUG, "resolve_address (blocking): name=%s, default_port=%s", @@ -342,16 +342,16 @@ static grpc_ares_request *grpc_dns_lookup_ares_impl( } */ /* parse name, splitting it into host and port parts */ - char *host; - char *port; + char* host; + char* port; gpr_split_host_port(name, &host, &port); - if (host == NULL) { + if (host == nullptr) { error = grpc_error_set_str( GRPC_ERROR_CREATE_FROM_STATIC_STRING("unparseable host:port"), GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(name)); goto error_cleanup; - } else if (port == NULL) { - if (default_port == NULL) { + } else if (port == nullptr) { + if (default_port == nullptr) { error = grpc_error_set_str( GRPC_ERROR_CREATE_FROM_STATIC_STRING("no port in name"), GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(name)); @@ -360,11 +360,11 @@ static grpc_ares_request *grpc_dns_lookup_ares_impl( port = gpr_strdup(default_port); } - grpc_ares_ev_driver *ev_driver; + grpc_ares_ev_driver* ev_driver; error = grpc_ares_ev_driver_create(&ev_driver, interested_parties); if (error != GRPC_ERROR_NONE) goto error_cleanup; - r = (grpc_ares_request *)gpr_zalloc(sizeof(grpc_ares_request)); + r = (grpc_ares_request*)gpr_zalloc(sizeof(grpc_ares_request)); gpr_mu_init(&r->mu); r->ev_driver = ev_driver; r->on_done = on_done; @@ -375,12 +375,12 @@ static grpc_ares_request *grpc_dns_lookup_ares_impl( channel = grpc_ares_ev_driver_get_channel(r->ev_driver); // If dns_server is specified, use it. - if (dns_server != NULL) { + if (dns_server != nullptr) { gpr_log(GPR_INFO, "Using DNS server %s", dns_server); grpc_resolved_address addr; if (grpc_parse_ipv4_hostport(dns_server, &addr, false /* log_errors */)) { r->dns_server_addr.family = AF_INET; - struct sockaddr_in *in = (struct sockaddr_in *)addr.addr; + struct sockaddr_in* in = (struct sockaddr_in*)addr.addr; memcpy(&r->dns_server_addr.addr.addr4, &in->sin_addr, sizeof(struct in_addr)); r->dns_server_addr.tcp_port = grpc_sockaddr_get_port(&addr); @@ -388,7 +388,7 @@ static grpc_ares_request *grpc_dns_lookup_ares_impl( } else if (grpc_parse_ipv6_hostport(dns_server, &addr, false /* log_errors */)) { r->dns_server_addr.family = AF_INET6; - struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)addr.addr; + struct sockaddr_in6* in6 = (struct sockaddr_in6*)addr.addr; memcpy(&r->dns_server_addr.addr.addr6, &in6->sin6_addr, sizeof(struct in6_addr)); r->dns_server_addr.tcp_port = grpc_sockaddr_get_port(&addr); @@ -402,7 +402,7 @@ static grpc_ares_request *grpc_dns_lookup_ares_impl( } int status = ares_set_servers_ports(*channel, &r->dns_server_addr); if (status != ARES_SUCCESS) { - char *error_msg; + char* error_msg; gpr_asprintf(&error_msg, "C-ares status is not ARES_SUCCESS: %s", ares_strerror(status)); error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg); @@ -423,15 +423,18 @@ static grpc_ares_request *grpc_dns_lookup_ares_impl( if (check_grpclb) { /* Query the SRV record */ grpc_ares_request_ref(r); - char *service_name; + char* service_name; gpr_asprintf(&service_name, "_grpclb._tcp.%s", host); ares_query(*channel, service_name, ns_c_in, ns_t_srv, on_srv_query_done_cb, r); gpr_free(service_name); } - if (service_config_json != NULL) { + if (service_config_json != nullptr) { grpc_ares_request_ref(r); - ares_search(*channel, hr->host, ns_c_in, ns_t_txt, on_txt_done_cb, r); + char* config_name; + gpr_asprintf(&config_name, "_grpc_config.%s", host); + ares_search(*channel, config_name, ns_c_in, ns_t_txt, on_txt_done_cb, r); + gpr_free(config_name); } /* TODO(zyc): Handle CNAME records here. */ grpc_ares_ev_driver_start(exec_ctx, r->ev_driver); @@ -444,32 +447,32 @@ error_cleanup: GRPC_CLOSURE_SCHED(exec_ctx, on_done, error); gpr_free(host); gpr_free(port); - return NULL; + return nullptr; } -grpc_ares_request *(*grpc_dns_lookup_ares)( - grpc_exec_ctx *exec_ctx, const char *dns_server, const char *name, - const char *default_port, grpc_pollset_set *interested_parties, - grpc_closure *on_done, grpc_lb_addresses **addrs, bool check_grpclb, - char **service_config_json) = grpc_dns_lookup_ares_impl; +grpc_ares_request* (*grpc_dns_lookup_ares)( + grpc_exec_ctx* exec_ctx, const char* dns_server, const char* name, + const char* default_port, grpc_pollset_set* interested_parties, + grpc_closure* on_done, grpc_lb_addresses** addrs, bool check_grpclb, + char** service_config_json) = grpc_dns_lookup_ares_impl; -void grpc_cancel_ares_request(grpc_exec_ctx *exec_ctx, grpc_ares_request *r) { +void grpc_cancel_ares_request(grpc_exec_ctx* exec_ctx, grpc_ares_request* r) { if (grpc_dns_lookup_ares == grpc_dns_lookup_ares_impl) { grpc_ares_ev_driver_shutdown(exec_ctx, r->ev_driver); } } -grpc_error *grpc_ares_init(void) { +grpc_error* grpc_ares_init(void) { gpr_once_init(&g_basic_init, do_basic_init); gpr_mu_lock(&g_init_mu); int status = ares_library_init(ARES_LIB_INIT_ALL); gpr_mu_unlock(&g_init_mu); if (status != ARES_SUCCESS) { - char *error_msg; + char* error_msg; gpr_asprintf(&error_msg, "ares_library_init failed: %s", ares_strerror(status)); - grpc_error *error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg); + grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg); gpr_free(error_msg); return error; } @@ -488,28 +491,28 @@ void grpc_ares_cleanup(void) { typedef struct grpc_resolve_address_ares_request { /** the pointer to receive the resolved addresses */ - grpc_resolved_addresses **addrs_out; + grpc_resolved_addresses** addrs_out; /** currently resolving lb addresses */ - grpc_lb_addresses *lb_addrs; + grpc_lb_addresses* lb_addrs; /** closure to call when the resolve_address_ares request completes */ - grpc_closure *on_resolve_address_done; + grpc_closure* on_resolve_address_done; /** a closure wrapping on_dns_lookup_done_cb, which should be invoked when the grpc_dns_lookup_ares operation is done. */ grpc_closure on_dns_lookup_done; } grpc_resolve_address_ares_request; -static void on_dns_lookup_done_cb(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_resolve_address_ares_request *r = - (grpc_resolve_address_ares_request *)arg; - grpc_resolved_addresses **resolved_addresses = r->addrs_out; - if (r->lb_addrs == NULL || r->lb_addrs->num_addresses == 0) { - *resolved_addresses = NULL; +static void on_dns_lookup_done_cb(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_resolve_address_ares_request* r = + (grpc_resolve_address_ares_request*)arg; + grpc_resolved_addresses** resolved_addresses = r->addrs_out; + if (r->lb_addrs == nullptr || r->lb_addrs->num_addresses == 0) { + *resolved_addresses = nullptr; } else { *resolved_addresses = - (grpc_resolved_addresses *)gpr_zalloc(sizeof(grpc_resolved_addresses)); + (grpc_resolved_addresses*)gpr_zalloc(sizeof(grpc_resolved_addresses)); (*resolved_addresses)->naddrs = r->lb_addrs->num_addresses; - (*resolved_addresses)->addrs = (grpc_resolved_address *)gpr_zalloc( + (*resolved_addresses)->addrs = (grpc_resolved_address*)gpr_zalloc( sizeof(grpc_resolved_address) * (*resolved_addresses)->naddrs); for (size_t i = 0; i < (*resolved_addresses)->naddrs; i++) { GPR_ASSERT(!r->lb_addrs->addresses[i].is_balancer); @@ -523,28 +526,28 @@ static void on_dns_lookup_done_cb(grpc_exec_ctx *exec_ctx, void *arg, gpr_free(r); } -static void grpc_resolve_address_ares_impl(grpc_exec_ctx *exec_ctx, - const char *name, - const char *default_port, - grpc_pollset_set *interested_parties, - grpc_closure *on_done, - grpc_resolved_addresses **addrs) { - grpc_resolve_address_ares_request *r = - (grpc_resolve_address_ares_request *)gpr_zalloc( +static void grpc_resolve_address_ares_impl(grpc_exec_ctx* exec_ctx, + const char* name, + const char* default_port, + grpc_pollset_set* interested_parties, + grpc_closure* on_done, + grpc_resolved_addresses** addrs) { + grpc_resolve_address_ares_request* r = + (grpc_resolve_address_ares_request*)gpr_zalloc( sizeof(grpc_resolve_address_ares_request)); r->addrs_out = addrs; r->on_resolve_address_done = on_done; GRPC_CLOSURE_INIT(&r->on_dns_lookup_done, on_dns_lookup_done_cb, r, grpc_schedule_on_exec_ctx); - grpc_dns_lookup_ares(exec_ctx, NULL /* dns_server */, name, default_port, + grpc_dns_lookup_ares(exec_ctx, nullptr /* dns_server */, name, default_port, interested_parties, &r->on_dns_lookup_done, &r->lb_addrs, false /* check_grpclb */, - NULL /* service_config_json */); + nullptr /* service_config_json */); } void (*grpc_resolve_address_ares)( - grpc_exec_ctx *exec_ctx, const char *name, const char *default_port, - grpc_pollset_set *interested_parties, grpc_closure *on_done, - grpc_resolved_addresses **addrs) = grpc_resolve_address_ares_impl; + grpc_exec_ctx* exec_ctx, const char* name, const char* default_port, + 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) */ diff --git a/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h b/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h index 38fbea9aac8..72db6229544 100644 --- a/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h +++ b/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h @@ -25,10 +25,6 @@ #include "src/core/lib/iomgr/polling_entity.h" #include "src/core/lib/iomgr/resolve_address.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_ares_request grpc_ares_request; /* Asynchronously resolve \a name. Use \a default_port if a port isn't @@ -36,12 +32,12 @@ typedef struct grpc_ares_request grpc_ares_request; must be called at least once before this function. \a on_done may be called directly in this function without being scheduled with \a exec_ctx, so it must not try to acquire locks that are being held by the caller. */ -extern void (*grpc_resolve_address_ares)(grpc_exec_ctx *exec_ctx, - const char *name, - const char *default_port, - grpc_pollset_set *interested_parties, - grpc_closure *on_done, - grpc_resolved_addresses **addresses); +extern void (*grpc_resolve_address_ares)(grpc_exec_ctx* exec_ctx, + const char* name, + const char* default_port, + grpc_pollset_set* interested_parties, + grpc_closure* on_done, + grpc_resolved_addresses** addresses); /* Asynchronously resolve \a name. It will try to resolve grpclb SRV records in addition to the normal address records. For normal address records, it uses @@ -50,28 +46,24 @@ extern void (*grpc_resolve_address_ares)(grpc_exec_ctx *exec_ctx, function. \a on_done may be called directly in this function without being scheduled with \a exec_ctx, so it must not try to acquire locks that are being held by the caller. */ -extern grpc_ares_request *(*grpc_dns_lookup_ares)( - grpc_exec_ctx *exec_ctx, const char *dns_server, const char *name, - const char *default_port, grpc_pollset_set *interested_parties, - grpc_closure *on_done, grpc_lb_addresses **addresses, bool check_grpclb, - char **service_config_json); +extern grpc_ares_request* (*grpc_dns_lookup_ares)( + grpc_exec_ctx* exec_ctx, const char* dns_server, const char* name, + const char* default_port, grpc_pollset_set* interested_parties, + grpc_closure* on_done, grpc_lb_addresses** addresses, bool check_grpclb, + char** service_config_json); /* Cancel the pending grpc_ares_request \a request */ -void grpc_cancel_ares_request(grpc_exec_ctx *exec_ctx, - grpc_ares_request *request); +void grpc_cancel_ares_request(grpc_exec_ctx* exec_ctx, + grpc_ares_request* request); /* Initialize gRPC ares wrapper. Must be called at least once before grpc_resolve_address_ares(). */ -grpc_error *grpc_ares_init(void); +grpc_error* grpc_ares_init(void); /* Uninitialized gRPC ares wrapper. If there was more than one previous call to grpc_ares_init(), this function uninitializes the gRPC ares wrapper only if it has been called the same number of times as grpc_ares_init(). */ void grpc_ares_cleanup(void); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_WRAPPER_H \ - */ + */ diff --git a/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc b/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc index f2587c4520f..a68a7c47fb6 100644 --- a/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc +++ b/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc @@ -25,36 +25,36 @@ struct grpc_ares_request { char val; }; -static grpc_ares_request *grpc_dns_lookup_ares_impl( - grpc_exec_ctx *exec_ctx, const char *dns_server, const char *name, - const char *default_port, grpc_pollset_set *interested_parties, - grpc_closure *on_done, grpc_lb_addresses **addrs, bool check_grpclb, - char **service_config_json) { +static grpc_ares_request* grpc_dns_lookup_ares_impl( + grpc_exec_ctx* exec_ctx, const char* dns_server, const char* name, + const char* default_port, grpc_pollset_set* interested_parties, + grpc_closure* on_done, grpc_lb_addresses** addrs, bool check_grpclb, + char** service_config_json) { return NULL; } -grpc_ares_request *(*grpc_dns_lookup_ares)( - grpc_exec_ctx *exec_ctx, const char *dns_server, const char *name, - const char *default_port, grpc_pollset_set *interested_parties, - grpc_closure *on_done, grpc_lb_addresses **addrs, bool check_grpclb, - char **service_config_json) = grpc_dns_lookup_ares_impl; +grpc_ares_request* (*grpc_dns_lookup_ares)( + grpc_exec_ctx* exec_ctx, const char* dns_server, const char* name, + const char* default_port, grpc_pollset_set* interested_parties, + grpc_closure* on_done, grpc_lb_addresses** addrs, bool check_grpclb, + char** service_config_json) = grpc_dns_lookup_ares_impl; -void grpc_cancel_ares_request(grpc_exec_ctx *exec_ctx, grpc_ares_request *r) {} +void grpc_cancel_ares_request(grpc_exec_ctx* exec_ctx, grpc_ares_request* r) {} -grpc_error *grpc_ares_init(void) { return GRPC_ERROR_NONE; } +grpc_error* grpc_ares_init(void) { return GRPC_ERROR_NONE; } void grpc_ares_cleanup(void) {} -static void grpc_resolve_address_ares_impl(grpc_exec_ctx *exec_ctx, - const char *name, - const char *default_port, - grpc_pollset_set *interested_parties, - grpc_closure *on_done, - grpc_resolved_addresses **addrs) {} +static void grpc_resolve_address_ares_impl(grpc_exec_ctx* exec_ctx, + const char* name, + const char* default_port, + grpc_pollset_set* interested_parties, + grpc_closure* on_done, + grpc_resolved_addresses** addrs) {} void (*grpc_resolve_address_ares)( - grpc_exec_ctx *exec_ctx, const char *name, const char *default_port, - grpc_pollset_set *interested_parties, grpc_closure *on_done, - grpc_resolved_addresses **addrs) = grpc_resolve_address_ares_impl; + grpc_exec_ctx* exec_ctx, const char* name, const char* default_port, + 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) */ diff --git a/src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc b/src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc index e669b6dfc7d..fc40ce69668 100644 --- a/src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc +++ b/src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc @@ -45,13 +45,13 @@ typedef struct { /** base class: must be first */ grpc_resolver base; /** name to resolve */ - char *name_to_resolve; + char* name_to_resolve; /** default port to use */ - char *default_port; + char* default_port; /** channel args. */ - grpc_channel_args *channel_args; + grpc_channel_args* channel_args; /** pollset_set to drive the name resolution process */ - grpc_pollset_set *interested_parties; + grpc_pollset_set* interested_parties; /** are we currently resolving? */ bool resolving; @@ -60,11 +60,11 @@ typedef struct { /** which version of the result is current? */ int resolved_version; /** pending next completion, or NULL */ - grpc_closure *next_completion; + grpc_closure* next_completion; /** target result address for next completion */ - grpc_channel_args **target_result; + grpc_channel_args** target_result; /** current (fully resolved) result */ - grpc_channel_args *resolved_result; + grpc_channel_args* resolved_result; /** retry timer */ bool have_retry_timer; grpc_timer retry_timer; @@ -73,55 +73,55 @@ typedef struct { grpc_backoff backoff_state; /** currently resolving addresses */ - grpc_resolved_addresses *addresses; + grpc_resolved_addresses* addresses; } dns_resolver; -static void dns_destroy(grpc_exec_ctx *exec_ctx, grpc_resolver *r); +static void dns_destroy(grpc_exec_ctx* exec_ctx, grpc_resolver* r); -static void dns_start_resolving_locked(grpc_exec_ctx *exec_ctx, - dns_resolver *r); -static void dns_maybe_finish_next_locked(grpc_exec_ctx *exec_ctx, - dns_resolver *r); +static void dns_start_resolving_locked(grpc_exec_ctx* exec_ctx, + dns_resolver* r); +static void dns_maybe_finish_next_locked(grpc_exec_ctx* exec_ctx, + dns_resolver* r); -static void dns_shutdown_locked(grpc_exec_ctx *exec_ctx, grpc_resolver *r); -static void dns_channel_saw_error_locked(grpc_exec_ctx *exec_ctx, - grpc_resolver *r); -static void dns_next_locked(grpc_exec_ctx *exec_ctx, grpc_resolver *r, - grpc_channel_args **target_result, - grpc_closure *on_complete); +static void dns_shutdown_locked(grpc_exec_ctx* exec_ctx, grpc_resolver* r); +static void dns_channel_saw_error_locked(grpc_exec_ctx* exec_ctx, + grpc_resolver* r); +static void dns_next_locked(grpc_exec_ctx* exec_ctx, grpc_resolver* r, + grpc_channel_args** target_result, + grpc_closure* on_complete); static const grpc_resolver_vtable dns_resolver_vtable = { dns_destroy, dns_shutdown_locked, dns_channel_saw_error_locked, dns_next_locked}; -static void dns_shutdown_locked(grpc_exec_ctx *exec_ctx, - grpc_resolver *resolver) { - dns_resolver *r = (dns_resolver *)resolver; +static void dns_shutdown_locked(grpc_exec_ctx* exec_ctx, + grpc_resolver* resolver) { + dns_resolver* r = (dns_resolver*)resolver; if (r->have_retry_timer) { grpc_timer_cancel(exec_ctx, &r->retry_timer); } - if (r->next_completion != NULL) { - *r->target_result = NULL; + if (r->next_completion != nullptr) { + *r->target_result = nullptr; GRPC_CLOSURE_SCHED( exec_ctx, r->next_completion, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Resolver Shutdown")); - r->next_completion = NULL; + r->next_completion = nullptr; } } -static void dns_channel_saw_error_locked(grpc_exec_ctx *exec_ctx, - grpc_resolver *resolver) { - dns_resolver *r = (dns_resolver *)resolver; +static void dns_channel_saw_error_locked(grpc_exec_ctx* exec_ctx, + grpc_resolver* resolver) { + dns_resolver* r = (dns_resolver*)resolver; if (!r->resolving) { grpc_backoff_reset(&r->backoff_state); dns_start_resolving_locked(exec_ctx, r); } } -static void dns_next_locked(grpc_exec_ctx *exec_ctx, grpc_resolver *resolver, - grpc_channel_args **target_result, - grpc_closure *on_complete) { - dns_resolver *r = (dns_resolver *)resolver; +static void dns_next_locked(grpc_exec_ctx* exec_ctx, grpc_resolver* resolver, + grpc_channel_args** target_result, + grpc_closure* on_complete) { + dns_resolver* r = (dns_resolver*)resolver; GPR_ASSERT(!r->next_completion); r->next_completion = on_complete; r->target_result = target_result; @@ -133,9 +133,9 @@ static void dns_next_locked(grpc_exec_ctx *exec_ctx, grpc_resolver *resolver, } } -static void dns_on_retry_timer_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - dns_resolver *r = (dns_resolver *)arg; +static void dns_on_retry_timer_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + dns_resolver* r = (dns_resolver*)arg; r->have_retry_timer = false; if (error == GRPC_ERROR_NONE) { @@ -147,30 +147,31 @@ static void dns_on_retry_timer_locked(grpc_exec_ctx *exec_ctx, void *arg, GRPC_RESOLVER_UNREF(exec_ctx, &r->base, "retry-timer"); } -static void dns_on_resolved_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - dns_resolver *r = (dns_resolver *)arg; - grpc_channel_args *result = NULL; +static void dns_on_resolved_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + dns_resolver* r = (dns_resolver*)arg; + grpc_channel_args* result = nullptr; GPR_ASSERT(r->resolving); r->resolving = false; GRPC_ERROR_REF(error); error = grpc_error_set_str(error, GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(r->name_to_resolve)); - if (r->addresses != NULL) { - grpc_lb_addresses *addresses = grpc_lb_addresses_create( - r->addresses->naddrs, NULL /* user_data_vtable */); + if (r->addresses != nullptr) { + grpc_lb_addresses* addresses = grpc_lb_addresses_create( + r->addresses->naddrs, nullptr /* user_data_vtable */); for (size_t i = 0; i < r->addresses->naddrs; ++i) { grpc_lb_addresses_set_address( addresses, i, &r->addresses->addrs[i].addr, r->addresses->addrs[i].len, false /* is_balancer */, - NULL /* balancer_name */, NULL /* user_data */); + nullptr /* balancer_name */, nullptr /* user_data */); } grpc_arg new_arg = grpc_lb_addresses_create_channel_arg(addresses); result = grpc_channel_args_copy_and_add(r->channel_args, &new_arg, 1); grpc_resolved_addresses_destroy(r->addresses); grpc_lb_addresses_destroy(exec_ctx, addresses); } else { - grpc_millis next_try = grpc_backoff_step(exec_ctx, &r->backoff_state); + grpc_millis next_try = + grpc_backoff_step(exec_ctx, &r->backoff_state).next_attempt_start_time; grpc_millis timeout = next_try - grpc_exec_ctx_now(exec_ctx); gpr_log(GPR_INFO, "dns resolution failed (will retry): %s", grpc_error_string(error)); @@ -186,7 +187,7 @@ static void dns_on_resolved_locked(grpc_exec_ctx *exec_ctx, void *arg, grpc_combiner_scheduler(r->base.combiner)); grpc_timer_init(exec_ctx, &r->retry_timer, next_try, &r->on_retry); } - if (r->resolved_result != NULL) { + if (r->resolved_result != nullptr) { grpc_channel_args_destroy(exec_ctx, r->resolved_result); } r->resolved_result = result; @@ -197,12 +198,12 @@ static void dns_on_resolved_locked(grpc_exec_ctx *exec_ctx, void *arg, GRPC_RESOLVER_UNREF(exec_ctx, &r->base, "dns-resolving"); } -static void dns_start_resolving_locked(grpc_exec_ctx *exec_ctx, - dns_resolver *r) { +static void dns_start_resolving_locked(grpc_exec_ctx* exec_ctx, + dns_resolver* r) { GRPC_RESOLVER_REF(&r->base, "dns-resolving"); GPR_ASSERT(!r->resolving); r->resolving = true; - r->addresses = NULL; + r->addresses = nullptr; grpc_resolve_address( exec_ctx, r->name_to_resolve, r->default_port, r->interested_parties, GRPC_CLOSURE_CREATE(dns_on_resolved_locked, r, @@ -210,22 +211,22 @@ static void dns_start_resolving_locked(grpc_exec_ctx *exec_ctx, &r->addresses); } -static void dns_maybe_finish_next_locked(grpc_exec_ctx *exec_ctx, - dns_resolver *r) { - if (r->next_completion != NULL && +static void dns_maybe_finish_next_locked(grpc_exec_ctx* exec_ctx, + dns_resolver* r) { + if (r->next_completion != nullptr && r->resolved_version != r->published_version) { - *r->target_result = r->resolved_result == NULL - ? NULL + *r->target_result = r->resolved_result == nullptr + ? nullptr : grpc_channel_args_copy(r->resolved_result); GRPC_CLOSURE_SCHED(exec_ctx, r->next_completion, GRPC_ERROR_NONE); - r->next_completion = NULL; + r->next_completion = nullptr; r->published_version = r->resolved_version; } } -static void dns_destroy(grpc_exec_ctx *exec_ctx, grpc_resolver *gr) { - dns_resolver *r = (dns_resolver *)gr; - if (r->resolved_result != NULL) { +static void dns_destroy(grpc_exec_ctx* exec_ctx, grpc_resolver* gr) { + dns_resolver* r = (dns_resolver*)gr; + if (r->resolved_result != nullptr) { grpc_channel_args_destroy(exec_ctx, r->resolved_result); } grpc_pollset_set_destroy(exec_ctx, r->interested_parties); @@ -235,32 +236,32 @@ static void dns_destroy(grpc_exec_ctx *exec_ctx, grpc_resolver *gr) { gpr_free(r); } -static grpc_resolver *dns_create(grpc_exec_ctx *exec_ctx, - grpc_resolver_args *args, - const char *default_port) { +static grpc_resolver* dns_create(grpc_exec_ctx* exec_ctx, + grpc_resolver_args* args, + const char* default_port) { if (0 != strcmp(args->uri->authority, "")) { gpr_log(GPR_ERROR, "authority based dns uri's not supported"); - return NULL; + return nullptr; } // Get name from args. - char *path = args->uri->path; + char* path = args->uri->path; if (path[0] == '/') ++path; // Create resolver. - dns_resolver *r = (dns_resolver *)gpr_zalloc(sizeof(dns_resolver)); + dns_resolver* r = (dns_resolver*)gpr_zalloc(sizeof(dns_resolver)); grpc_resolver_init(&r->base, &dns_resolver_vtable, args->combiner); r->name_to_resolve = gpr_strdup(path); r->default_port = gpr_strdup(default_port); r->channel_args = grpc_channel_args_copy(args->args); r->interested_parties = grpc_pollset_set_create(); - if (args->pollset_set != NULL) { + if (args->pollset_set != nullptr) { grpc_pollset_set_add_pollset_set(exec_ctx, r->interested_parties, args->pollset_set); } - grpc_backoff_init(&r->backoff_state, GRPC_DNS_INITIAL_CONNECT_BACKOFF_SECONDS, - GRPC_DNS_RECONNECT_BACKOFF_MULTIPLIER, - GRPC_DNS_RECONNECT_JITTER, - GRPC_DNS_MIN_CONNECT_TIMEOUT_SECONDS * 1000, - GRPC_DNS_RECONNECT_MAX_BACKOFF_SECONDS * 1000); + grpc_backoff_init( + &r->backoff_state, GRPC_DNS_INITIAL_CONNECT_BACKOFF_SECONDS * 1000, + GRPC_DNS_RECONNECT_BACKOFF_MULTIPLIER, GRPC_DNS_RECONNECT_JITTER, + GRPC_DNS_MIN_CONNECT_TIMEOUT_SECONDS * 1000, + GRPC_DNS_RECONNECT_MAX_BACKOFF_SECONDS * 1000); return &r->base; } @@ -268,19 +269,19 @@ static grpc_resolver *dns_create(grpc_exec_ctx *exec_ctx, * FACTORY */ -static void dns_factory_ref(grpc_resolver_factory *factory) {} +static void dns_factory_ref(grpc_resolver_factory* factory) {} -static void dns_factory_unref(grpc_resolver_factory *factory) {} +static void dns_factory_unref(grpc_resolver_factory* factory) {} -static grpc_resolver *dns_factory_create_resolver( - grpc_exec_ctx *exec_ctx, grpc_resolver_factory *factory, - grpc_resolver_args *args) { +static grpc_resolver* dns_factory_create_resolver( + grpc_exec_ctx* exec_ctx, grpc_resolver_factory* factory, + grpc_resolver_args* args) { return dns_create(exec_ctx, args, "https"); } -static char *dns_factory_get_default_host_name(grpc_resolver_factory *factory, - grpc_uri *uri) { - const char *path = uri->path; +static char* dns_factory_get_default_host_name(grpc_resolver_factory* factory, + grpc_uri* uri) { + const char* path = uri->path; if (path[0] == '/') ++path; return gpr_strdup(path); } @@ -290,19 +291,19 @@ static const grpc_resolver_factory_vtable dns_factory_vtable = { dns_factory_get_default_host_name, "dns"}; static grpc_resolver_factory dns_resolver_factory = {&dns_factory_vtable}; -static grpc_resolver_factory *dns_resolver_factory_create() { +static grpc_resolver_factory* dns_resolver_factory_create() { return &dns_resolver_factory; } -extern "C" void grpc_resolver_dns_native_init(void) { - char *resolver = gpr_getenv("GRPC_DNS_RESOLVER"); - if (resolver != NULL && gpr_stricmp(resolver, "native") == 0) { +void grpc_resolver_dns_native_init(void) { + char* resolver = gpr_getenv("GRPC_DNS_RESOLVER"); + if (resolver != nullptr && gpr_stricmp(resolver, "native") == 0) { gpr_log(GPR_DEBUG, "Using native dns resolver"); grpc_register_resolver_type(dns_resolver_factory_create()); } else { - grpc_resolver_factory *existing_factory = + grpc_resolver_factory* existing_factory = grpc_resolver_factory_lookup("dns"); - if (existing_factory == NULL) { + if (existing_factory == nullptr) { gpr_log(GPR_DEBUG, "Using native dns resolver"); grpc_register_resolver_type(dns_resolver_factory_create()); } else { @@ -312,4 +313,4 @@ extern "C" void grpc_resolver_dns_native_init(void) { gpr_free(resolver); } -extern "C" void grpc_resolver_dns_native_shutdown(void) {} +void grpc_resolver_dns_native_shutdown(void) {} diff --git a/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc b/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc index ed5b1011fbb..44798ca434e 100644 --- a/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc +++ b/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc @@ -78,31 +78,31 @@ static void fake_resolver_destroy(grpc_exec_ctx* exec_ctx, grpc_resolver* gr) { static void fake_resolver_shutdown_locked(grpc_exec_ctx* exec_ctx, grpc_resolver* resolver) { fake_resolver* r = (fake_resolver*)resolver; - if (r->next_completion != NULL) { - *r->target_result = NULL; + if (r->next_completion != nullptr) { + *r->target_result = nullptr; GRPC_CLOSURE_SCHED( exec_ctx, r->next_completion, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Resolver Shutdown")); - r->next_completion = NULL; + r->next_completion = nullptr; } } static void fake_resolver_maybe_finish_next_locked(grpc_exec_ctx* exec_ctx, fake_resolver* r) { - if (r->next_completion != NULL && r->next_results != NULL) { + if (r->next_completion != nullptr && r->next_results != nullptr) { *r->target_result = grpc_channel_args_union(r->next_results, r->channel_args); grpc_channel_args_destroy(exec_ctx, r->next_results); - r->next_results = NULL; + r->next_results = nullptr; GRPC_CLOSURE_SCHED(exec_ctx, r->next_completion, GRPC_ERROR_NONE); - r->next_completion = NULL; + r->next_completion = nullptr; } } static void fake_resolver_channel_saw_error_locked(grpc_exec_ctx* exec_ctx, grpc_resolver* resolver) { fake_resolver* r = (fake_resolver*)resolver; - if (r->next_results == NULL && r->results_upon_error != NULL) { + if (r->next_results == nullptr && r->results_upon_error != nullptr) { // Pretend we re-resolved. r->next_results = grpc_channel_args_copy(r->results_upon_error); } @@ -162,11 +162,11 @@ static void set_response_closure_fn(grpc_exec_ctx* exec_ctx, void* arg, set_response_closure_arg* closure_arg = (set_response_closure_arg*)arg; grpc_fake_resolver_response_generator* generator = closure_arg->generator; fake_resolver* r = generator->resolver; - if (r->next_results != NULL) { + if (r->next_results != nullptr) { grpc_channel_args_destroy(exec_ctx, r->next_results); } r->next_results = closure_arg->next_response; - if (r->results_upon_error != NULL) { + if (r->results_upon_error != nullptr) { grpc_channel_args_destroy(exec_ctx, r->results_upon_error); } r->results_upon_error = grpc_channel_args_copy(closure_arg->next_response); @@ -177,7 +177,7 @@ static void set_response_closure_fn(grpc_exec_ctx* exec_ctx, void* arg, void grpc_fake_resolver_response_generator_set_response( grpc_exec_ctx* exec_ctx, grpc_fake_resolver_response_generator* generator, grpc_channel_args* next_response) { - GPR_ASSERT(generator->resolver != NULL); + GPR_ASSERT(generator->resolver != nullptr); set_response_closure_arg* closure_arg = (set_response_closure_arg*)gpr_zalloc(sizeof(*closure_arg)); closure_arg->generator = generator; @@ -220,7 +220,7 @@ grpc_fake_resolver_response_generator* grpc_fake_resolver_get_response_generator(const grpc_channel_args* args) { const grpc_arg* arg = grpc_channel_args_find(args, GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR); - if (arg == NULL || arg->type != GRPC_ARG_POINTER) return NULL; + if (arg == nullptr || arg->type != GRPC_ARG_POINTER) return nullptr; return (grpc_fake_resolver_response_generator*)arg->value.pointer.p; } @@ -240,7 +240,7 @@ static grpc_resolver* fake_resolver_create(grpc_exec_ctx* exec_ctx, grpc_resolver_init(&r->base, &fake_resolver_vtable, args->combiner); grpc_fake_resolver_response_generator* response_generator = grpc_fake_resolver_get_response_generator(args->args); - if (response_generator != NULL) response_generator->resolver = r; + if (response_generator != nullptr) response_generator->resolver = r; return &r->base; } @@ -258,8 +258,8 @@ static const grpc_resolver_factory_vtable fake_resolver_factory_vtable = { static grpc_resolver_factory fake_resolver_factory = { &fake_resolver_factory_vtable}; -extern "C" void grpc_resolver_fake_init(void) { +void grpc_resolver_fake_init(void) { grpc_register_resolver_type(&fake_resolver_factory); } -extern "C" void grpc_resolver_fake_shutdown(void) {} +void grpc_resolver_fake_shutdown(void) {} diff --git a/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h b/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h index 95c3bafed82..7035cdda019 100644 --- a/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h +++ b/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h @@ -21,10 +21,6 @@ #include "src/core/ext/filters/client_channel/uri_parser.h" #include "src/core/lib/channel/channel_args.h" -#ifdef __cplusplus -extern "C" { -#endif - #define GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR \ "grpc.fake_resolver.response_generator" @@ -60,9 +56,5 @@ grpc_fake_resolver_response_generator_ref( void grpc_fake_resolver_response_generator_unref( grpc_fake_resolver_response_generator* generator); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_FAKE_FAKE_RESOLVER_H \ - */ + */ diff --git a/src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc b/src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc index dda9542325d..f0934b5943b 100644 --- a/src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc +++ b/src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc @@ -41,115 +41,115 @@ typedef struct { /** base class: must be first */ grpc_resolver base; /** the addresses that we've 'resolved' */ - grpc_lb_addresses *addresses; + grpc_lb_addresses* addresses; /** channel args */ - grpc_channel_args *channel_args; + grpc_channel_args* channel_args; /** have we published? */ bool published; /** pending next completion, or NULL */ - grpc_closure *next_completion; + grpc_closure* next_completion; /** target result address for next completion */ - grpc_channel_args **target_result; + grpc_channel_args** target_result; } sockaddr_resolver; -static void sockaddr_destroy(grpc_exec_ctx *exec_ctx, grpc_resolver *r); +static void sockaddr_destroy(grpc_exec_ctx* exec_ctx, grpc_resolver* r); -static void sockaddr_maybe_finish_next_locked(grpc_exec_ctx *exec_ctx, - sockaddr_resolver *r); +static void sockaddr_maybe_finish_next_locked(grpc_exec_ctx* exec_ctx, + sockaddr_resolver* r); -static void sockaddr_shutdown_locked(grpc_exec_ctx *exec_ctx, grpc_resolver *r); -static void sockaddr_channel_saw_error_locked(grpc_exec_ctx *exec_ctx, - grpc_resolver *r); -static void sockaddr_next_locked(grpc_exec_ctx *exec_ctx, grpc_resolver *r, - grpc_channel_args **target_result, - grpc_closure *on_complete); +static void sockaddr_shutdown_locked(grpc_exec_ctx* exec_ctx, grpc_resolver* r); +static void sockaddr_channel_saw_error_locked(grpc_exec_ctx* exec_ctx, + grpc_resolver* r); +static void sockaddr_next_locked(grpc_exec_ctx* exec_ctx, grpc_resolver* r, + grpc_channel_args** target_result, + grpc_closure* on_complete); static const grpc_resolver_vtable sockaddr_resolver_vtable = { sockaddr_destroy, sockaddr_shutdown_locked, sockaddr_channel_saw_error_locked, sockaddr_next_locked}; -static void sockaddr_shutdown_locked(grpc_exec_ctx *exec_ctx, - grpc_resolver *resolver) { - sockaddr_resolver *r = (sockaddr_resolver *)resolver; - if (r->next_completion != NULL) { - *r->target_result = NULL; +static void sockaddr_shutdown_locked(grpc_exec_ctx* exec_ctx, + grpc_resolver* resolver) { + sockaddr_resolver* r = (sockaddr_resolver*)resolver; + if (r->next_completion != nullptr) { + *r->target_result = nullptr; GRPC_CLOSURE_SCHED( exec_ctx, r->next_completion, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Resolver Shutdown")); - r->next_completion = NULL; + r->next_completion = nullptr; } } -static void sockaddr_channel_saw_error_locked(grpc_exec_ctx *exec_ctx, - grpc_resolver *resolver) { - sockaddr_resolver *r = (sockaddr_resolver *)resolver; +static void sockaddr_channel_saw_error_locked(grpc_exec_ctx* exec_ctx, + grpc_resolver* resolver) { + sockaddr_resolver* r = (sockaddr_resolver*)resolver; r->published = false; sockaddr_maybe_finish_next_locked(exec_ctx, r); } -static void sockaddr_next_locked(grpc_exec_ctx *exec_ctx, - grpc_resolver *resolver, - grpc_channel_args **target_result, - grpc_closure *on_complete) { - sockaddr_resolver *r = (sockaddr_resolver *)resolver; +static void sockaddr_next_locked(grpc_exec_ctx* exec_ctx, + grpc_resolver* resolver, + grpc_channel_args** target_result, + grpc_closure* on_complete) { + sockaddr_resolver* r = (sockaddr_resolver*)resolver; GPR_ASSERT(!r->next_completion); r->next_completion = on_complete; r->target_result = target_result; sockaddr_maybe_finish_next_locked(exec_ctx, r); } -static void sockaddr_maybe_finish_next_locked(grpc_exec_ctx *exec_ctx, - sockaddr_resolver *r) { - if (r->next_completion != NULL && !r->published) { +static void sockaddr_maybe_finish_next_locked(grpc_exec_ctx* exec_ctx, + sockaddr_resolver* r) { + if (r->next_completion != nullptr && !r->published) { r->published = true; grpc_arg arg = grpc_lb_addresses_create_channel_arg(r->addresses); *r->target_result = grpc_channel_args_copy_and_add(r->channel_args, &arg, 1); GRPC_CLOSURE_SCHED(exec_ctx, r->next_completion, GRPC_ERROR_NONE); - r->next_completion = NULL; + r->next_completion = nullptr; } } -static void sockaddr_destroy(grpc_exec_ctx *exec_ctx, grpc_resolver *gr) { - sockaddr_resolver *r = (sockaddr_resolver *)gr; +static void sockaddr_destroy(grpc_exec_ctx* exec_ctx, grpc_resolver* gr) { + sockaddr_resolver* r = (sockaddr_resolver*)gr; grpc_lb_addresses_destroy(exec_ctx, r->addresses); grpc_channel_args_destroy(exec_ctx, r->channel_args); gpr_free(r); } -static char *ip_get_default_authority(grpc_uri *uri) { - const char *path = uri->path; +static char* ip_get_default_authority(grpc_uri* uri) { + const char* path = uri->path; if (path[0] == '/') ++path; return gpr_strdup(path); } -static char *ipv4_get_default_authority(grpc_resolver_factory *factory, - grpc_uri *uri) { +static char* ipv4_get_default_authority(grpc_resolver_factory* factory, + grpc_uri* uri) { return ip_get_default_authority(uri); } -static char *ipv6_get_default_authority(grpc_resolver_factory *factory, - grpc_uri *uri) { +static char* ipv6_get_default_authority(grpc_resolver_factory* factory, + grpc_uri* uri) { return ip_get_default_authority(uri); } #ifdef GRPC_HAVE_UNIX_SOCKET -char *unix_get_default_authority(grpc_resolver_factory *factory, - grpc_uri *uri) { +char* unix_get_default_authority(grpc_resolver_factory* factory, + grpc_uri* uri) { return gpr_strdup("localhost"); } #endif -static void do_nothing(void *ignored) {} +static void do_nothing(void* ignored) {} -static grpc_resolver *sockaddr_create(grpc_exec_ctx *exec_ctx, - grpc_resolver_args *args, - bool parse(const grpc_uri *uri, - grpc_resolved_address *dst)) { +static grpc_resolver* sockaddr_create(grpc_exec_ctx* exec_ctx, + grpc_resolver_args* args, + bool parse(const grpc_uri* uri, + grpc_resolved_address* dst)) { if (0 != strcmp(args->uri->authority, "")) { gpr_log(GPR_ERROR, "authority based uri's not supported by the %s scheme", args->uri->scheme); - return NULL; + return nullptr; } /* Construct addresses. */ grpc_slice path_slice = @@ -157,12 +157,12 @@ static grpc_resolver *sockaddr_create(grpc_exec_ctx *exec_ctx, grpc_slice_buffer path_parts; grpc_slice_buffer_init(&path_parts); grpc_slice_split(path_slice, ",", &path_parts); - grpc_lb_addresses *addresses = - grpc_lb_addresses_create(path_parts.count, NULL /* user_data_vtable */); + grpc_lb_addresses* addresses = grpc_lb_addresses_create( + path_parts.count, nullptr /* user_data_vtable */); bool errors_found = false; for (size_t i = 0; i < addresses->num_addresses; i++) { grpc_uri ith_uri = *args->uri; - char *part_str = grpc_slice_to_c_string(path_parts.slices[i]); + char* part_str = grpc_slice_to_c_string(path_parts.slices[i]); ith_uri.path = part_str; if (!parse(&ith_uri, &addresses->addresses[i].address)) { errors_found = true; /* GPR_TRUE */ @@ -174,11 +174,11 @@ static grpc_resolver *sockaddr_create(grpc_exec_ctx *exec_ctx, grpc_slice_unref_internal(exec_ctx, path_slice); if (errors_found) { grpc_lb_addresses_destroy(exec_ctx, addresses); - return NULL; + return nullptr; } /* Instantiate resolver. */ - sockaddr_resolver *r = - (sockaddr_resolver *)gpr_zalloc(sizeof(sockaddr_resolver)); + sockaddr_resolver* r = + (sockaddr_resolver*)gpr_zalloc(sizeof(sockaddr_resolver)); r->addresses = addresses; r->channel_args = grpc_channel_args_copy(args->args); grpc_resolver_init(&r->base, &sockaddr_resolver_vtable, args->combiner); @@ -189,14 +189,14 @@ static grpc_resolver *sockaddr_create(grpc_exec_ctx *exec_ctx, * FACTORY */ -static void sockaddr_factory_ref(grpc_resolver_factory *factory) {} +static void sockaddr_factory_ref(grpc_resolver_factory* factory) {} -static void sockaddr_factory_unref(grpc_resolver_factory *factory) {} +static void sockaddr_factory_unref(grpc_resolver_factory* factory) {} #define DECL_FACTORY(name) \ - static grpc_resolver *name##_factory_create_resolver( \ - grpc_exec_ctx *exec_ctx, grpc_resolver_factory *factory, \ - grpc_resolver_args *args) { \ + static grpc_resolver* name##_factory_create_resolver( \ + grpc_exec_ctx* exec_ctx, grpc_resolver_factory* factory, \ + grpc_resolver_args* args) { \ return sockaddr_create(exec_ctx, args, grpc_parse_##name); \ } \ static const grpc_resolver_factory_vtable name##_factory_vtable = { \ @@ -211,7 +211,7 @@ DECL_FACTORY(unix); DECL_FACTORY(ipv4); DECL_FACTORY(ipv6); -extern "C" void grpc_resolver_sockaddr_init(void) { +void grpc_resolver_sockaddr_init(void) { grpc_register_resolver_type(&ipv4_resolver_factory); grpc_register_resolver_type(&ipv6_resolver_factory); #ifdef GRPC_HAVE_UNIX_SOCKET @@ -219,4 +219,4 @@ extern "C" void grpc_resolver_sockaddr_init(void) { #endif } -extern "C" void grpc_resolver_sockaddr_shutdown(void) {} +void grpc_resolver_sockaddr_shutdown(void) {} diff --git a/src/core/ext/filters/client_channel/resolver_factory.cc b/src/core/ext/filters/client_channel/resolver_factory.cc index 6f0a7c1e362..1a289d9771a 100644 --- a/src/core/ext/filters/client_channel/resolver_factory.cc +++ b/src/core/ext/filters/client_channel/resolver_factory.cc @@ -30,12 +30,12 @@ void grpc_resolver_factory_unref(grpc_resolver_factory* factory) { grpc_resolver* grpc_resolver_factory_create_resolver( grpc_exec_ctx* exec_ctx, grpc_resolver_factory* factory, grpc_resolver_args* args) { - if (factory == NULL) return NULL; + if (factory == nullptr) return nullptr; return factory->vtable->create_resolver(exec_ctx, factory, args); } char* grpc_resolver_factory_get_default_authority( grpc_resolver_factory* factory, grpc_uri* uri) { - if (factory == NULL) return NULL; + if (factory == nullptr) return nullptr; return factory->vtable->get_default_authority(factory, uri); } diff --git a/src/core/ext/filters/client_channel/resolver_factory.h b/src/core/ext/filters/client_channel/resolver_factory.h index c8b2c58db3e..fcf8ec425ec 100644 --- a/src/core/ext/filters/client_channel/resolver_factory.h +++ b/src/core/ext/filters/client_channel/resolver_factory.h @@ -24,55 +24,47 @@ #include "src/core/ext/filters/client_channel/uri_parser.h" #include "src/core/lib/iomgr/pollset_set.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_resolver_factory grpc_resolver_factory; typedef struct grpc_resolver_factory_vtable grpc_resolver_factory_vtable; struct grpc_resolver_factory { - const grpc_resolver_factory_vtable *vtable; + const grpc_resolver_factory_vtable* vtable; }; typedef struct grpc_resolver_args { - grpc_uri *uri; - const grpc_channel_args *args; - grpc_pollset_set *pollset_set; - grpc_combiner *combiner; + grpc_uri* uri; + const grpc_channel_args* args; + grpc_pollset_set* pollset_set; + grpc_combiner* combiner; } grpc_resolver_args; struct grpc_resolver_factory_vtable { - void (*ref)(grpc_resolver_factory *factory); - void (*unref)(grpc_resolver_factory *factory); + void (*ref)(grpc_resolver_factory* factory); + void (*unref)(grpc_resolver_factory* factory); /** Implementation of grpc_resolver_factory_create_resolver */ - grpc_resolver *(*create_resolver)(grpc_exec_ctx *exec_ctx, - grpc_resolver_factory *factory, - grpc_resolver_args *args); + grpc_resolver* (*create_resolver)(grpc_exec_ctx* exec_ctx, + grpc_resolver_factory* factory, + grpc_resolver_args* args); /** Implementation of grpc_resolver_factory_get_default_authority */ - char *(*get_default_authority)(grpc_resolver_factory *factory, grpc_uri *uri); + char* (*get_default_authority)(grpc_resolver_factory* factory, grpc_uri* uri); /** URI scheme that this factory implements */ - const char *scheme; + const char* scheme; }; -void grpc_resolver_factory_ref(grpc_resolver_factory *resolver); -void grpc_resolver_factory_unref(grpc_resolver_factory *resolver); +void grpc_resolver_factory_ref(grpc_resolver_factory* resolver); +void grpc_resolver_factory_unref(grpc_resolver_factory* resolver); /** Create a resolver instance for a name */ -grpc_resolver *grpc_resolver_factory_create_resolver( - grpc_exec_ctx *exec_ctx, grpc_resolver_factory *factory, - grpc_resolver_args *args); +grpc_resolver* grpc_resolver_factory_create_resolver( + grpc_exec_ctx* exec_ctx, grpc_resolver_factory* factory, + grpc_resolver_args* args); /** Return a (freshly allocated with gpr_malloc) string representing the default authority to use for this scheme. */ -char *grpc_resolver_factory_get_default_authority( - grpc_resolver_factory *factory, grpc_uri *uri); - -#ifdef __cplusplus -} -#endif +char* grpc_resolver_factory_get_default_authority( + grpc_resolver_factory* factory, grpc_uri* uri); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_FACTORY_H */ diff --git a/src/core/ext/filters/client_channel/resolver_registry.cc b/src/core/ext/filters/client_channel/resolver_registry.cc index 1a0fb0bc3cf..5da6114a3d0 100644 --- a/src/core/ext/filters/client_channel/resolver_registry.cc +++ b/src/core/ext/filters/client_channel/resolver_registry.cc @@ -27,7 +27,7 @@ #define MAX_RESOLVERS 10 #define DEFAULT_RESOLVER_PREFIX_MAX_LENGTH 32 -static grpc_resolver_factory *g_all_of_the_resolvers[MAX_RESOLVERS]; +static grpc_resolver_factory* g_all_of_the_resolvers[MAX_RESOLVERS]; static int g_number_of_resolvers = 0; static char g_default_resolver_prefix[DEFAULT_RESOLVER_PREFIX_MAX_LENGTH] = @@ -49,7 +49,7 @@ void grpc_resolver_registry_shutdown(void) { } void grpc_resolver_registry_set_default_prefix( - const char *default_resolver_prefix) { + const char* default_resolver_prefix) { const size_t len = strlen(default_resolver_prefix); GPR_ASSERT(len < DEFAULT_RESOLVER_PREFIX_MAX_LENGTH && "default resolver prefix too long"); @@ -59,7 +59,7 @@ void grpc_resolver_registry_set_default_prefix( strcpy(g_default_resolver_prefix, default_resolver_prefix); } -void grpc_register_resolver_type(grpc_resolver_factory *factory) { +void grpc_register_resolver_type(grpc_resolver_factory* factory) { int i; for (i = 0; i < g_number_of_resolvers; i++) { GPR_ASSERT(0 != strcmp(factory->vtable->scheme, @@ -70,7 +70,7 @@ void grpc_register_resolver_type(grpc_resolver_factory *factory) { g_all_of_the_resolvers[g_number_of_resolvers++] = factory; } -static grpc_resolver_factory *lookup_factory(const char *name) { +static grpc_resolver_factory* lookup_factory(const char* name) { int i; for (i = 0; i < g_number_of_resolvers; i++) { @@ -78,35 +78,35 @@ static grpc_resolver_factory *lookup_factory(const char *name) { return g_all_of_the_resolvers[i]; } } - return NULL; + return nullptr; } -grpc_resolver_factory *grpc_resolver_factory_lookup(const char *name) { - grpc_resolver_factory *f = lookup_factory(name); +grpc_resolver_factory* grpc_resolver_factory_lookup(const char* name) { + grpc_resolver_factory* f = lookup_factory(name); if (f) grpc_resolver_factory_ref(f); return f; } -static grpc_resolver_factory *lookup_factory_by_uri(grpc_uri *uri) { - if (!uri) return NULL; +static grpc_resolver_factory* lookup_factory_by_uri(grpc_uri* uri) { + if (!uri) return nullptr; return lookup_factory(uri->scheme); } -static grpc_resolver_factory *resolve_factory(grpc_exec_ctx *exec_ctx, - const char *target, - grpc_uri **uri, - char **canonical_target) { - grpc_resolver_factory *factory = NULL; +static grpc_resolver_factory* resolve_factory(grpc_exec_ctx* exec_ctx, + const char* target, + grpc_uri** uri, + char** canonical_target) { + grpc_resolver_factory* factory = nullptr; - GPR_ASSERT(uri != NULL); + GPR_ASSERT(uri != nullptr); *uri = grpc_uri_parse(exec_ctx, target, 1); factory = lookup_factory_by_uri(*uri); - if (factory == NULL) { + if (factory == nullptr) { grpc_uri_destroy(*uri); gpr_asprintf(canonical_target, "%s%s", g_default_resolver_prefix, target); *uri = grpc_uri_parse(exec_ctx, *canonical_target, 1); factory = lookup_factory_by_uri(*uri); - if (factory == NULL) { + if (factory == nullptr) { grpc_uri_destroy(grpc_uri_parse(exec_ctx, target, 0)); grpc_uri_destroy(grpc_uri_parse(exec_ctx, *canonical_target, 0)); gpr_log(GPR_ERROR, "don't know how to resolve '%s' or '%s'", target, @@ -116,15 +116,15 @@ static grpc_resolver_factory *resolve_factory(grpc_exec_ctx *exec_ctx, return factory; } -grpc_resolver *grpc_resolver_create(grpc_exec_ctx *exec_ctx, const char *target, - const grpc_channel_args *args, - grpc_pollset_set *pollset_set, - grpc_combiner *combiner) { - grpc_uri *uri = NULL; - char *canonical_target = NULL; - grpc_resolver_factory *factory = +grpc_resolver* grpc_resolver_create(grpc_exec_ctx* exec_ctx, const char* target, + const grpc_channel_args* args, + grpc_pollset_set* pollset_set, + grpc_combiner* combiner) { + grpc_uri* uri = nullptr; + char* canonical_target = nullptr; + grpc_resolver_factory* factory = resolve_factory(exec_ctx, target, &uri, &canonical_target); - grpc_resolver *resolver; + grpc_resolver* resolver; grpc_resolver_args resolver_args; memset(&resolver_args, 0, sizeof(resolver_args)); resolver_args.uri = uri; @@ -138,22 +138,22 @@ grpc_resolver *grpc_resolver_create(grpc_exec_ctx *exec_ctx, const char *target, return resolver; } -char *grpc_get_default_authority(grpc_exec_ctx *exec_ctx, const char *target) { - grpc_uri *uri = NULL; - char *canonical_target = NULL; - grpc_resolver_factory *factory = +char* grpc_get_default_authority(grpc_exec_ctx* exec_ctx, const char* target) { + grpc_uri* uri = nullptr; + char* canonical_target = nullptr; + grpc_resolver_factory* factory = resolve_factory(exec_ctx, target, &uri, &canonical_target); - char *authority = grpc_resolver_factory_get_default_authority(factory, uri); + char* authority = grpc_resolver_factory_get_default_authority(factory, uri); grpc_uri_destroy(uri); gpr_free(canonical_target); return authority; } -char *grpc_resolver_factory_add_default_prefix_if_needed( - grpc_exec_ctx *exec_ctx, const char *target) { - grpc_uri *uri = NULL; - char *canonical_target = NULL; +char* grpc_resolver_factory_add_default_prefix_if_needed( + grpc_exec_ctx* exec_ctx, const char* target) { + grpc_uri* uri = nullptr; + char* canonical_target = nullptr; resolve_factory(exec_ctx, target, &uri, &canonical_target); grpc_uri_destroy(uri); - return canonical_target == NULL ? gpr_strdup(target) : canonical_target; + return canonical_target == nullptr ? gpr_strdup(target) : canonical_target; } diff --git a/src/core/ext/filters/client_channel/resolver_registry.h b/src/core/ext/filters/client_channel/resolver_registry.h index 06d0b99a355..ecc9f824e8b 100644 --- a/src/core/ext/filters/client_channel/resolver_registry.h +++ b/src/core/ext/filters/client_channel/resolver_registry.h @@ -22,22 +22,18 @@ #include "src/core/ext/filters/client_channel/resolver_factory.h" #include "src/core/lib/iomgr/pollset_set.h" -#ifdef __cplusplus -extern "C" { -#endif - void grpc_resolver_registry_init(); void grpc_resolver_registry_shutdown(void); /** Set the default URI prefix to \a default_prefix. */ -void grpc_resolver_registry_set_default_prefix(const char *default_prefix); +void grpc_resolver_registry_set_default_prefix(const char* default_prefix); /** Register a resolver type. URI's of \a scheme will be resolved with the given resolver. If \a priority is greater than zero, then the resolver will be eligible to resolve names that are passed in with no scheme. Higher priority resolvers will be tried before lower priority schemes. */ -void grpc_register_resolver_type(grpc_resolver_factory *factory); +void grpc_register_resolver_type(grpc_resolver_factory* factory); /** Create a resolver given \a target. First tries to parse \a target as a URI. If this succeeds, tries @@ -52,26 +48,22 @@ void grpc_register_resolver_type(grpc_resolver_factory *factory); (typically the set of arguments passed in from the client API). \a pollset_set is used to drive IO in the name resolution process, it should not be NULL. */ -grpc_resolver *grpc_resolver_create(grpc_exec_ctx *exec_ctx, const char *target, - const grpc_channel_args *args, - grpc_pollset_set *pollset_set, - grpc_combiner *combiner); +grpc_resolver* grpc_resolver_create(grpc_exec_ctx* exec_ctx, const char* target, + const grpc_channel_args* args, + grpc_pollset_set* pollset_set, + grpc_combiner* combiner); /** Find a resolver factory given a name and return an (owned-by-the-caller) * reference to it */ -grpc_resolver_factory *grpc_resolver_factory_lookup(const char *name); +grpc_resolver_factory* grpc_resolver_factory_lookup(const char* name); /** Given a target, return a (freshly allocated with gpr_malloc) string representing the default authority to pass from a client. */ -char *grpc_get_default_authority(grpc_exec_ctx *exec_ctx, const char *target); +char* grpc_get_default_authority(grpc_exec_ctx* exec_ctx, const char* target); /** Returns a newly allocated string containing \a target, adding the default prefix if needed. */ -char *grpc_resolver_factory_add_default_prefix_if_needed( - grpc_exec_ctx *exec_ctx, const char *target); - -#ifdef __cplusplus -} -#endif +char* grpc_resolver_factory_add_default_prefix_if_needed( + grpc_exec_ctx* exec_ctx, const char* target); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_REGISTRY_H */ diff --git a/src/core/ext/filters/client_channel/retry_throttle.cc b/src/core/ext/filters/client_channel/retry_throttle.cc index 09dcade0890..867d775151b 100644 --- a/src/core/ext/filters/client_channel/retry_throttle.cc +++ b/src/core/ext/filters/client_channel/retry_throttle.cc @@ -48,7 +48,7 @@ static void get_replacement_throttle_data_if_needed( grpc_server_retry_throttle_data* new_throttle_data = (grpc_server_retry_throttle_data*)gpr_atm_acq_load( &(*throttle_data)->replacement); - if (new_throttle_data == NULL) return; + if (new_throttle_data == nullptr) return; *throttle_data = new_throttle_data; } } @@ -88,7 +88,7 @@ void grpc_server_retry_throttle_data_unref( grpc_server_retry_throttle_data* replacement = (grpc_server_retry_throttle_data*)gpr_atm_acq_load( &throttle_data->replacement); - if (replacement != NULL) { + if (replacement != nullptr) { grpc_server_retry_throttle_data_unref(replacement); } gpr_free(throttle_data); @@ -109,7 +109,7 @@ static grpc_server_retry_throttle_data* grpc_server_retry_throttle_data_create( // the token count by scaling proportionately to the old data. This // ensures that if we're already throttling retries on the old scale, // we will start out doing the same thing on the new one. - if (old_throttle_data != NULL) { + if (old_throttle_data != nullptr) { double token_fraction = (int)gpr_atm_acq_load(&old_throttle_data->milli_tokens) / (double)old_throttle_data->max_milli_tokens; @@ -119,7 +119,7 @@ static grpc_server_retry_throttle_data* grpc_server_retry_throttle_data_create( (gpr_atm)initial_milli_tokens); // If there was a pre-existing entry, mark it as stale and give it a // pointer to the new entry, which is its replacement. - if (old_throttle_data != NULL) { + if (old_throttle_data != nullptr) { grpc_server_retry_throttle_data_ref(throttle_data); gpr_atm_rel_store(&old_throttle_data->replacement, (gpr_atm)throttle_data); } @@ -170,7 +170,7 @@ void grpc_retry_throttle_map_init() { void grpc_retry_throttle_map_shutdown() { gpr_mu_destroy(&g_mu); - gpr_avl_unref(g_avl, NULL); + gpr_avl_unref(g_avl, nullptr); } grpc_server_retry_throttle_data* grpc_retry_throttle_map_get_data_for_server( @@ -178,12 +178,12 @@ grpc_server_retry_throttle_data* grpc_retry_throttle_map_get_data_for_server( gpr_mu_lock(&g_mu); grpc_server_retry_throttle_data* throttle_data = (grpc_server_retry_throttle_data*)gpr_avl_get(g_avl, (char*)server_name, - NULL); - if (throttle_data == NULL) { + nullptr); + if (throttle_data == nullptr) { // Entry not found. Create a new one. throttle_data = grpc_server_retry_throttle_data_create( - max_milli_tokens, milli_token_ratio, NULL); - g_avl = gpr_avl_add(g_avl, (char*)server_name, throttle_data, NULL); + max_milli_tokens, milli_token_ratio, nullptr); + g_avl = gpr_avl_add(g_avl, (char*)server_name, throttle_data, nullptr); } else { if (throttle_data->max_milli_tokens != max_milli_tokens || throttle_data->milli_token_ratio != milli_token_ratio) { @@ -191,7 +191,7 @@ grpc_server_retry_throttle_data* grpc_retry_throttle_map_get_data_for_server( // the original one. throttle_data = grpc_server_retry_throttle_data_create( max_milli_tokens, milli_token_ratio, throttle_data); - g_avl = gpr_avl_add(g_avl, (char*)server_name, throttle_data, NULL); + g_avl = gpr_avl_add(g_avl, (char*)server_name, throttle_data, nullptr); } else { // Entry found. Increase refcount. grpc_server_retry_throttle_data_ref(throttle_data); diff --git a/src/core/ext/filters/client_channel/retry_throttle.h b/src/core/ext/filters/client_channel/retry_throttle.h index 399383df78b..bf99297e988 100644 --- a/src/core/ext/filters/client_channel/retry_throttle.h +++ b/src/core/ext/filters/client_channel/retry_throttle.h @@ -21,10 +21,6 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /// Tracks retry throttling data for an individual server name. typedef struct grpc_server_retry_throttle_data grpc_server_retry_throttle_data; @@ -51,8 +47,4 @@ void grpc_retry_throttle_map_shutdown(); grpc_server_retry_throttle_data* grpc_retry_throttle_map_get_data_for_server( const char* server_name, int max_milli_tokens, int milli_token_ratio); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RETRY_THROTTLE_H */ diff --git a/src/core/ext/filters/client_channel/subchannel.cc b/src/core/ext/filters/client_channel/subchannel.cc index 5710a221784..58e294d597f 100644 --- a/src/core/ext/filters/client_channel/subchannel.cc +++ b/src/core/ext/filters/client_channel/subchannel.cc @@ -52,27 +52,27 @@ #define GRPC_SUBCHANNEL_RECONNECT_MAX_BACKOFF_SECONDS 120 #define GRPC_SUBCHANNEL_RECONNECT_JITTER 0.2 -#define GET_CONNECTED_SUBCHANNEL(subchannel, barrier) \ - ((grpc_connected_subchannel *)(gpr_atm_##barrier##_load( \ +#define GET_CONNECTED_SUBCHANNEL(subchannel, barrier) \ + ((grpc_connected_subchannel*)(gpr_atm_##barrier##_load( \ &(subchannel)->connected_subchannel))) typedef struct { grpc_closure closure; - grpc_subchannel *subchannel; + grpc_subchannel* subchannel; grpc_connectivity_state connectivity_state; } state_watcher; typedef struct external_state_watcher { - grpc_subchannel *subchannel; - grpc_pollset_set *pollset_set; - grpc_closure *notify; + grpc_subchannel* subchannel; + grpc_pollset_set* pollset_set; + grpc_closure* notify; grpc_closure closure; - struct external_state_watcher *next; - struct external_state_watcher *prev; + struct external_state_watcher* next; + struct external_state_watcher* prev; } external_state_watcher; struct grpc_subchannel { - grpc_connector *connector; + grpc_connector* connector; /** refcount - lower INTERNAL_REF_BITS bits are for internal references: @@ -82,12 +82,12 @@ struct grpc_subchannel { gpr_atm ref_pair; /** non-transport related channel filters */ - const grpc_channel_filter **filters; + const grpc_channel_filter** filters; size_t num_filters; /** channel arguments */ - grpc_channel_args *args; + grpc_channel_args* args; - grpc_subchannel_key *key; + grpc_subchannel_key* key; /** set during connection */ grpc_connect_out_args connecting_result; @@ -100,7 +100,7 @@ struct grpc_subchannel { /** pollset_set tracking who's interested in a connection being setup */ - grpc_pollset_set *pollset_set; + grpc_pollset_set* pollset_set; /** active connection, or null; of type grpc_connected_subchannel */ gpr_atm connected_subchannel; @@ -117,10 +117,10 @@ struct grpc_subchannel { external_state_watcher root_external_state_watcher; - /** next connect attempt time */ - grpc_millis next_attempt; /** backoff state */ grpc_backoff backoff_state; + grpc_backoff_result backoff_result; + /** do we have an active alarm? */ bool have_alarm; /** have we started the backoff loop */ @@ -130,22 +130,22 @@ struct grpc_subchannel { }; struct grpc_subchannel_call { - grpc_connected_subchannel *connection; - grpc_closure *schedule_closure_after_destroy; + grpc_connected_subchannel* connection; + grpc_closure* schedule_closure_after_destroy; }; -#define SUBCHANNEL_CALL_TO_CALL_STACK(call) ((grpc_call_stack *)((call) + 1)) -#define CHANNEL_STACK_FROM_CONNECTION(con) ((grpc_channel_stack *)(con)) +#define SUBCHANNEL_CALL_TO_CALL_STACK(call) ((grpc_call_stack*)((call) + 1)) +#define CHANNEL_STACK_FROM_CONNECTION(con) ((grpc_channel_stack*)(con)) #define CALLSTACK_TO_SUBCHANNEL_CALL(callstack) \ - (((grpc_subchannel_call *)(callstack)) - 1) + (((grpc_subchannel_call*)(callstack)) - 1) -static void subchannel_connected(grpc_exec_ctx *exec_ctx, void *subchannel, - grpc_error *error); +static void subchannel_connected(grpc_exec_ctx* exec_ctx, void* subchannel, + grpc_error* error); #ifndef NDEBUG #define REF_REASON reason #define REF_MUTATE_EXTRA_ARGS \ - GRPC_SUBCHANNEL_REF_EXTRA_ARGS, const char *purpose + GRPC_SUBCHANNEL_REF_EXTRA_ARGS, const char* purpose #define REF_MUTATE_PURPOSE(x) , file, line, reason, x #else #define REF_REASON "" @@ -157,21 +157,21 @@ static void subchannel_connected(grpc_exec_ctx *exec_ctx, void *subchannel, * connection implementation */ -static void connection_destroy(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_connected_subchannel *c = (grpc_connected_subchannel *)arg; +static void connection_destroy(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_connected_subchannel* c = (grpc_connected_subchannel*)arg; grpc_channel_stack_destroy(exec_ctx, CHANNEL_STACK_FROM_CONNECTION(c)); gpr_free(c); } -grpc_connected_subchannel *grpc_connected_subchannel_ref( - grpc_connected_subchannel *c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { +grpc_connected_subchannel* grpc_connected_subchannel_ref( + grpc_connected_subchannel* c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { GRPC_CHANNEL_STACK_REF(CHANNEL_STACK_FROM_CONNECTION(c), REF_REASON); return c; } -void grpc_connected_subchannel_unref(grpc_exec_ctx *exec_ctx, - grpc_connected_subchannel *c +void grpc_connected_subchannel_unref(grpc_exec_ctx* exec_ctx, + grpc_connected_subchannel* c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { GRPC_CHANNEL_STACK_UNREF(exec_ctx, CHANNEL_STACK_FROM_CONNECTION(c), REF_REASON); @@ -181,10 +181,10 @@ void grpc_connected_subchannel_unref(grpc_exec_ctx *exec_ctx, * grpc_subchannel implementation */ -static void subchannel_destroy(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_subchannel *c = (grpc_subchannel *)arg; - gpr_free((void *)c->filters); +static void subchannel_destroy(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_subchannel* c = (grpc_subchannel*)arg; + gpr_free((void*)c->filters); grpc_channel_args_destroy(exec_ctx, c->args); grpc_connectivity_state_destroy(exec_ctx, &c->state_tracker); grpc_connector_unref(exec_ctx, c->connector); @@ -194,12 +194,12 @@ static void subchannel_destroy(grpc_exec_ctx *exec_ctx, void *arg, gpr_free(c); } -static gpr_atm ref_mutate(grpc_subchannel *c, gpr_atm delta, +static gpr_atm ref_mutate(grpc_subchannel* c, gpr_atm delta, int barrier REF_MUTATE_EXTRA_ARGS) { gpr_atm old_val = barrier ? gpr_atm_full_fetch_add(&c->ref_pair, delta) : gpr_atm_no_barrier_fetch_add(&c->ref_pair, delta); #ifndef NDEBUG - if (GRPC_TRACER_ON(grpc_trace_stream_refcount)) { + if (grpc_trace_stream_refcount.enabled()) { gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "SUBCHANNEL: %p %12s 0x%" PRIxPTR " -> 0x%" PRIxPTR " [%s]", c, purpose, old_val, old_val + delta, reason); @@ -208,8 +208,8 @@ static gpr_atm ref_mutate(grpc_subchannel *c, gpr_atm delta, return old_val; } -grpc_subchannel *grpc_subchannel_ref( - grpc_subchannel *c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { +grpc_subchannel* grpc_subchannel_ref( + grpc_subchannel* c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { gpr_atm old_refs; old_refs = ref_mutate(c, (1 << INTERNAL_REF_BITS), 0 REF_MUTATE_PURPOSE("STRONG_REF")); @@ -217,17 +217,17 @@ grpc_subchannel *grpc_subchannel_ref( return c; } -grpc_subchannel *grpc_subchannel_weak_ref( - grpc_subchannel *c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { +grpc_subchannel* grpc_subchannel_weak_ref( + grpc_subchannel* c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { gpr_atm old_refs; old_refs = ref_mutate(c, 1, 0 REF_MUTATE_PURPOSE("WEAK_REF")); GPR_ASSERT(old_refs != 0); return c; } -grpc_subchannel *grpc_subchannel_ref_from_weak_ref( - grpc_subchannel *c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { - if (!c) return NULL; +grpc_subchannel* grpc_subchannel_ref_from_weak_ref( + grpc_subchannel* c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { + if (!c) return nullptr; for (;;) { gpr_atm old_refs = gpr_atm_acq_load(&c->ref_pair); if (old_refs >= (1 << INTERNAL_REF_BITS)) { @@ -236,13 +236,13 @@ grpc_subchannel *grpc_subchannel_ref_from_weak_ref( return c; } } else { - return NULL; + return nullptr; } } } -static void disconnect(grpc_exec_ctx *exec_ctx, grpc_subchannel *c) { - grpc_connected_subchannel *con; +static void disconnect(grpc_exec_ctx* exec_ctx, grpc_subchannel* c) { + grpc_connected_subchannel* con; grpc_subchannel_index_unregister(exec_ctx, c->key, c); gpr_mu_lock(&c->mu); GPR_ASSERT(!c->disconnected); @@ -251,15 +251,15 @@ static void disconnect(grpc_exec_ctx *exec_ctx, grpc_subchannel *c) { exec_ctx, c->connector, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Subchannel disconnected")); con = GET_CONNECTED_SUBCHANNEL(c, no_barrier); - if (con != NULL) { + if (con != nullptr) { GRPC_CONNECTED_SUBCHANNEL_UNREF(exec_ctx, con, "connection"); gpr_atm_no_barrier_store(&c->connected_subchannel, (gpr_atm)0xdeadbeef); } gpr_mu_unlock(&c->mu); } -void grpc_subchannel_unref(grpc_exec_ctx *exec_ctx, - grpc_subchannel *c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { +void grpc_subchannel_unref(grpc_exec_ctx* exec_ctx, + grpc_subchannel* c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { gpr_atm old_refs; // add a weak ref and subtract a strong ref (atomically) old_refs = ref_mutate(c, (gpr_atm)1 - (gpr_atm)(1 << INTERNAL_REF_BITS), @@ -270,63 +270,64 @@ void grpc_subchannel_unref(grpc_exec_ctx *exec_ctx, GRPC_SUBCHANNEL_WEAK_UNREF(exec_ctx, c, "strong-unref"); } -void grpc_subchannel_weak_unref(grpc_exec_ctx *exec_ctx, - grpc_subchannel *c +void grpc_subchannel_weak_unref(grpc_exec_ctx* exec_ctx, + grpc_subchannel* c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { gpr_atm old_refs; old_refs = ref_mutate(c, -(gpr_atm)1, 1 REF_MUTATE_PURPOSE("WEAK_UNREF")); if (old_refs == 1) { - GRPC_CLOSURE_SCHED(exec_ctx, GRPC_CLOSURE_CREATE(subchannel_destroy, c, - grpc_schedule_on_exec_ctx), - GRPC_ERROR_NONE); + GRPC_CLOSURE_SCHED( + exec_ctx, + GRPC_CLOSURE_CREATE(subchannel_destroy, c, grpc_schedule_on_exec_ctx), + GRPC_ERROR_NONE); } } -grpc_subchannel *grpc_subchannel_create(grpc_exec_ctx *exec_ctx, - grpc_connector *connector, - const grpc_subchannel_args *args) { - grpc_subchannel_key *key = grpc_subchannel_key_create(args); - grpc_subchannel *c = grpc_subchannel_index_find(exec_ctx, key); +grpc_subchannel* grpc_subchannel_create(grpc_exec_ctx* exec_ctx, + grpc_connector* connector, + const grpc_subchannel_args* args) { + grpc_subchannel_key* key = grpc_subchannel_key_create(args); + grpc_subchannel* c = grpc_subchannel_index_find(exec_ctx, key); if (c) { grpc_subchannel_key_destroy(exec_ctx, key); return c; } GRPC_STATS_INC_CLIENT_SUBCHANNELS_CREATED(exec_ctx); - c = (grpc_subchannel *)gpr_zalloc(sizeof(*c)); + c = (grpc_subchannel*)gpr_zalloc(sizeof(*c)); c->key = key; gpr_atm_no_barrier_store(&c->ref_pair, 1 << INTERNAL_REF_BITS); c->connector = connector; grpc_connector_ref(c->connector); c->num_filters = args->filter_count; if (c->num_filters > 0) { - c->filters = (const grpc_channel_filter **)gpr_malloc( - sizeof(grpc_channel_filter *) * c->num_filters); - memcpy((void *)c->filters, args->filters, - sizeof(grpc_channel_filter *) * c->num_filters); + c->filters = (const grpc_channel_filter**)gpr_malloc( + sizeof(grpc_channel_filter*) * c->num_filters); + memcpy((void*)c->filters, args->filters, + sizeof(grpc_channel_filter*) * c->num_filters); } else { - c->filters = NULL; + c->filters = nullptr; } c->pollset_set = grpc_pollset_set_create(); - grpc_resolved_address *addr = - (grpc_resolved_address *)gpr_malloc(sizeof(*addr)); + grpc_resolved_address* addr = + (grpc_resolved_address*)gpr_malloc(sizeof(*addr)); grpc_get_subchannel_address_arg(exec_ctx, args->args, addr); - grpc_resolved_address *new_address = NULL; - grpc_channel_args *new_args = NULL; + grpc_resolved_address* new_address = nullptr; + grpc_channel_args* new_args = nullptr; if (grpc_proxy_mappers_map_address(exec_ctx, addr, args->args, &new_address, &new_args)) { - GPR_ASSERT(new_address != NULL); + GPR_ASSERT(new_address != nullptr); gpr_free(addr); addr = new_address; } - static const char *keys_to_remove[] = {GRPC_ARG_SUBCHANNEL_ADDRESS}; + static const char* keys_to_remove[] = {GRPC_ARG_SUBCHANNEL_ADDRESS}; grpc_arg new_arg = grpc_create_subchannel_address_arg(addr); gpr_free(addr); c->args = grpc_channel_args_copy_and_add_and_remove( - new_args != NULL ? new_args : args->args, keys_to_remove, + new_args != nullptr ? new_args : args->args, keys_to_remove, GPR_ARRAY_SIZE(keys_to_remove), &new_arg, 1); gpr_free(new_arg.value.string); - if (new_args != NULL) grpc_channel_args_destroy(exec_ctx, new_args); + if (new_args != nullptr) grpc_channel_args_destroy(exec_ctx, new_args); c->root_external_state_watcher.next = c->root_external_state_watcher.prev = &c->root_external_state_watcher; GRPC_CLOSURE_INIT(&c->connected, subchannel_connected, c, @@ -375,12 +376,12 @@ grpc_subchannel *grpc_subchannel_create(grpc_exec_ctx *exec_ctx, return grpc_subchannel_index_register(exec_ctx, key, c); } -static void continue_connect_locked(grpc_exec_ctx *exec_ctx, - grpc_subchannel *c) { +static void continue_connect_locked(grpc_exec_ctx* exec_ctx, + grpc_subchannel* c) { grpc_connect_in_args args; args.interested_parties = c->pollset_set; - args.deadline = c->next_attempt; + args.deadline = c->backoff_result.current_deadline; args.channel_args = c->args; grpc_connectivity_state_set(exec_ctx, &c->state_tracker, @@ -390,8 +391,8 @@ static void continue_connect_locked(grpc_exec_ctx *exec_ctx, &c->connected); } -grpc_connectivity_state grpc_subchannel_check_connectivity(grpc_subchannel *c, - grpc_error **error) { +grpc_connectivity_state grpc_subchannel_check_connectivity(grpc_subchannel* c, + grpc_error** error) { grpc_connectivity_state state; gpr_mu_lock(&c->mu); state = grpc_connectivity_state_get(&c->state_tracker, error); @@ -399,11 +400,11 @@ grpc_connectivity_state grpc_subchannel_check_connectivity(grpc_subchannel *c, return state; } -static void on_external_state_watcher_done(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - external_state_watcher *w = (external_state_watcher *)arg; - grpc_closure *follow_up = w->notify; - if (w->pollset_set != NULL) { +static void on_external_state_watcher_done(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + external_state_watcher* w = (external_state_watcher*)arg; + grpc_closure* follow_up = w->notify; + if (w->pollset_set != nullptr) { grpc_pollset_set_del_pollset_set(exec_ctx, w->subchannel->pollset_set, w->pollset_set); } @@ -416,8 +417,8 @@ static void on_external_state_watcher_done(grpc_exec_ctx *exec_ctx, void *arg, GRPC_CLOSURE_RUN(exec_ctx, follow_up, GRPC_ERROR_REF(error)); } -static void on_alarm(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { - grpc_subchannel *c = (grpc_subchannel *)arg; +static void on_alarm(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { + grpc_subchannel* c = (grpc_subchannel*)arg; gpr_mu_lock(&c->mu); c->have_alarm = false; if (c->disconnected) { @@ -428,7 +429,7 @@ static void on_alarm(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { } if (error == GRPC_ERROR_NONE) { gpr_log(GPR_INFO, "Failed to connect to channel, retrying"); - c->next_attempt = grpc_backoff_step(exec_ctx, &c->backoff_state); + c->backoff_result = grpc_backoff_step(exec_ctx, &c->backoff_state); continue_connect_locked(exec_ctx, c); gpr_mu_unlock(&c->mu); } else { @@ -438,8 +439,8 @@ static void on_alarm(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { GRPC_ERROR_UNREF(error); } -static void maybe_start_connecting_locked(grpc_exec_ctx *exec_ctx, - grpc_subchannel *c) { +static void maybe_start_connecting_locked(grpc_exec_ctx* exec_ctx, + grpc_subchannel* c) { if (c->disconnected) { /* Don't try to connect if we're already disconnected */ return; @@ -450,7 +451,7 @@ static void maybe_start_connecting_locked(grpc_exec_ctx *exec_ctx, return; } - if (GET_CONNECTED_SUBCHANNEL(c, no_barrier) != NULL) { + if (GET_CONNECTED_SUBCHANNEL(c, no_barrier) != nullptr) { /* Already connected: don't restart */ return; } @@ -465,47 +466,48 @@ static void maybe_start_connecting_locked(grpc_exec_ctx *exec_ctx, if (!c->backoff_begun) { c->backoff_begun = true; - c->next_attempt = grpc_backoff_begin(exec_ctx, &c->backoff_state); + c->backoff_result = grpc_backoff_begin(exec_ctx, &c->backoff_state); continue_connect_locked(exec_ctx, c); } else { GPR_ASSERT(!c->have_alarm); c->have_alarm = true; const grpc_millis time_til_next = - c->next_attempt - grpc_exec_ctx_now(exec_ctx); + c->backoff_result.next_attempt_start_time - grpc_exec_ctx_now(exec_ctx); if (time_til_next <= 0) { gpr_log(GPR_INFO, "Retry immediately"); } else { gpr_log(GPR_INFO, "Retry in %" PRIdPTR " milliseconds", time_til_next); } GRPC_CLOSURE_INIT(&c->on_alarm, on_alarm, c, grpc_schedule_on_exec_ctx); - grpc_timer_init(exec_ctx, &c->alarm, c->next_attempt, &c->on_alarm); + grpc_timer_init(exec_ctx, &c->alarm, + c->backoff_result.next_attempt_start_time, &c->on_alarm); } } void grpc_subchannel_notify_on_state_change( - grpc_exec_ctx *exec_ctx, grpc_subchannel *c, - grpc_pollset_set *interested_parties, grpc_connectivity_state *state, - grpc_closure *notify) { - external_state_watcher *w; + grpc_exec_ctx* exec_ctx, grpc_subchannel* c, + grpc_pollset_set* interested_parties, grpc_connectivity_state* state, + grpc_closure* notify) { + external_state_watcher* w; - if (state == NULL) { + if (state == nullptr) { gpr_mu_lock(&c->mu); for (w = c->root_external_state_watcher.next; w != &c->root_external_state_watcher; w = w->next) { if (w->notify == notify) { grpc_connectivity_state_notify_on_state_change( - exec_ctx, &c->state_tracker, NULL, &w->closure); + exec_ctx, &c->state_tracker, nullptr, &w->closure); } } gpr_mu_unlock(&c->mu); } else { - w = (external_state_watcher *)gpr_malloc(sizeof(*w)); + w = (external_state_watcher*)gpr_malloc(sizeof(*w)); w->subchannel = c; w->pollset_set = interested_parties; w->notify = notify; GRPC_CLOSURE_INIT(&w->closure, on_external_state_watcher_done, w, grpc_schedule_on_exec_ctx); - if (interested_parties != NULL) { + if (interested_parties != nullptr) { grpc_pollset_set_add_pollset_set(exec_ctx, c->pollset_set, interested_parties); } @@ -522,18 +524,18 @@ void grpc_subchannel_notify_on_state_change( } void grpc_connected_subchannel_process_transport_op( - grpc_exec_ctx *exec_ctx, grpc_connected_subchannel *con, - grpc_transport_op *op) { - grpc_channel_stack *channel_stack = CHANNEL_STACK_FROM_CONNECTION(con); - grpc_channel_element *top_elem = grpc_channel_stack_element(channel_stack, 0); + grpc_exec_ctx* exec_ctx, grpc_connected_subchannel* con, + grpc_transport_op* op) { + grpc_channel_stack* channel_stack = CHANNEL_STACK_FROM_CONNECTION(con); + grpc_channel_element* top_elem = grpc_channel_stack_element(channel_stack, 0); top_elem->filter->start_transport_op(exec_ctx, top_elem, op); } -static void subchannel_on_child_state_changed(grpc_exec_ctx *exec_ctx, void *p, - grpc_error *error) { - state_watcher *sw = (state_watcher *)p; - grpc_subchannel *c = sw->subchannel; - gpr_mu *mu = &c->mu; +static void subchannel_on_child_state_changed(grpc_exec_ctx* exec_ctx, void* p, + grpc_error* error) { + state_watcher* sw = (state_watcher*)p; + grpc_subchannel* c = sw->subchannel; + gpr_mu* mu = &c->mu; gpr_mu_lock(mu); @@ -547,10 +549,10 @@ static void subchannel_on_child_state_changed(grpc_exec_ctx *exec_ctx, void *p, "reflect_child"); if (sw->connectivity_state != GRPC_CHANNEL_SHUTDOWN) { grpc_connected_subchannel_notify_on_state_change( - exec_ctx, GET_CONNECTED_SUBCHANNEL(c, no_barrier), NULL, + exec_ctx, GET_CONNECTED_SUBCHANNEL(c, no_barrier), nullptr, &sw->connectivity_state, &sw->closure); GRPC_SUBCHANNEL_WEAK_REF(c, "state_watcher"); - sw = NULL; + sw = nullptr; } gpr_mu_unlock(mu); @@ -558,13 +560,13 @@ static void subchannel_on_child_state_changed(grpc_exec_ctx *exec_ctx, void *p, gpr_free(sw); } -static void connected_subchannel_state_op(grpc_exec_ctx *exec_ctx, - grpc_connected_subchannel *con, - grpc_pollset_set *interested_parties, - grpc_connectivity_state *state, - grpc_closure *closure) { - grpc_transport_op *op = grpc_make_transport_op(NULL); - grpc_channel_element *elem; +static void connected_subchannel_state_op(grpc_exec_ctx* exec_ctx, + grpc_connected_subchannel* con, + grpc_pollset_set* interested_parties, + grpc_connectivity_state* state, + grpc_closure* closure) { + grpc_transport_op* op = grpc_make_transport_op(nullptr); + grpc_channel_element* elem; op->connectivity_state = state; op->on_connectivity_state_change = closure; op->bind_pollset_set = interested_parties; @@ -573,31 +575,31 @@ static void connected_subchannel_state_op(grpc_exec_ctx *exec_ctx, } void grpc_connected_subchannel_notify_on_state_change( - grpc_exec_ctx *exec_ctx, grpc_connected_subchannel *con, - grpc_pollset_set *interested_parties, grpc_connectivity_state *state, - grpc_closure *closure) { + grpc_exec_ctx* exec_ctx, grpc_connected_subchannel* con, + grpc_pollset_set* interested_parties, grpc_connectivity_state* state, + grpc_closure* closure) { connected_subchannel_state_op(exec_ctx, con, interested_parties, state, closure); } -void grpc_connected_subchannel_ping(grpc_exec_ctx *exec_ctx, - grpc_connected_subchannel *con, - grpc_closure *closure) { - grpc_transport_op *op = grpc_make_transport_op(NULL); - grpc_channel_element *elem; +void grpc_connected_subchannel_ping(grpc_exec_ctx* exec_ctx, + grpc_connected_subchannel* con, + grpc_closure* closure) { + grpc_transport_op* op = grpc_make_transport_op(nullptr); + grpc_channel_element* elem; op->send_ping = closure; elem = grpc_channel_stack_element(CHANNEL_STACK_FROM_CONNECTION(con), 0); elem->filter->start_transport_op(exec_ctx, elem, op); } -static bool publish_transport_locked(grpc_exec_ctx *exec_ctx, - grpc_subchannel *c) { - grpc_connected_subchannel *con; - grpc_channel_stack *stk; - state_watcher *sw_subchannel; +static bool publish_transport_locked(grpc_exec_ctx* exec_ctx, + grpc_subchannel* c) { + grpc_connected_subchannel* con; + grpc_channel_stack* stk; + state_watcher* sw_subchannel; /* construct channel stack */ - grpc_channel_stack_builder *builder = grpc_channel_stack_builder_create(); + grpc_channel_stack_builder* builder = grpc_channel_stack_builder_create(); grpc_channel_stack_builder_set_channel_arguments( exec_ctx, builder, c->connecting_result.channel_args); grpc_channel_stack_builder_set_transport(builder, @@ -608,8 +610,8 @@ static bool publish_transport_locked(grpc_exec_ctx *exec_ctx, grpc_channel_stack_builder_destroy(exec_ctx, builder); return false; } - grpc_error *error = grpc_channel_stack_builder_finish( - exec_ctx, builder, 0, 1, connection_destroy, NULL, (void **)&con); + grpc_error* error = grpc_channel_stack_builder_finish( + exec_ctx, builder, 0, 1, connection_destroy, nullptr, (void**)&con); if (error != GRPC_ERROR_NONE) { grpc_transport_destroy(exec_ctx, c->connecting_result.transport); gpr_log(GPR_ERROR, "error initializing subchannel stack: %s", @@ -621,7 +623,7 @@ static bool publish_transport_locked(grpc_exec_ctx *exec_ctx, memset(&c->connecting_result, 0, sizeof(c->connecting_result)); /* initialize state watcher */ - sw_subchannel = (state_watcher *)gpr_malloc(sizeof(*sw_subchannel)); + sw_subchannel = (state_watcher*)gpr_malloc(sizeof(*sw_subchannel)); sw_subchannel->subchannel = c; sw_subchannel->connectivity_state = GRPC_CHANNEL_READY; GRPC_CLOSURE_INIT(&sw_subchannel->closure, subchannel_on_child_state_changed, @@ -656,15 +658,15 @@ static bool publish_transport_locked(grpc_exec_ctx *exec_ctx, return true; } -static void subchannel_connected(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_subchannel *c = (grpc_subchannel *)arg; - grpc_channel_args *delete_channel_args = c->connecting_result.channel_args; +static void subchannel_connected(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_subchannel* c = (grpc_subchannel*)arg; + grpc_channel_args* delete_channel_args = c->connecting_result.channel_args; GRPC_SUBCHANNEL_WEAK_REF(c, "connected"); gpr_mu_lock(&c->mu); c->connecting = false; - if (c->connecting_result.transport != NULL && + if (c->connecting_result.transport != nullptr && publish_transport_locked(exec_ctx, c)) { /* do nothing, transport was published */ } else if (c->disconnected) { @@ -677,7 +679,7 @@ static void subchannel_connected(grpc_exec_ctx *exec_ctx, void *arg, GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE), "connect_failed"); - const char *errmsg = grpc_error_string(error); + const char* errmsg = grpc_error_string(error); gpr_log(GPR_INFO, "Connect failed: %s", errmsg); maybe_start_connecting_locked(exec_ctx, c); @@ -692,69 +694,69 @@ static void subchannel_connected(grpc_exec_ctx *exec_ctx, void *arg, * grpc_subchannel_call implementation */ -static void subchannel_call_destroy(grpc_exec_ctx *exec_ctx, void *call, - grpc_error *error) { - grpc_subchannel_call *c = (grpc_subchannel_call *)call; - GPR_ASSERT(c->schedule_closure_after_destroy != NULL); +static void subchannel_call_destroy(grpc_exec_ctx* exec_ctx, void* call, + grpc_error* error) { + grpc_subchannel_call* c = (grpc_subchannel_call*)call; + GPR_ASSERT(c->schedule_closure_after_destroy != nullptr); GPR_TIMER_BEGIN("grpc_subchannel_call_unref.destroy", 0); - grpc_connected_subchannel *connection = c->connection; - grpc_call_stack_destroy(exec_ctx, SUBCHANNEL_CALL_TO_CALL_STACK(c), NULL, + grpc_connected_subchannel* connection = c->connection; + grpc_call_stack_destroy(exec_ctx, SUBCHANNEL_CALL_TO_CALL_STACK(c), nullptr, c->schedule_closure_after_destroy); GRPC_CONNECTED_SUBCHANNEL_UNREF(exec_ctx, connection, "subchannel_call"); GPR_TIMER_END("grpc_subchannel_call_unref.destroy", 0); } -void grpc_subchannel_call_set_cleanup_closure(grpc_subchannel_call *call, - grpc_closure *closure) { - GPR_ASSERT(call->schedule_closure_after_destroy == NULL); - GPR_ASSERT(closure != NULL); +void grpc_subchannel_call_set_cleanup_closure(grpc_subchannel_call* call, + grpc_closure* closure) { + GPR_ASSERT(call->schedule_closure_after_destroy == nullptr); + GPR_ASSERT(closure != nullptr); call->schedule_closure_after_destroy = closure; } void grpc_subchannel_call_ref( - grpc_subchannel_call *c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { + grpc_subchannel_call* c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { GRPC_CALL_STACK_REF(SUBCHANNEL_CALL_TO_CALL_STACK(c), REF_REASON); } -void grpc_subchannel_call_unref(grpc_exec_ctx *exec_ctx, - grpc_subchannel_call *c +void grpc_subchannel_call_unref(grpc_exec_ctx* exec_ctx, + grpc_subchannel_call* c GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { GRPC_CALL_STACK_UNREF(exec_ctx, SUBCHANNEL_CALL_TO_CALL_STACK(c), REF_REASON); } -void grpc_subchannel_call_process_op(grpc_exec_ctx *exec_ctx, - grpc_subchannel_call *call, - grpc_transport_stream_op_batch *batch) { +void grpc_subchannel_call_process_op(grpc_exec_ctx* exec_ctx, + grpc_subchannel_call* call, + grpc_transport_stream_op_batch* batch) { GPR_TIMER_BEGIN("grpc_subchannel_call_process_op", 0); - grpc_call_stack *call_stack = SUBCHANNEL_CALL_TO_CALL_STACK(call); - grpc_call_element *top_elem = grpc_call_stack_element(call_stack, 0); + grpc_call_stack* call_stack = SUBCHANNEL_CALL_TO_CALL_STACK(call); + grpc_call_element* top_elem = grpc_call_stack_element(call_stack, 0); GRPC_CALL_LOG_OP(GPR_INFO, top_elem, batch); top_elem->filter->start_transport_stream_op_batch(exec_ctx, top_elem, batch); GPR_TIMER_END("grpc_subchannel_call_process_op", 0); } -grpc_connected_subchannel *grpc_subchannel_get_connected_subchannel( - grpc_subchannel *c) { +grpc_connected_subchannel* grpc_subchannel_get_connected_subchannel( + grpc_subchannel* c) { return GET_CONNECTED_SUBCHANNEL(c, acq); } -const grpc_subchannel_key *grpc_subchannel_get_key( - const grpc_subchannel *subchannel) { +const grpc_subchannel_key* grpc_subchannel_get_key( + const grpc_subchannel* subchannel) { return subchannel->key; } -grpc_error *grpc_connected_subchannel_create_call( - grpc_exec_ctx *exec_ctx, grpc_connected_subchannel *con, - const grpc_connected_subchannel_call_args *args, - grpc_subchannel_call **call) { - grpc_channel_stack *chanstk = CHANNEL_STACK_FROM_CONNECTION(con); - *call = (grpc_subchannel_call *)gpr_arena_alloc( +grpc_error* grpc_connected_subchannel_create_call( + grpc_exec_ctx* exec_ctx, grpc_connected_subchannel* con, + const grpc_connected_subchannel_call_args* args, + grpc_subchannel_call** call) { + grpc_channel_stack* chanstk = CHANNEL_STACK_FROM_CONNECTION(con); + *call = (grpc_subchannel_call*)gpr_arena_alloc( args->arena, sizeof(grpc_subchannel_call) + chanstk->call_stack_size); - grpc_call_stack *callstk = SUBCHANNEL_CALL_TO_CALL_STACK(*call); + grpc_call_stack* callstk = SUBCHANNEL_CALL_TO_CALL_STACK(*call); (*call)->connection = GRPC_CONNECTED_SUBCHANNEL_REF(con, "subchannel_call"); const grpc_call_element_args call_args = { callstk, /* call_stack */ - NULL, /* server_transport_data */ + nullptr, /* server_transport_data */ args->context, /* context */ args->path, /* path */ args->start_time, /* start_time */ @@ -762,10 +764,10 @@ grpc_error *grpc_connected_subchannel_create_call( args->arena, /* arena */ args->call_combiner /* call_combiner */ }; - grpc_error *error = grpc_call_stack_init( + grpc_error* error = grpc_call_stack_init( exec_ctx, chanstk, 1, subchannel_call_destroy, *call, &call_args); if (error != GRPC_ERROR_NONE) { - const char *error_string = grpc_error_string(error); + const char* error_string = grpc_error_string(error); gpr_log(GPR_ERROR, "error: %s", error_string); return error; } @@ -773,39 +775,39 @@ grpc_error *grpc_connected_subchannel_create_call( return GRPC_ERROR_NONE; } -grpc_call_stack *grpc_subchannel_call_get_call_stack( - grpc_subchannel_call *subchannel_call) { +grpc_call_stack* grpc_subchannel_call_get_call_stack( + grpc_subchannel_call* subchannel_call) { return SUBCHANNEL_CALL_TO_CALL_STACK(subchannel_call); } -static void grpc_uri_to_sockaddr(grpc_exec_ctx *exec_ctx, const char *uri_str, - grpc_resolved_address *addr) { - grpc_uri *uri = grpc_uri_parse(exec_ctx, uri_str, 0 /* suppress_errors */); - GPR_ASSERT(uri != NULL); +static void grpc_uri_to_sockaddr(grpc_exec_ctx* exec_ctx, const char* uri_str, + grpc_resolved_address* addr) { + grpc_uri* uri = grpc_uri_parse(exec_ctx, uri_str, 0 /* suppress_errors */); + GPR_ASSERT(uri != nullptr); if (!grpc_parse_uri(uri, addr)) memset(addr, 0, sizeof(*addr)); grpc_uri_destroy(uri); } -void grpc_get_subchannel_address_arg(grpc_exec_ctx *exec_ctx, - const grpc_channel_args *args, - grpc_resolved_address *addr) { - const char *addr_uri_str = grpc_get_subchannel_address_uri_arg(args); +void grpc_get_subchannel_address_arg(grpc_exec_ctx* exec_ctx, + const grpc_channel_args* args, + grpc_resolved_address* addr) { + const char* addr_uri_str = grpc_get_subchannel_address_uri_arg(args); memset(addr, 0, sizeof(*addr)); if (*addr_uri_str != '\0') { grpc_uri_to_sockaddr(exec_ctx, addr_uri_str, addr); } } -const char *grpc_get_subchannel_address_uri_arg(const grpc_channel_args *args) { - const grpc_arg *addr_arg = +const char* grpc_get_subchannel_address_uri_arg(const grpc_channel_args* args) { + const grpc_arg* addr_arg = grpc_channel_args_find(args, GRPC_ARG_SUBCHANNEL_ADDRESS); - GPR_ASSERT(addr_arg != NULL); // Should have been set by LB policy. + GPR_ASSERT(addr_arg != nullptr); // Should have been set by LB policy. GPR_ASSERT(addr_arg->type == GRPC_ARG_STRING); return addr_arg->value.string; } -grpc_arg grpc_create_subchannel_address_arg(const grpc_resolved_address *addr) { +grpc_arg grpc_create_subchannel_address_arg(const grpc_resolved_address* addr) { return grpc_channel_arg_string_create( - (char *)GRPC_ARG_SUBCHANNEL_ADDRESS, + (char*)GRPC_ARG_SUBCHANNEL_ADDRESS, addr->len > 0 ? grpc_sockaddr_to_uri(addr) : gpr_strdup("")); } diff --git a/src/core/ext/filters/client_channel/subchannel.h b/src/core/ext/filters/client_channel/subchannel.h index 1cd73f3ff45..1f326fc1d20 100644 --- a/src/core/ext/filters/client_channel/subchannel.h +++ b/src/core/ext/filters/client_channel/subchannel.h @@ -26,10 +26,6 @@ #include "src/core/lib/transport/connectivity_state.h" #include "src/core/lib/transport/metadata.h" -#ifdef __cplusplus -extern "C" { -#endif - // Channel arg containing a grpc_resolved_address to connect to. #define GRPC_ARG_SUBCHANNEL_ADDRESS "grpc.subchannel_address" @@ -79,121 +75,117 @@ typedef struct grpc_subchannel_key grpc_subchannel_key; #define GRPC_SUBCHANNEL_REF_EXTRA_ARGS #endif -grpc_subchannel *grpc_subchannel_ref( - grpc_subchannel *channel GRPC_SUBCHANNEL_REF_EXTRA_ARGS); -grpc_subchannel *grpc_subchannel_ref_from_weak_ref( - grpc_subchannel *channel GRPC_SUBCHANNEL_REF_EXTRA_ARGS); -void grpc_subchannel_unref(grpc_exec_ctx *exec_ctx, - grpc_subchannel *channel +grpc_subchannel* grpc_subchannel_ref( + grpc_subchannel* channel GRPC_SUBCHANNEL_REF_EXTRA_ARGS); +grpc_subchannel* grpc_subchannel_ref_from_weak_ref( + grpc_subchannel* channel GRPC_SUBCHANNEL_REF_EXTRA_ARGS); +void grpc_subchannel_unref(grpc_exec_ctx* exec_ctx, + grpc_subchannel* channel GRPC_SUBCHANNEL_REF_EXTRA_ARGS); -grpc_subchannel *grpc_subchannel_weak_ref( - grpc_subchannel *channel GRPC_SUBCHANNEL_REF_EXTRA_ARGS); -void grpc_subchannel_weak_unref(grpc_exec_ctx *exec_ctx, - grpc_subchannel *channel +grpc_subchannel* grpc_subchannel_weak_ref( + grpc_subchannel* channel GRPC_SUBCHANNEL_REF_EXTRA_ARGS); +void grpc_subchannel_weak_unref(grpc_exec_ctx* exec_ctx, + grpc_subchannel* channel GRPC_SUBCHANNEL_REF_EXTRA_ARGS); -grpc_connected_subchannel *grpc_connected_subchannel_ref( - grpc_connected_subchannel *channel GRPC_SUBCHANNEL_REF_EXTRA_ARGS); -void grpc_connected_subchannel_unref(grpc_exec_ctx *exec_ctx, - grpc_connected_subchannel *channel +grpc_connected_subchannel* grpc_connected_subchannel_ref( + grpc_connected_subchannel* channel GRPC_SUBCHANNEL_REF_EXTRA_ARGS); +void grpc_connected_subchannel_unref(grpc_exec_ctx* exec_ctx, + grpc_connected_subchannel* channel GRPC_SUBCHANNEL_REF_EXTRA_ARGS); void grpc_subchannel_call_ref( - grpc_subchannel_call *call GRPC_SUBCHANNEL_REF_EXTRA_ARGS); -void grpc_subchannel_call_unref(grpc_exec_ctx *exec_ctx, - grpc_subchannel_call *call + grpc_subchannel_call* call GRPC_SUBCHANNEL_REF_EXTRA_ARGS); +void grpc_subchannel_call_unref(grpc_exec_ctx* exec_ctx, + grpc_subchannel_call* call GRPC_SUBCHANNEL_REF_EXTRA_ARGS); /** construct a subchannel call */ typedef struct { - grpc_polling_entity *pollent; + grpc_polling_entity* pollent; grpc_slice path; gpr_timespec start_time; grpc_millis deadline; - gpr_arena *arena; - grpc_call_context_element *context; - grpc_call_combiner *call_combiner; + gpr_arena* arena; + grpc_call_context_element* context; + grpc_call_combiner* call_combiner; } grpc_connected_subchannel_call_args; -grpc_error *grpc_connected_subchannel_create_call( - grpc_exec_ctx *exec_ctx, grpc_connected_subchannel *connected_subchannel, - const grpc_connected_subchannel_call_args *args, - grpc_subchannel_call **subchannel_call); +grpc_error* grpc_connected_subchannel_create_call( + grpc_exec_ctx* exec_ctx, grpc_connected_subchannel* connected_subchannel, + const grpc_connected_subchannel_call_args* args, + grpc_subchannel_call** subchannel_call); /** process a transport level op */ void grpc_connected_subchannel_process_transport_op( - grpc_exec_ctx *exec_ctx, grpc_connected_subchannel *subchannel, - grpc_transport_op *op); + grpc_exec_ctx* exec_ctx, grpc_connected_subchannel* subchannel, + grpc_transport_op* op); /** poll the current connectivity state of a channel */ grpc_connectivity_state grpc_subchannel_check_connectivity( - grpc_subchannel *channel, grpc_error **error); + grpc_subchannel* channel, grpc_error** error); /** Calls notify when the connectivity state of a channel becomes different from *state. Updates *state with the new state of the channel. */ void grpc_subchannel_notify_on_state_change( - grpc_exec_ctx *exec_ctx, grpc_subchannel *channel, - grpc_pollset_set *interested_parties, grpc_connectivity_state *state, - grpc_closure *notify); + grpc_exec_ctx* exec_ctx, grpc_subchannel* channel, + grpc_pollset_set* interested_parties, grpc_connectivity_state* state, + grpc_closure* notify); void grpc_connected_subchannel_notify_on_state_change( - grpc_exec_ctx *exec_ctx, grpc_connected_subchannel *channel, - grpc_pollset_set *interested_parties, grpc_connectivity_state *state, - grpc_closure *notify); -void grpc_connected_subchannel_ping(grpc_exec_ctx *exec_ctx, - grpc_connected_subchannel *channel, - grpc_closure *notify); + grpc_exec_ctx* exec_ctx, grpc_connected_subchannel* channel, + grpc_pollset_set* interested_parties, grpc_connectivity_state* state, + grpc_closure* notify); +void grpc_connected_subchannel_ping(grpc_exec_ctx* exec_ctx, + grpc_connected_subchannel* channel, + grpc_closure* notify); /** retrieve the grpc_connected_subchannel - or NULL if called before the subchannel becomes connected */ -grpc_connected_subchannel *grpc_subchannel_get_connected_subchannel( - grpc_subchannel *subchannel); +grpc_connected_subchannel* grpc_subchannel_get_connected_subchannel( + grpc_subchannel* subchannel); /** return the subchannel index key for \a subchannel */ -const grpc_subchannel_key *grpc_subchannel_get_key( - const grpc_subchannel *subchannel); +const grpc_subchannel_key* grpc_subchannel_get_key( + const grpc_subchannel* subchannel); /** continue processing a transport op */ -void grpc_subchannel_call_process_op(grpc_exec_ctx *exec_ctx, - grpc_subchannel_call *subchannel_call, - grpc_transport_stream_op_batch *op); +void grpc_subchannel_call_process_op(grpc_exec_ctx* exec_ctx, + grpc_subchannel_call* subchannel_call, + grpc_transport_stream_op_batch* op); /** Must be called once per call. Sets the 'then_schedule_closure' argument for call stack destruction. */ void grpc_subchannel_call_set_cleanup_closure( - grpc_subchannel_call *subchannel_call, grpc_closure *closure); + grpc_subchannel_call* subchannel_call, grpc_closure* closure); -grpc_call_stack *grpc_subchannel_call_get_call_stack( - grpc_subchannel_call *subchannel_call); +grpc_call_stack* grpc_subchannel_call_get_call_stack( + grpc_subchannel_call* subchannel_call); struct grpc_subchannel_args { /* When updating this struct, also update subchannel_index.c */ /** Channel filters for this channel - wrapped factories will likely want to mutate this */ - const grpc_channel_filter **filters; + const grpc_channel_filter** filters; /** The number of filters in the above array */ size_t filter_count; /** Channel arguments to be supplied to the newly created channel */ - const grpc_channel_args *args; + const grpc_channel_args* args; }; /** create a subchannel given a connector */ -grpc_subchannel *grpc_subchannel_create(grpc_exec_ctx *exec_ctx, - grpc_connector *connector, - const grpc_subchannel_args *args); +grpc_subchannel* grpc_subchannel_create(grpc_exec_ctx* exec_ctx, + grpc_connector* connector, + const grpc_subchannel_args* args); /// Sets \a addr from \a args. -void grpc_get_subchannel_address_arg(grpc_exec_ctx *exec_ctx, - const grpc_channel_args *args, - grpc_resolved_address *addr); +void grpc_get_subchannel_address_arg(grpc_exec_ctx* exec_ctx, + const grpc_channel_args* args, + grpc_resolved_address* addr); /// Returns the URI string for the address to connect to. -const char *grpc_get_subchannel_address_uri_arg(const grpc_channel_args *args); +const char* grpc_get_subchannel_address_uri_arg(const grpc_channel_args* args); /// Returns a new channel arg encoding the subchannel address as a string. /// Caller is responsible for freeing the string. -grpc_arg grpc_create_subchannel_address_arg(const grpc_resolved_address *addr); - -#ifdef __cplusplus -} -#endif +grpc_arg grpc_create_subchannel_address_arg(const grpc_resolved_address* addr); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_H */ diff --git a/src/core/ext/filters/client_channel/subchannel_index.cc b/src/core/ext/filters/client_channel/subchannel_index.cc index 1f466ec0b8f..1624643d0b4 100644 --- a/src/core/ext/filters/client_channel/subchannel_index.cc +++ b/src/core/ext/filters/client_channel/subchannel_index.cc @@ -42,34 +42,34 @@ struct grpc_subchannel_key { static bool g_force_creation = false; -static grpc_subchannel_key *create_key( - const grpc_subchannel_args *args, - grpc_channel_args *(*copy_channel_args)(const grpc_channel_args *args)) { - grpc_subchannel_key *k = (grpc_subchannel_key *)gpr_malloc(sizeof(*k)); +static grpc_subchannel_key* create_key( + const grpc_subchannel_args* args, + grpc_channel_args* (*copy_channel_args)(const grpc_channel_args* args)) { + grpc_subchannel_key* k = (grpc_subchannel_key*)gpr_malloc(sizeof(*k)); k->args.filter_count = args->filter_count; if (k->args.filter_count > 0) { - k->args.filters = (const grpc_channel_filter **)gpr_malloc( + k->args.filters = (const grpc_channel_filter**)gpr_malloc( sizeof(*k->args.filters) * k->args.filter_count); - memcpy((grpc_channel_filter *)k->args.filters, args->filters, + memcpy((grpc_channel_filter*)k->args.filters, args->filters, sizeof(*k->args.filters) * k->args.filter_count); } else { - k->args.filters = NULL; + k->args.filters = nullptr; } k->args.args = copy_channel_args(args->args); return k; } -grpc_subchannel_key *grpc_subchannel_key_create( - const grpc_subchannel_args *args) { +grpc_subchannel_key* grpc_subchannel_key_create( + const grpc_subchannel_args* args) { return create_key(args, grpc_channel_args_normalize); } -static grpc_subchannel_key *subchannel_key_copy(grpc_subchannel_key *k) { +static grpc_subchannel_key* subchannel_key_copy(grpc_subchannel_key* k) { return create_key(&k->args, grpc_channel_args_copy); } -int grpc_subchannel_key_compare(const grpc_subchannel_key *a, - const grpc_subchannel_key *b) { +int grpc_subchannel_key_compare(const grpc_subchannel_key* a, + const grpc_subchannel_key* b) { if (g_force_creation) return false; int c = GPR_ICMP(a->args.filter_count, b->args.filter_count); if (c != 0) return c; @@ -81,35 +81,34 @@ int grpc_subchannel_key_compare(const grpc_subchannel_key *a, return grpc_channel_args_compare(a->args.args, b->args.args); } -void grpc_subchannel_key_destroy(grpc_exec_ctx *exec_ctx, - grpc_subchannel_key *k) { - gpr_free((grpc_channel_args *)k->args.filters); - grpc_channel_args_destroy(exec_ctx, (grpc_channel_args *)k->args.args); +void grpc_subchannel_key_destroy(grpc_exec_ctx* exec_ctx, + grpc_subchannel_key* k) { + gpr_free((grpc_channel_args*)k->args.filters); + grpc_channel_args_destroy(exec_ctx, (grpc_channel_args*)k->args.args); gpr_free(k); } -static void sck_avl_destroy(void *p, void *user_data) { - grpc_exec_ctx *exec_ctx = (grpc_exec_ctx *)user_data; - grpc_subchannel_key_destroy(exec_ctx, (grpc_subchannel_key *)p); +static void sck_avl_destroy(void* p, void* user_data) { + grpc_exec_ctx* exec_ctx = (grpc_exec_ctx*)user_data; + grpc_subchannel_key_destroy(exec_ctx, (grpc_subchannel_key*)p); } -static void *sck_avl_copy(void *p, void *unused) { - return subchannel_key_copy((grpc_subchannel_key *)p); +static void* sck_avl_copy(void* p, void* unused) { + return subchannel_key_copy((grpc_subchannel_key*)p); } -static long sck_avl_compare(void *a, void *b, void *unused) { - return grpc_subchannel_key_compare((grpc_subchannel_key *)a, - (grpc_subchannel_key *)b); +static long sck_avl_compare(void* a, void* b, void* unused) { + return grpc_subchannel_key_compare((grpc_subchannel_key*)a, + (grpc_subchannel_key*)b); } -static void scv_avl_destroy(void *p, void *user_data) { - grpc_exec_ctx *exec_ctx = (grpc_exec_ctx *)user_data; - GRPC_SUBCHANNEL_WEAK_UNREF(exec_ctx, (grpc_subchannel *)p, - "subchannel_index"); +static void scv_avl_destroy(void* p, void* user_data) { + grpc_exec_ctx* exec_ctx = (grpc_exec_ctx*)user_data; + GRPC_SUBCHANNEL_WEAK_UNREF(exec_ctx, (grpc_subchannel*)p, "subchannel_index"); } -static void *scv_avl_copy(void *p, void *unused) { - GRPC_SUBCHANNEL_WEAK_REF((grpc_subchannel *)p, "subchannel_index"); +static void* scv_avl_copy(void* p, void* unused) { + GRPC_SUBCHANNEL_WEAK_REF((grpc_subchannel*)p, "subchannel_index"); return p; } @@ -145,28 +144,28 @@ void grpc_subchannel_index_unref(void) { void grpc_subchannel_index_ref(void) { gpr_ref_non_zero(&g_refcount); } -grpc_subchannel *grpc_subchannel_index_find(grpc_exec_ctx *exec_ctx, - grpc_subchannel_key *key) { +grpc_subchannel* grpc_subchannel_index_find(grpc_exec_ctx* exec_ctx, + grpc_subchannel_key* key) { // Lock, and take a reference to the subchannel index. // We don't need to do the search under a lock as avl's are immutable. gpr_mu_lock(&g_mu); gpr_avl index = gpr_avl_ref(g_subchannel_index, exec_ctx); gpr_mu_unlock(&g_mu); - grpc_subchannel *c = GRPC_SUBCHANNEL_REF_FROM_WEAK_REF( - (grpc_subchannel *)gpr_avl_get(index, key, exec_ctx), "index_find"); + grpc_subchannel* c = GRPC_SUBCHANNEL_REF_FROM_WEAK_REF( + (grpc_subchannel*)gpr_avl_get(index, key, exec_ctx), "index_find"); gpr_avl_unref(index, exec_ctx); return c; } -grpc_subchannel *grpc_subchannel_index_register(grpc_exec_ctx *exec_ctx, - grpc_subchannel_key *key, - grpc_subchannel *constructed) { - grpc_subchannel *c = NULL; - bool need_to_unref_constructed; +grpc_subchannel* grpc_subchannel_index_register(grpc_exec_ctx* exec_ctx, + grpc_subchannel_key* key, + grpc_subchannel* constructed) { + grpc_subchannel* c = nullptr; + bool need_to_unref_constructed = false; - while (c == NULL) { + while (c == nullptr) { need_to_unref_constructed = false; // Compare and swap loop: @@ -176,11 +175,11 @@ grpc_subchannel *grpc_subchannel_index_register(grpc_exec_ctx *exec_ctx, gpr_mu_unlock(&g_mu); // - Check to see if a subchannel already exists - c = (grpc_subchannel *)gpr_avl_get(index, key, exec_ctx); - if (c != NULL) { + c = (grpc_subchannel*)gpr_avl_get(index, key, exec_ctx); + if (c != nullptr) { c = GRPC_SUBCHANNEL_REF_FROM_WEAK_REF(c, "index_register"); } - if (c != NULL) { + if (c != nullptr) { // yes -> we're done need_to_unref_constructed = true; } else { @@ -211,9 +210,9 @@ grpc_subchannel *grpc_subchannel_index_register(grpc_exec_ctx *exec_ctx, return c; } -void grpc_subchannel_index_unregister(grpc_exec_ctx *exec_ctx, - grpc_subchannel_key *key, - grpc_subchannel *constructed) { +void grpc_subchannel_index_unregister(grpc_exec_ctx* exec_ctx, + grpc_subchannel_key* key, + grpc_subchannel* constructed) { bool done = false; while (!done) { // Compare and swap loop: @@ -224,7 +223,7 @@ void grpc_subchannel_index_unregister(grpc_exec_ctx *exec_ctx, // Check to see if this key still refers to the previously // registered subchannel - grpc_subchannel *c = (grpc_subchannel *)gpr_avl_get(index, key, exec_ctx); + grpc_subchannel* c = (grpc_subchannel*)gpr_avl_get(index, key, exec_ctx); if (c != constructed) { gpr_avl_unref(index, exec_ctx); break; diff --git a/src/core/ext/filters/client_channel/subchannel_index.h b/src/core/ext/filters/client_channel/subchannel_index.h index 05c3878379f..6a4d06ef8ff 100644 --- a/src/core/ext/filters/client_channel/subchannel_index.h +++ b/src/core/ext/filters/client_channel/subchannel_index.h @@ -21,42 +21,38 @@ #include "src/core/ext/filters/client_channel/subchannel.h" -#ifdef __cplusplus -extern "C" { -#endif - /** \file Provides an index of active subchannels so that they can be shared amongst channels */ /** Create a key that can be used to uniquely identify a subchannel */ -grpc_subchannel_key *grpc_subchannel_key_create( - const grpc_subchannel_args *args); +grpc_subchannel_key* grpc_subchannel_key_create( + const grpc_subchannel_args* args); /** Destroy a subchannel key */ -void grpc_subchannel_key_destroy(grpc_exec_ctx *exec_ctx, - grpc_subchannel_key *key); +void grpc_subchannel_key_destroy(grpc_exec_ctx* exec_ctx, + grpc_subchannel_key* key); /** Given a subchannel key, find the subchannel registered for it. Returns NULL if no such channel exists. Thread-safe. */ -grpc_subchannel *grpc_subchannel_index_find(grpc_exec_ctx *exec_ctx, - grpc_subchannel_key *key); +grpc_subchannel* grpc_subchannel_index_find(grpc_exec_ctx* exec_ctx, + grpc_subchannel_key* key); /** Register a subchannel against a key. Takes ownership of \a constructed. Returns the registered subchannel. This may be different from \a constructed in the case of a registration race. */ -grpc_subchannel *grpc_subchannel_index_register(grpc_exec_ctx *exec_ctx, - grpc_subchannel_key *key, - grpc_subchannel *constructed); +grpc_subchannel* grpc_subchannel_index_register(grpc_exec_ctx* exec_ctx, + grpc_subchannel_key* key, + grpc_subchannel* constructed); /** Remove \a constructed as the registered subchannel for \a key. */ -void grpc_subchannel_index_unregister(grpc_exec_ctx *exec_ctx, - grpc_subchannel_key *key, - grpc_subchannel *constructed); +void grpc_subchannel_index_unregister(grpc_exec_ctx* exec_ctx, + grpc_subchannel_key* key, + grpc_subchannel* constructed); -int grpc_subchannel_key_compare(const grpc_subchannel_key *a, - const grpc_subchannel_key *b); +int grpc_subchannel_key_compare(const grpc_subchannel_key* a, + const grpc_subchannel_key* b); /** Initialize the subchannel index (global) */ void grpc_subchannel_index_init(void); @@ -82,8 +78,4 @@ void grpc_subchannel_index_unref(void); * force_creation set. */ void grpc_subchannel_index_test_only_set_force_creation(bool force_creation); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_INDEX_H */ diff --git a/src/core/ext/filters/client_channel/uri_parser.cc b/src/core/ext/filters/client_channel/uri_parser.cc index fb4fb8e694c..b76dcbe4e3b 100644 --- a/src/core/ext/filters/client_channel/uri_parser.cc +++ b/src/core/ext/filters/client_channel/uri_parser.cc @@ -34,9 +34,9 @@ /** a size_t default value... maps to all 1's */ #define NOT_SET (~(size_t)0) -static grpc_uri *bad_uri(const char *uri_text, size_t pos, const char *section, +static grpc_uri* bad_uri(const char* uri_text, size_t pos, const char* section, bool suppress_errors) { - char *line_prefix; + char* line_prefix; size_t pfx_len; if (!suppress_errors) { @@ -45,24 +45,26 @@ static grpc_uri *bad_uri(const char *uri_text, size_t pos, const char *section, gpr_log(GPR_ERROR, "%s%s'", line_prefix, uri_text); gpr_free(line_prefix); - line_prefix = (char *)gpr_malloc(pfx_len + 1); + line_prefix = (char*)gpr_malloc(pfx_len + 1); memset(line_prefix, ' ', pfx_len); line_prefix[pfx_len] = 0; gpr_log(GPR_ERROR, "%s^ here", line_prefix); gpr_free(line_prefix); } - return NULL; + return nullptr; } /** Returns a copy of percent decoded \a src[begin, end) */ -static char *decode_and_copy_component(grpc_exec_ctx *exec_ctx, const char *src, +static char* decode_and_copy_component(grpc_exec_ctx* exec_ctx, const char* src, size_t begin, size_t end) { grpc_slice component = - grpc_slice_from_copied_buffer(src + begin, end - begin); + (begin == NOT_SET || end == NOT_SET) + ? grpc_empty_slice() + : grpc_slice_from_copied_buffer(src + begin, end - begin); grpc_slice decoded_component = grpc_permissive_percent_decode_slice(component); - char *out = grpc_dump_slice(decoded_component, GPR_DUMP_ASCII); + char* out = grpc_dump_slice(decoded_component, GPR_DUMP_ASCII); grpc_slice_unref_internal(exec_ctx, component); grpc_slice_unref_internal(exec_ctx, decoded_component); return out; @@ -76,7 +78,7 @@ static bool valid_hex(char c) { /** Returns how many chars to advance if \a uri_text[i] begins a valid \a pchar * production. If \a uri_text[i] introduces an invalid \a pchar (such as percent * sign not followed by two hex digits), NOT_SET is returned. */ -static size_t parse_pchar(const char *uri_text, size_t i) { +static size_t parse_pchar(const char* uri_text, size_t i) { /* pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG @@ -118,7 +120,7 @@ static size_t parse_pchar(const char *uri_text, size_t i) { } /* *( pchar / "?" / "/" ) */ -static int parse_fragment_or_query(const char *uri_text, size_t *i) { +static int parse_fragment_or_query(const char* uri_text, size_t* i) { char c; while ((c = uri_text[*i]) != 0) { const size_t advance = parse_pchar(uri_text, *i); /* pchar */ @@ -143,13 +145,13 @@ static int parse_fragment_or_query(const char *uri_text, size_t *i) { return 1; } -static void parse_query_parts(grpc_uri *uri) { - static const char *QUERY_PARTS_SEPARATOR = "&"; - static const char *QUERY_PARTS_VALUE_SEPARATOR = "="; - GPR_ASSERT(uri->query != NULL); +static void parse_query_parts(grpc_uri* uri) { + static const char* QUERY_PARTS_SEPARATOR = "&"; + static const char* QUERY_PARTS_VALUE_SEPARATOR = "="; + GPR_ASSERT(uri->query != nullptr); if (uri->query[0] == '\0') { - uri->query_parts = NULL; - uri->query_parts_values = NULL; + uri->query_parts = nullptr; + uri->query_parts_values = nullptr; uri->num_query_parts = 0; return; } @@ -157,11 +159,11 @@ static void parse_query_parts(grpc_uri *uri) { gpr_string_split(uri->query, QUERY_PARTS_SEPARATOR, &uri->query_parts, &uri->num_query_parts); uri->query_parts_values = - (char **)gpr_malloc(uri->num_query_parts * sizeof(char **)); + (char**)gpr_malloc(uri->num_query_parts * sizeof(char**)); for (size_t i = 0; i < uri->num_query_parts; i++) { - char **query_param_parts; + char** query_param_parts; size_t num_query_param_parts; - char *full = uri->query_parts[i]; + char* full = uri->query_parts[i]; gpr_string_split(full, QUERY_PARTS_VALUE_SEPARATOR, &query_param_parts, &num_query_param_parts); GPR_ASSERT(num_query_param_parts > 0); @@ -172,7 +174,7 @@ static void parse_query_parts(grpc_uri *uri) { * be included, even if they include the separator. */ uri->query_parts_values[i] = query_param_parts[1]; } else { - uri->query_parts_values[i] = NULL; + uri->query_parts_values[i] = nullptr; } for (size_t j = 2; j < num_query_param_parts; j++) { gpr_free(query_param_parts[j]); @@ -182,9 +184,9 @@ static void parse_query_parts(grpc_uri *uri) { } } -grpc_uri *grpc_uri_parse(grpc_exec_ctx *exec_ctx, const char *uri_text, +grpc_uri* grpc_uri_parse(grpc_exec_ctx* exec_ctx, const char* uri_text, bool suppress_errors) { - grpc_uri *uri; + grpc_uri* uri; size_t scheme_begin = 0; size_t scheme_end = NOT_SET; size_t authority_begin = NOT_SET; @@ -270,7 +272,7 @@ grpc_uri *grpc_uri_parse(grpc_exec_ctx *exec_ctx, const char *uri_text, fragment_end = i; } - uri = (grpc_uri *)gpr_zalloc(sizeof(*uri)); + uri = (grpc_uri*)gpr_zalloc(sizeof(*uri)); uri->scheme = decode_and_copy_component(exec_ctx, uri_text, scheme_begin, scheme_end); uri->authority = decode_and_copy_component(exec_ctx, uri_text, @@ -286,19 +288,19 @@ grpc_uri *grpc_uri_parse(grpc_exec_ctx *exec_ctx, const char *uri_text, return uri; } -const char *grpc_uri_get_query_arg(const grpc_uri *uri, const char *key) { - GPR_ASSERT(key != NULL); - if (key[0] == '\0') return NULL; +const char* grpc_uri_get_query_arg(const grpc_uri* uri, const char* key) { + GPR_ASSERT(key != nullptr); + if (key[0] == '\0') return nullptr; for (size_t i = 0; i < uri->num_query_parts; ++i) { if (0 == strcmp(key, uri->query_parts[i])) { return uri->query_parts_values[i]; } } - return NULL; + return nullptr; } -void grpc_uri_destroy(grpc_uri *uri) { +void grpc_uri_destroy(grpc_uri* uri) { if (!uri) return; gpr_free(uri->scheme); gpr_free(uri->authority); diff --git a/src/core/ext/filters/client_channel/uri_parser.h b/src/core/ext/filters/client_channel/uri_parser.h index e78da5928b6..84752905e8f 100644 --- a/src/core/ext/filters/client_channel/uri_parser.h +++ b/src/core/ext/filters/client_channel/uri_parser.h @@ -22,37 +22,29 @@ #include #include "src/core/lib/iomgr/exec_ctx.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct { - char *scheme; - char *authority; - char *path; - char *query; + char* scheme; + char* authority; + char* path; + char* query; /** Query substrings separated by '&' */ - char **query_parts; + char** query_parts; /** Number of elements in \a query_parts and \a query_parts_values */ size_t num_query_parts; /** Split each query part by '='. NULL if not present. */ - char **query_parts_values; - char *fragment; + char** query_parts_values; + char* fragment; } grpc_uri; /** parse a uri, return NULL on failure */ -grpc_uri *grpc_uri_parse(grpc_exec_ctx *exec_ctx, const char *uri_text, +grpc_uri* grpc_uri_parse(grpc_exec_ctx* exec_ctx, const char* uri_text, bool suppress_errors); /** return the part of a query string after the '=' in "?key=xxx&...", or NULL * if key is not present */ -const char *grpc_uri_get_query_arg(const grpc_uri *uri, const char *key); +const char* grpc_uri_get_query_arg(const grpc_uri* uri, const char* key); /** destroy a uri */ -void grpc_uri_destroy(grpc_uri *uri); - -#ifdef __cplusplus -} -#endif +void grpc_uri_destroy(grpc_uri* uri); #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_URI_PARSER_H */ diff --git a/src/core/ext/filters/deadline/deadline_filter.cc b/src/core/ext/filters/deadline/deadline_filter.cc index dc194ec0684..5db7584a59d 100644 --- a/src/core/ext/filters/deadline/deadline_filter.cc +++ b/src/core/ext/filters/deadline/deadline_filter.cc @@ -91,7 +91,7 @@ static void start_timer_if_needed(grpc_exec_ctx* exec_ctx, return; } grpc_deadline_state* deadline_state = (grpc_deadline_state*)elem->call_data; - grpc_closure* closure = NULL; + grpc_closure* closure = nullptr; switch (deadline_state->timer_state) { case GRPC_DEADLINE_STATE_PENDING: // Note: We do not start the timer if there is already a timer @@ -111,7 +111,7 @@ static void start_timer_if_needed(grpc_exec_ctx* exec_ctx, elem, grpc_schedule_on_exec_ctx); break; } - GPR_ASSERT(closure != NULL); + GPR_ASSERT(closure != nullptr); GRPC_CALL_STACK_REF(deadline_state->call_stack, "deadline_timer"); grpc_timer_init(exec_ctx, &deadline_state->timer, deadline, closure); } @@ -378,11 +378,11 @@ static bool maybe_add_deadline_filter(grpc_exec_ctx* exec_ctx, return grpc_deadline_checking_enabled( grpc_channel_stack_builder_get_channel_arguments(builder)) ? grpc_channel_stack_builder_prepend_filter( - builder, (const grpc_channel_filter*)arg, NULL, NULL) + builder, (const grpc_channel_filter*)arg, nullptr, nullptr) : true; } -extern "C" void grpc_deadline_filter_init(void) { +void grpc_deadline_filter_init(void) { grpc_channel_init_register_stage( GRPC_CLIENT_DIRECT_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, maybe_add_deadline_filter, (void*)&grpc_client_deadline_filter); @@ -391,4 +391,4 @@ extern "C" void grpc_deadline_filter_init(void) { maybe_add_deadline_filter, (void*)&grpc_server_deadline_filter); } -extern "C" void grpc_deadline_filter_shutdown(void) {} +void grpc_deadline_filter_shutdown(void) {} diff --git a/src/core/ext/filters/deadline/deadline_filter.h b/src/core/ext/filters/deadline/deadline_filter.h index e665dc53ee3..8d835d03820 100644 --- a/src/core/ext/filters/deadline/deadline_filter.h +++ b/src/core/ext/filters/deadline/deadline_filter.h @@ -20,10 +20,6 @@ #include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/iomgr/timer.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef enum grpc_deadline_timer_state { GRPC_DEADLINE_STATE_INITIAL, GRPC_DEADLINE_STATE_PENDING, @@ -94,8 +90,4 @@ bool grpc_deadline_checking_enabled(const grpc_channel_args* args); extern const grpc_channel_filter grpc_client_deadline_filter; extern const grpc_channel_filter grpc_server_deadline_filter; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_DEADLINE_DEADLINE_FILTER_H */ diff --git a/src/core/ext/filters/http/client/http_client_filter.cc b/src/core/ext/filters/http/client/http_client_filter.cc index 6208089f2ec..a625369b029 100644 --- a/src/core/ext/filters/http/client/http_client_filter.cc +++ b/src/core/ext/filters/http/client/http_client_filter.cc @@ -36,7 +36,7 @@ static const size_t kMaxPayloadSizeForGet = 2048; typedef struct call_data { - grpc_call_combiner *call_combiner; + grpc_call_combiner* call_combiner; // State for handling send_initial_metadata ops. grpc_linked_mdelem method; grpc_linked_mdelem scheme; @@ -45,20 +45,20 @@ typedef struct call_data { grpc_linked_mdelem content_type; grpc_linked_mdelem user_agent; // State for handling recv_initial_metadata ops. - grpc_metadata_batch *recv_initial_metadata; - grpc_closure *original_recv_initial_metadata_ready; + grpc_metadata_batch* recv_initial_metadata; + grpc_closure* original_recv_initial_metadata_ready; grpc_closure recv_initial_metadata_ready; // State for handling recv_trailing_metadata ops. - grpc_metadata_batch *recv_trailing_metadata; - grpc_closure *original_recv_trailing_metadata_on_complete; + grpc_metadata_batch* recv_trailing_metadata; + grpc_closure* original_recv_trailing_metadata_on_complete; grpc_closure recv_trailing_metadata_on_complete; // State for handling send_message ops. - grpc_transport_stream_op_batch *send_message_batch; + grpc_transport_stream_op_batch* send_message_batch; size_t send_message_bytes_read; grpc_byte_stream_cache send_message_cache; grpc_caching_byte_stream send_message_caching_stream; grpc_closure on_send_message_next_done; - grpc_closure *original_send_message_on_complete; + grpc_closure* original_send_message_on_complete; grpc_closure send_message_on_complete; } call_data; @@ -68,18 +68,18 @@ typedef struct channel_data { size_t max_payload_size_for_get; } channel_data; -static grpc_error *client_filter_incoming_metadata(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_metadata_batch *b) { - if (b->idx.named.status != NULL) { +static grpc_error* client_filter_incoming_metadata(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_metadata_batch* b) { + if (b->idx.named.status != nullptr) { if (grpc_mdelem_eq(b->idx.named.status->md, GRPC_MDELEM_STATUS_200)) { grpc_metadata_batch_remove(exec_ctx, b, b->idx.named.status); } else { - char *val = grpc_dump_slice(GRPC_MDVALUE(b->idx.named.status->md), + char* val = grpc_dump_slice(GRPC_MDVALUE(b->idx.named.status->md), GPR_DUMP_ASCII); - char *msg; + char* msg; gpr_asprintf(&msg, "Received http2 header with status: %s", val); - grpc_error *e = grpc_error_set_str( + grpc_error* e = grpc_error_set_str( grpc_error_set_int( grpc_error_set_str( GRPC_ERROR_CREATE_FROM_STATIC_STRING( @@ -93,7 +93,7 @@ static grpc_error *client_filter_incoming_metadata(grpc_exec_ctx *exec_ctx, } } - if (b->idx.named.grpc_message != NULL) { + if (b->idx.named.grpc_message != nullptr) { grpc_slice pct_decoded_msg = grpc_permissive_percent_decode_slice( GRPC_MDVALUE(b->idx.named.grpc_message->md)); if (grpc_slice_is_equivalent(pct_decoded_msg, @@ -105,7 +105,7 @@ static grpc_error *client_filter_incoming_metadata(grpc_exec_ctx *exec_ctx, } } - if (b->idx.named.content_type != NULL) { + if (b->idx.named.content_type != nullptr) { if (!grpc_mdelem_eq(b->idx.named.content_type->md, GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC)) { if (grpc_slice_buf_start_eq(GRPC_MDVALUE(b->idx.named.content_type->md), @@ -125,7 +125,7 @@ static grpc_error *client_filter_incoming_metadata(grpc_exec_ctx *exec_ctx, } else { /* TODO(klempner): We're currently allowing this, but we shouldn't see it without a proxy so log for now. */ - char *val = grpc_dump_slice(GRPC_MDVALUE(b->idx.named.content_type->md), + char* val = grpc_dump_slice(GRPC_MDVALUE(b->idx.named.content_type->md), GPR_DUMP_ASCII); gpr_log(GPR_INFO, "Unexpected content-type '%s'", val); gpr_free(val); @@ -137,10 +137,10 @@ static grpc_error *client_filter_incoming_metadata(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static void recv_initial_metadata_ready(grpc_exec_ctx *exec_ctx, - void *user_data, grpc_error *error) { - grpc_call_element *elem = (grpc_call_element *)user_data; - call_data *calld = (call_data *)elem->call_data; +static void recv_initial_metadata_ready(grpc_exec_ctx* exec_ctx, + void* user_data, grpc_error* error) { + grpc_call_element* elem = (grpc_call_element*)user_data; + call_data* calld = (call_data*)elem->call_data; if (error == GRPC_ERROR_NONE) { error = client_filter_incoming_metadata(exec_ctx, elem, calld->recv_initial_metadata); @@ -151,11 +151,11 @@ static void recv_initial_metadata_ready(grpc_exec_ctx *exec_ctx, error); } -static void recv_trailing_metadata_on_complete(grpc_exec_ctx *exec_ctx, - void *user_data, - grpc_error *error) { - grpc_call_element *elem = (grpc_call_element *)user_data; - call_data *calld = (call_data *)elem->call_data; +static void recv_trailing_metadata_on_complete(grpc_exec_ctx* exec_ctx, + void* user_data, + grpc_error* error) { + grpc_call_element* elem = (grpc_call_element*)user_data; + call_data* calld = (call_data*)elem->call_data; if (error == GRPC_ERROR_NONE) { error = client_filter_incoming_metadata(exec_ctx, elem, calld->recv_trailing_metadata); @@ -166,10 +166,10 @@ static void recv_trailing_metadata_on_complete(grpc_exec_ctx *exec_ctx, error); } -static void send_message_on_complete(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_call_element *elem = (grpc_call_element *)arg; - call_data *calld = (call_data *)elem->call_data; +static void send_message_on_complete(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_call_element* elem = (grpc_call_element*)arg; + call_data* calld = (call_data*)elem->call_data; grpc_byte_stream_cache_destroy(exec_ctx, &calld->send_message_cache); GRPC_CLOSURE_RUN(exec_ctx, calld->original_send_message_on_complete, GRPC_ERROR_REF(error)); @@ -177,10 +177,10 @@ static void send_message_on_complete(grpc_exec_ctx *exec_ctx, void *arg, // Pulls a slice from the send_message byte stream, updating // calld->send_message_bytes_read. -static grpc_error *pull_slice_from_send_message(grpc_exec_ctx *exec_ctx, - call_data *calld) { +static grpc_error* pull_slice_from_send_message(grpc_exec_ctx* exec_ctx, + call_data* calld) { grpc_slice incoming_slice; - grpc_error *error = grpc_byte_stream_pull( + grpc_error* error = grpc_byte_stream_pull( exec_ctx, &calld->send_message_caching_stream.base, &incoming_slice); if (error == GRPC_ERROR_NONE) { calld->send_message_bytes_read += GRPC_SLICE_LENGTH(incoming_slice); @@ -194,12 +194,12 @@ static grpc_error *pull_slice_from_send_message(grpc_exec_ctx *exec_ctx, // calld->send_message_caching_stream.base.length, then we have completed // reading from the byte stream; otherwise, an async read has been dispatched // and on_send_message_next_done() will be invoked when it is complete. -static grpc_error *read_all_available_send_message_data(grpc_exec_ctx *exec_ctx, - call_data *calld) { +static grpc_error* read_all_available_send_message_data(grpc_exec_ctx* exec_ctx, + call_data* calld) { while (grpc_byte_stream_next(exec_ctx, &calld->send_message_caching_stream.base, ~(size_t)0, &calld->on_send_message_next_done)) { - grpc_error *error = pull_slice_from_send_message(exec_ctx, calld); + grpc_error* error = pull_slice_from_send_message(exec_ctx, calld); if (error != GRPC_ERROR_NONE) return error; if (calld->send_message_bytes_read == calld->send_message_caching_stream.base.length) { @@ -210,10 +210,10 @@ static grpc_error *read_all_available_send_message_data(grpc_exec_ctx *exec_ctx, } // Async callback for grpc_byte_stream_next(). -static void on_send_message_next_done(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_call_element *elem = (grpc_call_element *)arg; - call_data *calld = (call_data *)elem->call_data; +static void on_send_message_next_done(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_call_element* elem = (grpc_call_element*)arg; + call_data* calld = (call_data*)elem->call_data; if (error != GRPC_ERROR_NONE) { grpc_transport_stream_op_batch_finish_with_failure( exec_ctx, calld->send_message_batch, error, calld->call_combiner); @@ -233,8 +233,8 @@ static void on_send_message_next_done(grpc_exec_ctx *exec_ctx, void *arg, grpc_call_next_op(exec_ctx, elem, calld->send_message_batch); } -static char *slice_buffer_to_string(grpc_slice_buffer *slice_buffer) { - char *payload_bytes = (char *)gpr_malloc(slice_buffer->length + 1); +static char* slice_buffer_to_string(grpc_slice_buffer* slice_buffer) { + char* payload_bytes = (char*)gpr_malloc(slice_buffer->length + 1); size_t offset = 0; for (size_t i = 0; i < slice_buffer->count; ++i) { memcpy(payload_bytes + offset, @@ -248,10 +248,10 @@ static char *slice_buffer_to_string(grpc_slice_buffer *slice_buffer) { // Modifies the path entry in the batch's send_initial_metadata to // append the base64-encoded query for a GET request. -static grpc_error *update_path_for_get(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_transport_stream_op_batch *batch) { - call_data *calld = (call_data *)elem->call_data; +static grpc_error* update_path_for_get(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_transport_stream_op_batch* batch) { + call_data* calld = (call_data*)elem->call_data; grpc_slice path_slice = GRPC_MDVALUE(batch->payload->send_initial_metadata.send_initial_metadata ->idx.named.path->md); @@ -264,44 +264,44 @@ static grpc_error *update_path_for_get(grpc_exec_ctx *exec_ctx, false /* multi_line */); grpc_slice path_with_query_slice = GRPC_SLICE_MALLOC(estimated_len); /* memcopy individual pieces into this slice */ - char *write_ptr = (char *)GRPC_SLICE_START_PTR(path_with_query_slice); - char *original_path = (char *)GRPC_SLICE_START_PTR(path_slice); + char* write_ptr = (char*)GRPC_SLICE_START_PTR(path_with_query_slice); + char* original_path = (char*)GRPC_SLICE_START_PTR(path_slice); memcpy(write_ptr, original_path, GRPC_SLICE_LENGTH(path_slice)); write_ptr += GRPC_SLICE_LENGTH(path_slice); *write_ptr++ = '?'; - char *payload_bytes = + char* payload_bytes = slice_buffer_to_string(&calld->send_message_cache.cache_buffer); - grpc_base64_encode_core((char *)write_ptr, payload_bytes, + grpc_base64_encode_core((char*)write_ptr, payload_bytes, batch->payload->send_message.send_message->length, true /* url_safe */, false /* multi_line */); gpr_free(payload_bytes); /* remove trailing unused memory and add trailing 0 to terminate string */ - char *t = (char *)GRPC_SLICE_START_PTR(path_with_query_slice); + char* t = (char*)GRPC_SLICE_START_PTR(path_with_query_slice); /* safe to use strlen since base64_encode will always add '\0' */ path_with_query_slice = grpc_slice_sub_no_ref(path_with_query_slice, 0, strlen(t)); /* substitute previous path with the new path+query */ grpc_mdelem mdelem_path_and_query = grpc_mdelem_from_slices(exec_ctx, GRPC_MDSTR_PATH, path_with_query_slice); - grpc_metadata_batch *b = + grpc_metadata_batch* b = batch->payload->send_initial_metadata.send_initial_metadata; return grpc_metadata_batch_substitute(exec_ctx, b, b->idx.named.path, mdelem_path_and_query); } -static void remove_if_present(grpc_exec_ctx *exec_ctx, - grpc_metadata_batch *batch, +static void remove_if_present(grpc_exec_ctx* exec_ctx, + grpc_metadata_batch* batch, grpc_metadata_batch_callouts_index idx) { - if (batch->idx.array[idx] != NULL) { + if (batch->idx.array[idx] != nullptr) { grpc_metadata_batch_remove(exec_ctx, batch, batch->idx.array[idx]); } } static void hc_start_transport_stream_op_batch( - grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_transport_stream_op_batch *batch) { - call_data *calld = (call_data *)elem->call_data; - channel_data *channeld = (channel_data *)elem->channel_data; + grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_transport_stream_op_batch* batch) { + call_data* calld = (call_data*)elem->call_data; + channel_data* channeld = (channel_data*)elem->channel_data; GPR_TIMER_BEGIN("hc_start_transport_stream_op_batch", 0); if (batch->recv_initial_metadata) { @@ -322,7 +322,7 @@ static void hc_start_transport_stream_op_batch( batch->on_complete = &calld->recv_trailing_metadata_on_complete; } - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; bool batch_will_be_handled_asynchronously = false; if (batch->send_initial_metadata) { // Decide which HTTP VERB to use. We use GET if the request is marked @@ -422,10 +422,10 @@ done: } /* Constructor for call_data */ -static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - const grpc_call_element_args *args) { - call_data *calld = (call_data *)elem->call_data; +static grpc_error* init_call_elem(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + const grpc_call_element_args* args) { + call_data* calld = (call_data*)elem->call_data; calld->call_combiner = args->call_combiner; GRPC_CLOSURE_INIT(&calld->recv_initial_metadata_ready, recv_initial_metadata_ready, elem, @@ -441,16 +441,16 @@ static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, } /* Destructor for call_data */ -static void destroy_call_elem(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - const grpc_call_final_info *final_info, - grpc_closure *ignored) {} +static void destroy_call_elem(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + const grpc_call_final_info* final_info, + grpc_closure* ignored) {} -static grpc_mdelem scheme_from_args(const grpc_channel_args *args) { +static grpc_mdelem scheme_from_args(const grpc_channel_args* args) { unsigned i; size_t j; grpc_mdelem valid_schemes[] = {GRPC_MDELEM_SCHEME_HTTP, GRPC_MDELEM_SCHEME_HTTPS}; - if (args != NULL) { + if (args != nullptr) { for (i = 0; i < args->num_args; ++i) { if (args->args[i].type == GRPC_ARG_STRING && strcmp(args->args[i].key, GRPC_ARG_HTTP2_SCHEME) == 0) { @@ -466,8 +466,8 @@ static grpc_mdelem scheme_from_args(const grpc_channel_args *args) { return GRPC_MDELEM_SCHEME_HTTP; } -static size_t max_payload_size_from_args(const grpc_channel_args *args) { - if (args != NULL) { +static size_t max_payload_size_from_args(const grpc_channel_args* args) { + if (args != nullptr) { for (size_t i = 0; i < args->num_args; ++i) { if (0 == strcmp(args->args[i].key, GRPC_ARG_MAX_PAYLOAD_SIZE_FOR_GET)) { if (args->args[i].type != GRPC_ARG_INTEGER) { @@ -482,12 +482,12 @@ static size_t max_payload_size_from_args(const grpc_channel_args *args) { return kMaxPayloadSizeForGet; } -static grpc_slice user_agent_from_args(const grpc_channel_args *args, - const char *transport_name) { +static grpc_slice user_agent_from_args(const grpc_channel_args* args, + const char* transport_name) { gpr_strvec v; size_t i; int is_first = 1; - char *tmp; + char* tmp; grpc_slice result; gpr_strvec_init(&v); @@ -524,7 +524,7 @@ static grpc_slice user_agent_from_args(const grpc_channel_args *args, } } - tmp = gpr_strvec_flatten(&v, NULL); + tmp = gpr_strvec_flatten(&v, nullptr); gpr_strvec_destroy(&v); result = grpc_slice_intern(grpc_slice_from_static_string(tmp)); gpr_free(tmp); @@ -533,12 +533,12 @@ static grpc_slice user_agent_from_args(const grpc_channel_args *args, } /* Constructor for channel_data */ -static grpc_error *init_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_channel_element_args *args) { - channel_data *chand = (channel_data *)elem->channel_data; +static grpc_error* init_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_channel_element_args* args) { + channel_data* chand = (channel_data*)elem->channel_data; GPR_ASSERT(!args->is_last); - GPR_ASSERT(args->optional_transport != NULL); + GPR_ASSERT(args->optional_transport != nullptr); chand->static_scheme = scheme_from_args(args->channel_args); chand->max_payload_size_for_get = max_payload_size_from_args(args->channel_args); @@ -550,9 +550,9 @@ static grpc_error *init_channel_elem(grpc_exec_ctx *exec_ctx, } /* Destructor for channel data */ -static void destroy_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem) { - channel_data *chand = (channel_data *)elem->channel_data; +static void destroy_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem) { + channel_data* chand = (channel_data*)elem->channel_data; GRPC_MDELEM_UNREF(exec_ctx, chand->user_agent); } diff --git a/src/core/ext/filters/http/client/http_client_filter.h b/src/core/ext/filters/http/client/http_client_filter.h index 9ed8e769150..ec8177c4367 100644 --- a/src/core/ext/filters/http/client/http_client_filter.h +++ b/src/core/ext/filters/http/client/http_client_filter.h @@ -20,18 +20,10 @@ #include "src/core/lib/channel/channel_stack.h" -#ifdef __cplusplus -extern "C" { -#endif - /* Processes metadata on the client side for HTTP2 transports */ extern const grpc_channel_filter grpc_http_client_filter; /* Channel arg to determine maximum size of payload eligable for GET request */ #define GRPC_ARG_MAX_PAYLOAD_SIZE_FOR_GET "grpc.max_payload_size_for_get" -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_HTTP_CLIENT_HTTP_CLIENT_FILTER_H */ diff --git a/src/core/ext/filters/http/http_filters_plugin.cc b/src/core/ext/filters/http/http_filters_plugin.cc index 8f5b8563172..483eb021e8d 100644 --- a/src/core/ext/filters/http/http_filters_plugin.cc +++ b/src/core/ext/filters/http/http_filters_plugin.cc @@ -27,45 +27,44 @@ #include "src/core/lib/transport/transport_impl.h" typedef struct { - const grpc_channel_filter *filter; - const char *control_channel_arg; + const grpc_channel_filter* filter; + const char* control_channel_arg; } optional_filter; static optional_filter compress_filter = { &grpc_message_compress_filter, GRPC_ARG_ENABLE_PER_MESSAGE_COMPRESSION}; static bool is_building_http_like_transport( - grpc_channel_stack_builder *builder) { - grpc_transport *t = grpc_channel_stack_builder_get_transport(builder); - return t != NULL && strstr(t->vtable->name, "http"); + grpc_channel_stack_builder* builder) { + grpc_transport* t = grpc_channel_stack_builder_get_transport(builder); + return t != nullptr && strstr(t->vtable->name, "http"); } -static bool maybe_add_optional_filter(grpc_exec_ctx *exec_ctx, - grpc_channel_stack_builder *builder, - void *arg) { +static bool maybe_add_optional_filter(grpc_exec_ctx* exec_ctx, + grpc_channel_stack_builder* builder, + void* arg) { if (!is_building_http_like_transport(builder)) return true; - optional_filter *filtarg = (optional_filter *)arg; - const grpc_channel_args *channel_args = + optional_filter* filtarg = (optional_filter*)arg; + const grpc_channel_args* channel_args = grpc_channel_stack_builder_get_channel_arguments(builder); bool enable = grpc_channel_arg_get_bool( grpc_channel_args_find(channel_args, filtarg->control_channel_arg), !grpc_channel_args_want_minimal_stack(channel_args)); return enable ? grpc_channel_stack_builder_prepend_filter( - builder, filtarg->filter, NULL, NULL) + builder, filtarg->filter, nullptr, nullptr) : true; } -static bool maybe_add_required_filter(grpc_exec_ctx *exec_ctx, - grpc_channel_stack_builder *builder, - void *arg) { +static bool maybe_add_required_filter(grpc_exec_ctx* exec_ctx, + grpc_channel_stack_builder* builder, + void* arg) { return is_building_http_like_transport(builder) ? grpc_channel_stack_builder_prepend_filter( - builder, (const grpc_channel_filter *)arg, NULL, NULL) + builder, (const grpc_channel_filter*)arg, nullptr, nullptr) : true; } -extern "C" void grpc_http_filters_init(void) { - grpc_register_tracer(&grpc_compression_trace); +void grpc_http_filters_init(void) { grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, maybe_add_optional_filter, &compress_filter); @@ -77,13 +76,13 @@ extern "C" void grpc_http_filters_init(void) { maybe_add_optional_filter, &compress_filter); grpc_channel_init_register_stage( GRPC_CLIENT_SUBCHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, - maybe_add_required_filter, (void *)&grpc_http_client_filter); + maybe_add_required_filter, (void*)&grpc_http_client_filter); grpc_channel_init_register_stage( GRPC_CLIENT_DIRECT_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, - maybe_add_required_filter, (void *)&grpc_http_client_filter); + maybe_add_required_filter, (void*)&grpc_http_client_filter); grpc_channel_init_register_stage( GRPC_SERVER_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, - maybe_add_required_filter, (void *)&grpc_http_server_filter); + maybe_add_required_filter, (void*)&grpc_http_server_filter); } -extern "C" void grpc_http_filters_shutdown(void) {} +void grpc_http_filters_shutdown(void) {} diff --git a/src/core/ext/filters/http/message_compress/message_compress_filter.cc b/src/core/ext/filters/http/message_compress/message_compress_filter.cc index f785e1355d3..d070b56b6a5 100644 --- a/src/core/ext/filters/http/message_compress/message_compress_filter.cc +++ b/src/core/ext/filters/http/message_compress/message_compress_filter.cc @@ -45,7 +45,7 @@ typedef enum { } initial_metadata_state; typedef struct call_data { - grpc_call_combiner *call_combiner; + grpc_call_combiner* call_combiner; grpc_linked_mdelem compression_algorithm_storage; grpc_linked_mdelem stream_compression_algorithm_storage; grpc_linked_mdelem accept_encoding_storage; @@ -54,12 +54,12 @@ typedef struct call_data { * metadata, or by the channel's default compression settings. */ grpc_compression_algorithm compression_algorithm; initial_metadata_state send_initial_metadata_state; - grpc_error *cancel_error; + grpc_error* cancel_error; grpc_closure start_send_message_batch_in_call_combiner; - grpc_transport_stream_op_batch *send_message_batch; + grpc_transport_stream_op_batch* send_message_batch; grpc_slice_buffer slices; /**< Buffers up input slices to be compressed */ grpc_slice_buffer_stream replacement_stream; - grpc_closure *original_send_message_on_complete; + grpc_closure* original_send_message_on_complete; grpc_closure send_message_on_complete; grpc_closure on_send_message_next_done; } call_data; @@ -80,10 +80,10 @@ typedef struct channel_data { uint32_t supported_stream_compression_algorithms; } channel_data; -static bool skip_compression(grpc_call_element *elem, uint32_t flags, +static bool skip_compression(grpc_call_element* elem, uint32_t flags, bool has_compression_algorithm) { - call_data *calld = (call_data *)elem->call_data; - channel_data *channeld = (channel_data *)elem->channel_data; + call_data* calld = (call_data*)elem->call_data; + channel_data* channeld = (channel_data*)elem->channel_data; if (flags & (GRPC_WRITE_NO_COMPRESS | GRPC_WRITE_INTERNAL_COMPRESS)) { return true; @@ -99,25 +99,25 @@ static bool skip_compression(grpc_call_element *elem, uint32_t flags, } /** Filter initial metadata */ -static grpc_error *process_send_initial_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_metadata_batch *initial_metadata, - bool *has_compression_algorithm) GRPC_MUST_USE_RESULT; -static grpc_error *process_send_initial_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_metadata_batch *initial_metadata, bool *has_compression_algorithm) { - call_data *calld = (call_data *)elem->call_data; - channel_data *channeld = (channel_data *)elem->channel_data; +static grpc_error* process_send_initial_metadata( + grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_metadata_batch* initial_metadata, + bool* has_compression_algorithm) GRPC_MUST_USE_RESULT; +static grpc_error* process_send_initial_metadata( + grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_metadata_batch* initial_metadata, bool* has_compression_algorithm) { + call_data* calld = (call_data*)elem->call_data; + channel_data* channeld = (channel_data*)elem->channel_data; *has_compression_algorithm = false; grpc_stream_compression_algorithm stream_compression_algorithm = GRPC_STREAM_COMPRESS_NONE; if (initial_metadata->idx.named.grpc_internal_stream_encoding_request != - NULL) { + nullptr) { grpc_mdelem md = initial_metadata->idx.named.grpc_internal_stream_encoding_request->md; if (!grpc_stream_compression_algorithm_parse( GRPC_MDVALUE(md), &stream_compression_algorithm)) { - char *val = grpc_slice_to_c_string(GRPC_MDVALUE(md)); + char* val = grpc_slice_to_c_string(GRPC_MDVALUE(md)); gpr_log(GPR_ERROR, "Invalid stream compression algorithm: '%s' (unknown). Ignoring.", val); @@ -126,7 +126,7 @@ static grpc_error *process_send_initial_metadata( } if (!GPR_BITGET(channeld->enabled_stream_compression_algorithms_bitset, stream_compression_algorithm)) { - char *val = grpc_slice_to_c_string(GRPC_MDVALUE(md)); + char* val = grpc_slice_to_c_string(GRPC_MDVALUE(md)); gpr_log( GPR_ERROR, "Invalid stream compression algorithm: '%s' (previously disabled). " @@ -141,18 +141,18 @@ static grpc_error *process_send_initial_metadata( initial_metadata->idx.named.grpc_internal_stream_encoding_request); /* Disable message-wise compression */ calld->compression_algorithm = GRPC_COMPRESS_NONE; - if (initial_metadata->idx.named.grpc_internal_encoding_request != NULL) { + if (initial_metadata->idx.named.grpc_internal_encoding_request != nullptr) { grpc_metadata_batch_remove( exec_ctx, initial_metadata, initial_metadata->idx.named.grpc_internal_encoding_request); } } else if (initial_metadata->idx.named.grpc_internal_encoding_request != - NULL) { + nullptr) { grpc_mdelem md = initial_metadata->idx.named.grpc_internal_encoding_request->md; if (!grpc_compression_algorithm_parse(GRPC_MDVALUE(md), &calld->compression_algorithm)) { - char *val = grpc_slice_to_c_string(GRPC_MDVALUE(md)); + char* val = grpc_slice_to_c_string(GRPC_MDVALUE(md)); gpr_log(GPR_ERROR, "Invalid compression algorithm: '%s' (unknown). Ignoring.", val); gpr_free(val); @@ -177,7 +177,7 @@ static grpc_error *process_send_initial_metadata( *has_compression_algorithm = true; } - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; /* hint compression algorithm */ if (stream_compression_algorithm != GRPC_STREAM_COMPRESS_NONE) { error = grpc_metadata_batch_add_tail( @@ -211,30 +211,30 @@ static grpc_error *process_send_initial_metadata( return error; } -static void send_message_on_complete(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_call_element *elem = (grpc_call_element *)arg; - call_data *calld = (call_data *)elem->call_data; +static void send_message_on_complete(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_call_element* elem = (grpc_call_element*)arg; + call_data* calld = (call_data*)elem->call_data; grpc_slice_buffer_reset_and_unref_internal(exec_ctx, &calld->slices); GRPC_CLOSURE_RUN(exec_ctx, calld->original_send_message_on_complete, GRPC_ERROR_REF(error)); } -static void send_message_batch_continue(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem) { - call_data *calld = (call_data *)elem->call_data; +static void send_message_batch_continue(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem) { + call_data* calld = (call_data*)elem->call_data; // Note: The call to grpc_call_next_op() results in yielding the // call combiner, so we need to clear calld->send_message_batch // before we do that. - grpc_transport_stream_op_batch *send_message_batch = + grpc_transport_stream_op_batch* send_message_batch = calld->send_message_batch; - calld->send_message_batch = NULL; + calld->send_message_batch = nullptr; grpc_call_next_op(exec_ctx, elem, send_message_batch); } -static void finish_send_message(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem) { - call_data *calld = (call_data *)elem->call_data; +static void finish_send_message(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem) { + call_data* calld = (call_data*)elem->call_data; // Compress the data if appropriate. grpc_slice_buffer tmp; grpc_slice_buffer_init(&tmp); @@ -243,22 +243,23 @@ static void finish_send_message(grpc_exec_ctx *exec_ctx, bool did_compress = grpc_msg_compress(exec_ctx, calld->compression_algorithm, &calld->slices, &tmp); if (did_compress) { - if (GRPC_TRACER_ON(grpc_compression_trace)) { - const char *algo_name; + if (grpc_compression_trace.enabled()) { + const char* algo_name; const size_t before_size = calld->slices.length; const size_t after_size = tmp.length; const float savings_ratio = 1.0f - (float)after_size / (float)before_size; GPR_ASSERT(grpc_compression_algorithm_name(calld->compression_algorithm, &algo_name)); - gpr_log(GPR_DEBUG, "Compressed[%s] %" PRIuPTR " bytes vs. %" PRIuPTR - " bytes (%.2f%% savings)", + gpr_log(GPR_DEBUG, + "Compressed[%s] %" PRIuPTR " bytes vs. %" PRIuPTR + " bytes (%.2f%% savings)", algo_name, before_size, after_size, 100 * savings_ratio); } grpc_slice_buffer_swap(&calld->slices, &tmp); send_flags |= GRPC_WRITE_INTERNAL_COMPRESS; } else { - if (GRPC_TRACER_ON(grpc_compression_trace)) { - const char *algo_name; + if (grpc_compression_trace.enabled()) { + const char* algo_name; GPR_ASSERT(grpc_compression_algorithm_name(calld->compression_algorithm, &algo_name)); gpr_log(GPR_DEBUG, @@ -282,23 +283,23 @@ static void finish_send_message(grpc_exec_ctx *exec_ctx, send_message_batch_continue(exec_ctx, elem); } -static void fail_send_message_batch_in_call_combiner(grpc_exec_ctx *exec_ctx, - void *arg, - grpc_error *error) { - call_data *calld = (call_data *)arg; - if (calld->send_message_batch != NULL) { +static void fail_send_message_batch_in_call_combiner(grpc_exec_ctx* exec_ctx, + void* arg, + grpc_error* error) { + call_data* calld = (call_data*)arg; + if (calld->send_message_batch != nullptr) { grpc_transport_stream_op_batch_finish_with_failure( exec_ctx, calld->send_message_batch, GRPC_ERROR_REF(error), calld->call_combiner); - calld->send_message_batch = NULL; + calld->send_message_batch = nullptr; } } // Pulls a slice from the send_message byte stream and adds it to calld->slices. -static grpc_error *pull_slice_from_send_message(grpc_exec_ctx *exec_ctx, - call_data *calld) { +static grpc_error* pull_slice_from_send_message(grpc_exec_ctx* exec_ctx, + call_data* calld) { grpc_slice incoming_slice; - grpc_error *error = grpc_byte_stream_pull( + grpc_error* error = grpc_byte_stream_pull( exec_ctx, calld->send_message_batch->payload->send_message.send_message, &incoming_slice); if (error == GRPC_ERROR_NONE) { @@ -311,13 +312,13 @@ static grpc_error *pull_slice_from_send_message(grpc_exec_ctx *exec_ctx, // If all data has been read, invokes finish_send_message(). Otherwise, // an async call to grpc_byte_stream_next() has been started, which will // eventually result in calling on_send_message_next_done(). -static void continue_reading_send_message(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem) { - call_data *calld = (call_data *)elem->call_data; +static void continue_reading_send_message(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem) { + call_data* calld = (call_data*)elem->call_data; while (grpc_byte_stream_next( exec_ctx, calld->send_message_batch->payload->send_message.send_message, ~(size_t)0, &calld->on_send_message_next_done)) { - grpc_error *error = pull_slice_from_send_message(exec_ctx, calld); + grpc_error* error = pull_slice_from_send_message(exec_ctx, calld); if (error != GRPC_ERROR_NONE) { // Closure callback; does not take ownership of error. fail_send_message_batch_in_call_combiner(exec_ctx, calld, error); @@ -333,10 +334,10 @@ static void continue_reading_send_message(grpc_exec_ctx *exec_ctx, } // Async callback for grpc_byte_stream_next(). -static void on_send_message_next_done(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_call_element *elem = (grpc_call_element *)arg; - call_data *calld = (call_data *)elem->call_data; +static void on_send_message_next_done(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_call_element* elem = (grpc_call_element*)arg; + call_data* calld = (call_data*)elem->call_data; if (error != GRPC_ERROR_NONE) { // Closure callback; does not take ownership of error. fail_send_message_batch_in_call_combiner(exec_ctx, calld, error); @@ -357,10 +358,10 @@ static void on_send_message_next_done(grpc_exec_ctx *exec_ctx, void *arg, } } -static void start_send_message_batch(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *unused) { - grpc_call_element *elem = (grpc_call_element *)arg; - call_data *calld = (call_data *)elem->call_data; +static void start_send_message_batch(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* unused) { + grpc_call_element* elem = (grpc_call_element*)arg; + call_data* calld = (call_data*)elem->call_data; if (skip_compression( elem, calld->send_message_batch->payload->send_message.send_message->flags, @@ -372,16 +373,16 @@ static void start_send_message_batch(grpc_exec_ctx *exec_ctx, void *arg, } static void compress_start_transport_stream_op_batch( - grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_transport_stream_op_batch *batch) { - call_data *calld = (call_data *)elem->call_data; + grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_transport_stream_op_batch* batch) { + call_data* calld = (call_data*)elem->call_data; GPR_TIMER_BEGIN("compress_start_transport_stream_op_batch", 0); // Handle cancel_stream. if (batch->cancel_stream) { GRPC_ERROR_UNREF(calld->cancel_error); calld->cancel_error = GRPC_ERROR_REF(batch->payload->cancel_stream.cancel_error); - if (calld->send_message_batch != NULL) { + if (calld->send_message_batch != nullptr) { if (calld->send_initial_metadata_state == INITIAL_METADATA_UNSEEN) { GRPC_CALL_COMBINER_START( exec_ctx, calld->call_combiner, @@ -405,7 +406,7 @@ static void compress_start_transport_stream_op_batch( if (batch->send_initial_metadata) { GPR_ASSERT(calld->send_initial_metadata_state == INITIAL_METADATA_UNSEEN); bool has_compression_algorithm; - grpc_error *error = process_send_initial_metadata( + grpc_error* error = process_send_initial_metadata( exec_ctx, elem, batch->payload->send_initial_metadata.send_initial_metadata, &has_compression_algorithm); @@ -422,7 +423,7 @@ static void compress_start_transport_stream_op_batch( // for this, since we can't send two batches down while holding the // call combiner, since the connected_channel filter (at the bottom of // the call stack) will release the call combiner for each batch it sees. - if (calld->send_message_batch != NULL) { + if (calld->send_message_batch != nullptr) { GRPC_CALL_COMBINER_START( exec_ctx, calld->call_combiner, &calld->start_send_message_batch_in_call_combiner, GRPC_ERROR_NONE, @@ -431,7 +432,7 @@ static void compress_start_transport_stream_op_batch( } // Handle send_message. if (batch->send_message) { - GPR_ASSERT(calld->send_message_batch == NULL); + GPR_ASSERT(calld->send_message_batch == nullptr); calld->send_message_batch = batch; // If we have not yet seen send_initial_metadata, then we have to // wait. We save the batch in calld and then drop the call @@ -453,10 +454,10 @@ done: } /* Constructor for call_data */ -static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - const grpc_call_element_args *args) { - call_data *calld = (call_data *)elem->call_data; +static grpc_error* init_call_elem(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + const grpc_call_element_args* args) { + call_data* calld = (call_data*)elem->call_data; calld->call_combiner = args->call_combiner; calld->cancel_error = GRPC_ERROR_NONE; grpc_slice_buffer_init(&calld->slices); @@ -470,19 +471,19 @@ static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, } /* Destructor for call_data */ -static void destroy_call_elem(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - const grpc_call_final_info *final_info, - grpc_closure *ignored) { - call_data *calld = (call_data *)elem->call_data; +static void destroy_call_elem(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + const grpc_call_final_info* final_info, + grpc_closure* ignored) { + call_data* calld = (call_data*)elem->call_data; grpc_slice_buffer_destroy_internal(exec_ctx, &calld->slices); GRPC_ERROR_UNREF(calld->cancel_error); } /* Constructor for channel_data */ -static grpc_error *init_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_channel_element_args *args) { - channel_data *channeld = (channel_data *)elem->channel_data; +static grpc_error* init_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_channel_element_args* args) { + channel_data* channeld = (channel_data*)elem->channel_data; /* Configuration for message compression */ channeld->enabled_algorithms_bitset = @@ -530,8 +531,8 @@ static grpc_error *init_channel_elem(grpc_exec_ctx *exec_ctx, } /* Destructor for channel data */ -static void destroy_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem) {} +static void destroy_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem) {} const grpc_channel_filter grpc_message_compress_filter = { compress_start_transport_stream_op_batch, diff --git a/src/core/ext/filters/http/message_compress/message_compress_filter.h b/src/core/ext/filters/http/message_compress/message_compress_filter.h index 92771d98582..62207911c70 100644 --- a/src/core/ext/filters/http/message_compress/message_compress_filter.h +++ b/src/core/ext/filters/http/message_compress/message_compress_filter.h @@ -23,10 +23,6 @@ #include "src/core/lib/channel/channel_stack.h" -#ifdef __cplusplus -extern "C" { -#endif - /** Compression filter for outgoing data. * * See for the available compression settings. @@ -51,9 +47,5 @@ extern "C" { extern const grpc_channel_filter grpc_message_compress_filter; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_HTTP_MESSAGE_COMPRESS_MESSAGE_COMPRESS_FILTER_H \ - */ + */ diff --git a/src/core/ext/filters/http/server/http_server_filter.cc b/src/core/ext/filters/http/server/http_server_filter.cc index 03958136b44..4f3897915c0 100644 --- a/src/core/ext/filters/http/server/http_server_filter.cc +++ b/src/core/ext/filters/http/server/http_server_filter.cc @@ -32,7 +32,7 @@ #define EXPECTED_CONTENT_TYPE_LENGTH sizeof(EXPECTED_CONTENT_TYPE) - 1 typedef struct call_data { - grpc_call_combiner *call_combiner; + grpc_call_combiner* call_combiner; grpc_linked_mdelem status; grpc_linked_mdelem content_type; @@ -42,15 +42,15 @@ typedef struct call_data { /* flag to ensure payload_bin is delivered only once */ bool payload_bin_delivered; - grpc_metadata_batch *recv_initial_metadata; - uint32_t *recv_initial_metadata_flags; + grpc_metadata_batch* recv_initial_metadata; + uint32_t* recv_initial_metadata_flags; /** Closure to call when finished with the hs_on_recv hook */ - grpc_closure *on_done_recv; + grpc_closure* on_done_recv; /** Closure to call when we retrieve read message from the path URI */ - grpc_closure *recv_message_ready; - grpc_closure *on_complete; - grpc_byte_stream **pp_recv_message; + grpc_closure* recv_message_ready; + grpc_closure* on_complete; + grpc_byte_stream** pp_recv_message; grpc_slice_buffer read_slice_buffer; grpc_slice_buffer_stream read_stream; @@ -62,12 +62,14 @@ typedef struct call_data { grpc_closure hs_recv_message_ready; } call_data; -typedef struct channel_data { uint8_t unused; } channel_data; +typedef struct channel_data { + uint8_t unused; +} channel_data; -static grpc_error *server_filter_outgoing_metadata(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_metadata_batch *b) { - if (b->idx.named.grpc_message != NULL) { +static grpc_error* server_filter_outgoing_metadata(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_metadata_batch* b) { + if (b->idx.named.grpc_message != nullptr) { grpc_slice pct_encoded_msg = grpc_percent_encode_slice( GRPC_MDVALUE(b->idx.named.grpc_message->md), grpc_compatible_percent_encoding_unreserved_bytes); @@ -82,8 +84,8 @@ static grpc_error *server_filter_outgoing_metadata(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static void add_error(const char *error_name, grpc_error **cumulative, - grpc_error *new_err) { +static void add_error(const char* error_name, grpc_error** cumulative, + grpc_error* new_err) { if (new_err == GRPC_ERROR_NONE) return; if (*cumulative == GRPC_ERROR_NONE) { *cumulative = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_name); @@ -91,14 +93,14 @@ static void add_error(const char *error_name, grpc_error **cumulative, *cumulative = grpc_error_add_child(*cumulative, new_err); } -static grpc_error *server_filter_incoming_metadata(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_metadata_batch *b) { - call_data *calld = (call_data *)elem->call_data; - grpc_error *error = GRPC_ERROR_NONE; - static const char *error_name = "Failed processing incoming headers"; +static grpc_error* server_filter_incoming_metadata(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_metadata_batch* b) { + call_data* calld = (call_data*)elem->call_data; + grpc_error* error = GRPC_ERROR_NONE; + static const char* error_name = "Failed processing incoming headers"; - if (b->idx.named.method != NULL) { + if (b->idx.named.method != nullptr) { if (grpc_mdelem_eq(b->idx.named.method->md, GRPC_MDELEM_METHOD_POST)) { *calld->recv_initial_metadata_flags &= ~(GRPC_INITIAL_METADATA_CACHEABLE_REQUEST | @@ -130,7 +132,7 @@ static grpc_error *server_filter_incoming_metadata(grpc_exec_ctx *exec_ctx, GRPC_ERROR_STR_KEY, grpc_slice_from_static_string(":method"))); } - if (b->idx.named.te != NULL) { + if (b->idx.named.te != nullptr) { if (!grpc_mdelem_eq(b->idx.named.te->md, GRPC_MDELEM_TE_TRAILERS)) { add_error(error_name, &error, grpc_attach_md_to_error( @@ -145,7 +147,7 @@ static grpc_error *server_filter_incoming_metadata(grpc_exec_ctx *exec_ctx, GRPC_ERROR_STR_KEY, grpc_slice_from_static_string("te"))); } - if (b->idx.named.scheme != NULL) { + if (b->idx.named.scheme != nullptr) { if (!grpc_mdelem_eq(b->idx.named.scheme->md, GRPC_MDELEM_SCHEME_HTTP) && !grpc_mdelem_eq(b->idx.named.scheme->md, GRPC_MDELEM_SCHEME_HTTPS) && !grpc_mdelem_eq(b->idx.named.scheme->md, GRPC_MDELEM_SCHEME_GRPC)) { @@ -163,7 +165,7 @@ static grpc_error *server_filter_incoming_metadata(grpc_exec_ctx *exec_ctx, GRPC_ERROR_STR_KEY, grpc_slice_from_static_string(":scheme"))); } - if (b->idx.named.content_type != NULL) { + if (b->idx.named.content_type != nullptr) { if (!grpc_mdelem_eq(b->idx.named.content_type->md, GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC)) { if (grpc_slice_buf_start_eq(GRPC_MDVALUE(b->idx.named.content_type->md), @@ -183,7 +185,7 @@ static grpc_error *server_filter_incoming_metadata(grpc_exec_ctx *exec_ctx, } else { /* TODO(klempner): We're currently allowing this, but we shouldn't see it without a proxy so log for now. */ - char *val = grpc_dump_slice(GRPC_MDVALUE(b->idx.named.content_type->md), + char* val = grpc_dump_slice(GRPC_MDVALUE(b->idx.named.content_type->md), GPR_DUMP_ASCII); gpr_log(GPR_INFO, "Unexpected content-type '%s'", val); gpr_free(val); @@ -192,7 +194,7 @@ static grpc_error *server_filter_incoming_metadata(grpc_exec_ctx *exec_ctx, grpc_metadata_batch_remove(exec_ctx, b, b->idx.named.content_type); } - if (b->idx.named.path == NULL) { + if (b->idx.named.path == nullptr) { add_error(error_name, &error, grpc_error_set_str( GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"), @@ -203,7 +205,7 @@ static grpc_error *server_filter_incoming_metadata(grpc_exec_ctx *exec_ctx, * query parameter which is base64 encoded request payload. */ const char k_query_separator = '?'; grpc_slice path_slice = GRPC_MDVALUE(b->idx.named.path->md); - uint8_t *path_ptr = (uint8_t *)GRPC_SLICE_START_PTR(path_slice); + uint8_t* path_ptr = (uint8_t*)GRPC_SLICE_START_PTR(path_slice); size_t path_length = GRPC_SLICE_LENGTH(path_slice); /* offset of the character '?' */ size_t offset = 0; @@ -226,7 +228,7 @@ static grpc_error *server_filter_incoming_metadata(grpc_exec_ctx *exec_ctx, grpc_slice_buffer_add( &calld->read_slice_buffer, grpc_base64_decode_with_len( - exec_ctx, (const char *)GRPC_SLICE_START_PTR(query_slice), + exec_ctx, (const char*)GRPC_SLICE_START_PTR(query_slice), GRPC_SLICE_LENGTH(query_slice), k_url_safe)); grpc_slice_buffer_stream_init(&calld->read_stream, &calld->read_slice_buffer, 0); @@ -237,20 +239,20 @@ static grpc_error *server_filter_incoming_metadata(grpc_exec_ctx *exec_ctx, } } - if (b->idx.named.host != NULL && b->idx.named.authority == NULL) { - grpc_linked_mdelem *el = b->idx.named.host; + if (b->idx.named.host != nullptr && b->idx.named.authority == nullptr) { + grpc_linked_mdelem* el = b->idx.named.host; grpc_mdelem md = GRPC_MDELEM_REF(el->md); grpc_metadata_batch_remove(exec_ctx, b, el); - add_error( - error_name, &error, - grpc_metadata_batch_add_head( - exec_ctx, b, el, grpc_mdelem_from_slices( - exec_ctx, GRPC_MDSTR_AUTHORITY, - grpc_slice_ref_internal(GRPC_MDVALUE(md))))); + add_error(error_name, &error, + grpc_metadata_batch_add_head( + exec_ctx, b, el, + grpc_mdelem_from_slices( + exec_ctx, GRPC_MDSTR_AUTHORITY, + grpc_slice_ref_internal(GRPC_MDVALUE(md))))); GRPC_MDELEM_UNREF(exec_ctx, md); } - if (b->idx.named.authority == NULL) { + if (b->idx.named.authority == nullptr) { add_error( error_name, &error, grpc_error_set_str( @@ -261,10 +263,10 @@ static grpc_error *server_filter_incoming_metadata(grpc_exec_ctx *exec_ctx, return error; } -static void hs_on_recv(grpc_exec_ctx *exec_ctx, void *user_data, - grpc_error *err) { - grpc_call_element *elem = (grpc_call_element *)user_data; - call_data *calld = (call_data *)elem->call_data; +static void hs_on_recv(grpc_exec_ctx* exec_ctx, void* user_data, + grpc_error* err) { + grpc_call_element* elem = (grpc_call_element*)user_data; + call_data* calld = (call_data*)elem->call_data; if (err == GRPC_ERROR_NONE) { err = server_filter_incoming_metadata(exec_ctx, elem, calld->recv_initial_metadata); @@ -274,30 +276,30 @@ static void hs_on_recv(grpc_exec_ctx *exec_ctx, void *user_data, GRPC_CLOSURE_RUN(exec_ctx, calld->on_done_recv, err); } -static void hs_on_complete(grpc_exec_ctx *exec_ctx, void *user_data, - grpc_error *err) { - grpc_call_element *elem = (grpc_call_element *)user_data; - call_data *calld = (call_data *)elem->call_data; +static void hs_on_complete(grpc_exec_ctx* exec_ctx, void* user_data, + grpc_error* err) { + grpc_call_element* elem = (grpc_call_element*)user_data; + call_data* calld = (call_data*)elem->call_data; /* Call recv_message_ready if we got the payload via the path field */ - if (calld->seen_path_with_query && calld->recv_message_ready != NULL) { + if (calld->seen_path_with_query && calld->recv_message_ready != nullptr) { *calld->pp_recv_message = calld->payload_bin_delivered - ? NULL - : (grpc_byte_stream *)&calld->read_stream; + ? nullptr + : (grpc_byte_stream*)&calld->read_stream; // Re-enter call combiner for recv_message_ready, since the surface // code will release the call combiner for each callback it receives. GRPC_CALL_COMBINER_START(exec_ctx, calld->call_combiner, calld->recv_message_ready, GRPC_ERROR_REF(err), "resuming recv_message_ready from on_complete"); - calld->recv_message_ready = NULL; + calld->recv_message_ready = nullptr; calld->payload_bin_delivered = true; } GRPC_CLOSURE_RUN(exec_ctx, calld->on_complete, GRPC_ERROR_REF(err)); } -static void hs_recv_message_ready(grpc_exec_ctx *exec_ctx, void *user_data, - grpc_error *err) { - grpc_call_element *elem = (grpc_call_element *)user_data; - call_data *calld = (call_data *)elem->call_data; +static void hs_recv_message_ready(grpc_exec_ctx* exec_ctx, void* user_data, + grpc_error* err) { + grpc_call_element* elem = (grpc_call_element*)user_data; + call_data* calld = (call_data*)elem->call_data; if (calld->seen_path_with_query) { // Do nothing. This is probably a GET request, and payload will be // returned in hs_on_complete callback. @@ -310,15 +312,15 @@ static void hs_recv_message_ready(grpc_exec_ctx *exec_ctx, void *user_data, } } -static grpc_error *hs_mutate_op(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_transport_stream_op_batch *op) { +static grpc_error* hs_mutate_op(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_transport_stream_op_batch* op) { /* grab pointers to our data from the call element */ - call_data *calld = (call_data *)elem->call_data; + call_data* calld = (call_data*)elem->call_data; if (op->send_initial_metadata) { - grpc_error *error = GRPC_ERROR_NONE; - static const char *error_name = "Failed sending initial metadata"; + grpc_error* error = GRPC_ERROR_NONE; + static const char* error_name = "Failed sending initial metadata"; add_error( error_name, &error, grpc_metadata_batch_add_head( @@ -339,7 +341,7 @@ static grpc_error *hs_mutate_op(grpc_exec_ctx *exec_ctx, if (op->recv_initial_metadata) { /* substitute our callback for the higher callback */ - GPR_ASSERT(op->payload->recv_initial_metadata.recv_flags != NULL); + GPR_ASSERT(op->payload->recv_initial_metadata.recv_flags != nullptr); calld->recv_initial_metadata = op->payload->recv_initial_metadata.recv_initial_metadata; calld->recv_initial_metadata_flags = @@ -364,7 +366,7 @@ static grpc_error *hs_mutate_op(grpc_exec_ctx *exec_ctx, } if (op->send_trailing_metadata) { - grpc_error *error = server_filter_outgoing_metadata( + grpc_error* error = server_filter_outgoing_metadata( exec_ctx, elem, op->payload->send_trailing_metadata.send_trailing_metadata); if (error != GRPC_ERROR_NONE) return error; @@ -374,11 +376,11 @@ static grpc_error *hs_mutate_op(grpc_exec_ctx *exec_ctx, } static void hs_start_transport_stream_op_batch( - grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_transport_stream_op_batch *op) { - call_data *calld = (call_data *)elem->call_data; + grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_transport_stream_op_batch* op) { + call_data* calld = (call_data*)elem->call_data; GPR_TIMER_BEGIN("hs_start_transport_stream_op_batch", 0); - grpc_error *error = hs_mutate_op(exec_ctx, elem, op); + grpc_error* error = hs_mutate_op(exec_ctx, elem, op); if (error != GRPC_ERROR_NONE) { grpc_transport_stream_op_batch_finish_with_failure(exec_ctx, op, error, calld->call_combiner); @@ -389,11 +391,11 @@ static void hs_start_transport_stream_op_batch( } /* Constructor for call_data */ -static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - const grpc_call_element_args *args) { +static grpc_error* init_call_elem(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + const grpc_call_element_args* args) { /* grab pointers to our data from the call element */ - call_data *calld = (call_data *)elem->call_data; + call_data* calld = (call_data*)elem->call_data; /* initialize members */ calld->call_combiner = args->call_combiner; GRPC_CLOSURE_INIT(&calld->hs_on_recv, hs_on_recv, elem, @@ -407,24 +409,24 @@ static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, } /* Destructor for call_data */ -static void destroy_call_elem(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - const grpc_call_final_info *final_info, - grpc_closure *ignored) { - call_data *calld = (call_data *)elem->call_data; +static void destroy_call_elem(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + const grpc_call_final_info* final_info, + grpc_closure* ignored) { + call_data* calld = (call_data*)elem->call_data; grpc_slice_buffer_destroy_internal(exec_ctx, &calld->read_slice_buffer); } /* Constructor for channel_data */ -static grpc_error *init_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_channel_element_args *args) { +static grpc_error* init_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_channel_element_args* args) { GPR_ASSERT(!args->is_last); return GRPC_ERROR_NONE; } /* Destructor for channel data */ -static void destroy_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem) {} +static void destroy_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem) {} const grpc_channel_filter grpc_http_server_filter = { hs_start_transport_stream_op_batch, diff --git a/src/core/ext/filters/http/server/http_server_filter.h b/src/core/ext/filters/http/server/http_server_filter.h index 4b38cc5bf76..c0f678a3299 100644 --- a/src/core/ext/filters/http/server/http_server_filter.h +++ b/src/core/ext/filters/http/server/http_server_filter.h @@ -21,15 +21,7 @@ #include "src/core/lib/channel/channel_stack.h" -#ifdef __cplusplus -extern "C" { -#endif - /* Processes metadata on the client side for HTTP2 transports */ extern const grpc_channel_filter grpc_http_server_filter; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_HTTP_SERVER_HTTP_SERVER_FILTER_H */ diff --git a/src/core/ext/filters/load_reporting/server_load_reporting_filter.cc b/src/core/ext/filters/load_reporting/server_load_reporting_filter.cc index ca8a3b2a134..762198f0347 100644 --- a/src/core/ext/filters/load_reporting/server_load_reporting_filter.cc +++ b/src/core/ext/filters/load_reporting/server_load_reporting_filter.cc @@ -43,24 +43,24 @@ typedef struct call_data { /* stores the recv_initial_metadata op's ready closure, which we wrap with our * own (on_initial_md_ready) in order to capture the incoming initial metadata * */ - grpc_closure *ops_recv_initial_metadata_ready; + grpc_closure* ops_recv_initial_metadata_ready; /* to get notified of the availability of the incoming initial metadata. */ grpc_closure on_initial_md_ready; - grpc_metadata_batch *recv_initial_metadata; + grpc_metadata_batch* recv_initial_metadata; } call_data; typedef struct channel_data { intptr_t id; /**< an id unique to the channel */ } channel_data; -static void on_initial_md_ready(grpc_exec_ctx *exec_ctx, void *user_data, - grpc_error *err) { - grpc_call_element *elem = (grpc_call_element *)user_data; - call_data *calld = (call_data *)elem->call_data; +static void on_initial_md_ready(grpc_exec_ctx* exec_ctx, void* user_data, + grpc_error* err) { + grpc_call_element* elem = (grpc_call_element*)user_data; + call_data* calld = (call_data*)elem->call_data; if (err == GRPC_ERROR_NONE) { - if (calld->recv_initial_metadata->idx.named.path != NULL) { + if (calld->recv_initial_metadata->idx.named.path != nullptr) { calld->service_method = grpc_slice_ref_internal( GRPC_MDVALUE(calld->recv_initial_metadata->idx.named.path->md)); calld->have_service_method = true; @@ -68,7 +68,7 @@ static void on_initial_md_ready(grpc_exec_ctx *exec_ctx, void *user_data, err = grpc_error_add_child( err, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing :path header")); } - if (calld->recv_initial_metadata->idx.named.lb_token != NULL) { + if (calld->recv_initial_metadata->idx.named.lb_token != nullptr) { calld->initial_md_string = grpc_slice_ref_internal( GRPC_MDVALUE(calld->recv_initial_metadata->idx.named.lb_token->md)); calld->have_initial_md_string = true; @@ -85,10 +85,10 @@ static void on_initial_md_ready(grpc_exec_ctx *exec_ctx, void *user_data, } /* Constructor for call_data */ -static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - const grpc_call_element_args *args) { - call_data *calld = (call_data *)elem->call_data; +static grpc_error* init_call_elem(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + const grpc_call_element_args* args) { + call_data* calld = (call_data*)elem->call_data; calld->id = (intptr_t)args->call_stack; GRPC_CLOSURE_INIT(&calld->on_initial_md_ready, on_initial_md_ready, elem, grpc_schedule_on_exec_ctx); @@ -108,10 +108,10 @@ static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, } /* Destructor for call_data */ -static void destroy_call_elem(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - const grpc_call_final_info *final_info, - grpc_closure *ignored) { - call_data *calld = (call_data *)elem->call_data; +static void destroy_call_elem(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + const grpc_call_final_info* final_info, + grpc_closure* ignored) { + call_data* calld = (call_data*)elem->call_data; /* TODO(dgq): do something with the data channel_data *chand = elem->channel_data; @@ -136,12 +136,12 @@ static void destroy_call_elem(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, } /* Constructor for channel_data */ -static grpc_error *init_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_channel_element_args *args) { +static grpc_error* init_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_channel_element_args* args) { GPR_ASSERT(!args->is_last); - channel_data *chand = (channel_data *)elem->channel_data; + channel_data* chand = (channel_data*)elem->channel_data; chand->id = (intptr_t)args->channel_stack; /* TODO(dgq): do something with the data @@ -158,8 +158,8 @@ static grpc_error *init_channel_elem(grpc_exec_ctx *exec_ctx, } /* Destructor for channel data */ -static void destroy_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem) { +static void destroy_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem) { /* TODO(dgq): do something with the data channel_data *chand = elem->channel_data; grpc_load_reporting_call_data lr_call_data = { @@ -173,11 +173,11 @@ static void destroy_channel_elem(grpc_exec_ctx *exec_ctx, */ } -static grpc_filtered_mdelem lr_trailing_md_filter(grpc_exec_ctx *exec_ctx, - void *user_data, +static grpc_filtered_mdelem lr_trailing_md_filter(grpc_exec_ctx* exec_ctx, + void* user_data, grpc_mdelem md) { - grpc_call_element *elem = (grpc_call_element *)user_data; - call_data *calld = (call_data *)elem->call_data; + grpc_call_element* elem = (grpc_call_element*)user_data; + call_data* calld = (call_data*)elem->call_data; if (grpc_slice_eq(GRPC_MDKEY(md), GRPC_MDSTR_LB_COST_BIN)) { calld->trailing_md_string = GRPC_MDVALUE(md); return GRPC_FILTERED_REMOVE(); @@ -186,10 +186,10 @@ static grpc_filtered_mdelem lr_trailing_md_filter(grpc_exec_ctx *exec_ctx, } static void lr_start_transport_stream_op_batch( - grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_transport_stream_op_batch *op) { + grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_transport_stream_op_batch* op) { GPR_TIMER_BEGIN("lr_start_transport_stream_op_batch", 0); - call_data *calld = (call_data *)elem->call_data; + call_data* calld = (call_data*)elem->call_data; if (op->recv_initial_metadata) { /* substitute our callback for the higher callback */ diff --git a/src/core/ext/filters/load_reporting/server_load_reporting_filter.h b/src/core/ext/filters/load_reporting/server_load_reporting_filter.h index 94d19cc2495..1baee5e7cd6 100644 --- a/src/core/ext/filters/load_reporting/server_load_reporting_filter.h +++ b/src/core/ext/filters/load_reporting/server_load_reporting_filter.h @@ -22,15 +22,7 @@ #include "src/core/ext/filters/load_reporting/server_load_reporting_plugin.h" #include "src/core/lib/channel/channel_stack.h" -#ifdef __cplusplus -extern "C" { -#endif - extern const grpc_channel_filter grpc_server_load_reporting_filter; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_LOAD_REPORTING_SERVER_LOAD_REPORTING_FILTER_H \ - */ + */ diff --git a/src/core/ext/filters/load_reporting/server_load_reporting_plugin.cc b/src/core/ext/filters/load_reporting/server_load_reporting_plugin.cc index 223fb3ee8b4..accb7797dd5 100644 --- a/src/core/ext/filters/load_reporting/server_load_reporting_plugin.cc +++ b/src/core/ext/filters/load_reporting/server_load_reporting_plugin.cc @@ -32,39 +32,39 @@ #include "src/core/lib/surface/call.h" #include "src/core/lib/surface/channel_init.h" -static bool is_load_reporting_enabled(const grpc_channel_args *a) { +static bool is_load_reporting_enabled(const grpc_channel_args* a) { return grpc_channel_arg_get_bool( grpc_channel_args_find(a, GRPC_ARG_ENABLE_LOAD_REPORTING), false); } static bool maybe_add_server_load_reporting_filter( - grpc_exec_ctx *exec_ctx, grpc_channel_stack_builder *builder, void *arg) { - const grpc_channel_args *args = + grpc_exec_ctx* exec_ctx, grpc_channel_stack_builder* builder, void* arg) { + const grpc_channel_args* args = grpc_channel_stack_builder_get_channel_arguments(builder); - const grpc_channel_filter *filter = (const grpc_channel_filter *)arg; - grpc_channel_stack_builder_iterator *it = + const grpc_channel_filter* filter = (const grpc_channel_filter*)arg; + grpc_channel_stack_builder_iterator* it = grpc_channel_stack_builder_iterator_find(builder, filter->name); const bool already_has_load_reporting_filter = !grpc_channel_stack_builder_iterator_is_end(it); grpc_channel_stack_builder_iterator_destroy(it); if (is_load_reporting_enabled(args) && !already_has_load_reporting_filter) { - return grpc_channel_stack_builder_prepend_filter(builder, filter, NULL, - NULL); + return grpc_channel_stack_builder_prepend_filter(builder, filter, nullptr, + nullptr); } return true; } grpc_arg grpc_load_reporting_enable_arg() { - return grpc_channel_arg_integer_create((char *)GRPC_ARG_ENABLE_LOAD_REPORTING, + return grpc_channel_arg_integer_create((char*)GRPC_ARG_ENABLE_LOAD_REPORTING, 1); } /* Plugin registration */ -extern "C" void grpc_server_load_reporting_plugin_init(void) { +void grpc_server_load_reporting_plugin_init(void) { grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL, INT_MAX, maybe_add_server_load_reporting_filter, - (void *)&grpc_server_load_reporting_filter); + (void*)&grpc_server_load_reporting_filter); } -extern "C" void grpc_server_load_reporting_plugin_shutdown() {} +void grpc_server_load_reporting_plugin_shutdown() {} diff --git a/src/core/ext/filters/load_reporting/server_load_reporting_plugin.h b/src/core/ext/filters/load_reporting/server_load_reporting_plugin.h index 65e254eb53f..4b694d336de 100644 --- a/src/core/ext/filters/load_reporting/server_load_reporting_plugin.h +++ b/src/core/ext/filters/load_reporting/server_load_reporting_plugin.h @@ -23,10 +23,6 @@ #include "src/core/lib/channel/channel_stack.h" -#ifdef __cplusplus -extern "C" { -#endif - /** Identifiers for the invocation point of the users LR callback */ typedef enum grpc_load_reporting_source { GRPC_LR_POINT_UNKNOWN = 0, @@ -49,19 +45,15 @@ typedef struct grpc_load_reporting_call_data { /** Only valid when \a source is \a GRPC_LR_POINT_CALL_DESTRUCTION, that is, * once the call has completed */ - const grpc_call_final_info *final_info; + const grpc_call_final_info* final_info; - const char *initial_md_string; /**< value string for LR's initial md key */ - const char *trailing_md_string; /**< value string for LR's trailing md key */ - const char *method_name; /**< Corresponds to :path header */ + const char* initial_md_string; /**< value string for LR's initial md key */ + const char* trailing_md_string; /**< value string for LR's trailing md key */ + const char* method_name; /**< Corresponds to :path header */ } grpc_load_reporting_call_data; /** Return a \a grpc_arg enabling load reporting */ grpc_arg grpc_load_reporting_enable_arg(); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_LOAD_REPORTING_SERVER_LOAD_REPORTING_PLUGIN_H \ - */ + */ diff --git a/src/core/ext/filters/max_age/max_age_filter.cc b/src/core/ext/filters/max_age/max_age_filter.cc index ade2e5bc825..917fbd9198f 100644 --- a/src/core/ext/filters/max_age/max_age_filter.cc +++ b/src/core/ext/filters/max_age/max_age_filter.cc @@ -126,8 +126,8 @@ static void start_max_age_timer_after_init(grpc_exec_ctx* exec_ctx, void* arg, grpc_exec_ctx_now(exec_ctx) + chand->max_connection_age, &chand->close_max_age_channel); gpr_mu_unlock(&chand->max_age_timer_mu); - grpc_transport_op* op = grpc_make_transport_op(NULL); - op->on_connectivity_state_change = &chand->channel_connectivity_changed, + grpc_transport_op* op = grpc_make_transport_op(nullptr); + op->on_connectivity_state_change = &chand->channel_connectivity_changed; op->connectivity_state = &chand->connectivity_state; grpc_channel_next_op(exec_ctx, grpc_channel_stack_element(chand->channel_stack, 0), op); @@ -159,7 +159,7 @@ static void close_max_idle_channel(grpc_exec_ctx* exec_ctx, void* arg, if (error == GRPC_ERROR_NONE) { /* Prevent the max idle timer from being set again */ gpr_atm_no_barrier_fetch_add(&chand->call_count, 1); - grpc_transport_op* op = grpc_make_transport_op(NULL); + grpc_transport_op* op = grpc_make_transport_op(nullptr); op->goaway_error = grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING("max_idle"), GRPC_ERROR_INT_HTTP2_ERROR, GRPC_HTTP2_NO_ERROR); @@ -204,7 +204,7 @@ static void force_close_max_age_channel(grpc_exec_ctx* exec_ctx, void* arg, chand->max_age_grace_timer_pending = false; gpr_mu_unlock(&chand->max_age_timer_mu); if (error == GRPC_ERROR_NONE) { - grpc_transport_op* op = grpc_make_transport_op(NULL); + grpc_transport_op* op = grpc_make_transport_op(nullptr); op->disconnect_with_error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Channel reaches max age"); grpc_channel_element* elem = @@ -221,8 +221,8 @@ static void channel_connectivity_changed(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { channel_data* chand = (channel_data*)arg; if (chand->connectivity_state != GRPC_CHANNEL_SHUTDOWN) { - grpc_transport_op* op = grpc_make_transport_op(NULL); - op->on_connectivity_state_change = &chand->channel_connectivity_changed, + grpc_transport_op* op = grpc_make_transport_op(nullptr); + op->on_connectivity_state_change = &chand->channel_connectivity_changed; op->connectivity_state = &chand->connectivity_state; grpc_channel_next_op( exec_ctx, grpc_channel_stack_element(chand->channel_stack, 0), op); @@ -398,16 +398,16 @@ static bool maybe_add_max_age_filter(grpc_exec_ctx* exec_ctx, MAX_CONNECTION_IDLE_INTEGER_OPTIONS) != INT_MAX; if (enable) { return grpc_channel_stack_builder_prepend_filter( - builder, &grpc_max_age_filter, NULL, NULL); + builder, &grpc_max_age_filter, nullptr, nullptr); } else { return true; } } -extern "C" void grpc_max_age_filter_init(void) { +void grpc_max_age_filter_init(void) { grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, - maybe_add_max_age_filter, NULL); + maybe_add_max_age_filter, nullptr); } -extern "C" void grpc_max_age_filter_shutdown(void) {} +void grpc_max_age_filter_shutdown(void) {} diff --git a/src/core/ext/filters/max_age/max_age_filter.h b/src/core/ext/filters/max_age/max_age_filter.h index eeeefd695e2..68fb4a4ca57 100644 --- a/src/core/ext/filters/max_age/max_age_filter.h +++ b/src/core/ext/filters/max_age/max_age_filter.h @@ -19,14 +19,6 @@ #include "src/core/lib/channel/channel_stack.h" -#ifdef __cplusplus -extern "C" { -#endif - extern const grpc_channel_filter grpc_max_age_filter; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_MAX_AGE_MAX_AGE_FILTER_H */ diff --git a/src/core/ext/filters/message_size/message_size_filter.cc b/src/core/ext/filters/message_size/message_size_filter.cc index 5dc131b9f6c..3d2252af2e6 100644 --- a/src/core/ext/filters/message_size/message_size_filter.cc +++ b/src/core/ext/filters/message_size/message_size_filter.cc @@ -30,40 +30,60 @@ #include "src/core/lib/surface/channel_init.h" #include "src/core/lib/transport/service_config.h" -typedef struct message_size_limits { +typedef struct { int max_send_size; int max_recv_size; } message_size_limits; -static void message_size_limits_free(grpc_exec_ctx* exec_ctx, void* value) { - gpr_free(value); +typedef struct { + gpr_refcount refs; + message_size_limits limits; +} refcounted_message_size_limits; + +static void* refcounted_message_size_limits_ref(void* value) { + refcounted_message_size_limits* limits = + (refcounted_message_size_limits*)value; + gpr_ref(&limits->refs); + return value; +} + +static void refcounted_message_size_limits_unref(grpc_exec_ctx* exec_ctx, + void* value) { + refcounted_message_size_limits* limits = + (refcounted_message_size_limits*)value; + if (gpr_unref(&limits->refs)) { + gpr_free(value); + } } -static void* message_size_limits_create_from_json(const grpc_json* json) { +static void* refcounted_message_size_limits_create_from_json( + const grpc_json* json) { int max_request_message_bytes = -1; int max_response_message_bytes = -1; - for (grpc_json* field = json->child; field != NULL; field = field->next) { - if (field->key == NULL) continue; + for (grpc_json* field = json->child; field != nullptr; field = field->next) { + if (field->key == nullptr) continue; if (strcmp(field->key, "maxRequestMessageBytes") == 0) { - if (max_request_message_bytes >= 0) return NULL; // Duplicate. + if (max_request_message_bytes >= 0) return nullptr; // Duplicate. if (field->type != GRPC_JSON_STRING && field->type != GRPC_JSON_NUMBER) { - return NULL; + return nullptr; } max_request_message_bytes = gpr_parse_nonnegative_int(field->value); - if (max_request_message_bytes == -1) return NULL; + if (max_request_message_bytes == -1) return nullptr; } else if (strcmp(field->key, "maxResponseMessageBytes") == 0) { - if (max_response_message_bytes >= 0) return NULL; // Duplicate. + if (max_response_message_bytes >= 0) return nullptr; // Duplicate. if (field->type != GRPC_JSON_STRING && field->type != GRPC_JSON_NUMBER) { - return NULL; + return nullptr; } max_response_message_bytes = gpr_parse_nonnegative_int(field->value); - if (max_response_message_bytes == -1) return NULL; + if (max_response_message_bytes == -1) return nullptr; } } - message_size_limits* value = - (message_size_limits*)gpr_malloc(sizeof(message_size_limits)); - value->max_send_size = max_request_message_bytes; - value->max_recv_size = max_response_message_bytes; + refcounted_message_size_limits* value = + (refcounted_message_size_limits*)gpr_malloc( + sizeof(refcounted_message_size_limits)); + gpr_ref_init(&value->refs, 1); + value->limits.max_send_size = max_request_message_bytes; + value->limits.max_recv_size = max_response_message_bytes; return value; } @@ -82,7 +102,7 @@ typedef struct call_data { typedef struct channel_data { message_size_limits limits; - // Maps path names to message_size_limits structs. + // Maps path names to refcounted_message_size_limits structs. grpc_slice_hash_table* method_limit_table; } channel_data; @@ -92,7 +112,7 @@ static void recv_message_ready(grpc_exec_ctx* exec_ctx, void* user_data, grpc_error* error) { grpc_call_element* elem = (grpc_call_element*)user_data; call_data* calld = (call_data*)elem->call_data; - if (*calld->recv_message != NULL && calld->limits.max_recv_size >= 0 && + if (*calld->recv_message != nullptr && calld->limits.max_recv_size >= 0 && (*calld->recv_message)->length > (size_t)calld->limits.max_recv_size) { char* message_string; gpr_asprintf(&message_string, @@ -155,7 +175,7 @@ static grpc_error* init_call_elem(grpc_exec_ctx* exec_ctx, channel_data* chand = (channel_data*)elem->channel_data; call_data* calld = (call_data*)elem->call_data; calld->call_combiner = args->call_combiner; - calld->next_recv_message_ready = NULL; + calld->next_recv_message_ready = nullptr; GRPC_CLOSURE_INIT(&calld->recv_message_ready, recv_message_ready, elem, grpc_schedule_on_exec_ctx); // Get max sizes from channel data, then merge in per-method config values. @@ -163,20 +183,20 @@ static grpc_error* init_call_elem(grpc_exec_ctx* exec_ctx, // apply the max request size to the send limit and the max response // size to the receive limit. calld->limits = chand->limits; - if (chand->method_limit_table != NULL) { - message_size_limits* limits = - (message_size_limits*)grpc_method_config_table_get( + if (chand->method_limit_table != nullptr) { + refcounted_message_size_limits* limits = + (refcounted_message_size_limits*)grpc_method_config_table_get( exec_ctx, chand->method_limit_table, args->path); - if (limits != NULL) { - if (limits->max_send_size >= 0 && - (limits->max_send_size < calld->limits.max_send_size || + if (limits != nullptr) { + if (limits->limits.max_send_size >= 0 && + (limits->limits.max_send_size < calld->limits.max_send_size || calld->limits.max_send_size < 0)) { - calld->limits.max_send_size = limits->max_send_size; + calld->limits.max_send_size = limits->limits.max_send_size; } - if (limits->max_recv_size >= 0 && - (limits->max_recv_size < calld->limits.max_recv_size || + if (limits->limits.max_recv_size >= 0 && + (limits->limits.max_recv_size < calld->limits.max_recv_size || calld->limits.max_recv_size < 0)) { - calld->limits.max_recv_size = limits->max_recv_size; + calld->limits.max_recv_size = limits->limits.max_recv_size; } } } @@ -230,15 +250,17 @@ static grpc_error* init_channel_elem(grpc_exec_ctx* exec_ctx, // Get method config table from channel args. const grpc_arg* channel_arg = grpc_channel_args_find(args->channel_args, GRPC_ARG_SERVICE_CONFIG); - if (channel_arg != NULL) { + if (channel_arg != nullptr) { GPR_ASSERT(channel_arg->type == GRPC_ARG_STRING); grpc_service_config* service_config = grpc_service_config_create(channel_arg->value.string); - if (service_config != NULL) { + if (service_config != nullptr) { chand->method_limit_table = grpc_service_config_create_method_config_table( - exec_ctx, service_config, message_size_limits_create_from_json, - message_size_limits_free); + exec_ctx, service_config, + refcounted_message_size_limits_create_from_json, + refcounted_message_size_limits_ref, + refcounted_message_size_limits_unref); grpc_service_config_destroy(service_config); } } @@ -277,27 +299,27 @@ static bool maybe_add_message_size_filter(grpc_exec_ctx* exec_ctx, } const grpc_arg* a = grpc_channel_args_find(channel_args, GRPC_ARG_SERVICE_CONFIG); - if (a != NULL) { + if (a != nullptr) { enable = true; } if (enable) { return grpc_channel_stack_builder_prepend_filter( - builder, &grpc_message_size_filter, NULL, NULL); + builder, &grpc_message_size_filter, nullptr, nullptr); } else { return true; } } -extern "C" void grpc_message_size_filter_init(void) { +void grpc_message_size_filter_init(void) { grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, - maybe_add_message_size_filter, NULL); + maybe_add_message_size_filter, nullptr); grpc_channel_init_register_stage(GRPC_CLIENT_DIRECT_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, - maybe_add_message_size_filter, NULL); + maybe_add_message_size_filter, nullptr); grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, - maybe_add_message_size_filter, NULL); + maybe_add_message_size_filter, nullptr); } -extern "C" void grpc_message_size_filter_shutdown(void) {} +void grpc_message_size_filter_shutdown(void) {} diff --git a/src/core/ext/filters/message_size/message_size_filter.h b/src/core/ext/filters/message_size/message_size_filter.h index da325d6f890..d3667f70037 100644 --- a/src/core/ext/filters/message_size/message_size_filter.h +++ b/src/core/ext/filters/message_size/message_size_filter.h @@ -19,14 +19,6 @@ #include "src/core/lib/channel/channel_stack.h" -#ifdef __cplusplus -extern "C" { -#endif - extern const grpc_channel_filter grpc_message_size_filter; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_MESSAGE_SIZE_MESSAGE_SIZE_FILTER_H */ diff --git a/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.cc b/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.cc index f77ed024211..4ab1ee4e79c 100644 --- a/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.cc +++ b/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.cc @@ -42,7 +42,7 @@ typedef struct call_data { // Find the user agent metadata element in the batch static bool get_user_agent_mdelem(const grpc_metadata_batch* batch, grpc_mdelem* md) { - if (batch->idx.named.user_agent != NULL) { + if (batch->idx.named.user_agent != nullptr) { *md = batch->idx.named.user_agent->md; return true; } @@ -104,7 +104,7 @@ static grpc_error* init_call_elem(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, const grpc_call_element_args* args) { call_data* calld = (call_data*)elem->call_data; - calld->next_recv_initial_metadata_ready = NULL; + calld->next_recv_initial_metadata_ready = nullptr; calld->workaround_active = false; GRPC_CLOSURE_INIT(&calld->recv_initial_metadata_ready, recv_initial_metadata_ready, elem, @@ -139,10 +139,10 @@ static bool parse_user_agent(grpc_mdelem md) { bool grpc_objc_specifier_seen = false; bool cronet_specifier_seen = false; char *major_version_str = user_agent_str, *minor_version_str; - long major_version, minor_version; + long major_version = 0, minor_version = 0; char* head = strtok(user_agent_str, " "); - while (head != NULL) { + while (head != nullptr) { if (!grpc_objc_specifier_seen && 0 == strncmp(head, grpc_objc_specifier, grpc_objc_specifier_len)) { major_version_str = head + grpc_objc_specifier_len; @@ -153,11 +153,11 @@ static bool parse_user_agent(grpc_mdelem md) { break; } - head = strtok(NULL, " "); + head = strtok(nullptr, " "); } if (grpc_objc_specifier_seen) { major_version_str = strtok(major_version_str, "."); - minor_version_str = strtok(NULL, "."); + minor_version_str = strtok(nullptr, "."); major_version = atol(major_version_str); minor_version = atol(minor_version_str); } @@ -186,22 +186,22 @@ static bool register_workaround_cronet_compression( grpc_channel_stack_builder_get_channel_arguments(builder); const grpc_arg* a = grpc_channel_args_find( channel_args, GRPC_ARG_WORKAROUND_CRONET_COMPRESSION); - if (a == NULL) { + if (a == nullptr) { return true; } if (grpc_channel_arg_get_bool(a, false) == false) { return true; } return grpc_channel_stack_builder_prepend_filter( - builder, &grpc_workaround_cronet_compression_filter, NULL, NULL); + builder, &grpc_workaround_cronet_compression_filter, nullptr, nullptr); } -extern "C" void grpc_workaround_cronet_compression_filter_init(void) { +void grpc_workaround_cronet_compression_filter_init(void) { grpc_channel_init_register_stage( GRPC_SERVER_CHANNEL, GRPC_WORKAROUND_PRIORITY_HIGH, - register_workaround_cronet_compression, NULL); + register_workaround_cronet_compression, nullptr); grpc_register_workaround(GRPC_WORKAROUND_ID_CRONET_COMPRESSION, parse_user_agent); } -extern "C" void grpc_workaround_cronet_compression_filter_shutdown(void) {} +void grpc_workaround_cronet_compression_filter_shutdown(void) {} diff --git a/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.h b/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.h index c8b07df63ec..9dae4f07342 100644 --- a/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.h +++ b/src/core/ext/filters/workarounds/workaround_cronet_compression_filter.h @@ -19,15 +19,7 @@ #include "src/core/lib/channel/channel_stack.h" -#ifdef __cplusplus -extern "C" { -#endif - extern const grpc_channel_filter grpc_workaround_cronet_compression_filter; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_WORKAROUNDS_WORKAROUND_CRONET_COMPRESSION_FILTER_H \ */ diff --git a/src/core/ext/filters/workarounds/workaround_utils.cc b/src/core/ext/filters/workarounds/workaround_utils.cc index e600fbee676..9d76582ea24 100644 --- a/src/core/ext/filters/workarounds/workaround_utils.cc +++ b/src/core/ext/filters/workarounds/workaround_utils.cc @@ -21,26 +21,26 @@ user_agent_parser ua_parser[GRPC_MAX_WORKAROUND_ID]; -static void destroy_user_agent_md(void *user_agent_md) { +static void destroy_user_agent_md(void* user_agent_md) { gpr_free(user_agent_md); } -grpc_workaround_user_agent_md *grpc_parse_user_agent(grpc_mdelem md) { - grpc_workaround_user_agent_md *user_agent_md = - (grpc_workaround_user_agent_md *)grpc_mdelem_get_user_data( +grpc_workaround_user_agent_md* grpc_parse_user_agent(grpc_mdelem md) { + grpc_workaround_user_agent_md* user_agent_md = + (grpc_workaround_user_agent_md*)grpc_mdelem_get_user_data( md, destroy_user_agent_md); - if (NULL != user_agent_md) { + if (nullptr != user_agent_md) { return user_agent_md; } - user_agent_md = (grpc_workaround_user_agent_md *)gpr_malloc( + user_agent_md = (grpc_workaround_user_agent_md*)gpr_malloc( sizeof(grpc_workaround_user_agent_md)); for (int i = 0; i < GRPC_MAX_WORKAROUND_ID; i++) { if (ua_parser[i]) { user_agent_md->workaround_active[i] = ua_parser[i](md); } } - grpc_mdelem_set_user_data(md, destroy_user_agent_md, (void *)user_agent_md); + grpc_mdelem_set_user_data(md, destroy_user_agent_md, (void*)user_agent_md); return user_agent_md; } diff --git a/src/core/ext/filters/workarounds/workaround_utils.h b/src/core/ext/filters/workarounds/workaround_utils.h index 3913cae6b2b..d6ef5e84fa5 100644 --- a/src/core/ext/filters/workarounds/workaround_utils.h +++ b/src/core/ext/filters/workarounds/workaround_utils.h @@ -24,22 +24,14 @@ #define GRPC_WORKAROUND_PRIORITY_HIGH 10001 #define GRPC_WORKAROUND_PROIRITY_LOW 9999 -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_workaround_user_agent_md { bool workaround_active[GRPC_MAX_WORKAROUND_ID]; } grpc_workaround_user_agent_md; -grpc_workaround_user_agent_md *grpc_parse_user_agent(grpc_mdelem md); +grpc_workaround_user_agent_md* grpc_parse_user_agent(grpc_mdelem md); typedef bool (*user_agent_parser)(grpc_mdelem); void grpc_register_workaround(uint32_t id, user_agent_parser parser); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_FILTERS_WORKAROUNDS_WORKAROUND_UTILS_H */ diff --git a/src/core/ext/transport/chttp2/alpn/alpn.cc b/src/core/ext/transport/chttp2/alpn/alpn.cc index ca2e801ec83..89892457d6d 100644 --- a/src/core/ext/transport/chttp2/alpn/alpn.cc +++ b/src/core/ext/transport/chttp2/alpn/alpn.cc @@ -21,9 +21,9 @@ #include /* in order of preference */ -static const char *const supported_versions[] = {"grpc-exp", "h2"}; +static const char* const supported_versions[] = {"grpc-exp", "h2"}; -int grpc_chttp2_is_alpn_version_supported(const char *version, size_t size) { +int grpc_chttp2_is_alpn_version_supported(const char* version, size_t size) { size_t i; for (i = 0; i < GPR_ARRAY_SIZE(supported_versions); i++) { if (!strncmp(version, supported_versions[i], size)) return 1; @@ -35,7 +35,7 @@ size_t grpc_chttp2_num_alpn_versions(void) { return GPR_ARRAY_SIZE(supported_versions); } -const char *grpc_chttp2_get_alpn_version_index(size_t i) { +const char* grpc_chttp2_get_alpn_version_index(size_t i) { GPR_ASSERT(i < GPR_ARRAY_SIZE(supported_versions)); return supported_versions[i]; } diff --git a/src/core/ext/transport/chttp2/alpn/alpn.h b/src/core/ext/transport/chttp2/alpn/alpn.h index 99b928ea591..fd7513c6654 100644 --- a/src/core/ext/transport/chttp2/alpn/alpn.h +++ b/src/core/ext/transport/chttp2/alpn/alpn.h @@ -21,22 +21,14 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /* Retuns 1 if the version is supported, 0 otherwise. */ -int grpc_chttp2_is_alpn_version_supported(const char *version, size_t size); +int grpc_chttp2_is_alpn_version_supported(const char* version, size_t size); /* Returns the number of protocol versions to advertise */ size_t grpc_chttp2_num_alpn_versions(void); /* Returns the protocol version at index i (0 <= i < * grpc_chttp2_num_alpn_versions()) */ -const char *grpc_chttp2_get_alpn_version_index(size_t i); - -#ifdef __cplusplus -} -#endif +const char* grpc_chttp2_get_alpn_version_index(size_t i); #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_ALPN_ALPN_H */ diff --git a/src/core/ext/transport/chttp2/client/chttp2_connector.cc b/src/core/ext/transport/chttp2/client/chttp2_connector.cc index 74839f21560..819f66aec34 100644 --- a/src/core/ext/transport/chttp2/client/chttp2_connector.cc +++ b/src/core/ext/transport/chttp2/client/chttp2_connector.cc @@ -45,56 +45,56 @@ typedef struct { bool shutdown; bool connecting; - grpc_closure *notify; + grpc_closure* notify; grpc_connect_in_args args; - grpc_connect_out_args *result; + grpc_connect_out_args* result; - grpc_endpoint *endpoint; // Non-NULL until handshaking starts. + grpc_endpoint* endpoint; // Non-NULL until handshaking starts. grpc_closure connected; - grpc_handshake_manager *handshake_mgr; + grpc_handshake_manager* handshake_mgr; } chttp2_connector; -static void chttp2_connector_ref(grpc_connector *con) { - chttp2_connector *c = (chttp2_connector *)con; +static void chttp2_connector_ref(grpc_connector* con) { + chttp2_connector* c = (chttp2_connector*)con; gpr_ref(&c->refs); } -static void chttp2_connector_unref(grpc_exec_ctx *exec_ctx, - grpc_connector *con) { - chttp2_connector *c = (chttp2_connector *)con; +static void chttp2_connector_unref(grpc_exec_ctx* exec_ctx, + grpc_connector* con) { + chttp2_connector* c = (chttp2_connector*)con; if (gpr_unref(&c->refs)) { gpr_mu_destroy(&c->mu); // If handshaking is not yet in progress, destroy the endpoint. // Otherwise, the handshaker will do this for us. - if (c->endpoint != NULL) grpc_endpoint_destroy(exec_ctx, c->endpoint); + if (c->endpoint != nullptr) grpc_endpoint_destroy(exec_ctx, c->endpoint); gpr_free(c); } } -static void chttp2_connector_shutdown(grpc_exec_ctx *exec_ctx, - grpc_connector *con, grpc_error *why) { - chttp2_connector *c = (chttp2_connector *)con; +static void chttp2_connector_shutdown(grpc_exec_ctx* exec_ctx, + grpc_connector* con, grpc_error* why) { + chttp2_connector* c = (chttp2_connector*)con; gpr_mu_lock(&c->mu); c->shutdown = true; - if (c->handshake_mgr != NULL) { + if (c->handshake_mgr != nullptr) { grpc_handshake_manager_shutdown(exec_ctx, c->handshake_mgr, GRPC_ERROR_REF(why)); } // If handshaking is not yet in progress, shutdown the endpoint. // Otherwise, the handshaker will do this for us. - if (!c->connecting && c->endpoint != NULL) { + if (!c->connecting && c->endpoint != nullptr) { grpc_endpoint_shutdown(exec_ctx, c->endpoint, GRPC_ERROR_REF(why)); } gpr_mu_unlock(&c->mu); GRPC_ERROR_UNREF(why); } -static void on_handshake_done(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_handshaker_args *args = (grpc_handshaker_args *)arg; - chttp2_connector *c = (chttp2_connector *)args->user_data; +static void on_handshake_done(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_handshaker_args* args = (grpc_handshaker_args*)arg; + chttp2_connector* c = (chttp2_connector*)args->user_data; gpr_mu_lock(&c->mu); if (error != GRPC_ERROR_NONE || c->shutdown) { if (error == GRPC_ERROR_NONE) { @@ -117,37 +117,62 @@ static void on_handshake_done(grpc_exec_ctx *exec_ctx, void *arg, } else { grpc_endpoint_delete_from_pollset_set(exec_ctx, args->endpoint, c->args.interested_parties); - c->result->transport = - grpc_create_chttp2_transport(exec_ctx, args->args, args->endpoint, 1); + c->result->transport = grpc_create_chttp2_transport(exec_ctx, args->args, + args->endpoint, true); GPR_ASSERT(c->result->transport); + // TODO(roth): We ideally want to wait until we receive HTTP/2 + // settings from the server before we consider the connection + // established. If that doesn't happen before the connection + // timeout expires, then we should consider the connection attempt a + // failure and feed that information back into the backoff code. + // We could pass a notify_on_receive_settings callback to + // grpc_chttp2_transport_start_reading() to let us know when + // settings are received, but we would need to figure out how to use + // that information here. + // + // Unfortunately, we don't currently have a way to split apart the two + // effects of scheduling c->notify: we start sending RPCs immediately + // (which we want to do) and we consider the connection attempt successful + // (which we don't want to do until we get the notify_on_receive_settings + // callback from the transport). If we could split those things + // apart, then we could start sending RPCs but then wait for our + // timeout before deciding if the connection attempt is successful. + // If the attempt is not successful, then we would tear down the + // transport and feed the failure back into the backoff code. + // + // In addition, even if we did that, we would probably not want to do + // so until after transparent retries is implemented. Otherwise, any + // RPC that we attempt to send on the connection before the timeout + // would fail instead of being retried on a subsequent attempt. grpc_chttp2_transport_start_reading(exec_ctx, c->result->transport, - args->read_buffer); + args->read_buffer, nullptr); c->result->channel_args = args->args; } - grpc_closure *notify = c->notify; - c->notify = NULL; + grpc_closure* notify = c->notify; + c->notify = nullptr; GRPC_CLOSURE_SCHED(exec_ctx, notify, error); grpc_handshake_manager_destroy(exec_ctx, c->handshake_mgr); - c->handshake_mgr = NULL; + c->handshake_mgr = nullptr; gpr_mu_unlock(&c->mu); - chttp2_connector_unref(exec_ctx, (grpc_connector *)c); + chttp2_connector_unref(exec_ctx, (grpc_connector*)c); } -static void start_handshake_locked(grpc_exec_ctx *exec_ctx, - chttp2_connector *c) { +static void start_handshake_locked(grpc_exec_ctx* exec_ctx, + chttp2_connector* c) { c->handshake_mgr = grpc_handshake_manager_create(); grpc_handshakers_add(exec_ctx, HANDSHAKER_CLIENT, c->args.channel_args, c->handshake_mgr); grpc_endpoint_add_to_pollset_set(exec_ctx, c->endpoint, c->args.interested_parties); grpc_handshake_manager_do_handshake( - exec_ctx, c->handshake_mgr, c->endpoint, c->args.channel_args, - c->args.deadline, NULL /* acceptor */, on_handshake_done, c); - c->endpoint = NULL; // Endpoint handed off to handshake manager. + exec_ctx, c->handshake_mgr, c->args.interested_parties, c->endpoint, + c->args.channel_args, c->args.deadline, nullptr /* acceptor */, + on_handshake_done, c); + c->endpoint = nullptr; // Endpoint handed off to handshake manager. } -static void connected(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { - chttp2_connector *c = (chttp2_connector *)arg; +static void connected(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { + chttp2_connector* c = (chttp2_connector*)arg; gpr_mu_lock(&c->mu); GPR_ASSERT(c->connecting); c->connecting = false; @@ -158,35 +183,35 @@ static void connected(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { error = GRPC_ERROR_REF(error); } memset(c->result, 0, sizeof(*c->result)); - grpc_closure *notify = c->notify; - c->notify = NULL; + grpc_closure* notify = c->notify; + c->notify = nullptr; GRPC_CLOSURE_SCHED(exec_ctx, notify, error); - if (c->endpoint != NULL) { + if (c->endpoint != nullptr) { grpc_endpoint_shutdown(exec_ctx, c->endpoint, GRPC_ERROR_REF(error)); } gpr_mu_unlock(&c->mu); - chttp2_connector_unref(exec_ctx, (grpc_connector *)arg); + chttp2_connector_unref(exec_ctx, (grpc_connector*)arg); } else { - GPR_ASSERT(c->endpoint != NULL); + GPR_ASSERT(c->endpoint != nullptr); start_handshake_locked(exec_ctx, c); gpr_mu_unlock(&c->mu); } } -static void chttp2_connector_connect(grpc_exec_ctx *exec_ctx, - grpc_connector *con, - const grpc_connect_in_args *args, - grpc_connect_out_args *result, - grpc_closure *notify) { - chttp2_connector *c = (chttp2_connector *)con; +static void chttp2_connector_connect(grpc_exec_ctx* exec_ctx, + grpc_connector* con, + const grpc_connect_in_args* args, + grpc_connect_out_args* result, + grpc_closure* notify) { + chttp2_connector* c = (chttp2_connector*)con; grpc_resolved_address addr; grpc_get_subchannel_address_arg(exec_ctx, args->channel_args, &addr); gpr_mu_lock(&c->mu); - GPR_ASSERT(c->notify == NULL); + GPR_ASSERT(c->notify == nullptr); c->notify = notify; c->args = *args; c->result = result; - GPR_ASSERT(c->endpoint == NULL); + GPR_ASSERT(c->endpoint == nullptr); chttp2_connector_ref(con); // Ref taken for callback. GRPC_CLOSURE_INIT(&c->connected, connected, c, grpc_schedule_on_exec_ctx); GPR_ASSERT(!c->connecting); @@ -201,8 +226,8 @@ static const grpc_connector_vtable chttp2_connector_vtable = { chttp2_connector_ref, chttp2_connector_unref, chttp2_connector_shutdown, chttp2_connector_connect}; -grpc_connector *grpc_chttp2_connector_create() { - chttp2_connector *c = (chttp2_connector *)gpr_zalloc(sizeof(*c)); +grpc_connector* grpc_chttp2_connector_create() { + chttp2_connector* c = (chttp2_connector*)gpr_zalloc(sizeof(*c)); c->base.vtable = &chttp2_connector_vtable; gpr_mu_init(&c->mu); gpr_ref_init(&c->refs, 1); diff --git a/src/core/ext/transport/chttp2/client/chttp2_connector.h b/src/core/ext/transport/chttp2/client/chttp2_connector.h index 63f264e0efa..e258892cfc7 100644 --- a/src/core/ext/transport/chttp2/client/chttp2_connector.h +++ b/src/core/ext/transport/chttp2/client/chttp2_connector.h @@ -19,16 +19,8 @@ #ifndef GRPC_CORE_EXT_TRANSPORT_CHTTP2_CLIENT_CHTTP2_CONNECTOR_H #define GRPC_CORE_EXT_TRANSPORT_CHTTP2_CLIENT_CHTTP2_CONNECTOR_H -#ifdef __cplusplus -extern "C" { -#endif - #include "src/core/ext/filters/client_channel/connector.h" grpc_connector* grpc_chttp2_connector_create(); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_CLIENT_CHTTP2_CONNECTOR_H */ diff --git a/src/core/ext/transport/chttp2/client/insecure/channel_create.cc b/src/core/ext/transport/chttp2/client/insecure/channel_create.cc index 6410a6043db..028b69e5ff9 100644 --- a/src/core/ext/transport/chttp2/client/insecure/channel_create.cc +++ b/src/core/ext/transport/chttp2/client/insecure/channel_create.cc @@ -31,38 +31,38 @@ #include "src/core/lib/surface/channel.h" static void client_channel_factory_ref( - grpc_client_channel_factory *cc_factory) {} + grpc_client_channel_factory* cc_factory) {} static void client_channel_factory_unref( - grpc_exec_ctx *exec_ctx, grpc_client_channel_factory *cc_factory) {} + grpc_exec_ctx* exec_ctx, grpc_client_channel_factory* cc_factory) {} -static grpc_subchannel *client_channel_factory_create_subchannel( - grpc_exec_ctx *exec_ctx, grpc_client_channel_factory *cc_factory, - const grpc_subchannel_args *args) { - grpc_connector *connector = grpc_chttp2_connector_create(); - grpc_subchannel *s = grpc_subchannel_create(exec_ctx, connector, args); +static grpc_subchannel* client_channel_factory_create_subchannel( + grpc_exec_ctx* exec_ctx, grpc_client_channel_factory* cc_factory, + const grpc_subchannel_args* args) { + grpc_connector* connector = grpc_chttp2_connector_create(); + grpc_subchannel* s = grpc_subchannel_create(exec_ctx, connector, args); grpc_connector_unref(exec_ctx, connector); return s; } -static grpc_channel *client_channel_factory_create_channel( - grpc_exec_ctx *exec_ctx, grpc_client_channel_factory *cc_factory, - const char *target, grpc_client_channel_type type, - const grpc_channel_args *args) { - if (target == NULL) { +static grpc_channel* client_channel_factory_create_channel( + grpc_exec_ctx* exec_ctx, grpc_client_channel_factory* cc_factory, + const char* target, grpc_client_channel_type type, + const grpc_channel_args* args) { + if (target == nullptr) { gpr_log(GPR_ERROR, "cannot create channel with NULL target name"); - return NULL; + return nullptr; } // Add channel arg containing the server URI. grpc_arg arg = grpc_channel_arg_string_create( - (char *)GRPC_ARG_SERVER_URI, + (char*)GRPC_ARG_SERVER_URI, grpc_resolver_factory_add_default_prefix_if_needed(exec_ctx, target)); - const char *to_remove[] = {GRPC_ARG_SERVER_URI}; - grpc_channel_args *new_args = + const char* to_remove[] = {GRPC_ARG_SERVER_URI}; + grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(args, to_remove, 1, &arg, 1); gpr_free(arg.value.string); - grpc_channel *channel = grpc_channel_create(exec_ctx, target, new_args, - GRPC_CLIENT_CHANNEL, NULL); + grpc_channel* channel = grpc_channel_create(exec_ctx, target, new_args, + GRPC_CLIENT_CHANNEL, nullptr); grpc_channel_args_destroy(exec_ctx, new_args); return channel; } @@ -79,26 +79,27 @@ static grpc_client_channel_factory client_channel_factory = { Asynchronously: - resolve target - connect to it (trying alternatives as presented) - perform handshakes */ -grpc_channel *grpc_insecure_channel_create(const char *target, - const grpc_channel_args *args, - void *reserved) { +grpc_channel* grpc_insecure_channel_create(const char* target, + const grpc_channel_args* args, + void* reserved) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GRPC_API_TRACE( "grpc_insecure_channel_create(target=%s, args=%p, reserved=%p)", 3, (target, args, reserved)); - GPR_ASSERT(reserved == NULL); + GPR_ASSERT(reserved == nullptr); // Add channel arg containing the client channel factory. grpc_arg arg = grpc_client_channel_factory_create_channel_arg(&client_channel_factory); - grpc_channel_args *new_args = grpc_channel_args_copy_and_add(args, &arg, 1); + grpc_channel_args* new_args = grpc_channel_args_copy_and_add(args, &arg, 1); // Create channel. - grpc_channel *channel = client_channel_factory_create_channel( + grpc_channel* channel = client_channel_factory_create_channel( &exec_ctx, &client_channel_factory, target, GRPC_CLIENT_CHANNEL_TYPE_REGULAR, new_args); // Clean up. grpc_channel_args_destroy(&exec_ctx, new_args); grpc_exec_ctx_finish(&exec_ctx); - return channel != NULL ? channel : grpc_lame_client_channel_create( - target, GRPC_STATUS_INTERNAL, - "Failed to create client channel"); + return channel != nullptr ? channel + : grpc_lame_client_channel_create( + target, GRPC_STATUS_INTERNAL, + "Failed to create client channel"); } diff --git a/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc b/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc index dd88136f7b5..c6b149d0b1d 100644 --- a/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc +++ b/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc @@ -35,42 +35,43 @@ #include "src/core/lib/surface/channel.h" #include "src/core/lib/transport/transport.h" -grpc_channel *grpc_insecure_channel_create_from_fd( - const char *target, int fd, const grpc_channel_args *args) { +grpc_channel* grpc_insecure_channel_create_from_fd( + const char* target, int fd, const grpc_channel_args* args) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GRPC_API_TRACE("grpc_insecure_channel_create(target=%p, fd=%d, args=%p)", 3, (target, fd, args)); grpc_arg default_authority_arg = grpc_channel_arg_string_create( - (char *)GRPC_ARG_DEFAULT_AUTHORITY, (char *)"test.authority"); - grpc_channel_args *final_args = + (char*)GRPC_ARG_DEFAULT_AUTHORITY, (char*)"test.authority"); + grpc_channel_args* final_args = grpc_channel_args_copy_and_add(args, &default_authority_arg, 1); int flags = fcntl(fd, F_GETFL, 0); GPR_ASSERT(fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0); - grpc_endpoint *client = grpc_tcp_client_create_from_fd( + grpc_endpoint* client = grpc_tcp_client_create_from_fd( &exec_ctx, grpc_fd_create(fd, "client"), args, "fd-client"); - grpc_transport *transport = - grpc_create_chttp2_transport(&exec_ctx, final_args, client, 1); + grpc_transport* transport = + grpc_create_chttp2_transport(&exec_ctx, final_args, client, true); GPR_ASSERT(transport); - grpc_channel *channel = grpc_channel_create( + grpc_channel* channel = grpc_channel_create( &exec_ctx, target, final_args, GRPC_CLIENT_DIRECT_CHANNEL, transport); grpc_channel_args_destroy(&exec_ctx, final_args); - grpc_chttp2_transport_start_reading(&exec_ctx, transport, NULL); + grpc_chttp2_transport_start_reading(&exec_ctx, transport, nullptr, nullptr); grpc_exec_ctx_finish(&exec_ctx); - return channel != NULL ? channel : grpc_lame_client_channel_create( - target, GRPC_STATUS_INTERNAL, - "Failed to create client channel"); + return channel != nullptr ? channel + : grpc_lame_client_channel_create( + target, GRPC_STATUS_INTERNAL, + "Failed to create client channel"); } #else // !GPR_SUPPORT_CHANNELS_FROM_FD -grpc_channel *grpc_insecure_channel_create_from_fd( - const char *target, int fd, const grpc_channel_args *args) { +grpc_channel* grpc_insecure_channel_create_from_fd( + const char* target, int fd, const grpc_channel_args* args) { GPR_ASSERT(0); return NULL; } diff --git a/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc b/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc index fe296cf4ff3..dd2bc427a7b 100644 --- a/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc +++ b/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc @@ -38,60 +38,60 @@ #include "src/core/lib/surface/channel.h" static void client_channel_factory_ref( - grpc_client_channel_factory *cc_factory) {} + grpc_client_channel_factory* cc_factory) {} static void client_channel_factory_unref( - grpc_exec_ctx *exec_ctx, grpc_client_channel_factory *cc_factory) {} + grpc_exec_ctx* exec_ctx, grpc_client_channel_factory* cc_factory) {} -static grpc_subchannel_args *get_secure_naming_subchannel_args( - grpc_exec_ctx *exec_ctx, const grpc_subchannel_args *args) { - grpc_channel_credentials *channel_credentials = +static grpc_subchannel_args* get_secure_naming_subchannel_args( + grpc_exec_ctx* exec_ctx, const grpc_subchannel_args* args) { + grpc_channel_credentials* channel_credentials = grpc_channel_credentials_find_in_args(args->args); - if (channel_credentials == NULL) { + if (channel_credentials == nullptr) { gpr_log(GPR_ERROR, "Can't create subchannel: channel credentials missing for secure " "channel."); - return NULL; + return nullptr; } // Make sure security connector does not already exist in args. - if (grpc_security_connector_find_in_args(args->args) != NULL) { + if (grpc_security_connector_find_in_args(args->args) != nullptr) { gpr_log(GPR_ERROR, "Can't create subchannel: security connector already present in " "channel args."); - return NULL; + return nullptr; } // To which address are we connecting? By default, use the server URI. - const grpc_arg *server_uri_arg = + const grpc_arg* server_uri_arg = grpc_channel_args_find(args->args, GRPC_ARG_SERVER_URI); - GPR_ASSERT(server_uri_arg != NULL); + GPR_ASSERT(server_uri_arg != nullptr); GPR_ASSERT(server_uri_arg->type == GRPC_ARG_STRING); - const char *server_uri_str = server_uri_arg->value.string; - GPR_ASSERT(server_uri_str != NULL); - grpc_uri *server_uri = + const char* server_uri_str = server_uri_arg->value.string; + GPR_ASSERT(server_uri_str != nullptr); + grpc_uri* server_uri = grpc_uri_parse(exec_ctx, server_uri_str, true /* supress errors */); - GPR_ASSERT(server_uri != NULL); - const char *server_uri_path; + GPR_ASSERT(server_uri != nullptr); + const char* server_uri_path; server_uri_path = server_uri->path[0] == '/' ? server_uri->path + 1 : server_uri->path; - const grpc_slice_hash_table *targets_info = + const grpc_slice_hash_table* targets_info = grpc_lb_targets_info_find_in_args(args->args); - char *target_name_to_check = NULL; - if (targets_info != NULL) { // LB channel + char* target_name_to_check = nullptr; + if (targets_info != nullptr) { // LB channel // Find the balancer name for the target. - const char *target_uri_str = + const char* target_uri_str = grpc_get_subchannel_address_uri_arg(args->args); - grpc_uri *target_uri = + grpc_uri* target_uri = grpc_uri_parse(exec_ctx, target_uri_str, false /* suppress errors */); - GPR_ASSERT(target_uri != NULL); + GPR_ASSERT(target_uri != nullptr); if (target_uri->path[0] != '\0') { // "path" may be empty const grpc_slice key = grpc_slice_from_static_string( target_uri->path[0] == '/' ? target_uri->path + 1 : target_uri->path); - const char *value = - (const char *)grpc_slice_hash_table_get(targets_info, key); - if (value != NULL) target_name_to_check = gpr_strdup(value); + const char* value = + (const char*)grpc_slice_hash_table_get(targets_info, key); + if (value != nullptr) target_name_to_check = gpr_strdup(value); grpc_slice_unref_internal(exec_ctx, key); } - if (target_name_to_check == NULL) { + if (target_name_to_check == nullptr) { // If the target name to check hasn't already been set, fall back to using // SERVER_URI target_name_to_check = gpr_strdup(server_uri_path); @@ -101,10 +101,10 @@ static grpc_subchannel_args *get_secure_naming_subchannel_args( target_name_to_check = gpr_strdup(server_uri_path); } grpc_uri_destroy(server_uri); - GPR_ASSERT(target_name_to_check != NULL); - grpc_channel_security_connector *subchannel_security_connector = NULL; + GPR_ASSERT(target_name_to_check != nullptr); + grpc_channel_security_connector* subchannel_security_connector = nullptr; // Create the security connector using the credentials and target name. - grpc_channel_args *new_args_from_connector = NULL; + grpc_channel_args* new_args_from_connector = nullptr; const grpc_security_status security_status = grpc_channel_credentials_create_security_connector( exec_ctx, channel_credentials, target_name_to_check, args->args, @@ -114,66 +114,66 @@ static grpc_subchannel_args *get_secure_naming_subchannel_args( "Failed to create secure subchannel for secure name '%s'", target_name_to_check); gpr_free(target_name_to_check); - return NULL; + return nullptr; } gpr_free(target_name_to_check); grpc_arg new_security_connector_arg = grpc_security_connector_to_arg(&subchannel_security_connector->base); - grpc_channel_args *new_args = grpc_channel_args_copy_and_add( - new_args_from_connector != NULL ? new_args_from_connector : args->args, + grpc_channel_args* new_args = grpc_channel_args_copy_and_add( + new_args_from_connector != nullptr ? new_args_from_connector : args->args, &new_security_connector_arg, 1); GRPC_SECURITY_CONNECTOR_UNREF(exec_ctx, &subchannel_security_connector->base, "lb_channel_create"); - if (new_args_from_connector != NULL) { + if (new_args_from_connector != nullptr) { grpc_channel_args_destroy(exec_ctx, new_args_from_connector); } - grpc_subchannel_args *final_sc_args = - (grpc_subchannel_args *)gpr_malloc(sizeof(*final_sc_args)); + grpc_subchannel_args* final_sc_args = + (grpc_subchannel_args*)gpr_malloc(sizeof(*final_sc_args)); memcpy(final_sc_args, args, sizeof(*args)); final_sc_args->args = new_args; return final_sc_args; } -static grpc_subchannel *client_channel_factory_create_subchannel( - grpc_exec_ctx *exec_ctx, grpc_client_channel_factory *cc_factory, - const grpc_subchannel_args *args) { - grpc_subchannel_args *subchannel_args = +static grpc_subchannel* client_channel_factory_create_subchannel( + grpc_exec_ctx* exec_ctx, grpc_client_channel_factory* cc_factory, + const grpc_subchannel_args* args) { + grpc_subchannel_args* subchannel_args = get_secure_naming_subchannel_args(exec_ctx, args); - if (subchannel_args == NULL) { + if (subchannel_args == nullptr) { gpr_log( GPR_ERROR, "Failed to create subchannel arguments during subchannel creation."); - return NULL; + return nullptr; } - grpc_connector *connector = grpc_chttp2_connector_create(); - grpc_subchannel *s = + grpc_connector* connector = grpc_chttp2_connector_create(); + grpc_subchannel* s = grpc_subchannel_create(exec_ctx, connector, subchannel_args); grpc_connector_unref(exec_ctx, connector); grpc_channel_args_destroy(exec_ctx, - (grpc_channel_args *)subchannel_args->args); + (grpc_channel_args*)subchannel_args->args); gpr_free(subchannel_args); return s; } -static grpc_channel *client_channel_factory_create_channel( - grpc_exec_ctx *exec_ctx, grpc_client_channel_factory *cc_factory, - const char *target, grpc_client_channel_type type, - const grpc_channel_args *args) { - if (target == NULL) { +static grpc_channel* client_channel_factory_create_channel( + grpc_exec_ctx* exec_ctx, grpc_client_channel_factory* cc_factory, + const char* target, grpc_client_channel_type type, + const grpc_channel_args* args) { + if (target == nullptr) { gpr_log(GPR_ERROR, "cannot create channel with NULL target name"); - return NULL; + return nullptr; } // Add channel arg containing the server URI. grpc_arg arg = grpc_channel_arg_string_create( - (char *)GRPC_ARG_SERVER_URI, + (char*)GRPC_ARG_SERVER_URI, grpc_resolver_factory_add_default_prefix_if_needed(exec_ctx, target)); - const char *to_remove[] = {GRPC_ARG_SERVER_URI}; - grpc_channel_args *new_args = + const char* to_remove[] = {GRPC_ARG_SERVER_URI}; + grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(args, to_remove, 1, &arg, 1); gpr_free(arg.value.string); - grpc_channel *channel = grpc_channel_create(exec_ctx, target, new_args, - GRPC_CLIENT_CHANNEL, NULL); + grpc_channel* channel = grpc_channel_create(exec_ctx, target, new_args, + GRPC_CLIENT_CHANNEL, nullptr); grpc_channel_args_destroy(exec_ctx, new_args); return channel; } @@ -190,24 +190,24 @@ static grpc_client_channel_factory client_channel_factory = { // Asynchronously: - resolve target // - connect to it (trying alternatives as presented) // - perform handshakes -grpc_channel *grpc_secure_channel_create(grpc_channel_credentials *creds, - const char *target, - const grpc_channel_args *args, - void *reserved) { +grpc_channel* grpc_secure_channel_create(grpc_channel_credentials* creds, + const char* target, + const grpc_channel_args* args, + void* reserved) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GRPC_API_TRACE( "grpc_secure_channel_create(creds=%p, target=%s, args=%p, " "reserved=%p)", - 4, ((void *)creds, target, (void *)args, (void *)reserved)); - GPR_ASSERT(reserved == NULL); - grpc_channel *channel = NULL; - if (creds != NULL) { + 4, ((void*)creds, target, (void*)args, (void*)reserved)); + GPR_ASSERT(reserved == nullptr); + grpc_channel* channel = nullptr; + if (creds != nullptr) { // Add channel args containing the client channel factory and channel // credentials. grpc_arg args_to_add[] = { grpc_client_channel_factory_create_channel_arg(&client_channel_factory), grpc_channel_credentials_to_arg(creds)}; - grpc_channel_args *new_args = grpc_channel_args_copy_and_add( + grpc_channel_args* new_args = grpc_channel_args_copy_and_add( args, args_to_add, GPR_ARRAY_SIZE(args_to_add)); // Create channel. channel = client_channel_factory_create_channel( @@ -217,8 +217,8 @@ grpc_channel *grpc_secure_channel_create(grpc_channel_credentials *creds, grpc_channel_args_destroy(&exec_ctx, new_args); grpc_exec_ctx_finish(&exec_ctx); } - return channel != NULL ? channel - : grpc_lame_client_channel_create( - target, GRPC_STATUS_INTERNAL, - "Failed to create secure client channel"); + return channel != nullptr ? channel + : grpc_lame_client_channel_create( + target, GRPC_STATUS_INTERNAL, + "Failed to create secure client channel"); } diff --git a/src/core/ext/transport/chttp2/server/chttp2_server.cc b/src/core/ext/transport/chttp2/server/chttp2_server.cc index 7ac7f4ece82..49ee6774640 100644 --- a/src/core/ext/transport/chttp2/server/chttp2_server.cc +++ b/src/core/ext/transport/chttp2/server/chttp2_server.cc @@ -21,6 +21,7 @@ #include #include +#include #include #include @@ -31,6 +32,7 @@ #include "src/core/ext/filters/http/server/http_server_filter.h" #include "src/core/ext/transport/chttp2/transport/chttp2_transport.h" +#include "src/core/ext/transport/chttp2/transport/internal.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/handshaker.h" #include "src/core/lib/channel/handshaker_registry.h" @@ -42,34 +44,73 @@ #include "src/core/lib/surface/server.h" typedef struct { - grpc_server *server; - grpc_tcp_server *tcp_server; - grpc_channel_args *args; + grpc_server* server; + grpc_tcp_server* tcp_server; + grpc_channel_args* args; gpr_mu mu; bool shutdown; grpc_closure tcp_server_shutdown_complete; - grpc_closure *server_destroy_listener_done; - grpc_handshake_manager *pending_handshake_mgrs; + grpc_closure* server_destroy_listener_done; + grpc_handshake_manager* pending_handshake_mgrs; } server_state; typedef struct { - server_state *svr_state; - grpc_pollset *accepting_pollset; - grpc_tcp_server_acceptor *acceptor; - grpc_handshake_manager *handshake_mgr; + gpr_refcount refs; + server_state* svr_state; + grpc_pollset* accepting_pollset; + grpc_tcp_server_acceptor* acceptor; + grpc_handshake_manager* handshake_mgr; + // State for enforcing handshake timeout on receiving HTTP/2 settings. + grpc_chttp2_transport* transport; + grpc_millis deadline; + grpc_timer timer; + grpc_closure on_timeout; + grpc_closure on_receive_settings; } server_connection_state; -static void on_handshake_done(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_handshaker_args *args = (grpc_handshaker_args *)arg; - server_connection_state *connection_state = - (server_connection_state *)args->user_data; +static void server_connection_state_unref( + grpc_exec_ctx* exec_ctx, server_connection_state* connection_state) { + if (gpr_unref(&connection_state->refs)) { + if (connection_state->transport != nullptr) { + GRPC_CHTTP2_UNREF_TRANSPORT(exec_ctx, connection_state->transport, + "receive settings timeout"); + } + gpr_free(connection_state); + } +} + +static void on_timeout(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { + server_connection_state* connection_state = (server_connection_state*)arg; + // Note that we may be called with GRPC_ERROR_NONE when the timer fires + // or with an error indicating that the timer system is being shut down. + if (error != GRPC_ERROR_CANCELLED) { + grpc_transport_op* op = grpc_make_transport_op(nullptr); + op->disconnect_with_error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "Did not receive HTTP/2 settings before handshake timeout"); + grpc_transport_perform_op(exec_ctx, &connection_state->transport->base, op); + } + server_connection_state_unref(exec_ctx, connection_state); +} + +static void on_receive_settings(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + server_connection_state* connection_state = (server_connection_state*)arg; + if (error == GRPC_ERROR_NONE) { + grpc_timer_cancel(exec_ctx, &connection_state->timer); + } + server_connection_state_unref(exec_ctx, connection_state); +} + +static void on_handshake_done(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_handshaker_args* args = (grpc_handshaker_args*)arg; + server_connection_state* connection_state = + (server_connection_state*)args->user_data; gpr_mu_lock(&connection_state->svr_state->mu); if (error != GRPC_ERROR_NONE || connection_state->svr_state->shutdown) { - const char *error_str = grpc_error_string(error); + const char* error_str = grpc_error_string(error); gpr_log(GPR_DEBUG, "Handshaking failed: %s", error_str); - - if (error == GRPC_ERROR_NONE && args->endpoint != NULL) { + if (error == GRPC_ERROR_NONE && args->endpoint != nullptr) { // We were shut down after handshaking completed successfully, so // destroy the endpoint here. // TODO(ctiller): It is currently necessary to shutdown endpoints @@ -86,15 +127,31 @@ static void on_handshake_done(grpc_exec_ctx *exec_ctx, void *arg, // If the handshaking succeeded but there is no endpoint, then the // handshaker may have handed off the connection to some external // code, so we can just clean up here without creating a transport. - if (args->endpoint != NULL) { - grpc_transport *transport = - grpc_create_chttp2_transport(exec_ctx, args->args, args->endpoint, 0); + if (args->endpoint != nullptr) { + grpc_transport* transport = grpc_create_chttp2_transport( + exec_ctx, args->args, args->endpoint, false); grpc_server_setup_transport( exec_ctx, connection_state->svr_state->server, transport, connection_state->accepting_pollset, args->args); - grpc_chttp2_transport_start_reading(exec_ctx, transport, - args->read_buffer); + // Use notify_on_receive_settings callback to enforce the + // handshake deadline. + connection_state->transport = (grpc_chttp2_transport*)transport; + gpr_ref(&connection_state->refs); + GRPC_CLOSURE_INIT(&connection_state->on_receive_settings, + on_receive_settings, connection_state, + grpc_schedule_on_exec_ctx); + grpc_chttp2_transport_start_reading( + exec_ctx, transport, args->read_buffer, + &connection_state->on_receive_settings); grpc_channel_args_destroy(exec_ctx, args->args); + gpr_ref(&connection_state->refs); + GRPC_CHTTP2_REF_TRANSPORT((grpc_chttp2_transport*)transport, + "receive settings timeout"); + GRPC_CLOSURE_INIT(&connection_state->on_timeout, on_timeout, + connection_state, grpc_schedule_on_exec_ctx); + grpc_timer_init(exec_ctx, &connection_state->timer, + connection_state->deadline, + &connection_state->on_timeout); } } grpc_handshake_manager_pending_list_remove( @@ -102,15 +159,15 @@ static void on_handshake_done(grpc_exec_ctx *exec_ctx, void *arg, connection_state->handshake_mgr); gpr_mu_unlock(&connection_state->svr_state->mu); grpc_handshake_manager_destroy(exec_ctx, connection_state->handshake_mgr); - grpc_tcp_server_unref(exec_ctx, connection_state->svr_state->tcp_server); gpr_free(connection_state->acceptor); - gpr_free(connection_state); + grpc_tcp_server_unref(exec_ctx, connection_state->svr_state->tcp_server); + server_connection_state_unref(exec_ctx, connection_state); } -static void on_accept(grpc_exec_ctx *exec_ctx, void *arg, grpc_endpoint *tcp, - grpc_pollset *accepting_pollset, - grpc_tcp_server_acceptor *acceptor) { - server_state *state = (server_state *)arg; +static void on_accept(grpc_exec_ctx* exec_ctx, void* arg, grpc_endpoint* tcp, + grpc_pollset* accepting_pollset, + grpc_tcp_server_acceptor* acceptor) { + server_state* state = (server_state*)arg; gpr_mu_lock(&state->mu); if (state->shutdown) { gpr_mu_unlock(&state->mu); @@ -119,33 +176,38 @@ static void on_accept(grpc_exec_ctx *exec_ctx, void *arg, grpc_endpoint *tcp, gpr_free(acceptor); return; } - grpc_handshake_manager *handshake_mgr = grpc_handshake_manager_create(); + grpc_handshake_manager* handshake_mgr = grpc_handshake_manager_create(); grpc_handshake_manager_pending_list_add(&state->pending_handshake_mgrs, handshake_mgr); gpr_mu_unlock(&state->mu); grpc_tcp_server_ref(state->tcp_server); - server_connection_state *connection_state = - (server_connection_state *)gpr_malloc(sizeof(*connection_state)); + server_connection_state* connection_state = + (server_connection_state*)gpr_zalloc(sizeof(*connection_state)); + gpr_ref_init(&connection_state->refs, 1); connection_state->svr_state = state; connection_state->accepting_pollset = accepting_pollset; connection_state->acceptor = acceptor; connection_state->handshake_mgr = handshake_mgr; grpc_handshakers_add(exec_ctx, HANDSHAKER_SERVER, state->args, connection_state->handshake_mgr); - // TODO(roth): We should really get this timeout value from channel - // args instead of hard-coding it. - const grpc_millis deadline = - grpc_exec_ctx_now(exec_ctx) + 120 * GPR_MS_PER_SEC; + const grpc_arg* timeout_arg = + grpc_channel_args_find(state->args, GRPC_ARG_SERVER_HANDSHAKE_TIMEOUT_MS); + connection_state->deadline = + grpc_exec_ctx_now(exec_ctx) + + grpc_channel_arg_get_integer(timeout_arg, + {120 * GPR_MS_PER_SEC, 1, INT_MAX}); grpc_handshake_manager_do_handshake(exec_ctx, connection_state->handshake_mgr, - tcp, state->args, deadline, acceptor, - on_handshake_done, connection_state); + nullptr /* interested_parties */, tcp, + state->args, connection_state->deadline, + acceptor, on_handshake_done, + connection_state); } /* Server callback: start listening on our ports */ -static void server_start_listener(grpc_exec_ctx *exec_ctx, grpc_server *server, - void *arg, grpc_pollset **pollsets, +static void server_start_listener(grpc_exec_ctx* exec_ctx, grpc_server* server, + void* arg, grpc_pollset** pollsets, size_t pollset_count) { - server_state *state = (server_state *)arg; + server_state* state = (server_state*)arg; gpr_mu_lock(&state->mu); state->shutdown = false; gpr_mu_unlock(&state->mu); @@ -153,12 +215,12 @@ static void server_start_listener(grpc_exec_ctx *exec_ctx, grpc_server *server, on_accept, state); } -static void tcp_server_shutdown_complete(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - server_state *state = (server_state *)arg; +static void tcp_server_shutdown_complete(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + server_state* state = (server_state*)arg; /* ensure all threads have unlocked */ gpr_mu_lock(&state->mu); - grpc_closure *destroy_done = state->server_destroy_listener_done; + grpc_closure* destroy_done = state->server_destroy_listener_done; GPR_ASSERT(state->shutdown); grpc_handshake_manager_pending_list_shutdown_all( exec_ctx, state->pending_handshake_mgrs, GRPC_ERROR_REF(error)); @@ -166,7 +228,7 @@ static void tcp_server_shutdown_complete(grpc_exec_ctx *exec_ctx, void *arg, // Flush queued work before destroying handshaker factory, since that // may do a synchronous unref. grpc_exec_ctx_flush(exec_ctx); - if (destroy_done != NULL) { + if (destroy_done != nullptr) { destroy_done->cb(exec_ctx, destroy_done->cb_arg, GRPC_ERROR_REF(error)); grpc_exec_ctx_flush(exec_ctx); } @@ -177,31 +239,31 @@ static void tcp_server_shutdown_complete(grpc_exec_ctx *exec_ctx, void *arg, /* Server callback: destroy the tcp listener (so we don't generate further callbacks) */ -static void server_destroy_listener(grpc_exec_ctx *exec_ctx, - grpc_server *server, void *arg, - grpc_closure *destroy_done) { - server_state *state = (server_state *)arg; +static void server_destroy_listener(grpc_exec_ctx* exec_ctx, + grpc_server* server, void* arg, + grpc_closure* destroy_done) { + server_state* state = (server_state*)arg; gpr_mu_lock(&state->mu); state->shutdown = true; state->server_destroy_listener_done = destroy_done; - grpc_tcp_server *tcp_server = state->tcp_server; + grpc_tcp_server* tcp_server = state->tcp_server; gpr_mu_unlock(&state->mu); grpc_tcp_server_shutdown_listeners(exec_ctx, tcp_server); grpc_tcp_server_unref(exec_ctx, tcp_server); } -grpc_error *grpc_chttp2_server_add_port(grpc_exec_ctx *exec_ctx, - grpc_server *server, const char *addr, - grpc_channel_args *args, - int *port_num) { - grpc_resolved_addresses *resolved = NULL; - grpc_tcp_server *tcp_server = NULL; +grpc_error* grpc_chttp2_server_add_port(grpc_exec_ctx* exec_ctx, + grpc_server* server, const char* addr, + grpc_channel_args* args, + int* port_num) { + grpc_resolved_addresses* resolved = nullptr; + grpc_tcp_server* tcp_server = nullptr; size_t i; size_t count = 0; int port_temp; - grpc_error *err = GRPC_ERROR_NONE; - server_state *state = NULL; - grpc_error **errors = NULL; + grpc_error* err = GRPC_ERROR_NONE; + server_state* state = nullptr; + grpc_error** errors = nullptr; size_t naddrs = 0; *port_num = -1; @@ -211,7 +273,7 @@ grpc_error *grpc_chttp2_server_add_port(grpc_exec_ctx *exec_ctx, if (err != GRPC_ERROR_NONE) { goto error; } - state = (server_state *)gpr_zalloc(sizeof(*state)); + state = (server_state*)gpr_zalloc(sizeof(*state)); GRPC_CLOSURE_INIT(&state->tcp_server_shutdown_complete, tcp_server_shutdown_complete, state, grpc_schedule_on_exec_ctx); @@ -228,7 +290,7 @@ grpc_error *grpc_chttp2_server_add_port(grpc_exec_ctx *exec_ctx, gpr_mu_init(&state->mu); naddrs = resolved->naddrs; - errors = (grpc_error **)gpr_malloc(sizeof(*errors) * naddrs); + errors = (grpc_error**)gpr_malloc(sizeof(*errors) * naddrs); for (i = 0; i < naddrs; i++) { errors[i] = grpc_tcp_server_add_port(tcp_server, &resolved->addrs[i], &port_temp); @@ -242,21 +304,22 @@ grpc_error *grpc_chttp2_server_add_port(grpc_exec_ctx *exec_ctx, } } if (count == 0) { - char *msg; + char* msg; gpr_asprintf(&msg, "No address added out of total %" PRIuPTR " resolved", naddrs); err = GRPC_ERROR_CREATE_REFERENCING_FROM_COPIED_STRING(msg, errors, naddrs); gpr_free(msg); goto error; } else if (count != naddrs) { - char *msg; - gpr_asprintf(&msg, "Only %" PRIuPTR - " addresses added out of total %" PRIuPTR " resolved", + char* msg; + gpr_asprintf(&msg, + "Only %" PRIuPTR " addresses added out of total %" PRIuPTR + " resolved", count, naddrs); err = GRPC_ERROR_CREATE_REFERENCING_FROM_COPIED_STRING(msg, errors, naddrs); gpr_free(msg); - const char *warning_message = grpc_error_string(err); + const char* warning_message = grpc_error_string(err); gpr_log(GPR_INFO, "WARNING: %s", warning_message); /* we managed to bind some addresses: continue */ @@ -283,7 +346,7 @@ error: *port_num = 0; done: - if (errors != NULL) { + if (errors != nullptr) { for (i = 0; i < naddrs; i++) { GRPC_ERROR_UNREF(errors[i]); } diff --git a/src/core/ext/transport/chttp2/server/chttp2_server.h b/src/core/ext/transport/chttp2/server/chttp2_server.h index 2ac155160fc..68304fd4f7e 100644 --- a/src/core/ext/transport/chttp2/server/chttp2_server.h +++ b/src/core/ext/transport/chttp2/server/chttp2_server.h @@ -23,18 +23,10 @@ #include "src/core/lib/iomgr/exec_ctx.h" -#ifdef __cplusplus -extern "C" { -#endif - /// Adds a port to \a server. Sets \a port_num to the port number. /// Takes ownership of \a args. -grpc_error *grpc_chttp2_server_add_port(grpc_exec_ctx *exec_ctx, - grpc_server *server, const char *addr, - grpc_channel_args *args, int *port_num); - -#ifdef __cplusplus -} -#endif +grpc_error* grpc_chttp2_server_add_port(grpc_exec_ctx* exec_ctx, + grpc_server* server, const char* addr, + grpc_channel_args* args, int* port_num); #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_SERVER_CHTTP2_SERVER_H */ diff --git a/src/core/ext/transport/chttp2/server/insecure/server_chttp2.cc b/src/core/ext/transport/chttp2/server/insecure/server_chttp2.cc index d42b2d123e6..89848965384 100644 --- a/src/core/ext/transport/chttp2/server/insecure/server_chttp2.cc +++ b/src/core/ext/transport/chttp2/server/insecure/server_chttp2.cc @@ -25,16 +25,16 @@ #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/server.h" -int grpc_server_add_insecure_http2_port(grpc_server *server, const char *addr) { +int grpc_server_add_insecure_http2_port(grpc_server* server, const char* addr) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; int port_num = 0; GRPC_API_TRACE("grpc_server_add_insecure_http2_port(server=%p, addr=%s)", 2, (server, addr)); - grpc_error *err = grpc_chttp2_server_add_port( + grpc_error* err = grpc_chttp2_server_add_port( &exec_ctx, server, addr, grpc_channel_args_copy(grpc_server_get_channel_args(server)), &port_num); if (err != GRPC_ERROR_NONE) { - const char *msg = grpc_error_string(err); + const char* msg = grpc_error_string(err); gpr_log(GPR_ERROR, "%s", msg); GRPC_ERROR_UNREF(err); diff --git a/src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc b/src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc index e647067f733..3fe05ce4ef9 100644 --- a/src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc +++ b/src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc @@ -34,25 +34,25 @@ #include "src/core/lib/surface/completion_queue.h" #include "src/core/lib/surface/server.h" -void grpc_server_add_insecure_channel_from_fd(grpc_server *server, - void *reserved, int fd) { - GPR_ASSERT(reserved == NULL); +void grpc_server_add_insecure_channel_from_fd(grpc_server* server, + void* reserved, int fd) { + GPR_ASSERT(reserved == nullptr); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - char *name; + char* name; gpr_asprintf(&name, "fd:%d", fd); - grpc_endpoint *server_endpoint = + grpc_endpoint* server_endpoint = grpc_tcp_create(&exec_ctx, grpc_fd_create(fd, name), grpc_server_get_channel_args(server), name); gpr_free(name); - const grpc_channel_args *server_args = grpc_server_get_channel_args(server); - grpc_transport *transport = grpc_create_chttp2_transport( - &exec_ctx, server_args, server_endpoint, 0 /* is_client */); + const grpc_channel_args* server_args = grpc_server_get_channel_args(server); + grpc_transport* transport = grpc_create_chttp2_transport( + &exec_ctx, server_args, server_endpoint, false /* is_client */); - grpc_pollset **pollsets; + grpc_pollset** pollsets; size_t num_pollsets = 0; grpc_server_get_pollsets(server, &pollsets, &num_pollsets); @@ -60,15 +60,16 @@ void grpc_server_add_insecure_channel_from_fd(grpc_server *server, grpc_endpoint_add_to_pollset(&exec_ctx, server_endpoint, pollsets[i]); } - grpc_server_setup_transport(&exec_ctx, server, transport, NULL, server_args); - grpc_chttp2_transport_start_reading(&exec_ctx, transport, NULL); + grpc_server_setup_transport(&exec_ctx, server, transport, nullptr, + server_args); + grpc_chttp2_transport_start_reading(&exec_ctx, transport, nullptr, nullptr); grpc_exec_ctx_finish(&exec_ctx); } #else // !GPR_SUPPORT_CHANNELS_FROM_FD -void grpc_server_add_insecure_channel_from_fd(grpc_server *server, - void *reserved, int fd) { +void grpc_server_add_insecure_channel_from_fd(grpc_server* server, + void* reserved, int fd) { GPR_ASSERT(0); } diff --git a/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc b/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc index e74a138d232..ac3ea40f478 100644 --- a/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc +++ b/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc @@ -34,20 +34,20 @@ #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/server.h" -int grpc_server_add_secure_http2_port(grpc_server *server, const char *addr, - grpc_server_credentials *creds) { +int grpc_server_add_secure_http2_port(grpc_server* server, const char* addr, + grpc_server_credentials* creds) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - grpc_error *err = GRPC_ERROR_NONE; - grpc_server_security_connector *sc = NULL; + grpc_error* err = GRPC_ERROR_NONE; + grpc_server_security_connector* sc = nullptr; int port_num = 0; grpc_security_status status; - grpc_channel_args *args = NULL; + grpc_channel_args* args = nullptr; GRPC_API_TRACE( "grpc_server_add_secure_http2_port(" "server=%p, addr=%s, creds=%p)", 3, (server, addr, creds)); // Create security context. - if (creds == NULL) { + if (creds == nullptr) { err = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "No credentials specified for secure server port (creds==NULL)"); goto done; @@ -55,7 +55,7 @@ int grpc_server_add_secure_http2_port(grpc_server *server, const char *addr, status = grpc_server_credentials_create_security_connector(&exec_ctx, creds, &sc); if (status != GRPC_SECURITY_OK) { - char *msg; + char* msg; gpr_asprintf(&msg, "Unable to create secure server with credentials of type %s.", creds->type); @@ -74,12 +74,12 @@ int grpc_server_add_secure_http2_port(grpc_server *server, const char *addr, // Add server port. err = grpc_chttp2_server_add_port(&exec_ctx, server, addr, args, &port_num); done: - if (sc != NULL) { + if (sc != nullptr) { GRPC_SECURITY_CONNECTOR_UNREF(&exec_ctx, &sc->base, "server"); } grpc_exec_ctx_finish(&exec_ctx); if (err != GRPC_ERROR_NONE) { - const char *msg = grpc_error_string(err); + const char* msg = grpc_error_string(err); gpr_log(GPR_ERROR, "%s", msg); GRPC_ERROR_UNREF(err); diff --git a/src/core/ext/transport/chttp2/transport/bin_decoder.cc b/src/core/ext/transport/chttp2/transport/bin_decoder.cc index 5a99cbeffcf..3ccae7afc35 100644 --- a/src/core/ext/transport/chttp2/transport/bin_decoder.cc +++ b/src/core/ext/transport/chttp2/transport/bin_decoder.cc @@ -49,7 +49,7 @@ static uint8_t decode_table[] = { static const uint8_t tail_xtra[4] = {0, 0, 1, 2}; -static bool input_is_valid(uint8_t *input_ptr, size_t length) { +static bool input_is_valid(uint8_t* input_ptr, size_t length) { size_t i; for (i = 0; i < length; ++i) { @@ -75,7 +75,7 @@ static bool input_is_valid(uint8_t *input_ptr, size_t length) { #define COMPOSE_OUTPUT_BYTE_2(input_ptr) \ (uint8_t)((decode_table[input_ptr[2]] << 6) | decode_table[input_ptr[3]]) -bool grpc_base64_decode_partial(struct grpc_base64_decode_context *ctx) { +bool grpc_base64_decode_partial(struct grpc_base64_decode_context* ctx) { size_t input_tail; if (ctx->input_cur > ctx->input_end || ctx->output_cur > ctx->output_end) { @@ -130,7 +130,7 @@ bool grpc_base64_decode_partial(struct grpc_base64_decode_context *ctx) { return true; } -grpc_slice grpc_chttp2_base64_decode(grpc_exec_ctx *exec_ctx, +grpc_slice grpc_chttp2_base64_decode(grpc_exec_ctx* exec_ctx, grpc_slice input) { size_t input_length = GRPC_SLICE_LENGTH(input); size_t output_length = input_length / 4 * 3; @@ -147,7 +147,7 @@ grpc_slice grpc_chttp2_base64_decode(grpc_exec_ctx *exec_ctx, } if (input_length > 0) { - uint8_t *input_end = GRPC_SLICE_END_PTR(input); + uint8_t* input_end = GRPC_SLICE_END_PTR(input); if (*(--input_end) == '=') { output_length--; if (*(--input_end) == '=') { @@ -164,7 +164,7 @@ grpc_slice grpc_chttp2_base64_decode(grpc_exec_ctx *exec_ctx, ctx.contains_tail = false; if (!grpc_base64_decode_partial(&ctx)) { - char *s = grpc_slice_to_c_string(input); + char* s = grpc_slice_to_c_string(input); gpr_log(GPR_ERROR, "Base64 decoding failed, input string:\n%s\n", s); gpr_free(s); grpc_slice_unref_internal(exec_ctx, output); @@ -175,7 +175,7 @@ grpc_slice grpc_chttp2_base64_decode(grpc_exec_ctx *exec_ctx, return output; } -grpc_slice grpc_chttp2_base64_decode_with_length(grpc_exec_ctx *exec_ctx, +grpc_slice grpc_chttp2_base64_decode_with_length(grpc_exec_ctx* exec_ctx, grpc_slice input, size_t output_length) { size_t input_length = GRPC_SLICE_LENGTH(input); @@ -210,7 +210,7 @@ grpc_slice grpc_chttp2_base64_decode_with_length(grpc_exec_ctx *exec_ctx, ctx.contains_tail = true; if (!grpc_base64_decode_partial(&ctx)) { - char *s = grpc_slice_to_c_string(input); + char* s = grpc_slice_to_c_string(input); gpr_log(GPR_ERROR, "Base64 decoding failed, input string:\n%s\n", s); gpr_free(s); grpc_slice_unref_internal(exec_ctx, output); diff --git a/src/core/ext/transport/chttp2/transport/bin_decoder.h b/src/core/ext/transport/chttp2/transport/bin_decoder.h index 1c0b2b7e97a..a78c305766e 100644 --- a/src/core/ext/transport/chttp2/transport/bin_decoder.h +++ b/src/core/ext/transport/chttp2/transport/bin_decoder.h @@ -22,16 +22,12 @@ #include #include -#ifdef __cplusplus -extern "C" { -#endif - struct grpc_base64_decode_context { /* input/output: */ - uint8_t *input_cur; - uint8_t *input_end; - uint8_t *output_cur; - uint8_t *output_end; + uint8_t* input_cur; + uint8_t* input_end; + uint8_t* output_cur; + uint8_t* output_end; /* Indicate if the decoder should handle the tail of input data*/ bool contains_tail; }; @@ -40,21 +36,17 @@ struct grpc_base64_decode_context { or output_end is reached. When input_end is reached, (input_end - input_cur) is less than 4. When output_end is reached, (output_end - output_cur) is less than 3. Returns false if decoding is failed. */ -bool grpc_base64_decode_partial(struct grpc_base64_decode_context *ctx); +bool grpc_base64_decode_partial(struct grpc_base64_decode_context* ctx); /* base64 decode a slice with pad chars. Returns a new slice, does not take ownership of the input. Returns an empty slice if decoding is failed. */ -grpc_slice grpc_chttp2_base64_decode(grpc_exec_ctx *exec_ctx, grpc_slice input); +grpc_slice grpc_chttp2_base64_decode(grpc_exec_ctx* exec_ctx, grpc_slice input); /* base64 decode a slice without pad chars, data length is needed. Returns a new slice, does not take ownership of the input. Returns an empty slice if decoding is failed. */ -grpc_slice grpc_chttp2_base64_decode_with_length(grpc_exec_ctx *exec_ctx, +grpc_slice grpc_chttp2_base64_decode_with_length(grpc_exec_ctx* exec_ctx, grpc_slice input, size_t output_length); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_BIN_DECODER_H */ diff --git a/src/core/ext/transport/chttp2/transport/bin_encoder.cc b/src/core/ext/transport/chttp2/transport/bin_encoder.cc index 42d481b3c0f..09f984d7b2d 100644 --- a/src/core/ext/transport/chttp2/transport/bin_encoder.cc +++ b/src/core/ext/transport/chttp2/transport/bin_encoder.cc @@ -52,8 +52,8 @@ grpc_slice grpc_chttp2_base64_encode(grpc_slice input) { size_t tail_case = input_length % 3; size_t output_length = input_triplets * 4 + tail_xtra[tail_case]; grpc_slice output = GRPC_SLICE_MALLOC(output_length); - uint8_t *in = GRPC_SLICE_START_PTR(input); - char *out = (char *)GRPC_SLICE_START_PTR(output); + uint8_t* in = GRPC_SLICE_START_PTR(input); + char* out = (char*)GRPC_SLICE_START_PTR(output); size_t i; /* encode full triplets */ @@ -85,15 +85,15 @@ grpc_slice grpc_chttp2_base64_encode(grpc_slice input) { break; } - GPR_ASSERT(out == (char *)GRPC_SLICE_END_PTR(output)); + GPR_ASSERT(out == (char*)GRPC_SLICE_END_PTR(output)); GPR_ASSERT(in == GRPC_SLICE_END_PTR(input)); return output; } grpc_slice grpc_chttp2_huffman_compress(grpc_slice input) { size_t nbits; - uint8_t *in; - uint8_t *out; + uint8_t* in; + uint8_t* out; grpc_slice output; uint32_t temp = 0; uint32_t temp_length = 0; @@ -136,17 +136,17 @@ grpc_slice grpc_chttp2_huffman_compress(grpc_slice input) { typedef struct { uint32_t temp; uint32_t temp_length; - uint8_t *out; + uint8_t* out; } huff_out; -static void enc_flush_some(huff_out *out) { +static void enc_flush_some(huff_out* out) { while (out->temp_length > 8) { out->temp_length -= 8; *out->out++ = (uint8_t)(out->temp >> out->temp_length); } } -static void enc_add2(huff_out *out, uint8_t a, uint8_t b) { +static void enc_add2(huff_out* out, uint8_t a, uint8_t b) { b64_huff_sym sa = huff_alphabet[a]; b64_huff_sym sb = huff_alphabet[b]; out->temp = (out->temp << (sa.length + sb.length)) | @@ -155,7 +155,7 @@ static void enc_add2(huff_out *out, uint8_t a, uint8_t b) { enc_flush_some(out); } -static void enc_add1(huff_out *out, uint8_t a) { +static void enc_add1(huff_out* out, uint8_t a) { b64_huff_sym sa = huff_alphabet[a]; out->temp = (out->temp << sa.length) | sa.bits; out->temp_length += sa.length; @@ -170,8 +170,8 @@ grpc_slice grpc_chttp2_base64_encode_and_huffman_compress(grpc_slice input) { size_t max_output_bits = 11 * output_syms; size_t max_output_length = max_output_bits / 8 + (max_output_bits % 8 != 0); grpc_slice output = GRPC_SLICE_MALLOC(max_output_length); - uint8_t *in = GRPC_SLICE_START_PTR(input); - uint8_t *start_out = GRPC_SLICE_START_PTR(output); + uint8_t* in = GRPC_SLICE_START_PTR(input); + uint8_t* start_out = GRPC_SLICE_START_PTR(output); huff_out out; size_t i; diff --git a/src/core/ext/transport/chttp2/transport/bin_encoder.h b/src/core/ext/transport/chttp2/transport/bin_encoder.h index 0be3633354e..a8f36a345ad 100644 --- a/src/core/ext/transport/chttp2/transport/bin_encoder.h +++ b/src/core/ext/transport/chttp2/transport/bin_encoder.h @@ -21,10 +21,6 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /* base64 encode a slice. Returns a new slice, does not take ownership of the input */ grpc_slice grpc_chttp2_base64_encode(grpc_slice input); @@ -40,8 +36,4 @@ grpc_slice grpc_chttp2_huffman_compress(grpc_slice input); return y; */ grpc_slice grpc_chttp2_base64_encode_and_huffman_compress(grpc_slice input); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_BIN_ENCODER_H */ diff --git a/src/core/ext/transport/chttp2/transport/chttp2_plugin.cc b/src/core/ext/transport/chttp2/transport/chttp2_plugin.cc index ac9ae5c395f..97c1878f340 100644 --- a/src/core/ext/transport/chttp2/transport/chttp2_plugin.cc +++ b/src/core/ext/transport/chttp2/transport/chttp2_plugin.cc @@ -20,13 +20,6 @@ #include "src/core/lib/debug/trace.h" #include "src/core/lib/transport/metadata.h" -extern "C" void grpc_chttp2_plugin_init(void) { - grpc_register_tracer(&grpc_http_trace); - grpc_register_tracer(&grpc_flowctl_trace); - grpc_register_tracer(&grpc_trace_http2_stream_state); -#ifndef NDEBUG - grpc_register_tracer(&grpc_trace_chttp2_refcount); -#endif -} +void grpc_chttp2_plugin_init(void) {} -extern "C" void grpc_chttp2_plugin_shutdown(void) {} +void grpc_chttp2_plugin_shutdown(void) {} diff --git a/src/core/ext/transport/chttp2/transport/chttp2_transport.cc b/src/core/ext/transport/chttp2/transport/chttp2_transport.cc index 02fc53122da..63ac65ac788 100644 --- a/src/core/ext/transport/chttp2/transport/chttp2_transport.cc +++ b/src/core/ext/transport/chttp2/transport/chttp2_transport.cc @@ -90,103 +90,99 @@ static int g_default_max_pings_without_data = DEFAULT_MAX_PINGS_BETWEEN_DATA; static int g_default_max_ping_strikes = DEFAULT_MAX_PING_STRIKES; #define MAX_CLIENT_STREAM_ID 0x7fffffffu -grpc_tracer_flag grpc_http_trace = GRPC_TRACER_INITIALIZER(false, "http"); -grpc_tracer_flag grpc_flowctl_trace = GRPC_TRACER_INITIALIZER(false, "flowctl"); - -#ifndef NDEBUG -grpc_tracer_flag grpc_trace_chttp2_refcount = - GRPC_TRACER_INITIALIZER(false, "chttp2_refcount"); -#endif +grpc_core::TraceFlag grpc_http_trace(false, "http"); +grpc_core::DebugOnlyTraceFlag grpc_trace_chttp2_refcount(false, + "chttp2_refcount"); /* forward declarations of various callbacks that we'll build closures around */ -static void write_action_begin_locked(grpc_exec_ctx *exec_ctx, void *t, - grpc_error *error); -static void write_action(grpc_exec_ctx *exec_ctx, void *t, grpc_error *error); -static void write_action_end_locked(grpc_exec_ctx *exec_ctx, void *t, - grpc_error *error); +static void write_action_begin_locked(grpc_exec_ctx* exec_ctx, void* t, + grpc_error* error); +static void write_action(grpc_exec_ctx* exec_ctx, void* t, grpc_error* error); +static void write_action_end_locked(grpc_exec_ctx* exec_ctx, void* t, + grpc_error* error); -static void read_action_locked(grpc_exec_ctx *exec_ctx, void *t, - grpc_error *error); +static void read_action_locked(grpc_exec_ctx* exec_ctx, void* t, + grpc_error* error); -static void complete_fetch_locked(grpc_exec_ctx *exec_ctx, void *gs, - grpc_error *error); +static void complete_fetch_locked(grpc_exec_ctx* exec_ctx, void* gs, + grpc_error* error); /** Set a transport level setting, and push it to our peer */ -static void queue_setting_update(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, +static void queue_setting_update(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, grpc_chttp2_setting_id id, uint32_t value); -static void close_from_api(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_chttp2_stream *s, grpc_error *error); +static void close_from_api(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_error* error); /** Start new streams that have been created if we can */ -static void maybe_start_some_streams(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t); +static void maybe_start_some_streams(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t); -static void connectivity_state_set(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, +static void connectivity_state_set(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, grpc_connectivity_state state, - grpc_error *error, const char *reason); + grpc_error* error, const char* reason); -static void incoming_byte_stream_destroy_locked(grpc_exec_ctx *exec_ctx, - void *byte_stream, - grpc_error *error_ignored); +static void incoming_byte_stream_destroy_locked(grpc_exec_ctx* exec_ctx, + void* byte_stream, + grpc_error* error_ignored); static void incoming_byte_stream_publish_error( - grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_byte_stream *bs, - grpc_error *error); -static void incoming_byte_stream_unref(grpc_exec_ctx *exec_ctx, - grpc_chttp2_incoming_byte_stream *bs); - -static void benign_reclaimer_locked(grpc_exec_ctx *exec_ctx, void *t, - grpc_error *error); -static void destructive_reclaimer_locked(grpc_exec_ctx *exec_ctx, void *t, - grpc_error *error); - -static void post_benign_reclaimer(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t); -static void post_destructive_reclaimer(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t); - -static void close_transport_locked(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, grpc_error *error); -static void end_all_the_calls(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_error *error); - -static void schedule_bdp_ping_locked(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t); -static void start_bdp_ping_locked(grpc_exec_ctx *exec_ctx, void *tp, - grpc_error *error); -static void finish_bdp_ping_locked(grpc_exec_ctx *exec_ctx, void *tp, - grpc_error *error); -static void next_bdp_ping_timer_expired_locked(grpc_exec_ctx *exec_ctx, - void *tp, grpc_error *error); - -static void cancel_pings(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_error *error); -static void send_ping_locked(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_closure *on_initiate, - grpc_closure *on_complete); -static void retry_initiate_ping_locked(grpc_exec_ctx *exec_ctx, void *tp, - grpc_error *error); + grpc_exec_ctx* exec_ctx, grpc_chttp2_incoming_byte_stream* bs, + grpc_error* error); +static void incoming_byte_stream_unref(grpc_exec_ctx* exec_ctx, + grpc_chttp2_incoming_byte_stream* bs); + +static void benign_reclaimer_locked(grpc_exec_ctx* exec_ctx, void* t, + grpc_error* error); +static void destructive_reclaimer_locked(grpc_exec_ctx* exec_ctx, void* t, + grpc_error* error); + +static void post_benign_reclaimer(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t); +static void post_destructive_reclaimer(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t); + +static void close_transport_locked(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, grpc_error* error); +static void end_all_the_calls(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_error* error); + +static void schedule_bdp_ping_locked(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t); +static void start_bdp_ping_locked(grpc_exec_ctx* exec_ctx, void* tp, + grpc_error* error); +static void finish_bdp_ping_locked(grpc_exec_ctx* exec_ctx, void* tp, + grpc_error* error); +static void next_bdp_ping_timer_expired_locked(grpc_exec_ctx* exec_ctx, + void* tp, grpc_error* error); + +static void cancel_pings(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_error* error); +static void send_ping_locked(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_closure* on_initiate, + grpc_closure* on_complete); +static void retry_initiate_ping_locked(grpc_exec_ctx* exec_ctx, void* tp, + grpc_error* error); /** keepalive-relevant functions */ -static void init_keepalive_ping_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error); -static void start_keepalive_ping_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error); -static void finish_keepalive_ping_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error); -static void keepalive_watchdog_fired_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error); - -static void reset_byte_stream(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error); +static void init_keepalive_ping_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error); +static void start_keepalive_ping_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error); +static void finish_keepalive_ping_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error); +static void keepalive_watchdog_fired_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error); + +static void reset_byte_stream(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error); /******************************************************************************* * CONSTRUCTION/DESTRUCTION/REFCOUNTING */ -static void destruct_transport(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { +static void destruct_transport(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { size_t i; grpc_endpoint_destroy(exec_ctx, t->ep); @@ -201,10 +197,12 @@ static void destruct_transport(grpc_exec_ctx *exec_ctx, grpc_chttp2_goaway_parser_destroy(&t->goaway_parser); for (i = 0; i < STREAM_LIST_COUNT; i++) { - GPR_ASSERT(t->lists[i].head == NULL); - GPR_ASSERT(t->lists[i].tail == NULL); + GPR_ASSERT(t->lists[i].head == nullptr); + GPR_ASSERT(t->lists[i].tail == nullptr); } + GRPC_ERROR_UNREF(t->goaway_error); + GPR_ASSERT(grpc_chttp2_stream_map_size(&t->stream_map) == 0); grpc_chttp2_stream_map_destroy(&t->stream_map); @@ -216,7 +214,7 @@ static void destruct_transport(grpc_exec_ctx *exec_ctx, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Transport destroyed")); while (t->write_cb_pool) { - grpc_chttp2_write_cb *next = t->write_cb_pool->next; + grpc_chttp2_write_cb* next = t->write_cb_pool->next; gpr_free(t->write_cb_pool); t->write_cb_pool = next; } @@ -230,10 +228,10 @@ static void destruct_transport(grpc_exec_ctx *exec_ctx, } #ifndef NDEBUG -void grpc_chttp2_unref_transport(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, const char *reason, - const char *file, int line) { - if (GRPC_TRACER_ON(grpc_trace_chttp2_refcount)) { +void grpc_chttp2_unref_transport(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, const char* reason, + const char* file, int line) { + if (grpc_trace_chttp2_refcount.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&t->refs.count); gpr_log(GPR_DEBUG, "chttp2:unref:%p %" PRIdPTR "->%" PRIdPTR " %s [%s:%d]", t, val, val - 1, reason, file, line); @@ -242,9 +240,9 @@ void grpc_chttp2_unref_transport(grpc_exec_ctx *exec_ctx, destruct_transport(exec_ctx, t); } -void grpc_chttp2_ref_transport(grpc_chttp2_transport *t, const char *reason, - const char *file, int line) { - if (GRPC_TRACER_ON(grpc_trace_chttp2_refcount)) { +void grpc_chttp2_ref_transport(grpc_chttp2_transport* t, const char* reason, + const char* file, int line) { + if (grpc_trace_chttp2_refcount.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&t->refs.count); gpr_log(GPR_DEBUG, "chttp2: ref:%p %" PRIdPTR "->%" PRIdPTR " %s [%s:%d]", t, val, val + 1, reason, file, line); @@ -252,20 +250,20 @@ void grpc_chttp2_ref_transport(grpc_chttp2_transport *t, const char *reason, gpr_ref(&t->refs); } #else -void grpc_chttp2_unref_transport(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { +void grpc_chttp2_unref_transport(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { if (!gpr_unref(&t->refs)) return; destruct_transport(exec_ctx, t); } -void grpc_chttp2_ref_transport(grpc_chttp2_transport *t) { gpr_ref(&t->refs); } +void grpc_chttp2_ref_transport(grpc_chttp2_transport* t) { gpr_ref(&t->refs); } #endif -static const grpc_transport_vtable *get_vtable(void); +static const grpc_transport_vtable* get_vtable(void); -static void init_transport(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - const grpc_channel_args *channel_args, - grpc_endpoint *ep, bool is_client) { +static void init_transport(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + const grpc_channel_args* channel_args, + grpc_endpoint* ep, bool is_client) { size_t i; int j; @@ -320,6 +318,7 @@ static void init_transport(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, keepalive_watchdog_fired_locked, t, grpc_combiner_scheduler(t->combiner)); + t->goaway_error = GRPC_ERROR_NONE; grpc_chttp2_goaway_parser_init(&t->goaway_parser); grpc_chttp2_hpack_parser_init(exec_ctx, &t->hpack_parser); @@ -494,7 +493,7 @@ static void init_transport(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, } } else { static const struct { - const char *channel_arg_name; + const char* channel_arg_name; grpc_chttp2_setting_id setting_id; grpc_integer_options integer_options; bool availability[2] /* server, client */; @@ -550,6 +549,7 @@ static void init_transport(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, /* No pings allowed before receiving a header or data frame. */ t->ping_state.pings_before_data_required = 0; t->ping_state.is_delayed_ping_timer_set = false; + t->ping_state.last_ping_sent_time = GRPC_MILLIS_INF_PAST; t->ping_recv_state.last_ping_recv_time = GRPC_MILLIS_INF_PAST; t->ping_recv_state.ping_strikes = 0; @@ -572,7 +572,7 @@ static void init_transport(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, schedule_bdp_ping_locked(exec_ctx, t); grpc_chttp2_act_on_flowctl_action( - exec_ctx, t->flow_control->PeriodicUpdate(exec_ctx), t, NULL); + exec_ctx, t->flow_control->PeriodicUpdate(exec_ctx), t, nullptr); } grpc_chttp2_initiate_write(exec_ctx, t, @@ -580,9 +580,9 @@ static void init_transport(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, post_benign_reclaimer(exec_ctx, t); } -static void destroy_transport_locked(grpc_exec_ctx *exec_ctx, void *tp, - grpc_error *error) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)tp; +static void destroy_transport_locked(grpc_exec_ctx* exec_ctx, void* tp, + grpc_error* error) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)tp; t->destroying = 1; close_transport_locked( exec_ctx, t, @@ -592,17 +592,17 @@ static void destroy_transport_locked(grpc_exec_ctx *exec_ctx, void *tp, GRPC_CHTTP2_UNREF_TRANSPORT(exec_ctx, t, "destroy"); } -static void destroy_transport(grpc_exec_ctx *exec_ctx, grpc_transport *gt) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)gt; +static void destroy_transport(grpc_exec_ctx* exec_ctx, grpc_transport* gt) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)gt; GRPC_CLOSURE_SCHED(exec_ctx, GRPC_CLOSURE_CREATE(destroy_transport_locked, t, grpc_combiner_scheduler(t->combiner)), GRPC_ERROR_NONE); } -static void close_transport_locked(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_error *error) { +static void close_transport_locked(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_error* error) { end_all_the_calls(exec_ctx, t, GRPC_ERROR_REF(error)); cancel_pings(exec_ctx, t, GRPC_ERROR_REF(error)); if (t->closed_with_error == GRPC_ERROR_NONE) { @@ -611,7 +611,7 @@ static void close_transport_locked(grpc_exec_ctx *exec_ctx, GRPC_STATUS_UNAVAILABLE); } if (t->write_state != GRPC_CHTTP2_WRITE_STATE_IDLE) { - if (t->close_transport_on_writes_finished == NULL) { + if (t->close_transport_on_writes_finished == nullptr) { t->close_transport_on_writes_finished = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Delayed close due to in-progress write"); @@ -645,39 +645,44 @@ static void close_transport_locked(grpc_exec_ctx *exec_ctx, } /* flush writable stream list to avoid dangling references */ - grpc_chttp2_stream *s; + grpc_chttp2_stream* s; while (grpc_chttp2_list_pop_writable_stream(t, &s)) { GRPC_CHTTP2_STREAM_UNREF(exec_ctx, s, "chttp2_writing:close"); } GPR_ASSERT(t->write_state == GRPC_CHTTP2_WRITE_STATE_IDLE); grpc_endpoint_shutdown(exec_ctx, t->ep, GRPC_ERROR_REF(error)); } + if (t->notify_on_receive_settings != nullptr) { + GRPC_CLOSURE_SCHED(exec_ctx, t->notify_on_receive_settings, + GRPC_ERROR_CANCELLED); + t->notify_on_receive_settings = nullptr; + } GRPC_ERROR_UNREF(error); } #ifndef NDEBUG -void grpc_chttp2_stream_ref(grpc_chttp2_stream *s, const char *reason) { +void grpc_chttp2_stream_ref(grpc_chttp2_stream* s, const char* reason) { grpc_stream_ref(s->refcount, reason); } -void grpc_chttp2_stream_unref(grpc_exec_ctx *exec_ctx, grpc_chttp2_stream *s, - const char *reason) { +void grpc_chttp2_stream_unref(grpc_exec_ctx* exec_ctx, grpc_chttp2_stream* s, + const char* reason) { grpc_stream_unref(exec_ctx, s->refcount, reason); } #else -void grpc_chttp2_stream_ref(grpc_chttp2_stream *s) { +void grpc_chttp2_stream_ref(grpc_chttp2_stream* s) { grpc_stream_ref(s->refcount); } -void grpc_chttp2_stream_unref(grpc_exec_ctx *exec_ctx, grpc_chttp2_stream *s) { +void grpc_chttp2_stream_unref(grpc_exec_ctx* exec_ctx, grpc_chttp2_stream* s) { grpc_stream_unref(exec_ctx, s->refcount); } #endif -static int init_stream(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_stream *gs, grpc_stream_refcount *refcount, - const void *server_data, gpr_arena *arena) { +static int init_stream(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_stream* gs, grpc_stream_refcount* refcount, + const void* server_data, gpr_arena* arena) { GPR_TIMER_BEGIN("init_stream", 0); - grpc_chttp2_transport *t = (grpc_chttp2_transport *)gt; - grpc_chttp2_stream *s = (grpc_chttp2_stream *)gs; + grpc_chttp2_transport* t = (grpc_chttp2_transport*)gt; + grpc_chttp2_stream* s = (grpc_chttp2_stream*)gs; s->t = t; s->refcount = refcount; @@ -717,16 +722,16 @@ static int init_stream(grpc_exec_ctx *exec_ctx, grpc_transport *gt, return 0; } -static void destroy_stream_locked(grpc_exec_ctx *exec_ctx, void *sp, - grpc_error *error) { - grpc_chttp2_stream *s = (grpc_chttp2_stream *)sp; - grpc_chttp2_transport *t = s->t; +static void destroy_stream_locked(grpc_exec_ctx* exec_ctx, void* sp, + grpc_error* error) { + grpc_chttp2_stream* s = (grpc_chttp2_stream*)sp; + grpc_chttp2_transport* t = s->t; GPR_TIMER_BEGIN("destroy_stream", 0); GPR_ASSERT((s->write_closed && s->read_closed) || s->id == 0); if (s->id != 0) { - GPR_ASSERT(grpc_chttp2_stream_map_find(&t->stream_map, s->id) == NULL); + GPR_ASSERT(grpc_chttp2_stream_map_find(&t->stream_map, s->id) == nullptr); } grpc_slice_buffer_destroy_internal(exec_ctx, @@ -746,12 +751,12 @@ static void destroy_stream_locked(grpc_exec_ctx *exec_ctx, void *sp, } } - GPR_ASSERT(s->send_initial_metadata_finished == NULL); - GPR_ASSERT(s->fetching_send_message == NULL); - GPR_ASSERT(s->send_trailing_metadata_finished == NULL); - GPR_ASSERT(s->recv_initial_metadata_ready == NULL); - GPR_ASSERT(s->recv_message_ready == NULL); - GPR_ASSERT(s->recv_trailing_metadata_finished == NULL); + GPR_ASSERT(s->send_initial_metadata_finished == nullptr); + GPR_ASSERT(s->fetching_send_message == nullptr); + GPR_ASSERT(s->send_trailing_metadata_finished == nullptr); + GPR_ASSERT(s->recv_initial_metadata_ready == nullptr); + GPR_ASSERT(s->recv_message_ready == nullptr); + GPR_ASSERT(s->recv_trailing_metadata_finished == nullptr); grpc_chttp2_data_parser_destroy(exec_ctx, &s->data_parser); grpc_chttp2_incoming_metadata_buffer_destroy(exec_ctx, &s->metadata_buffer[0]); @@ -771,48 +776,49 @@ static void destroy_stream_locked(grpc_exec_ctx *exec_ctx, void *sp, GRPC_CLOSURE_SCHED(exec_ctx, s->destroy_stream_arg, GRPC_ERROR_NONE); } -static void destroy_stream(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_stream *gs, - grpc_closure *then_schedule_closure) { +static void destroy_stream(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_stream* gs, + grpc_closure* then_schedule_closure) { GPR_TIMER_BEGIN("destroy_stream", 0); - grpc_chttp2_transport *t = (grpc_chttp2_transport *)gt; - grpc_chttp2_stream *s = (grpc_chttp2_stream *)gs; + grpc_chttp2_transport* t = (grpc_chttp2_transport*)gt; + grpc_chttp2_stream* s = (grpc_chttp2_stream*)gs; - if (s->stream_compression_ctx != NULL) { + if (s->stream_compression_ctx != nullptr) { grpc_stream_compression_context_destroy(s->stream_compression_ctx); - s->stream_compression_ctx = NULL; + s->stream_compression_ctx = nullptr; } - if (s->stream_decompression_ctx != NULL) { + if (s->stream_decompression_ctx != nullptr) { grpc_stream_compression_context_destroy(s->stream_decompression_ctx); - s->stream_decompression_ctx = NULL; + s->stream_decompression_ctx = nullptr; } s->destroy_stream_arg = then_schedule_closure; GRPC_CLOSURE_SCHED( - exec_ctx, GRPC_CLOSURE_INIT(&s->destroy_stream, destroy_stream_locked, s, - grpc_combiner_scheduler(t->combiner)), + exec_ctx, + GRPC_CLOSURE_INIT(&s->destroy_stream, destroy_stream_locked, s, + grpc_combiner_scheduler(t->combiner)), GRPC_ERROR_NONE); GPR_TIMER_END("destroy_stream", 0); } -grpc_chttp2_stream *grpc_chttp2_parsing_lookup_stream(grpc_chttp2_transport *t, +grpc_chttp2_stream* grpc_chttp2_parsing_lookup_stream(grpc_chttp2_transport* t, uint32_t id) { - return (grpc_chttp2_stream *)grpc_chttp2_stream_map_find(&t->stream_map, id); + return (grpc_chttp2_stream*)grpc_chttp2_stream_map_find(&t->stream_map, id); } -grpc_chttp2_stream *grpc_chttp2_parsing_accept_stream(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, +grpc_chttp2_stream* grpc_chttp2_parsing_accept_stream(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, uint32_t id) { - if (t->channel_callback.accept_stream == NULL) { - return NULL; + if (t->channel_callback.accept_stream == nullptr) { + return nullptr; } - grpc_chttp2_stream *accepting; - GPR_ASSERT(t->accepting_stream == NULL); + grpc_chttp2_stream* accepting; + GPR_ASSERT(t->accepting_stream == nullptr); t->accepting_stream = &accepting; t->channel_callback.accept_stream(exec_ctx, t->channel_callback.accept_stream_user_data, - &t->base, (void *)(uintptr_t)id); - t->accepting_stream = NULL; + &t->base, (void*)(uintptr_t)id); + t->accepting_stream = nullptr; return accepting; } @@ -820,7 +826,7 @@ grpc_chttp2_stream *grpc_chttp2_parsing_accept_stream(grpc_exec_ctx *exec_ctx, * OUTPUT PROCESSING */ -static const char *write_state_name(grpc_chttp2_write_state st) { +static const char* write_state_name(grpc_chttp2_write_state st) { switch (st) { case GRPC_CHTTP2_WRITE_STATE_IDLE: return "IDLE"; @@ -832,8 +838,8 @@ static const char *write_state_name(grpc_chttp2_write_state st) { GPR_UNREACHABLE_CODE(return "UNKNOWN"); } -static void set_write_state(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_chttp2_write_state st, const char *reason) { +static void set_write_state(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_chttp2_write_state st, const char* reason) { GRPC_CHTTP2_IF_TRACING(gpr_log(GPR_DEBUG, "W:%p %s state %s -> %s [%s]", t, t->is_client ? "CLIENT" : "SERVER", write_state_name(t->write_state), @@ -841,16 +847,16 @@ static void set_write_state(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, t->write_state = st; if (st == GRPC_CHTTP2_WRITE_STATE_IDLE) { GRPC_CLOSURE_LIST_SCHED(exec_ctx, &t->run_after_write); - if (t->close_transport_on_writes_finished != NULL) { - grpc_error *err = t->close_transport_on_writes_finished; - t->close_transport_on_writes_finished = NULL; + if (t->close_transport_on_writes_finished != nullptr) { + grpc_error* err = t->close_transport_on_writes_finished; + t->close_transport_on_writes_finished = nullptr; close_transport_locked(exec_ctx, t, err); } } } static void inc_initiate_write_reason( - grpc_exec_ctx *exec_ctx, grpc_chttp2_initiate_write_reason reason) { + grpc_exec_ctx* exec_ctx, grpc_chttp2_initiate_write_reason reason) { switch (reason) { case GRPC_CHTTP2_INITIATE_WRITE_INITIAL_WRITE: GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_INITIAL_WRITE(exec_ctx); @@ -921,8 +927,8 @@ static void inc_initiate_write_reason( } } -void grpc_chttp2_initiate_write(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, +void grpc_chttp2_initiate_write(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, grpc_chttp2_initiate_write_reason reason) { GPR_TIMER_BEGIN("grpc_chttp2_initiate_write", 0); @@ -950,16 +956,16 @@ void grpc_chttp2_initiate_write(grpc_exec_ctx *exec_ctx, GPR_TIMER_END("grpc_chttp2_initiate_write", 0); } -void grpc_chttp2_mark_stream_writable(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s) { +void grpc_chttp2_mark_stream_writable(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s) { if (t->closed_with_error == GRPC_ERROR_NONE && grpc_chttp2_list_add_writable_stream(t, s)) { GRPC_CHTTP2_STREAM_REF(s, "chttp2_writing:become"); } } -static grpc_closure_scheduler *write_scheduler(grpc_chttp2_transport *t, +static grpc_closure_scheduler* write_scheduler(grpc_chttp2_transport* t, bool early_results_scheduled, bool partial_write) { /* if it's not the first write in a batch, always offload to the executor: @@ -983,11 +989,11 @@ static grpc_closure_scheduler *write_scheduler(grpc_chttp2_transport *t, case GRPC_CHTTP2_OPTIMIZE_FOR_LATENCY: return grpc_schedule_on_exec_ctx; } - GPR_UNREACHABLE_CODE(return NULL); + GPR_UNREACHABLE_CODE(return nullptr); } #define WRITE_STATE_TUPLE_TO_INT(p, i) (2 * (int)(p) + (int)(i)) -static const char *begin_writing_desc(bool partial, bool inlined) { +static const char* begin_writing_desc(bool partial, bool inlined) { switch (WRITE_STATE_TUPLE_TO_INT(partial, inlined)) { case WRITE_STATE_TUPLE_TO_INT(false, false): return "begin write in background"; @@ -1001,10 +1007,10 @@ static const char *begin_writing_desc(bool partial, bool inlined) { GPR_UNREACHABLE_CODE(return "bad state tuple"); } -static void write_action_begin_locked(grpc_exec_ctx *exec_ctx, void *gt, - grpc_error *error_ignored) { +static void write_action_begin_locked(grpc_exec_ctx* exec_ctx, void* gt, + grpc_error* error_ignored) { GPR_TIMER_BEGIN("write_action_begin_locked", 0); - grpc_chttp2_transport *t = (grpc_chttp2_transport *)gt; + grpc_chttp2_transport* t = (grpc_chttp2_transport*)gt; GPR_ASSERT(t->write_state != GRPC_CHTTP2_WRITE_STATE_IDLE); grpc_chttp2_begin_write_result r; if (t->closed_with_error != GRPC_ERROR_NONE) { @@ -1019,18 +1025,20 @@ static void write_action_begin_locked(grpc_exec_ctx *exec_ctx, void *gt, if (!t->is_first_write_in_batch) { GRPC_STATS_INC_HTTP2_WRITES_CONTINUED(exec_ctx); } - grpc_closure_scheduler *scheduler = + grpc_closure_scheduler* scheduler = write_scheduler(t, r.early_results_scheduled, r.partial); if (scheduler != grpc_schedule_on_exec_ctx) { GRPC_STATS_INC_HTTP2_WRITES_OFFLOADED(exec_ctx); } set_write_state( - exec_ctx, t, r.partial ? GRPC_CHTTP2_WRITE_STATE_WRITING_WITH_MORE - : GRPC_CHTTP2_WRITE_STATE_WRITING, + exec_ctx, t, + r.partial ? GRPC_CHTTP2_WRITE_STATE_WRITING_WITH_MORE + : GRPC_CHTTP2_WRITE_STATE_WRITING, begin_writing_desc(r.partial, scheduler == grpc_schedule_on_exec_ctx)); - GRPC_CLOSURE_SCHED(exec_ctx, GRPC_CLOSURE_INIT(&t->write_action, - write_action, t, scheduler), - GRPC_ERROR_NONE); + GRPC_CLOSURE_SCHED( + exec_ctx, + GRPC_CLOSURE_INIT(&t->write_action, write_action, t, scheduler), + GRPC_ERROR_NONE); } else { GRPC_STATS_INC_HTTP2_SPURIOUS_WRITES_BEGUN(exec_ctx); set_write_state(exec_ctx, t, GRPC_CHTTP2_WRITE_STATE_IDLE, @@ -1040,8 +1048,8 @@ static void write_action_begin_locked(grpc_exec_ctx *exec_ctx, void *gt, GPR_TIMER_END("write_action_begin_locked", 0); } -static void write_action(grpc_exec_ctx *exec_ctx, void *gt, grpc_error *error) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)gt; +static void write_action(grpc_exec_ctx* exec_ctx, void* gt, grpc_error* error) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)gt; GPR_TIMER_BEGIN("write_action", 0); grpc_endpoint_write( exec_ctx, t->ep, &t->outbuf, @@ -1050,10 +1058,10 @@ static void write_action(grpc_exec_ctx *exec_ctx, void *gt, grpc_error *error) { GPR_TIMER_END("write_action", 0); } -static void write_action_end_locked(grpc_exec_ctx *exec_ctx, void *tp, - grpc_error *error) { +static void write_action_end_locked(grpc_exec_ctx* exec_ctx, void* tp, + grpc_error* error) { GPR_TIMER_BEGIN("terminate_writing_with_lock", 0); - grpc_chttp2_transport *t = (grpc_chttp2_transport *)tp; + grpc_chttp2_transport* t = (grpc_chttp2_transport*)tp; if (error != GRPC_ERROR_NONE) { close_transport_locked(exec_ctx, t, GRPC_ERROR_REF(error)); @@ -1098,10 +1106,10 @@ static void write_action_end_locked(grpc_exec_ctx *exec_ctx, void *tp, // Dirties an HTTP2 setting to be sent out next time a writing path occurs. // If the change needs to occur immediately, manually initiate a write. -static void queue_setting_update(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, +static void queue_setting_update(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, grpc_chttp2_setting_id id, uint32_t value) { - const grpc_chttp2_setting_parameters *sp = + const grpc_chttp2_setting_parameters* sp = &grpc_chttp2_settings_parameters[id]; uint32_t use_value = GPR_CLAMP(value, sp->min_value, sp->max_value); if (use_value != value) { @@ -1114,13 +1122,22 @@ static void queue_setting_update(grpc_exec_ctx *exec_ctx, } } -void grpc_chttp2_add_incoming_goaway(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, +void grpc_chttp2_add_incoming_goaway(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, uint32_t goaway_error, grpc_slice goaway_text) { // GRPC_CHTTP2_IF_TRACING( // gpr_log(GPR_DEBUG, "got goaway [%d]: %s", goaway_error, msg)); - t->seen_goaway = 1; + + // Discard the error from a previous goaway frame (if any) + if (t->goaway_error != GRPC_ERROR_NONE) { + GRPC_ERROR_UNREF(t->goaway_error); + } + t->goaway_error = grpc_error_set_str( + grpc_error_set_int( + GRPC_ERROR_CREATE_FROM_STATIC_STRING("GOAWAY received"), + GRPC_ERROR_INT_HTTP2_ERROR, (intptr_t)goaway_error), + GRPC_ERROR_STR_RAW_BYTES, goaway_text); /* When a client receives a GOAWAY with error code ENHANCE_YOUR_CALM and debug * data equal to "too_many_pings", it should log the occurrence at a log level @@ -1141,19 +1158,13 @@ void grpc_chttp2_add_incoming_goaway(grpc_exec_ctx *exec_ctx, /* lie: use transient failure from the transport to indicate goaway has been * received */ - connectivity_state_set( - exec_ctx, t, GRPC_CHANNEL_TRANSIENT_FAILURE, - grpc_error_set_str( - grpc_error_set_int( - GRPC_ERROR_CREATE_FROM_STATIC_STRING("GOAWAY received"), - GRPC_ERROR_INT_HTTP2_ERROR, (intptr_t)goaway_error), - GRPC_ERROR_STR_RAW_BYTES, goaway_text), - "got_goaway"); + connectivity_state_set(exec_ctx, t, GRPC_CHANNEL_TRANSIENT_FAILURE, + GRPC_ERROR_REF(t->goaway_error), "got_goaway"); } -static void maybe_start_some_streams(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { - grpc_chttp2_stream *s; +static void maybe_start_some_streams(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { + grpc_chttp2_stream* s; /* start streams where we have free grpc_chttp2_stream ids and free * concurrency */ while (t->next_stream_id <= MAX_CLIENT_STREAM_ID && @@ -1204,32 +1215,32 @@ static void maybe_start_some_streams(grpc_exec_ctx *exec_ctx, bits being used for flags defined above) */ #define CLOSURE_BARRIER_FIRST_REF_BIT (1 << 16) -static grpc_closure *add_closure_barrier(grpc_closure *closure) { +static grpc_closure* add_closure_barrier(grpc_closure* closure) { closure->next_data.scratch += CLOSURE_BARRIER_FIRST_REF_BIT; return closure; } -static void null_then_run_closure(grpc_exec_ctx *exec_ctx, - grpc_closure **closure, grpc_error *error) { - grpc_closure *c = *closure; - *closure = NULL; +static void null_then_run_closure(grpc_exec_ctx* exec_ctx, + grpc_closure** closure, grpc_error* error) { + grpc_closure* c = *closure; + *closure = nullptr; GRPC_CLOSURE_RUN(exec_ctx, c, error); } -void grpc_chttp2_complete_closure_step(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, - grpc_closure **pclosure, - grpc_error *error, const char *desc) { - grpc_closure *closure = *pclosure; - *pclosure = NULL; - if (closure == NULL) { +void grpc_chttp2_complete_closure_step(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, + grpc_closure** pclosure, + grpc_error* error, const char* desc) { + grpc_closure* closure = *pclosure; + *pclosure = nullptr; + if (closure == nullptr) { GRPC_ERROR_UNREF(error); return; } closure->next_data.scratch -= CLOSURE_BARRIER_FIRST_REF_BIT; - if (GRPC_TRACER_ON(grpc_http_trace)) { - const char *errstr = grpc_error_string(error); + if (grpc_http_trace.enabled()) { + const char* errstr = grpc_error_string(error); gpr_log( GPR_DEBUG, "complete_closure_step: t=%p %p refs=%d flags=0x%04x desc=%s err=%s " @@ -1253,7 +1264,7 @@ void grpc_chttp2_complete_closure_step(grpc_exec_ctx *exec_ctx, if (closure->next_data.scratch < CLOSURE_BARRIER_FIRST_REF_BIT) { if (closure->next_data.scratch & CLOSURE_BARRIER_STATS_BIT) { grpc_transport_move_stats(&s->stats, s->collecting_stats); - s->collecting_stats = NULL; + s->collecting_stats = nullptr; } if ((t->write_state == GRPC_CHTTP2_WRITE_STATE_IDLE) || !(closure->next_data.scratch & CLOSURE_BARRIER_MAY_COVER_WRITE)) { @@ -1265,17 +1276,17 @@ void grpc_chttp2_complete_closure_step(grpc_exec_ctx *exec_ctx, } } -static bool contains_non_ok_status(grpc_metadata_batch *batch) { - if (batch->idx.named.grpc_status != NULL) { +static bool contains_non_ok_status(grpc_metadata_batch* batch) { + if (batch->idx.named.grpc_status != nullptr) { return !grpc_mdelem_eq(batch->idx.named.grpc_status->md, GRPC_MDELEM_GRPC_STATUS_0); } return false; } -static void maybe_become_writable_due_to_send_msg(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s) { +static void maybe_become_writable_due_to_send_msg(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s) { if (s->id != 0 && (!s->write_buffering || s->flow_controlled_buffer.length > t->write_buffer_size)) { grpc_chttp2_mark_stream_writable(exec_ctx, t, s); @@ -1284,20 +1295,20 @@ static void maybe_become_writable_due_to_send_msg(grpc_exec_ctx *exec_ctx, } } -static void add_fetched_slice_locked(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s) { +static void add_fetched_slice_locked(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s) { s->fetched_send_message_length += (uint32_t)GRPC_SLICE_LENGTH(s->fetching_slice); grpc_slice_buffer_add(&s->flow_controlled_buffer, s->fetching_slice); maybe_become_writable_due_to_send_msg(exec_ctx, t, s); } -static void continue_fetching_send_locked(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s) { +static void continue_fetching_send_locked(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s) { for (;;) { - if (s->fetching_send_message == NULL) { + if (s->fetching_send_message == nullptr) { /* Stream was cancelled before message fetch completed */ abort(); /* TODO(ctiller): what cleanup here? */ return; /* early out */ @@ -1310,27 +1321,27 @@ static void continue_fetching_send_locked(grpc_exec_ctx *exec_ctx, exec_ctx, t, s, &s->fetching_send_message_finished, GRPC_ERROR_NONE, "fetching_send_message_finished"); } else { - grpc_chttp2_write_cb *cb = t->write_cb_pool; - if (cb == NULL) { - cb = (grpc_chttp2_write_cb *)gpr_malloc(sizeof(*cb)); + grpc_chttp2_write_cb* cb = t->write_cb_pool; + if (cb == nullptr) { + cb = (grpc_chttp2_write_cb*)gpr_malloc(sizeof(*cb)); } else { t->write_cb_pool = cb->next; } cb->call_at_byte = notify_offset; cb->closure = s->fetching_send_message_finished; - s->fetching_send_message_finished = NULL; - grpc_chttp2_write_cb **list = + s->fetching_send_message_finished = nullptr; + grpc_chttp2_write_cb** list = s->fetching_send_message->flags & GRPC_WRITE_THROUGH ? &s->on_write_finished_cbs : &s->on_flow_controlled_cbs; cb->next = *list; *list = cb; } - s->fetching_send_message = NULL; + s->fetching_send_message = nullptr; return; /* early out */ } else if (grpc_byte_stream_next(exec_ctx, s->fetching_send_message, UINT32_MAX, &s->complete_fetch_locked)) { - grpc_error *error = grpc_byte_stream_pull( + grpc_error* error = grpc_byte_stream_pull( exec_ctx, s->fetching_send_message, &s->fetching_slice); if (error != GRPC_ERROR_NONE) { grpc_byte_stream_destroy(exec_ctx, s->fetching_send_message); @@ -1342,10 +1353,10 @@ static void continue_fetching_send_locked(grpc_exec_ctx *exec_ctx, } } -static void complete_fetch_locked(grpc_exec_ctx *exec_ctx, void *gs, - grpc_error *error) { - grpc_chttp2_stream *s = (grpc_chttp2_stream *)gs; - grpc_chttp2_transport *t = s->t; +static void complete_fetch_locked(grpc_exec_ctx* exec_ctx, void* gs, + grpc_error* error) { + grpc_chttp2_stream* s = (grpc_chttp2_stream*)gs; + grpc_chttp2_transport* t = s->t; if (error == GRPC_ERROR_NONE) { error = grpc_byte_stream_pull(exec_ctx, s->fetching_send_message, &s->fetching_slice); @@ -1360,14 +1371,14 @@ static void complete_fetch_locked(grpc_exec_ctx *exec_ctx, void *gs, } } -static void do_nothing(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) {} +static void do_nothing(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) {} -static void log_metadata(const grpc_metadata_batch *md_batch, uint32_t id, +static void log_metadata(const grpc_metadata_batch* md_batch, uint32_t id, bool is_client, bool is_initial) { - for (grpc_linked_mdelem *md = md_batch->list.head; md != NULL; + for (grpc_linked_mdelem* md = md_batch->list.head; md != nullptr; md = md->next) { - char *key = grpc_slice_to_c_string(GRPC_MDKEY(md->md)); - char *value = grpc_slice_to_c_string(GRPC_MDVALUE(md->md)); + char* key = grpc_slice_to_c_string(GRPC_MDKEY(md->md)); + char* value = grpc_slice_to_c_string(GRPC_MDVALUE(md->md)); gpr_log(GPR_INFO, "HTTP:%d:%s:%s: %s: %s", id, is_initial ? "HDR" : "TRL", is_client ? "CLI" : "SVR", key, value); gpr_free(key); @@ -1375,20 +1386,20 @@ static void log_metadata(const grpc_metadata_batch *md_batch, uint32_t id, } } -static void perform_stream_op_locked(grpc_exec_ctx *exec_ctx, void *stream_op, - grpc_error *error_ignored) { +static void perform_stream_op_locked(grpc_exec_ctx* exec_ctx, void* stream_op, + grpc_error* error_ignored) { GPR_TIMER_BEGIN("perform_stream_op_locked", 0); - grpc_transport_stream_op_batch *op = - (grpc_transport_stream_op_batch *)stream_op; - grpc_chttp2_stream *s = (grpc_chttp2_stream *)op->handler_private.extra_arg; - grpc_transport_stream_op_batch_payload *op_payload = op->payload; - grpc_chttp2_transport *t = s->t; + grpc_transport_stream_op_batch* op = + (grpc_transport_stream_op_batch*)stream_op; + grpc_chttp2_stream* s = (grpc_chttp2_stream*)op->handler_private.extra_arg; + grpc_transport_stream_op_batch_payload* op_payload = op->payload; + grpc_chttp2_transport* t = s->t; GRPC_STATS_INC_HTTP2_OP_BATCHES(exec_ctx); - if (GRPC_TRACER_ON(grpc_http_trace)) { - char *str = grpc_transport_stream_op_batch_string(op); + if (grpc_http_trace.enabled()) { + char* str = grpc_transport_stream_op_batch_string(op); gpr_log(GPR_DEBUG, "perform_stream_op_locked: %s; on_complete = %p", str, op->on_complete); gpr_free(str); @@ -1402,10 +1413,10 @@ static void perform_stream_op_locked(grpc_exec_ctx *exec_ctx, void *stream_op, } } - grpc_closure *on_complete = op->on_complete; - if (on_complete == NULL) { + grpc_closure* on_complete = op->on_complete; + if (on_complete == nullptr) { on_complete = - GRPC_CLOSURE_CREATE(do_nothing, NULL, grpc_schedule_on_exec_ctx); + GRPC_CLOSURE_CREATE(do_nothing, nullptr, grpc_schedule_on_exec_ctx); } /* use final_data as a barrier until enqueue time; the inital counter is @@ -1414,7 +1425,7 @@ static void perform_stream_op_locked(grpc_exec_ctx *exec_ctx, void *stream_op, on_complete->error_data.error = GRPC_ERROR_NONE; if (op->collect_stats) { - GPR_ASSERT(s->collecting_stats == NULL); + GPR_ASSERT(s->collecting_stats == nullptr); s->collecting_stats = op_payload->collect_stats.collect_stats; on_complete->next_data.scratch |= CLOSURE_BARRIER_STATS_BIT; } @@ -1427,12 +1438,12 @@ static void perform_stream_op_locked(grpc_exec_ctx *exec_ctx, void *stream_op, if (op->send_initial_metadata) { GRPC_STATS_INC_HTTP2_OP_SEND_INITIAL_METADATA(exec_ctx); - GPR_ASSERT(s->send_initial_metadata_finished == NULL); + GPR_ASSERT(s->send_initial_metadata_finished == nullptr); on_complete->next_data.scratch |= CLOSURE_BARRIER_MAY_COVER_WRITE; /* Identify stream compression */ if (op_payload->send_initial_metadata.send_initial_metadata->idx.named - .content_encoding == NULL || + .content_encoding == nullptr || grpc_stream_compression_method_parse( GRPC_MDVALUE( op_payload->send_initial_metadata.send_initial_metadata->idx @@ -1493,7 +1504,7 @@ static void perform_stream_op_locked(grpc_exec_ctx *exec_ctx, void *stream_op, } } } else { - s->send_initial_metadata = NULL; + s->send_initial_metadata = nullptr; grpc_chttp2_complete_closure_step( exec_ctx, t, s, &s->send_initial_metadata_finished, GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( @@ -1502,7 +1513,7 @@ static void perform_stream_op_locked(grpc_exec_ctx *exec_ctx, void *stream_op, "send_initial_metadata_finished"); } } - if (op_payload->send_initial_metadata.peer_string != NULL) { + if (op_payload->send_initial_metadata.peer_string != nullptr) { gpr_atm_rel_store(op_payload->send_initial_metadata.peer_string, (gpr_atm)gpr_strdup(t->peer_string)); } @@ -1529,8 +1540,8 @@ static void perform_stream_op_locked(grpc_exec_ctx *exec_ctx, void *stream_op, &s->write_closed_error, 1), "fetching_send_message_finished"); } else { - GPR_ASSERT(s->fetching_send_message == NULL); - uint8_t *frame_hdr = grpc_slice_buffer_tiny_add( + GPR_ASSERT(s->fetching_send_message == nullptr); + uint8_t* frame_hdr = grpc_slice_buffer_tiny_add( &s->flow_controlled_buffer, GRPC_HEADER_SIZE_IN_BYTES); uint32_t flags = op_payload->send_message.send_message->flags; frame_hdr[0] = (flags & GRPC_WRITE_INTERNAL_COMPRESS) != 0; @@ -1557,7 +1568,7 @@ static void perform_stream_op_locked(grpc_exec_ctx *exec_ctx, void *stream_op, if (op->send_trailing_metadata) { GRPC_STATS_INC_HTTP2_OP_SEND_TRAILING_METADATA(exec_ctx); - GPR_ASSERT(s->send_trailing_metadata_finished == NULL); + GPR_ASSERT(s->send_trailing_metadata_finished == nullptr); on_complete->next_data.scratch |= CLOSURE_BARRIER_MAY_COVER_WRITE; s->send_trailing_metadata_finished = add_closure_barrier(on_complete); s->send_trailing_metadata = @@ -1585,7 +1596,7 @@ static void perform_stream_op_locked(grpc_exec_ctx *exec_ctx, void *stream_op, s->seen_error = true; } if (s->write_closed) { - s->send_trailing_metadata = NULL; + s->send_trailing_metadata = nullptr; grpc_chttp2_complete_closure_step( exec_ctx, t, s, &s->send_trailing_metadata_finished, grpc_metadata_batch_is_empty( @@ -1607,14 +1618,14 @@ static void perform_stream_op_locked(grpc_exec_ctx *exec_ctx, void *stream_op, if (op->recv_initial_metadata) { GRPC_STATS_INC_HTTP2_OP_RECV_INITIAL_METADATA(exec_ctx); - GPR_ASSERT(s->recv_initial_metadata_ready == NULL); + GPR_ASSERT(s->recv_initial_metadata_ready == nullptr); s->recv_initial_metadata_ready = op_payload->recv_initial_metadata.recv_initial_metadata_ready; s->recv_initial_metadata = op_payload->recv_initial_metadata.recv_initial_metadata; s->trailing_metadata_available = op_payload->recv_initial_metadata.trailing_metadata_available; - if (op_payload->recv_initial_metadata.peer_string != NULL) { + if (op_payload->recv_initial_metadata.peer_string != nullptr) { gpr_atm_rel_store(op_payload->recv_initial_metadata.peer_string, (gpr_atm)gpr_strdup(t->peer_string)); } @@ -1624,7 +1635,7 @@ static void perform_stream_op_locked(grpc_exec_ctx *exec_ctx, void *stream_op, if (op->recv_message) { GRPC_STATS_INC_HTTP2_OP_RECV_MESSAGE(exec_ctx); size_t already_received; - GPR_ASSERT(s->recv_message_ready == NULL); + GPR_ASSERT(s->recv_message_ready == nullptr); GPR_ASSERT(!s->pending_byte_stream); s->recv_message_ready = op_payload->recv_message.recv_message_ready; s->recv_message = op_payload->recv_message.recv_message; @@ -1642,7 +1653,7 @@ static void perform_stream_op_locked(grpc_exec_ctx *exec_ctx, void *stream_op, if (op->recv_trailing_metadata) { GRPC_STATS_INC_HTTP2_OP_RECV_TRAILING_METADATA(exec_ctx); - GPR_ASSERT(s->recv_trailing_metadata_finished == NULL); + GPR_ASSERT(s->recv_trailing_metadata_finished == nullptr); s->recv_trailing_metadata_finished = add_closure_barrier(on_complete); s->recv_trailing_metadata = op_payload->recv_trailing_metadata.recv_trailing_metadata; @@ -1657,12 +1668,12 @@ static void perform_stream_op_locked(grpc_exec_ctx *exec_ctx, void *stream_op, GRPC_CHTTP2_STREAM_UNREF(exec_ctx, s, "perform_stream_op"); } -static void perform_stream_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_stream *gs, - grpc_transport_stream_op_batch *op) { +static void perform_stream_op(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_stream* gs, + grpc_transport_stream_op_batch* op) { GPR_TIMER_BEGIN("perform_stream_op", 0); - grpc_chttp2_transport *t = (grpc_chttp2_transport *)gt; - grpc_chttp2_stream *s = (grpc_chttp2_stream *)gs; + grpc_chttp2_transport* t = (grpc_chttp2_transport*)gt; + grpc_chttp2_stream* s = (grpc_chttp2_stream*)gs; if (!t->is_client) { if (op->send_initial_metadata) { @@ -1677,8 +1688,8 @@ static void perform_stream_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, } } - if (GRPC_TRACER_ON(grpc_http_trace)) { - char *str = grpc_transport_stream_op_batch_string(op); + if (grpc_http_trace.enabled()) { + char* str = grpc_transport_stream_op_batch_string(op); gpr_log(GPR_DEBUG, "perform_stream_op[s=%p]: %s", s, str); gpr_free(str); } @@ -1693,11 +1704,11 @@ static void perform_stream_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, GPR_TIMER_END("perform_stream_op", 0); } -static void cancel_pings(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_error *error) { +static void cancel_pings(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_error* error) { /* callback remaining pings: they're not allowed to call into the transpot, and maybe they hold resources that need to be freed */ - grpc_chttp2_ping_queue *pq = &t->ping_queue; + grpc_chttp2_ping_queue* pq = &t->ping_queue; GPR_ASSERT(error != GRPC_ERROR_NONE); for (size_t j = 0; j < GRPC_CHTTP2_PCL_COUNT; j++) { grpc_closure_list_fail_all(&pq->lists[j], GRPC_ERROR_REF(error)); @@ -1706,24 +1717,24 @@ static void cancel_pings(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, GRPC_ERROR_UNREF(error); } -static void send_ping_locked(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_closure *on_initiate, grpc_closure *on_ack) { +static void send_ping_locked(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_closure* on_initiate, grpc_closure* on_ack) { if (t->closed_with_error != GRPC_ERROR_NONE) { GRPC_CLOSURE_SCHED(exec_ctx, on_initiate, GRPC_ERROR_REF(t->closed_with_error)); GRPC_CLOSURE_SCHED(exec_ctx, on_ack, GRPC_ERROR_REF(t->closed_with_error)); return; } - grpc_chttp2_ping_queue *pq = &t->ping_queue; + grpc_chttp2_ping_queue* pq = &t->ping_queue; grpc_closure_list_append(&pq->lists[GRPC_CHTTP2_PCL_INITIATE], on_initiate, GRPC_ERROR_NONE); grpc_closure_list_append(&pq->lists[GRPC_CHTTP2_PCL_NEXT], on_ack, GRPC_ERROR_NONE); } -static void retry_initiate_ping_locked(grpc_exec_ctx *exec_ctx, void *tp, - grpc_error *error) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)tp; +static void retry_initiate_ping_locked(grpc_exec_ctx* exec_ctx, void* tp, + grpc_error* error) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)tp; t->ping_state.is_delayed_ping_timer_set = false; if (error == GRPC_ERROR_NONE) { grpc_chttp2_initiate_write(exec_ctx, t, @@ -1731,11 +1742,11 @@ static void retry_initiate_ping_locked(grpc_exec_ctx *exec_ctx, void *tp, } } -void grpc_chttp2_ack_ping(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, +void grpc_chttp2_ack_ping(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, uint64_t id) { - grpc_chttp2_ping_queue *pq = &t->ping_queue; + grpc_chttp2_ping_queue* pq = &t->ping_queue; if (pq->inflight_id != id) { - char *from = grpc_endpoint_get_peer(t->ep); + char* from = grpc_endpoint_get_peer(t->ep); gpr_log(GPR_DEBUG, "Unknown ping response from %s: %" PRIx64, from, id); gpr_free(from); return; @@ -1747,13 +1758,13 @@ void grpc_chttp2_ack_ping(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, } } -static void send_goaway(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_error *error) { +static void send_goaway(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_error* error) { t->sent_goaway_state = GRPC_CHTTP2_GOAWAY_SEND_SCHEDULED; grpc_http2_error_code http_error; grpc_slice slice; - grpc_error_get_status(exec_ctx, error, GRPC_MILLIS_INF_FUTURE, NULL, &slice, - &http_error); + grpc_error_get_status(exec_ctx, error, GRPC_MILLIS_INF_FUTURE, nullptr, + &slice, &http_error, nullptr); grpc_chttp2_goaway_append(t->last_new_stream_id, (uint32_t)http_error, grpc_slice_ref_internal(slice), &t->qbuf); grpc_chttp2_initiate_write(exec_ctx, t, @@ -1761,8 +1772,8 @@ static void send_goaway(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, GRPC_ERROR_UNREF(error); } -void grpc_chttp2_add_ping_strike(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { +void grpc_chttp2_add_ping_strike(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { t->ping_recv_state.ping_strikes++; if (++t->ping_recv_state.ping_strikes > t->ping_policy.max_ping_strikes && t->ping_policy.max_ping_strikes != 0) { @@ -1772,19 +1783,19 @@ void grpc_chttp2_add_ping_strike(grpc_exec_ctx *exec_ctx, GRPC_ERROR_INT_HTTP2_ERROR, GRPC_HTTP2_ENHANCE_YOUR_CALM)); /*The transport will be closed after the write is done */ close_transport_locked( - exec_ctx, t, grpc_error_set_int( - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Too many pings"), - GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE)); + exec_ctx, t, + grpc_error_set_int( + GRPC_ERROR_CREATE_FROM_STATIC_STRING("Too many pings"), + GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE)); } } -static void perform_transport_op_locked(grpc_exec_ctx *exec_ctx, - void *stream_op, - grpc_error *error_ignored) { - grpc_transport_op *op = (grpc_transport_op *)stream_op; - grpc_chttp2_transport *t = - (grpc_chttp2_transport *)op->handler_private.extra_arg; - grpc_error *close_transport = op->disconnect_with_error; +static void perform_transport_op_locked(grpc_exec_ctx* exec_ctx, + void* stream_op, + grpc_error* error_ignored) { + grpc_transport_op* op = (grpc_transport_op*)stream_op; + grpc_chttp2_transport* t = + (grpc_chttp2_transport*)op->handler_private.extra_arg; if (op->goaway_error) { send_goaway(exec_ctx, t, op->goaway_error); @@ -1805,19 +1816,19 @@ static void perform_transport_op_locked(grpc_exec_ctx *exec_ctx, } if (op->send_ping) { - send_ping_locked(exec_ctx, t, NULL, op->send_ping); + send_ping_locked(exec_ctx, t, nullptr, op->send_ping); grpc_chttp2_initiate_write(exec_ctx, t, GRPC_CHTTP2_INITIATE_WRITE_APPLICATION_PING); } - if (op->on_connectivity_state_change != NULL) { + if (op->on_connectivity_state_change != nullptr) { grpc_connectivity_state_notify_on_state_change( exec_ctx, &t->channel_callback.state_tracker, op->connectivity_state, op->on_connectivity_state_change); } - if (close_transport != GRPC_ERROR_NONE) { - close_transport_locked(exec_ctx, t, close_transport); + if (op->disconnect_with_error != GRPC_ERROR_NONE) { + close_transport_locked(exec_ctx, t, op->disconnect_with_error); } GRPC_CLOSURE_RUN(exec_ctx, op->on_consumed, GRPC_ERROR_NONE); @@ -1825,10 +1836,10 @@ static void perform_transport_op_locked(grpc_exec_ctx *exec_ctx, GRPC_CHTTP2_UNREF_TRANSPORT(exec_ctx, t, "transport_op"); } -static void perform_transport_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_transport_op *op) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)gt; - char *msg = grpc_transport_op_string(op); +static void perform_transport_op(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_transport_op* op) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)gt; + char* msg = grpc_transport_op_string(op); gpr_free(msg); op->handler_private.extra_arg = gt; GRPC_CHTTP2_REF_TRANSPORT(t, "transport_op"); @@ -1843,10 +1854,10 @@ static void perform_transport_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, * INPUT PROCESSING - GENERAL */ -void grpc_chttp2_maybe_complete_recv_initial_metadata(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s) { - if (s->recv_initial_metadata_ready != NULL && +void grpc_chttp2_maybe_complete_recv_initial_metadata(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s) { + if (s->recv_initial_metadata_ready != nullptr && s->published_metadata[0] != GRPC_METADATA_NOT_PUBLISHED) { if (s->seen_error) { grpc_slice_buffer_reset_and_unref_internal(exec_ctx, &s->frame_storage); @@ -1862,12 +1873,12 @@ void grpc_chttp2_maybe_complete_recv_initial_metadata(grpc_exec_ctx *exec_ctx, } } -void grpc_chttp2_maybe_complete_recv_message(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s) { - grpc_error *error = GRPC_ERROR_NONE; - if (s->recv_message_ready != NULL) { - *s->recv_message = NULL; +void grpc_chttp2_maybe_complete_recv_message(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s) { + grpc_error* error = GRPC_ERROR_NONE; + if (s->recv_message_ready != nullptr) { + *s->recv_message = nullptr; if (s->final_metadata_requested && s->seen_error) { grpc_slice_buffer_reset_and_unref_internal(exec_ctx, &s->frame_storage); if (!s->pending_byte_stream) { @@ -1896,7 +1907,7 @@ void grpc_chttp2_maybe_complete_recv_message(grpc_exec_ctx *exec_ctx, if (!grpc_stream_decompress( s->stream_decompression_ctx, &s->unprocessed_incoming_frames_buffer, - &s->decompressed_data_buffer, NULL, + &s->decompressed_data_buffer, nullptr, GRPC_HEADER_SIZE_IN_BYTES - s->decompressed_header_bytes, &end_of_context)) { grpc_slice_buffer_reset_and_unref_internal(exec_ctx, @@ -1912,17 +1923,17 @@ void grpc_chttp2_maybe_complete_recv_message(grpc_exec_ctx *exec_ctx, } error = grpc_deframe_unprocessed_incoming_frames( exec_ctx, &s->data_parser, s, &s->decompressed_data_buffer, - NULL, s->recv_message); + nullptr, s->recv_message); if (end_of_context) { grpc_stream_compression_context_destroy( s->stream_decompression_ctx); - s->stream_decompression_ctx = NULL; + s->stream_decompression_ctx = nullptr; } } } else { error = grpc_deframe_unprocessed_incoming_frames( exec_ctx, &s->data_parser, s, - &s->unprocessed_incoming_frames_buffer, NULL, s->recv_message); + &s->unprocessed_incoming_frames_buffer, nullptr, s->recv_message); } if (error != GRPC_ERROR_NONE) { s->seen_error = true; @@ -1931,26 +1942,26 @@ void grpc_chttp2_maybe_complete_recv_message(grpc_exec_ctx *exec_ctx, grpc_slice_buffer_reset_and_unref_internal( exec_ctx, &s->unprocessed_incoming_frames_buffer); break; - } else if (*s->recv_message != NULL) { + } else if (*s->recv_message != nullptr) { break; } } } - if (error == GRPC_ERROR_NONE && *s->recv_message != NULL) { + if (error == GRPC_ERROR_NONE && *s->recv_message != nullptr) { null_then_run_closure(exec_ctx, &s->recv_message_ready, GRPC_ERROR_NONE); } else if (s->published_metadata[1] != GRPC_METADATA_NOT_PUBLISHED) { - *s->recv_message = NULL; + *s->recv_message = nullptr; null_then_run_closure(exec_ctx, &s->recv_message_ready, GRPC_ERROR_NONE); } GRPC_ERROR_UNREF(error); } } -void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s) { +void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s) { grpc_chttp2_maybe_complete_recv_message(exec_ctx, t, s); - if (s->recv_trailing_metadata_finished != NULL && s->read_closed && + if (s->recv_trailing_metadata_finished != nullptr && s->read_closed && s->write_closed) { if (s->seen_error) { grpc_slice_buffer_reset_and_unref_internal(exec_ctx, &s->frame_storage); @@ -1962,7 +1973,7 @@ void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_exec_ctx *exec_ctx, bool pending_data = s->pending_byte_stream || s->unprocessed_incoming_frames_buffer.length > 0; if (s->read_closed && s->frame_storage.length > 0 && !pending_data && - !s->seen_error && s->recv_trailing_metadata_finished != NULL) { + !s->seen_error && s->recv_trailing_metadata_finished != nullptr) { /* Maybe some SYNC_FLUSH data is left in frame_storage. Consume them and * maybe decompress the next 5 bytes in the stream. */ bool end_of_context; @@ -1970,10 +1981,10 @@ void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_exec_ctx *exec_ctx, s->stream_decompression_ctx = grpc_stream_compression_context_create( s->stream_decompression_method); } - if (!grpc_stream_decompress(s->stream_decompression_ctx, - &s->frame_storage, - &s->unprocessed_incoming_frames_buffer, NULL, - GRPC_HEADER_SIZE_IN_BYTES, &end_of_context)) { + if (!grpc_stream_decompress( + s->stream_decompression_ctx, &s->frame_storage, + &s->unprocessed_incoming_frames_buffer, nullptr, + GRPC_HEADER_SIZE_IN_BYTES, &end_of_context)) { grpc_slice_buffer_reset_and_unref_internal(exec_ctx, &s->frame_storage); grpc_slice_buffer_reset_and_unref_internal( exec_ctx, &s->unprocessed_incoming_frames_buffer); @@ -1985,12 +1996,12 @@ void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_exec_ctx *exec_ctx, } if (end_of_context) { grpc_stream_compression_context_destroy(s->stream_decompression_ctx); - s->stream_decompression_ctx = NULL; + s->stream_decompression_ctx = nullptr; } } } if (s->read_closed && s->frame_storage.length == 0 && !pending_data && - s->recv_trailing_metadata_finished != NULL) { + s->recv_trailing_metadata_finished != nullptr) { grpc_chttp2_incoming_metadata_buffer_publish( exec_ctx, &s->metadata_buffer[1], s->recv_trailing_metadata); grpc_chttp2_complete_closure_step( @@ -2000,24 +2011,24 @@ void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_exec_ctx *exec_ctx, } } -static void remove_stream(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - uint32_t id, grpc_error *error) { - grpc_chttp2_stream *s = - (grpc_chttp2_stream *)grpc_chttp2_stream_map_delete(&t->stream_map, id); +static void remove_stream(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + uint32_t id, grpc_error* error) { + grpc_chttp2_stream* s = + (grpc_chttp2_stream*)grpc_chttp2_stream_map_delete(&t->stream_map, id); GPR_ASSERT(s); if (t->incoming_stream == s) { - t->incoming_stream = NULL; + t->incoming_stream = nullptr; grpc_chttp2_parsing_become_skip_parser(exec_ctx, t); } if (s->pending_byte_stream) { - if (s->on_next != NULL) { - grpc_chttp2_incoming_byte_stream *bs = s->data_parser.parsing_frame; + if (s->on_next != nullptr) { + grpc_chttp2_incoming_byte_stream* bs = s->data_parser.parsing_frame; if (error == GRPC_ERROR_NONE) { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Truncated message"); } incoming_byte_stream_publish_error(exec_ctx, bs, error); incoming_byte_stream_unref(exec_ctx, bs); - s->data_parser.parsing_frame = NULL; + s->data_parser.parsing_frame = nullptr; } else { GRPC_ERROR_UNREF(s->byte_stream_error); s->byte_stream_error = GRPC_ERROR_REF(error); @@ -2042,9 +2053,9 @@ static void remove_stream(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, maybe_start_some_streams(exec_ctx, t); } -void grpc_chttp2_cancel_stream(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, grpc_chttp2_stream *s, - grpc_error *due_to_error) { +void grpc_chttp2_cancel_stream(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, grpc_chttp2_stream* s, + grpc_error* due_to_error) { if (!t->is_client && !s->sent_trailing_metadata && grpc_error_has_clear_grpc_status(due_to_error)) { close_from_api(exec_ctx, t, s, due_to_error); @@ -2054,8 +2065,8 @@ void grpc_chttp2_cancel_stream(grpc_exec_ctx *exec_ctx, if (!s->read_closed || !s->write_closed) { if (s->id != 0) { grpc_http2_error_code http_error; - grpc_error_get_status(exec_ctx, due_to_error, s->deadline, NULL, NULL, - &http_error); + grpc_error_get_status(exec_ctx, due_to_error, s->deadline, nullptr, + nullptr, &http_error, nullptr); grpc_slice_buffer_add( &t->qbuf, grpc_chttp2_rst_stream_create(s->id, (uint32_t)http_error, &s->stats.outgoing)); @@ -2069,12 +2080,12 @@ void grpc_chttp2_cancel_stream(grpc_exec_ctx *exec_ctx, grpc_chttp2_mark_stream_closed(exec_ctx, t, s, 1, 1, due_to_error); } -void grpc_chttp2_fake_status(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_chttp2_stream *s, grpc_error *error) { +void grpc_chttp2_fake_status(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_error* error) { grpc_status_code status; grpc_slice slice; - grpc_error_get_status(exec_ctx, error, s->deadline, &status, &slice, NULL); - + grpc_error_get_status(exec_ctx, error, s->deadline, &status, &slice, nullptr, + nullptr); if (status != GRPC_STATUS_OK) { s->seen_error = true; } @@ -2085,7 +2096,7 @@ void grpc_chttp2_fake_status(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, what we want - which is safe because we haven't told anyone about the metadata yet */ if (s->published_metadata[1] == GRPC_METADATA_NOT_PUBLISHED || - s->recv_trailing_metadata_finished != NULL) { + s->recv_trailing_metadata_finished != nullptr) { char status_string[GPR_LTOA_MIN_BUFSIZE]; gpr_ltoa(status, status_string); GRPC_LOG_IF_ERROR("add_status", @@ -2109,7 +2120,7 @@ void grpc_chttp2_fake_status(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, GRPC_ERROR_UNREF(error); } -static void add_error(grpc_error *error, grpc_error **refs, size_t *nrefs) { +static void add_error(grpc_error* error, grpc_error** refs, size_t* nrefs) { if (error == GRPC_ERROR_NONE) return; for (size_t i = 0; i < *nrefs; i++) { if (error == refs[i]) { @@ -2120,14 +2131,14 @@ static void add_error(grpc_error *error, grpc_error **refs, size_t *nrefs) { ++*nrefs; } -static grpc_error *removal_error(grpc_error *extra_error, grpc_chttp2_stream *s, - const char *master_error_msg) { - grpc_error *refs[3]; +static grpc_error* removal_error(grpc_error* extra_error, grpc_chttp2_stream* s, + const char* master_error_msg) { + grpc_error* refs[3]; size_t nrefs = 0; add_error(s->read_closed_error, refs, &nrefs); add_error(s->write_closed_error, refs, &nrefs); add_error(extra_error, refs, &nrefs); - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; if (nrefs > 0) { error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(master_error_msg, refs, nrefs); @@ -2136,11 +2147,11 @@ static grpc_error *removal_error(grpc_error *extra_error, grpc_chttp2_stream *s, return error; } -static void flush_write_list(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_chttp2_stream *s, grpc_chttp2_write_cb **list, - grpc_error *error) { +static void flush_write_list(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_chttp2_write_cb** list, + grpc_error* error) { while (*list) { - grpc_chttp2_write_cb *cb = *list; + grpc_chttp2_write_cb* cb = *list; *list = cb->next; grpc_chttp2_complete_closure_step(exec_ctx, t, s, &cb->closure, GRPC_ERROR_REF(error), @@ -2151,22 +2162,22 @@ static void flush_write_list(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, GRPC_ERROR_UNREF(error); } -void grpc_chttp2_fail_pending_writes(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, grpc_error *error) { +void grpc_chttp2_fail_pending_writes(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_error* error) { error = removal_error(error, s, "Pending writes failed due to stream closure"); - s->send_initial_metadata = NULL; + s->send_initial_metadata = nullptr; grpc_chttp2_complete_closure_step( exec_ctx, t, s, &s->send_initial_metadata_finished, GRPC_ERROR_REF(error), "send_initial_metadata_finished"); - s->send_trailing_metadata = NULL; + s->send_trailing_metadata = nullptr; grpc_chttp2_complete_closure_step( exec_ctx, t, s, &s->send_trailing_metadata_finished, GRPC_ERROR_REF(error), "send_trailing_metadata_finished"); - s->fetching_send_message = NULL; + s->fetching_send_message = nullptr; grpc_chttp2_complete_closure_step( exec_ctx, t, s, &s->fetching_send_message_finished, GRPC_ERROR_REF(error), "fetching_send_message_finished"); @@ -2175,10 +2186,10 @@ void grpc_chttp2_fail_pending_writes(grpc_exec_ctx *exec_ctx, flush_write_list(exec_ctx, t, s, &s->on_flow_controlled_cbs, error); } -void grpc_chttp2_mark_stream_closed(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, int close_reads, - int close_writes, grpc_error *error) { +void grpc_chttp2_mark_stream_closed(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, int close_reads, + int close_writes, grpc_error* error) { if (s->read_closed && s->write_closed) { /* already closed */ grpc_chttp2_maybe_complete_recv_trailing_metadata(exec_ctx, t, s); @@ -2199,7 +2210,7 @@ void grpc_chttp2_mark_stream_closed(grpc_exec_ctx *exec_ctx, } if (s->read_closed && s->write_closed) { became_closed = true; - grpc_error *overall_error = + grpc_error* overall_error = removal_error(GRPC_ERROR_REF(error), s, "Stream removed"); if (s->id != 0) { remove_stream(exec_ctx, t, s->id, GRPC_ERROR_REF(overall_error)); @@ -2227,19 +2238,19 @@ void grpc_chttp2_mark_stream_closed(grpc_exec_ctx *exec_ctx, GRPC_ERROR_UNREF(error); } -static void close_from_api(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_chttp2_stream *s, grpc_error *error) { +static void close_from_api(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_error* error) { grpc_slice hdr; grpc_slice status_hdr; grpc_slice http_status_hdr; grpc_slice content_type_hdr; grpc_slice message_pfx; - uint8_t *p; + uint8_t* p; uint32_t len = 0; grpc_status_code grpc_status; grpc_slice slice; grpc_error_get_status(exec_ctx, error, s->deadline, &grpc_status, &slice, - NULL); + nullptr, nullptr); GPR_ASSERT(grpc_status >= 0 && (int)grpc_status < 100); @@ -2387,20 +2398,20 @@ static void close_from_api(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, } typedef struct { - grpc_exec_ctx *exec_ctx; - grpc_error *error; - grpc_chttp2_transport *t; + grpc_exec_ctx* exec_ctx; + grpc_error* error; + grpc_chttp2_transport* t; } cancel_stream_cb_args; -static void cancel_stream_cb(void *user_data, uint32_t key, void *stream) { - cancel_stream_cb_args *args = (cancel_stream_cb_args *)user_data; - grpc_chttp2_stream *s = (grpc_chttp2_stream *)stream; +static void cancel_stream_cb(void* user_data, uint32_t key, void* stream) { + cancel_stream_cb_args* args = (cancel_stream_cb_args*)user_data; + grpc_chttp2_stream* s = (grpc_chttp2_stream*)stream; grpc_chttp2_cancel_stream(args->exec_ctx, args->t, s, GRPC_ERROR_REF(args->error)); } -static void end_all_the_calls(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_error *error) { +static void end_all_the_calls(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_error* error) { cancel_stream_cb_args args = {exec_ctx, error, t}; grpc_chttp2_stream_map_for_each(&t->stream_map, cancel_stream_cb, &args); GRPC_ERROR_UNREF(error); @@ -2411,7 +2422,7 @@ static void end_all_the_calls(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, */ template -static void WithUrgency(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, +static void WithUrgency(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, grpc_core::chttp2::FlowControlAction::Urgency urgency, grpc_chttp2_initiate_write_reason reason, F action) { switch (urgency) { @@ -2427,8 +2438,8 @@ static void WithUrgency(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, } void grpc_chttp2_act_on_flowctl_action( - grpc_exec_ctx *exec_ctx, const grpc_core::chttp2::FlowControlAction &action, - grpc_chttp2_transport *t, grpc_chttp2_stream *s) { + grpc_exec_ctx* exec_ctx, const grpc_core::chttp2::FlowControlAction& action, + grpc_chttp2_transport* t, grpc_chttp2_stream* s) { WithUrgency( exec_ctx, t, action.send_stream_update(), GRPC_CHTTP2_INITIATE_WRITE_STREAM_FLOW_CONTROL, @@ -2450,20 +2461,20 @@ void grpc_chttp2_act_on_flowctl_action( }); } -static grpc_error *try_http_parsing(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { +static grpc_error* try_http_parsing(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { grpc_http_parser parser; size_t i = 0; - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; grpc_http_response response; memset(&response, 0, sizeof(response)); grpc_http_parser_init(&parser, GRPC_HTTP_RESPONSE, &response); - grpc_error *parse_error = GRPC_ERROR_NONE; + grpc_error* parse_error = GRPC_ERROR_NONE; for (; i < t->read_buffer.count && parse_error == GRPC_ERROR_NONE; i++) { parse_error = - grpc_http_parser_parse(&parser, t->read_buffer.slices[i], NULL); + grpc_http_parser_parse(&parser, t->read_buffer.slices[i], nullptr); } if (parse_error == GRPC_ERROR_NONE && (parse_error = grpc_http_parser_eof(&parser)) == GRPC_ERROR_NONE) { @@ -2480,27 +2491,27 @@ static grpc_error *try_http_parsing(grpc_exec_ctx *exec_ctx, return error; } -static void read_action_locked(grpc_exec_ctx *exec_ctx, void *tp, - grpc_error *error) { +static void read_action_locked(grpc_exec_ctx* exec_ctx, void* tp, + grpc_error* error) { GPR_TIMER_BEGIN("reading_action_locked", 0); - grpc_chttp2_transport *t = (grpc_chttp2_transport *)tp; + grpc_chttp2_transport* t = (grpc_chttp2_transport*)tp; GRPC_ERROR_REF(error); - grpc_error *err = error; + grpc_error* err = error; if (err != GRPC_ERROR_NONE) { err = grpc_error_set_int(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Endpoint read failed", &err, 1), GRPC_ERROR_INT_OCCURRED_DURING_WRITE, t->write_state); } - GPR_SWAP(grpc_error *, err, error); + GPR_SWAP(grpc_error*, err, error); GRPC_ERROR_UNREF(err); if (t->closed_with_error == GRPC_ERROR_NONE) { GPR_TIMER_BEGIN("reading_action.parse", 0); size_t i = 0; - grpc_error *errors[3] = {GRPC_ERROR_REF(error), GRPC_ERROR_NONE, + grpc_error* errors[3] = {GRPC_ERROR_REF(error), GRPC_ERROR_NONE, GRPC_ERROR_NONE}; for (; i < t->read_buffer.count && errors[1] == GRPC_ERROR_NONE; i++) { t->flow_control->bdp_estimator()->AddIncomingBytes( @@ -2522,7 +2533,7 @@ static void read_action_locked(grpc_exec_ctx *exec_ctx, void *tp, GPR_TIMER_BEGIN("post_parse_locked", 0); if (t->initial_window_update != 0) { if (t->initial_window_update > 0) { - grpc_chttp2_stream *s; + grpc_chttp2_stream* s; while (grpc_chttp2_list_pop_stalled_by_stream(t, &s)) { grpc_chttp2_mark_stream_writable(exec_ctx, t, s); grpc_chttp2_initiate_write( @@ -2542,6 +2553,12 @@ static void read_action_locked(grpc_exec_ctx *exec_ctx, void *tp, "Transport closed", &t->closed_with_error, 1); } if (error != GRPC_ERROR_NONE) { + /* If a goaway frame was received, this might be the reason why the read + * failed. Add this info to the error */ + if (t->goaway_error != GRPC_ERROR_NONE) { + error = grpc_error_add_child(error, GRPC_ERROR_REF(t->goaway_error)); + } + close_transport_locked(exec_ctx, t, GRPC_ERROR_REF(error)); t->endpoint_reading = 0; } else if (t->closed_with_error == GRPC_ERROR_NONE) { @@ -2554,7 +2571,7 @@ static void read_action_locked(grpc_exec_ctx *exec_ctx, void *tp, grpc_endpoint_read(exec_ctx, t->ep, &t->read_buffer, &t->read_action_locked); grpc_chttp2_act_on_flowctl_action(exec_ctx, t->flow_control->MakeAction(), - t, NULL); + t, nullptr); GRPC_CHTTP2_UNREF_TRANSPORT(exec_ctx, t, "keep_reading"); } else { GRPC_CHTTP2_UNREF_TRANSPORT(exec_ctx, t, "reading_action"); @@ -2569,17 +2586,17 @@ static void read_action_locked(grpc_exec_ctx *exec_ctx, void *tp, // t is reffed prior to calling the first time, and once the callback chain // that kicks off finishes, it's unreffed -static void schedule_bdp_ping_locked(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { +static void schedule_bdp_ping_locked(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { t->flow_control->bdp_estimator()->SchedulePing(); send_ping_locked(exec_ctx, t, &t->start_bdp_ping_locked, &t->finish_bdp_ping_locked); } -static void start_bdp_ping_locked(grpc_exec_ctx *exec_ctx, void *tp, - grpc_error *error) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)tp; - if (GRPC_TRACER_ON(grpc_http_trace)) { +static void start_bdp_ping_locked(grpc_exec_ctx* exec_ctx, void* tp, + grpc_error* error) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)tp; + if (grpc_http_trace.enabled()) { gpr_log(GPR_DEBUG, "%s: Start BDP ping err=%s", t->peer_string, grpc_error_string(error)); } @@ -2590,10 +2607,10 @@ static void start_bdp_ping_locked(grpc_exec_ctx *exec_ctx, void *tp, t->flow_control->bdp_estimator()->StartPing(); } -static void finish_bdp_ping_locked(grpc_exec_ctx *exec_ctx, void *tp, - grpc_error *error) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)tp; - if (GRPC_TRACER_ON(grpc_http_trace)) { +static void finish_bdp_ping_locked(grpc_exec_ctx* exec_ctx, void* tp, + grpc_error* error) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)tp; + if (grpc_http_trace.enabled()) { gpr_log(GPR_DEBUG, "%s: Complete BDP ping err=%s", t->peer_string, grpc_error_string(error)); } @@ -2611,9 +2628,9 @@ static void finish_bdp_ping_locked(grpc_exec_ctx *exec_ctx, void *tp, &t->next_bdp_ping_timer_expired_locked); } -static void next_bdp_ping_timer_expired_locked(grpc_exec_ctx *exec_ctx, - void *tp, grpc_error *error) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)tp; +static void next_bdp_ping_timer_expired_locked(grpc_exec_ctx* exec_ctx, + void* tp, grpc_error* error) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)tp; GPR_ASSERT(t->have_next_bdp_ping_timer); t->have_next_bdp_ping_timer = false; if (error != GRPC_ERROR_NONE) { @@ -2623,7 +2640,7 @@ static void next_bdp_ping_timer_expired_locked(grpc_exec_ctx *exec_ctx, schedule_bdp_ping_locked(exec_ctx, t); } -void grpc_chttp2_config_default_keepalive_args(grpc_channel_args *args, +void grpc_chttp2_config_default_keepalive_args(grpc_channel_args* args, bool is_client) { size_t i; if (args) { @@ -2681,9 +2698,9 @@ void grpc_chttp2_config_default_keepalive_args(grpc_channel_args *args, } } -static void init_keepalive_ping_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)arg; +static void init_keepalive_ping_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)arg; GPR_ASSERT(t->keepalive_state == GRPC_CHTTP2_KEEPALIVE_STATE_WAITING); if (t->destroying || t->closed_with_error != GRPC_ERROR_NONE) { t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_DYING; @@ -2712,18 +2729,18 @@ static void init_keepalive_ping_locked(grpc_exec_ctx *exec_ctx, void *arg, GRPC_CHTTP2_UNREF_TRANSPORT(exec_ctx, t, "init keepalive ping"); } -static void start_keepalive_ping_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)arg; +static void start_keepalive_ping_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)arg; GRPC_CHTTP2_REF_TRANSPORT(t, "keepalive watchdog"); grpc_timer_init(exec_ctx, &t->keepalive_watchdog_timer, grpc_exec_ctx_now(exec_ctx) + t->keepalive_time, &t->keepalive_watchdog_fired_locked); } -static void finish_keepalive_ping_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)arg; +static void finish_keepalive_ping_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)arg; if (t->keepalive_state == GRPC_CHTTP2_KEEPALIVE_STATE_PINGING) { if (error == GRPC_ERROR_NONE) { t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_WAITING; @@ -2737,9 +2754,9 @@ static void finish_keepalive_ping_locked(grpc_exec_ctx *exec_ctx, void *arg, GRPC_CHTTP2_UNREF_TRANSPORT(exec_ctx, t, "keepalive ping end"); } -static void keepalive_watchdog_fired_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)arg; +static void keepalive_watchdog_fired_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)arg; if (t->keepalive_state == GRPC_CHTTP2_KEEPALIVE_STATE_PINGING) { if (error == GRPC_ERROR_NONE) { t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_DYING; @@ -2764,10 +2781,10 @@ static void keepalive_watchdog_fired_locked(grpc_exec_ctx *exec_ctx, void *arg, * CALLBACK LOOP */ -static void connectivity_state_set(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, +static void connectivity_state_set(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, grpc_connectivity_state state, - grpc_error *error, const char *reason) { + grpc_error* error, const char* reason) { GRPC_CHTTP2_IF_TRACING( gpr_log(GPR_DEBUG, "set connectivity_state=%d", state)); grpc_connectivity_state_set(exec_ctx, &t->channel_callback.state_tracker, @@ -2778,15 +2795,15 @@ static void connectivity_state_set(grpc_exec_ctx *exec_ctx, * POLLSET STUFF */ -static void set_pollset(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_stream *gs, grpc_pollset *pollset) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)gt; +static void set_pollset(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_stream* gs, grpc_pollset* pollset) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)gt; grpc_endpoint_add_to_pollset(exec_ctx, t->ep, pollset); } -static void set_pollset_set(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_stream *gs, grpc_pollset_set *pollset_set) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)gt; +static void set_pollset_set(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_stream* gs, grpc_pollset_set* pollset_set) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)gt; grpc_endpoint_add_to_pollset_set(exec_ctx, t->ep, pollset_set); } @@ -2794,9 +2811,9 @@ static void set_pollset_set(grpc_exec_ctx *exec_ctx, grpc_transport *gt, * BYTE STREAM */ -static void reset_byte_stream(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_chttp2_stream *s = (grpc_chttp2_stream *)arg; +static void reset_byte_stream(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_chttp2_stream* s = (grpc_chttp2_stream*)arg; s->pending_byte_stream = false; if (error == GRPC_ERROR_NONE) { @@ -2805,7 +2822,7 @@ static void reset_byte_stream(grpc_exec_ctx *exec_ctx, void *arg, } else { GPR_ASSERT(error != GRPC_ERROR_NONE); GRPC_CLOSURE_SCHED(exec_ctx, s->on_next, GRPC_ERROR_REF(error)); - s->on_next = NULL; + s->on_next = nullptr; GRPC_ERROR_UNREF(s->byte_stream_error); s->byte_stream_error = GRPC_ERROR_NONE; grpc_chttp2_cancel_stream(exec_ctx, s->t, s, GRPC_ERROR_REF(error)); @@ -2813,20 +2830,20 @@ static void reset_byte_stream(grpc_exec_ctx *exec_ctx, void *arg, } } -static void incoming_byte_stream_unref(grpc_exec_ctx *exec_ctx, - grpc_chttp2_incoming_byte_stream *bs) { +static void incoming_byte_stream_unref(grpc_exec_ctx* exec_ctx, + grpc_chttp2_incoming_byte_stream* bs) { if (gpr_unref(&bs->refs)) { gpr_free(bs); } } -static void incoming_byte_stream_next_locked(grpc_exec_ctx *exec_ctx, - void *argp, - grpc_error *error_ignored) { - grpc_chttp2_incoming_byte_stream *bs = - (grpc_chttp2_incoming_byte_stream *)argp; - grpc_chttp2_transport *t = bs->transport; - grpc_chttp2_stream *s = bs->stream; +static void incoming_byte_stream_next_locked(grpc_exec_ctx* exec_ctx, + void* argp, + grpc_error* error_ignored) { + grpc_chttp2_incoming_byte_stream* bs = + (grpc_chttp2_incoming_byte_stream*)argp; + grpc_chttp2_transport* t = bs->transport; + grpc_chttp2_stream* s = bs->stream; size_t cur_length = s->frame_storage.length; if (!s->read_closed) { @@ -2844,9 +2861,9 @@ static void incoming_byte_stream_next_locked(grpc_exec_ctx *exec_ctx, } else if (s->byte_stream_error != GRPC_ERROR_NONE) { GRPC_CLOSURE_SCHED(exec_ctx, bs->next_action.on_complete, GRPC_ERROR_REF(s->byte_stream_error)); - if (s->data_parser.parsing_frame != NULL) { + if (s->data_parser.parsing_frame != nullptr) { incoming_byte_stream_unref(exec_ctx, s->data_parser.parsing_frame); - s->data_parser.parsing_frame = NULL; + s->data_parser.parsing_frame = nullptr; } } else if (s->read_closed) { if (bs->remaining_bytes != 0) { @@ -2854,9 +2871,9 @@ static void incoming_byte_stream_next_locked(grpc_exec_ctx *exec_ctx, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Truncated message"); GRPC_CLOSURE_SCHED(exec_ctx, bs->next_action.on_complete, GRPC_ERROR_REF(s->byte_stream_error)); - if (s->data_parser.parsing_frame != NULL) { + if (s->data_parser.parsing_frame != nullptr) { incoming_byte_stream_unref(exec_ctx, s->data_parser.parsing_frame); - s->data_parser.parsing_frame = NULL; + s->data_parser.parsing_frame = nullptr; } } else { /* Should never reach here. */ @@ -2868,14 +2885,14 @@ static void incoming_byte_stream_next_locked(grpc_exec_ctx *exec_ctx, incoming_byte_stream_unref(exec_ctx, bs); } -static bool incoming_byte_stream_next(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream, +static bool incoming_byte_stream_next(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream, size_t max_size_hint, - grpc_closure *on_complete) { + grpc_closure* on_complete) { GPR_TIMER_BEGIN("incoming_byte_stream_next", 0); - grpc_chttp2_incoming_byte_stream *bs = - (grpc_chttp2_incoming_byte_stream *)byte_stream; - grpc_chttp2_stream *s = bs->stream; + grpc_chttp2_incoming_byte_stream* bs = + (grpc_chttp2_incoming_byte_stream*)byte_stream; + grpc_chttp2_stream* s = bs->stream; if (s->unprocessed_incoming_frames_buffer.length > 0) { GPR_TIMER_END("incoming_byte_stream_next", 0); return true; @@ -2894,14 +2911,14 @@ static bool incoming_byte_stream_next(grpc_exec_ctx *exec_ctx, } } -static grpc_error *incoming_byte_stream_pull(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream, - grpc_slice *slice) { +static grpc_error* incoming_byte_stream_pull(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream, + grpc_slice* slice) { GPR_TIMER_BEGIN("incoming_byte_stream_pull", 0); - grpc_chttp2_incoming_byte_stream *bs = - (grpc_chttp2_incoming_byte_stream *)byte_stream; - grpc_chttp2_stream *s = bs->stream; - grpc_error *error; + grpc_chttp2_incoming_byte_stream* bs = + (grpc_chttp2_incoming_byte_stream*)byte_stream; + grpc_chttp2_stream* s = bs->stream; + grpc_error* error; if (s->unprocessed_incoming_frames_buffer.length > 0) { if (!s->unprocessed_incoming_frames_decompressed) { @@ -2912,7 +2929,7 @@ static grpc_error *incoming_byte_stream_pull(grpc_exec_ctx *exec_ctx, } if (!grpc_stream_decompress(s->stream_decompression_ctx, &s->unprocessed_incoming_frames_buffer, - &s->decompressed_data_buffer, NULL, + &s->decompressed_data_buffer, nullptr, MAX_SIZE_T, &end_of_context)) { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Stream decompression error."); @@ -2924,7 +2941,7 @@ static grpc_error *incoming_byte_stream_pull(grpc_exec_ctx *exec_ctx, s->unprocessed_incoming_frames_decompressed = true; if (end_of_context) { grpc_stream_compression_context_destroy(s->stream_decompression_ctx); - s->stream_decompression_ctx = NULL; + s->stream_decompression_ctx = nullptr; } if (s->unprocessed_incoming_frames_buffer.length == 0) { *slice = grpc_empty_slice(); @@ -2932,7 +2949,7 @@ static grpc_error *incoming_byte_stream_pull(grpc_exec_ctx *exec_ctx, } error = grpc_deframe_unprocessed_incoming_frames( exec_ctx, &s->data_parser, s, &s->unprocessed_incoming_frames_buffer, - slice, NULL); + slice, nullptr); if (error != GRPC_ERROR_NONE) { return error; } @@ -2945,44 +2962,45 @@ static grpc_error *incoming_byte_stream_pull(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static void incoming_byte_stream_destroy_locked(grpc_exec_ctx *exec_ctx, - void *byte_stream, - grpc_error *error_ignored); +static void incoming_byte_stream_destroy_locked(grpc_exec_ctx* exec_ctx, + void* byte_stream, + grpc_error* error_ignored); -static void incoming_byte_stream_destroy(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream) { +static void incoming_byte_stream_destroy(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream) { GPR_TIMER_BEGIN("incoming_byte_stream_destroy", 0); - grpc_chttp2_incoming_byte_stream *bs = - (grpc_chttp2_incoming_byte_stream *)byte_stream; + grpc_chttp2_incoming_byte_stream* bs = + (grpc_chttp2_incoming_byte_stream*)byte_stream; GRPC_CLOSURE_SCHED( - exec_ctx, GRPC_CLOSURE_INIT( - &bs->destroy_action, incoming_byte_stream_destroy_locked, - bs, grpc_combiner_scheduler(bs->transport->combiner)), + exec_ctx, + GRPC_CLOSURE_INIT(&bs->destroy_action, + incoming_byte_stream_destroy_locked, bs, + grpc_combiner_scheduler(bs->transport->combiner)), GRPC_ERROR_NONE); GPR_TIMER_END("incoming_byte_stream_destroy", 0); } static void incoming_byte_stream_publish_error( - grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_byte_stream *bs, - grpc_error *error) { - grpc_chttp2_stream *s = bs->stream; + grpc_exec_ctx* exec_ctx, grpc_chttp2_incoming_byte_stream* bs, + grpc_error* error) { + grpc_chttp2_stream* s = bs->stream; GPR_ASSERT(error != GRPC_ERROR_NONE); GRPC_CLOSURE_SCHED(exec_ctx, s->on_next, GRPC_ERROR_REF(error)); - s->on_next = NULL; + s->on_next = nullptr; GRPC_ERROR_UNREF(s->byte_stream_error); s->byte_stream_error = GRPC_ERROR_REF(error); grpc_chttp2_cancel_stream(exec_ctx, bs->transport, bs->stream, GRPC_ERROR_REF(error)); } -grpc_error *grpc_chttp2_incoming_byte_stream_push( - grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_byte_stream *bs, - grpc_slice slice, grpc_slice *slice_out) { - grpc_chttp2_stream *s = bs->stream; +grpc_error* grpc_chttp2_incoming_byte_stream_push( + grpc_exec_ctx* exec_ctx, grpc_chttp2_incoming_byte_stream* bs, + grpc_slice slice, grpc_slice* slice_out) { + grpc_chttp2_stream* s = bs->stream; if (bs->remaining_bytes < GRPC_SLICE_LENGTH(slice)) { - grpc_error *error = + grpc_error* error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Too many bytes in stream"); GRPC_CLOSURE_SCHED(exec_ctx, &s->reset_byte_stream, GRPC_ERROR_REF(error)); @@ -2990,17 +3008,17 @@ grpc_error *grpc_chttp2_incoming_byte_stream_push( return error; } else { bs->remaining_bytes -= (uint32_t)GRPC_SLICE_LENGTH(slice); - if (slice_out != NULL) { + if (slice_out != nullptr) { *slice_out = slice; } return GRPC_ERROR_NONE; } } -grpc_error *grpc_chttp2_incoming_byte_stream_finished( - grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_byte_stream *bs, - grpc_error *error, bool reset_on_error) { - grpc_chttp2_stream *s = bs->stream; +grpc_error* grpc_chttp2_incoming_byte_stream_finished( + grpc_exec_ctx* exec_ctx, grpc_chttp2_incoming_byte_stream* bs, + grpc_error* error, bool reset_on_error) { + grpc_chttp2_stream* s = bs->stream; if (error == GRPC_ERROR_NONE) { if (bs->remaining_bytes != 0) { @@ -3014,11 +3032,11 @@ grpc_error *grpc_chttp2_incoming_byte_stream_finished( return error; } -static void incoming_byte_stream_shutdown(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream, - grpc_error *error) { - grpc_chttp2_incoming_byte_stream *bs = - (grpc_chttp2_incoming_byte_stream *)byte_stream; +static void incoming_byte_stream_shutdown(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream, + grpc_error* error) { + grpc_chttp2_incoming_byte_stream* bs = + (grpc_chttp2_incoming_byte_stream*)byte_stream; GRPC_ERROR_UNREF(grpc_chttp2_incoming_byte_stream_finished( exec_ctx, bs, error, true /* reset_on_error */)); } @@ -3027,13 +3045,13 @@ static const grpc_byte_stream_vtable grpc_chttp2_incoming_byte_stream_vtable = { incoming_byte_stream_next, incoming_byte_stream_pull, incoming_byte_stream_shutdown, incoming_byte_stream_destroy}; -static void incoming_byte_stream_destroy_locked(grpc_exec_ctx *exec_ctx, - void *byte_stream, - grpc_error *error_ignored) { - grpc_chttp2_incoming_byte_stream *bs = - (grpc_chttp2_incoming_byte_stream *)byte_stream; - grpc_chttp2_stream *s = bs->stream; - grpc_chttp2_transport *t = s->t; +static void incoming_byte_stream_destroy_locked(grpc_exec_ctx* exec_ctx, + void* byte_stream, + grpc_error* error_ignored) { + grpc_chttp2_incoming_byte_stream* bs = + (grpc_chttp2_incoming_byte_stream*)byte_stream; + grpc_chttp2_stream* s = bs->stream; + grpc_chttp2_transport* t = s->t; GPR_ASSERT(bs->base.vtable == &grpc_chttp2_incoming_byte_stream_vtable); incoming_byte_stream_unref(exec_ctx, bs); @@ -3042,11 +3060,11 @@ static void incoming_byte_stream_destroy_locked(grpc_exec_ctx *exec_ctx, grpc_chttp2_maybe_complete_recv_trailing_metadata(exec_ctx, t, s); } -grpc_chttp2_incoming_byte_stream *grpc_chttp2_incoming_byte_stream_create( - grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, grpc_chttp2_stream *s, +grpc_chttp2_incoming_byte_stream* grpc_chttp2_incoming_byte_stream_create( + grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, grpc_chttp2_stream* s, uint32_t frame_size, uint32_t flags) { - grpc_chttp2_incoming_byte_stream *incoming_byte_stream = - (grpc_chttp2_incoming_byte_stream *)gpr_malloc( + grpc_chttp2_incoming_byte_stream* incoming_byte_stream = + (grpc_chttp2_incoming_byte_stream*)gpr_malloc( sizeof(*incoming_byte_stream)); incoming_byte_stream->base.length = frame_size; incoming_byte_stream->remaining_bytes = frame_size; @@ -3064,8 +3082,8 @@ grpc_chttp2_incoming_byte_stream *grpc_chttp2_incoming_byte_stream_create( * RESOURCE QUOTAS */ -static void post_benign_reclaimer(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { +static void post_benign_reclaimer(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { if (!t->benign_reclaimer_registered) { t->benign_reclaimer_registered = true; GRPC_CHTTP2_REF_TRANSPORT(t, "benign_reclaimer"); @@ -3075,8 +3093,8 @@ static void post_benign_reclaimer(grpc_exec_ctx *exec_ctx, } } -static void post_destructive_reclaimer(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { +static void post_destructive_reclaimer(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { if (!t->destructive_reclaimer_registered) { t->destructive_reclaimer_registered = true; GRPC_CHTTP2_REF_TRANSPORT(t, "destructive_reclaimer"); @@ -3086,14 +3104,14 @@ static void post_destructive_reclaimer(grpc_exec_ctx *exec_ctx, } } -static void benign_reclaimer_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)arg; +static void benign_reclaimer_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)arg; if (error == GRPC_ERROR_NONE && grpc_chttp2_stream_map_size(&t->stream_map) == 0) { /* Channel with no active streams: send a goaway to try and make it * disconnect cleanly */ - if (GRPC_TRACER_ON(grpc_resource_quota_trace)) { + if (grpc_resource_quota_trace.enabled()) { gpr_log(GPR_DEBUG, "HTTP2: %s - send goaway to free memory", t->peer_string); } @@ -3101,8 +3119,7 @@ static void benign_reclaimer_locked(grpc_exec_ctx *exec_ctx, void *arg, grpc_error_set_int( GRPC_ERROR_CREATE_FROM_STATIC_STRING("Buffers full"), GRPC_ERROR_INT_HTTP2_ERROR, GRPC_HTTP2_ENHANCE_YOUR_CALM)); - } else if (error == GRPC_ERROR_NONE && - GRPC_TRACER_ON(grpc_resource_quota_trace)) { + } else if (error == GRPC_ERROR_NONE && grpc_resource_quota_trace.enabled()) { gpr_log(GPR_DEBUG, "HTTP2: %s - skip benign reclamation, there are still %" PRIdPTR " streams", @@ -3116,15 +3133,15 @@ static void benign_reclaimer_locked(grpc_exec_ctx *exec_ctx, void *arg, GRPC_CHTTP2_UNREF_TRANSPORT(exec_ctx, t, "benign_reclaimer"); } -static void destructive_reclaimer_locked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)arg; +static void destructive_reclaimer_locked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)arg; size_t n = grpc_chttp2_stream_map_size(&t->stream_map); t->destructive_reclaimer_registered = false; if (error == GRPC_ERROR_NONE && n > 0) { - grpc_chttp2_stream *s = - (grpc_chttp2_stream *)grpc_chttp2_stream_map_rand(&t->stream_map); - if (GRPC_TRACER_ON(grpc_resource_quota_trace)) { + grpc_chttp2_stream* s = + (grpc_chttp2_stream*)grpc_chttp2_stream_map_rand(&t->stream_map); + if (grpc_resource_quota_trace.enabled()) { gpr_log(GPR_DEBUG, "HTTP2: %s - abandon stream id %d", t->peer_string, s->id); } @@ -3152,7 +3169,7 @@ static void destructive_reclaimer_locked(grpc_exec_ctx *exec_ctx, void *arg, * MONITORING */ -const char *grpc_chttp2_initiate_write_reason_string( +const char* grpc_chttp2_initiate_write_reason_string( grpc_chttp2_initiate_write_reason reason) { switch (reason) { case GRPC_CHTTP2_INITIATE_WRITE_INITIAL_WRITE: @@ -3199,9 +3216,9 @@ const char *grpc_chttp2_initiate_write_reason_string( GPR_UNREACHABLE_CODE(return "unknown"); } -static grpc_endpoint *chttp2_get_endpoint(grpc_exec_ctx *exec_ctx, - grpc_transport *t) { - return ((grpc_chttp2_transport *)t)->ep; +static grpc_endpoint* chttp2_get_endpoint(grpc_exec_ctx* exec_ctx, + grpc_transport* t) { + return ((grpc_chttp2_transport*)t)->ep; } static const grpc_transport_vtable vtable = {sizeof(grpc_chttp2_stream), @@ -3215,26 +3232,27 @@ static const grpc_transport_vtable vtable = {sizeof(grpc_chttp2_stream), destroy_transport, chttp2_get_endpoint}; -static const grpc_transport_vtable *get_vtable(void) { return &vtable; } +static const grpc_transport_vtable* get_vtable(void) { return &vtable; } -grpc_transport *grpc_create_chttp2_transport( - grpc_exec_ctx *exec_ctx, const grpc_channel_args *channel_args, - grpc_endpoint *ep, int is_client) { - grpc_chttp2_transport *t = - (grpc_chttp2_transport *)gpr_zalloc(sizeof(grpc_chttp2_transport)); - init_transport(exec_ctx, t, channel_args, ep, is_client != 0); +grpc_transport* grpc_create_chttp2_transport( + grpc_exec_ctx* exec_ctx, const grpc_channel_args* channel_args, + grpc_endpoint* ep, bool is_client) { + grpc_chttp2_transport* t = + (grpc_chttp2_transport*)gpr_zalloc(sizeof(grpc_chttp2_transport)); + init_transport(exec_ctx, t, channel_args, ep, is_client); return &t->base; } -void grpc_chttp2_transport_start_reading(grpc_exec_ctx *exec_ctx, - grpc_transport *transport, - grpc_slice_buffer *read_buffer) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)transport; +void grpc_chttp2_transport_start_reading( + grpc_exec_ctx* exec_ctx, grpc_transport* transport, + grpc_slice_buffer* read_buffer, grpc_closure* notify_on_receive_settings) { + grpc_chttp2_transport* t = (grpc_chttp2_transport*)transport; GRPC_CHTTP2_REF_TRANSPORT( t, "reading_action"); /* matches unref inside reading_action */ - if (read_buffer != NULL) { + if (read_buffer != nullptr) { grpc_slice_buffer_move_into(read_buffer, &t->read_buffer); gpr_free(read_buffer); } + t->notify_on_receive_settings = notify_on_receive_settings; GRPC_CLOSURE_SCHED(exec_ctx, &t->read_action_locked, GRPC_ERROR_NONE); } diff --git a/src/core/ext/transport/chttp2/transport/chttp2_transport.h b/src/core/ext/transport/chttp2/transport/chttp2_transport.h index 321fca4c825..bd72e07babe 100644 --- a/src/core/ext/transport/chttp2/transport/chttp2_transport.h +++ b/src/core/ext/transport/chttp2/transport/chttp2_transport.h @@ -23,30 +23,20 @@ #include "src/core/lib/iomgr/endpoint.h" #include "src/core/lib/transport/transport.h" -#ifdef __cplusplus -extern "C" { -#endif +extern grpc_core::TraceFlag grpc_http_trace; +extern grpc_core::TraceFlag grpc_trace_http2_stream_state; +extern grpc_core::DebugOnlyTraceFlag grpc_trace_chttp2_refcount; -extern grpc_tracer_flag grpc_http_trace; -extern grpc_tracer_flag grpc_flowctl_trace; -extern grpc_tracer_flag grpc_trace_http2_stream_state; - -#ifndef NDEBUG -extern grpc_tracer_flag grpc_trace_chttp2_refcount; -#endif - -grpc_transport *grpc_create_chttp2_transport( - grpc_exec_ctx *exec_ctx, const grpc_channel_args *channel_args, - grpc_endpoint *ep, int is_client); +grpc_transport* grpc_create_chttp2_transport( + grpc_exec_ctx* exec_ctx, const grpc_channel_args* channel_args, + grpc_endpoint* ep, bool is_client); /// Takes ownership of \a read_buffer, which (if non-NULL) contains /// leftover bytes previously read from the endpoint (e.g., by handshakers). -void grpc_chttp2_transport_start_reading(grpc_exec_ctx *exec_ctx, - grpc_transport *transport, - grpc_slice_buffer *read_buffer); - -#ifdef __cplusplus -} -#endif +/// If non-null, \a notify_on_receive_settings will be scheduled when +/// HTTP/2 settings are received from the peer. +void grpc_chttp2_transport_start_reading( + grpc_exec_ctx* exec_ctx, grpc_transport* transport, + grpc_slice_buffer* read_buffer, grpc_closure* notify_on_receive_settings); #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_CHTTP2_TRANSPORT_H */ diff --git a/src/core/ext/transport/chttp2/transport/flow_control.cc b/src/core/ext/transport/chttp2/transport/flow_control.cc index 40545bc74b4..8a057bd9ff4 100644 --- a/src/core/ext/transport/chttp2/transport/flow_control.cc +++ b/src/core/ext/transport/chttp2/transport/flow_control.cc @@ -31,6 +31,8 @@ #include "src/core/ext/transport/chttp2/transport/internal.h" #include "src/core/lib/support/string.h" +grpc_core::TraceFlag grpc_flowctl_trace(false, "flowctl"); + namespace grpc_core { namespace chttp2 { @@ -224,9 +226,9 @@ grpc_error* StreamFlowControl::RecvData(int64_t incoming_frame_size) { incoming_frame_size, acked_stream_window, sent_stream_window); } else { char* msg; - gpr_asprintf(&msg, "frame of size %" PRId64 - " overflows local window of %" PRId64, - incoming_frame_size, acked_stream_window); + gpr_asprintf( + &msg, "frame of size %" PRId64 " overflows local window of %" PRId64, + incoming_frame_size, acked_stream_window); grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return err; @@ -312,7 +314,9 @@ double TransportFlowControl::SmoothLogBdp(grpc_exec_ctx* exec_ctx, double bdp_error = value - pid_controller_.last_control_value(); const double dt = (double)(now - last_pid_update_) * 1e-3; last_pid_update_ = now; - return pid_controller_.Update(bdp_error, dt); + // Limit dt to 100ms + const double kMaxDt = 0.1; + return pid_controller_.Update(bdp_error, dt > kMaxDt ? kMaxDt : dt); } FlowControlAction::Urgency TransportFlowControl::DeltaUrgency( diff --git a/src/core/ext/transport/chttp2/transport/flow_control.h b/src/core/ext/transport/chttp2/transport/flow_control.h index 7dd348ed5f1..2515c94309a 100644 --- a/src/core/ext/transport/chttp2/transport/flow_control.h +++ b/src/core/ext/transport/chttp2/transport/flow_control.h @@ -19,6 +19,7 @@ #ifndef GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FLOW_CONTROL_H #define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FLOW_CONTROL_H +#include #include #include @@ -30,7 +31,7 @@ struct grpc_chttp2_transport; struct grpc_chttp2_stream; -extern "C" grpc_tracer_flag grpc_flowctl_trace; +extern grpc_core::TraceFlag grpc_flowctl_trace; namespace grpc { namespace testing { @@ -118,7 +119,7 @@ class FlowControlTrace { StreamFlowControl* sfc); void Finish(); - const bool enabled_ = GRPC_TRACER_ON(grpc_flowctl_trace); + const bool enabled_ = grpc_flowctl_trace.enabled(); TransportFlowControl* tfc_; StreamFlowControl* sfc_; diff --git a/src/core/ext/transport/chttp2/transport/frame.h b/src/core/ext/transport/chttp2/transport/frame.h index e7debdad79a..dba4c004eca 100644 --- a/src/core/ext/transport/chttp2/transport/frame.h +++ b/src/core/ext/transport/chttp2/transport/frame.h @@ -24,10 +24,6 @@ #include "src/core/lib/iomgr/error.h" -#ifdef __cplusplus -extern "C" { -#endif - /* defined in internal.h */ typedef struct grpc_chttp2_stream grpc_chttp2_stream; typedef struct grpc_chttp2_transport grpc_chttp2_transport; @@ -47,8 +43,4 @@ typedef struct grpc_chttp2_transport grpc_chttp2_transport; #define GRPC_CHTTP2_DATA_FLAG_PADDED 8 #define GRPC_CHTTP2_FLAG_HAS_PRIORITY 0x20 -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_H */ diff --git a/src/core/ext/transport/chttp2/transport/frame_data.cc b/src/core/ext/transport/chttp2/transport/frame_data.cc index 73aaab18025..f0c3b557922 100644 --- a/src/core/ext/transport/chttp2/transport/frame_data.cc +++ b/src/core/ext/transport/chttp2/transport/frame_data.cc @@ -30,15 +30,15 @@ #include "src/core/lib/support/string.h" #include "src/core/lib/transport/transport.h" -grpc_error *grpc_chttp2_data_parser_init(grpc_chttp2_data_parser *parser) { +grpc_error* grpc_chttp2_data_parser_init(grpc_chttp2_data_parser* parser) { parser->state = GRPC_CHTTP2_DATA_FH_0; - parser->parsing_frame = NULL; + parser->parsing_frame = nullptr; return GRPC_ERROR_NONE; } -void grpc_chttp2_data_parser_destroy(grpc_exec_ctx *exec_ctx, - grpc_chttp2_data_parser *parser) { - if (parser->parsing_frame != NULL) { +void grpc_chttp2_data_parser_destroy(grpc_exec_ctx* exec_ctx, + grpc_chttp2_data_parser* parser) { + if (parser->parsing_frame != nullptr) { GRPC_ERROR_UNREF(grpc_chttp2_incoming_byte_stream_finished( exec_ctx, parser->parsing_frame, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Parser destroyed"), false)); @@ -46,14 +46,14 @@ void grpc_chttp2_data_parser_destroy(grpc_exec_ctx *exec_ctx, GRPC_ERROR_UNREF(parser->error); } -grpc_error *grpc_chttp2_data_parser_begin_frame(grpc_chttp2_data_parser *parser, +grpc_error* grpc_chttp2_data_parser_begin_frame(grpc_chttp2_data_parser* parser, uint8_t flags, uint32_t stream_id, - grpc_chttp2_stream *s) { + grpc_chttp2_stream* s) { if (flags & ~GRPC_CHTTP2_DATA_FLAG_END_STREAM) { - char *msg; + char* msg; gpr_asprintf(&msg, "unsupported data flags: 0x%02x", flags); - grpc_error *err = + grpc_error* err = grpc_error_set_int(GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg), GRPC_ERROR_INT_STREAM_ID, (intptr_t)stream_id); gpr_free(msg); @@ -69,12 +69,12 @@ grpc_error *grpc_chttp2_data_parser_begin_frame(grpc_chttp2_data_parser *parser, return GRPC_ERROR_NONE; } -void grpc_chttp2_encode_data(uint32_t id, grpc_slice_buffer *inbuf, +void grpc_chttp2_encode_data(uint32_t id, grpc_slice_buffer* inbuf, uint32_t write_bytes, int is_eof, - grpc_transport_one_way_stats *stats, - grpc_slice_buffer *outbuf) { + grpc_transport_one_way_stats* stats, + grpc_slice_buffer* outbuf) { grpc_slice hdr; - uint8_t *p; + uint8_t* p; static const size_t header_size = 9; hdr = GRPC_SLICE_MALLOC(header_size); @@ -97,17 +97,17 @@ void grpc_chttp2_encode_data(uint32_t id, grpc_slice_buffer *inbuf, stats->data_bytes += write_bytes; } -grpc_error *grpc_deframe_unprocessed_incoming_frames( - grpc_exec_ctx *exec_ctx, grpc_chttp2_data_parser *p, grpc_chttp2_stream *s, - grpc_slice_buffer *slices, grpc_slice *slice_out, - grpc_byte_stream **stream_out) { - grpc_error *error = GRPC_ERROR_NONE; - grpc_chttp2_transport *t = s->t; +grpc_error* grpc_deframe_unprocessed_incoming_frames( + grpc_exec_ctx* exec_ctx, grpc_chttp2_data_parser* p, grpc_chttp2_stream* s, + grpc_slice_buffer* slices, grpc_slice* slice_out, + grpc_byte_stream** stream_out) { + grpc_error* error = GRPC_ERROR_NONE; + grpc_chttp2_transport* t = s->t; while (slices->count > 0) { - uint8_t *beg = NULL; - uint8_t *end = NULL; - uint8_t *cur = NULL; + uint8_t* beg = nullptr; + uint8_t* end = nullptr; + uint8_t* cur = nullptr; grpc_slice slice = grpc_slice_buffer_take_first(slices); @@ -115,7 +115,7 @@ grpc_error *grpc_deframe_unprocessed_incoming_frames( end = GRPC_SLICE_END_PTR(slice); cur = beg; uint32_t message_flags; - char *msg; + char* msg; if (cur == end) { grpc_slice_unref_internal(exec_ctx, slice); @@ -188,8 +188,8 @@ grpc_error *grpc_deframe_unprocessed_incoming_frames( /* fallthrough */ case GRPC_CHTTP2_DATA_FH_4: s->stats.incoming.framing_bytes++; - GPR_ASSERT(stream_out != NULL); - GPR_ASSERT(p->parsing_frame == NULL); + GPR_ASSERT(stream_out != nullptr); + GPR_ASSERT(p->parsing_frame == nullptr); p->frame_size |= ((uint32_t)*cur); p->state = GRPC_CHTTP2_DATA_FRAME; ++cur; @@ -203,7 +203,7 @@ grpc_error *grpc_deframe_unprocessed_incoming_frames( if (p->parsing_frame->remaining_bytes == 0) { GRPC_ERROR_UNREF(grpc_chttp2_incoming_byte_stream_finished( exec_ctx, p->parsing_frame, GRPC_ERROR_NONE, true)); - p->parsing_frame = NULL; + p->parsing_frame = nullptr; p->state = GRPC_CHTTP2_DATA_FH_0; } s->pending_byte_stream = true; @@ -216,8 +216,8 @@ grpc_error *grpc_deframe_unprocessed_incoming_frames( grpc_slice_unref_internal(exec_ctx, slice); return GRPC_ERROR_NONE; case GRPC_CHTTP2_DATA_FRAME: { - GPR_ASSERT(p->parsing_frame != NULL); - GPR_ASSERT(slice_out != NULL); + GPR_ASSERT(p->parsing_frame != nullptr); + GPR_ASSERT(slice_out != nullptr); if (cur == end) { grpc_slice_unref_internal(exec_ctx, slice); continue; @@ -239,7 +239,7 @@ grpc_error *grpc_deframe_unprocessed_incoming_frames( grpc_slice_unref_internal(exec_ctx, slice); return error; } - p->parsing_frame = NULL; + p->parsing_frame = nullptr; p->state = GRPC_CHTTP2_DATA_FH_0; grpc_slice_unref_internal(exec_ctx, slice); return GRPC_ERROR_NONE; @@ -273,7 +273,7 @@ grpc_error *grpc_deframe_unprocessed_incoming_frames( grpc_slice_unref_internal(exec_ctx, slice); return error; } - p->parsing_frame = NULL; + p->parsing_frame = nullptr; p->state = GRPC_CHTTP2_DATA_FH_0; cur += p->frame_size; grpc_slice_buffer_undo_take_first( @@ -289,9 +289,9 @@ grpc_error *grpc_deframe_unprocessed_incoming_frames( return GRPC_ERROR_NONE; } -grpc_error *grpc_chttp2_data_parser_parse(grpc_exec_ctx *exec_ctx, void *parser, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, +grpc_error* grpc_chttp2_data_parser_parse(grpc_exec_ctx* exec_ctx, void* parser, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_slice slice, int is_last) { if (!s->pending_byte_stream) { grpc_slice_ref_internal(slice); @@ -302,7 +302,7 @@ grpc_error *grpc_chttp2_data_parser_parse(grpc_exec_ctx *exec_ctx, void *parser, grpc_slice_ref_internal(slice); grpc_slice_buffer_add(&s->unprocessed_incoming_frames_buffer, slice); GRPC_CLOSURE_SCHED(exec_ctx, s->on_next, GRPC_ERROR_NONE); - s->on_next = NULL; + s->on_next = nullptr; s->unprocessed_incoming_frames_decompressed = false; } else { grpc_slice_ref_internal(slice); diff --git a/src/core/ext/transport/chttp2/transport/frame_data.h b/src/core/ext/transport/chttp2/transport/frame_data.h index 81ec5361a39..4de553ea426 100644 --- a/src/core/ext/transport/chttp2/transport/frame_data.h +++ b/src/core/ext/transport/chttp2/transport/frame_data.h @@ -28,10 +28,6 @@ #include "src/core/lib/transport/byte_stream.h" #include "src/core/lib/transport/transport.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef enum { GRPC_CHTTP2_DATA_FH_0, GRPC_CHTTP2_DATA_FH_1, @@ -49,43 +45,39 @@ typedef struct { grpc_chttp2_stream_state state; uint8_t frame_type; uint32_t frame_size; - grpc_error *error; + grpc_error* error; bool is_frame_compressed; - grpc_chttp2_incoming_byte_stream *parsing_frame; + grpc_chttp2_incoming_byte_stream* parsing_frame; } grpc_chttp2_data_parser; /* initialize per-stream state for data frame parsing */ -grpc_error *grpc_chttp2_data_parser_init(grpc_chttp2_data_parser *parser); +grpc_error* grpc_chttp2_data_parser_init(grpc_chttp2_data_parser* parser); -void grpc_chttp2_data_parser_destroy(grpc_exec_ctx *exec_ctx, - grpc_chttp2_data_parser *parser); +void grpc_chttp2_data_parser_destroy(grpc_exec_ctx* exec_ctx, + grpc_chttp2_data_parser* parser); /* start processing a new data frame */ -grpc_error *grpc_chttp2_data_parser_begin_frame(grpc_chttp2_data_parser *parser, +grpc_error* grpc_chttp2_data_parser_begin_frame(grpc_chttp2_data_parser* parser, uint8_t flags, uint32_t stream_id, - grpc_chttp2_stream *s); + grpc_chttp2_stream* s); /* handle a slice of a data frame - is_last indicates the last slice of a frame */ -grpc_error *grpc_chttp2_data_parser_parse(grpc_exec_ctx *exec_ctx, void *parser, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, +grpc_error* grpc_chttp2_data_parser_parse(grpc_exec_ctx* exec_ctx, void* parser, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_slice slice, int is_last); -void grpc_chttp2_encode_data(uint32_t id, grpc_slice_buffer *inbuf, +void grpc_chttp2_encode_data(uint32_t id, grpc_slice_buffer* inbuf, uint32_t write_bytes, int is_eof, - grpc_transport_one_way_stats *stats, - grpc_slice_buffer *outbuf); - -grpc_error *grpc_deframe_unprocessed_incoming_frames( - grpc_exec_ctx *exec_ctx, grpc_chttp2_data_parser *p, grpc_chttp2_stream *s, - grpc_slice_buffer *slices, grpc_slice *slice_out, - grpc_byte_stream **stream_out); + grpc_transport_one_way_stats* stats, + grpc_slice_buffer* outbuf); -#ifdef __cplusplus -} -#endif +grpc_error* grpc_deframe_unprocessed_incoming_frames( + grpc_exec_ctx* exec_ctx, grpc_chttp2_data_parser* p, grpc_chttp2_stream* s, + grpc_slice_buffer* slices, grpc_slice* slice_out, + grpc_byte_stream** stream_out); #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_DATA_H */ diff --git a/src/core/ext/transport/chttp2/transport/frame_goaway.cc b/src/core/ext/transport/chttp2/transport/frame_goaway.cc index 78ec08e177f..a2ce709a2e4 100644 --- a/src/core/ext/transport/chttp2/transport/frame_goaway.cc +++ b/src/core/ext/transport/chttp2/transport/frame_goaway.cc @@ -25,42 +25,42 @@ #include #include -void grpc_chttp2_goaway_parser_init(grpc_chttp2_goaway_parser *p) { - p->debug_data = NULL; +void grpc_chttp2_goaway_parser_init(grpc_chttp2_goaway_parser* p) { + p->debug_data = nullptr; } -void grpc_chttp2_goaway_parser_destroy(grpc_chttp2_goaway_parser *p) { +void grpc_chttp2_goaway_parser_destroy(grpc_chttp2_goaway_parser* p) { gpr_free(p->debug_data); } -grpc_error *grpc_chttp2_goaway_parser_begin_frame(grpc_chttp2_goaway_parser *p, +grpc_error* grpc_chttp2_goaway_parser_begin_frame(grpc_chttp2_goaway_parser* p, uint32_t length, uint8_t flags) { if (length < 8) { - char *msg; + char* msg; gpr_asprintf(&msg, "goaway frame too short (%d bytes)", length); - grpc_error *err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return err; } gpr_free(p->debug_data); p->debug_length = length - 8; - p->debug_data = (char *)gpr_malloc(p->debug_length); + p->debug_data = (char*)gpr_malloc(p->debug_length); p->debug_pos = 0; p->state = GRPC_CHTTP2_GOAWAY_LSI0; return GRPC_ERROR_NONE; } -grpc_error *grpc_chttp2_goaway_parser_parse(grpc_exec_ctx *exec_ctx, - void *parser, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, +grpc_error* grpc_chttp2_goaway_parser_parse(grpc_exec_ctx* exec_ctx, + void* parser, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_slice slice, int is_last) { - uint8_t *const beg = GRPC_SLICE_START_PTR(slice); - uint8_t *const end = GRPC_SLICE_END_PTR(slice); - uint8_t *cur = beg; - grpc_chttp2_goaway_parser *p = (grpc_chttp2_goaway_parser *)parser; + uint8_t* const beg = GRPC_SLICE_START_PTR(slice); + uint8_t* const end = GRPC_SLICE_END_PTR(slice); + uint8_t* cur = beg; + grpc_chttp2_goaway_parser* p = (grpc_chttp2_goaway_parser*)parser; switch (p->state) { case GRPC_CHTTP2_GOAWAY_LSI0: @@ -137,7 +137,7 @@ grpc_error *grpc_chttp2_goaway_parser_parse(grpc_exec_ctx *exec_ctx, grpc_chttp2_add_incoming_goaway( exec_ctx, t, (uint32_t)p->error_code, grpc_slice_new(p->debug_data, p->debug_length, gpr_free)); - p->debug_data = NULL; + p->debug_data = nullptr; } return GRPC_ERROR_NONE; } @@ -147,9 +147,9 @@ grpc_error *grpc_chttp2_goaway_parser_parse(grpc_exec_ctx *exec_ctx, void grpc_chttp2_goaway_append(uint32_t last_stream_id, uint32_t error_code, grpc_slice debug_data, - grpc_slice_buffer *slice_buffer) { + grpc_slice_buffer* slice_buffer) { grpc_slice header = GRPC_SLICE_MALLOC(9 + 4 + 4); - uint8_t *p = GRPC_SLICE_START_PTR(header); + uint8_t* p = GRPC_SLICE_START_PTR(header); uint32_t frame_length; GPR_ASSERT(GRPC_SLICE_LENGTH(debug_data) < UINT32_MAX - 4 - 4); frame_length = 4 + 4 + (uint32_t)GRPC_SLICE_LENGTH(debug_data); diff --git a/src/core/ext/transport/chttp2/transport/frame_goaway.h b/src/core/ext/transport/chttp2/transport/frame_goaway.h index 7b3aa45f3f2..743e763342d 100644 --- a/src/core/ext/transport/chttp2/transport/frame_goaway.h +++ b/src/core/ext/transport/chttp2/transport/frame_goaway.h @@ -25,10 +25,6 @@ #include "src/core/ext/transport/chttp2/transport/frame.h" #include "src/core/lib/iomgr/exec_ctx.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef enum { GRPC_CHTTP2_GOAWAY_LSI0, GRPC_CHTTP2_GOAWAY_LSI1, @@ -45,27 +41,23 @@ typedef struct { grpc_chttp2_goaway_parse_state state; uint32_t last_stream_id; uint32_t error_code; - char *debug_data; + char* debug_data; uint32_t debug_length; uint32_t debug_pos; } grpc_chttp2_goaway_parser; -void grpc_chttp2_goaway_parser_init(grpc_chttp2_goaway_parser *p); -void grpc_chttp2_goaway_parser_destroy(grpc_chttp2_goaway_parser *p); -grpc_error *grpc_chttp2_goaway_parser_begin_frame( - grpc_chttp2_goaway_parser *parser, uint32_t length, uint8_t flags); -grpc_error *grpc_chttp2_goaway_parser_parse(grpc_exec_ctx *exec_ctx, - void *parser, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, +void grpc_chttp2_goaway_parser_init(grpc_chttp2_goaway_parser* p); +void grpc_chttp2_goaway_parser_destroy(grpc_chttp2_goaway_parser* p); +grpc_error* grpc_chttp2_goaway_parser_begin_frame( + grpc_chttp2_goaway_parser* parser, uint32_t length, uint8_t flags); +grpc_error* grpc_chttp2_goaway_parser_parse(grpc_exec_ctx* exec_ctx, + void* parser, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_slice slice, int is_last); void grpc_chttp2_goaway_append(uint32_t last_stream_id, uint32_t error_code, grpc_slice debug_data, - grpc_slice_buffer *slice_buffer); - -#ifdef __cplusplus -} -#endif + grpc_slice_buffer* slice_buffer); #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_GOAWAY_H */ diff --git a/src/core/ext/transport/chttp2/transport/frame_ping.cc b/src/core/ext/transport/chttp2/transport/frame_ping.cc index 1cfa883ee15..d0feb519225 100644 --- a/src/core/ext/transport/chttp2/transport/frame_ping.cc +++ b/src/core/ext/transport/chttp2/transport/frame_ping.cc @@ -29,7 +29,7 @@ static bool g_disable_ping_ack = false; grpc_slice grpc_chttp2_ping_create(uint8_t ack, uint64_t opaque_8bytes) { grpc_slice slice = GRPC_SLICE_MALLOC(9 + 8); - uint8_t *p = GRPC_SLICE_START_PTR(slice); + uint8_t* p = GRPC_SLICE_START_PTR(slice); *p++ = 0; *p++ = 0; @@ -52,13 +52,13 @@ grpc_slice grpc_chttp2_ping_create(uint8_t ack, uint64_t opaque_8bytes) { return slice; } -grpc_error *grpc_chttp2_ping_parser_begin_frame(grpc_chttp2_ping_parser *parser, +grpc_error* grpc_chttp2_ping_parser_begin_frame(grpc_chttp2_ping_parser* parser, uint32_t length, uint8_t flags) { if (flags & 0xfe || length != 8) { - char *msg; + char* msg; gpr_asprintf(&msg, "invalid ping: length=%d, flags=%02x", length, flags); - grpc_error *error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return error; } @@ -68,14 +68,14 @@ grpc_error *grpc_chttp2_ping_parser_begin_frame(grpc_chttp2_ping_parser *parser, return GRPC_ERROR_NONE; } -grpc_error *grpc_chttp2_ping_parser_parse(grpc_exec_ctx *exec_ctx, void *parser, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, +grpc_error* grpc_chttp2_ping_parser_parse(grpc_exec_ctx* exec_ctx, void* parser, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_slice slice, int is_last) { - uint8_t *const beg = GRPC_SLICE_START_PTR(slice); - uint8_t *const end = GRPC_SLICE_END_PTR(slice); - uint8_t *cur = beg; - grpc_chttp2_ping_parser *p = (grpc_chttp2_ping_parser *)parser; + uint8_t* const beg = GRPC_SLICE_START_PTR(slice); + uint8_t* const end = GRPC_SLICE_END_PTR(slice); + uint8_t* cur = beg; + grpc_chttp2_ping_parser* p = (grpc_chttp2_ping_parser*)parser; while (p->byte != 8 && cur != end) { p->opaque_8bytes |= (((uint64_t)*cur) << (56 - 8 * p->byte)); @@ -112,7 +112,7 @@ grpc_error *grpc_chttp2_ping_parser_parse(grpc_exec_ctx *exec_ctx, void *parser, if (!g_disable_ping_ack) { if (t->ping_ack_count == t->ping_ack_capacity) { t->ping_ack_capacity = GPR_MAX(t->ping_ack_capacity * 3 / 2, 3); - t->ping_acks = (uint64_t *)gpr_realloc( + t->ping_acks = (uint64_t*)gpr_realloc( t->ping_acks, t->ping_ack_capacity * sizeof(*t->ping_acks)); } t->ping_acks[t->ping_ack_count++] = p->opaque_8bytes; diff --git a/src/core/ext/transport/chttp2/transport/frame_ping.h b/src/core/ext/transport/chttp2/transport/frame_ping.h index ffc2f0cf2ff..76ca3977091 100644 --- a/src/core/ext/transport/chttp2/transport/frame_ping.h +++ b/src/core/ext/transport/chttp2/transport/frame_ping.h @@ -23,10 +23,6 @@ #include "src/core/ext/transport/chttp2/transport/frame.h" #include "src/core/lib/iomgr/exec_ctx.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct { uint8_t byte; uint8_t is_ack; @@ -35,18 +31,14 @@ typedef struct { grpc_slice grpc_chttp2_ping_create(uint8_t ack, uint64_t opaque_8bytes); -grpc_error *grpc_chttp2_ping_parser_begin_frame(grpc_chttp2_ping_parser *parser, +grpc_error* grpc_chttp2_ping_parser_begin_frame(grpc_chttp2_ping_parser* parser, uint32_t length, uint8_t flags); -grpc_error *grpc_chttp2_ping_parser_parse(grpc_exec_ctx *exec_ctx, void *parser, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, +grpc_error* grpc_chttp2_ping_parser_parse(grpc_exec_ctx* exec_ctx, void* parser, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_slice slice, int is_last); /* Test-only function for disabling ping ack */ void grpc_set_disable_ping_ack(bool disable_ping_ack); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_PING_H */ diff --git a/src/core/ext/transport/chttp2/transport/frame_rst_stream.cc b/src/core/ext/transport/chttp2/transport/frame_rst_stream.cc index 0133b6efa25..05a7f056a44 100644 --- a/src/core/ext/transport/chttp2/transport/frame_rst_stream.cc +++ b/src/core/ext/transport/chttp2/transport/frame_rst_stream.cc @@ -27,11 +27,11 @@ #include "src/core/lib/transport/http2_errors.h" grpc_slice grpc_chttp2_rst_stream_create(uint32_t id, uint32_t code, - grpc_transport_one_way_stats *stats) { + grpc_transport_one_way_stats* stats) { static const size_t frame_size = 13; grpc_slice slice = GRPC_SLICE_MALLOC(frame_size); stats->framing_bytes += frame_size; - uint8_t *p = GRPC_SLICE_START_PTR(slice); + uint8_t* p = GRPC_SLICE_START_PTR(slice); // Frame size. *p++ = 0; @@ -55,13 +55,13 @@ grpc_slice grpc_chttp2_rst_stream_create(uint32_t id, uint32_t code, return slice; } -grpc_error *grpc_chttp2_rst_stream_parser_begin_frame( - grpc_chttp2_rst_stream_parser *parser, uint32_t length, uint8_t flags) { +grpc_error* grpc_chttp2_rst_stream_parser_begin_frame( + grpc_chttp2_rst_stream_parser* parser, uint32_t length, uint8_t flags) { if (length != 4) { - char *msg; + char* msg; gpr_asprintf(&msg, "invalid rst_stream: length=%d, flags=%02x", length, flags); - grpc_error *err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return err; } @@ -69,15 +69,15 @@ grpc_error *grpc_chttp2_rst_stream_parser_begin_frame( return GRPC_ERROR_NONE; } -grpc_error *grpc_chttp2_rst_stream_parser_parse(grpc_exec_ctx *exec_ctx, - void *parser, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, +grpc_error* grpc_chttp2_rst_stream_parser_parse(grpc_exec_ctx* exec_ctx, + void* parser, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_slice slice, int is_last) { - uint8_t *const beg = GRPC_SLICE_START_PTR(slice); - uint8_t *const end = GRPC_SLICE_END_PTR(slice); - uint8_t *cur = beg; - grpc_chttp2_rst_stream_parser *p = (grpc_chttp2_rst_stream_parser *)parser; + uint8_t* const beg = GRPC_SLICE_START_PTR(slice); + uint8_t* const end = GRPC_SLICE_END_PTR(slice); + uint8_t* cur = beg; + grpc_chttp2_rst_stream_parser* p = (grpc_chttp2_rst_stream_parser*)parser; while (p->byte != 4 && cur != end) { p->reason_bytes[p->byte] = *cur; @@ -92,9 +92,9 @@ grpc_error *grpc_chttp2_rst_stream_parser_parse(grpc_exec_ctx *exec_ctx, (((uint32_t)p->reason_bytes[1]) << 16) | (((uint32_t)p->reason_bytes[2]) << 8) | (((uint32_t)p->reason_bytes[3])); - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; if (reason != GRPC_HTTP2_NO_ERROR || s->metadata_buffer[1].size == 0) { - char *message; + char* message; gpr_asprintf(&message, "Received RST_STREAM with error code %d", reason); error = grpc_error_set_int( grpc_error_set_str(GRPC_ERROR_CREATE_FROM_STATIC_STRING("RST_STREAM"), diff --git a/src/core/ext/transport/chttp2/transport/frame_rst_stream.h b/src/core/ext/transport/chttp2/transport/frame_rst_stream.h index 102ffdb3f36..7dfc5d4578b 100644 --- a/src/core/ext/transport/chttp2/transport/frame_rst_stream.h +++ b/src/core/ext/transport/chttp2/transport/frame_rst_stream.h @@ -24,28 +24,20 @@ #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/transport/transport.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct { uint8_t byte; uint8_t reason_bytes[4]; } grpc_chttp2_rst_stream_parser; grpc_slice grpc_chttp2_rst_stream_create(uint32_t stream_id, uint32_t code, - grpc_transport_one_way_stats *stats); - -grpc_error *grpc_chttp2_rst_stream_parser_begin_frame( - grpc_chttp2_rst_stream_parser *parser, uint32_t length, uint8_t flags); -grpc_error *grpc_chttp2_rst_stream_parser_parse(grpc_exec_ctx *exec_ctx, - void *parser, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, + grpc_transport_one_way_stats* stats); + +grpc_error* grpc_chttp2_rst_stream_parser_begin_frame( + grpc_chttp2_rst_stream_parser* parser, uint32_t length, uint8_t flags); +grpc_error* grpc_chttp2_rst_stream_parser_parse(grpc_exec_ctx* exec_ctx, + void* parser, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_slice slice, int is_last); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_RST_STREAM_H */ diff --git a/src/core/ext/transport/chttp2/transport/frame_settings.cc b/src/core/ext/transport/chttp2/transport/frame_settings.cc index db0245bb576..de4340fea50 100644 --- a/src/core/ext/transport/chttp2/transport/frame_settings.cc +++ b/src/core/ext/transport/chttp2/transport/frame_settings.cc @@ -31,7 +31,7 @@ #include "src/core/lib/debug/trace.h" #include "src/core/lib/transport/http2_errors.h" -static uint8_t *fill_header(uint8_t *out, uint32_t length, uint8_t flags) { +static uint8_t* fill_header(uint8_t* out, uint32_t length, uint8_t flags) { *out++ = (uint8_t)(length >> 16); *out++ = (uint8_t)(length >> 8); *out++ = (uint8_t)(length); @@ -44,13 +44,13 @@ static uint8_t *fill_header(uint8_t *out, uint32_t length, uint8_t flags) { return out; } -grpc_slice grpc_chttp2_settings_create(uint32_t *old_settings, - const uint32_t *new_settings, +grpc_slice grpc_chttp2_settings_create(uint32_t* old_settings, + const uint32_t* new_settings, uint32_t force_mask, size_t count) { size_t i; uint32_t n = 0; grpc_slice output; - uint8_t *p; + uint8_t* p; for (i = 0; i < count; i++) { n += (new_settings[i] != old_settings[i] || (force_mask & (1u << i)) != 0); @@ -82,9 +82,9 @@ grpc_slice grpc_chttp2_settings_ack_create(void) { return output; } -grpc_error *grpc_chttp2_settings_parser_begin_frame( - grpc_chttp2_settings_parser *parser, uint32_t length, uint8_t flags, - uint32_t *settings) { +grpc_error* grpc_chttp2_settings_parser_begin_frame( + grpc_chttp2_settings_parser* parser, uint32_t length, uint8_t flags, + uint32_t* settings) { parser->target_settings = settings; memcpy(parser->incoming_settings, settings, GRPC_CHTTP2_NUM_SETTINGS * sizeof(uint32_t)); @@ -108,14 +108,14 @@ grpc_error *grpc_chttp2_settings_parser_begin_frame( } } -grpc_error *grpc_chttp2_settings_parser_parse(grpc_exec_ctx *exec_ctx, void *p, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, +grpc_error* grpc_chttp2_settings_parser_parse(grpc_exec_ctx* exec_ctx, void* p, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_slice slice, int is_last) { - grpc_chttp2_settings_parser *parser = (grpc_chttp2_settings_parser *)p; - const uint8_t *cur = GRPC_SLICE_START_PTR(slice); - const uint8_t *end = GRPC_SLICE_END_PTR(slice); - char *msg; + grpc_chttp2_settings_parser* parser = (grpc_chttp2_settings_parser*)p; + const uint8_t* cur = GRPC_SLICE_START_PTR(slice); + const uint8_t* end = GRPC_SLICE_END_PTR(slice); + char* msg; grpc_chttp2_setting_id id; if (parser->is_ack) { @@ -131,6 +131,11 @@ grpc_error *grpc_chttp2_settings_parser_parse(grpc_exec_ctx *exec_ctx, void *p, memcpy(parser->target_settings, parser->incoming_settings, GRPC_CHTTP2_NUM_SETTINGS * sizeof(uint32_t)); grpc_slice_buffer_add(&t->qbuf, grpc_chttp2_settings_ack_create()); + if (t->notify_on_receive_settings != nullptr) { + GRPC_CLOSURE_SCHED(exec_ctx, t->notify_on_receive_settings, + GRPC_ERROR_NONE); + t->notify_on_receive_settings = nullptr; + } } return GRPC_ERROR_NONE; } @@ -180,7 +185,7 @@ grpc_error *grpc_chttp2_settings_parser_parse(grpc_exec_ctx *exec_ctx, void *p, cur++; if (grpc_wire_id_to_setting_id(parser->id, &id)) { - const grpc_chttp2_setting_parameters *sp = + const grpc_chttp2_setting_parameters* sp = &grpc_chttp2_settings_parameters[id]; if (parser->value < sp->min_value || parser->value > sp->max_value) { switch (sp->invalid_value_behavior) { @@ -195,7 +200,7 @@ grpc_error *grpc_chttp2_settings_parser_parse(grpc_exec_ctx *exec_ctx, void *p, &t->qbuf); gpr_asprintf(&msg, "invalid value %u passed for %s", parser->value, sp->name); - grpc_error *err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return err; } @@ -204,20 +209,19 @@ grpc_error *grpc_chttp2_settings_parser_parse(grpc_exec_ctx *exec_ctx, void *p, parser->incoming_settings[id] != parser->value) { t->initial_window_update += (int64_t)parser->value - parser->incoming_settings[id]; - if (GRPC_TRACER_ON(grpc_http_trace) || - GRPC_TRACER_ON(grpc_flowctl_trace)) { + if (grpc_http_trace.enabled() || grpc_flowctl_trace.enabled()) { gpr_log(GPR_DEBUG, "%p[%s] adding %d for initial_window change", t, t->is_client ? "cli" : "svr", (int)t->initial_window_update); } } parser->incoming_settings[id] = parser->value; - if (GRPC_TRACER_ON(grpc_http_trace)) { + if (grpc_http_trace.enabled()) { gpr_log(GPR_DEBUG, "CHTTP2:%s:%s: got setting %s = %d", t->is_client ? "CLI" : "SVR", t->peer_string, sp->name, parser->value); } - } else if (GRPC_TRACER_ON(grpc_http_trace)) { + } else if (grpc_http_trace.enabled()) { gpr_log(GPR_ERROR, "CHTTP2: Ignoring unknown setting %d (value %d)", parser->id, parser->value); } diff --git a/src/core/ext/transport/chttp2/transport/frame_settings.h b/src/core/ext/transport/chttp2/transport/frame_settings.h index 3364da15207..36e2ca83a0f 100644 --- a/src/core/ext/transport/chttp2/transport/frame_settings.h +++ b/src/core/ext/transport/chttp2/transport/frame_settings.h @@ -25,10 +25,6 @@ #include "src/core/ext/transport/chttp2/transport/http2_settings.h" #include "src/core/lib/iomgr/exec_ctx.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef enum { GRPC_CHTTP2_SPS_ID0, GRPC_CHTTP2_SPS_ID1, @@ -40,7 +36,7 @@ typedef enum { typedef struct { grpc_chttp2_settings_parse_state state; - uint32_t *target_settings; + uint32_t* target_settings; uint8_t is_ack; uint16_t id; uint32_t value; @@ -48,22 +44,18 @@ typedef struct { } grpc_chttp2_settings_parser; /* Create a settings frame by diffing old & new, and updating old to be new */ -grpc_slice grpc_chttp2_settings_create(uint32_t *old, const uint32_t *newval, +grpc_slice grpc_chttp2_settings_create(uint32_t* old, const uint32_t* newval, uint32_t force_mask, size_t count); /* Create an ack settings frame */ grpc_slice grpc_chttp2_settings_ack_create(void); -grpc_error *grpc_chttp2_settings_parser_begin_frame( - grpc_chttp2_settings_parser *parser, uint32_t length, uint8_t flags, - uint32_t *settings); -grpc_error *grpc_chttp2_settings_parser_parse(grpc_exec_ctx *exec_ctx, - void *parser, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, +grpc_error* grpc_chttp2_settings_parser_begin_frame( + grpc_chttp2_settings_parser* parser, uint32_t length, uint8_t flags, + uint32_t* settings); +grpc_error* grpc_chttp2_settings_parser_parse(grpc_exec_ctx* exec_ctx, + void* parser, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_slice slice, int is_last); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_SETTINGS_H */ diff --git a/src/core/ext/transport/chttp2/transport/frame_window_update.cc b/src/core/ext/transport/chttp2/transport/frame_window_update.cc index 15eaf59285f..08407a8e671 100644 --- a/src/core/ext/transport/chttp2/transport/frame_window_update.cc +++ b/src/core/ext/transport/chttp2/transport/frame_window_update.cc @@ -24,11 +24,11 @@ #include grpc_slice grpc_chttp2_window_update_create( - uint32_t id, uint32_t window_update, grpc_transport_one_way_stats *stats) { + uint32_t id, uint32_t window_update, grpc_transport_one_way_stats* stats) { static const size_t frame_size = 13; grpc_slice slice = GRPC_SLICE_MALLOC(frame_size); stats->header_bytes += frame_size; - uint8_t *p = GRPC_SLICE_START_PTR(slice); + uint8_t* p = GRPC_SLICE_START_PTR(slice); GPR_ASSERT(window_update); @@ -49,13 +49,13 @@ grpc_slice grpc_chttp2_window_update_create( return slice; } -grpc_error *grpc_chttp2_window_update_parser_begin_frame( - grpc_chttp2_window_update_parser *parser, uint32_t length, uint8_t flags) { +grpc_error* grpc_chttp2_window_update_parser_begin_frame( + grpc_chttp2_window_update_parser* parser, uint32_t length, uint8_t flags) { if (flags || length != 4) { - char *msg; + char* msg; gpr_asprintf(&msg, "invalid window update: length=%d, flags=%02x", length, flags); - grpc_error *err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return err; } @@ -64,14 +64,14 @@ grpc_error *grpc_chttp2_window_update_parser_begin_frame( return GRPC_ERROR_NONE; } -grpc_error *grpc_chttp2_window_update_parser_parse( - grpc_exec_ctx *exec_ctx, void *parser, grpc_chttp2_transport *t, - grpc_chttp2_stream *s, grpc_slice slice, int is_last) { - uint8_t *const beg = GRPC_SLICE_START_PTR(slice); - uint8_t *const end = GRPC_SLICE_END_PTR(slice); - uint8_t *cur = beg; - grpc_chttp2_window_update_parser *p = - (grpc_chttp2_window_update_parser *)parser; +grpc_error* grpc_chttp2_window_update_parser_parse( + grpc_exec_ctx* exec_ctx, void* parser, grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_slice slice, int is_last) { + uint8_t* const beg = GRPC_SLICE_START_PTR(slice); + uint8_t* const end = GRPC_SLICE_END_PTR(slice); + uint8_t* cur = beg; + grpc_chttp2_window_update_parser* p = + (grpc_chttp2_window_update_parser*)parser; while (p->byte != 4 && cur != end) { p->amount |= ((uint32_t)*cur) << (8 * (3 - p->byte)); @@ -79,23 +79,23 @@ grpc_error *grpc_chttp2_window_update_parser_parse( p->byte++; } - if (s != NULL) { + if (s != nullptr) { s->stats.incoming.framing_bytes += (uint32_t)(end - cur); } if (p->byte == 4) { uint32_t received_update = p->amount; if (received_update == 0 || (received_update & 0x80000000u)) { - char *msg; + char* msg; gpr_asprintf(&msg, "invalid window update bytes: %d", p->amount); - grpc_error *err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return err; } GPR_ASSERT(is_last); if (t->incoming_stream_id != 0) { - if (s != NULL) { + if (s != nullptr) { s->flow_control->RecvUpdate(received_update); if (grpc_chttp2_list_remove_stalled_by_stream(t, s)) { grpc_chttp2_mark_stream_writable(exec_ctx, t, s); diff --git a/src/core/ext/transport/chttp2/transport/frame_window_update.h b/src/core/ext/transport/chttp2/transport/frame_window_update.h index 400f9f53989..e031b585faa 100644 --- a/src/core/ext/transport/chttp2/transport/frame_window_update.h +++ b/src/core/ext/transport/chttp2/transport/frame_window_update.h @@ -24,10 +24,6 @@ #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/transport/transport.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct { uint8_t byte; uint8_t is_connection_update; @@ -35,16 +31,12 @@ typedef struct { } grpc_chttp2_window_update_parser; grpc_slice grpc_chttp2_window_update_create( - uint32_t id, uint32_t window_delta, grpc_transport_one_way_stats *stats); - -grpc_error *grpc_chttp2_window_update_parser_begin_frame( - grpc_chttp2_window_update_parser *parser, uint32_t length, uint8_t flags); -grpc_error *grpc_chttp2_window_update_parser_parse( - grpc_exec_ctx *exec_ctx, void *parser, grpc_chttp2_transport *t, - grpc_chttp2_stream *s, grpc_slice slice, int is_last); + uint32_t id, uint32_t window_delta, grpc_transport_one_way_stats* stats); -#ifdef __cplusplus -} -#endif +grpc_error* grpc_chttp2_window_update_parser_begin_frame( + grpc_chttp2_window_update_parser* parser, uint32_t length, uint8_t flags); +grpc_error* grpc_chttp2_window_update_parser_parse( + grpc_exec_ctx* exec_ctx, void* parser, grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_slice slice, int is_last); #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_FRAME_WINDOW_UPDATE_H */ diff --git a/src/core/ext/transport/chttp2/transport/hpack_encoder.cc b/src/core/ext/transport/chttp2/transport/hpack_encoder.cc index 0ea50e394b2..e76d92e31d4 100644 --- a/src/core/ext/transport/chttp2/transport/hpack_encoder.cc +++ b/src/core/ext/transport/chttp2/transport/hpack_encoder.cc @@ -51,14 +51,12 @@ /* don't consider adding anything bigger than this to the hpack table */ #define MAX_DECODER_SPACE_USAGE 512 -static grpc_slice_refcount terminal_slice_refcount = {NULL, NULL}; +static grpc_slice_refcount terminal_slice_refcount = {nullptr, nullptr}; static const grpc_slice terminal_slice = { &terminal_slice_refcount, /* refcount */ - {{0, 0}} /* data.refcounted */ + {{nullptr, 0}} /* data.refcounted */ }; -extern "C" grpc_tracer_flag grpc_http_trace; - typedef struct { int is_first_frame; /* number of bytes in 'output' when we started the frame - used to calculate @@ -70,15 +68,15 @@ typedef struct { uint8_t seen_regular_header; /* output stream id */ uint32_t stream_id; - grpc_slice_buffer *output; - grpc_transport_one_way_stats *stats; + grpc_slice_buffer* output; + grpc_transport_one_way_stats* stats; /* maximum size of a frame */ size_t max_frame_size; bool use_true_binary_metadata; } framer_state; /* fills p (which is expected to be 9 bytes long) with a data frame header */ -static void fill_header(uint8_t *p, uint8_t type, uint32_t id, size_t len, +static void fill_header(uint8_t* p, uint8_t type, uint32_t id, size_t len, uint8_t flags) { GPR_ASSERT(len < 16777316); *p++ = (uint8_t)(len >> 16); @@ -93,7 +91,7 @@ static void fill_header(uint8_t *p, uint8_t type, uint32_t id, size_t len, } /* finish a frame - fill in the previously reserved header */ -static void finish_frame(framer_state *st, int is_header_boundary, +static void finish_frame(framer_state* st, int is_header_boundary, int is_last_in_stream) { uint8_t type = 0xff; type = st->is_first_frame ? GRPC_CHTTP2_FRAME_HEADER @@ -109,7 +107,7 @@ static void finish_frame(framer_state *st, int is_header_boundary, /* begin a new frame: reserve off header space, remember how many bytes we'd output before beginning */ -static void begin_frame(framer_state *st) { +static void begin_frame(framer_state* st) { st->header_idx = grpc_slice_buffer_add_indexed(st->output, GRPC_SLICE_MALLOC(9)); st->output_length_at_start_of_frame = st->output->length; @@ -118,7 +116,7 @@ static void begin_frame(framer_state *st) { /* make sure that the current frame is of the type desired, and has sufficient space to add at least about_to_add bytes -- finishes the current frame if needed */ -static void ensure_space(framer_state *st, size_t need_bytes) { +static void ensure_space(framer_state* st, size_t need_bytes) { if (st->output->length - st->output_length_at_start_of_frame + need_bytes <= st->max_frame_size) { return; @@ -128,7 +126,7 @@ static void ensure_space(framer_state *st, size_t need_bytes) { } /* increment a filter count, halve all counts if one element reaches max */ -static void inc_filter(uint8_t idx, uint32_t *sum, uint8_t *elems) { +static void inc_filter(uint8_t idx, uint32_t* sum, uint8_t* elems) { elems[idx]++; if (elems[idx] < 255) { (*sum)++; @@ -142,7 +140,7 @@ static void inc_filter(uint8_t idx, uint32_t *sum, uint8_t *elems) { } } -static void add_header_data(framer_state *st, grpc_slice slice) { +static void add_header_data(framer_state* st, grpc_slice slice) { size_t len = GRPC_SLICE_LENGTH(slice); size_t remaining; if (len == 0) return; @@ -160,13 +158,13 @@ static void add_header_data(framer_state *st, grpc_slice slice) { } } -static uint8_t *add_tiny_header_data(framer_state *st, size_t len) { +static uint8_t* add_tiny_header_data(framer_state* st, size_t len) { ensure_space(st, len); st->stats->header_bytes += len; return grpc_slice_buffer_tiny_add(st->output, len); } -static void evict_entry(grpc_chttp2_hpack_compressor *c) { +static void evict_entry(grpc_chttp2_hpack_compressor* c) { c->tail_remote_index++; GPR_ASSERT(c->tail_remote_index > 0); GPR_ASSERT(c->table_size >= @@ -181,7 +179,7 @@ static void evict_entry(grpc_chttp2_hpack_compressor *c) { // Reserve space in table for the new element, evict entries if needed. // Return the new index of the element. Return 0 to indicate not adding to // table. -static uint32_t prepare_space_for_new_elem(grpc_chttp2_hpack_compressor *c, +static uint32_t prepare_space_for_new_elem(grpc_chttp2_hpack_compressor* c, size_t elem_size) { uint32_t new_index = c->tail_remote_index + c->table_elems + 1; GPR_ASSERT(elem_size < 65536); @@ -208,14 +206,14 @@ static uint32_t prepare_space_for_new_elem(grpc_chttp2_hpack_compressor *c, } /* dummy function */ -static void add_nothing(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_compressor *c, grpc_mdelem elem, +static void add_nothing(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_compressor* c, grpc_mdelem elem, size_t elem_size) {} // Add a key to the dynamic table. Both key and value will be added to table at // the decoder. -static void add_key_with_index(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_compressor *c, +static void add_key_with_index(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_compressor* c, grpc_mdelem elem, uint32_t new_index) { if (new_index == 0) { return; @@ -257,8 +255,8 @@ static void add_key_with_index(grpc_exec_ctx *exec_ctx, } /* add an element to the decoder table */ -static void add_elem_with_index(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_compressor *c, +static void add_elem_with_index(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_compressor* c, grpc_mdelem elem, uint32_t new_index) { if (new_index == 0) { return; @@ -301,21 +299,21 @@ static void add_elem_with_index(grpc_exec_ctx *exec_ctx, add_key_with_index(exec_ctx, c, elem, new_index); } -static void add_elem(grpc_exec_ctx *exec_ctx, grpc_chttp2_hpack_compressor *c, +static void add_elem(grpc_exec_ctx* exec_ctx, grpc_chttp2_hpack_compressor* c, grpc_mdelem elem, size_t elem_size) { uint32_t new_index = prepare_space_for_new_elem(c, elem_size); add_elem_with_index(exec_ctx, c, elem, new_index); } -static void add_key(grpc_exec_ctx *exec_ctx, grpc_chttp2_hpack_compressor *c, +static void add_key(grpc_exec_ctx* exec_ctx, grpc_chttp2_hpack_compressor* c, grpc_mdelem elem, size_t elem_size) { uint32_t new_index = prepare_space_for_new_elem(c, elem_size); add_key_with_index(exec_ctx, c, elem, new_index); } -static void emit_indexed(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_compressor *c, uint32_t elem_index, - framer_state *st) { +static void emit_indexed(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_compressor* c, uint32_t elem_index, + framer_state* st) { GRPC_STATS_INC_HPACK_SEND_INDEXED(exec_ctx); uint32_t len = GRPC_CHTTP2_VARINT_LENGTH(elem_index, 1); GRPC_CHTTP2_WRITE_VARINT(elem_index, 1, 0x80, add_tiny_header_data(st, len), @@ -328,7 +326,7 @@ typedef struct { bool insert_null_before_wire_value; } wire_value; -static wire_value get_wire_value(grpc_exec_ctx *exec_ctx, grpc_mdelem elem, +static wire_value get_wire_value(grpc_exec_ctx* exec_ctx, grpc_mdelem elem, bool true_binary_enabled) { wire_value wire_val; if (grpc_is_binary_header(GRPC_MDKEY(elem))) { @@ -359,15 +357,15 @@ static size_t wire_value_length(wire_value v) { return GPR_SLICE_LENGTH(v.data) + v.insert_null_before_wire_value; } -static void add_wire_value(framer_state *st, wire_value v) { +static void add_wire_value(framer_state* st, wire_value v) { if (v.insert_null_before_wire_value) *add_tiny_header_data(st, 1) = 0; add_header_data(st, v.data); } -static void emit_lithdr_incidx(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_compressor *c, +static void emit_lithdr_incidx(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_compressor* c, uint32_t key_index, grpc_mdelem elem, - framer_state *st) { + framer_state* st) { GRPC_STATS_INC_HPACK_SEND_LITHDR_INCIDX(exec_ctx); uint32_t len_pfx = GRPC_CHTTP2_VARINT_LENGTH(key_index, 2); wire_value value = @@ -383,10 +381,10 @@ static void emit_lithdr_incidx(grpc_exec_ctx *exec_ctx, add_wire_value(st, value); } -static void emit_lithdr_noidx(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_compressor *c, +static void emit_lithdr_noidx(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_compressor* c, uint32_t key_index, grpc_mdelem elem, - framer_state *st) { + framer_state* st) { GRPC_STATS_INC_HPACK_SEND_LITHDR_NOTIDX(exec_ctx); uint32_t len_pfx = GRPC_CHTTP2_VARINT_LENGTH(key_index, 4); wire_value value = @@ -402,10 +400,10 @@ static void emit_lithdr_noidx(grpc_exec_ctx *exec_ctx, add_wire_value(st, value); } -static void emit_lithdr_incidx_v(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_compressor *c, +static void emit_lithdr_incidx_v(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_compressor* c, uint32_t unused_index, grpc_mdelem elem, - framer_state *st) { + framer_state* st) { GPR_ASSERT(unused_index == 0); GRPC_STATS_INC_HPACK_SEND_LITHDR_INCIDX_V(exec_ctx); GRPC_STATS_INC_HPACK_SEND_UNCOMPRESSED(exec_ctx); @@ -426,10 +424,10 @@ static void emit_lithdr_incidx_v(grpc_exec_ctx *exec_ctx, add_wire_value(st, value); } -static void emit_lithdr_noidx_v(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_compressor *c, +static void emit_lithdr_noidx_v(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_compressor* c, uint32_t unused_index, grpc_mdelem elem, - framer_state *st) { + framer_state* st) { GPR_ASSERT(unused_index == 0); GRPC_STATS_INC_HPACK_SEND_LITHDR_NOTIDX_V(exec_ctx); GRPC_STATS_INC_HPACK_SEND_UNCOMPRESSED(exec_ctx); @@ -450,22 +448,22 @@ static void emit_lithdr_noidx_v(grpc_exec_ctx *exec_ctx, add_wire_value(st, value); } -static void emit_advertise_table_size_change(grpc_chttp2_hpack_compressor *c, - framer_state *st) { +static void emit_advertise_table_size_change(grpc_chttp2_hpack_compressor* c, + framer_state* st) { uint32_t len = GRPC_CHTTP2_VARINT_LENGTH(c->max_table_size, 3); GRPC_CHTTP2_WRITE_VARINT(c->max_table_size, 3, 0x20, add_tiny_header_data(st, len), len); c->advertise_table_size_change = 0; } -static uint32_t dynidx(grpc_chttp2_hpack_compressor *c, uint32_t elem_index) { +static uint32_t dynidx(grpc_chttp2_hpack_compressor* c, uint32_t elem_index) { return 1 + GRPC_CHTTP2_LAST_STATIC_ENTRY + c->tail_remote_index + c->table_elems - elem_index; } /* encode an mdelem */ -static void hpack_enc(grpc_exec_ctx *exec_ctx, grpc_chttp2_hpack_compressor *c, - grpc_mdelem elem, framer_state *st) { +static void hpack_enc(grpc_exec_ctx* exec_ctx, grpc_chttp2_hpack_compressor* c, + grpc_mdelem elem, framer_state* st) { GPR_ASSERT(GRPC_SLICE_LENGTH(GRPC_MDKEY(elem)) > 0); if (GRPC_SLICE_START_PTR(GRPC_MDKEY(elem))[0] != ':') { /* regular header */ st->seen_regular_header = 1; @@ -475,9 +473,9 @@ static void hpack_enc(grpc_exec_ctx *exec_ctx, grpc_chttp2_hpack_compressor *c, "Reserved header (colon-prefixed) happening after regular ones."); } - if (GRPC_TRACER_ON(grpc_http_trace)) { - char *k = grpc_slice_to_c_string(GRPC_MDKEY(elem)); - char *v = NULL; + if (grpc_http_trace.enabled()) { + char* k = grpc_slice_to_c_string(GRPC_MDKEY(elem)); + char* v = nullptr; if (grpc_is_binary_header(GRPC_MDKEY(elem))) { v = grpc_dump_slice(GRPC_MDVALUE(elem), GPR_DUMP_HEX); } else { @@ -540,11 +538,10 @@ static void hpack_enc(grpc_exec_ctx *exec_ctx, grpc_chttp2_hpack_compressor *c, decoder_space_usage < MAX_DECODER_SPACE_USAGE && c->filter_elems[HASH_FRAGMENT_1(elem_hash)] >= c->filter_elems_sum / ONE_ON_ADD_PROBABILITY; - void (*maybe_add)(grpc_exec_ctx *, grpc_chttp2_hpack_compressor *, - grpc_mdelem, size_t) = - should_add_elem ? add_elem : add_nothing; - void (*emit)(grpc_exec_ctx *, grpc_chttp2_hpack_compressor *, uint32_t, - grpc_mdelem, framer_state *) = + void (*maybe_add)(grpc_exec_ctx*, grpc_chttp2_hpack_compressor*, grpc_mdelem, + size_t) = should_add_elem ? add_elem : add_nothing; + void (*emit)(grpc_exec_ctx*, grpc_chttp2_hpack_compressor*, uint32_t, + grpc_mdelem, framer_state*) = should_add_elem ? emit_lithdr_incidx : emit_lithdr_noidx; /* no hits for the elem... maybe there's a key? */ @@ -582,9 +579,9 @@ static void hpack_enc(grpc_exec_ctx *exec_ctx, grpc_chttp2_hpack_compressor *c, #define STRLEN_LIT(x) (sizeof(x) - 1) #define TIMEOUT_KEY "grpc-timeout" -static void deadline_enc(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_compressor *c, grpc_millis deadline, - framer_state *st) { +static void deadline_enc(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_compressor* c, grpc_millis deadline, + framer_state* st) { char timeout_str[GRPC_HTTP2_TIMEOUT_ENCODE_MIN_BUFSIZE]; grpc_mdelem mdelem; grpc_http2_encode_timeout(deadline - grpc_exec_ctx_now(exec_ctx), @@ -597,14 +594,14 @@ static void deadline_enc(grpc_exec_ctx *exec_ctx, static uint32_t elems_for_bytes(uint32_t bytes) { return (bytes + 31) / 32; } -void grpc_chttp2_hpack_compressor_init(grpc_chttp2_hpack_compressor *c) { +void grpc_chttp2_hpack_compressor_init(grpc_chttp2_hpack_compressor* c) { memset(c, 0, sizeof(*c)); c->max_table_size = GRPC_CHTTP2_HPACKC_INITIAL_TABLE_SIZE; c->cap_table_elems = elems_for_bytes(c->max_table_size); c->max_table_elems = c->cap_table_elems; c->max_usable_size = GRPC_CHTTP2_HPACKC_INITIAL_TABLE_SIZE; c->table_elem_size = - (uint16_t *)gpr_malloc(sizeof(*c->table_elem_size) * c->cap_table_elems); + (uint16_t*)gpr_malloc(sizeof(*c->table_elem_size) * c->cap_table_elems); memset(c->table_elem_size, 0, sizeof(*c->table_elem_size) * c->cap_table_elems); for (size_t i = 0; i < GPR_ARRAY_SIZE(c->entries_keys); i++) { @@ -612,8 +609,8 @@ void grpc_chttp2_hpack_compressor_init(grpc_chttp2_hpack_compressor *c) { } } -void grpc_chttp2_hpack_compressor_destroy(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_compressor *c) { +void grpc_chttp2_hpack_compressor_destroy(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_compressor* c) { int i; for (i = 0; i < GRPC_CHTTP2_HPACKC_NUM_VALUES; i++) { if (c->entries_keys[i].refcount != &terminal_slice_refcount) { @@ -625,15 +622,15 @@ void grpc_chttp2_hpack_compressor_destroy(grpc_exec_ctx *exec_ctx, } void grpc_chttp2_hpack_compressor_set_max_usable_size( - grpc_chttp2_hpack_compressor *c, uint32_t max_table_size) { + grpc_chttp2_hpack_compressor* c, uint32_t max_table_size) { c->max_usable_size = max_table_size; grpc_chttp2_hpack_compressor_set_max_table_size( c, GPR_MIN(c->max_table_size, max_table_size)); } -static void rebuild_elems(grpc_chttp2_hpack_compressor *c, uint32_t new_cap) { - uint16_t *table_elem_size = - (uint16_t *)gpr_malloc(sizeof(*table_elem_size) * new_cap); +static void rebuild_elems(grpc_chttp2_hpack_compressor* c, uint32_t new_cap) { + uint16_t* table_elem_size = + (uint16_t*)gpr_malloc(sizeof(*table_elem_size) * new_cap); uint32_t i; memset(table_elem_size, 0, sizeof(*table_elem_size) * new_cap); @@ -651,7 +648,7 @@ static void rebuild_elems(grpc_chttp2_hpack_compressor *c, uint32_t new_cap) { } void grpc_chttp2_hpack_compressor_set_max_table_size( - grpc_chttp2_hpack_compressor *c, uint32_t max_table_size) { + grpc_chttp2_hpack_compressor* c, uint32_t max_table_size) { max_table_size = GPR_MIN(max_table_size, c->max_usable_size); if (max_table_size == c->max_table_size) { return; @@ -670,18 +667,18 @@ void grpc_chttp2_hpack_compressor_set_max_table_size( } } c->advertise_table_size_change = 1; - if (GRPC_TRACER_ON(grpc_http_trace)) { + if (grpc_http_trace.enabled()) { gpr_log(GPR_DEBUG, "set max table size from encoder to %d", max_table_size); } } -void grpc_chttp2_encode_header(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_compressor *c, - grpc_mdelem **extra_headers, +void grpc_chttp2_encode_header(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_compressor* c, + grpc_mdelem** extra_headers, size_t extra_headers_size, - grpc_metadata_batch *metadata, - const grpc_encode_header_options *options, - grpc_slice_buffer *outbuf) { + grpc_metadata_batch* metadata, + const grpc_encode_header_options* options, + grpc_slice_buffer* outbuf) { GPR_ASSERT(options->stream_id != 0); framer_state st; @@ -705,7 +702,7 @@ void grpc_chttp2_encode_header(grpc_exec_ctx *exec_ctx, hpack_enc(exec_ctx, c, *extra_headers[i], &st); } grpc_metadata_batch_assert_ok(metadata); - for (grpc_linked_mdelem *l = metadata->list.head; l; l = l->next) { + for (grpc_linked_mdelem* l = metadata->list.head; l; l = l->next) { hpack_enc(exec_ctx, c, l->md, &st); } grpc_millis deadline = metadata->deadline; diff --git a/src/core/ext/transport/chttp2/transport/hpack_encoder.h b/src/core/ext/transport/chttp2/transport/hpack_encoder.h index 16316b63f7c..08921b19ec7 100644 --- a/src/core/ext/transport/chttp2/transport/hpack_encoder.h +++ b/src/core/ext/transport/chttp2/transport/hpack_encoder.h @@ -34,9 +34,7 @@ /* maximum table size we'll actually use */ #define GRPC_CHTTP2_HPACKC_MAX_TABLE_SIZE (1024 * 1024) -#ifdef __cplusplus -extern "C" { -#endif +extern grpc_core::TraceFlag grpc_http_trace; typedef struct { uint32_t filter_elems_sum; @@ -68,35 +66,31 @@ typedef struct { uint32_t indices_keys[GRPC_CHTTP2_HPACKC_NUM_VALUES]; uint32_t indices_elems[GRPC_CHTTP2_HPACKC_NUM_VALUES]; - uint16_t *table_elem_size; + uint16_t* table_elem_size; } grpc_chttp2_hpack_compressor; -void grpc_chttp2_hpack_compressor_init(grpc_chttp2_hpack_compressor *c); -void grpc_chttp2_hpack_compressor_destroy(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_compressor *c); +void grpc_chttp2_hpack_compressor_init(grpc_chttp2_hpack_compressor* c); +void grpc_chttp2_hpack_compressor_destroy(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_compressor* c); void grpc_chttp2_hpack_compressor_set_max_table_size( - grpc_chttp2_hpack_compressor *c, uint32_t max_table_size); + grpc_chttp2_hpack_compressor* c, uint32_t max_table_size); void grpc_chttp2_hpack_compressor_set_max_usable_size( - grpc_chttp2_hpack_compressor *c, uint32_t max_table_size); + grpc_chttp2_hpack_compressor* c, uint32_t max_table_size); typedef struct { uint32_t stream_id; bool is_eof; bool use_true_binary_metadata; size_t max_frame_size; - grpc_transport_one_way_stats *stats; + grpc_transport_one_way_stats* stats; } grpc_encode_header_options; -void grpc_chttp2_encode_header(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_compressor *c, - grpc_mdelem **extra_headers, +void grpc_chttp2_encode_header(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_compressor* c, + grpc_mdelem** extra_headers, size_t extra_headers_size, - grpc_metadata_batch *metadata, - const grpc_encode_header_options *options, - grpc_slice_buffer *outbuf); - -#ifdef __cplusplus -} -#endif + grpc_metadata_batch* metadata, + const grpc_encode_header_options* options, + grpc_slice_buffer* outbuf); #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HPACK_ENCODER_H */ diff --git a/src/core/ext/transport/chttp2/transport/hpack_parser.cc b/src/core/ext/transport/chttp2/transport/hpack_parser.cc index 7c172291224..18cb27f199c 100644 --- a/src/core/ext/transport/chttp2/transport/hpack_parser.cc +++ b/src/core/ext/transport/chttp2/transport/hpack_parser.cc @@ -61,97 +61,97 @@ typedef enum { a set of indirect jumps, and so not waste stack space. */ /* forward declarations for parsing states */ -static grpc_error *parse_begin(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end); -static grpc_error *parse_error(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end, grpc_error *error); -static grpc_error *still_parse_error(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end); -static grpc_error *parse_illegal_op(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end); - -static grpc_error *parse_string_prefix(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end); -static grpc_error *parse_key_string(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end); -static grpc_error *parse_value_string_with_indexed_key( - grpc_exec_ctx *exec_ctx, grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end); -static grpc_error *parse_value_string_with_literal_key( - grpc_exec_ctx *exec_ctx, grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end); - -static grpc_error *parse_value0(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end); -static grpc_error *parse_value1(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end); -static grpc_error *parse_value2(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end); -static grpc_error *parse_value3(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end); -static grpc_error *parse_value4(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end); -static grpc_error *parse_value5up(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end); - -static grpc_error *parse_indexed_field(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end); -static grpc_error *parse_indexed_field_x(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end); -static grpc_error *parse_lithdr_incidx(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end); -static grpc_error *parse_lithdr_incidx_x(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end); -static grpc_error *parse_lithdr_incidx_v(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end); -static grpc_error *parse_lithdr_notidx(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end); -static grpc_error *parse_lithdr_notidx_x(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end); -static grpc_error *parse_lithdr_notidx_v(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end); -static grpc_error *parse_lithdr_nvridx(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end); -static grpc_error *parse_lithdr_nvridx_x(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end); -static grpc_error *parse_lithdr_nvridx_v(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end); -static grpc_error *parse_max_tbl_size(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end); -static grpc_error *parse_max_tbl_size_x(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end); +static grpc_error* parse_begin(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end); +static grpc_error* parse_error(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end, grpc_error* error); +static grpc_error* still_parse_error(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end); +static grpc_error* parse_illegal_op(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end); + +static grpc_error* parse_string_prefix(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end); +static grpc_error* parse_key_string(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end); +static grpc_error* parse_value_string_with_indexed_key( + grpc_exec_ctx* exec_ctx, grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end); +static grpc_error* parse_value_string_with_literal_key( + grpc_exec_ctx* exec_ctx, grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end); + +static grpc_error* parse_value0(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end); +static grpc_error* parse_value1(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end); +static grpc_error* parse_value2(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end); +static grpc_error* parse_value3(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end); +static grpc_error* parse_value4(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end); +static grpc_error* parse_value5up(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end); + +static grpc_error* parse_indexed_field(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end); +static grpc_error* parse_indexed_field_x(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end); +static grpc_error* parse_lithdr_incidx(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end); +static grpc_error* parse_lithdr_incidx_x(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end); +static grpc_error* parse_lithdr_incidx_v(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end); +static grpc_error* parse_lithdr_notidx(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end); +static grpc_error* parse_lithdr_notidx_x(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end); +static grpc_error* parse_lithdr_notidx_v(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end); +static grpc_error* parse_lithdr_nvridx(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end); +static grpc_error* parse_lithdr_nvridx_x(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end); +static grpc_error* parse_lithdr_nvridx_v(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end); +static grpc_error* parse_max_tbl_size(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end); +static grpc_error* parse_max_tbl_size_x(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end); /* we translate the first byte of a hpack field into one of these decoding cases, then use a lookup table to jump directly to the appropriate parser. @@ -649,11 +649,11 @@ static const uint8_t inverse_base64[256] = { }; /* emission helpers */ -static grpc_error *on_hdr(grpc_exec_ctx *exec_ctx, grpc_chttp2_hpack_parser *p, +static grpc_error* on_hdr(grpc_exec_ctx* exec_ctx, grpc_chttp2_hpack_parser* p, grpc_mdelem md, int add_to_table) { - if (GRPC_TRACER_ON(grpc_http_trace)) { - char *k = grpc_slice_to_c_string(GRPC_MDKEY(md)); - char *v = NULL; + if (grpc_http_trace.enabled()) { + char* k = grpc_slice_to_c_string(GRPC_MDKEY(md)); + char* v = nullptr; if (grpc_is_binary_header(GRPC_MDKEY(md))) { v = grpc_dump_slice(GRPC_MDVALUE(md), GPR_DUMP_HEX); } else { @@ -671,10 +671,10 @@ static grpc_error *on_hdr(grpc_exec_ctx *exec_ctx, grpc_chttp2_hpack_parser *p, if (add_to_table) { GPR_ASSERT(GRPC_MDELEM_STORAGE(md) == GRPC_MDELEM_STORAGE_INTERNED || GRPC_MDELEM_STORAGE(md) == GRPC_MDELEM_STORAGE_STATIC); - grpc_error *err = grpc_chttp2_hptbl_add(exec_ctx, &p->table, md); + grpc_error* err = grpc_chttp2_hptbl_add(exec_ctx, &p->table, md); if (err != GRPC_ERROR_NONE) return err; } - if (p->on_header == NULL) { + if (p->on_header == nullptr) { GRPC_MDELEM_UNREF(exec_ctx, md); return GRPC_ERROR_CREATE_FROM_STATIC_STRING("on_header callback not set"); } @@ -682,9 +682,9 @@ static grpc_error *on_hdr(grpc_exec_ctx *exec_ctx, grpc_chttp2_hpack_parser *p, return GRPC_ERROR_NONE; } -static grpc_slice take_string(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - grpc_chttp2_hpack_parser_string *str, +static grpc_slice take_string(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + grpc_chttp2_hpack_parser_string* str, bool intern) { grpc_slice s; if (!str->copied) { @@ -708,18 +708,18 @@ static grpc_slice take_string(grpc_exec_ctx *exec_ctx, } /* jump to the next state */ -static grpc_error *parse_next(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_next(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end) { p->state = *p->next_state++; return p->state(exec_ctx, p, cur, end); } /* begin parsing a header: all functionality is encoded into lookup tables above */ -static grpc_error *parse_begin(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_begin(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end) { if (cur == end) { p->state = parse_begin; return GRPC_ERROR_NONE; @@ -729,9 +729,9 @@ static grpc_error *parse_begin(grpc_exec_ctx *exec_ctx, } /* stream dependency and prioritization data: we just skip it */ -static grpc_error *parse_stream_weight(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* parse_stream_weight(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { if (cur == end) { p->state = parse_stream_weight; return GRPC_ERROR_NONE; @@ -740,9 +740,9 @@ static grpc_error *parse_stream_weight(grpc_exec_ctx *exec_ctx, return p->after_prioritization(exec_ctx, p, cur + 1, end); } -static grpc_error *parse_stream_dep3(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* parse_stream_dep3(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { if (cur == end) { p->state = parse_stream_dep3; return GRPC_ERROR_NONE; @@ -751,9 +751,9 @@ static grpc_error *parse_stream_dep3(grpc_exec_ctx *exec_ctx, return parse_stream_weight(exec_ctx, p, cur + 1, end); } -static grpc_error *parse_stream_dep2(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* parse_stream_dep2(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { if (cur == end) { p->state = parse_stream_dep2; return GRPC_ERROR_NONE; @@ -762,9 +762,9 @@ static grpc_error *parse_stream_dep2(grpc_exec_ctx *exec_ctx, return parse_stream_dep3(exec_ctx, p, cur + 1, end); } -static grpc_error *parse_stream_dep1(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* parse_stream_dep1(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { if (cur == end) { p->state = parse_stream_dep1; return GRPC_ERROR_NONE; @@ -773,9 +773,9 @@ static grpc_error *parse_stream_dep1(grpc_exec_ctx *exec_ctx, return parse_stream_dep2(exec_ctx, p, cur + 1, end); } -static grpc_error *parse_stream_dep0(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* parse_stream_dep0(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { if (cur == end) { p->state = parse_stream_dep0; return GRPC_ERROR_NONE; @@ -785,10 +785,10 @@ static grpc_error *parse_stream_dep0(grpc_exec_ctx *exec_ctx, } /* emit an indexed field; jumps to begin the next field on completion */ -static grpc_error *finish_indexed_field(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end) { +static grpc_error* finish_indexed_field(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end) { grpc_mdelem md = grpc_chttp2_hptbl_lookup(&p->table, p->index); if (GRPC_MDISNULL(md)) { return grpc_error_set_int( @@ -799,25 +799,25 @@ static grpc_error *finish_indexed_field(grpc_exec_ctx *exec_ctx, } GRPC_MDELEM_REF(md); GRPC_STATS_INC_HPACK_RECV_INDEXED(exec_ctx); - grpc_error *err = on_hdr(exec_ctx, p, md, 0); + grpc_error* err = on_hdr(exec_ctx, p, md, 0); if (err != GRPC_ERROR_NONE) return err; return parse_begin(exec_ctx, p, cur, end); } /* parse an indexed field with index < 127 */ -static grpc_error *parse_indexed_field(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* parse_indexed_field(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { p->dynamic_table_update_allowed = 0; p->index = (*cur) & 0x7f; return finish_indexed_field(exec_ctx, p, cur + 1, end); } /* parse an indexed field with index >= 127 */ -static grpc_error *parse_indexed_field_x(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_indexed_field_x(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end) { static const grpc_chttp2_hpack_parser_state and_then[] = { finish_indexed_field}; p->dynamic_table_update_allowed = 0; @@ -828,14 +828,14 @@ static grpc_error *parse_indexed_field_x(grpc_exec_ctx *exec_ctx, } /* finish a literal header with incremental indexing */ -static grpc_error *finish_lithdr_incidx(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end) { +static grpc_error* finish_lithdr_incidx(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end) { grpc_mdelem md = grpc_chttp2_hptbl_lookup(&p->table, p->index); GPR_ASSERT(!GRPC_MDISNULL(md)); /* handled in string parsing */ GRPC_STATS_INC_HPACK_RECV_LITHDR_INCIDX(exec_ctx); - grpc_error *err = on_hdr( + grpc_error* err = on_hdr( exec_ctx, p, grpc_mdelem_from_slices(exec_ctx, grpc_slice_ref_internal(GRPC_MDKEY(md)), take_string(exec_ctx, p, &p->value, true)), @@ -845,12 +845,12 @@ static grpc_error *finish_lithdr_incidx(grpc_exec_ctx *exec_ctx, } /* finish a literal header with incremental indexing with no index */ -static grpc_error *finish_lithdr_incidx_v(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end) { +static grpc_error* finish_lithdr_incidx_v(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end) { GRPC_STATS_INC_HPACK_RECV_LITHDR_INCIDX_V(exec_ctx); - grpc_error *err = on_hdr( + grpc_error* err = on_hdr( exec_ctx, p, grpc_mdelem_from_slices(exec_ctx, take_string(exec_ctx, p, &p->key, true), take_string(exec_ctx, p, &p->value, true)), @@ -860,9 +860,9 @@ static grpc_error *finish_lithdr_incidx_v(grpc_exec_ctx *exec_ctx, } /* parse a literal header with incremental indexing; index < 63 */ -static grpc_error *parse_lithdr_incidx(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* parse_lithdr_incidx(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { static const grpc_chttp2_hpack_parser_state and_then[] = { parse_value_string_with_indexed_key, finish_lithdr_incidx}; p->dynamic_table_update_allowed = 0; @@ -872,10 +872,10 @@ static grpc_error *parse_lithdr_incidx(grpc_exec_ctx *exec_ctx, } /* parse a literal header with incremental indexing; index >= 63 */ -static grpc_error *parse_lithdr_incidx_x(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_lithdr_incidx_x(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end) { static const grpc_chttp2_hpack_parser_state and_then[] = { parse_string_prefix, parse_value_string_with_indexed_key, finish_lithdr_incidx}; @@ -887,10 +887,10 @@ static grpc_error *parse_lithdr_incidx_x(grpc_exec_ctx *exec_ctx, } /* parse a literal header with incremental indexing; index = 0 */ -static grpc_error *parse_lithdr_incidx_v(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_lithdr_incidx_v(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end) { static const grpc_chttp2_hpack_parser_state and_then[] = { parse_key_string, parse_string_prefix, parse_value_string_with_literal_key, finish_lithdr_incidx_v}; @@ -900,14 +900,14 @@ static grpc_error *parse_lithdr_incidx_v(grpc_exec_ctx *exec_ctx, } /* finish a literal header without incremental indexing */ -static grpc_error *finish_lithdr_notidx(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end) { +static grpc_error* finish_lithdr_notidx(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end) { grpc_mdelem md = grpc_chttp2_hptbl_lookup(&p->table, p->index); GPR_ASSERT(!GRPC_MDISNULL(md)); /* handled in string parsing */ GRPC_STATS_INC_HPACK_RECV_LITHDR_NOTIDX(exec_ctx); - grpc_error *err = on_hdr( + grpc_error* err = on_hdr( exec_ctx, p, grpc_mdelem_from_slices(exec_ctx, grpc_slice_ref_internal(GRPC_MDKEY(md)), take_string(exec_ctx, p, &p->value, false)), @@ -917,12 +917,12 @@ static grpc_error *finish_lithdr_notidx(grpc_exec_ctx *exec_ctx, } /* finish a literal header without incremental indexing with index = 0 */ -static grpc_error *finish_lithdr_notidx_v(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end) { +static grpc_error* finish_lithdr_notidx_v(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end) { GRPC_STATS_INC_HPACK_RECV_LITHDR_NOTIDX_V(exec_ctx); - grpc_error *err = on_hdr( + grpc_error* err = on_hdr( exec_ctx, p, grpc_mdelem_from_slices(exec_ctx, take_string(exec_ctx, p, &p->key, true), take_string(exec_ctx, p, &p->value, false)), @@ -932,9 +932,9 @@ static grpc_error *finish_lithdr_notidx_v(grpc_exec_ctx *exec_ctx, } /* parse a literal header without incremental indexing; index < 15 */ -static grpc_error *parse_lithdr_notidx(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* parse_lithdr_notidx(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { static const grpc_chttp2_hpack_parser_state and_then[] = { parse_value_string_with_indexed_key, finish_lithdr_notidx}; p->dynamic_table_update_allowed = 0; @@ -944,10 +944,10 @@ static grpc_error *parse_lithdr_notidx(grpc_exec_ctx *exec_ctx, } /* parse a literal header without incremental indexing; index >= 15 */ -static grpc_error *parse_lithdr_notidx_x(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_lithdr_notidx_x(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end) { static const grpc_chttp2_hpack_parser_state and_then[] = { parse_string_prefix, parse_value_string_with_indexed_key, finish_lithdr_notidx}; @@ -959,10 +959,10 @@ static grpc_error *parse_lithdr_notidx_x(grpc_exec_ctx *exec_ctx, } /* parse a literal header without incremental indexing; index == 0 */ -static grpc_error *parse_lithdr_notidx_v(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_lithdr_notidx_v(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end) { static const grpc_chttp2_hpack_parser_state and_then[] = { parse_key_string, parse_string_prefix, parse_value_string_with_literal_key, finish_lithdr_notidx_v}; @@ -972,14 +972,14 @@ static grpc_error *parse_lithdr_notidx_v(grpc_exec_ctx *exec_ctx, } /* finish a literal header that is never indexed */ -static grpc_error *finish_lithdr_nvridx(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end) { +static grpc_error* finish_lithdr_nvridx(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end) { grpc_mdelem md = grpc_chttp2_hptbl_lookup(&p->table, p->index); GPR_ASSERT(!GRPC_MDISNULL(md)); /* handled in string parsing */ GRPC_STATS_INC_HPACK_RECV_LITHDR_NVRIDX(exec_ctx); - grpc_error *err = on_hdr( + grpc_error* err = on_hdr( exec_ctx, p, grpc_mdelem_from_slices(exec_ctx, grpc_slice_ref_internal(GRPC_MDKEY(md)), take_string(exec_ctx, p, &p->value, false)), @@ -989,12 +989,12 @@ static grpc_error *finish_lithdr_nvridx(grpc_exec_ctx *exec_ctx, } /* finish a literal header that is never indexed with an extra value */ -static grpc_error *finish_lithdr_nvridx_v(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end) { +static grpc_error* finish_lithdr_nvridx_v(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end) { GRPC_STATS_INC_HPACK_RECV_LITHDR_NVRIDX_V(exec_ctx); - grpc_error *err = on_hdr( + grpc_error* err = on_hdr( exec_ctx, p, grpc_mdelem_from_slices(exec_ctx, take_string(exec_ctx, p, &p->key, true), take_string(exec_ctx, p, &p->value, false)), @@ -1004,9 +1004,9 @@ static grpc_error *finish_lithdr_nvridx_v(grpc_exec_ctx *exec_ctx, } /* parse a literal header that is never indexed; index < 15 */ -static grpc_error *parse_lithdr_nvridx(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* parse_lithdr_nvridx(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { static const grpc_chttp2_hpack_parser_state and_then[] = { parse_value_string_with_indexed_key, finish_lithdr_nvridx}; p->dynamic_table_update_allowed = 0; @@ -1016,10 +1016,10 @@ static grpc_error *parse_lithdr_nvridx(grpc_exec_ctx *exec_ctx, } /* parse a literal header that is never indexed; index >= 15 */ -static grpc_error *parse_lithdr_nvridx_x(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_lithdr_nvridx_x(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end) { static const grpc_chttp2_hpack_parser_state and_then[] = { parse_string_prefix, parse_value_string_with_indexed_key, finish_lithdr_nvridx}; @@ -1031,10 +1031,10 @@ static grpc_error *parse_lithdr_nvridx_x(grpc_exec_ctx *exec_ctx, } /* parse a literal header that is never indexed; index == 0 */ -static grpc_error *parse_lithdr_nvridx_v(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_lithdr_nvridx_v(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end) { static const grpc_chttp2_hpack_parser_state and_then[] = { parse_key_string, parse_string_prefix, parse_value_string_with_literal_key, finish_lithdr_nvridx_v}; @@ -1044,22 +1044,22 @@ static grpc_error *parse_lithdr_nvridx_v(grpc_exec_ctx *exec_ctx, } /* finish parsing a max table size change */ -static grpc_error *finish_max_tbl_size(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { - if (GRPC_TRACER_ON(grpc_http_trace)) { +static grpc_error* finish_max_tbl_size(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { + if (grpc_http_trace.enabled()) { gpr_log(GPR_INFO, "MAX TABLE SIZE: %d", p->index); } - grpc_error *err = + grpc_error* err = grpc_chttp2_hptbl_set_current_table_size(exec_ctx, &p->table, p->index); if (err != GRPC_ERROR_NONE) return parse_error(exec_ctx, p, cur, end, err); return parse_begin(exec_ctx, p, cur, end); } /* parse a max table size change, max size < 15 */ -static grpc_error *parse_max_tbl_size(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* parse_max_tbl_size(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { if (p->dynamic_table_update_allowed == 0) { return parse_error( exec_ctx, p, cur, end, @@ -1072,10 +1072,10 @@ static grpc_error *parse_max_tbl_size(grpc_exec_ctx *exec_ctx, } /* parse a max table size change, max size >= 15 */ -static grpc_error *parse_max_tbl_size_x(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_max_tbl_size_x(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, + const uint8_t* end) { static const grpc_chttp2_hpack_parser_state and_then[] = { finish_max_tbl_size}; if (p->dynamic_table_update_allowed == 0) { @@ -1092,9 +1092,9 @@ static grpc_error *parse_max_tbl_size_x(grpc_exec_ctx *exec_ctx, } /* a parse error: jam the parse state into parse_error, and return error */ -static grpc_error *parse_error(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end, grpc_error *err) { +static grpc_error* parse_error(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end, grpc_error* err) { GPR_ASSERT(err != GRPC_ERROR_NONE); if (p->last_error == GRPC_ERROR_NONE) { p->last_error = GRPC_ERROR_REF(err); @@ -1103,28 +1103,28 @@ static grpc_error *parse_error(grpc_exec_ctx *exec_ctx, return err; } -static grpc_error *still_parse_error(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* still_parse_error(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { return GRPC_ERROR_REF(p->last_error); } -static grpc_error *parse_illegal_op(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* parse_illegal_op(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { GPR_ASSERT(cur != end); - char *msg; + char* msg; gpr_asprintf(&msg, "Illegal hpack op code %d", *cur); - grpc_error *err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return parse_error(exec_ctx, p, cur, end, err); } /* parse the 1st byte of a varint into p->parsing.value no overflow is possible */ -static grpc_error *parse_value0(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_value0(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end) { if (cur == end) { p->state = parse_value0; return GRPC_ERROR_NONE; @@ -1141,9 +1141,9 @@ static grpc_error *parse_value0(grpc_exec_ctx *exec_ctx, /* parse the 2nd byte of a varint into p->parsing.value no overflow is possible */ -static grpc_error *parse_value1(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_value1(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end) { if (cur == end) { p->state = parse_value1; return GRPC_ERROR_NONE; @@ -1160,9 +1160,9 @@ static grpc_error *parse_value1(grpc_exec_ctx *exec_ctx, /* parse the 3rd byte of a varint into p->parsing.value no overflow is possible */ -static grpc_error *parse_value2(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_value2(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end) { if (cur == end) { p->state = parse_value2; return GRPC_ERROR_NONE; @@ -1179,9 +1179,9 @@ static grpc_error *parse_value2(grpc_exec_ctx *exec_ctx, /* parse the 4th byte of a varint into p->parsing.value no overflow is possible */ -static grpc_error *parse_value3(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_value3(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end) { if (cur == end) { p->state = parse_value3; return GRPC_ERROR_NONE; @@ -1198,13 +1198,13 @@ static grpc_error *parse_value3(grpc_exec_ctx *exec_ctx, /* parse the 5th byte of a varint into p->parsing.value depending on the byte, we may overflow, and care must be taken */ -static grpc_error *parse_value4(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_value4(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end) { uint8_t c; uint32_t cur_value; uint32_t add_value; - char *msg; + char* msg; if (cur == end) { p->state = parse_value4; @@ -1235,7 +1235,7 @@ error: "integer overflow in hpack integer decoding: have 0x%08x, " "got byte 0x%02x on byte 5", *p->parsing.value, *cur); - grpc_error *err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return parse_error(exec_ctx, p, cur, end, err); } @@ -1243,9 +1243,9 @@ error: /* parse any trailing bytes in a varint: it's possible to append an arbitrary number of 0x80's and not affect the value - a zero will terminate - and anything else will overflow */ -static grpc_error *parse_value5up(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* parse_value5up(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { while (cur != end && *cur == 0x80) { ++cur; } @@ -1259,20 +1259,20 @@ static grpc_error *parse_value5up(grpc_exec_ctx *exec_ctx, return parse_next(exec_ctx, p, cur + 1, end); } - char *msg; + char* msg; gpr_asprintf(&msg, "integer overflow in hpack integer decoding: have 0x%08x, " "got byte 0x%02x sometime after byte 5", *p->parsing.value, *cur); - grpc_error *err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return parse_error(exec_ctx, p, cur, end, err); } /* parse a string prefix */ -static grpc_error *parse_string_prefix(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* parse_string_prefix(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { if (cur == end) { p->state = parse_string_prefix; return GRPC_ERROR_NONE; @@ -1289,24 +1289,24 @@ static grpc_error *parse_string_prefix(grpc_exec_ctx *exec_ctx, } /* append some bytes to a string */ -static void append_bytes(grpc_chttp2_hpack_parser_string *str, - const uint8_t *data, size_t length) { +static void append_bytes(grpc_chttp2_hpack_parser_string* str, + const uint8_t* data, size_t length) { if (length == 0) return; if (length + str->data.copied.length > str->data.copied.capacity) { GPR_ASSERT(str->data.copied.length + length <= UINT32_MAX); str->data.copied.capacity = (uint32_t)(str->data.copied.length + length); str->data.copied.str = - (char *)gpr_realloc(str->data.copied.str, str->data.copied.capacity); + (char*)gpr_realloc(str->data.copied.str, str->data.copied.capacity); } memcpy(str->data.copied.str + str->data.copied.length, data, length); GPR_ASSERT(length <= UINT32_MAX - str->data.copied.length); str->data.copied.length += (uint32_t)length; } -static grpc_error *append_string(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { - grpc_chttp2_hpack_parser_string *str = p->parsing.str; +static grpc_error* append_string(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { + grpc_chttp2_hpack_parser_string* str = p->parsing.str; uint32_t bits; uint8_t decoded[3]; switch ((binary_state)p->binary) { @@ -1403,12 +1403,12 @@ static grpc_error *append_string(grpc_exec_ctx *exec_ctx, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Should never reach here"))); } -static grpc_error *finish_str(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end) { +static grpc_error* finish_str(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end) { uint8_t decoded[2]; uint32_t bits; - grpc_chttp2_hpack_parser_string *str = p->parsing.str; + grpc_chttp2_hpack_parser_string* str = p->parsing.str; switch ((binary_state)p->binary) { case NOT_BINARY: break; @@ -1423,10 +1423,10 @@ static grpc_error *finish_str(grpc_exec_ctx *exec_ctx, case B64_BYTE2: bits = p->base64_buffer; if (bits & 0xffff) { - char *msg; + char* msg; gpr_asprintf(&msg, "trailing bits in base64 encoding: 0x%04x", bits & 0xffff); - grpc_error *err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return parse_error(exec_ctx, p, cur, end, err); } @@ -1436,10 +1436,10 @@ static grpc_error *finish_str(grpc_exec_ctx *exec_ctx, case B64_BYTE3: bits = p->base64_buffer; if (bits & 0xff) { - char *msg; + char* msg; gpr_asprintf(&msg, "trailing bits in base64 encoding: 0x%02x", bits & 0xff); - grpc_error *err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return parse_error(exec_ctx, p, cur, end, err); } @@ -1452,14 +1452,14 @@ static grpc_error *finish_str(grpc_exec_ctx *exec_ctx, } /* decode a nibble from a huffman encoded stream */ -static grpc_error *huff_nibble(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, uint8_t nibble) { +static grpc_error* huff_nibble(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, uint8_t nibble) { int16_t emit = emit_sub_tbl[16 * emit_tbl[p->huff_state] + nibble]; int16_t next = next_sub_tbl[16 * next_tbl[p->huff_state] + nibble]; if (emit != -1) { if (emit >= 0 && emit < 256) { uint8_t c = (uint8_t)emit; - grpc_error *err = append_string(exec_ctx, p, &c, (&c) + 1); + grpc_error* err = append_string(exec_ctx, p, &c, (&c) + 1); if (err != GRPC_ERROR_NONE) return err; } else { assert(emit == 256); @@ -1470,11 +1470,11 @@ static grpc_error *huff_nibble(grpc_exec_ctx *exec_ctx, } /* decode full bytes from a huffman encoded stream */ -static grpc_error *add_huff_bytes(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* add_huff_bytes(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { for (; cur != end; ++cur) { - grpc_error *err = huff_nibble(exec_ctx, p, *cur >> 4); + grpc_error* err = huff_nibble(exec_ctx, p, *cur >> 4); if (err != GRPC_ERROR_NONE) return parse_error(exec_ctx, p, cur, end, err); err = huff_nibble(exec_ctx, p, *cur & 0xf); if (err != GRPC_ERROR_NONE) return parse_error(exec_ctx, p, cur, end, err); @@ -1484,9 +1484,9 @@ static grpc_error *add_huff_bytes(grpc_exec_ctx *exec_ctx, /* decode some string bytes based on the current decoding mode (huffman or not) */ -static grpc_error *add_str_bytes(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* add_str_bytes(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { if (p->huff) { return add_huff_bytes(exec_ctx, p, cur, end); } else { @@ -1495,19 +1495,19 @@ static grpc_error *add_str_bytes(grpc_exec_ctx *exec_ctx, } /* parse a string - tries to do large chunks at a time */ -static grpc_error *parse_string(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_string(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end) { size_t remaining = p->strlen - p->strgot; size_t given = (size_t)(end - cur); if (remaining <= given) { - grpc_error *err = add_str_bytes(exec_ctx, p, cur, cur + remaining); + grpc_error* err = add_str_bytes(exec_ctx, p, cur, cur + remaining); if (err != GRPC_ERROR_NONE) return parse_error(exec_ctx, p, cur, end, err); err = finish_str(exec_ctx, p, cur + remaining, end); if (err != GRPC_ERROR_NONE) return parse_error(exec_ctx, p, cur, end, err); return parse_next(exec_ctx, p, cur + remaining, end); } else { - grpc_error *err = add_str_bytes(exec_ctx, p, cur, cur + given); + grpc_error* err = add_str_bytes(exec_ctx, p, cur, cur + given); if (err != GRPC_ERROR_NONE) return parse_error(exec_ctx, p, cur, end, err); GPR_ASSERT(given <= UINT32_MAX - p->strgot); p->strgot += (uint32_t)given; @@ -1517,17 +1517,17 @@ static grpc_error *parse_string(grpc_exec_ctx *exec_ctx, } /* begin parsing a string - performs setup, calls parse_string */ -static grpc_error *begin_parse_string(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end, +static grpc_error* begin_parse_string(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end, uint8_t binary, - grpc_chttp2_hpack_parser_string *str) { + grpc_chttp2_hpack_parser_string* str) { if (!p->huff && binary == NOT_BINARY && (end - cur) >= (intptr_t)p->strlen && - p->current_slice_refcount != NULL) { + p->current_slice_refcount != nullptr) { GRPC_STATS_INC_HPACK_RECV_UNCOMPRESSED(exec_ctx); str->copied = false; str->data.referenced.refcount = p->current_slice_refcount; - str->data.referenced.data.refcounted.bytes = (uint8_t *)cur; + str->data.referenced.data.refcounted.bytes = (uint8_t*)cur; str->data.referenced.data.refcounted.length = p->strlen; grpc_slice_ref_internal(str->data.referenced); return parse_next(exec_ctx, p, cur + p->strlen, end); @@ -1556,23 +1556,23 @@ static grpc_error *begin_parse_string(grpc_exec_ctx *exec_ctx, } /* parse the key string */ -static grpc_error *parse_key_string(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end) { +static grpc_error* parse_key_string(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end) { return begin_parse_string(exec_ctx, p, cur, end, NOT_BINARY, &p->key); } /* check if a key represents a binary header or not */ -static bool is_binary_literal_header(grpc_chttp2_hpack_parser *p) { +static bool is_binary_literal_header(grpc_chttp2_hpack_parser* p) { return grpc_is_binary_header( p->key.copied ? grpc_slice_from_static_buffer(p->key.data.copied.str, p->key.data.copied.length) : p->key.data.referenced); } -static grpc_error *is_binary_indexed_header(grpc_chttp2_hpack_parser *p, - bool *is) { +static grpc_error* is_binary_indexed_header(grpc_chttp2_hpack_parser* p, + bool* is) { grpc_mdelem elem = grpc_chttp2_hptbl_lookup(&p->table, p->index); if (GRPC_MDISNULL(elem)) { return grpc_error_set_int( @@ -1586,42 +1586,42 @@ static grpc_error *is_binary_indexed_header(grpc_chttp2_hpack_parser *p, } /* parse the value string */ -static grpc_error *parse_value_string(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, - const uint8_t *cur, const uint8_t *end, +static grpc_error* parse_value_string(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, + const uint8_t* cur, const uint8_t* end, bool is_binary) { return begin_parse_string(exec_ctx, p, cur, end, is_binary ? BINARY_BEGIN : NOT_BINARY, &p->value); } -static grpc_error *parse_value_string_with_indexed_key( - grpc_exec_ctx *exec_ctx, grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_value_string_with_indexed_key( + grpc_exec_ctx* exec_ctx, grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end) { bool is_binary = false; - grpc_error *err = is_binary_indexed_header(p, &is_binary); + grpc_error* err = is_binary_indexed_header(p, &is_binary); if (err != GRPC_ERROR_NONE) return parse_error(exec_ctx, p, cur, end, err); return parse_value_string(exec_ctx, p, cur, end, is_binary); } -static grpc_error *parse_value_string_with_literal_key( - grpc_exec_ctx *exec_ctx, grpc_chttp2_hpack_parser *p, const uint8_t *cur, - const uint8_t *end) { +static grpc_error* parse_value_string_with_literal_key( + grpc_exec_ctx* exec_ctx, grpc_chttp2_hpack_parser* p, const uint8_t* cur, + const uint8_t* end) { return parse_value_string(exec_ctx, p, cur, end, is_binary_literal_header(p)); } /* PUBLIC INTERFACE */ -void grpc_chttp2_hpack_parser_init(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p) { - p->on_header = NULL; - p->on_header_user_data = NULL; +void grpc_chttp2_hpack_parser_init(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p) { + p->on_header = nullptr; + p->on_header_user_data = nullptr; p->state = parse_begin; p->key.data.referenced = grpc_empty_slice(); - p->key.data.copied.str = NULL; + p->key.data.copied.str = nullptr; p->key.data.copied.capacity = 0; p->key.data.copied.length = 0; p->value.data.referenced = grpc_empty_slice(); - p->value.data.copied.str = NULL; + p->value.data.copied.str = nullptr; p->value.data.copied.capacity = 0; p->value.data.copied.length = 0; p->dynamic_table_update_allowed = 2; @@ -1629,13 +1629,13 @@ void grpc_chttp2_hpack_parser_init(grpc_exec_ctx *exec_ctx, grpc_chttp2_hptbl_init(exec_ctx, &p->table); } -void grpc_chttp2_hpack_parser_set_has_priority(grpc_chttp2_hpack_parser *p) { +void grpc_chttp2_hpack_parser_set_has_priority(grpc_chttp2_hpack_parser* p) { p->after_prioritization = p->state; p->state = parse_stream_dep0; } -void grpc_chttp2_hpack_parser_destroy(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p) { +void grpc_chttp2_hpack_parser_destroy(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p) { grpc_chttp2_hptbl_destroy(exec_ctx, &p->table); GRPC_ERROR_UNREF(p->last_error); grpc_slice_unref_internal(exec_ctx, p->key.data.referenced); @@ -1644,36 +1644,36 @@ void grpc_chttp2_hpack_parser_destroy(grpc_exec_ctx *exec_ctx, gpr_free(p->value.data.copied.str); } -grpc_error *grpc_chttp2_hpack_parser_parse(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, +grpc_error* grpc_chttp2_hpack_parser_parse(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, grpc_slice slice) { /* max number of bytes to parse at a time... limits call stack depth on * compilers without TCO */ #define MAX_PARSE_LENGTH 1024 p->current_slice_refcount = slice.refcount; - uint8_t *start = GRPC_SLICE_START_PTR(slice); - uint8_t *end = GRPC_SLICE_END_PTR(slice); - grpc_error *error = GRPC_ERROR_NONE; + uint8_t* start = GRPC_SLICE_START_PTR(slice); + uint8_t* end = GRPC_SLICE_END_PTR(slice); + grpc_error* error = GRPC_ERROR_NONE; while (start != end && error == GRPC_ERROR_NONE) { - uint8_t *target = start + GPR_MIN(MAX_PARSE_LENGTH, end - start); + uint8_t* target = start + GPR_MIN(MAX_PARSE_LENGTH, end - start); error = p->state(exec_ctx, p, start, target); start = target; } - p->current_slice_refcount = NULL; + p->current_slice_refcount = nullptr; return error; } -typedef void (*maybe_complete_func_type)(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s); +typedef void (*maybe_complete_func_type)(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s); static const maybe_complete_func_type maybe_complete_funcs[] = { grpc_chttp2_maybe_complete_recv_initial_metadata, grpc_chttp2_maybe_complete_recv_trailing_metadata}; -static void force_client_rst_stream(grpc_exec_ctx *exec_ctx, void *sp, - grpc_error *error) { - grpc_chttp2_stream *s = (grpc_chttp2_stream *)sp; - grpc_chttp2_transport *t = s->t; +static void force_client_rst_stream(grpc_exec_ctx* exec_ctx, void* sp, + grpc_error* error) { + grpc_chttp2_stream* s = (grpc_chttp2_stream*)sp; + grpc_chttp2_transport* t = s->t; if (!s->write_closed) { grpc_slice_buffer_add( &t->qbuf, grpc_chttp2_rst_stream_create(s->id, GRPC_HTTP2_NO_ERROR, @@ -1685,11 +1685,11 @@ static void force_client_rst_stream(grpc_exec_ctx *exec_ctx, void *sp, GRPC_CHTTP2_STREAM_UNREF(exec_ctx, s, "final_rst"); } -static void parse_stream_compression_md(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, - grpc_metadata_batch *initial_metadata) { - if (initial_metadata->idx.named.content_encoding == NULL || +static void parse_stream_compression_md(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, + grpc_metadata_batch* initial_metadata) { + if (initial_metadata->idx.named.content_encoding == nullptr || grpc_stream_compression_method_parse( GRPC_MDVALUE(initial_metadata->idx.named.content_encoding->md), false, &s->stream_decompression_method) == 0) { @@ -1698,17 +1698,17 @@ static void parse_stream_compression_md(grpc_exec_ctx *exec_ctx, } } -grpc_error *grpc_chttp2_header_parser_parse(grpc_exec_ctx *exec_ctx, - void *hpack_parser, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, +grpc_error* grpc_chttp2_header_parser_parse(grpc_exec_ctx* exec_ctx, + void* hpack_parser, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_slice slice, int is_last) { - grpc_chttp2_hpack_parser *parser = (grpc_chttp2_hpack_parser *)hpack_parser; + grpc_chttp2_hpack_parser* parser = (grpc_chttp2_hpack_parser*)hpack_parser; GPR_TIMER_BEGIN("grpc_chttp2_hpack_parser_parse", 0); - if (s != NULL) { + if (s != nullptr) { s->stats.incoming.header_bytes += GRPC_SLICE_LENGTH(slice); } - grpc_error *error = grpc_chttp2_hpack_parser_parse(exec_ctx, parser, slice); + grpc_error* error = grpc_chttp2_hpack_parser_parse(exec_ctx, parser, slice); if (error != GRPC_ERROR_NONE) { GPR_TIMER_END("grpc_chttp2_hpack_parser_parse", 0); return error; @@ -1721,7 +1721,7 @@ grpc_error *grpc_chttp2_header_parser_parse(grpc_exec_ctx *exec_ctx, } /* need to check for null stream: this can occur if we receive an invalid stream id on a header */ - if (s != NULL) { + if (s != nullptr) { if (parser->is_boundary) { if (s->header_frames_received == GPR_ARRAY_SIZE(s->metadata_buffer)) { GPR_TIMER_END("grpc_chttp2_hpack_parser_parse", 0); @@ -1756,8 +1756,8 @@ grpc_error *grpc_chttp2_header_parser_parse(grpc_exec_ctx *exec_ctx, GRPC_ERROR_NONE); } } - parser->on_header = NULL; - parser->on_header_user_data = NULL; + parser->on_header = nullptr; + parser->on_header_user_data = nullptr; parser->is_boundary = 0xde; parser->is_eof = 0xde; parser->dynamic_table_update_allowed = 2; diff --git a/src/core/ext/transport/chttp2/transport/hpack_parser.h b/src/core/ext/transport/chttp2/transport/hpack_parser.h index 52014175a06..b4a2b14bdb7 100644 --- a/src/core/ext/transport/chttp2/transport/hpack_parser.h +++ b/src/core/ext/transport/chttp2/transport/hpack_parser.h @@ -27,22 +27,18 @@ #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/transport/metadata.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_chttp2_hpack_parser grpc_chttp2_hpack_parser; -typedef grpc_error *(*grpc_chttp2_hpack_parser_state)( - grpc_exec_ctx *exec_ctx, grpc_chttp2_hpack_parser *p, const uint8_t *beg, - const uint8_t *end); +typedef grpc_error* (*grpc_chttp2_hpack_parser_state)( + grpc_exec_ctx* exec_ctx, grpc_chttp2_hpack_parser* p, const uint8_t* beg, + const uint8_t* end); typedef struct { bool copied; struct { grpc_slice referenced; struct { - char *str; + char* str; uint32_t length; uint32_t capacity; } copied; @@ -51,23 +47,23 @@ typedef struct { struct grpc_chttp2_hpack_parser { /* user specified callback for each header output */ - void (*on_header)(grpc_exec_ctx *exec_ctx, void *user_data, grpc_mdelem md); - void *on_header_user_data; + void (*on_header)(grpc_exec_ctx* exec_ctx, void* user_data, grpc_mdelem md); + void* on_header_user_data; - grpc_error *last_error; + grpc_error* last_error; /* current parse state - or a function that implements it */ grpc_chttp2_hpack_parser_state state; /* future states dependent on the opening op code */ - const grpc_chttp2_hpack_parser_state *next_state; + const grpc_chttp2_hpack_parser_state* next_state; /* what to do after skipping prioritization data */ grpc_chttp2_hpack_parser_state after_prioritization; /* the refcount of the slice that we're currently parsing */ - grpc_slice_refcount *current_slice_refcount; + grpc_slice_refcount* current_slice_refcount; /* the value we're currently parsing */ union { - uint32_t *value; - grpc_chttp2_hpack_parser_string *str; + uint32_t* value; + grpc_chttp2_hpack_parser_string* str; } parsing; /* string parameters for each chunk */ grpc_chttp2_hpack_parser_string key; @@ -96,27 +92,23 @@ struct grpc_chttp2_hpack_parser { grpc_chttp2_hptbl table; }; -void grpc_chttp2_hpack_parser_init(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p); -void grpc_chttp2_hpack_parser_destroy(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p); +void grpc_chttp2_hpack_parser_init(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p); +void grpc_chttp2_hpack_parser_destroy(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p); -void grpc_chttp2_hpack_parser_set_has_priority(grpc_chttp2_hpack_parser *p); +void grpc_chttp2_hpack_parser_set_has_priority(grpc_chttp2_hpack_parser* p); -grpc_error *grpc_chttp2_hpack_parser_parse(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hpack_parser *p, +grpc_error* grpc_chttp2_hpack_parser_parse(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hpack_parser* p, grpc_slice slice); /* wraps grpc_chttp2_hpack_parser_parse to provide a frame level parser for the transport */ -grpc_error *grpc_chttp2_header_parser_parse(grpc_exec_ctx *exec_ctx, - void *hpack_parser, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, +grpc_error* grpc_chttp2_header_parser_parse(grpc_exec_ctx* exec_ctx, + void* hpack_parser, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_slice slice, int is_last); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HPACK_PARSER_H */ diff --git a/src/core/ext/transport/chttp2/transport/hpack_table.cc b/src/core/ext/transport/chttp2/transport/hpack_table.cc index 82c284b36e3..75b83b80b67 100644 --- a/src/core/ext/transport/chttp2/transport/hpack_table.cc +++ b/src/core/ext/transport/chttp2/transport/hpack_table.cc @@ -28,14 +28,14 @@ #include "src/core/lib/debug/trace.h" #include "src/core/lib/support/murmur_hash.h" -extern "C" grpc_tracer_flag grpc_http_trace; +extern grpc_core::TraceFlag grpc_http_trace; static struct { - const char *key; - const char *value; + const char* key; + const char* value; } static_table[] = { /* 0: */ - {NULL, NULL}, + {nullptr, nullptr}, /* 1: */ {":authority", ""}, /* 2: */ @@ -165,7 +165,7 @@ static uint32_t entries_for_bytes(uint32_t bytes) { GRPC_CHTTP2_HPACK_ENTRY_OVERHEAD; } -void grpc_chttp2_hptbl_init(grpc_exec_ctx *exec_ctx, grpc_chttp2_hptbl *tbl) { +void grpc_chttp2_hptbl_init(grpc_exec_ctx* exec_ctx, grpc_chttp2_hptbl* tbl) { size_t i; memset(tbl, 0, sizeof(*tbl)); @@ -173,7 +173,7 @@ void grpc_chttp2_hptbl_init(grpc_exec_ctx *exec_ctx, grpc_chttp2_hptbl *tbl) { GRPC_CHTTP2_INITIAL_HPACK_TABLE_SIZE; tbl->max_entries = tbl->cap_entries = entries_for_bytes(tbl->current_table_bytes); - tbl->ents = (grpc_mdelem *)gpr_malloc(sizeof(*tbl->ents) * tbl->cap_entries); + tbl->ents = (grpc_mdelem*)gpr_malloc(sizeof(*tbl->ents) * tbl->cap_entries); memset(tbl->ents, 0, sizeof(*tbl->ents) * tbl->cap_entries); for (i = 1; i <= GRPC_CHTTP2_LAST_STATIC_ENTRY; i++) { tbl->static_ents[i - 1] = grpc_mdelem_from_slices( @@ -184,8 +184,8 @@ void grpc_chttp2_hptbl_init(grpc_exec_ctx *exec_ctx, grpc_chttp2_hptbl *tbl) { } } -void grpc_chttp2_hptbl_destroy(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hptbl *tbl) { +void grpc_chttp2_hptbl_destroy(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hptbl* tbl) { size_t i; for (i = 0; i < GRPC_CHTTP2_LAST_STATIC_ENTRY; i++) { GRPC_MDELEM_UNREF(exec_ctx, tbl->static_ents[i]); @@ -197,7 +197,7 @@ void grpc_chttp2_hptbl_destroy(grpc_exec_ctx *exec_ctx, gpr_free(tbl->ents); } -grpc_mdelem grpc_chttp2_hptbl_lookup(const grpc_chttp2_hptbl *tbl, +grpc_mdelem grpc_chttp2_hptbl_lookup(const grpc_chttp2_hptbl* tbl, uint32_t tbl_index) { /* Static table comes first, just return an entry from it */ if (tbl_index <= GRPC_CHTTP2_LAST_STATIC_ENTRY) { @@ -215,7 +215,7 @@ grpc_mdelem grpc_chttp2_hptbl_lookup(const grpc_chttp2_hptbl *tbl, } /* Evict one element from the table */ -static void evict1(grpc_exec_ctx *exec_ctx, grpc_chttp2_hptbl *tbl) { +static void evict1(grpc_exec_ctx* exec_ctx, grpc_chttp2_hptbl* tbl) { grpc_mdelem first_ent = tbl->ents[tbl->first_ent]; size_t elem_bytes = GRPC_SLICE_LENGTH(GRPC_MDKEY(first_ent)) + GRPC_SLICE_LENGTH(GRPC_MDVALUE(first_ent)) + @@ -227,8 +227,8 @@ static void evict1(grpc_exec_ctx *exec_ctx, grpc_chttp2_hptbl *tbl) { GRPC_MDELEM_UNREF(exec_ctx, first_ent); } -static void rebuild_ents(grpc_chttp2_hptbl *tbl, uint32_t new_cap) { - grpc_mdelem *ents = (grpc_mdelem *)gpr_malloc(sizeof(*ents) * new_cap); +static void rebuild_ents(grpc_chttp2_hptbl* tbl, uint32_t new_cap) { + grpc_mdelem* ents = (grpc_mdelem*)gpr_malloc(sizeof(*ents) * new_cap); uint32_t i; for (i = 0; i < tbl->num_ents; i++) { @@ -240,13 +240,13 @@ static void rebuild_ents(grpc_chttp2_hptbl *tbl, uint32_t new_cap) { tbl->first_ent = 0; } -void grpc_chttp2_hptbl_set_max_bytes(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hptbl *tbl, +void grpc_chttp2_hptbl_set_max_bytes(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hptbl* tbl, uint32_t max_bytes) { if (tbl->max_bytes == max_bytes) { return; } - if (GRPC_TRACER_ON(grpc_http_trace)) { + if (grpc_http_trace.enabled()) { gpr_log(GPR_DEBUG, "Update hpack parser max size to %d", max_bytes); } while (tbl->mem_used > max_bytes) { @@ -255,22 +255,22 @@ void grpc_chttp2_hptbl_set_max_bytes(grpc_exec_ctx *exec_ctx, tbl->max_bytes = max_bytes; } -grpc_error *grpc_chttp2_hptbl_set_current_table_size(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hptbl *tbl, +grpc_error* grpc_chttp2_hptbl_set_current_table_size(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hptbl* tbl, uint32_t bytes) { if (tbl->current_table_bytes == bytes) { return GRPC_ERROR_NONE; } if (bytes > tbl->max_bytes) { - char *msg; + char* msg; gpr_asprintf(&msg, "Attempt to make hpack table %d bytes when max is %d bytes", bytes, tbl->max_bytes); - grpc_error *err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return err; } - if (GRPC_TRACER_ON(grpc_http_trace)) { + if (grpc_http_trace.enabled()) { gpr_log(GPR_DEBUG, "Update hpack parser table size to %d", bytes); } while (tbl->mem_used > bytes) { @@ -289,21 +289,21 @@ grpc_error *grpc_chttp2_hptbl_set_current_table_size(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -grpc_error *grpc_chttp2_hptbl_add(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hptbl *tbl, grpc_mdelem md) { +grpc_error* grpc_chttp2_hptbl_add(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hptbl* tbl, grpc_mdelem md) { /* determine how many bytes of buffer this entry represents */ size_t elem_bytes = GRPC_SLICE_LENGTH(GRPC_MDKEY(md)) + GRPC_SLICE_LENGTH(GRPC_MDVALUE(md)) + GRPC_CHTTP2_HPACK_ENTRY_OVERHEAD; if (tbl->current_table_bytes > tbl->max_bytes) { - char *msg; + char* msg; gpr_asprintf( &msg, "HPACK max table size reduced to %d but not reflected by hpack " "stream (still at %d)", tbl->max_bytes, tbl->current_table_bytes); - grpc_error *err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return err; } @@ -341,7 +341,7 @@ grpc_error *grpc_chttp2_hptbl_add(grpc_exec_ctx *exec_ctx, } grpc_chttp2_hptbl_find_result grpc_chttp2_hptbl_find( - const grpc_chttp2_hptbl *tbl, grpc_mdelem md) { + const grpc_chttp2_hptbl* tbl, grpc_mdelem md) { grpc_chttp2_hptbl_find_result r = {0, 0}; uint32_t i; diff --git a/src/core/ext/transport/chttp2/transport/hpack_table.h b/src/core/ext/transport/chttp2/transport/hpack_table.h index a3ce2730a89..aed7b13f0be 100644 --- a/src/core/ext/transport/chttp2/transport/hpack_table.h +++ b/src/core/ext/transport/chttp2/transport/hpack_table.h @@ -24,10 +24,6 @@ #include "src/core/lib/iomgr/error.h" #include "src/core/lib/transport/metadata.h" -#ifdef __cplusplus -extern "C" { -#endif - /* HPACK header table */ /* last index in the static table */ @@ -68,26 +64,26 @@ typedef struct { /* a circular buffer of headers - this is stored in the opposite order to what hpack specifies, in order to simplify table management a little... meaning lookups need to SUBTRACT from the end position */ - grpc_mdelem *ents; + grpc_mdelem* ents; grpc_mdelem static_ents[GRPC_CHTTP2_LAST_STATIC_ENTRY]; } grpc_chttp2_hptbl; /* initialize a hpack table */ -void grpc_chttp2_hptbl_init(grpc_exec_ctx *exec_ctx, grpc_chttp2_hptbl *tbl); -void grpc_chttp2_hptbl_destroy(grpc_exec_ctx *exec_ctx, grpc_chttp2_hptbl *tbl); -void grpc_chttp2_hptbl_set_max_bytes(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hptbl *tbl, +void grpc_chttp2_hptbl_init(grpc_exec_ctx* exec_ctx, grpc_chttp2_hptbl* tbl); +void grpc_chttp2_hptbl_destroy(grpc_exec_ctx* exec_ctx, grpc_chttp2_hptbl* tbl); +void grpc_chttp2_hptbl_set_max_bytes(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hptbl* tbl, uint32_t max_bytes); -grpc_error *grpc_chttp2_hptbl_set_current_table_size(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hptbl *tbl, +grpc_error* grpc_chttp2_hptbl_set_current_table_size(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hptbl* tbl, uint32_t bytes); /* lookup a table entry based on its hpack index */ -grpc_mdelem grpc_chttp2_hptbl_lookup(const grpc_chttp2_hptbl *tbl, +grpc_mdelem grpc_chttp2_hptbl_lookup(const grpc_chttp2_hptbl* tbl, uint32_t index); /* add a table entry to the index */ -grpc_error *grpc_chttp2_hptbl_add(grpc_exec_ctx *exec_ctx, - grpc_chttp2_hptbl *tbl, +grpc_error* grpc_chttp2_hptbl_add(grpc_exec_ctx* exec_ctx, + grpc_chttp2_hptbl* tbl, grpc_mdelem md) GRPC_MUST_USE_RESULT; /* Find a key/value pair in the table... returns the index in the table of the most similar entry, or 0 if the value was not found */ @@ -96,10 +92,6 @@ typedef struct { int has_value; } grpc_chttp2_hptbl_find_result; grpc_chttp2_hptbl_find_result grpc_chttp2_hptbl_find( - const grpc_chttp2_hptbl *tbl, grpc_mdelem md); - -#ifdef __cplusplus -} -#endif + const grpc_chttp2_hptbl* tbl, grpc_mdelem md); #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HPACK_TABLE_H */ diff --git a/src/core/ext/transport/chttp2/transport/http2_settings.cc b/src/core/ext/transport/chttp2/transport/http2_settings.cc index 46b7c0c49c7..0aab8644007 100644 --- a/src/core/ext/transport/chttp2/transport/http2_settings.cc +++ b/src/core/ext/transport/chttp2/transport/http2_settings.cc @@ -25,7 +25,7 @@ const uint16_t grpc_setting_id_to_wire_id[] = {1, 2, 3, 4, 5, 6, 65027}; -bool grpc_wire_id_to_setting_id(uint32_t wire_id, grpc_chttp2_setting_id *out) { +bool grpc_wire_id_to_setting_id(uint32_t wire_id, grpc_chttp2_setting_id* out) { uint32_t i = wire_id - 1; uint32_t x = i % 256; uint32_t y = i / 256; diff --git a/src/core/ext/transport/chttp2/transport/http2_settings.h b/src/core/ext/transport/chttp2/transport/http2_settings.h index 0f76106dceb..fd15b6977b9 100644 --- a/src/core/ext/transport/chttp2/transport/http2_settings.h +++ b/src/core/ext/transport/chttp2/transport/http2_settings.h @@ -36,12 +36,9 @@ typedef enum { #define GRPC_CHTTP2_NUM_SETTINGS 7 -#ifdef __cplusplus -extern "C" { -#endif extern const uint16_t grpc_setting_id_to_wire_id[]; -bool grpc_wire_id_to_setting_id(uint32_t wire_id, grpc_chttp2_setting_id *out); +bool grpc_wire_id_to_setting_id(uint32_t wire_id, grpc_chttp2_setting_id* out); typedef enum { GRPC_CHTTP2_CLAMP_INVALID_VALUE, @@ -49,7 +46,7 @@ typedef enum { } grpc_chttp2_invalid_value_behavior; typedef struct { - const char *name; + const char* name; uint32_t default_value; uint32_t min_value; uint32_t max_value; @@ -60,8 +57,4 @@ typedef struct { extern const grpc_chttp2_setting_parameters grpc_chttp2_settings_parameters[GRPC_CHTTP2_NUM_SETTINGS]; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HTTP2_SETTINGS_H */ diff --git a/src/core/ext/transport/chttp2/transport/huffsyms.h b/src/core/ext/transport/chttp2/transport/huffsyms.h index 4002706bc0f..2e2a5dacaed 100644 --- a/src/core/ext/transport/chttp2/transport/huffsyms.h +++ b/src/core/ext/transport/chttp2/transport/huffsyms.h @@ -19,10 +19,6 @@ #ifndef GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HUFFSYMS_H #define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HUFFSYMS_H -#ifdef __cplusplus -extern "C" { -#endif - /* HPACK static huffman table */ #define GRPC_CHTTP2_NUM_HUFFSYMS 257 @@ -34,8 +30,4 @@ typedef struct { extern const grpc_chttp2_huffsym grpc_chttp2_huffsyms[GRPC_CHTTP2_NUM_HUFFSYMS]; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_HUFFSYMS_H */ diff --git a/src/core/ext/transport/chttp2/transport/incoming_metadata.cc b/src/core/ext/transport/chttp2/transport/incoming_metadata.cc index 187ce0ea874..4461f8c12c5 100644 --- a/src/core/ext/transport/chttp2/transport/incoming_metadata.cc +++ b/src/core/ext/transport/chttp2/transport/incoming_metadata.cc @@ -26,31 +26,32 @@ #include void grpc_chttp2_incoming_metadata_buffer_init( - grpc_chttp2_incoming_metadata_buffer *buffer, gpr_arena *arena) { + grpc_chttp2_incoming_metadata_buffer* buffer, gpr_arena* arena) { buffer->arena = arena; grpc_metadata_batch_init(&buffer->batch); buffer->batch.deadline = GRPC_MILLIS_INF_FUTURE; } void grpc_chttp2_incoming_metadata_buffer_destroy( - grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_metadata_buffer *buffer) { + grpc_exec_ctx* exec_ctx, grpc_chttp2_incoming_metadata_buffer* buffer) { grpc_metadata_batch_destroy(exec_ctx, &buffer->batch); } -grpc_error *grpc_chttp2_incoming_metadata_buffer_add( - grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_metadata_buffer *buffer, +grpc_error* grpc_chttp2_incoming_metadata_buffer_add( + grpc_exec_ctx* exec_ctx, grpc_chttp2_incoming_metadata_buffer* buffer, grpc_mdelem elem) { buffer->size += GRPC_MDELEM_LENGTH(elem); return grpc_metadata_batch_add_tail( - exec_ctx, &buffer->batch, (grpc_linked_mdelem *)gpr_arena_alloc( - buffer->arena, sizeof(grpc_linked_mdelem)), + exec_ctx, &buffer->batch, + (grpc_linked_mdelem*)gpr_arena_alloc(buffer->arena, + sizeof(grpc_linked_mdelem)), elem); } -grpc_error *grpc_chttp2_incoming_metadata_buffer_replace_or_add( - grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_metadata_buffer *buffer, +grpc_error* grpc_chttp2_incoming_metadata_buffer_replace_or_add( + grpc_exec_ctx* exec_ctx, grpc_chttp2_incoming_metadata_buffer* buffer, grpc_mdelem elem) { - for (grpc_linked_mdelem *l = buffer->batch.list.head; l != NULL; + for (grpc_linked_mdelem* l = buffer->batch.list.head; l != nullptr; l = l->next) { if (grpc_slice_eq(GRPC_MDKEY(l->md), GRPC_MDKEY(elem))) { GRPC_MDELEM_UNREF(exec_ctx, l->md); @@ -62,13 +63,13 @@ grpc_error *grpc_chttp2_incoming_metadata_buffer_replace_or_add( } void grpc_chttp2_incoming_metadata_buffer_set_deadline( - grpc_chttp2_incoming_metadata_buffer *buffer, grpc_millis deadline) { + grpc_chttp2_incoming_metadata_buffer* buffer, grpc_millis deadline) { buffer->batch.deadline = deadline; } void grpc_chttp2_incoming_metadata_buffer_publish( - grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_metadata_buffer *buffer, - grpc_metadata_batch *batch) { + grpc_exec_ctx* exec_ctx, grpc_chttp2_incoming_metadata_buffer* buffer, + grpc_metadata_batch* batch) { *batch = buffer->batch; grpc_metadata_batch_init(&buffer->batch); } diff --git a/src/core/ext/transport/chttp2/transport/incoming_metadata.h b/src/core/ext/transport/chttp2/transport/incoming_metadata.h index a0e01f2c4d2..6f2b81ef6ce 100644 --- a/src/core/ext/transport/chttp2/transport/incoming_metadata.h +++ b/src/core/ext/transport/chttp2/transport/incoming_metadata.h @@ -21,36 +21,28 @@ #include "src/core/lib/transport/transport.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct { - gpr_arena *arena; + gpr_arena* arena; grpc_metadata_batch batch; size_t size; // total size of metadata } grpc_chttp2_incoming_metadata_buffer; /** assumes everything initially zeroed */ void grpc_chttp2_incoming_metadata_buffer_init( - grpc_chttp2_incoming_metadata_buffer *buffer, gpr_arena *arena); + grpc_chttp2_incoming_metadata_buffer* buffer, gpr_arena* arena); void grpc_chttp2_incoming_metadata_buffer_destroy( - grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_metadata_buffer *buffer); + grpc_exec_ctx* exec_ctx, grpc_chttp2_incoming_metadata_buffer* buffer); void grpc_chttp2_incoming_metadata_buffer_publish( - grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_metadata_buffer *buffer, - grpc_metadata_batch *batch); + grpc_exec_ctx* exec_ctx, grpc_chttp2_incoming_metadata_buffer* buffer, + grpc_metadata_batch* batch); -grpc_error *grpc_chttp2_incoming_metadata_buffer_add( - grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_metadata_buffer *buffer, +grpc_error* grpc_chttp2_incoming_metadata_buffer_add( + grpc_exec_ctx* exec_ctx, grpc_chttp2_incoming_metadata_buffer* buffer, grpc_mdelem elem) GRPC_MUST_USE_RESULT; -grpc_error *grpc_chttp2_incoming_metadata_buffer_replace_or_add( - grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_metadata_buffer *buffer, +grpc_error* grpc_chttp2_incoming_metadata_buffer_replace_or_add( + grpc_exec_ctx* exec_ctx, grpc_chttp2_incoming_metadata_buffer* buffer, grpc_mdelem elem) GRPC_MUST_USE_RESULT; void grpc_chttp2_incoming_metadata_buffer_set_deadline( - grpc_chttp2_incoming_metadata_buffer *buffer, grpc_millis deadline); - -#ifdef __cplusplus -} -#endif + grpc_chttp2_incoming_metadata_buffer* buffer, grpc_millis deadline); #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_INCOMING_METADATA_H */ diff --git a/src/core/ext/transport/chttp2/transport/internal.h b/src/core/ext/transport/chttp2/transport/internal.h index 9e0796e8207..f6fd6795d0a 100644 --- a/src/core/ext/transport/chttp2/transport/internal.h +++ b/src/core/ext/transport/chttp2/transport/internal.h @@ -42,10 +42,6 @@ #include "src/core/lib/transport/connectivity_state.h" #include "src/core/lib/transport/transport_impl.h" -#ifdef __cplusplus -extern "C" { -#endif - /* streams are kept in various linked lists depending on what things need to happen to them... this enum labels each list */ typedef enum { @@ -100,7 +96,7 @@ typedef enum { GRPC_CHTTP2_INITIATE_WRITE_FORCE_RST_STREAM, } grpc_chttp2_initiate_write_reason; -const char *grpc_chttp2_initiate_write_reason_string( +const char* grpc_chttp2_initiate_write_reason_string( grpc_chttp2_initiate_write_reason reason); typedef struct { @@ -171,13 +167,13 @@ typedef enum { } grpc_chttp2_deframe_transport_state; typedef struct { - grpc_chttp2_stream *head; - grpc_chttp2_stream *tail; + grpc_chttp2_stream* head; + grpc_chttp2_stream* tail; } grpc_chttp2_stream_list; typedef struct { - grpc_chttp2_stream *next; - grpc_chttp2_stream *prev; + grpc_chttp2_stream* next; + grpc_chttp2_stream* prev; } grpc_chttp2_stream_link; /* We keep several sets of connection wide parameters */ @@ -201,8 +197,8 @@ typedef enum { typedef struct grpc_chttp2_write_cb { int64_t call_at_byte; - grpc_closure *closure; - struct grpc_chttp2_write_cb *next; + grpc_closure* closure; + struct grpc_chttp2_write_cb* next; } grpc_chttp2_write_cb; /* forward declared in frame_data.h */ @@ -210,8 +206,8 @@ struct grpc_chttp2_incoming_byte_stream { grpc_byte_stream base; gpr_refcount refs; - grpc_chttp2_transport *transport; /* immutable */ - grpc_chttp2_stream *stream; /* immutable */ + grpc_chttp2_transport* transport; /* immutable */ + grpc_chttp2_stream* stream; /* immutable */ /* Accessed only by transport thread when stream->pending_byte_stream == false * Accessed only by application thread when stream->pending_byte_stream == @@ -224,7 +220,7 @@ struct grpc_chttp2_incoming_byte_stream { struct { grpc_closure closure; size_t max_size_hint; - grpc_closure *on_complete; + grpc_closure* on_complete; } next_action; grpc_closure destroy_action; grpc_closure finished_action; @@ -240,10 +236,12 @@ typedef enum { struct grpc_chttp2_transport { grpc_transport base; /* must be first */ gpr_refcount refs; - grpc_endpoint *ep; - char *peer_string; + grpc_endpoint* ep; + char* peer_string; - grpc_combiner *combiner; + grpc_combiner* combiner; + + grpc_closure* notify_on_receive_settings; /** write execution state of the transport */ grpc_chttp2_write_state write_state; @@ -255,7 +253,7 @@ struct grpc_chttp2_transport { /** is the transport destroying itself? */ uint8_t destroying; /** has the upper layer closed the transport? */ - grpc_error *closed_with_error; + grpc_error* closed_with_error; /** is there a read request to the endpoint outstanding? */ uint8_t endpoint_reading; @@ -280,13 +278,13 @@ struct grpc_chttp2_transport { /** address to place a newly accepted stream - set and unset by grpc_chttp2_parsing_accept_stream; used by init_stream to publish the accepted server stream */ - grpc_chttp2_stream **accepting_stream; + grpc_chttp2_stream** accepting_stream; struct { /* accept stream callback */ - void (*accept_stream)(grpc_exec_ctx *exec_ctx, void *user_data, - grpc_transport *transport, const void *server_data); - void *accept_stream_user_data; + void (*accept_stream)(grpc_exec_ctx* exec_ctx, void* user_data, + grpc_transport* transport, const void* server_data); + void* accept_stream_user_data; /** connectivity tracking */ grpc_connectivity_state_tracker state_tracker; @@ -306,9 +304,10 @@ struct grpc_chttp2_transport { */ uint32_t write_buffer_size; - /** have we seen a goaway */ - bool seen_goaway; - /** have we sent a goaway */ + /** Set to a grpc_error object if a goaway frame is received. By default, set + * to GRPC_ERROR_NONE */ + grpc_error* goaway_error; + grpc_chttp2_sent_goaway_state sent_goaway_state; /** are the local settings dirty and need to be sent? */ @@ -337,7 +336,7 @@ struct grpc_chttp2_transport { /** ping acks */ size_t ping_ack_count; size_t ping_ack_capacity; - uint64_t *ping_acks; + uint64_t* ping_acks; grpc_chttp2_server_ping_recv_state ping_recv_state; /** parser for headers */ @@ -370,18 +369,13 @@ struct grpc_chttp2_transport { uint32_t incoming_stream_id; /* active parser */ - void *parser_data; - grpc_chttp2_stream *incoming_stream; - grpc_error *(*parser)(grpc_exec_ctx *exec_ctx, void *parser_user_data, - grpc_chttp2_transport *t, grpc_chttp2_stream *s, + void* parser_data; + grpc_chttp2_stream* incoming_stream; + grpc_error* (*parser)(grpc_exec_ctx* exec_ctx, void* parser_user_data, + grpc_chttp2_transport* t, grpc_chttp2_stream* s, grpc_slice slice, int is_last); - /* goaway data */ - grpc_status_code goaway_error; - uint32_t goaway_last_stream_index; - grpc_slice goaway_text; - - grpc_chttp2_write_cb *write_cb_pool; + grpc_chttp2_write_cb* write_cb_pool; /* bdp estimator */ grpc_closure next_bdp_ping_timer_expired_locked; @@ -390,7 +384,7 @@ struct grpc_chttp2_transport { /* if non-NULL, close the transport with this error when writes are finished */ - grpc_error *close_transport_on_writes_finished; + grpc_error* close_transport_on_writes_finished; /* a list of closures to run after writes are finished */ grpc_closure_list run_after_write; @@ -440,11 +434,11 @@ typedef enum { } grpc_published_metadata_method; struct grpc_chttp2_stream { - grpc_chttp2_transport *t; - grpc_stream_refcount *refcount; + grpc_chttp2_transport* t; + grpc_stream_refcount* refcount; grpc_closure destroy_stream; - grpc_closure *destroy_stream_arg; + grpc_closure* destroy_stream_arg; grpc_chttp2_stream_link links[STREAM_LIST_COUNT]; uint8_t included[STREAM_LIST_COUNT]; @@ -453,29 +447,29 @@ struct grpc_chttp2_stream { uint32_t id; /** things the upper layers would like to send */ - grpc_metadata_batch *send_initial_metadata; - grpc_closure *send_initial_metadata_finished; - grpc_metadata_batch *send_trailing_metadata; - grpc_closure *send_trailing_metadata_finished; + grpc_metadata_batch* send_initial_metadata; + grpc_closure* send_initial_metadata_finished; + grpc_metadata_batch* send_trailing_metadata; + grpc_closure* send_trailing_metadata_finished; - grpc_byte_stream *fetching_send_message; + grpc_byte_stream* fetching_send_message; uint32_t fetched_send_message_length; grpc_slice fetching_slice; int64_t next_message_end_offset; int64_t flow_controlled_bytes_written; int64_t flow_controlled_bytes_flowed; grpc_closure complete_fetch_locked; - grpc_closure *fetching_send_message_finished; + grpc_closure* fetching_send_message_finished; - grpc_metadata_batch *recv_initial_metadata; - grpc_closure *recv_initial_metadata_ready; - bool *trailing_metadata_available; - grpc_byte_stream **recv_message; - grpc_closure *recv_message_ready; - grpc_metadata_batch *recv_trailing_metadata; - grpc_closure *recv_trailing_metadata_finished; + grpc_metadata_batch* recv_initial_metadata; + grpc_closure* recv_initial_metadata_ready; + bool* trailing_metadata_available; + grpc_byte_stream** recv_message; + grpc_closure* recv_message_ready; + grpc_metadata_batch* recv_trailing_metadata; + grpc_closure* recv_trailing_metadata_finished; - grpc_transport_stream_stats *collecting_stats; + grpc_transport_stream_stats* collecting_stats; grpc_transport_stream_stats stats; /** Is this stream closed for writing. */ @@ -494,9 +488,9 @@ struct grpc_chttp2_stream { bool received_trailing_metadata; /** the error that resulted in this stream being read-closed */ - grpc_error *read_closed_error; + grpc_error* read_closed_error; /** the error that resulted in this stream being write-closed */ - grpc_error *write_closed_error; + grpc_error* write_closed_error; grpc_published_metadata_method published_metadata[2]; bool final_metadata_requested; @@ -509,16 +503,16 @@ struct grpc_chttp2_stream { * Accessed only by application thread when stream->pending_byte_stream == * true */ grpc_slice_buffer unprocessed_incoming_frames_buffer; - grpc_closure *on_next; /* protected by t combiner */ + grpc_closure* on_next; /* protected by t combiner */ bool pending_byte_stream; /* protected by t combiner */ grpc_closure reset_byte_stream; - grpc_error *byte_stream_error; /* protected by t combiner */ + grpc_error* byte_stream_error; /* protected by t combiner */ bool received_last_frame; /* protected by t combiner */ grpc_millis deadline; /** saw some stream level error */ - grpc_error *forced_close_error; + grpc_error* forced_close_error; /** how many header frames have we received? */ uint8_t header_frames_received; /** parsing state for data frames */ @@ -537,9 +531,9 @@ struct grpc_chttp2_stream { grpc_slice_buffer flow_controlled_buffer; - grpc_chttp2_write_cb *on_flow_controlled_cbs; - grpc_chttp2_write_cb *on_write_finished_cbs; - grpc_chttp2_write_cb *finish_after_write; + grpc_chttp2_write_cb* on_flow_controlled_cbs; + grpc_chttp2_write_cb* on_write_finished_cbs; + grpc_chttp2_write_cb* finish_after_write; size_t sending_bytes; /* Stream compression method to be used. */ @@ -547,9 +541,9 @@ struct grpc_chttp2_stream { /* Stream decompression method to be used. */ grpc_stream_compression_method stream_decompression_method; /** Stream compression decompress context */ - grpc_stream_compression_context *stream_decompression_ctx; + grpc_stream_compression_context* stream_decompression_ctx; /** Stream compression compress context */ - grpc_stream_compression_context *stream_compression_ctx; + grpc_stream_compression_context* stream_compression_ctx; /** Buffer storing data that is compressed but not sent */ grpc_slice_buffer compressed_data_buffer; @@ -577,8 +571,8 @@ struct grpc_chttp2_stream { The actual call chain is documented in the implementation of this function. */ -void grpc_chttp2_initiate_write(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, +void grpc_chttp2_initiate_write(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, grpc_chttp2_initiate_write_reason reason); typedef struct { @@ -591,85 +585,85 @@ typedef struct { } grpc_chttp2_begin_write_result; grpc_chttp2_begin_write_result grpc_chttp2_begin_write( - grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t); -void grpc_chttp2_end_write(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_error *error); + grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t); +void grpc_chttp2_end_write(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_error* error); /** Process one slice of incoming data; return 1 if the connection is still viable after reading, or 0 if the connection should be torn down */ -grpc_error *grpc_chttp2_perform_read(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, +grpc_error* grpc_chttp2_perform_read(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, grpc_slice slice); -bool grpc_chttp2_list_add_writable_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream *s); +bool grpc_chttp2_list_add_writable_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream* s); /** Get a writable stream returns non-zero if there was a stream available */ -bool grpc_chttp2_list_pop_writable_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream **s); -bool grpc_chttp2_list_remove_writable_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream *s); - -bool grpc_chttp2_list_add_writing_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream *s); -bool grpc_chttp2_list_have_writing_streams(grpc_chttp2_transport *t); -bool grpc_chttp2_list_pop_writing_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream **s); - -void grpc_chttp2_list_add_written_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream *s); -bool grpc_chttp2_list_pop_written_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream **s); - -void grpc_chttp2_list_add_waiting_for_concurrency(grpc_chttp2_transport *t, - grpc_chttp2_stream *s); -bool grpc_chttp2_list_pop_waiting_for_concurrency(grpc_chttp2_transport *t, - grpc_chttp2_stream **s); -void grpc_chttp2_list_remove_waiting_for_concurrency(grpc_chttp2_transport *t, - grpc_chttp2_stream *s); - -void grpc_chttp2_list_add_stalled_by_transport(grpc_chttp2_transport *t, - grpc_chttp2_stream *s); -bool grpc_chttp2_list_pop_stalled_by_transport(grpc_chttp2_transport *t, - grpc_chttp2_stream **s); -void grpc_chttp2_list_remove_stalled_by_transport(grpc_chttp2_transport *t, - grpc_chttp2_stream *s); - -void grpc_chttp2_list_add_stalled_by_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream *s); -bool grpc_chttp2_list_pop_stalled_by_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream **s); -bool grpc_chttp2_list_remove_stalled_by_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream *s); +bool grpc_chttp2_list_pop_writable_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream** s); +bool grpc_chttp2_list_remove_writable_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream* s); + +bool grpc_chttp2_list_add_writing_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream* s); +bool grpc_chttp2_list_have_writing_streams(grpc_chttp2_transport* t); +bool grpc_chttp2_list_pop_writing_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream** s); + +void grpc_chttp2_list_add_written_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream* s); +bool grpc_chttp2_list_pop_written_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream** s); + +void grpc_chttp2_list_add_waiting_for_concurrency(grpc_chttp2_transport* t, + grpc_chttp2_stream* s); +bool grpc_chttp2_list_pop_waiting_for_concurrency(grpc_chttp2_transport* t, + grpc_chttp2_stream** s); +void grpc_chttp2_list_remove_waiting_for_concurrency(grpc_chttp2_transport* t, + grpc_chttp2_stream* s); + +void grpc_chttp2_list_add_stalled_by_transport(grpc_chttp2_transport* t, + grpc_chttp2_stream* s); +bool grpc_chttp2_list_pop_stalled_by_transport(grpc_chttp2_transport* t, + grpc_chttp2_stream** s); +void grpc_chttp2_list_remove_stalled_by_transport(grpc_chttp2_transport* t, + grpc_chttp2_stream* s); + +void grpc_chttp2_list_add_stalled_by_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream* s); +bool grpc_chttp2_list_pop_stalled_by_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream** s); +bool grpc_chttp2_list_remove_stalled_by_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream* s); /********* Flow Control ***************/ // Takes in a flow control action and performs all the needed operations. void grpc_chttp2_act_on_flowctl_action( - grpc_exec_ctx *exec_ctx, const grpc_core::chttp2::FlowControlAction &action, - grpc_chttp2_transport *t, grpc_chttp2_stream *s); + grpc_exec_ctx* exec_ctx, const grpc_core::chttp2::FlowControlAction& action, + grpc_chttp2_transport* t, grpc_chttp2_stream* s); /********* End of Flow Control ***************/ -grpc_chttp2_stream *grpc_chttp2_parsing_lookup_stream(grpc_chttp2_transport *t, +grpc_chttp2_stream* grpc_chttp2_parsing_lookup_stream(grpc_chttp2_transport* t, uint32_t id); -grpc_chttp2_stream *grpc_chttp2_parsing_accept_stream(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, +grpc_chttp2_stream* grpc_chttp2_parsing_accept_stream(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, uint32_t id); -void grpc_chttp2_add_incoming_goaway(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, +void grpc_chttp2_add_incoming_goaway(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, uint32_t goaway_error, grpc_slice goaway_text); -void grpc_chttp2_parsing_become_skip_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t); +void grpc_chttp2_parsing_become_skip_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t); -void grpc_chttp2_complete_closure_step(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, - grpc_closure **pclosure, - grpc_error *error, const char *desc); +void grpc_chttp2_complete_closure_step(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, + grpc_closure** pclosure, + grpc_error* error, const char* desc); #define GRPC_HEADER_SIZE_IN_BYTES 5 #define MAX_SIZE_T (~(size_t)0) @@ -678,38 +672,38 @@ void grpc_chttp2_complete_closure_step(grpc_exec_ctx *exec_ctx, #define GRPC_CHTTP2_CLIENT_CONNECT_STRLEN \ (sizeof(GRPC_CHTTP2_CLIENT_CONNECT_STRING) - 1) -extern grpc_tracer_flag grpc_http_trace; -extern grpc_tracer_flag grpc_flowctl_trace; +// extern grpc_core::TraceFlag grpc_http_trace; +// extern grpc_core::TraceFlag grpc_flowctl_trace; -#define GRPC_CHTTP2_IF_TRACING(stmt) \ - if (!(GRPC_TRACER_ON(grpc_http_trace))) \ - ; \ - else \ - stmt +#define GRPC_CHTTP2_IF_TRACING(stmt) \ + if (!(grpc_http_trace.enabled())) \ + ; \ + else \ + stmt -void grpc_chttp2_fake_status(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_chttp2_stream *stream, grpc_error *error); -void grpc_chttp2_mark_stream_closed(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, int close_reads, - int close_writes, grpc_error *error); -void grpc_chttp2_start_writing(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t); +void grpc_chttp2_fake_status(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_chttp2_stream* stream, grpc_error* error); +void grpc_chttp2_mark_stream_closed(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, int close_reads, + int close_writes, grpc_error* error); +void grpc_chttp2_start_writing(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t); #ifndef NDEBUG #define GRPC_CHTTP2_STREAM_REF(stream, reason) \ grpc_chttp2_stream_ref(stream, reason) #define GRPC_CHTTP2_STREAM_UNREF(exec_ctx, stream, reason) \ grpc_chttp2_stream_unref(exec_ctx, stream, reason) -void grpc_chttp2_stream_ref(grpc_chttp2_stream *s, const char *reason); -void grpc_chttp2_stream_unref(grpc_exec_ctx *exec_ctx, grpc_chttp2_stream *s, - const char *reason); +void grpc_chttp2_stream_ref(grpc_chttp2_stream* s, const char* reason); +void grpc_chttp2_stream_unref(grpc_exec_ctx* exec_ctx, grpc_chttp2_stream* s, + const char* reason); #else #define GRPC_CHTTP2_STREAM_REF(stream, reason) grpc_chttp2_stream_ref(stream) #define GRPC_CHTTP2_STREAM_UNREF(exec_ctx, stream, reason) \ grpc_chttp2_stream_unref(exec_ctx, stream) -void grpc_chttp2_stream_ref(grpc_chttp2_stream *s); -void grpc_chttp2_stream_unref(grpc_exec_ctx *exec_ctx, grpc_chttp2_stream *s); +void grpc_chttp2_stream_ref(grpc_chttp2_stream* s); +void grpc_chttp2_stream_unref(grpc_exec_ctx* exec_ctx, grpc_chttp2_stream* s); #endif #ifndef NDEBUG @@ -717,73 +711,69 @@ void grpc_chttp2_stream_unref(grpc_exec_ctx *exec_ctx, grpc_chttp2_stream *s); grpc_chttp2_ref_transport(t, r, __FILE__, __LINE__) #define GRPC_CHTTP2_UNREF_TRANSPORT(cl, t, r) \ grpc_chttp2_unref_transport(cl, t, r, __FILE__, __LINE__) -void grpc_chttp2_unref_transport(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, const char *reason, - const char *file, int line); -void grpc_chttp2_ref_transport(grpc_chttp2_transport *t, const char *reason, - const char *file, int line); +void grpc_chttp2_unref_transport(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, const char* reason, + const char* file, int line); +void grpc_chttp2_ref_transport(grpc_chttp2_transport* t, const char* reason, + const char* file, int line); #else #define GRPC_CHTTP2_REF_TRANSPORT(t, r) grpc_chttp2_ref_transport(t) #define GRPC_CHTTP2_UNREF_TRANSPORT(cl, t, r) grpc_chttp2_unref_transport(cl, t) -void grpc_chttp2_unref_transport(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t); -void grpc_chttp2_ref_transport(grpc_chttp2_transport *t); +void grpc_chttp2_unref_transport(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t); +void grpc_chttp2_ref_transport(grpc_chttp2_transport* t); #endif -grpc_chttp2_incoming_byte_stream *grpc_chttp2_incoming_byte_stream_create( - grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, grpc_chttp2_stream *s, +grpc_chttp2_incoming_byte_stream* grpc_chttp2_incoming_byte_stream_create( + grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, grpc_chttp2_stream* s, uint32_t frame_size, uint32_t flags); -grpc_error *grpc_chttp2_incoming_byte_stream_push( - grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_byte_stream *bs, - grpc_slice slice, grpc_slice *slice_out); -grpc_error *grpc_chttp2_incoming_byte_stream_finished( - grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_byte_stream *bs, - grpc_error *error, bool reset_on_error); +grpc_error* grpc_chttp2_incoming_byte_stream_push( + grpc_exec_ctx* exec_ctx, grpc_chttp2_incoming_byte_stream* bs, + grpc_slice slice, grpc_slice* slice_out); +grpc_error* grpc_chttp2_incoming_byte_stream_finished( + grpc_exec_ctx* exec_ctx, grpc_chttp2_incoming_byte_stream* bs, + grpc_error* error, bool reset_on_error); void grpc_chttp2_incoming_byte_stream_notify( - grpc_exec_ctx *exec_ctx, grpc_chttp2_incoming_byte_stream *bs, - grpc_error *error); + grpc_exec_ctx* exec_ctx, grpc_chttp2_incoming_byte_stream* bs, + grpc_error* error); -void grpc_chttp2_ack_ping(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, +void grpc_chttp2_ack_ping(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, uint64_t id); /** Add a new ping strike to ping_recv_state.ping_strikes. If ping_recv_state.ping_strikes > ping_policy.max_ping_strikes, it sends GOAWAY with error code ENHANCE_YOUR_CALM and additional debug data resembling "too_many_pings" followed by immediately closing the connection. */ -void grpc_chttp2_add_ping_strike(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t); +void grpc_chttp2_add_ping_strike(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t); /** add a ref to the stream and add it to the writable list; ref will be dropped in writing.c */ -void grpc_chttp2_mark_stream_writable(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s); - -void grpc_chttp2_cancel_stream(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, grpc_chttp2_stream *s, - grpc_error *due_to_error); - -void grpc_chttp2_maybe_complete_recv_initial_metadata(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s); -void grpc_chttp2_maybe_complete_recv_message(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s); -void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s); - -void grpc_chttp2_fail_pending_writes(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, - grpc_chttp2_stream *s, grpc_error *error); +void grpc_chttp2_mark_stream_writable(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s); + +void grpc_chttp2_cancel_stream(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, grpc_chttp2_stream* s, + grpc_error* due_to_error); + +void grpc_chttp2_maybe_complete_recv_initial_metadata(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s); +void grpc_chttp2_maybe_complete_recv_message(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s); +void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s); + +void grpc_chttp2_fail_pending_writes(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_error* error); /** Set the default keepalive configurations, must only be called at initialization */ -void grpc_chttp2_config_default_keepalive_args(grpc_channel_args *args, +void grpc_chttp2_config_default_keepalive_args(grpc_channel_args* args, bool is_client); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_INTERNAL_H */ diff --git a/src/core/ext/transport/chttp2/transport/parsing.cc b/src/core/ext/transport/chttp2/transport/parsing.cc index efa5791d3f5..46ec3fbaa61 100644 --- a/src/core/ext/transport/chttp2/transport/parsing.cc +++ b/src/core/ext/transport/chttp2/transport/parsing.cc @@ -31,38 +31,38 @@ #include "src/core/lib/transport/status_conversion.h" #include "src/core/lib/transport/timeout_encoding.h" -static grpc_error *init_frame_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t); -static grpc_error *init_header_frame_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, +static grpc_error* init_frame_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t); +static grpc_error* init_header_frame_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, int is_continuation); -static grpc_error *init_data_frame_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t); -static grpc_error *init_rst_stream_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t); -static grpc_error *init_settings_frame_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t); -static grpc_error *init_window_update_frame_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t); -static grpc_error *init_ping_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t); -static grpc_error *init_goaway_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t); -static grpc_error *init_skip_frame_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, +static grpc_error* init_data_frame_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t); +static grpc_error* init_rst_stream_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t); +static grpc_error* init_settings_frame_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t); +static grpc_error* init_window_update_frame_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t); +static grpc_error* init_ping_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t); +static grpc_error* init_goaway_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t); +static grpc_error* init_skip_frame_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, int is_header); -static grpc_error *parse_frame_slice(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, grpc_slice slice, +static grpc_error* parse_frame_slice(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, grpc_slice slice, int is_last); -grpc_error *grpc_chttp2_perform_read(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, +grpc_error* grpc_chttp2_perform_read(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, grpc_slice slice) { - uint8_t *beg = GRPC_SLICE_START_PTR(slice); - uint8_t *end = GRPC_SLICE_END_PTR(slice); - uint8_t *cur = beg; - grpc_error *err; + uint8_t* beg = GRPC_SLICE_START_PTR(slice); + uint8_t* end = GRPC_SLICE_END_PTR(slice); + uint8_t* cur = beg; + grpc_error* err; if (cur == end) return GRPC_ERROR_NONE; @@ -93,7 +93,7 @@ grpc_error *grpc_chttp2_perform_read(grpc_exec_ctx *exec_ctx, case GRPC_DTS_CLIENT_PREFIX_23: while (cur != end && t->deframe_state != GRPC_DTS_FH_0) { if (*cur != GRPC_CHTTP2_CLIENT_CONNECT_STRING[t->deframe_state]) { - char *msg; + char* msg; gpr_asprintf( &msg, "Connect string mismatch: expected '%c' (%d) got '%c' (%d) " @@ -191,7 +191,7 @@ grpc_error *grpc_chttp2_perform_read(grpc_exec_ctx *exec_ctx, if (err != GRPC_ERROR_NONE) { return err; } - t->incoming_stream = NULL; + t->incoming_stream = nullptr; if (++cur == end) { t->deframe_state = GRPC_DTS_FH_0; return GRPC_ERROR_NONE; @@ -200,7 +200,7 @@ grpc_error *grpc_chttp2_perform_read(grpc_exec_ctx *exec_ctx, } else if (t->incoming_frame_size > t->settings[GRPC_ACKED_SETTINGS] [GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE]) { - char *msg; + char* msg; gpr_asprintf(&msg, "Frame size %d is larger than max frame size %d", t->incoming_frame_size, t->settings[GRPC_ACKED_SETTINGS] @@ -216,15 +216,16 @@ grpc_error *grpc_chttp2_perform_read(grpc_exec_ctx *exec_ctx, case GRPC_DTS_FRAME: GPR_ASSERT(cur < end); if ((uint32_t)(end - cur) == t->incoming_frame_size) { - err = parse_frame_slice( - exec_ctx, t, grpc_slice_sub_no_ref(slice, (size_t)(cur - beg), - (size_t)(end - beg)), - 1); + err = + parse_frame_slice(exec_ctx, t, + grpc_slice_sub_no_ref(slice, (size_t)(cur - beg), + (size_t)(end - beg)), + 1); if (err != GRPC_ERROR_NONE) { return err; } t->deframe_state = GRPC_DTS_FH_0; - t->incoming_stream = NULL; + t->incoming_stream = nullptr; return GRPC_ERROR_NONE; } else if ((uint32_t)(end - cur) > t->incoming_frame_size) { size_t cur_offset = (size_t)(cur - beg); @@ -237,55 +238,56 @@ grpc_error *grpc_chttp2_perform_read(grpc_exec_ctx *exec_ctx, return err; } cur += t->incoming_frame_size; - t->incoming_stream = NULL; + t->incoming_stream = nullptr; goto dts_fh_0; /* loop */ } else { - err = parse_frame_slice( - exec_ctx, t, grpc_slice_sub_no_ref(slice, (size_t)(cur - beg), - (size_t)(end - beg)), - 0); + err = + parse_frame_slice(exec_ctx, t, + grpc_slice_sub_no_ref(slice, (size_t)(cur - beg), + (size_t)(end - beg)), + 0); if (err != GRPC_ERROR_NONE) { return err; } t->incoming_frame_size -= (uint32_t)(end - cur); return GRPC_ERROR_NONE; } - GPR_UNREACHABLE_CODE(return 0); + GPR_UNREACHABLE_CODE(return nullptr); } - GPR_UNREACHABLE_CODE(return 0); + GPR_UNREACHABLE_CODE(return nullptr); } -static grpc_error *init_frame_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { +static grpc_error* init_frame_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { if (t->is_first_frame && t->incoming_frame_type != GRPC_CHTTP2_FRAME_SETTINGS) { - char *msg; + char* msg; gpr_asprintf( &msg, "Expected SETTINGS frame as the first frame, got frame type %d", t->incoming_frame_type); - grpc_error *err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return err; } t->is_first_frame = false; if (t->expect_continuation_stream_id != 0) { if (t->incoming_frame_type != GRPC_CHTTP2_FRAME_CONTINUATION) { - char *msg; + char* msg; gpr_asprintf(&msg, "Expected CONTINUATION frame, got frame type %02x", t->incoming_frame_type); - grpc_error *err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return err; } if (t->expect_continuation_stream_id != t->incoming_stream_id) { - char *msg; + char* msg; gpr_asprintf( &msg, "Expected CONTINUATION frame for grpc_chttp2_stream %08x, got " "grpc_chttp2_stream %08x", t->expect_continuation_stream_id, t->incoming_stream_id); - grpc_error *err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return err; } @@ -310,32 +312,32 @@ static grpc_error *init_frame_parser(grpc_exec_ctx *exec_ctx, case GRPC_CHTTP2_FRAME_GOAWAY: return init_goaway_parser(exec_ctx, t); default: - if (GRPC_TRACER_ON(grpc_http_trace)) { + if (grpc_http_trace.enabled()) { gpr_log(GPR_ERROR, "Unknown frame type %02x", t->incoming_frame_type); } return init_skip_frame_parser(exec_ctx, t, 0); } } -static grpc_error *skip_parser(grpc_exec_ctx *exec_ctx, void *parser, - grpc_chttp2_transport *t, grpc_chttp2_stream *s, +static grpc_error* skip_parser(grpc_exec_ctx* exec_ctx, void* parser, + grpc_chttp2_transport* t, grpc_chttp2_stream* s, grpc_slice slice, int is_last) { return GRPC_ERROR_NONE; } -static void skip_header(grpc_exec_ctx *exec_ctx, void *tp, grpc_mdelem md) { +static void skip_header(grpc_exec_ctx* exec_ctx, void* tp, grpc_mdelem md) { GRPC_MDELEM_UNREF(exec_ctx, md); } -static grpc_error *init_skip_frame_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, +static grpc_error* init_skip_frame_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, int is_header) { if (is_header) { uint8_t is_eoh = t->expect_continuation_stream_id != 0; t->parser = grpc_chttp2_header_parser_parse; t->parser_data = &t->hpack_parser; t->hpack_parser.on_header = skip_header; - t->hpack_parser.on_header_user_data = NULL; + t->hpack_parser.on_header_user_data = nullptr; t->hpack_parser.is_boundary = is_eoh; t->hpack_parser.is_eof = (uint8_t)(is_eoh ? t->header_eof : 0); } else { @@ -344,17 +346,17 @@ static grpc_error *init_skip_frame_parser(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -void grpc_chttp2_parsing_become_skip_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { +void grpc_chttp2_parsing_become_skip_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { init_skip_frame_parser(exec_ctx, t, t->parser == grpc_chttp2_header_parser_parse); } -static grpc_error *init_data_frame_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { - grpc_chttp2_stream *s = +static grpc_error* init_data_frame_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { + grpc_chttp2_stream* s = grpc_chttp2_parsing_lookup_stream(t, t->incoming_stream_id); - grpc_error *err = GRPC_ERROR_NONE; + grpc_error* err = GRPC_ERROR_NONE; grpc_core::chttp2::FlowControlAction action; if (s == nullptr) { err = t->flow_control->RecvData(t->incoming_frame_size); @@ -367,7 +369,7 @@ static grpc_error *init_data_frame_parser(grpc_exec_ctx *exec_ctx, if (err != GRPC_ERROR_NONE) { goto error_handler; } - if (s == NULL) { + if (s == nullptr) { return init_skip_frame_parser(exec_ctx, t, 0); } s->received_bytes += t->incoming_frame_size; @@ -389,9 +391,9 @@ error_handler: t->ping_policy.max_pings_without_data; t->ping_state.last_ping_sent_time = GRPC_MILLIS_INF_PAST; return GRPC_ERROR_NONE; - } else if (grpc_error_get_int(err, GRPC_ERROR_INT_STREAM_ID, NULL)) { + } else if (grpc_error_get_int(err, GRPC_ERROR_INT_STREAM_ID, nullptr)) { /* handle stream errors by closing the stream */ - if (s != NULL) { + if (s != nullptr) { grpc_chttp2_mark_stream_closed(exec_ctx, t, s, true, false, err); } grpc_slice_buffer_add( @@ -404,20 +406,20 @@ error_handler: } } -static void free_timeout(void *p) { gpr_free(p); } +static void free_timeout(void* p) { gpr_free(p); } -static void on_initial_header(grpc_exec_ctx *exec_ctx, void *tp, +static void on_initial_header(grpc_exec_ctx* exec_ctx, void* tp, grpc_mdelem md) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)tp; - grpc_chttp2_stream *s = t->incoming_stream; + grpc_chttp2_transport* t = (grpc_chttp2_transport*)tp; + grpc_chttp2_stream* s = t->incoming_stream; GPR_TIMER_BEGIN("on_initial_header", 0); - GPR_ASSERT(s != NULL); + GPR_ASSERT(s != nullptr); - if (GRPC_TRACER_ON(grpc_http_trace)) { - char *key = grpc_slice_to_c_string(GRPC_MDKEY(md)); - char *value = + if (grpc_http_trace.enabled()) { + char* key = grpc_slice_to_c_string(GRPC_MDKEY(md)); + char* value = grpc_dump_slice(GRPC_MDVALUE(md), GPR_DUMP_HEX | GPR_DUMP_ASCII); gpr_log(GPR_INFO, "HTTP:%d:HDR:%s: %s: %s", s->id, t->is_client ? "CLI" : "SVR", key, value); @@ -432,21 +434,21 @@ static void on_initial_header(grpc_exec_ctx *exec_ctx, void *tp, } if (grpc_slice_eq(GRPC_MDKEY(md), GRPC_MDSTR_GRPC_TIMEOUT)) { - grpc_millis *cached_timeout = - static_cast(grpc_mdelem_get_user_data(md, free_timeout)); + grpc_millis* cached_timeout = + static_cast(grpc_mdelem_get_user_data(md, free_timeout)); grpc_millis timeout; - if (cached_timeout != NULL) { + if (cached_timeout != nullptr) { timeout = *cached_timeout; } else { if (!grpc_http2_decode_timeout(GRPC_MDVALUE(md), &timeout)) { - char *val = grpc_slice_to_c_string(GRPC_MDVALUE(md)); + char* val = grpc_slice_to_c_string(GRPC_MDVALUE(md)); gpr_log(GPR_ERROR, "Ignoring bad timeout value '%s'", val); gpr_free(val); timeout = GRPC_MILLIS_INF_FUTURE; } if (GRPC_MDELEM_IS_INTERNED(md)) { /* store the result */ - cached_timeout = (grpc_millis *)gpr_malloc(sizeof(grpc_millis)); + cached_timeout = (grpc_millis*)gpr_malloc(sizeof(grpc_millis)); *cached_timeout = timeout; grpc_mdelem_set_user_data(md, free_timeout, cached_timeout); } @@ -476,7 +478,7 @@ static void on_initial_header(grpc_exec_ctx *exec_ctx, void *tp, s->seen_error = true; GRPC_MDELEM_UNREF(exec_ctx, md); } else { - grpc_error *error = grpc_chttp2_incoming_metadata_buffer_add( + grpc_error* error = grpc_chttp2_incoming_metadata_buffer_add( exec_ctx, &s->metadata_buffer[0], md); if (error != GRPC_ERROR_NONE) { grpc_chttp2_cancel_stream(exec_ctx, t, s, error); @@ -490,18 +492,18 @@ static void on_initial_header(grpc_exec_ctx *exec_ctx, void *tp, GPR_TIMER_END("on_initial_header", 0); } -static void on_trailing_header(grpc_exec_ctx *exec_ctx, void *tp, +static void on_trailing_header(grpc_exec_ctx* exec_ctx, void* tp, grpc_mdelem md) { - grpc_chttp2_transport *t = (grpc_chttp2_transport *)tp; - grpc_chttp2_stream *s = t->incoming_stream; + grpc_chttp2_transport* t = (grpc_chttp2_transport*)tp; + grpc_chttp2_stream* s = t->incoming_stream; GPR_TIMER_BEGIN("on_trailing_header", 0); - GPR_ASSERT(s != NULL); + GPR_ASSERT(s != nullptr); - if (GRPC_TRACER_ON(grpc_http_trace)) { - char *key = grpc_slice_to_c_string(GRPC_MDKEY(md)); - char *value = + if (grpc_http_trace.enabled()) { + char* key = grpc_slice_to_c_string(GRPC_MDKEY(md)); + char* value = grpc_dump_slice(GRPC_MDVALUE(md), GPR_DUMP_HEX | GPR_DUMP_ASCII); gpr_log(GPR_INFO, "HTTP:%d:TRL:%s: %s: %s", s->id, t->is_client ? "CLI" : "SVR", key, value); @@ -534,7 +536,7 @@ static void on_trailing_header(grpc_exec_ctx *exec_ctx, void *tp, s->seen_error = true; GRPC_MDELEM_UNREF(exec_ctx, md); } else { - grpc_error *error = grpc_chttp2_incoming_metadata_buffer_add( + grpc_error* error = grpc_chttp2_incoming_metadata_buffer_add( exec_ctx, &s->metadata_buffer[1], md); if (error != GRPC_ERROR_NONE) { grpc_chttp2_cancel_stream(exec_ctx, t, s, error); @@ -547,12 +549,12 @@ static void on_trailing_header(grpc_exec_ctx *exec_ctx, void *tp, GPR_TIMER_END("on_trailing_header", 0); } -static grpc_error *init_header_frame_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, +static grpc_error* init_header_frame_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, int is_continuation) { uint8_t is_eoh = (t->incoming_frame_flags & GRPC_CHTTP2_DATA_FLAG_END_HEADERS) != 0; - grpc_chttp2_stream *s; + grpc_chttp2_stream* s; /* TODO(ctiller): when to increment header_frames_received? */ @@ -573,7 +575,7 @@ static grpc_error *init_header_frame_parser(grpc_exec_ctx *exec_ctx, /* could be a new grpc_chttp2_stream or an existing grpc_chttp2_stream */ s = grpc_chttp2_parsing_lookup_stream(t, t->incoming_stream_id); - if (s == NULL) { + if (s == nullptr) { if (is_continuation) { GRPC_CHTTP2_IF_TRACING( gpr_log(GPR_ERROR, @@ -588,7 +590,11 @@ static grpc_error *init_header_frame_parser(grpc_exec_ctx *exec_ctx, GRPC_CHTTP2_IF_TRACING(gpr_log( GPR_ERROR, "ignoring new grpc_chttp2_stream creation on client")); } - return init_skip_frame_parser(exec_ctx, t, 1); + grpc_error* err = init_skip_frame_parser(exec_ctx, t, 1); + if (t->incoming_frame_flags & GRPC_CHTTP2_FLAG_HAS_PRIORITY) { + grpc_chttp2_hpack_parser_set_has_priority(&t->hpack_parser); + } + return err; } else if (t->last_new_stream_id >= t->incoming_stream_id) { GRPC_CHTTP2_IF_TRACING(gpr_log( GPR_ERROR, @@ -611,7 +617,7 @@ static grpc_error *init_header_frame_parser(grpc_exec_ctx *exec_ctx, t->last_new_stream_id = t->incoming_stream_id; s = t->incoming_stream = grpc_chttp2_parsing_accept_stream(exec_ctx, t, t->incoming_stream_id); - if (s == NULL) { + if (s == nullptr) { GRPC_CHTTP2_IF_TRACING( gpr_log(GPR_ERROR, "grpc_chttp2_stream not accepted")); return init_skip_frame_parser(exec_ctx, t, 1); @@ -619,12 +625,12 @@ static grpc_error *init_header_frame_parser(grpc_exec_ctx *exec_ctx, } else { t->incoming_stream = s; } - GPR_ASSERT(s != NULL); + GPR_ASSERT(s != nullptr); s->stats.incoming.framing_bytes += 9; if (s->read_closed) { GRPC_CHTTP2_IF_TRACING(gpr_log( GPR_ERROR, "skipping already closed grpc_chttp2_stream header")); - t->incoming_stream = NULL; + t->incoming_stream = nullptr; return init_skip_frame_parser(exec_ctx, t, 1); } t->parser = grpc_chttp2_header_parser_parse; @@ -633,7 +639,7 @@ static grpc_error *init_header_frame_parser(grpc_exec_ctx *exec_ctx, case 0: if (t->is_client && t->header_eof) { GRPC_CHTTP2_IF_TRACING(gpr_log(GPR_INFO, "parsing Trailers-Only")); - if (s->trailing_metadata_available != NULL) { + if (s->trailing_metadata_available != nullptr) { *s->trailing_metadata_available = true; } t->hpack_parser.on_header = on_trailing_header; @@ -662,16 +668,16 @@ static grpc_error *init_header_frame_parser(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static grpc_error *init_window_update_frame_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { - grpc_error *err = grpc_chttp2_window_update_parser_begin_frame( +static grpc_error* init_window_update_frame_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { + grpc_error* err = grpc_chttp2_window_update_parser_begin_frame( &t->simple.window_update, t->incoming_frame_size, t->incoming_frame_flags); if (err != GRPC_ERROR_NONE) return err; if (t->incoming_stream_id != 0) { - grpc_chttp2_stream *s = t->incoming_stream = + grpc_chttp2_stream* s = t->incoming_stream = grpc_chttp2_parsing_lookup_stream(t, t->incoming_stream_id); - if (s == NULL) { + if (s == nullptr) { return init_skip_frame_parser(exec_ctx, t, 0); } s->stats.incoming.framing_bytes += 9; @@ -681,9 +687,9 @@ static grpc_error *init_window_update_frame_parser(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static grpc_error *init_ping_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { - grpc_error *err = grpc_chttp2_ping_parser_begin_frame( +static grpc_error* init_ping_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { + grpc_error* err = grpc_chttp2_ping_parser_begin_frame( &t->simple.ping, t->incoming_frame_size, t->incoming_frame_flags); if (err != GRPC_ERROR_NONE) return err; t->parser = grpc_chttp2_ping_parser_parse; @@ -691,12 +697,12 @@ static grpc_error *init_ping_parser(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static grpc_error *init_rst_stream_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { - grpc_error *err = grpc_chttp2_rst_stream_parser_begin_frame( +static grpc_error* init_rst_stream_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { + grpc_error* err = grpc_chttp2_rst_stream_parser_begin_frame( &t->simple.rst_stream, t->incoming_frame_size, t->incoming_frame_flags); if (err != GRPC_ERROR_NONE) return err; - grpc_chttp2_stream *s = t->incoming_stream = + grpc_chttp2_stream* s = t->incoming_stream = grpc_chttp2_parsing_lookup_stream(t, t->incoming_stream_id); if (!t->incoming_stream) { return init_skip_frame_parser(exec_ctx, t, 0); @@ -707,9 +713,9 @@ static grpc_error *init_rst_stream_parser(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static grpc_error *init_goaway_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { - grpc_error *err = grpc_chttp2_goaway_parser_begin_frame( +static grpc_error* init_goaway_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { + grpc_error* err = grpc_chttp2_goaway_parser_begin_frame( &t->goaway_parser, t->incoming_frame_size, t->incoming_frame_flags); if (err != GRPC_ERROR_NONE) return err; t->parser = grpc_chttp2_goaway_parser_parse; @@ -717,14 +723,14 @@ static grpc_error *init_goaway_parser(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static grpc_error *init_settings_frame_parser(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { +static grpc_error* init_settings_frame_parser(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { if (t->incoming_stream_id != 0) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Settings frame received for grpc_chttp2_stream"); } - grpc_error *err = grpc_chttp2_settings_parser_begin_frame( + grpc_error* err = grpc_chttp2_settings_parser_begin_frame( &t->simple.settings, t->incoming_frame_size, t->incoming_frame_flags, t->settings[GRPC_PEER_SETTINGS]); if (err != GRPC_ERROR_NONE) { @@ -744,16 +750,16 @@ static grpc_error *init_settings_frame_parser(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static grpc_error *parse_frame_slice(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t, grpc_slice slice, +static grpc_error* parse_frame_slice(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t, grpc_slice slice, int is_last) { - grpc_chttp2_stream *s = t->incoming_stream; - grpc_error *err = t->parser(exec_ctx, t->parser_data, t, s, slice, is_last); + grpc_chttp2_stream* s = t->incoming_stream; + grpc_error* err = t->parser(exec_ctx, t->parser_data, t, s, slice, is_last); if (err == GRPC_ERROR_NONE) { return err; - } else if (grpc_error_get_int(err, GRPC_ERROR_INT_STREAM_ID, NULL)) { - if (GRPC_TRACER_ON(grpc_http_trace)) { - const char *msg = grpc_error_string(err); + } else if (grpc_error_get_int(err, GRPC_ERROR_INT_STREAM_ID, nullptr)) { + if (grpc_http_trace.enabled()) { + const char* msg = grpc_error_string(err); gpr_log(GPR_ERROR, "%s", msg); } grpc_chttp2_parsing_become_skip_parser(exec_ctx, t); diff --git a/src/core/ext/transport/chttp2/transport/stream_lists.cc b/src/core/ext/transport/chttp2/transport/stream_lists.cc index 9f731a397f3..c95d02541a7 100644 --- a/src/core/ext/transport/chttp2/transport/stream_lists.cc +++ b/src/core/ext/transport/chttp2/transport/stream_lists.cc @@ -21,7 +21,7 @@ #include -static const char *stream_list_id_string(grpc_chttp2_stream_list_id id) { +static const char* stream_list_id_string(grpc_chttp2_stream_list_id id) { switch (id) { case GRPC_CHTTP2_LIST_WRITABLE: return "writable"; @@ -39,41 +39,40 @@ static const char *stream_list_id_string(grpc_chttp2_stream_list_id id) { GPR_UNREACHABLE_CODE(return "unknown"); } -grpc_tracer_flag grpc_trace_http2_stream_state = - GRPC_TRACER_INITIALIZER(false, "http2_stream_state"); +grpc_core::TraceFlag grpc_trace_http2_stream_state(false, "http2_stream_state"); /* core list management */ -static bool stream_list_empty(grpc_chttp2_transport *t, +static bool stream_list_empty(grpc_chttp2_transport* t, grpc_chttp2_stream_list_id id) { - return t->lists[id].head == NULL; + return t->lists[id].head == nullptr; } -static bool stream_list_pop(grpc_chttp2_transport *t, - grpc_chttp2_stream **stream, +static bool stream_list_pop(grpc_chttp2_transport* t, + grpc_chttp2_stream** stream, grpc_chttp2_stream_list_id id) { - grpc_chttp2_stream *s = t->lists[id].head; + grpc_chttp2_stream* s = t->lists[id].head; if (s) { - grpc_chttp2_stream *new_head = s->links[id].next; + grpc_chttp2_stream* new_head = s->links[id].next; GPR_ASSERT(s->included[id]); if (new_head) { t->lists[id].head = new_head; - new_head->links[id].prev = NULL; + new_head->links[id].prev = nullptr; } else { - t->lists[id].head = NULL; - t->lists[id].tail = NULL; + t->lists[id].head = nullptr; + t->lists[id].tail = nullptr; } s->included[id] = 0; } *stream = s; - if (s && GRPC_TRACER_ON(grpc_trace_http2_stream_state)) { + if (s && grpc_trace_http2_stream_state.enabled()) { gpr_log(GPR_DEBUG, "%p[%d][%s]: pop from %s", t, s->id, t->is_client ? "cli" : "svr", stream_list_id_string(id)); } - return s != 0; + return s != nullptr; } -static void stream_list_remove(grpc_chttp2_transport *t, grpc_chttp2_stream *s, +static void stream_list_remove(grpc_chttp2_transport* t, grpc_chttp2_stream* s, grpc_chttp2_stream_list_id id) { GPR_ASSERT(s->included[id]); s->included[id] = 0; @@ -88,14 +87,14 @@ static void stream_list_remove(grpc_chttp2_transport *t, grpc_chttp2_stream *s, } else { t->lists[id].tail = s->links[id].prev; } - if (GRPC_TRACER_ON(grpc_trace_http2_stream_state)) { + if (grpc_trace_http2_stream_state.enabled()) { gpr_log(GPR_DEBUG, "%p[%d][%s]: remove from %s", t, s->id, t->is_client ? "cli" : "svr", stream_list_id_string(id)); } } -static bool stream_list_maybe_remove(grpc_chttp2_transport *t, - grpc_chttp2_stream *s, +static bool stream_list_maybe_remove(grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_chttp2_stream_list_id id) { if (s->included[id]) { stream_list_remove(t, s, id); @@ -105,13 +104,13 @@ static bool stream_list_maybe_remove(grpc_chttp2_transport *t, } } -static void stream_list_add_tail(grpc_chttp2_transport *t, - grpc_chttp2_stream *s, +static void stream_list_add_tail(grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_chttp2_stream_list_id id) { - grpc_chttp2_stream *old_tail; + grpc_chttp2_stream* old_tail; GPR_ASSERT(!s->included[id]); old_tail = t->lists[id].tail; - s->links[id].next = NULL; + s->links[id].next = nullptr; s->links[id].prev = old_tail; if (old_tail) { old_tail->links[id].next = s; @@ -120,13 +119,13 @@ static void stream_list_add_tail(grpc_chttp2_transport *t, } t->lists[id].tail = s; s->included[id] = 1; - if (GRPC_TRACER_ON(grpc_trace_http2_stream_state)) { + if (grpc_trace_http2_stream_state.enabled()) { gpr_log(GPR_DEBUG, "%p[%d][%s]: add to %s", t, s->id, t->is_client ? "cli" : "svr", stream_list_id_string(id)); } } -static bool stream_list_add(grpc_chttp2_transport *t, grpc_chttp2_stream *s, +static bool stream_list_add(grpc_chttp2_transport* t, grpc_chttp2_stream* s, grpc_chttp2_stream_list_id id) { if (s->included[id]) { return false; @@ -137,77 +136,77 @@ static bool stream_list_add(grpc_chttp2_transport *t, grpc_chttp2_stream *s, /* wrappers for specializations */ -bool grpc_chttp2_list_add_writable_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream *s) { +bool grpc_chttp2_list_add_writable_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream* s) { GPR_ASSERT(s->id != 0); return stream_list_add(t, s, GRPC_CHTTP2_LIST_WRITABLE); } -bool grpc_chttp2_list_pop_writable_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream **s) { +bool grpc_chttp2_list_pop_writable_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream** s) { return stream_list_pop(t, s, GRPC_CHTTP2_LIST_WRITABLE); } -bool grpc_chttp2_list_remove_writable_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream *s) { +bool grpc_chttp2_list_remove_writable_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream* s) { return stream_list_maybe_remove(t, s, GRPC_CHTTP2_LIST_WRITABLE); } -bool grpc_chttp2_list_add_writing_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream *s) { +bool grpc_chttp2_list_add_writing_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream* s) { return stream_list_add(t, s, GRPC_CHTTP2_LIST_WRITING); } -bool grpc_chttp2_list_have_writing_streams(grpc_chttp2_transport *t) { +bool grpc_chttp2_list_have_writing_streams(grpc_chttp2_transport* t) { return !stream_list_empty(t, GRPC_CHTTP2_LIST_WRITING); } -bool grpc_chttp2_list_pop_writing_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream **s) { +bool grpc_chttp2_list_pop_writing_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream** s) { return stream_list_pop(t, s, GRPC_CHTTP2_LIST_WRITING); } -void grpc_chttp2_list_add_waiting_for_concurrency(grpc_chttp2_transport *t, - grpc_chttp2_stream *s) { +void grpc_chttp2_list_add_waiting_for_concurrency(grpc_chttp2_transport* t, + grpc_chttp2_stream* s) { stream_list_add(t, s, GRPC_CHTTP2_LIST_WAITING_FOR_CONCURRENCY); } -bool grpc_chttp2_list_pop_waiting_for_concurrency(grpc_chttp2_transport *t, - grpc_chttp2_stream **s) { +bool grpc_chttp2_list_pop_waiting_for_concurrency(grpc_chttp2_transport* t, + grpc_chttp2_stream** s) { return stream_list_pop(t, s, GRPC_CHTTP2_LIST_WAITING_FOR_CONCURRENCY); } -void grpc_chttp2_list_remove_waiting_for_concurrency(grpc_chttp2_transport *t, - grpc_chttp2_stream *s) { +void grpc_chttp2_list_remove_waiting_for_concurrency(grpc_chttp2_transport* t, + grpc_chttp2_stream* s) { stream_list_maybe_remove(t, s, GRPC_CHTTP2_LIST_WAITING_FOR_CONCURRENCY); } -void grpc_chttp2_list_add_stalled_by_transport(grpc_chttp2_transport *t, - grpc_chttp2_stream *s) { +void grpc_chttp2_list_add_stalled_by_transport(grpc_chttp2_transport* t, + grpc_chttp2_stream* s) { stream_list_add(t, s, GRPC_CHTTP2_LIST_STALLED_BY_TRANSPORT); } -bool grpc_chttp2_list_pop_stalled_by_transport(grpc_chttp2_transport *t, - grpc_chttp2_stream **s) { +bool grpc_chttp2_list_pop_stalled_by_transport(grpc_chttp2_transport* t, + grpc_chttp2_stream** s) { return stream_list_pop(t, s, GRPC_CHTTP2_LIST_STALLED_BY_TRANSPORT); } -void grpc_chttp2_list_remove_stalled_by_transport(grpc_chttp2_transport *t, - grpc_chttp2_stream *s) { +void grpc_chttp2_list_remove_stalled_by_transport(grpc_chttp2_transport* t, + grpc_chttp2_stream* s) { stream_list_maybe_remove(t, s, GRPC_CHTTP2_LIST_STALLED_BY_TRANSPORT); } -void grpc_chttp2_list_add_stalled_by_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream *s) { +void grpc_chttp2_list_add_stalled_by_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream* s) { stream_list_add(t, s, GRPC_CHTTP2_LIST_STALLED_BY_STREAM); } -bool grpc_chttp2_list_pop_stalled_by_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream **s) { +bool grpc_chttp2_list_pop_stalled_by_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream** s) { return stream_list_pop(t, s, GRPC_CHTTP2_LIST_STALLED_BY_STREAM); } -bool grpc_chttp2_list_remove_stalled_by_stream(grpc_chttp2_transport *t, - grpc_chttp2_stream *s) { +bool grpc_chttp2_list_remove_stalled_by_stream(grpc_chttp2_transport* t, + grpc_chttp2_stream* s) { return stream_list_maybe_remove(t, s, GRPC_CHTTP2_LIST_STALLED_BY_STREAM); } diff --git a/src/core/ext/transport/chttp2/transport/stream_map.cc b/src/core/ext/transport/chttp2/transport/stream_map.cc index d6079a9a33e..e4f08f5a6c0 100644 --- a/src/core/ext/transport/chttp2/transport/stream_map.cc +++ b/src/core/ext/transport/chttp2/transport/stream_map.cc @@ -24,22 +24,22 @@ #include #include -void grpc_chttp2_stream_map_init(grpc_chttp2_stream_map *map, +void grpc_chttp2_stream_map_init(grpc_chttp2_stream_map* map, size_t initial_capacity) { GPR_ASSERT(initial_capacity > 1); - map->keys = (uint32_t *)gpr_malloc(sizeof(uint32_t) * initial_capacity); - map->values = (void **)gpr_malloc(sizeof(void *) * initial_capacity); + map->keys = (uint32_t*)gpr_malloc(sizeof(uint32_t) * initial_capacity); + map->values = (void**)gpr_malloc(sizeof(void*) * initial_capacity); map->count = 0; map->free = 0; map->capacity = initial_capacity; } -void grpc_chttp2_stream_map_destroy(grpc_chttp2_stream_map *map) { +void grpc_chttp2_stream_map_destroy(grpc_chttp2_stream_map* map) { gpr_free(map->keys); gpr_free(map->values); } -static size_t compact(uint32_t *keys, void **values, size_t count) { +static size_t compact(uint32_t* keys, void** values, size_t count) { size_t i, out; for (i = 0, out = 0; i < count; i++) { @@ -53,16 +53,16 @@ static size_t compact(uint32_t *keys, void **values, size_t count) { return out; } -void grpc_chttp2_stream_map_add(grpc_chttp2_stream_map *map, uint32_t key, - void *value) { +void grpc_chttp2_stream_map_add(grpc_chttp2_stream_map* map, uint32_t key, + void* value) { size_t count = map->count; size_t capacity = map->capacity; - uint32_t *keys = map->keys; - void **values = map->values; + uint32_t* keys = map->keys; + void** values = map->values; GPR_ASSERT(count == 0 || keys[count - 1] < key); GPR_ASSERT(value); - GPR_ASSERT(grpc_chttp2_stream_map_find(map, key) == NULL); + GPR_ASSERT(grpc_chttp2_stream_map_find(map, key) == nullptr); if (count == capacity) { if (map->free > capacity / 4) { @@ -73,9 +73,9 @@ void grpc_chttp2_stream_map_add(grpc_chttp2_stream_map *map, uint32_t key, won't help much */ map->capacity = capacity = 3 * capacity / 2; map->keys = keys = - (uint32_t *)gpr_realloc(keys, capacity * sizeof(uint32_t)); + (uint32_t*)gpr_realloc(keys, capacity * sizeof(uint32_t)); map->values = values = - (void **)gpr_realloc(values, capacity * sizeof(void *)); + (void**)gpr_realloc(values, capacity * sizeof(void*)); } } @@ -84,15 +84,15 @@ void grpc_chttp2_stream_map_add(grpc_chttp2_stream_map *map, uint32_t key, map->count = count + 1; } -static void **find(grpc_chttp2_stream_map *map, uint32_t key) { +static void** find(grpc_chttp2_stream_map* map, uint32_t key) { size_t min_idx = 0; size_t max_idx = map->count; size_t mid_idx; - uint32_t *keys = map->keys; - void **values = map->values; + uint32_t* keys = map->keys; + void** values = map->values; uint32_t mid_key; - if (max_idx == 0) return NULL; + if (max_idx == 0) return nullptr; while (min_idx < max_idx) { /* find the midpoint, avoiding overflow */ @@ -109,50 +109,51 @@ static void **find(grpc_chttp2_stream_map *map, uint32_t key) { } } - return NULL; + return nullptr; } -void *grpc_chttp2_stream_map_delete(grpc_chttp2_stream_map *map, uint32_t key) { - void **pvalue = find(map, key); - void *out = NULL; - if (pvalue != NULL) { +void* grpc_chttp2_stream_map_delete(grpc_chttp2_stream_map* map, uint32_t key) { + void** pvalue = find(map, key); + void* out = nullptr; + if (pvalue != nullptr) { out = *pvalue; - *pvalue = NULL; - map->free += (out != NULL); + *pvalue = nullptr; + map->free += (out != nullptr); /* recognize complete emptyness and ensure we can skip * defragmentation later */ if (map->free == map->count) { map->free = map->count = 0; } - GPR_ASSERT(grpc_chttp2_stream_map_find(map, key) == NULL); + GPR_ASSERT(grpc_chttp2_stream_map_find(map, key) == nullptr); } return out; } -void *grpc_chttp2_stream_map_find(grpc_chttp2_stream_map *map, uint32_t key) { - void **pvalue = find(map, key); - return pvalue != NULL ? *pvalue : NULL; +void* grpc_chttp2_stream_map_find(grpc_chttp2_stream_map* map, uint32_t key) { + void** pvalue = find(map, key); + return pvalue != nullptr ? *pvalue : nullptr; } -size_t grpc_chttp2_stream_map_size(grpc_chttp2_stream_map *map) { +size_t grpc_chttp2_stream_map_size(grpc_chttp2_stream_map* map) { return map->count - map->free; } -void *grpc_chttp2_stream_map_rand(grpc_chttp2_stream_map *map) { +void* grpc_chttp2_stream_map_rand(grpc_chttp2_stream_map* map) { if (map->count == map->free) { - return NULL; + return nullptr; } if (map->free != 0) { map->count = compact(map->keys, map->values, map->count); map->free = 0; + GPR_ASSERT(map->count > 0); } return map->values[((size_t)rand()) % map->count]; } -void grpc_chttp2_stream_map_for_each(grpc_chttp2_stream_map *map, - void (*f)(void *user_data, uint32_t key, - void *value), - void *user_data) { +void grpc_chttp2_stream_map_for_each(grpc_chttp2_stream_map* map, + void (*f)(void* user_data, uint32_t key, + void* value), + void* user_data) { size_t i; for (i = 0; i < map->count; i++) { diff --git a/src/core/ext/transport/chttp2/transport/stream_map.h b/src/core/ext/transport/chttp2/transport/stream_map.h index 7ab6a4f5ed0..9fb8826e8e6 100644 --- a/src/core/ext/transport/chttp2/transport/stream_map.h +++ b/src/core/ext/transport/chttp2/transport/stream_map.h @@ -23,10 +23,6 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /* Data structure to map a uint32_t to a data object (represented by a void*) Represented as a sorted array of keys, and a corresponding array of values. @@ -34,43 +30,39 @@ extern "C" { Adds are restricted to strictly higher keys than previously seen (this is guaranteed by http2). */ typedef struct { - uint32_t *keys; - void **values; + uint32_t* keys; + void** values; size_t count; size_t free; size_t capacity; } grpc_chttp2_stream_map; -void grpc_chttp2_stream_map_init(grpc_chttp2_stream_map *map, +void grpc_chttp2_stream_map_init(grpc_chttp2_stream_map* map, size_t initial_capacity); -void grpc_chttp2_stream_map_destroy(grpc_chttp2_stream_map *map); +void grpc_chttp2_stream_map_destroy(grpc_chttp2_stream_map* map); /* Add a new key: given http2 semantics, new keys must always be greater than existing keys - this is asserted */ -void grpc_chttp2_stream_map_add(grpc_chttp2_stream_map *map, uint32_t key, - void *value); +void grpc_chttp2_stream_map_add(grpc_chttp2_stream_map* map, uint32_t key, + void* value); /* Delete an existing key - returns the previous value of the key if it existed, or NULL otherwise */ -void *grpc_chttp2_stream_map_delete(grpc_chttp2_stream_map *map, uint32_t key); +void* grpc_chttp2_stream_map_delete(grpc_chttp2_stream_map* map, uint32_t key); /* Return an existing key, or NULL if it does not exist */ -void *grpc_chttp2_stream_map_find(grpc_chttp2_stream_map *map, uint32_t key); +void* grpc_chttp2_stream_map_find(grpc_chttp2_stream_map* map, uint32_t key); /* Return a random entry */ -void *grpc_chttp2_stream_map_rand(grpc_chttp2_stream_map *map); +void* grpc_chttp2_stream_map_rand(grpc_chttp2_stream_map* map); /* How many (populated) entries are in the stream map? */ -size_t grpc_chttp2_stream_map_size(grpc_chttp2_stream_map *map); +size_t grpc_chttp2_stream_map_size(grpc_chttp2_stream_map* map); /* Callback on each stream */ -void grpc_chttp2_stream_map_for_each(grpc_chttp2_stream_map *map, - void (*f)(void *user_data, uint32_t key, - void *value), - void *user_data); - -#ifdef __cplusplus -} -#endif +void grpc_chttp2_stream_map_for_each(grpc_chttp2_stream_map* map, + void (*f)(void* user_data, uint32_t key, + void* value), + void* user_data); #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_STREAM_MAP_H */ diff --git a/src/core/ext/transport/chttp2/transport/varint.h b/src/core/ext/transport/chttp2/transport/varint.h index d3a9d902c42..5a2b670f065 100644 --- a/src/core/ext/transport/chttp2/transport/varint.h +++ b/src/core/ext/transport/chttp2/transport/varint.h @@ -21,10 +21,6 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /* Helpers for hpack varint encoding */ /* length of a value that needs varint tail encoding (it's bigger than can be @@ -61,8 +57,4 @@ void grpc_chttp2_hpack_write_varint_tail(uint32_t tail_value, uint8_t* target, } \ } while (0) -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_VARINT_H */ diff --git a/src/core/ext/transport/chttp2/transport/writing.cc b/src/core/ext/transport/chttp2/transport/writing.cc index ff76a5fcdb6..204b5a77087 100644 --- a/src/core/ext/transport/chttp2/transport/writing.cc +++ b/src/core/ext/transport/chttp2/transport/writing.cc @@ -27,32 +27,31 @@ #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/transport/http2_errors.h" -static void add_to_write_list(grpc_chttp2_write_cb **list, - grpc_chttp2_write_cb *cb) { +static void add_to_write_list(grpc_chttp2_write_cb** list, + grpc_chttp2_write_cb* cb) { cb->next = *list; *list = cb; } -static void finish_write_cb(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_chttp2_stream *s, grpc_chttp2_write_cb *cb, - grpc_error *error) { +static void finish_write_cb(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_chttp2_stream* s, grpc_chttp2_write_cb* cb, + grpc_error* error) { grpc_chttp2_complete_closure_step(exec_ctx, t, s, &cb->closure, error, "finish_write_cb"); cb->next = t->write_cb_pool; t->write_cb_pool = cb; } -static void maybe_initiate_ping(grpc_exec_ctx *exec_ctx, - grpc_chttp2_transport *t) { - grpc_chttp2_ping_queue *pq = &t->ping_queue; +static void maybe_initiate_ping(grpc_exec_ctx* exec_ctx, + grpc_chttp2_transport* t) { + grpc_chttp2_ping_queue* pq = &t->ping_queue; if (grpc_closure_list_empty(pq->lists[GRPC_CHTTP2_PCL_NEXT])) { /* no ping needed: wait */ return; } if (!grpc_closure_list_empty(pq->lists[GRPC_CHTTP2_PCL_INFLIGHT])) { /* ping already in-flight: wait */ - if (GRPC_TRACER_ON(grpc_http_trace) || - GRPC_TRACER_ON(grpc_bdp_estimator_trace)) { + if (grpc_http_trace.enabled() || grpc_bdp_estimator_trace.enabled()) { gpr_log(GPR_DEBUG, "%s: Ping delayed [%p]: already pinging", t->is_client ? "CLIENT" : "SERVER", t->peer_string); } @@ -61,8 +60,7 @@ static void maybe_initiate_ping(grpc_exec_ctx *exec_ctx, if (t->ping_state.pings_before_data_required == 0 && t->ping_policy.max_pings_without_data != 0) { /* need to receive something of substance before sending a ping again */ - if (GRPC_TRACER_ON(grpc_http_trace) || - GRPC_TRACER_ON(grpc_bdp_estimator_trace)) { + if (grpc_http_trace.enabled() || grpc_bdp_estimator_trace.enabled()) { gpr_log(GPR_DEBUG, "%s: Ping delayed [%p]: too many recent pings: %d/%d", t->is_client ? "CLIENT" : "SERVER", t->peer_string, t->ping_state.pings_before_data_required, @@ -81,11 +79,13 @@ static void maybe_initiate_ping(grpc_exec_ctx *exec_ctx, } if (next_allowed_ping > now) { /* not enough elapsed time between successive pings */ - if (GRPC_TRACER_ON(grpc_http_trace) || - GRPC_TRACER_ON(grpc_bdp_estimator_trace)) { + if (grpc_http_trace.enabled() || grpc_bdp_estimator_trace.enabled()) { gpr_log(GPR_DEBUG, - "%s: Ping delayed [%p]: not enough time elapsed since last ping", - t->is_client ? "CLIENT" : "SERVER", t->peer_string); + "%s: Ping delayed [%p]: not enough time elapsed since last ping. " + " Last ping %f: Next ping %f: Now %f", + t->is_client ? "CLIENT" : "SERVER", t->peer_string, + (double)t->ping_state.last_ping_sent_time, + (double)next_allowed_ping, (double)now); } if (!t->ping_state.is_delayed_ping_timer_set) { t->ping_state.is_delayed_ping_timer_set = true; @@ -94,6 +94,7 @@ static void maybe_initiate_ping(grpc_exec_ctx *exec_ctx, } return; } + pq->inflight_id = t->ping_ctr; t->ping_ctr++; GRPC_CLOSURE_LIST_SCHED(exec_ctx, &pq->lists[GRPC_CHTTP2_PCL_INITIATE]); @@ -103,8 +104,7 @@ static void maybe_initiate_ping(grpc_exec_ctx *exec_ctx, grpc_chttp2_ping_create(false, pq->inflight_id)); GRPC_STATS_INC_HTTP2_PINGS_SENT(exec_ctx); t->ping_state.last_ping_sent_time = now; - if (GRPC_TRACER_ON(grpc_http_trace) || - GRPC_TRACER_ON(grpc_bdp_estimator_trace)) { + if (grpc_http_trace.enabled() || grpc_bdp_estimator_trace.enabled()) { gpr_log(GPR_DEBUG, "%s: Ping sent [%p]: %d/%d", t->is_client ? "CLIENT" : "SERVER", t->peer_string, t->ping_state.pings_before_data_required, @@ -114,16 +114,16 @@ static void maybe_initiate_ping(grpc_exec_ctx *exec_ctx, (t->ping_state.pings_before_data_required != 0); } -static bool update_list(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_chttp2_stream *s, int64_t send_bytes, - grpc_chttp2_write_cb **list, int64_t *ctr, - grpc_error *error) { +static bool update_list(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_chttp2_stream* s, int64_t send_bytes, + grpc_chttp2_write_cb** list, int64_t* ctr, + grpc_error* error) { bool sched_any = false; - grpc_chttp2_write_cb *cb = *list; - *list = NULL; + grpc_chttp2_write_cb* cb = *list; + *list = nullptr; *ctr += send_bytes; while (cb) { - grpc_chttp2_write_cb *next = cb->next; + grpc_chttp2_write_cb* next = cb->next; if (cb->call_at_byte <= *ctr) { sched_any = true; finish_write_cb(exec_ctx, t, s, cb, GRPC_ERROR_REF(error)); @@ -136,8 +136,8 @@ static bool update_list(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, return sched_any; } -static void report_stall(grpc_chttp2_transport *t, grpc_chttp2_stream *s, - const char *staller) { +static void report_stall(grpc_chttp2_transport* t, grpc_chttp2_stream* s, + const char* staller) { gpr_log( GPR_DEBUG, "%s:%p stream %d stalled by %s [fc:pending=%" PRIdPTR ":flowed=%" PRId64 @@ -155,7 +155,7 @@ static void report_stall(grpc_chttp2_transport *t, grpc_chttp2_stream *s, s->flow_control->remote_window_delta()); } -static bool stream_ref_if_not_destroyed(gpr_refcount *r) { +static bool stream_ref_if_not_destroyed(gpr_refcount* r) { gpr_atm count; do { count = gpr_atm_acq_load(&r->count); @@ -165,12 +165,12 @@ static bool stream_ref_if_not_destroyed(gpr_refcount *r) { } /* How many bytes would we like to put on the wire during a single syscall */ -static uint32_t target_write_size(grpc_chttp2_transport *t) { +static uint32_t target_write_size(grpc_chttp2_transport* t) { return 1024 * 1024; } // Returns true if initial_metadata contains only default headers. -static bool is_default_initial_metadata(grpc_metadata_batch *initial_metadata) { +static bool is_default_initial_metadata(grpc_metadata_batch* initial_metadata) { return initial_metadata->list.default_count == initial_metadata->list.count; } @@ -179,13 +179,13 @@ class StreamWriteContext; class WriteContext { public: - WriteContext(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t) : t_(t) { + WriteContext(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t) : t_(t) { GRPC_STATS_INC_HTTP2_WRITES_BEGUN(exec_ctx); GPR_TIMER_BEGIN("grpc_chttp2_begin_write", 0); } // TODO(ctiller): make this the destructor - void FlushStats(grpc_exec_ctx *exec_ctx) { + void FlushStats(grpc_exec_ctx* exec_ctx) { GRPC_STATS_INC_HTTP2_SEND_INITIAL_METADATA_PER_WRITE( exec_ctx, initial_metadata_writes_); GRPC_STATS_INC_HTTP2_SEND_MESSAGE_PER_WRITE(exec_ctx, message_writes_); @@ -194,7 +194,7 @@ class WriteContext { GRPC_STATS_INC_HTTP2_SEND_FLOWCTL_PER_WRITE(exec_ctx, flow_control_writes_); } - void FlushSettings(grpc_exec_ctx *exec_ctx) { + void FlushSettings(grpc_exec_ctx* exec_ctx) { if (t_->dirtied_local_settings && !t_->sent_local_settings) { grpc_slice_buffer_add( &t_->outbuf, grpc_chttp2_settings_create( @@ -208,13 +208,13 @@ class WriteContext { } } - void FlushQueuedBuffers(grpc_exec_ctx *exec_ctx) { + void FlushQueuedBuffers(grpc_exec_ctx* exec_ctx) { /* simple writes are queued to qbuf, and flushed here */ grpc_slice_buffer_move_into(&t_->qbuf, &t_->outbuf); GPR_ASSERT(t_->qbuf.count == 0); } - void FlushWindowUpdates(grpc_exec_ctx *exec_ctx) { + void FlushWindowUpdates(grpc_exec_ctx* exec_ctx) { uint32_t transport_announce = t_->flow_control->MaybeSendUpdate(t_->outbuf.count > 0); if (transport_announce) { @@ -234,7 +234,7 @@ class WriteContext { t_->ping_ack_count = 0; } - void EnactHpackSettings(grpc_exec_ctx *exec_ctx) { + void EnactHpackSettings(grpc_exec_ctx* exec_ctx) { grpc_chttp2_hpack_compressor_set_max_table_size( &t_->hpack_compressor, t_->settings[GRPC_PEER_SETTINGS] @@ -242,7 +242,7 @@ class WriteContext { } void UpdateStreamsNoLongerStalled() { - grpc_chttp2_stream *s; + grpc_chttp2_stream* s; while (grpc_chttp2_list_pop_stalled_by_transport(t_, &s)) { if (t_->closed_with_error == GRPC_ERROR_NONE && grpc_chttp2_list_add_writable_stream(t_, s)) { @@ -253,13 +253,13 @@ class WriteContext { } } - grpc_chttp2_stream *NextStream() { + grpc_chttp2_stream* NextStream() { if (t_->outbuf.length > target_write_size(t_)) { result_.partial = true; return nullptr; } - grpc_chttp2_stream *s; + grpc_chttp2_stream* s; if (!grpc_chttp2_list_pop_writable_stream(t_, &s)) { return nullptr; } @@ -281,7 +281,7 @@ class WriteContext { void NoteScheduledResults() { result_.early_results_scheduled = true; } - grpc_chttp2_transport *transport() const { return t_; } + grpc_chttp2_transport* transport() const { return t_; } grpc_chttp2_begin_write_result Result() { result_.writing = t_->outbuf.count > 0; @@ -289,7 +289,7 @@ class WriteContext { } private: - grpc_chttp2_transport *const t_; + grpc_chttp2_transport* const t_; /* stats histogram counters: we increment these throughout this function, and at the end publish to the central stats histograms */ @@ -302,8 +302,8 @@ class WriteContext { class DataSendContext { public: - DataSendContext(WriteContext *write_context, grpc_chttp2_transport *t, - grpc_chttp2_stream *s) + DataSendContext(WriteContext* write_context, grpc_chttp2_transport* t, + grpc_chttp2_stream* s) : write_context_(write_context), t_(t), s_(s), @@ -322,7 +322,7 @@ class DataSendContext { GPR_MIN(stream_remote_window(), t_->flow_control->remote_window())); } - bool AnyOutgoing() const { return max_outgoing() != 0; } + bool AnyOutgoing() const { return max_outgoing() > 0; } void FlushCompressedBytes() { uint32_t send_bytes = @@ -330,24 +330,25 @@ class DataSendContext { bool is_last_data_frame = (send_bytes == s_->compressed_data_buffer.length && s_->flow_controlled_buffer.length == 0 && - s_->fetching_send_message == NULL); - if (is_last_data_frame && s_->send_trailing_metadata != NULL && - s_->stream_compression_ctx != NULL) { - if (!grpc_stream_compress(s_->stream_compression_ctx, - &s_->flow_controlled_buffer, - &s_->compressed_data_buffer, NULL, MAX_SIZE_T, - GRPC_STREAM_COMPRESSION_FLUSH_FINISH)) { + s_->fetching_send_message == nullptr); + if (is_last_data_frame && s_->send_trailing_metadata != nullptr && + s_->stream_compression_ctx != nullptr) { + if (!grpc_stream_compress( + s_->stream_compression_ctx, &s_->flow_controlled_buffer, + &s_->compressed_data_buffer, nullptr, MAX_SIZE_T, + GRPC_STREAM_COMPRESSION_FLUSH_FINISH)) { gpr_log(GPR_ERROR, "Stream compression failed."); } grpc_stream_compression_context_destroy(s_->stream_compression_ctx); - s_->stream_compression_ctx = NULL; + s_->stream_compression_ctx = nullptr; /* After finish, bytes in s->compressed_data_buffer may be * more than max_outgoing. Start another round of the current * while loop so that send_bytes and is_last_data_frame are * recalculated. */ return; } - is_last_frame_ = is_last_data_frame && s_->send_trailing_metadata != NULL && + is_last_frame_ = is_last_data_frame && + s_->send_trailing_metadata != nullptr && grpc_metadata_batch_is_empty(s_->send_trailing_metadata); grpc_chttp2_encode_data(s_->id, &s_->compressed_data_buffer, send_bytes, is_last_frame_, &s_->stats.outgoing, &t_->outbuf); @@ -358,14 +359,14 @@ class DataSendContext { } void CompressMoreBytes() { - if (s_->stream_compression_ctx == NULL) { + if (s_->stream_compression_ctx == nullptr) { s_->stream_compression_ctx = grpc_stream_compression_context_create(s_->stream_compression_method); } s_->uncompressed_data_size = s_->flow_controlled_buffer.length; if (!grpc_stream_compress(s_->stream_compression_ctx, &s_->flow_controlled_buffer, - &s_->compressed_data_buffer, NULL, MAX_SIZE_T, + &s_->compressed_data_buffer, nullptr, MAX_SIZE_T, GRPC_STREAM_COMPRESSION_FLUSH_SYNC)) { gpr_log(GPR_ERROR, "Stream compression failed."); } @@ -373,7 +374,7 @@ class DataSendContext { bool is_last_frame() const { return is_last_frame_; } - void CallCallbacks(grpc_exec_ctx *exec_ctx) { + void CallCallbacks(grpc_exec_ctx* exec_ctx) { if (update_list(exec_ctx, t_, s_, (int64_t)(s_->sending_bytes - sending_bytes_before_), &s_->on_flow_controlled_cbs, @@ -383,26 +384,26 @@ class DataSendContext { } private: - WriteContext *write_context_; - grpc_chttp2_transport *t_; - grpc_chttp2_stream *s_; + WriteContext* write_context_; + grpc_chttp2_transport* t_; + grpc_chttp2_stream* s_; const size_t sending_bytes_before_; bool is_last_frame_ = false; }; class StreamWriteContext { public: - StreamWriteContext(WriteContext *write_context, grpc_chttp2_stream *s) + StreamWriteContext(WriteContext* write_context, grpc_chttp2_stream* s) : write_context_(write_context), t_(write_context->transport()), s_(s) { GRPC_CHTTP2_IF_TRACING( gpr_log(GPR_DEBUG, "W:%p %s[%d] im-(sent,send)=(%d,%d) announce=%d", t_, t_->is_client ? "CLIENT" : "SERVER", s->id, - s->sent_initial_metadata, s->send_initial_metadata != NULL, + s->sent_initial_metadata, s->send_initial_metadata != nullptr, (int)(s->flow_control->local_window_delta() - s->flow_control->announced_window_delta()))); } - void FlushInitialMetadata(grpc_exec_ctx *exec_ctx) { + void FlushInitialMetadata(grpc_exec_ctx* exec_ctx) { /* send initial metadata if it's available */ if (s_->sent_initial_metadata) return; if (s_->send_initial_metadata == nullptr) return; @@ -429,13 +430,13 @@ class StreamWriteContext { [GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE], // max_frame_size &s_->stats.outgoing // stats }; - grpc_chttp2_encode_header(exec_ctx, &t_->hpack_compressor, NULL, 0, + grpc_chttp2_encode_header(exec_ctx, &t_->hpack_compressor, nullptr, 0, s_->send_initial_metadata, &hopt, &t_->outbuf); write_context_->ResetPingRecvClock(); write_context_->IncInitialMetadataWrites(); } - s_->send_initial_metadata = NULL; + s_->send_initial_metadata = nullptr; s_->sent_initial_metadata = true; write_context_->NoteScheduledResults(); grpc_chttp2_complete_closure_step( @@ -443,7 +444,7 @@ class StreamWriteContext { "send_initial_metadata_finished"); } - void FlushWindowUpdates(grpc_exec_ctx *exec_ctx) { + void FlushWindowUpdates(grpc_exec_ctx* exec_ctx) { /* send any window updates */ const uint32_t stream_announce = s_->flow_control->MaybeSendUpdate(); if (stream_announce == 0) return; @@ -455,7 +456,7 @@ class StreamWriteContext { write_context_->IncWindowUpdateWrites(); } - void FlushData(grpc_exec_ctx *exec_ctx) { + void FlushData(grpc_exec_ctx* exec_ctx) { if (!s_->sent_initial_metadata) return; if (s_->flow_controlled_buffer.length == 0 && @@ -499,11 +500,11 @@ class StreamWriteContext { write_context_->IncMessageWrites(); } - void FlushTrailingMetadata(grpc_exec_ctx *exec_ctx) { + void FlushTrailingMetadata(grpc_exec_ctx* exec_ctx) { if (!s_->sent_initial_metadata) return; - if (s_->send_trailing_metadata == NULL) return; - if (s_->fetching_send_message != NULL) return; + if (s_->send_trailing_metadata == nullptr) return; + if (s_->fetching_send_message != nullptr) return; if (s_->flow_controlled_buffer.length != 0) return; if (s_->compressed_data_buffer.length != 0) return; @@ -543,20 +544,20 @@ class StreamWriteContext { gpr_log(GPR_INFO, "not sending initial_metadata (Trailers-Only)")); // When sending Trailers-Only, we need to move the :status and // content-type headers to the trailers. - if (s_->send_initial_metadata->idx.named.status != NULL) { + if (s_->send_initial_metadata->idx.named.status != nullptr) { extra_headers_for_trailing_metadata_ [num_extra_headers_for_trailing_metadata_++] = &s_->send_initial_metadata->idx.named.status->md; } - if (s_->send_initial_metadata->idx.named.content_type != NULL) { + if (s_->send_initial_metadata->idx.named.content_type != nullptr) { extra_headers_for_trailing_metadata_ [num_extra_headers_for_trailing_metadata_++] = &s_->send_initial_metadata->idx.named.content_type->md; } } - void SentLastFrame(grpc_exec_ctx *exec_ctx) { - s_->send_trailing_metadata = NULL; + void SentLastFrame(grpc_exec_ctx* exec_ctx) { + s_->send_trailing_metadata = nullptr; s_->sent_trailing_metadata = true; if (!t_->is_client && !s_->read_closed) { @@ -568,17 +569,17 @@ class StreamWriteContext { GRPC_ERROR_NONE); } - WriteContext *const write_context_; - grpc_chttp2_transport *const t_; - grpc_chttp2_stream *const s_; + WriteContext* const write_context_; + grpc_chttp2_transport* const t_; + grpc_chttp2_stream* const s_; bool stream_became_writable_ = false; - grpc_mdelem *extra_headers_for_trailing_metadata_[2]; + grpc_mdelem* extra_headers_for_trailing_metadata_[2]; size_t num_extra_headers_for_trailing_metadata_ = 0; }; } // namespace grpc_chttp2_begin_write_result grpc_chttp2_begin_write( - grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t) { + grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t) { WriteContext ctx(exec_ctx, t); ctx.FlushSettings(exec_ctx); ctx.FlushPingAcks(); @@ -591,7 +592,7 @@ grpc_chttp2_begin_write_result grpc_chttp2_begin_write( /* for each grpc_chttp2_stream that's become writable, frame it's data (according to available window sizes) and add to the output buffer */ - while (grpc_chttp2_stream *s = ctx.NextStream()) { + while (grpc_chttp2_stream* s = ctx.NextStream()) { StreamWriteContext stream_ctx(&ctx, s); stream_ctx.FlushInitialMetadata(exec_ctx); stream_ctx.FlushWindowUpdates(exec_ctx); @@ -619,10 +620,10 @@ grpc_chttp2_begin_write_result grpc_chttp2_begin_write( return ctx.Result(); } -void grpc_chttp2_end_write(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, - grpc_error *error) { +void grpc_chttp2_end_write(grpc_exec_ctx* exec_ctx, grpc_chttp2_transport* t, + grpc_error* error) { GPR_TIMER_BEGIN("grpc_chttp2_end_write", 0); - grpc_chttp2_stream *s; + grpc_chttp2_stream* s; while (grpc_chttp2_list_pop_writing_stream(t, &s)) { if (s->sending_bytes != 0) { diff --git a/src/core/ext/transport/cronet/client/secure/cronet_channel_create.cc b/src/core/ext/transport/cronet/client/secure/cronet_channel_create.cc index b280487ca3e..d590ba03711 100644 --- a/src/core/ext/transport/cronet/client/secure/cronet_channel_create.cc +++ b/src/core/ext/transport/cronet/client/secure/cronet_channel_create.cc @@ -33,20 +33,20 @@ // Cronet transport object typedef struct cronet_transport { grpc_transport base; // must be first element in this structure - void *engine; - char *host; + void* engine; + char* host; } cronet_transport; extern grpc_transport_vtable grpc_cronet_vtable; -GRPCAPI grpc_channel *grpc_cronet_secure_channel_create( - void *engine, const char *target, const grpc_channel_args *args, - void *reserved) { +GRPCAPI grpc_channel* grpc_cronet_secure_channel_create( + void* engine, const char* target, const grpc_channel_args* args, + void* reserved) { gpr_log(GPR_DEBUG, "grpc_create_cronet_transport: stream_engine = %p, target=%s", engine, target); - grpc_transport *ct = + grpc_transport* ct = grpc_create_cronet_transport(engine, target, args, reserved); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; diff --git a/src/core/ext/transport/cronet/transport/cronet_api_dummy.cc b/src/core/ext/transport/cronet/transport/cronet_api_dummy.cc index 4f248ad9194..578cbb8ac6c 100644 --- a/src/core/ext/transport/cronet/transport/cronet_api_dummy.cc +++ b/src/core/ext/transport/cronet/transport/cronet_api_dummy.cc @@ -33,7 +33,7 @@ bidirectional_stream* bidirectional_stream_create( stream_engine* engine, void* annotation, bidirectional_stream_callback* callback) { GPR_ASSERT(0); - return NULL; + return nullptr; } int bidirectional_stream_destroy(bidirectional_stream* stream) { diff --git a/src/core/ext/transport/cronet/transport/cronet_transport.cc b/src/core/ext/transport/cronet/transport/cronet_transport.cc index 97e4f7d72bc..4d24efe47b1 100644 --- a/src/core/ext/transport/cronet/transport/cronet_transport.cc +++ b/src/core/ext/transport/cronet/transport/cronet_transport.cc @@ -75,17 +75,17 @@ enum e_op_id { /* Cronet callbacks. See cronet_c_for_grpc.h for documentation for each. */ -static void on_stream_ready(bidirectional_stream *); +static void on_stream_ready(bidirectional_stream*); static void on_response_headers_received( - bidirectional_stream *, const bidirectional_stream_header_array *, - const char *); -static void on_write_completed(bidirectional_stream *, const char *); -static void on_read_completed(bidirectional_stream *, char *, int); + bidirectional_stream*, const bidirectional_stream_header_array*, + const char*); +static void on_write_completed(bidirectional_stream*, const char*); +static void on_read_completed(bidirectional_stream*, char*, int); static void on_response_trailers_received( - bidirectional_stream *, const bidirectional_stream_header_array *); -static void on_succeeded(bidirectional_stream *); -static void on_failed(bidirectional_stream *, int); -static void on_canceled(bidirectional_stream *); + bidirectional_stream*, const bidirectional_stream_header_array*); +static void on_succeeded(bidirectional_stream*); +static void on_failed(bidirectional_stream*, int); +static void on_canceled(bidirectional_stream*); static bidirectional_stream_callback cronet_callbacks = { on_stream_ready, on_response_headers_received, @@ -99,8 +99,8 @@ static bidirectional_stream_callback cronet_callbacks = { /* Cronet transport object */ struct grpc_cronet_transport { grpc_transport base; /* must be first element in this structure */ - stream_engine *engine; - char *host; + stream_engine* engine; + char* host; bool use_packet_coalescing; }; typedef struct grpc_cronet_transport grpc_cronet_transport; @@ -109,14 +109,14 @@ typedef struct grpc_cronet_transport grpc_cronet_transport; http://www.catb.org/esr/structure-packing/#_structure_reordering: */ struct read_state { /* vars to store data coming from server */ - char *read_buffer; + char* read_buffer; bool length_field_received; int received_bytes; int remaining_bytes; int length_field; bool compressed; char grpc_header_bytes[GRPC_HEADER_SIZE_IN_BYTES]; - char *payload_field; + char* payload_field; bool read_stream_closed; /* vars for holding data destined for the application */ @@ -132,7 +132,7 @@ struct read_state { }; struct write_state { - char *write_buffer; + char* write_buffer; }; /* track state of one stream op */ @@ -150,7 +150,7 @@ struct op_state { bool pending_recv_trailing_metadata; /* Cronet has not issued a callback of a bidirectional read */ bool pending_read_from_cronet; - grpc_error *cancel_error; + grpc_error* cancel_error; /* data structure for storing data coming from server */ struct read_state rs; /* data structure for storing data going to the server */ @@ -161,22 +161,22 @@ struct op_and_state { grpc_transport_stream_op_batch op; struct op_state state; bool done; - struct stream_obj *s; /* Pointer back to the stream object */ - struct op_and_state *next; /* next op_and_state in the linked list */ + struct stream_obj* s; /* Pointer back to the stream object */ + struct op_and_state* next; /* next op_and_state in the linked list */ }; struct op_storage { int num_pending_ops; - struct op_and_state *head; + struct op_and_state* head; }; struct stream_obj { - gpr_arena *arena; - struct op_and_state *oas; - grpc_transport_stream_op_batch *curr_op; - grpc_cronet_transport *curr_ct; - grpc_stream *curr_gs; - bidirectional_stream *cbs; + gpr_arena* arena; + struct op_and_state* oas; + grpc_transport_stream_op_batch* curr_op; + grpc_cronet_transport* curr_ct; + grpc_stream* curr_gs; + bidirectional_stream* cbs; bidirectional_stream_header_array header_array; /* Stream level state. Some state will be tracked both at stream and stream_op @@ -190,7 +190,7 @@ struct stream_obj { gpr_mu mu; /* Refcount object of the stream */ - grpc_stream_refcount *refcount; + grpc_stream_refcount* refcount; }; typedef struct stream_obj stream_obj; @@ -199,30 +199,30 @@ typedef struct stream_obj stream_obj; grpc_cronet_stream_ref((stream), (reason)) #define GRPC_CRONET_STREAM_UNREF(exec_ctx, stream, reason) \ grpc_cronet_stream_unref((exec_ctx), (stream), (reason)) -void grpc_cronet_stream_ref(stream_obj *s, const char *reason) { +void grpc_cronet_stream_ref(stream_obj* s, const char* reason) { grpc_stream_ref(s->refcount, reason); } -void grpc_cronet_stream_unref(grpc_exec_ctx *exec_ctx, stream_obj *s, - const char *reason) { +void grpc_cronet_stream_unref(grpc_exec_ctx* exec_ctx, stream_obj* s, + const char* reason) { grpc_stream_unref(exec_ctx, s->refcount, reason); } #else #define GRPC_CRONET_STREAM_REF(stream, reason) grpc_cronet_stream_ref((stream)) #define GRPC_CRONET_STREAM_UNREF(exec_ctx, stream, reason) \ grpc_cronet_stream_unref((exec_ctx), (stream)) -void grpc_cronet_stream_ref(stream_obj *s) { grpc_stream_ref(s->refcount); } -void grpc_cronet_stream_unref(grpc_exec_ctx *exec_ctx, stream_obj *s) { +void grpc_cronet_stream_ref(stream_obj* s) { grpc_stream_ref(s->refcount); } +void grpc_cronet_stream_unref(grpc_exec_ctx* exec_ctx, stream_obj* s) { grpc_stream_unref(exec_ctx, s->refcount); } #endif -static enum e_op_result execute_stream_op(grpc_exec_ctx *exec_ctx, - struct op_and_state *oas); +static enum e_op_result execute_stream_op(grpc_exec_ctx* exec_ctx, + struct op_and_state* oas); /* Utility function to translate enum into string for printing */ -static const char *op_result_string(enum e_op_result i) { +static const char* op_result_string(enum e_op_result i) { switch (i) { case ACTION_TAKEN_WITH_CALLBACK: return "ACTION_TAKEN_WITH_CALLBACK"; @@ -234,7 +234,7 @@ static const char *op_result_string(enum e_op_result i) { GPR_UNREACHABLE_CODE(return "UNKNOWN"); } -static const char *op_id_string(enum e_op_id i) { +static const char* op_id_string(enum e_op_id i) { switch (i) { case OP_SEND_INITIAL_METADATA: return "OP_SEND_INITIAL_METADATA"; @@ -268,15 +268,15 @@ static const char *op_id_string(enum e_op_id i) { return "UNKNOWN"; } -static void null_and_maybe_free_read_buffer(stream_obj *s) { +static void null_and_maybe_free_read_buffer(stream_obj* s) { if (s->state.rs.read_buffer && s->state.rs.read_buffer != s->state.rs.grpc_header_bytes) { gpr_free(s->state.rs.read_buffer); } - s->state.rs.read_buffer = NULL; + s->state.rs.read_buffer = nullptr; } -static void maybe_flush_read(stream_obj *s) { +static void maybe_flush_read(stream_obj* s) { /* To enter flush read state (discarding all the buffered messages in * transport layer), two conditions must be satisfied: 1) non-zero grpc status * has been received, and 2) an op requesting the status code @@ -289,7 +289,7 @@ static void maybe_flush_read(stream_obj *s) { CRONET_LOG(GPR_DEBUG, "%p: Flush read", s); s->state.flush_read = true; null_and_maybe_free_read_buffer(s); - s->state.rs.read_buffer = (char *)gpr_malloc(GRPC_FLUSH_READ_SIZE); + s->state.rs.read_buffer = (char*)gpr_malloc(GRPC_FLUSH_READ_SIZE); if (!s->state.pending_read_from_cronet) { CRONET_LOG(GPR_DEBUG, "bidirectional_stream_read(%p)", s->cbs); bidirectional_stream_read(s->cbs, s->state.rs.read_buffer, @@ -300,8 +300,8 @@ static void maybe_flush_read(stream_obj *s) { } } -static grpc_error *make_error_with_desc(int error_code, const char *desc) { - grpc_error *error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(desc); +static grpc_error* make_error_with_desc(int error_code, const char* desc) { + grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(desc); error = grpc_error_set_int(error, GRPC_ERROR_INT_GRPC_STATUS, error_code); return error; } @@ -309,13 +309,13 @@ static grpc_error *make_error_with_desc(int error_code, const char *desc) { /* Add a new stream op to op storage. */ -static void add_to_storage(struct stream_obj *s, - grpc_transport_stream_op_batch *op) { - struct op_storage *storage = &s->storage; +static void add_to_storage(struct stream_obj* s, + grpc_transport_stream_op_batch* op) { + struct op_storage* storage = &s->storage; /* add new op at the beginning of the linked list. The memory is freed in remove_from_storage */ - struct op_and_state *new_op = - (struct op_and_state *)gpr_malloc(sizeof(struct op_and_state)); + struct op_and_state* new_op = + (struct op_and_state*)gpr_malloc(sizeof(struct op_and_state)); memcpy(&new_op->op, op, sizeof(grpc_transport_stream_op_batch)); memset(&new_op->state, 0, sizeof(new_op->state)); new_op->s = s; @@ -339,10 +339,10 @@ static void add_to_storage(struct stream_obj *s, /* Traverse the linked list and delete op and free memory */ -static void remove_from_storage(struct stream_obj *s, - struct op_and_state *oas) { - struct op_and_state *curr; - if (s->storage.head == NULL || oas == NULL) { +static void remove_from_storage(struct stream_obj* s, + struct op_and_state* oas) { + struct op_and_state* curr; + if (s->storage.head == nullptr || oas == nullptr) { return; } if (s->storage.head == oas) { @@ -352,7 +352,7 @@ static void remove_from_storage(struct stream_obj *s, CRONET_LOG(GPR_DEBUG, "Freed %p. Now %d in the queue", oas, s->storage.num_pending_ops); } else { - for (curr = s->storage.head; curr != NULL; curr = curr->next) { + for (curr = s->storage.head; curr != nullptr; curr = curr->next) { if (curr->next == oas) { curr->next = oas->next; s->storage.num_pending_ops--; @@ -360,7 +360,7 @@ static void remove_from_storage(struct stream_obj *s, s->storage.num_pending_ops); gpr_free(oas); break; - } else if (curr->next == NULL) { + } else if (curr->next == nullptr) { CRONET_LOG(GPR_ERROR, "Reached end of LL and did not find op to free"); } } @@ -373,9 +373,9 @@ static void remove_from_storage(struct stream_obj *s, This can get executed from the Cronet network thread via cronet callback or on the application supplied thread via the perform_stream_op function. */ -static void execute_from_storage(grpc_exec_ctx *exec_ctx, stream_obj *s) { +static void execute_from_storage(grpc_exec_ctx* exec_ctx, stream_obj* s) { gpr_mu_lock(&s->mu); - for (struct op_and_state *curr = s->storage.head; curr != NULL;) { + for (struct op_and_state* curr = s->storage.head; curr != nullptr;) { CRONET_LOG(GPR_DEBUG, "calling op at %p. done = %d", curr, curr->done); GPR_ASSERT(curr->done == 0); enum e_op_result result = execute_stream_op(exec_ctx, curr); @@ -383,7 +383,7 @@ static void execute_from_storage(grpc_exec_ctx *exec_ctx, stream_obj *s) { op_result_string(result)); /* if this op is done, then remove it and free memory */ if (curr->done) { - struct op_and_state *next = curr->next; + struct op_and_state* next = curr->next; remove_from_storage(s, curr); curr = next; } @@ -400,22 +400,22 @@ static void execute_from_storage(grpc_exec_ctx *exec_ctx, stream_obj *s) { /* Cronet callback */ -static void on_failed(bidirectional_stream *stream, int net_error) { +static void on_failed(bidirectional_stream* stream, int net_error) { CRONET_LOG(GPR_DEBUG, "on_failed(%p, %d)", stream, net_error); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - stream_obj *s = (stream_obj *)stream->annotation; + stream_obj* s = (stream_obj*)stream->annotation; gpr_mu_lock(&s->mu); bidirectional_stream_destroy(s->cbs); s->state.state_callback_received[OP_FAILED] = true; - s->cbs = NULL; + s->cbs = nullptr; if (s->header_array.headers) { gpr_free(s->header_array.headers); - s->header_array.headers = NULL; + s->header_array.headers = nullptr; } if (s->state.ws.write_buffer) { gpr_free(s->state.ws.write_buffer); - s->state.ws.write_buffer = NULL; + s->state.ws.write_buffer = nullptr; } null_and_maybe_free_read_buffer(s); gpr_mu_unlock(&s->mu); @@ -427,22 +427,22 @@ static void on_failed(bidirectional_stream *stream, int net_error) { /* Cronet callback */ -static void on_canceled(bidirectional_stream *stream) { +static void on_canceled(bidirectional_stream* stream) { CRONET_LOG(GPR_DEBUG, "on_canceled(%p)", stream); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - stream_obj *s = (stream_obj *)stream->annotation; + stream_obj* s = (stream_obj*)stream->annotation; gpr_mu_lock(&s->mu); bidirectional_stream_destroy(s->cbs); s->state.state_callback_received[OP_CANCELED] = true; - s->cbs = NULL; + s->cbs = nullptr; if (s->header_array.headers) { gpr_free(s->header_array.headers); - s->header_array.headers = NULL; + s->header_array.headers = nullptr; } if (s->state.ws.write_buffer) { gpr_free(s->state.ws.write_buffer); - s->state.ws.write_buffer = NULL; + s->state.ws.write_buffer = nullptr; } null_and_maybe_free_read_buffer(s); gpr_mu_unlock(&s->mu); @@ -454,15 +454,15 @@ static void on_canceled(bidirectional_stream *stream) { /* Cronet callback */ -static void on_succeeded(bidirectional_stream *stream) { +static void on_succeeded(bidirectional_stream* stream) { CRONET_LOG(GPR_DEBUG, "on_succeeded(%p)", stream); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - stream_obj *s = (stream_obj *)stream->annotation; + stream_obj* s = (stream_obj*)stream->annotation; gpr_mu_lock(&s->mu); bidirectional_stream_destroy(s->cbs); s->state.state_callback_received[OP_SUCCEEDED] = true; - s->cbs = NULL; + s->cbs = nullptr; null_and_maybe_free_read_buffer(s); gpr_mu_unlock(&s->mu); execute_from_storage(&exec_ctx, s); @@ -473,18 +473,18 @@ static void on_succeeded(bidirectional_stream *stream) { /* Cronet callback */ -static void on_stream_ready(bidirectional_stream *stream) { +static void on_stream_ready(bidirectional_stream* stream) { CRONET_LOG(GPR_DEBUG, "W: on_stream_ready(%p)", stream); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - stream_obj *s = (stream_obj *)stream->annotation; - grpc_cronet_transport *t = (grpc_cronet_transport *)s->curr_ct; + stream_obj* s = (stream_obj*)stream->annotation; + grpc_cronet_transport* t = (grpc_cronet_transport*)s->curr_ct; gpr_mu_lock(&s->mu); s->state.state_op_done[OP_SEND_INITIAL_METADATA] = true; s->state.state_callback_received[OP_SEND_INITIAL_METADATA] = true; /* Free the memory allocated for headers */ if (s->header_array.headers) { gpr_free(s->header_array.headers); - s->header_array.headers = NULL; + s->header_array.headers = nullptr; } /* Send the initial metadata on wire if there is no SEND_MESSAGE or * SEND_TRAILING_METADATA ops pending */ @@ -503,13 +503,13 @@ static void on_stream_ready(bidirectional_stream *stream) { Cronet callback */ static void on_response_headers_received( - bidirectional_stream *stream, - const bidirectional_stream_header_array *headers, - const char *negotiated_protocol) { + bidirectional_stream* stream, + const bidirectional_stream_header_array* headers, + const char* negotiated_protocol) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; CRONET_LOG(GPR_DEBUG, "R: on_response_headers_received(%p, %p, %s)", stream, headers, negotiated_protocol); - stream_obj *s = (stream_obj *)stream->annotation; + stream_obj* s = (stream_obj*)stream->annotation; /* Identify if this is a header or a trailer (in a trailer-only response case) */ @@ -526,15 +526,15 @@ static void on_response_headers_received( grpc_chttp2_incoming_metadata_buffer_init(&s->state.rs.initial_metadata, s->arena); for (size_t i = 0; i < headers->count; i++) { - GRPC_LOG_IF_ERROR( - "on_response_headers_received", - grpc_chttp2_incoming_metadata_buffer_add( - &exec_ctx, &s->state.rs.initial_metadata, - grpc_mdelem_from_slices( - &exec_ctx, grpc_slice_intern(grpc_slice_from_static_string( - headers->headers[i].key)), - grpc_slice_intern(grpc_slice_from_static_string( - headers->headers[i].value))))); + GRPC_LOG_IF_ERROR("on_response_headers_received", + grpc_chttp2_incoming_metadata_buffer_add( + &exec_ctx, &s->state.rs.initial_metadata, + grpc_mdelem_from_slices( + &exec_ctx, + grpc_slice_intern(grpc_slice_from_static_string( + headers->headers[i].key)), + grpc_slice_intern(grpc_slice_from_static_string( + headers->headers[i].value))))); } s->state.state_callback_received[OP_RECV_INITIAL_METADATA] = true; if (!(s->state.state_op_done[OP_CANCEL_ERROR] || @@ -559,14 +559,14 @@ static void on_response_headers_received( /* Cronet callback */ -static void on_write_completed(bidirectional_stream *stream, const char *data) { +static void on_write_completed(bidirectional_stream* stream, const char* data) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - stream_obj *s = (stream_obj *)stream->annotation; + stream_obj* s = (stream_obj*)stream->annotation; CRONET_LOG(GPR_DEBUG, "W: on_write_completed(%p, %s)", stream, data); gpr_mu_lock(&s->mu); if (s->state.ws.write_buffer) { gpr_free(s->state.ws.write_buffer); - s->state.ws.write_buffer = NULL; + s->state.ws.write_buffer = nullptr; } s->state.state_callback_received[OP_SEND_MESSAGE] = true; gpr_mu_unlock(&s->mu); @@ -577,10 +577,10 @@ static void on_write_completed(bidirectional_stream *stream, const char *data) { /* Cronet callback */ -static void on_read_completed(bidirectional_stream *stream, char *data, +static void on_read_completed(bidirectional_stream* stream, char* data, int count) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - stream_obj *s = (stream_obj *)stream->annotation; + stream_obj* s = (stream_obj*)stream->annotation; CRONET_LOG(GPR_DEBUG, "R: on_read_completed(%p, %p, %d)", stream, data, count); gpr_mu_lock(&s->mu); @@ -620,13 +620,13 @@ static void on_read_completed(bidirectional_stream *stream, char *data, Cronet callback */ static void on_response_trailers_received( - bidirectional_stream *stream, - const bidirectional_stream_header_array *trailers) { + bidirectional_stream* stream, + const bidirectional_stream_header_array* trailers) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; CRONET_LOG(GPR_DEBUG, "R: on_response_trailers_received(%p,%p)", stream, trailers); - stream_obj *s = (stream_obj *)stream->annotation; - grpc_cronet_transport *t = (grpc_cronet_transport *)s->curr_ct; + stream_obj* s = (stream_obj*)stream->annotation; + grpc_cronet_transport* t = (grpc_cronet_transport*)s->curr_ct; gpr_mu_lock(&s->mu); memset(&s->state.rs.trailing_metadata, 0, sizeof(s->state.rs.trailing_metadata)); @@ -636,15 +636,15 @@ static void on_response_trailers_received( for (size_t i = 0; i < trailers->count; i++) { CRONET_LOG(GPR_DEBUG, "trailer key=%s, value=%s", trailers->headers[i].key, trailers->headers[i].value); - GRPC_LOG_IF_ERROR( - "on_response_trailers_received", - grpc_chttp2_incoming_metadata_buffer_add( - &exec_ctx, &s->state.rs.trailing_metadata, - grpc_mdelem_from_slices( - &exec_ctx, grpc_slice_intern(grpc_slice_from_static_string( - trailers->headers[i].key)), - grpc_slice_intern(grpc_slice_from_static_string( - trailers->headers[i].value))))); + GRPC_LOG_IF_ERROR("on_response_trailers_received", + grpc_chttp2_incoming_metadata_buffer_add( + &exec_ctx, &s->state.rs.trailing_metadata, + grpc_mdelem_from_slices( + &exec_ctx, + grpc_slice_intern(grpc_slice_from_static_string( + trailers->headers[i].key)), + grpc_slice_intern(grpc_slice_from_static_string( + trailers->headers[i].value))))); s->state.rs.trailing_metadata_valid = true; if (0 == strcmp(trailers->headers[i].key, "grpc-status") && 0 != strcmp(trailers->headers[i].value, "0")) { @@ -679,17 +679,17 @@ static void on_response_trailers_received( Utility function that takes the data from s->write_slice_buffer and assembles into a contiguous byte stream with 5 byte gRPC header prepended. */ -static void create_grpc_frame(grpc_exec_ctx *exec_ctx, - grpc_slice_buffer *write_slice_buffer, - char **pp_write_buffer, - size_t *p_write_buffer_size, uint32_t flags) { +static void create_grpc_frame(grpc_exec_ctx* exec_ctx, + grpc_slice_buffer* write_slice_buffer, + char** pp_write_buffer, + size_t* p_write_buffer_size, uint32_t flags) { grpc_slice slice = grpc_slice_buffer_take_first(write_slice_buffer); size_t length = GRPC_SLICE_LENGTH(slice); *p_write_buffer_size = length + GRPC_HEADER_SIZE_IN_BYTES; /* This is freed in the on_write_completed callback */ - char *write_buffer = (char *)gpr_malloc(length + GRPC_HEADER_SIZE_IN_BYTES); + char* write_buffer = (char*)gpr_malloc(length + GRPC_HEADER_SIZE_IN_BYTES); *pp_write_buffer = write_buffer; - uint8_t *p = (uint8_t *)write_buffer; + uint8_t* p = (uint8_t*)write_buffer; /* Append 5 byte header */ /* Compressed flag */ *p++ = (uint8_t)((flags & GRPC_WRITE_INTERNAL_COMPRESS) ? 1 : 0); @@ -707,20 +707,20 @@ static void create_grpc_frame(grpc_exec_ctx *exec_ctx, Convert metadata in a format that Cronet can consume */ static void convert_metadata_to_cronet_headers( - grpc_linked_mdelem *head, const char *host, char **pp_url, - bidirectional_stream_header **pp_headers, size_t *p_num_headers, - const char **method) { - grpc_linked_mdelem *curr = head; + grpc_linked_mdelem* head, const char* host, char** pp_url, + bidirectional_stream_header** pp_headers, size_t* p_num_headers, + const char** method) { + grpc_linked_mdelem* curr = head; /* Walk the linked list and get number of header fields */ size_t num_headers_available = 0; - while (curr != NULL) { + while (curr != nullptr) { curr = curr->next; num_headers_available++; } /* Allocate enough memory. It is freed in the on_stream_ready callback */ - bidirectional_stream_header *headers = - (bidirectional_stream_header *)gpr_malloc( + bidirectional_stream_header* headers = + (bidirectional_stream_header*)gpr_malloc( sizeof(bidirectional_stream_header) * num_headers_available); *pp_headers = headers; @@ -734,8 +734,8 @@ static void convert_metadata_to_cronet_headers( while (num_headers < num_headers_available) { grpc_mdelem mdelem = curr->md; curr = curr->next; - char *key = grpc_slice_to_c_string(GRPC_MDKEY(mdelem)); - char *value = grpc_slice_to_c_string(GRPC_MDVALUE(mdelem)); + char* key = grpc_slice_to_c_string(GRPC_MDKEY(mdelem)); + char* value = grpc_slice_to_c_string(GRPC_MDVALUE(mdelem)); if (grpc_slice_eq(GRPC_MDKEY(mdelem), GRPC_MDSTR_SCHEME) || grpc_slice_eq(GRPC_MDKEY(mdelem), GRPC_MDSTR_AUTHORITY)) { /* Cronet populates these fields on its own */ @@ -765,17 +765,17 @@ static void convert_metadata_to_cronet_headers( headers[num_headers].key = key; headers[num_headers].value = value; num_headers++; - if (curr == NULL) { + if (curr == nullptr) { break; } } *p_num_headers = (size_t)num_headers; } -static void parse_grpc_header(const uint8_t *data, int *length, - bool *compressed) { +static void parse_grpc_header(const uint8_t* data, int* length, + bool* compressed) { const uint8_t c = *data; - const uint8_t *p = data + 1; + const uint8_t* p = data + 1; *compressed = ((c & 0x01) == 0x01); *length = 0; *length |= ((uint8_t)*p++) << 24; @@ -784,8 +784,8 @@ static void parse_grpc_header(const uint8_t *data, int *length, *length |= ((uint8_t)*p++); } -static bool header_has_authority(grpc_linked_mdelem *head) { - while (head != NULL) { +static bool header_has_authority(grpc_linked_mdelem* head) { + while (head != nullptr) { if (grpc_slice_eq(GRPC_MDKEY(head->md), GRPC_MDSTR_AUTHORITY)) { return true; } @@ -798,11 +798,11 @@ static bool header_has_authority(grpc_linked_mdelem *head) { Op Execution: Decide if one of the actions contained in the stream op can be executed. This is the heart of the state machine. */ -static bool op_can_be_run(grpc_transport_stream_op_batch *curr_op, - struct stream_obj *s, struct op_state *op_state, +static bool op_can_be_run(grpc_transport_stream_op_batch* curr_op, + struct stream_obj* s, struct op_state* op_state, enum e_op_id op_id) { - struct op_state *stream_state = &s->state; - grpc_cronet_transport *t = s->curr_ct; + struct op_state* stream_state = &s->state; + grpc_cronet_transport* t = s->curr_ct; bool result = true; /* When call is canceled, every op can be run, except under following conditions @@ -981,19 +981,19 @@ static bool op_can_be_run(grpc_transport_stream_op_batch *curr_op, /* TODO (makdharma): Break down this function in smaller chunks for readability. */ -static enum e_op_result execute_stream_op(grpc_exec_ctx *exec_ctx, - struct op_and_state *oas) { - grpc_transport_stream_op_batch *stream_op = &oas->op; - struct stream_obj *s = oas->s; - grpc_cronet_transport *t = (grpc_cronet_transport *)s->curr_ct; - struct op_state *stream_state = &s->state; +static enum e_op_result execute_stream_op(grpc_exec_ctx* exec_ctx, + struct op_and_state* oas) { + grpc_transport_stream_op_batch* stream_op = &oas->op; + struct stream_obj* s = oas->s; + grpc_cronet_transport* t = (grpc_cronet_transport*)s->curr_ct; + struct op_state* stream_state = &s->state; enum e_op_result result = NO_ACTION_POSSIBLE; if (stream_op->send_initial_metadata && op_can_be_run(stream_op, s, &oas->state, OP_SEND_INITIAL_METADATA)) { CRONET_LOG(GPR_DEBUG, "running: %p OP_SEND_INITIAL_METADATA", oas); /* Start new cronet stream. It is destroyed in on_succeeded, on_canceled, * on_failed */ - GPR_ASSERT(s->cbs == NULL); + GPR_ASSERT(s->cbs == nullptr); GPR_ASSERT(!stream_state->state_op_done[OP_SEND_INITIAL_METADATA]); s->cbs = bidirectional_stream_create(t->engine, s->curr_gs, &cronet_callbacks); @@ -1002,9 +1002,9 @@ static enum e_op_result execute_stream_op(grpc_exec_ctx *exec_ctx, bidirectional_stream_disable_auto_flush(s->cbs, true); bidirectional_stream_delay_request_headers_until_flush(s->cbs, true); } - char *url = NULL; - const char *method = "POST"; - s->header_array.headers = NULL; + char* url = nullptr; + const char* method = "POST"; + s->header_array.headers = nullptr; convert_metadata_to_cronet_headers(stream_op->payload->send_initial_metadata .send_initial_metadata->list.head, t->host, &url, &s->header_array.headers, @@ -1018,8 +1018,8 @@ static enum e_op_result execute_stream_op(grpc_exec_ctx *exec_ctx, unsigned int header_index; for (header_index = 0; header_index < s->header_array.count; header_index++) { - gpr_free((void *)s->header_array.headers[header_index].key); - gpr_free((void *)s->header_array.headers[header_index].value); + gpr_free((void*)s->header_array.headers[header_index].key); + gpr_free((void*)s->header_array.headers[header_index].value); } stream_state->state_op_done[OP_SEND_INITIAL_METADATA] = true; if (t->use_packet_coalescing) { @@ -1042,7 +1042,7 @@ static enum e_op_result execute_stream_op(grpc_exec_ctx *exec_ctx, if (1 != grpc_byte_stream_next( exec_ctx, stream_op->payload->send_message.send_message, stream_op->payload->send_message.send_message->length, - NULL)) { + nullptr)) { /* Should never reach here */ GPR_ASSERT(false); } @@ -1177,14 +1177,14 @@ static enum e_op_result execute_stream_op(grpc_exec_ctx *exec_ctx, stream_state->rs.remaining_bytes == 0) { /* Start a read operation for data */ stream_state->rs.length_field_received = true; - parse_grpc_header((const uint8_t *)stream_state->rs.read_buffer, + parse_grpc_header((const uint8_t*)stream_state->rs.read_buffer, &stream_state->rs.length_field, &stream_state->rs.compressed); CRONET_LOG(GPR_DEBUG, "length field = %d", stream_state->rs.length_field); if (stream_state->rs.length_field > 0) { stream_state->rs.read_buffer = - (char *)gpr_malloc((size_t)stream_state->rs.length_field); + (char*)gpr_malloc((size_t)stream_state->rs.length_field); GPR_ASSERT(stream_state->rs.read_buffer); stream_state->rs.remaining_bytes = stream_state->rs.length_field; stream_state->rs.received_bytes = 0; @@ -1207,9 +1207,8 @@ static enum e_op_result execute_stream_op(grpc_exec_ctx *exec_ctx, if (stream_state->rs.compressed) { stream_state->rs.sbs.base.flags |= GRPC_WRITE_INTERNAL_COMPRESS; } - *((grpc_byte_buffer **) - stream_op->payload->recv_message.recv_message) = - (grpc_byte_buffer *)&stream_state->rs.sbs; + *((grpc_byte_buffer**)stream_op->payload->recv_message.recv_message) = + (grpc_byte_buffer*)&stream_state->rs.sbs; GRPC_CLOSURE_SCHED( exec_ctx, stream_op->payload->recv_message.recv_message_ready, GRPC_ERROR_NONE); @@ -1250,7 +1249,7 @@ static enum e_op_result execute_stream_op(grpc_exec_ctx *exec_ctx, CRONET_LOG(GPR_DEBUG, "read operation complete"); grpc_slice read_data_slice = GRPC_SLICE_MALLOC((uint32_t)stream_state->rs.length_field); - uint8_t *dst_p = GRPC_SLICE_START_PTR(read_data_slice); + uint8_t* dst_p = GRPC_SLICE_START_PTR(read_data_slice); memcpy(dst_p, stream_state->rs.read_buffer, (size_t)stream_state->rs.length_field); null_and_maybe_free_read_buffer(s); @@ -1265,8 +1264,8 @@ static enum e_op_result execute_stream_op(grpc_exec_ctx *exec_ctx, if (stream_state->rs.compressed) { stream_state->rs.sbs.base.flags = GRPC_WRITE_INTERNAL_COMPRESS; } - *((grpc_byte_buffer **)stream_op->payload->recv_message.recv_message) = - (grpc_byte_buffer *)&stream_state->rs.sbs; + *((grpc_byte_buffer**)stream_op->payload->recv_message.recv_message) = + (grpc_byte_buffer*)&stream_state->rs.sbs; GRPC_CLOSURE_SCHED(exec_ctx, stream_op->payload->recv_message.recv_message_ready, GRPC_ERROR_NONE); @@ -1351,18 +1350,18 @@ static enum e_op_result execute_stream_op(grpc_exec_ctx *exec_ctx, Functions used by upper layers to access transport functionality. */ -static int init_stream(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_stream *gs, grpc_stream_refcount *refcount, - const void *server_data, gpr_arena *arena) { - stream_obj *s = (stream_obj *)gs; +static int init_stream(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_stream* gs, grpc_stream_refcount* refcount, + const void* server_data, gpr_arena* arena) { + stream_obj* s = (stream_obj*)gs; s->refcount = refcount; GRPC_CRONET_STREAM_REF(s, "cronet transport"); memset(&s->storage, 0, sizeof(s->storage)); - s->storage.head = NULL; + s->storage.head = nullptr; memset(&s->state, 0, sizeof(s->state)); - s->curr_op = NULL; - s->cbs = NULL; + s->curr_op = nullptr; + s->cbs = nullptr; memset(&s->header_array, 0, sizeof(s->header_array)); memset(&s->state.rs, 0, sizeof(s->state.rs)); memset(&s->state.ws, 0, sizeof(s->state.ws)); @@ -1370,30 +1369,30 @@ static int init_stream(grpc_exec_ctx *exec_ctx, grpc_transport *gt, memset(s->state.state_callback_received, 0, sizeof(s->state.state_callback_received)); s->state.fail_state = s->state.flush_read = false; - s->state.cancel_error = NULL; + s->state.cancel_error = nullptr; s->state.flush_cronet_when_ready = s->state.pending_write_for_trailer = false; s->state.pending_send_message = false; s->state.pending_recv_trailing_metadata = false; s->state.pending_read_from_cronet = false; s->curr_gs = gs; - s->curr_ct = (grpc_cronet_transport *)gt; + s->curr_ct = (grpc_cronet_transport*)gt; s->arena = arena; gpr_mu_init(&s->mu); return 0; } -static void set_pollset_do_nothing(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_stream *gs, grpc_pollset *pollset) {} +static void set_pollset_do_nothing(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_stream* gs, grpc_pollset* pollset) {} -static void set_pollset_set_do_nothing(grpc_exec_ctx *exec_ctx, - grpc_transport *gt, grpc_stream *gs, - grpc_pollset_set *pollset_set) {} +static void set_pollset_set_do_nothing(grpc_exec_ctx* exec_ctx, + grpc_transport* gt, grpc_stream* gs, + grpc_pollset_set* pollset_set) {} -static void perform_stream_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_stream *gs, - grpc_transport_stream_op_batch *op) { +static void perform_stream_op(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_stream* gs, + grpc_transport_stream_op_batch* op) { CRONET_LOG(GPR_DEBUG, "perform_stream_op"); if (op->send_initial_metadata && header_has_authority(op->payload->send_initial_metadata @@ -1413,15 +1412,15 @@ static void perform_stream_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, GRPC_CLOSURE_SCHED(exec_ctx, op->on_complete, GRPC_ERROR_CANCELLED); return; } - stream_obj *s = (stream_obj *)gs; + stream_obj* s = (stream_obj*)gs; add_to_storage(s, op); execute_from_storage(exec_ctx, s); } -static void destroy_stream(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_stream *gs, - grpc_closure *then_schedule_closure) { - stream_obj *s = (stream_obj *)gs; +static void destroy_stream(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_stream* gs, + grpc_closure* then_schedule_closure) { + stream_obj* s = (stream_obj*)gs; null_and_maybe_free_read_buffer(s); /* Clean up read_slice_buffer in case there is unread data. */ grpc_slice_buffer_destroy_internal(exec_ctx, &s->state.rs.read_slice_buffer); @@ -1429,15 +1428,15 @@ static void destroy_stream(grpc_exec_ctx *exec_ctx, grpc_transport *gt, GRPC_CLOSURE_SCHED(exec_ctx, then_schedule_closure, GRPC_ERROR_NONE); } -static void destroy_transport(grpc_exec_ctx *exec_ctx, grpc_transport *gt) {} +static void destroy_transport(grpc_exec_ctx* exec_ctx, grpc_transport* gt) {} -static grpc_endpoint *get_endpoint(grpc_exec_ctx *exec_ctx, - grpc_transport *gt) { - return NULL; +static grpc_endpoint* get_endpoint(grpc_exec_ctx* exec_ctx, + grpc_transport* gt) { + return nullptr; } -static void perform_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_transport_op *op) {} +static void perform_op(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_transport_op* op) {} static const grpc_transport_vtable grpc_cronet_vtable = { sizeof(stream_obj), @@ -1451,17 +1450,17 @@ static const grpc_transport_vtable grpc_cronet_vtable = { destroy_transport, get_endpoint}; -grpc_transport *grpc_create_cronet_transport(void *engine, const char *target, - const grpc_channel_args *args, - void *reserved) { - grpc_cronet_transport *ct = - (grpc_cronet_transport *)gpr_malloc(sizeof(grpc_cronet_transport)); +grpc_transport* grpc_create_cronet_transport(void* engine, const char* target, + const grpc_channel_args* args, + void* reserved) { + grpc_cronet_transport* ct = + (grpc_cronet_transport*)gpr_malloc(sizeof(grpc_cronet_transport)); if (!ct) { goto error; } ct->base.vtable = &grpc_cronet_vtable; - ct->engine = (stream_engine *)engine; - ct->host = (char *)gpr_malloc(strlen(target) + 1); + ct->engine = (stream_engine*)engine; + ct->host = (char*)gpr_malloc(strlen(target) + 1); if (!ct->host) { goto error; } @@ -1492,5 +1491,5 @@ error: gpr_free(ct); } - return NULL; + return nullptr; } diff --git a/src/core/ext/transport/cronet/transport/cronet_transport.h b/src/core/ext/transport/cronet/transport/cronet_transport.h index 43ff391f792..d9ff913326a 100644 --- a/src/core/ext/transport/cronet/transport/cronet_transport.h +++ b/src/core/ext/transport/cronet/transport/cronet_transport.h @@ -21,16 +21,8 @@ #include "src/core/lib/transport/transport.h" -#ifdef __cplusplus -extern "C" { -#endif - -grpc_transport *grpc_create_cronet_transport(void *engine, const char *target, - const grpc_channel_args *args, - void *reserved); - -#ifdef __cplusplus -} -#endif +grpc_transport* grpc_create_cronet_transport(void* engine, const char* target, + const grpc_channel_args* args, + void* reserved); #endif /* GRPC_CORE_EXT_TRANSPORT_CRONET_TRANSPORT_CRONET_TRANSPORT_H */ diff --git a/src/core/ext/transport/inproc/inproc_plugin.cc b/src/core/ext/transport/inproc/inproc_plugin.cc index 5d8a1c74abd..83a7d8d52f9 100644 --- a/src/core/ext/transport/inproc/inproc_plugin.cc +++ b/src/core/ext/transport/inproc/inproc_plugin.cc @@ -19,13 +19,8 @@ #include "src/core/ext/transport/inproc/inproc_transport.h" #include "src/core/lib/debug/trace.h" -grpc_tracer_flag grpc_inproc_trace = GRPC_TRACER_INITIALIZER(false, "inproc"); +grpc_core::TraceFlag grpc_inproc_trace(false, "inproc"); -extern "C" void grpc_inproc_plugin_init(void) { - grpc_register_tracer(&grpc_inproc_trace); - grpc_inproc_transport_init(); -} +void grpc_inproc_plugin_init(void) { grpc_inproc_transport_init(); } -extern "C" void grpc_inproc_plugin_shutdown(void) { - grpc_inproc_transport_shutdown(); -} +void grpc_inproc_plugin_shutdown(void) { grpc_inproc_transport_shutdown(); } diff --git a/src/core/ext/transport/inproc/inproc_transport.cc b/src/core/ext/transport/inproc/inproc_transport.cc index 1551f5e988c..d8d753e4591 100644 --- a/src/core/ext/transport/inproc/inproc_transport.cc +++ b/src/core/ext/transport/inproc/inproc_transport.cc @@ -32,9 +32,9 @@ #include "src/core/lib/transport/error_utils.h" #include "src/core/lib/transport/transport_impl.h" -#define INPROC_LOG(...) \ - do { \ - if (GRPC_TRACER_ON(grpc_inproc_trace)) gpr_log(__VA_ARGS__); \ +#define INPROC_LOG(...) \ + do { \ + if (grpc_inproc_trace.enabled()) gpr_log(__VA_ARGS__); \ } while (0) static grpc_slice g_empty_slice; @@ -50,20 +50,20 @@ typedef struct { typedef struct inproc_transport { grpc_transport base; - shared_mu *mu; + shared_mu* mu; gpr_refcount refs; bool is_client; grpc_connectivity_state_tracker connectivity; - void (*accept_stream_cb)(grpc_exec_ctx *exec_ctx, void *user_data, - grpc_transport *transport, const void *server_data); - void *accept_stream_data; + void (*accept_stream_cb)(grpc_exec_ctx* exec_ctx, void* user_data, + grpc_transport* transport, const void* server_data); + void* accept_stream_data; bool is_closed; - struct inproc_transport *other_side; - struct inproc_stream *stream_list; + struct inproc_transport* other_side; + struct inproc_stream* stream_list; } inproc_transport; typedef struct inproc_stream { - inproc_transport *t; + inproc_transport* t; grpc_metadata_batch to_read_initial_md; uint32_t to_read_initial_md_flags; bool to_read_initial_md_filled; @@ -80,21 +80,21 @@ typedef struct inproc_stream { grpc_millis write_buffer_deadline; grpc_metadata_batch write_buffer_trailing_md; bool write_buffer_trailing_md_filled; - grpc_error *write_buffer_cancel_error; + grpc_error* write_buffer_cancel_error; - struct inproc_stream *other_side; + struct inproc_stream* other_side; bool other_side_closed; // won't talk anymore bool write_buffer_other_side_closed; // on hold - grpc_stream_refcount *refs; - grpc_closure *closure_at_destroy; + grpc_stream_refcount* refs; + grpc_closure* closure_at_destroy; - gpr_arena *arena; + gpr_arena* arena; - grpc_transport_stream_op_batch *send_message_op; - grpc_transport_stream_op_batch *send_trailing_md_op; - grpc_transport_stream_op_batch *recv_initial_md_op; - grpc_transport_stream_op_batch *recv_message_op; - grpc_transport_stream_op_batch *recv_trailing_md_op; + grpc_transport_stream_op_batch* send_message_op; + grpc_transport_stream_op_batch* send_trailing_md_op; + grpc_transport_stream_op_batch* recv_initial_md_op; + grpc_transport_stream_op_batch* recv_message_op; + grpc_transport_stream_op_batch* recv_trailing_md_op; grpc_slice_buffer recv_message; grpc_slice_buffer_stream recv_stream; @@ -107,29 +107,29 @@ typedef struct inproc_stream { bool closed; - grpc_error *cancel_self_error; - grpc_error *cancel_other_error; + grpc_error* cancel_self_error; + grpc_error* cancel_other_error; grpc_millis deadline; bool listed; - struct inproc_stream *stream_list_prev; - struct inproc_stream *stream_list_next; + struct inproc_stream* stream_list_prev; + struct inproc_stream* stream_list_next; } inproc_stream; static grpc_closure do_nothing_closure; -static bool cancel_stream_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s, - grpc_error *error); -static void op_state_machine(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error); +static bool cancel_stream_locked(grpc_exec_ctx* exec_ctx, inproc_stream* s, + grpc_error* error); +static void op_state_machine(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error); -static void ref_transport(inproc_transport *t) { +static void ref_transport(inproc_transport* t) { INPROC_LOG(GPR_DEBUG, "ref_transport %p", t); gpr_ref(&t->refs); } -static void really_destroy_transport(grpc_exec_ctx *exec_ctx, - inproc_transport *t) { +static void really_destroy_transport(grpc_exec_ctx* exec_ctx, + inproc_transport* t) { INPROC_LOG(GPR_DEBUG, "really_destroy_transport %p", t); grpc_connectivity_state_destroy(exec_ctx, &t->connectivity); if (gpr_unref(&t->mu->refs)) { @@ -138,7 +138,7 @@ static void really_destroy_transport(grpc_exec_ctx *exec_ctx, gpr_free(t); } -static void unref_transport(grpc_exec_ctx *exec_ctx, inproc_transport *t) { +static void unref_transport(grpc_exec_ctx* exec_ctx, inproc_transport* t) { INPROC_LOG(GPR_DEBUG, "unref_transport %p", t); if (gpr_unref(&t->refs)) { really_destroy_transport(exec_ctx, t); @@ -153,18 +153,18 @@ static void unref_transport(grpc_exec_ctx *exec_ctx, inproc_transport *t) { #define STREAM_UNREF(e, refs, reason) grpc_stream_unref(e, refs) #endif -static void ref_stream(inproc_stream *s, const char *reason) { +static void ref_stream(inproc_stream* s, const char* reason) { INPROC_LOG(GPR_DEBUG, "ref_stream %p %s", s, reason); STREAM_REF(s->refs, reason); } -static void unref_stream(grpc_exec_ctx *exec_ctx, inproc_stream *s, - const char *reason) { +static void unref_stream(grpc_exec_ctx* exec_ctx, inproc_stream* s, + const char* reason) { INPROC_LOG(GPR_DEBUG, "unref_stream %p %s", s, reason); STREAM_UNREF(exec_ctx, s->refs, reason); } -static void really_destroy_stream(grpc_exec_ctx *exec_ctx, inproc_stream *s) { +static void really_destroy_stream(grpc_exec_ctx* exec_ctx, inproc_stream* s) { INPROC_LOG(GPR_DEBUG, "really_destroy_stream %p", s); GRPC_ERROR_UNREF(s->write_buffer_cancel_error); @@ -182,12 +182,12 @@ static void really_destroy_stream(grpc_exec_ctx *exec_ctx, inproc_stream *s) { } } -static void log_metadata(const grpc_metadata_batch *md_batch, bool is_client, +static void log_metadata(const grpc_metadata_batch* md_batch, bool is_client, bool is_initial) { - for (grpc_linked_mdelem *md = md_batch->list.head; md != NULL; + for (grpc_linked_mdelem* md = md_batch->list.head; md != nullptr; md = md->next) { - char *key = grpc_slice_to_c_string(GRPC_MDKEY(md->md)); - char *value = grpc_slice_to_c_string(GRPC_MDVALUE(md->md)); + char* key = grpc_slice_to_c_string(GRPC_MDKEY(md->md)); + char* value = grpc_slice_to_c_string(GRPC_MDVALUE(md->md)); gpr_log(GPR_INFO, "INPROC:%s:%s: %s: %s", is_initial ? "HDR" : "TRL", is_client ? "CLI" : "SVR", key, value); gpr_free(key); @@ -195,25 +195,25 @@ static void log_metadata(const grpc_metadata_batch *md_batch, bool is_client, } } -static grpc_error *fill_in_metadata(grpc_exec_ctx *exec_ctx, inproc_stream *s, - const grpc_metadata_batch *metadata, - uint32_t flags, grpc_metadata_batch *out_md, - uint32_t *outflags, bool *markfilled) { - if (GRPC_TRACER_ON(grpc_inproc_trace)) { - log_metadata(metadata, s->t->is_client, outflags != NULL); +static grpc_error* fill_in_metadata(grpc_exec_ctx* exec_ctx, inproc_stream* s, + const grpc_metadata_batch* metadata, + uint32_t flags, grpc_metadata_batch* out_md, + uint32_t* outflags, bool* markfilled) { + if (grpc_inproc_trace.enabled()) { + log_metadata(metadata, s->t->is_client, outflags != nullptr); } - if (outflags != NULL) { + if (outflags != nullptr) { *outflags = flags; } - if (markfilled != NULL) { + if (markfilled != nullptr) { *markfilled = true; } - grpc_error *error = GRPC_ERROR_NONE; - for (grpc_linked_mdelem *elem = metadata->list.head; - (elem != NULL) && (error == GRPC_ERROR_NONE); elem = elem->next) { - grpc_linked_mdelem *nelem = - (grpc_linked_mdelem *)gpr_arena_alloc(s->arena, sizeof(*nelem)); + grpc_error* error = GRPC_ERROR_NONE; + for (grpc_linked_mdelem* elem = metadata->list.head; + (elem != nullptr) && (error == GRPC_ERROR_NONE); elem = elem->next) { + grpc_linked_mdelem* nelem = + (grpc_linked_mdelem*)gpr_arena_alloc(s->arena, sizeof(*nelem)); nelem->md = grpc_mdelem_from_slices( exec_ctx, grpc_slice_intern(GRPC_MDKEY(elem->md)), grpc_slice_intern(GRPC_MDVALUE(elem->md))); @@ -223,12 +223,12 @@ static grpc_error *fill_in_metadata(grpc_exec_ctx *exec_ctx, inproc_stream *s, return error; } -static int init_stream(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_stream *gs, grpc_stream_refcount *refcount, - const void *server_data, gpr_arena *arena) { +static int init_stream(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_stream* gs, grpc_stream_refcount* refcount, + const void* server_data, gpr_arena* arena) { INPROC_LOG(GPR_DEBUG, "init_stream %p %p %p", gt, gs, server_data); - inproc_transport *t = (inproc_transport *)gt; - inproc_stream *s = (inproc_stream *)gs; + inproc_transport* t = (inproc_transport*)gt; + inproc_stream* s = (inproc_stream*)gs; s->arena = arena; s->refs = refcount; @@ -250,7 +250,7 @@ static int init_stream(grpc_exec_ctx *exec_ctx, grpc_transport *gt, GRPC_CLOSURE_INIT(&s->op_closure, op_state_machine, s, grpc_schedule_on_exec_ctx); s->t = t; - s->closure_at_destroy = NULL; + s->closure_at_destroy = nullptr; s->other_side_closed = false; s->initial_md_sent = s->trailing_md_sent = s->initial_md_recvd = @@ -264,7 +264,7 @@ static int init_stream(grpc_exec_ctx *exec_ctx, grpc_transport *gt, s->deadline = GRPC_MILLIS_INF_FUTURE; s->write_buffer_deadline = GRPC_MILLIS_INF_FUTURE; - s->stream_list_prev = NULL; + s->stream_list_prev = nullptr; gpr_mu_lock(&t->mu->mu); s->listed = true; ref_stream(s, "inproc_init_stream:list"); @@ -277,19 +277,19 @@ static int init_stream(grpc_exec_ctx *exec_ctx, grpc_transport *gt, if (!server_data) { ref_transport(t); - inproc_transport *st = t->other_side; + inproc_transport* st = t->other_side; ref_transport(st); - s->other_side = NULL; // will get filled in soon + s->other_side = nullptr; // will get filled in soon // Pass the client-side stream address to the server-side for a ref ref_stream(s, "inproc_init_stream:clt"); // ref it now on behalf of server // side to avoid destruction INPROC_LOG(GPR_DEBUG, "calling accept stream cb %p %p", st->accept_stream_cb, st->accept_stream_data); (*st->accept_stream_cb)(exec_ctx, st->accept_stream_data, &st->base, - (void *)s); + (void*)s); } else { // This is the server-side and is being called through accept_stream_cb - inproc_stream *cs = (inproc_stream *)server_data; + inproc_stream* cs = (inproc_stream*)server_data; s->other_side = cs; // Ref the server-side stream on behalf of the client now ref_stream(s, "inproc_init_stream:srv"); @@ -311,7 +311,7 @@ static int init_stream(grpc_exec_ctx *exec_ctx, grpc_transport *gt, } if (cs->write_buffer_trailing_md_filled) { fill_in_metadata(exec_ctx, s, &cs->write_buffer_trailing_md, 0, - &s->to_read_trailing_md, NULL, + &s->to_read_trailing_md, nullptr, &s->to_read_trailing_md_filled); grpc_metadata_batch_clear(exec_ctx, &cs->write_buffer_trailing_md); cs->write_buffer_trailing_md_filled = false; @@ -326,21 +326,21 @@ static int init_stream(grpc_exec_ctx *exec_ctx, grpc_transport *gt, return 0; // return value is not important } -static void close_stream_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s) { +static void close_stream_locked(grpc_exec_ctx* exec_ctx, inproc_stream* s) { if (!s->closed) { // Release the metadata that we would have written out grpc_metadata_batch_destroy(exec_ctx, &s->write_buffer_initial_md); grpc_metadata_batch_destroy(exec_ctx, &s->write_buffer_trailing_md); if (s->listed) { - inproc_stream *p = s->stream_list_prev; - inproc_stream *n = s->stream_list_next; - if (p != NULL) { + inproc_stream* p = s->stream_list_prev; + inproc_stream* n = s->stream_list_next; + if (p != nullptr) { p->stream_list_next = n; } else { s->t->stream_list = n; } - if (n != NULL) { + if (n != nullptr) { n->stream_list_prev = p; } s->listed = false; @@ -352,16 +352,16 @@ static void close_stream_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s) { } // This function means that we are done talking/listening to the other side -static void close_other_side_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s, - const char *reason) { - if (s->other_side != NULL) { +static void close_other_side_locked(grpc_exec_ctx* exec_ctx, inproc_stream* s, + const char* reason) { + if (s->other_side != nullptr) { // First release the metadata that came from the other side's arena grpc_metadata_batch_destroy(exec_ctx, &s->to_read_initial_md); grpc_metadata_batch_destroy(exec_ctx, &s->to_read_trailing_md); unref_stream(exec_ctx, s->other_side, reason); s->other_side_closed = true; - s->other_side = NULL; + s->other_side = nullptr; } else if (!s->other_side_closed) { s->write_buffer_other_side_closed = true; } @@ -371,10 +371,10 @@ static void close_other_side_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s, // this stream_op_batch is only one of the pending operations for this // stream. This is called when one of the pending operations for the stream // is done and about to be NULLed out -static void complete_if_batch_end_locked(grpc_exec_ctx *exec_ctx, - inproc_stream *s, grpc_error *error, - grpc_transport_stream_op_batch *op, - const char *msg) { +static void complete_if_batch_end_locked(grpc_exec_ctx* exec_ctx, + inproc_stream* s, grpc_error* error, + grpc_transport_stream_op_batch* op, + const char* msg) { int is_sm = (int)(op == s->send_message_op); int is_stm = (int)(op == s->send_trailing_md_op); int is_rim = (int)(op == s->recv_initial_md_op); @@ -387,9 +387,9 @@ static void complete_if_batch_end_locked(grpc_exec_ctx *exec_ctx, } } -static void maybe_schedule_op_closure_locked(grpc_exec_ctx *exec_ctx, - inproc_stream *s, - grpc_error *error) { +static void maybe_schedule_op_closure_locked(grpc_exec_ctx* exec_ctx, + inproc_stream* s, + grpc_error* error) { if (s && s->ops_needed && !s->op_closure_scheduled) { GRPC_CLOSURE_SCHED(exec_ctx, &s->op_closure, GRPC_ERROR_REF(error)); s->op_closure_scheduled = true; @@ -397,8 +397,8 @@ static void maybe_schedule_op_closure_locked(grpc_exec_ctx *exec_ctx, } } -static void fail_helper_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s, - grpc_error *error) { +static void fail_helper_locked(grpc_exec_ctx* exec_ctx, inproc_stream* s, + grpc_error* error) { INPROC_LOG(GPR_DEBUG, "op_state_machine %p fail_helper", s); // If we're failing this side, we need to make sure that // we also send or have already sent trailing metadata @@ -409,15 +409,16 @@ static void fail_helper_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s, grpc_metadata_batch fake_md; grpc_metadata_batch_init(&fake_md); - inproc_stream *other = s->other_side; - grpc_metadata_batch *dest = (other == NULL) ? &s->write_buffer_trailing_md - : &other->to_read_trailing_md; - bool *destfilled = (other == NULL) ? &s->write_buffer_trailing_md_filled - : &other->to_read_trailing_md_filled; - fill_in_metadata(exec_ctx, s, &fake_md, 0, dest, NULL, destfilled); + inproc_stream* other = s->other_side; + grpc_metadata_batch* dest = (other == nullptr) + ? &s->write_buffer_trailing_md + : &other->to_read_trailing_md; + bool* destfilled = (other == nullptr) ? &s->write_buffer_trailing_md_filled + : &other->to_read_trailing_md_filled; + fill_in_metadata(exec_ctx, s, &fake_md, 0, dest, nullptr, destfilled); grpc_metadata_batch_destroy(exec_ctx, &fake_md); - if (other != NULL) { + if (other != nullptr) { if (other->cancel_other_error == GRPC_ERROR_NONE) { other->cancel_other_error = GRPC_ERROR_REF(error); } @@ -427,20 +428,20 @@ static void fail_helper_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s, } } if (s->recv_initial_md_op) { - grpc_error *err; + grpc_error* err; if (!s->t->is_client) { // If this is a server, provide initial metadata with a path and authority // since it expects that as well as no error yet grpc_metadata_batch fake_md; grpc_metadata_batch_init(&fake_md); - grpc_linked_mdelem *path_md = - (grpc_linked_mdelem *)gpr_arena_alloc(s->arena, sizeof(*path_md)); + grpc_linked_mdelem* path_md = + (grpc_linked_mdelem*)gpr_arena_alloc(s->arena, sizeof(*path_md)); path_md->md = grpc_mdelem_from_slices(exec_ctx, g_fake_path_key, g_fake_path_value); GPR_ASSERT(grpc_metadata_batch_link_tail(exec_ctx, &fake_md, path_md) == GRPC_ERROR_NONE); - grpc_linked_mdelem *auth_md = - (grpc_linked_mdelem *)gpr_arena_alloc(s->arena, sizeof(*auth_md)); + grpc_linked_mdelem* auth_md = + (grpc_linked_mdelem*)gpr_arena_alloc(s->arena, sizeof(*auth_md)); auth_md->md = grpc_mdelem_from_slices(exec_ctx, g_fake_auth_key, g_fake_auth_value); GPR_ASSERT(grpc_metadata_batch_link_tail(exec_ctx, &fake_md, auth_md) == @@ -451,12 +452,20 @@ static void fail_helper_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s, s->recv_initial_md_op->payload->recv_initial_metadata .recv_initial_metadata, s->recv_initial_md_op->payload->recv_initial_metadata.recv_flags, - NULL); + nullptr); grpc_metadata_batch_destroy(exec_ctx, &fake_md); err = GRPC_ERROR_NONE; } else { err = GRPC_ERROR_REF(error); } + if (s->recv_initial_md_op->payload->recv_initial_metadata + .trailing_metadata_available != nullptr) { + // Set to true unconditionally, because we're failing the call, so even + // if we haven't actually seen the send_trailing_metadata op from the + // other side, we're going to return trailing metadata anyway. + *s->recv_initial_md_op->payload->recv_initial_metadata + .trailing_metadata_available = true; + } INPROC_LOG(GPR_DEBUG, "fail_helper %p scheduling initial-metadata-ready %p %p", s, error, err); @@ -469,7 +478,7 @@ static void fail_helper_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s, complete_if_batch_end_locked( exec_ctx, s, error, s->recv_initial_md_op, "fail_helper scheduling recv-initial-metadata-on-complete"); - s->recv_initial_md_op = NULL; + s->recv_initial_md_op = nullptr; } if (s->recv_message_op) { INPROC_LOG(GPR_DEBUG, "fail_helper %p scheduling message-ready %p", s, @@ -480,19 +489,19 @@ static void fail_helper_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s, complete_if_batch_end_locked( exec_ctx, s, error, s->recv_message_op, "fail_helper scheduling recv-message-on-complete"); - s->recv_message_op = NULL; + s->recv_message_op = nullptr; } if (s->send_message_op) { complete_if_batch_end_locked( exec_ctx, s, error, s->send_message_op, "fail_helper scheduling send-message-on-complete"); - s->send_message_op = NULL; + s->send_message_op = nullptr; } if (s->send_trailing_md_op) { complete_if_batch_end_locked( exec_ctx, s, error, s->send_trailing_md_op, "fail_helper scheduling send-trailng-md-on-complete"); - s->send_trailing_md_op = NULL; + s->send_trailing_md_op = nullptr; } if (s->recv_trailing_md_op) { INPROC_LOG(GPR_DEBUG, @@ -501,7 +510,7 @@ static void fail_helper_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s, complete_if_batch_end_locked( exec_ctx, s, error, s->recv_trailing_md_op, "fail_helper scheduling recv-trailing-metadata-on-complete"); - s->recv_trailing_md_op = NULL; + s->recv_trailing_md_op = nullptr; } close_other_side_locked(exec_ctx, s, "fail_helper:other_side"); close_stream_locked(exec_ctx, s); @@ -509,9 +518,9 @@ static void fail_helper_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s, GRPC_ERROR_UNREF(error); } -static void message_transfer_locked(grpc_exec_ctx *exec_ctx, - inproc_stream *sender, - inproc_stream *receiver) { +static void message_transfer_locked(grpc_exec_ctx* exec_ctx, + inproc_stream* sender, + inproc_stream* receiver) { size_t remaining = sender->send_message_op->payload->send_message.send_message->length; if (receiver->recv_inited) { @@ -525,7 +534,7 @@ static void message_transfer_locked(grpc_exec_ctx *exec_ctx, GPR_ASSERT(grpc_byte_stream_next( exec_ctx, sender->send_message_op->payload->send_message.send_message, SIZE_MAX, &unused)); - grpc_error *error = grpc_byte_stream_pull( + grpc_error* error = grpc_byte_stream_pull( exec_ctx, sender->send_message_op->payload->send_message.send_message, &message_slice); if (error != GRPC_ERROR_NONE) { @@ -554,12 +563,12 @@ static void message_transfer_locked(grpc_exec_ctx *exec_ctx, exec_ctx, receiver, GRPC_ERROR_NONE, receiver->recv_message_op, "message_transfer scheduling receiver on_complete"); - receiver->recv_message_op = NULL; - sender->send_message_op = NULL; + receiver->recv_message_op = nullptr; + sender->send_message_op = nullptr; } -static void op_state_machine(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { +static void op_state_machine(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { // This function gets called when we have contents in the unprocessed reads // Get what we want based on our ops wanted // Schedule our appropriate closures @@ -567,17 +576,17 @@ static void op_state_machine(grpc_exec_ctx *exec_ctx, void *arg, // Since this is a closure directly invoked by the combiner, it should not // unref the error parameter explicitly; the combiner will do that implicitly - grpc_error *new_err = GRPC_ERROR_NONE; + grpc_error* new_err = GRPC_ERROR_NONE; bool needs_close = false; INPROC_LOG(GPR_DEBUG, "op_state_machine %p", arg); - inproc_stream *s = (inproc_stream *)arg; - gpr_mu *mu = &s->t->mu->mu; // keep aside in case s gets closed + inproc_stream* s = (inproc_stream*)arg; + gpr_mu* mu = &s->t->mu->mu; // keep aside in case s gets closed gpr_mu_lock(mu); s->op_closure_scheduled = false; // cancellation takes precedence - inproc_stream *other = s->other_side; + inproc_stream* other = s->other_side; if (s->cancel_self_error != GRPC_ERROR_NONE) { fail_helper_locked(exec_ctx, s, GRPC_ERROR_REF(s->cancel_self_error)); @@ -601,7 +610,7 @@ static void op_state_machine(grpc_exec_ctx *exec_ctx, void *arg, complete_if_batch_end_locked( exec_ctx, s, GRPC_ERROR_NONE, s->send_message_op, "op_state_machine scheduling send-message-on-complete"); - s->send_message_op = NULL; + s->send_message_op = nullptr; } } // Pause a send trailing metadata if there is still an outstanding @@ -612,10 +621,11 @@ static void op_state_machine(grpc_exec_ctx *exec_ctx, void *arg, (!s->send_message_op || (s->t->is_client && (s->trailing_md_recvd || s->to_read_trailing_md_filled)))) { - grpc_metadata_batch *dest = (other == NULL) ? &s->write_buffer_trailing_md - : &other->to_read_trailing_md; - bool *destfilled = (other == NULL) ? &s->write_buffer_trailing_md_filled - : &other->to_read_trailing_md_filled; + grpc_metadata_batch* dest = (other == nullptr) + ? &s->write_buffer_trailing_md + : &other->to_read_trailing_md; + bool* destfilled = (other == nullptr) ? &s->write_buffer_trailing_md_filled + : &other->to_read_trailing_md_filled; if (*destfilled || s->trailing_md_sent) { // The buffer is already in use; that's an error! INPROC_LOG(GPR_DEBUG, "Extra trailing metadata %p", s); @@ -627,7 +637,7 @@ static void op_state_machine(grpc_exec_ctx *exec_ctx, void *arg, fill_in_metadata(exec_ctx, s, s->send_trailing_md_op->payload->send_trailing_metadata .send_trailing_metadata, - 0, dest, NULL, destfilled); + 0, dest, nullptr, destfilled); } s->trailing_md_sent = true; if (!s->t->is_client && s->trailing_md_recvd && s->recv_trailing_md_op) { @@ -635,7 +645,7 @@ static void op_state_machine(grpc_exec_ctx *exec_ctx, void *arg, "op_state_machine %p scheduling trailing-md-on-complete", s); GRPC_CLOSURE_SCHED(exec_ctx, s->recv_trailing_md_op->on_complete, GRPC_ERROR_NONE); - s->recv_trailing_md_op = NULL; + s->recv_trailing_md_op = nullptr; needs_close = true; } } @@ -643,7 +653,7 @@ static void op_state_machine(grpc_exec_ctx *exec_ctx, void *arg, complete_if_batch_end_locked( exec_ctx, s, GRPC_ERROR_NONE, s->send_trailing_md_op, "op_state_machine scheduling send-trailing-metadata-on-complete"); - s->send_trailing_md_op = NULL; + s->send_trailing_md_op = nullptr; } if (s->recv_initial_md_op) { if (s->initial_md_recvd) { @@ -665,9 +675,15 @@ static void op_state_machine(grpc_exec_ctx *exec_ctx, void *arg, s->recv_initial_md_op->payload->recv_initial_metadata .recv_initial_metadata, s->recv_initial_md_op->payload->recv_initial_metadata.recv_flags, - NULL); + nullptr); s->recv_initial_md_op->payload->recv_initial_metadata .recv_initial_metadata->deadline = s->deadline; + if (s->recv_initial_md_op->payload->recv_initial_metadata + .trailing_metadata_available != nullptr) { + *s->recv_initial_md_op->payload->recv_initial_metadata + .trailing_metadata_available = + (other != nullptr && other->send_trailing_md_op != nullptr); + } grpc_metadata_batch_clear(exec_ctx, &s->to_read_initial_md); s->to_read_initial_md_filled = false; INPROC_LOG(GPR_DEBUG, @@ -680,7 +696,7 @@ static void op_state_machine(grpc_exec_ctx *exec_ctx, void *arg, complete_if_batch_end_locked( exec_ctx, s, new_err, s->recv_initial_md_op, "op_state_machine scheduling recv-initial-metadata-on-complete"); - s->recv_initial_md_op = NULL; + s->recv_initial_md_op = nullptr; if (new_err != GRPC_ERROR_NONE) { INPROC_LOG(GPR_DEBUG, @@ -713,7 +729,7 @@ static void op_state_machine(grpc_exec_ctx *exec_ctx, void *arg, fail_helper_locked(exec_ctx, s, GRPC_ERROR_REF(new_err)); goto done; } - if (s->recv_message_op != NULL) { + if (s->recv_message_op != nullptr) { // This message needs to be wrapped up because it will never be // satisfied INPROC_LOG(GPR_DEBUG, "op_state_machine %p scheduling message-ready", s); @@ -724,7 +740,7 @@ static void op_state_machine(grpc_exec_ctx *exec_ctx, void *arg, complete_if_batch_end_locked( exec_ctx, s, new_err, s->recv_message_op, "op_state_machine scheduling recv-message-on-complete"); - s->recv_message_op = NULL; + s->recv_message_op = nullptr; } if ((s->trailing_md_sent || s->t->is_client) && s->send_message_op) { // Nothing further will try to receive from this stream, so finish off @@ -732,16 +748,16 @@ static void op_state_machine(grpc_exec_ctx *exec_ctx, void *arg, complete_if_batch_end_locked( exec_ctx, s, new_err, s->send_message_op, "op_state_machine scheduling send-message-on-complete"); - s->send_message_op = NULL; + s->send_message_op = nullptr; } - if (s->recv_trailing_md_op != NULL) { + if (s->recv_trailing_md_op != nullptr) { // We wanted trailing metadata and we got it s->trailing_md_recvd = true; new_err = fill_in_metadata(exec_ctx, s, &s->to_read_trailing_md, 0, s->recv_trailing_md_op->payload ->recv_trailing_metadata.recv_trailing_metadata, - NULL, NULL); + nullptr, nullptr); grpc_metadata_batch_clear(exec_ctx, &s->to_read_trailing_md); s->to_read_trailing_md_filled = false; @@ -756,7 +772,7 @@ static void op_state_machine(grpc_exec_ctx *exec_ctx, void *arg, s, new_err); GRPC_CLOSURE_SCHED(exec_ctx, s->recv_trailing_md_op->on_complete, GRPC_ERROR_REF(new_err)); - s->recv_trailing_md_op = NULL; + s->recv_trailing_md_op = nullptr; needs_close = true; } else { INPROC_LOG(GPR_DEBUG, @@ -780,7 +796,7 @@ static void op_state_machine(grpc_exec_ctx *exec_ctx, void *arg, complete_if_batch_end_locked( exec_ctx, s, new_err, s->recv_message_op, "op_state_machine scheduling recv-message-on-complete"); - s->recv_message_op = NULL; + s->recv_message_op = nullptr; } if (s->trailing_md_recvd && (s->trailing_md_sent || s->t->is_client) && s->send_message_op) { @@ -789,7 +805,7 @@ static void op_state_machine(grpc_exec_ctx *exec_ctx, void *arg, complete_if_batch_end_locked( exec_ctx, s, new_err, s->send_message_op, "op_state_machine scheduling send-message-on-complete"); - s->send_message_op = NULL; + s->send_message_op = nullptr; } if (s->send_message_op || s->send_trailing_md_op || s->recv_initial_md_op || s->recv_message_op || s->recv_trailing_md_op) { @@ -810,8 +826,8 @@ done: GRPC_ERROR_UNREF(new_err); } -static bool cancel_stream_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s, - grpc_error *error) { +static bool cancel_stream_locked(grpc_exec_ctx* exec_ctx, inproc_stream* s, + grpc_error* error) { bool ret = false; // was the cancel accepted INPROC_LOG(GPR_DEBUG, "cancel_stream %p with %s", s, grpc_error_string(error)); @@ -826,15 +842,16 @@ static bool cancel_stream_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s, grpc_metadata_batch cancel_md; grpc_metadata_batch_init(&cancel_md); - inproc_stream *other = s->other_side; - grpc_metadata_batch *dest = (other == NULL) ? &s->write_buffer_trailing_md - : &other->to_read_trailing_md; - bool *destfilled = (other == NULL) ? &s->write_buffer_trailing_md_filled - : &other->to_read_trailing_md_filled; - fill_in_metadata(exec_ctx, s, &cancel_md, 0, dest, NULL, destfilled); + inproc_stream* other = s->other_side; + grpc_metadata_batch* dest = (other == nullptr) + ? &s->write_buffer_trailing_md + : &other->to_read_trailing_md; + bool* destfilled = (other == nullptr) ? &s->write_buffer_trailing_md_filled + : &other->to_read_trailing_md_filled; + fill_in_metadata(exec_ctx, s, &cancel_md, 0, dest, nullptr, destfilled); grpc_metadata_batch_destroy(exec_ctx, &cancel_md); - if (other != NULL) { + if (other != nullptr) { if (other->cancel_other_error == GRPC_ERROR_NONE) { other->cancel_other_error = GRPC_ERROR_REF(s->cancel_self_error); } @@ -851,7 +868,7 @@ static bool cancel_stream_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s, complete_if_batch_end_locked( exec_ctx, s, s->cancel_self_error, s->recv_trailing_md_op, "cancel_stream scheduling trailing-md-on-complete"); - s->recv_trailing_md_op = NULL; + s->recv_trailing_md_op = nullptr; } } @@ -862,15 +879,15 @@ static bool cancel_stream_locked(grpc_exec_ctx *exec_ctx, inproc_stream *s, return ret; } -static void perform_stream_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_stream *gs, - grpc_transport_stream_op_batch *op) { +static void perform_stream_op(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_stream* gs, + grpc_transport_stream_op_batch* op) { INPROC_LOG(GPR_DEBUG, "perform_stream_op %p %p %p", gt, gs, op); - inproc_stream *s = (inproc_stream *)gs; - gpr_mu *mu = &s->t->mu->mu; // save aside in case s gets closed + inproc_stream* s = (inproc_stream*)gs; + gpr_mu* mu = &s->t->mu->mu; // save aside in case s gets closed gpr_mu_lock(mu); - if (GRPC_TRACER_ON(grpc_inproc_trace)) { + if (grpc_inproc_trace.enabled()) { if (op->send_initial_metadata) { log_metadata(op->payload->send_initial_metadata.send_initial_metadata, s->t->is_client, true); @@ -880,9 +897,9 @@ static void perform_stream_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, s->t->is_client, false); } } - grpc_error *error = GRPC_ERROR_NONE; - grpc_closure *on_complete = op->on_complete; - if (on_complete == NULL) { + grpc_error* error = GRPC_ERROR_NONE; + grpc_closure* on_complete = op->on_complete; + if (on_complete == nullptr) { on_complete = &do_nothing_closure; } @@ -907,19 +924,21 @@ static void perform_stream_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, bool needs_close = false; - inproc_stream *other = s->other_side; + inproc_stream* other = s->other_side; if (error == GRPC_ERROR_NONE && (op->send_initial_metadata || op->send_trailing_metadata)) { if (s->t->is_closed) { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Endpoint already shutdown"); } if (error == GRPC_ERROR_NONE && op->send_initial_metadata) { - grpc_metadata_batch *dest = (other == NULL) ? &s->write_buffer_initial_md - : &other->to_read_initial_md; - uint32_t *destflags = (other == NULL) ? &s->write_buffer_initial_md_flags - : &other->to_read_initial_md_flags; - bool *destfilled = (other == NULL) ? &s->write_buffer_initial_md_filled - : &other->to_read_initial_md_filled; + grpc_metadata_batch* dest = (other == nullptr) + ? &s->write_buffer_initial_md + : &other->to_read_initial_md; + uint32_t* destflags = (other == nullptr) + ? &s->write_buffer_initial_md_flags + : &other->to_read_initial_md_flags; + bool* destfilled = (other == nullptr) ? &s->write_buffer_initial_md_filled + : &other->to_read_initial_md_filled; if (*destfilled || s->initial_md_sent) { // The buffer is already in use; that's an error! INPROC_LOG(GPR_DEBUG, "Extra initial metadata %p", s); @@ -933,8 +952,8 @@ static void perform_stream_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, dest, destflags, destfilled); } if (s->t->is_client) { - grpc_millis *dl = - (other == NULL) ? &s->write_buffer_deadline : &other->deadline; + grpc_millis* dl = + (other == nullptr) ? &s->write_buffer_deadline : &other->deadline; *dl = GPR_MIN(*dl, op->payload->send_initial_metadata .send_initial_metadata->deadline); s->initial_md_sent = true; @@ -972,11 +991,12 @@ static void perform_stream_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, // 4. We want to receive a message and there is a message ready // 5. There is trailing metadata, even if nothing specifically wants // that because that can shut down the receive message as well - if ((op->send_message && other && ((other->recv_message_op != NULL) || - (other->recv_trailing_md_op != NULL))) || + if ((op->send_message && other && + ((other->recv_message_op != nullptr) || + (other->recv_trailing_md_op != nullptr))) || (op->send_trailing_metadata && !op->send_message) || (op->recv_initial_metadata && s->to_read_initial_md_filled) || - (op->recv_message && other && (other->send_message_op != NULL)) || + (op->recv_message && other && (other->send_message_op != nullptr)) || (s->to_read_trailing_md_filled || s->trailing_md_recvd)) { if (!s->op_closure_scheduled) { GRPC_CLOSURE_SCHED(exec_ctx, &s->op_closure, GRPC_ERROR_NONE); @@ -989,6 +1009,15 @@ static void perform_stream_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, if (error != GRPC_ERROR_NONE) { // Schedule op's closures that we didn't push to op state machine if (op->recv_initial_metadata) { + if (op->payload->recv_initial_metadata.trailing_metadata_available != + nullptr) { + // Set to true unconditionally, because we're failing the call, so + // even if we haven't actually seen the send_trailing_metadata op + // from the other side, we're going to return trailing metadata + // anyway. + *op->payload->recv_initial_metadata.trailing_metadata_available = + true; + } INPROC_LOG( GPR_DEBUG, "perform_stream_op error %p scheduling initial-metadata-ready %p", @@ -1020,8 +1049,8 @@ static void perform_stream_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, GRPC_ERROR_UNREF(error); } -static void close_transport_locked(grpc_exec_ctx *exec_ctx, - inproc_transport *t) { +static void close_transport_locked(grpc_exec_ctx* exec_ctx, + inproc_transport* t) { INPROC_LOG(GPR_DEBUG, "close_transport %p %d", t, t->is_closed); grpc_connectivity_state_set( exec_ctx, &t->connectivity, GRPC_CHANNEL_SHUTDOWN, @@ -1030,7 +1059,7 @@ static void close_transport_locked(grpc_exec_ctx *exec_ctx, if (!t->is_closed) { t->is_closed = true; /* Also end all streams on this transport */ - while (t->stream_list != NULL) { + while (t->stream_list != nullptr) { // cancel_stream_locked also adjusts stream list cancel_stream_locked( exec_ctx, t->stream_list, @@ -1041,9 +1070,9 @@ static void close_transport_locked(grpc_exec_ctx *exec_ctx, } } -static void perform_transport_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_transport_op *op) { - inproc_transport *t = (inproc_transport *)gt; +static void perform_transport_op(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_transport_op* op) { + inproc_transport* t = (inproc_transport*)gt; INPROC_LOG(GPR_DEBUG, "perform_transport_op %p %p", t, op); gpr_mu_lock(&t->mu->mu); if (op->on_connectivity_state_change) { @@ -1075,17 +1104,17 @@ static void perform_transport_op(grpc_exec_ctx *exec_ctx, grpc_transport *gt, gpr_mu_unlock(&t->mu->mu); } -static void destroy_stream(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_stream *gs, - grpc_closure *then_schedule_closure) { +static void destroy_stream(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_stream* gs, + grpc_closure* then_schedule_closure) { INPROC_LOG(GPR_DEBUG, "destroy_stream %p %p", gs, then_schedule_closure); - inproc_stream *s = (inproc_stream *)gs; + inproc_stream* s = (inproc_stream*)gs; s->closure_at_destroy = then_schedule_closure; really_destroy_stream(exec_ctx, s); } -static void destroy_transport(grpc_exec_ctx *exec_ctx, grpc_transport *gt) { - inproc_transport *t = (inproc_transport *)gt; +static void destroy_transport(grpc_exec_ctx* exec_ctx, grpc_transport* gt) { + inproc_transport* t = (inproc_transport*)gt; INPROC_LOG(GPR_DEBUG, "destroy_transport %p", t); gpr_mu_lock(&t->mu->mu); close_transport_locked(exec_ctx, t); @@ -1098,30 +1127,30 @@ static void destroy_transport(grpc_exec_ctx *exec_ctx, grpc_transport *gt) { * INTEGRATION GLUE */ -static void set_pollset(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_stream *gs, grpc_pollset *pollset) { +static void set_pollset(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_stream* gs, grpc_pollset* pollset) { // Nothing to do here } -static void set_pollset_set(grpc_exec_ctx *exec_ctx, grpc_transport *gt, - grpc_stream *gs, grpc_pollset_set *pollset_set) { +static void set_pollset_set(grpc_exec_ctx* exec_ctx, grpc_transport* gt, + grpc_stream* gs, grpc_pollset_set* pollset_set) { // Nothing to do here } -static grpc_endpoint *get_endpoint(grpc_exec_ctx *exec_ctx, grpc_transport *t) { - return NULL; +static grpc_endpoint* get_endpoint(grpc_exec_ctx* exec_ctx, grpc_transport* t) { + return nullptr; } /******************************************************************************* * GLOBAL INIT AND DESTROY */ -static void do_nothing(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) {} +static void do_nothing(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) {} void grpc_inproc_transport_init(void) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - GRPC_CLOSURE_INIT(&do_nothing_closure, do_nothing, NULL, + GRPC_CLOSURE_INIT(&do_nothing_closure, do_nothing, nullptr, grpc_schedule_on_exec_ctx); - g_empty_slice = grpc_slice_from_static_buffer(NULL, 0); + g_empty_slice = grpc_slice_from_static_buffer(nullptr, 0); grpc_slice key_tmp = grpc_slice_from_static_string(":path"); g_fake_path_key = grpc_slice_intern(key_tmp); @@ -1146,16 +1175,16 @@ static const grpc_transport_vtable inproc_vtable = { /******************************************************************************* * Main inproc transport functions */ -static void inproc_transports_create(grpc_exec_ctx *exec_ctx, - grpc_transport **server_transport, - const grpc_channel_args *server_args, - grpc_transport **client_transport, - const grpc_channel_args *client_args) { +static void inproc_transports_create(grpc_exec_ctx* exec_ctx, + grpc_transport** server_transport, + const grpc_channel_args* server_args, + grpc_transport** client_transport, + const grpc_channel_args* client_args) { INPROC_LOG(GPR_DEBUG, "inproc_transports_create"); - inproc_transport *st = (inproc_transport *)gpr_zalloc(sizeof(*st)); - inproc_transport *ct = (inproc_transport *)gpr_zalloc(sizeof(*ct)); + inproc_transport* st = (inproc_transport*)gpr_zalloc(sizeof(*st)); + inproc_transport* ct = (inproc_transport*)gpr_zalloc(sizeof(*ct)); // Share one lock between both sides since both sides get affected - st->mu = ct->mu = (shared_mu *)gpr_malloc(sizeof(*st->mu)); + st->mu = ct->mu = (shared_mu*)gpr_malloc(sizeof(*st->mu)); gpr_mu_init(&st->mu->mu); gpr_ref_init(&st->mu->refs, 2); st->base.vtable = &inproc_vtable; @@ -1172,39 +1201,39 @@ static void inproc_transports_create(grpc_exec_ctx *exec_ctx, "inproc_client"); st->other_side = ct; ct->other_side = st; - st->stream_list = NULL; - ct->stream_list = NULL; - *server_transport = (grpc_transport *)st; - *client_transport = (grpc_transport *)ct; + st->stream_list = nullptr; + ct->stream_list = nullptr; + *server_transport = (grpc_transport*)st; + *client_transport = (grpc_transport*)ct; } -grpc_channel *grpc_inproc_channel_create(grpc_server *server, - grpc_channel_args *args, - void *reserved) { +grpc_channel* grpc_inproc_channel_create(grpc_server* server, + grpc_channel_args* args, + void* reserved) { GRPC_API_TRACE("grpc_inproc_channel_create(server=%p, args=%p)", 2, (server, args)); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - const grpc_channel_args *server_args = grpc_server_get_channel_args(server); + const grpc_channel_args* server_args = grpc_server_get_channel_args(server); // Add a default authority channel argument for the client grpc_arg default_authority_arg; default_authority_arg.type = GRPC_ARG_STRING; - default_authority_arg.key = (char *)GRPC_ARG_DEFAULT_AUTHORITY; - default_authority_arg.value.string = (char *)"inproc.authority"; - grpc_channel_args *client_args = + default_authority_arg.key = (char*)GRPC_ARG_DEFAULT_AUTHORITY; + default_authority_arg.value.string = (char*)"inproc.authority"; + grpc_channel_args* client_args = grpc_channel_args_copy_and_add(args, &default_authority_arg, 1); - grpc_transport *server_transport; - grpc_transport *client_transport; + grpc_transport* server_transport; + grpc_transport* client_transport; inproc_transports_create(&exec_ctx, &server_transport, server_args, &client_transport, client_args); - grpc_server_setup_transport(&exec_ctx, server, server_transport, NULL, + grpc_server_setup_transport(&exec_ctx, server, server_transport, nullptr, server_args); - grpc_channel *channel = + grpc_channel* channel = grpc_channel_create(&exec_ctx, "inproc", client_args, GRPC_CLIENT_DIRECT_CHANNEL, client_transport); diff --git a/src/core/ext/transport/inproc/inproc_transport.h b/src/core/ext/transport/inproc/inproc_transport.h index 37e6d99e99f..7c0453e7ce1 100644 --- a/src/core/ext/transport/inproc/inproc_transport.h +++ b/src/core/ext/transport/inproc/inproc_transport.h @@ -21,21 +21,13 @@ #include "src/core/lib/transport/transport_impl.h" -#ifdef __cplusplus -extern "C" { -#endif +grpc_channel* grpc_inproc_channel_create(grpc_server* server, + grpc_channel_args* args, + void* reserved); -grpc_channel *grpc_inproc_channel_create(grpc_server *server, - grpc_channel_args *args, - void *reserved); - -extern grpc_tracer_flag grpc_inproc_trace; +extern grpc_core::TraceFlag grpc_inproc_trace; void grpc_inproc_transport_init(void); void grpc_inproc_transport_shutdown(void); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_EXT_TRANSPORT_INPROC_INPROC_TRANSPORT_H */ diff --git a/src/core/lib/backoff/backoff.cc b/src/core/lib/backoff/backoff.cc index fe0a7518171..dc754ddd821 100644 --- a/src/core/lib/backoff/backoff.cc +++ b/src/core/lib/backoff/backoff.cc @@ -20,54 +20,61 @@ #include -void grpc_backoff_init(grpc_backoff *backoff, - grpc_millis initial_connect_timeout, double multiplier, - double jitter, grpc_millis min_timeout_millis, - grpc_millis max_timeout_millis) { - backoff->initial_connect_timeout = initial_connect_timeout; +void grpc_backoff_init(grpc_backoff* backoff, grpc_millis initial_backoff, + double multiplier, double jitter, + grpc_millis min_connect_timeout, + grpc_millis max_backoff) { + backoff->initial_backoff = initial_backoff; backoff->multiplier = multiplier; backoff->jitter = jitter; - backoff->min_timeout_millis = min_timeout_millis; - backoff->max_timeout_millis = max_timeout_millis; + backoff->min_connect_timeout = min_connect_timeout; + backoff->max_backoff = max_backoff; backoff->rng_state = (uint32_t)gpr_now(GPR_CLOCK_REALTIME).tv_nsec; } -grpc_millis grpc_backoff_begin(grpc_exec_ctx *exec_ctx, grpc_backoff *backoff) { - backoff->current_timeout_millis = backoff->initial_connect_timeout; - const grpc_millis first_timeout = - GPR_MAX(backoff->current_timeout_millis, backoff->min_timeout_millis); - return grpc_exec_ctx_now(exec_ctx) + first_timeout; +grpc_backoff_result grpc_backoff_begin(grpc_exec_ctx* exec_ctx, + grpc_backoff* backoff) { + backoff->current_backoff = backoff->initial_backoff; + const grpc_millis initial_timeout = + GPR_MAX(backoff->initial_backoff, backoff->min_connect_timeout); + const grpc_millis now = grpc_exec_ctx_now(exec_ctx); + const grpc_backoff_result result = {now + initial_timeout, + now + backoff->current_backoff}; + return result; } /* Generate a random number between 0 and 1. */ -static double generate_uniform_random_number(uint32_t *rng_state) { +static double generate_uniform_random_number(uint32_t* rng_state) { *rng_state = (1103515245 * *rng_state + 12345) % ((uint32_t)1 << 31); return *rng_state / (double)((uint32_t)1 << 31); } -grpc_millis grpc_backoff_step(grpc_exec_ctx *exec_ctx, grpc_backoff *backoff) { - const double new_timeout_millis = - backoff->multiplier * (double)backoff->current_timeout_millis; - backoff->current_timeout_millis = - GPR_MIN((grpc_millis)new_timeout_millis, backoff->max_timeout_millis); - - const double jitter_range_width = backoff->jitter * new_timeout_millis; - const double jitter = - (2 * generate_uniform_random_number(&backoff->rng_state) - 1) * - jitter_range_width; - - backoff->current_timeout_millis = - (grpc_millis)((double)(backoff->current_timeout_millis) + jitter); - - const grpc_millis current_deadline = - grpc_exec_ctx_now(exec_ctx) + backoff->current_timeout_millis; - - const grpc_millis min_deadline = - grpc_exec_ctx_now(exec_ctx) + backoff->min_timeout_millis; +static double generate_uniform_random_number_between(uint32_t* rng_state, + double a, double b) { + if (a == b) return a; + if (a > b) GPR_SWAP(double, a, b); // make sure a < b + const double range = b - a; + return a + generate_uniform_random_number(rng_state) * range; +} - return GPR_MAX(current_deadline, min_deadline); +grpc_backoff_result grpc_backoff_step(grpc_exec_ctx* exec_ctx, + grpc_backoff* backoff) { + backoff->current_backoff = (grpc_millis)(GPR_MIN( + backoff->current_backoff * backoff->multiplier, backoff->max_backoff)); + const double jitter = generate_uniform_random_number_between( + &backoff->rng_state, -backoff->jitter * backoff->current_backoff, + backoff->jitter * backoff->current_backoff); + const grpc_millis current_timeout = + GPR_MAX((grpc_millis)(backoff->current_backoff + jitter), + backoff->min_connect_timeout); + const grpc_millis next_timeout = GPR_MIN( + (grpc_millis)(backoff->current_backoff + jitter), backoff->max_backoff); + const grpc_millis now = grpc_exec_ctx_now(exec_ctx); + const grpc_backoff_result result = {now + current_timeout, + now + next_timeout}; + return result; } -void grpc_backoff_reset(grpc_backoff *backoff) { - backoff->current_timeout_millis = backoff->initial_connect_timeout; +void grpc_backoff_reset(grpc_backoff* backoff) { + backoff->current_backoff = backoff->initial_backoff; } diff --git a/src/core/lib/backoff/backoff.h b/src/core/lib/backoff/backoff.h index 80e49ea52ab..0da9082e702 100644 --- a/src/core/lib/backoff/backoff.h +++ b/src/core/lib/backoff/backoff.h @@ -21,46 +21,55 @@ #include "src/core/lib/iomgr/exec_ctx.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct { /// const: how long to wait after the first failure before retrying - grpc_millis initial_connect_timeout; + grpc_millis initial_backoff; + /// const: factor with which to multiply backoff after a failed retry double multiplier; + /// const: amount to randomize backoffs double jitter; - /// const: minimum time between retries in milliseconds - grpc_millis min_timeout_millis; - /// const: maximum time between retries in milliseconds - grpc_millis max_timeout_millis; + + /// const: minimum time between retries + grpc_millis min_connect_timeout; + + /// const: maximum time between retries + grpc_millis max_backoff; + + /// current delay before retries + grpc_millis current_backoff; /// random number generator uint32_t rng_state; - - /// current retry timeout in milliseconds - grpc_millis current_timeout_millis; } grpc_backoff; +typedef struct { + /// Deadline to be used for the current attempt. + grpc_millis current_deadline; + + /// Deadline to be used for the next attempt, following the backoff strategy. + grpc_millis next_attempt_start_time; +} grpc_backoff_result; + /// Initialize backoff machinery - does not need to be destroyed -void grpc_backoff_init(grpc_backoff *backoff, - grpc_millis initial_connect_timeout, double multiplier, - double jitter, grpc_millis min_timeout_millis, - grpc_millis max_timeout_millis); - -/// Begin retry loop: returns a timespec for the NEXT retry -grpc_millis grpc_backoff_begin(grpc_exec_ctx *exec_ctx, grpc_backoff *backoff); -/// Step a retry loop: returns a timespec for the NEXT retry -grpc_millis grpc_backoff_step(grpc_exec_ctx *exec_ctx, grpc_backoff *backoff); -/// Reset the backoff, so the next grpc_backoff_step will be a -/// grpc_backoff_begin -/// instead -void grpc_backoff_reset(grpc_backoff *backoff); +void grpc_backoff_init(grpc_backoff* backoff, grpc_millis initial_backoff, + double multiplier, double jitter, + grpc_millis min_connect_timeout, + grpc_millis max_backoff); -#ifdef __cplusplus -} -#endif +/// Begin retry loop: returns the deadlines to be used for the current attempt +/// and the subsequent retry, if any. +grpc_backoff_result grpc_backoff_begin(grpc_exec_ctx* exec_ctx, + grpc_backoff* backoff); + +/// Step a retry loop: returns the deadlines to be used for the current attempt +/// and the subsequent retry, if any. +grpc_backoff_result grpc_backoff_step(grpc_exec_ctx* exec_ctx, + grpc_backoff* backoff); + +/// Reset the backoff, so the next grpc_backoff_step will be a +/// grpc_backoff_begin. +void grpc_backoff_reset(grpc_backoff* backoff); #endif /* GRPC_CORE_LIB_BACKOFF_BACKOFF_H */ diff --git a/src/core/lib/channel/channel_args.cc b/src/core/lib/channel/channel_args.cc index 30248b3c609..735fcbe405c 100644 --- a/src/core/lib/channel/channel_args.cc +++ b/src/core/lib/channel/channel_args.cc @@ -31,7 +31,7 @@ #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/support/string.h" -static grpc_arg copy_arg(const grpc_arg *src) { +static grpc_arg copy_arg(const grpc_arg* src) { grpc_arg dst; dst.type = src->type; dst.key = gpr_strdup(src->key); @@ -51,21 +51,21 @@ static grpc_arg copy_arg(const grpc_arg *src) { return dst; } -grpc_channel_args *grpc_channel_args_copy_and_add(const grpc_channel_args *src, - const grpc_arg *to_add, +grpc_channel_args* grpc_channel_args_copy_and_add(const grpc_channel_args* src, + const grpc_arg* to_add, size_t num_to_add) { - return grpc_channel_args_copy_and_add_and_remove(src, NULL, 0, to_add, + return grpc_channel_args_copy_and_add_and_remove(src, nullptr, 0, to_add, num_to_add); } -grpc_channel_args *grpc_channel_args_copy_and_remove( - const grpc_channel_args *src, const char **to_remove, +grpc_channel_args* grpc_channel_args_copy_and_remove( + const grpc_channel_args* src, const char** to_remove, size_t num_to_remove) { return grpc_channel_args_copy_and_add_and_remove(src, to_remove, - num_to_remove, NULL, 0); + num_to_remove, nullptr, 0); } -static bool should_remove_arg(const grpc_arg *arg, const char **to_remove, +static bool should_remove_arg(const grpc_arg* arg, const char** to_remove, size_t num_to_remove) { for (size_t i = 0; i < num_to_remove; ++i) { if (strcmp(arg->key, to_remove[i]) == 0) return true; @@ -73,12 +73,12 @@ static bool should_remove_arg(const grpc_arg *arg, const char **to_remove, return false; } -grpc_channel_args *grpc_channel_args_copy_and_add_and_remove( - const grpc_channel_args *src, const char **to_remove, size_t num_to_remove, - const grpc_arg *to_add, size_t num_to_add) { +grpc_channel_args* grpc_channel_args_copy_and_add_and_remove( + const grpc_channel_args* src, const char** to_remove, size_t num_to_remove, + const grpc_arg* to_add, size_t num_to_add) { // Figure out how many args we'll be copying. size_t num_args_to_copy = 0; - if (src != NULL) { + if (src != nullptr) { for (size_t i = 0; i < src->num_args; ++i) { if (!should_remove_arg(&src->args[i], to_remove, num_to_remove)) { ++num_args_to_copy; @@ -86,17 +86,17 @@ grpc_channel_args *grpc_channel_args_copy_and_add_and_remove( } } // Create result. - grpc_channel_args *dst = - (grpc_channel_args *)gpr_malloc(sizeof(grpc_channel_args)); + grpc_channel_args* dst = + (grpc_channel_args*)gpr_malloc(sizeof(grpc_channel_args)); dst->num_args = num_args_to_copy + num_to_add; if (dst->num_args == 0) { - dst->args = NULL; + dst->args = nullptr; return dst; } - dst->args = (grpc_arg *)gpr_malloc(sizeof(grpc_arg) * dst->num_args); + dst->args = (grpc_arg*)gpr_malloc(sizeof(grpc_arg) * dst->num_args); // Copy args from src that are not being removed. size_t dst_idx = 0; - if (src != NULL) { + if (src != nullptr) { for (size_t i = 0; i < src->num_args; ++i) { if (!should_remove_arg(&src->args[i], to_remove, num_to_remove)) { dst->args[dst_idx++] = copy_arg(&src->args[i]); @@ -111,30 +111,30 @@ grpc_channel_args *grpc_channel_args_copy_and_add_and_remove( return dst; } -grpc_channel_args *grpc_channel_args_copy(const grpc_channel_args *src) { - return grpc_channel_args_copy_and_add(src, NULL, 0); +grpc_channel_args* grpc_channel_args_copy(const grpc_channel_args* src) { + return grpc_channel_args_copy_and_add(src, nullptr, 0); } -grpc_channel_args *grpc_channel_args_union(const grpc_channel_args *a, - const grpc_channel_args *b) { +grpc_channel_args* grpc_channel_args_union(const grpc_channel_args* a, + const grpc_channel_args* b) { const size_t max_out = (a->num_args + b->num_args); - grpc_arg *uniques = (grpc_arg *)gpr_malloc(sizeof(*uniques) * max_out); + grpc_arg* uniques = (grpc_arg*)gpr_malloc(sizeof(*uniques) * max_out); for (size_t i = 0; i < a->num_args; ++i) uniques[i] = a->args[i]; size_t uniques_idx = a->num_args; for (size_t i = 0; i < b->num_args; ++i) { - const char *b_key = b->args[i].key; - if (grpc_channel_args_find(a, b_key) == NULL) { // not found + const char* b_key = b->args[i].key; + if (grpc_channel_args_find(a, b_key) == nullptr) { // not found uniques[uniques_idx++] = b->args[i]; } } - grpc_channel_args *result = - grpc_channel_args_copy_and_add(NULL, uniques, uniques_idx); + grpc_channel_args* result = + grpc_channel_args_copy_and_add(nullptr, uniques, uniques_idx); gpr_free(uniques); return result; } -static int cmp_arg(const grpc_arg *a, const grpc_arg *b) { +static int cmp_arg(const grpc_arg* a, const grpc_arg* b) { int c = GPR_ICMP(a->type, b->type); if (c != 0) return c; c = strcmp(a->key, b->key); @@ -160,26 +160,26 @@ static int cmp_arg(const grpc_arg *a, const grpc_arg *b) { /* stabilizing comparison function: since channel_args ordering matters for * keys with the same name, we need to preserve that ordering */ -static int cmp_key_stable(const void *ap, const void *bp) { - const grpc_arg *const *a = (const grpc_arg *const *)ap; - const grpc_arg *const *b = (const grpc_arg *const *)bp; +static int cmp_key_stable(const void* ap, const void* bp) { + const grpc_arg* const* a = (const grpc_arg* const*)ap; + const grpc_arg* const* b = (const grpc_arg* const*)bp; int c = strcmp((*a)->key, (*b)->key); if (c == 0) c = GPR_ICMP(*a, *b); return c; } -grpc_channel_args *grpc_channel_args_normalize(const grpc_channel_args *a) { - grpc_arg **args = (grpc_arg **)gpr_malloc(sizeof(grpc_arg *) * a->num_args); +grpc_channel_args* grpc_channel_args_normalize(const grpc_channel_args* a) { + grpc_arg** args = (grpc_arg**)gpr_malloc(sizeof(grpc_arg*) * a->num_args); for (size_t i = 0; i < a->num_args; i++) { args[i] = &a->args[i]; } if (a->num_args > 1) - qsort(args, a->num_args, sizeof(grpc_arg *), cmp_key_stable); + qsort(args, a->num_args, sizeof(grpc_arg*), cmp_key_stable); - grpc_channel_args *b = - (grpc_channel_args *)gpr_malloc(sizeof(grpc_channel_args)); + grpc_channel_args* b = + (grpc_channel_args*)gpr_malloc(sizeof(grpc_channel_args)); b->num_args = a->num_args; - b->args = (grpc_arg *)gpr_malloc(sizeof(grpc_arg) * b->num_args); + b->args = (grpc_arg*)gpr_malloc(sizeof(grpc_arg) * b->num_args); for (size_t i = 0; i < a->num_args; i++) { b->args[i] = copy_arg(args[i]); } @@ -188,7 +188,7 @@ grpc_channel_args *grpc_channel_args_normalize(const grpc_channel_args *a) { return b; } -void grpc_channel_args_destroy(grpc_exec_ctx *exec_ctx, grpc_channel_args *a) { +void grpc_channel_args_destroy(grpc_exec_ctx* exec_ctx, grpc_channel_args* a) { size_t i; if (!a) return; for (i = 0; i < a->num_args; i++) { @@ -210,9 +210,9 @@ void grpc_channel_args_destroy(grpc_exec_ctx *exec_ctx, grpc_channel_args *a) { } grpc_compression_algorithm grpc_channel_args_get_compression_algorithm( - const grpc_channel_args *a) { + const grpc_channel_args* a) { size_t i; - if (a == NULL) return GRPC_COMPRESS_NONE; + if (a == nullptr) return GRPC_COMPRESS_NONE; for (i = 0; i < a->num_args; ++i) { if (a->args[i].type == GRPC_ARG_INTEGER && !strcmp(GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM, a->args[i].key)) { @@ -224,9 +224,9 @@ grpc_compression_algorithm grpc_channel_args_get_compression_algorithm( } grpc_stream_compression_algorithm -grpc_channel_args_get_stream_compression_algorithm(const grpc_channel_args *a) { +grpc_channel_args_get_stream_compression_algorithm(const grpc_channel_args* a) { size_t i; - if (a == NULL) return GRPC_STREAM_COMPRESS_NONE; + if (a == nullptr) return GRPC_STREAM_COMPRESS_NONE; for (i = 0; i < a->num_args; ++i) { if (a->args[i].type == GRPC_ARG_INTEGER && !strcmp(GRPC_STREAM_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM, @@ -238,22 +238,22 @@ grpc_channel_args_get_stream_compression_algorithm(const grpc_channel_args *a) { return GRPC_STREAM_COMPRESS_NONE; } -grpc_channel_args *grpc_channel_args_set_compression_algorithm( - grpc_channel_args *a, grpc_compression_algorithm algorithm) { +grpc_channel_args* grpc_channel_args_set_compression_algorithm( + grpc_channel_args* a, grpc_compression_algorithm algorithm) { GPR_ASSERT(algorithm < GRPC_COMPRESS_ALGORITHMS_COUNT); grpc_arg tmp; tmp.type = GRPC_ARG_INTEGER; - tmp.key = (char *)GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM; + tmp.key = (char*)GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM; tmp.value.integer = algorithm; return grpc_channel_args_copy_and_add(a, &tmp, 1); } -grpc_channel_args *grpc_channel_args_set_stream_compression_algorithm( - grpc_channel_args *a, grpc_stream_compression_algorithm algorithm) { +grpc_channel_args* grpc_channel_args_set_stream_compression_algorithm( + grpc_channel_args* a, grpc_stream_compression_algorithm algorithm) { GPR_ASSERT(algorithm < GRPC_STREAM_COMPRESS_ALGORITHMS_COUNT); grpc_arg tmp; tmp.type = GRPC_ARG_INTEGER; - tmp.key = (char *)GRPC_STREAM_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM; + tmp.key = (char*)GRPC_STREAM_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM; tmp.value.integer = algorithm; return grpc_channel_args_copy_and_add(a, &tmp, 1); } @@ -261,9 +261,9 @@ grpc_channel_args *grpc_channel_args_set_stream_compression_algorithm( /** Returns 1 if the argument for compression algorithm's enabled states bitset * was found in \a a, returning the arg's value in \a states. Otherwise, returns * 0. */ -static int find_compression_algorithm_states_bitset(const grpc_channel_args *a, - int **states_arg) { - if (a != NULL) { +static int find_compression_algorithm_states_bitset(const grpc_channel_args* a, + int** states_arg) { + if (a != nullptr) { size_t i; for (i = 0; i < a->num_args; ++i) { if (a->args[i].type == GRPC_ARG_INTEGER && @@ -282,8 +282,8 @@ static int find_compression_algorithm_states_bitset(const grpc_channel_args *a, * was found in \a a, returning the arg's value in \a states. Otherwise, returns * 0. */ static int find_stream_compression_algorithm_states_bitset( - const grpc_channel_args *a, int **states_arg) { - if (a != NULL) { + const grpc_channel_args* a, int** states_arg) { + if (a != nullptr) { size_t i; for (i = 0; i < a->num_args; ++i) { if (a->args[i].type == GRPC_ARG_INTEGER && @@ -298,17 +298,17 @@ static int find_stream_compression_algorithm_states_bitset( return 0; /* GPR_FALSE */ } -grpc_channel_args *grpc_channel_args_compression_algorithm_set_state( - grpc_exec_ctx *exec_ctx, grpc_channel_args **a, +grpc_channel_args* grpc_channel_args_compression_algorithm_set_state( + grpc_exec_ctx* exec_ctx, grpc_channel_args** a, grpc_compression_algorithm algorithm, int state) { - int *states_arg = NULL; - grpc_channel_args *result = *a; + int* states_arg = nullptr; + grpc_channel_args* result = *a; const int states_arg_found = find_compression_algorithm_states_bitset(*a, &states_arg); if (grpc_channel_args_get_compression_algorithm(*a) == algorithm && state == 0) { - const char *algo_name = NULL; + const char* algo_name = nullptr; GPR_ASSERT(grpc_compression_algorithm_name(algorithm, &algo_name) != 0); gpr_log(GPR_ERROR, "Tried to disable default compression algorithm '%s'. The " @@ -316,21 +316,21 @@ grpc_channel_args *grpc_channel_args_compression_algorithm_set_state( algo_name); } else if (states_arg_found) { if (state != 0) { - GPR_BITSET((unsigned *)states_arg, algorithm); + GPR_BITSET((unsigned*)states_arg, algorithm); } else if (algorithm != GRPC_COMPRESS_NONE) { - GPR_BITCLEAR((unsigned *)states_arg, algorithm); + GPR_BITCLEAR((unsigned*)states_arg, algorithm); } } else { /* create a new arg */ grpc_arg tmp; tmp.type = GRPC_ARG_INTEGER; - tmp.key = (char *)GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET; + tmp.key = (char*)GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET; /* all enabled by default */ tmp.value.integer = (1u << GRPC_COMPRESS_ALGORITHMS_COUNT) - 1; if (state != 0) { - GPR_BITSET((unsigned *)&tmp.value.integer, algorithm); + GPR_BITSET((unsigned*)&tmp.value.integer, algorithm); } else if (algorithm != GRPC_COMPRESS_NONE) { - GPR_BITCLEAR((unsigned *)&tmp.value.integer, algorithm); + GPR_BITCLEAR((unsigned*)&tmp.value.integer, algorithm); } result = grpc_channel_args_copy_and_add(*a, &tmp, 1); grpc_channel_args_destroy(exec_ctx, *a); @@ -339,17 +339,17 @@ grpc_channel_args *grpc_channel_args_compression_algorithm_set_state( return result; } -grpc_channel_args *grpc_channel_args_stream_compression_algorithm_set_state( - grpc_exec_ctx *exec_ctx, grpc_channel_args **a, +grpc_channel_args* grpc_channel_args_stream_compression_algorithm_set_state( + grpc_exec_ctx* exec_ctx, grpc_channel_args** a, grpc_stream_compression_algorithm algorithm, int state) { - int *states_arg = NULL; - grpc_channel_args *result = *a; + int* states_arg = nullptr; + grpc_channel_args* result = *a; const int states_arg_found = find_stream_compression_algorithm_states_bitset(*a, &states_arg); if (grpc_channel_args_get_stream_compression_algorithm(*a) == algorithm && state == 0) { - const char *algo_name = NULL; + const char* algo_name = nullptr; GPR_ASSERT(grpc_stream_compression_algorithm_name(algorithm, &algo_name) != 0); gpr_log(GPR_ERROR, @@ -358,21 +358,21 @@ grpc_channel_args *grpc_channel_args_stream_compression_algorithm_set_state( algo_name); } else if (states_arg_found) { if (state != 0) { - GPR_BITSET((unsigned *)states_arg, algorithm); + GPR_BITSET((unsigned*)states_arg, algorithm); } else if (algorithm != GRPC_STREAM_COMPRESS_NONE) { - GPR_BITCLEAR((unsigned *)states_arg, algorithm); + GPR_BITCLEAR((unsigned*)states_arg, algorithm); } } else { /* create a new arg */ grpc_arg tmp; tmp.type = GRPC_ARG_INTEGER; - tmp.key = (char *)GRPC_STREAM_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET; + tmp.key = (char*)GRPC_STREAM_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET; /* all enabled by default */ tmp.value.integer = (1u << GRPC_STREAM_COMPRESS_ALGORITHMS_COUNT) - 1; if (state != 0) { - GPR_BITSET((unsigned *)&tmp.value.integer, algorithm); + GPR_BITSET((unsigned*)&tmp.value.integer, algorithm); } else if (algorithm != GRPC_STREAM_COMPRESS_NONE) { - GPR_BITCLEAR((unsigned *)&tmp.value.integer, algorithm); + GPR_BITCLEAR((unsigned*)&tmp.value.integer, algorithm); } result = grpc_channel_args_copy_and_add(*a, &tmp, 1); grpc_channel_args_destroy(exec_ctx, *a); @@ -382,8 +382,8 @@ grpc_channel_args *grpc_channel_args_stream_compression_algorithm_set_state( } uint32_t grpc_channel_args_compression_algorithm_get_states( - const grpc_channel_args *a) { - int *states_arg; + const grpc_channel_args* a) { + int* states_arg; if (find_compression_algorithm_states_bitset(a, &states_arg)) { return (uint32_t)*states_arg; } else { @@ -392,8 +392,8 @@ uint32_t grpc_channel_args_compression_algorithm_get_states( } uint32_t grpc_channel_args_stream_compression_algorithm_get_states( - const grpc_channel_args *a) { - int *states_arg; + const grpc_channel_args* a) { + int* states_arg; if (find_stream_compression_algorithm_states_bitset(a, &states_arg)) { return (uint32_t)*states_arg; } else { @@ -402,14 +402,14 @@ uint32_t grpc_channel_args_stream_compression_algorithm_get_states( } } -grpc_channel_args *grpc_channel_args_set_socket_mutator( - grpc_channel_args *a, grpc_socket_mutator *mutator) { +grpc_channel_args* grpc_channel_args_set_socket_mutator( + grpc_channel_args* a, grpc_socket_mutator* mutator) { grpc_arg tmp = grpc_socket_mutator_to_arg(mutator); return grpc_channel_args_copy_and_add(a, &tmp, 1); } -int grpc_channel_args_compare(const grpc_channel_args *a, - const grpc_channel_args *b) { +int grpc_channel_args_compare(const grpc_channel_args* a, + const grpc_channel_args* b) { int c = GPR_ICMP(a->num_args, b->num_args); if (c != 0) return c; for (size_t i = 0; i < a->num_args; i++) { @@ -419,21 +419,21 @@ int grpc_channel_args_compare(const grpc_channel_args *a, return 0; } -const grpc_arg *grpc_channel_args_find(const grpc_channel_args *args, - const char *name) { - if (args != NULL) { +const grpc_arg* grpc_channel_args_find(const grpc_channel_args* args, + const char* name) { + if (args != nullptr) { for (size_t i = 0; i < args->num_args; ++i) { if (strcmp(args->args[i].key, name) == 0) { return &args->args[i]; } } } - return NULL; + return nullptr; } -int grpc_channel_arg_get_integer(const grpc_arg *arg, +int grpc_channel_arg_get_integer(const grpc_arg* arg, const grpc_integer_options options) { - if (arg == NULL) return options.default_value; + if (arg == nullptr) return options.default_value; if (arg->type != GRPC_ARG_INTEGER) { gpr_log(GPR_ERROR, "%s ignored: it must be an integer", arg->key); return options.default_value; @@ -451,8 +451,8 @@ int grpc_channel_arg_get_integer(const grpc_arg *arg, return arg->value.integer; } -bool grpc_channel_arg_get_bool(const grpc_arg *arg, bool default_value) { - if (arg == NULL) return default_value; +bool grpc_channel_arg_get_bool(const grpc_arg* arg, bool default_value) { + if (arg == nullptr) return default_value; if (arg->type != GRPC_ARG_INTEGER) { gpr_log(GPR_ERROR, "%s ignored: it must be an integer", arg->key); return default_value; @@ -469,12 +469,12 @@ bool grpc_channel_arg_get_bool(const grpc_arg *arg, bool default_value) { } } -bool grpc_channel_args_want_minimal_stack(const grpc_channel_args *args) { +bool grpc_channel_args_want_minimal_stack(const grpc_channel_args* args) { return grpc_channel_arg_get_bool( grpc_channel_args_find(args, GRPC_ARG_MINIMAL_STACK), false); } -grpc_arg grpc_channel_arg_string_create(char *name, char *value) { +grpc_arg grpc_channel_arg_string_create(char* name, char* value) { grpc_arg arg; arg.type = GRPC_ARG_STRING; arg.key = name; @@ -482,7 +482,7 @@ grpc_arg grpc_channel_arg_string_create(char *name, char *value) { return arg; } -grpc_arg grpc_channel_arg_integer_create(char *name, int value) { +grpc_arg grpc_channel_arg_integer_create(char* name, int value) { grpc_arg arg; arg.type = GRPC_ARG_INTEGER; arg.key = name; @@ -491,7 +491,7 @@ grpc_arg grpc_channel_arg_integer_create(char *name, int value) { } grpc_arg grpc_channel_arg_pointer_create( - char *name, void *value, const grpc_arg_pointer_vtable *vtable) { + char* name, void* value, const grpc_arg_pointer_vtable* vtable) { grpc_arg arg; arg.type = GRPC_ARG_POINTER; arg.key = name; diff --git a/src/core/lib/channel/channel_args.h b/src/core/lib/channel/channel_args.h index 1896d35cf45..f6cb7fa73db 100644 --- a/src/core/lib/channel/channel_args.h +++ b/src/core/lib/channel/channel_args.h @@ -23,63 +23,59 @@ #include #include "src/core/lib/iomgr/socket_mutator.h" -#ifdef __cplusplus -extern "C" { -#endif - // Channel args are intentionally immutable, to avoid the need for locking. /** Copy the arguments in \a src into a new instance */ -grpc_channel_args *grpc_channel_args_copy(const grpc_channel_args *src); +grpc_channel_args* grpc_channel_args_copy(const grpc_channel_args* src); /** Copy the arguments in \a src into a new instance, stably sorting keys */ -grpc_channel_args *grpc_channel_args_normalize(const grpc_channel_args *src); +grpc_channel_args* grpc_channel_args_normalize(const grpc_channel_args* src); /** Copy the arguments in \a src and append \a to_add. If \a to_add is NULL, it * is equivalent to calling \a grpc_channel_args_copy. */ -grpc_channel_args *grpc_channel_args_copy_and_add(const grpc_channel_args *src, - const grpc_arg *to_add, +grpc_channel_args* grpc_channel_args_copy_and_add(const grpc_channel_args* src, + const grpc_arg* to_add, size_t num_to_add); /** Copies the arguments in \a src except for those whose keys are in \a to_remove. */ -grpc_channel_args *grpc_channel_args_copy_and_remove( - const grpc_channel_args *src, const char **to_remove, size_t num_to_remove); +grpc_channel_args* grpc_channel_args_copy_and_remove( + const grpc_channel_args* src, const char** to_remove, size_t num_to_remove); /** Copies the arguments from \a src except for those whose keys are in \a to_remove and appends the arguments in \a to_add. */ -grpc_channel_args *grpc_channel_args_copy_and_add_and_remove( - const grpc_channel_args *src, const char **to_remove, size_t num_to_remove, - const grpc_arg *to_add, size_t num_to_add); +grpc_channel_args* grpc_channel_args_copy_and_add_and_remove( + const grpc_channel_args* src, const char** to_remove, size_t num_to_remove, + const grpc_arg* to_add, size_t num_to_add); /** Perform the union of \a a and \a b, prioritizing \a a entries */ -grpc_channel_args *grpc_channel_args_union(const grpc_channel_args *a, - const grpc_channel_args *b); +grpc_channel_args* grpc_channel_args_union(const grpc_channel_args* a, + const grpc_channel_args* b); /** Destroy arguments created by \a grpc_channel_args_copy */ -void grpc_channel_args_destroy(grpc_exec_ctx *exec_ctx, grpc_channel_args *a); +void grpc_channel_args_destroy(grpc_exec_ctx* exec_ctx, grpc_channel_args* a); /** Returns the compression algorithm set in \a a. */ grpc_compression_algorithm grpc_channel_args_get_compression_algorithm( - const grpc_channel_args *a); + const grpc_channel_args* a); /** Returns the stream compression algorithm set in \a a. */ grpc_stream_compression_algorithm -grpc_channel_args_get_stream_compression_algorithm(const grpc_channel_args *a); +grpc_channel_args_get_stream_compression_algorithm(const grpc_channel_args* a); /** Returns a channel arg instance with compression enabled. If \a a is * non-NULL, its args are copied. N.B. GRPC_COMPRESS_NONE disables compression * for the channel. */ -grpc_channel_args *grpc_channel_args_set_compression_algorithm( - grpc_channel_args *a, grpc_compression_algorithm algorithm); +grpc_channel_args* grpc_channel_args_set_compression_algorithm( + grpc_channel_args* a, grpc_compression_algorithm algorithm); /** Returns a channel arg instance with stream compression enabled. If \a a is * non-NULL, its args are copied. N.B. GRPC_STREAM_COMPRESS_NONE disables * stream compression for the channel. If a value other than * GRPC_STREAM_COMPRESS_NONE is set, it takes precedence over message-wise * compression algorithms. */ -grpc_channel_args *grpc_channel_args_set_stream_compression_algorithm( - grpc_channel_args *a, grpc_stream_compression_algorithm algorithm); +grpc_channel_args* grpc_channel_args_set_stream_compression_algorithm( + grpc_channel_args* a, grpc_stream_compression_algorithm algorithm); /** Sets the support for the given compression algorithm. By default, all * compression algorithms are enabled. It's an error to disable an algorithm set @@ -88,8 +84,8 @@ grpc_channel_args *grpc_channel_args_set_stream_compression_algorithm( * Returns an instance with the updated algorithm states. The \a a pointer is * modified to point to the returned instance (which may be different from the * input value of \a a). */ -grpc_channel_args *grpc_channel_args_compression_algorithm_set_state( - grpc_exec_ctx *exec_ctx, grpc_channel_args **a, +grpc_channel_args* grpc_channel_args_compression_algorithm_set_state( + grpc_exec_ctx* exec_ctx, grpc_channel_args** a, grpc_compression_algorithm algorithm, int enabled); /** Sets the support for the given stream compression algorithm. By default, all @@ -99,8 +95,8 @@ grpc_channel_args *grpc_channel_args_compression_algorithm_set_state( * Returns an instance with the updated algorithm states. The \a a pointer is * modified to point to the returned instance (which may be different from the * input value of \a a). */ -grpc_channel_args *grpc_channel_args_stream_compression_algorithm_set_state( - grpc_exec_ctx *exec_ctx, grpc_channel_args **a, +grpc_channel_args* grpc_channel_args_stream_compression_algorithm_set_state( + grpc_exec_ctx* exec_ctx, grpc_channel_args** a, grpc_stream_compression_algorithm algorithm, int enabled); /** Returns the bitset representing the support state (true for enabled, false @@ -109,7 +105,7 @@ grpc_channel_args *grpc_channel_args_stream_compression_algorithm_set_state( * The i-th bit of the returned bitset corresponds to the i-th entry in the * grpc_compression_algorithm enum. */ uint32_t grpc_channel_args_compression_algorithm_get_states( - const grpc_channel_args *a); + const grpc_channel_args* a); /** Returns the bitset representing the support state (true for enabled, false * for disabled) for stream compression algorithms. @@ -117,23 +113,23 @@ uint32_t grpc_channel_args_compression_algorithm_get_states( * The i-th bit of the returned bitset corresponds to the i-th entry in the * grpc_stream_compression_algorithm enum. */ uint32_t grpc_channel_args_stream_compression_algorithm_get_states( - const grpc_channel_args *a); + const grpc_channel_args* a); -int grpc_channel_args_compare(const grpc_channel_args *a, - const grpc_channel_args *b); +int grpc_channel_args_compare(const grpc_channel_args* a, + const grpc_channel_args* b); /** Returns a channel arg instance with socket mutator added. The socket mutator * will perform its mutate_fd method on all file descriptors used by the * channel. * If \a a is non-MULL, its args are copied. */ -grpc_channel_args *grpc_channel_args_set_socket_mutator( - grpc_channel_args *a, grpc_socket_mutator *mutator); +grpc_channel_args* grpc_channel_args_set_socket_mutator( + grpc_channel_args* a, grpc_socket_mutator* mutator); /** Returns the value of argument \a name from \a args, or NULL if not found. */ -const grpc_arg *grpc_channel_args_find(const grpc_channel_args *args, - const char *name); +const grpc_arg* grpc_channel_args_find(const grpc_channel_args* args, + const char* name); -bool grpc_channel_args_want_minimal_stack(const grpc_channel_args *args); +bool grpc_channel_args_want_minimal_stack(const grpc_channel_args* args); typedef struct grpc_integer_options { int default_value; // Return this if value is outside of expected bounds. @@ -142,19 +138,15 @@ typedef struct grpc_integer_options { } grpc_integer_options; /** Returns the value of \a arg, subject to the contraints in \a options. */ -int grpc_channel_arg_get_integer(const grpc_arg *arg, +int grpc_channel_arg_get_integer(const grpc_arg* arg, const grpc_integer_options options); -bool grpc_channel_arg_get_bool(const grpc_arg *arg, bool default_value); +bool grpc_channel_arg_get_bool(const grpc_arg* arg, bool default_value); // Helpers for creating channel args. -grpc_arg grpc_channel_arg_string_create(char *name, char *value); -grpc_arg grpc_channel_arg_integer_create(char *name, int value); -grpc_arg grpc_channel_arg_pointer_create(char *name, void *value, - const grpc_arg_pointer_vtable *vtable); - -#ifdef __cplusplus -} -#endif +grpc_arg grpc_channel_arg_string_create(char* name, char* value); +grpc_arg grpc_channel_arg_integer_create(char* name, int value); +grpc_arg grpc_channel_arg_pointer_create(char* name, void* value, + const grpc_arg_pointer_vtable* vtable); #endif /* GRPC_CORE_LIB_CHANNEL_CHANNEL_ARGS_H */ diff --git a/src/core/lib/channel/channel_stack.cc b/src/core/lib/channel/channel_stack.cc index 775c8bc667c..7629d18789d 100644 --- a/src/core/lib/channel/channel_stack.cc +++ b/src/core/lib/channel/channel_stack.cc @@ -23,7 +23,7 @@ #include #include -grpc_tracer_flag grpc_trace_channel = GRPC_TRACER_INITIALIZER(false, "channel"); +grpc_core::TraceFlag grpc_trace_channel(false, "channel"); /* Memory layouts. @@ -45,7 +45,7 @@ grpc_tracer_flag grpc_trace_channel = GRPC_TRACER_INITIALIZER(false, "channel"); #define ROUND_UP_TO_ALIGNMENT_SIZE(x) \ (((x) + GPR_MAX_ALIGNMENT - 1u) & ~(GPR_MAX_ALIGNMENT - 1u)) -size_t grpc_channel_stack_size(const grpc_channel_filter **filters, +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 = @@ -64,52 +64,51 @@ size_t grpc_channel_stack_size(const grpc_channel_filter **filters, return size; } -#define CHANNEL_ELEMS_FROM_STACK(stk) \ - ((grpc_channel_element *)((char *)(stk) + ROUND_UP_TO_ALIGNMENT_SIZE( \ - sizeof(grpc_channel_stack)))) +#define CHANNEL_ELEMS_FROM_STACK(stk) \ + ((grpc_channel_element*)((char*)(stk) + ROUND_UP_TO_ALIGNMENT_SIZE( \ + sizeof(grpc_channel_stack)))) -#define CALL_ELEMS_FROM_STACK(stk) \ - ((grpc_call_element *)((char *)(stk) + \ - ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call_stack)))) +#define CALL_ELEMS_FROM_STACK(stk) \ + ((grpc_call_element*)((char*)(stk) + \ + ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call_stack)))) -grpc_channel_element *grpc_channel_stack_element( - grpc_channel_stack *channel_stack, size_t index) { +grpc_channel_element* grpc_channel_stack_element( + grpc_channel_stack* channel_stack, size_t index) { return CHANNEL_ELEMS_FROM_STACK(channel_stack) + index; } -grpc_channel_element *grpc_channel_stack_last_element( - grpc_channel_stack *channel_stack) { +grpc_channel_element* grpc_channel_stack_last_element( + grpc_channel_stack* channel_stack) { return grpc_channel_stack_element(channel_stack, channel_stack->count - 1); } -grpc_call_element *grpc_call_stack_element(grpc_call_stack *call_stack, +grpc_call_element* grpc_call_stack_element(grpc_call_stack* call_stack, size_t index) { return CALL_ELEMS_FROM_STACK(call_stack) + index; } -grpc_error *grpc_channel_stack_init( - grpc_exec_ctx *exec_ctx, int initial_refs, grpc_iomgr_cb_func destroy, - void *destroy_arg, const grpc_channel_filter **filters, size_t filter_count, - const grpc_channel_args *channel_args, grpc_transport *optional_transport, - const char *name, grpc_channel_stack *stack) { +grpc_error* grpc_channel_stack_init( + grpc_exec_ctx* exec_ctx, int initial_refs, grpc_iomgr_cb_func destroy, + void* destroy_arg, const grpc_channel_filter** filters, size_t filter_count, + const grpc_channel_args* channel_args, grpc_transport* optional_transport, + const char* name, grpc_channel_stack* stack) { size_t call_size = ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call_stack)) + ROUND_UP_TO_ALIGNMENT_SIZE(filter_count * sizeof(grpc_call_element)); - grpc_channel_element *elems; + grpc_channel_element* elems; grpc_channel_element_args args; - char *user_data; + char* user_data; size_t i; stack->count = filter_count; GRPC_STREAM_REF_INIT(&stack->refcount, initial_refs, destroy, destroy_arg, name); elems = CHANNEL_ELEMS_FROM_STACK(stack); - user_data = - ((char *)elems) + - ROUND_UP_TO_ALIGNMENT_SIZE(filter_count * sizeof(grpc_channel_element)); + user_data = ((char*)elems) + ROUND_UP_TO_ALIGNMENT_SIZE( + filter_count * sizeof(grpc_channel_element)); /* init per-filter data */ - grpc_error *first_error = GRPC_ERROR_NONE; + grpc_error* first_error = GRPC_ERROR_NONE; for (i = 0; i < filter_count; i++) { args.channel_stack = stack; args.channel_args = channel_args; @@ -118,7 +117,7 @@ grpc_error *grpc_channel_stack_init( args.is_last = i == (filter_count - 1); elems[i].filter = filters[i]; elems[i].channel_data = user_data; - grpc_error *error = + grpc_error* error = elems[i].filter->init_channel_elem(exec_ctx, &elems[i], &args); if (error != GRPC_ERROR_NONE) { if (first_error == GRPC_ERROR_NONE) { @@ -131,17 +130,17 @@ grpc_error *grpc_channel_stack_init( call_size += ROUND_UP_TO_ALIGNMENT_SIZE(filters[i]->sizeof_call_data); } - GPR_ASSERT(user_data > (char *)stack); - GPR_ASSERT((uintptr_t)(user_data - (char *)stack) == + GPR_ASSERT(user_data > (char*)stack); + GPR_ASSERT((uintptr_t)(user_data - (char*)stack) == grpc_channel_stack_size(filters, filter_count)); stack->call_stack_size = call_size; return first_error; } -void grpc_channel_stack_destroy(grpc_exec_ctx *exec_ctx, - grpc_channel_stack *stack) { - grpc_channel_element *channel_elems = CHANNEL_ELEMS_FROM_STACK(stack); +void grpc_channel_stack_destroy(grpc_exec_ctx* exec_ctx, + grpc_channel_stack* stack) { + grpc_channel_element* channel_elems = CHANNEL_ELEMS_FROM_STACK(stack); size_t count = stack->count; size_t i; @@ -151,31 +150,31 @@ void grpc_channel_stack_destroy(grpc_exec_ctx *exec_ctx, } } -grpc_error *grpc_call_stack_init(grpc_exec_ctx *exec_ctx, - grpc_channel_stack *channel_stack, +grpc_error* grpc_call_stack_init(grpc_exec_ctx* exec_ctx, + grpc_channel_stack* channel_stack, int initial_refs, grpc_iomgr_cb_func destroy, - void *destroy_arg, - const grpc_call_element_args *elem_args) { - grpc_channel_element *channel_elems = CHANNEL_ELEMS_FROM_STACK(channel_stack); + void* destroy_arg, + const grpc_call_element_args* elem_args) { + grpc_channel_element* channel_elems = CHANNEL_ELEMS_FROM_STACK(channel_stack); size_t count = channel_stack->count; - grpc_call_element *call_elems; - char *user_data; + grpc_call_element* call_elems; + char* user_data; size_t i; elem_args->call_stack->count = count; 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 = ((char *)call_elems) + + user_data = ((char*)call_elems) + ROUND_UP_TO_ALIGNMENT_SIZE(count * sizeof(grpc_call_element)); /* init per-filter data */ - grpc_error *first_error = GRPC_ERROR_NONE; + grpc_error* first_error = GRPC_ERROR_NONE; for (i = 0; i < count; i++) { 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; - grpc_error *error = call_elems[i].filter->init_call_elem( + grpc_error* error = call_elems[i].filter->init_call_elem( exec_ctx, &call_elems[i], elem_args); if (error != GRPC_ERROR_NONE) { if (first_error == GRPC_ERROR_NONE) { @@ -190,16 +189,16 @@ grpc_error *grpc_call_stack_init(grpc_exec_ctx *exec_ctx, return first_error; } -void grpc_call_stack_set_pollset_or_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_call_stack *call_stack, - grpc_polling_entity *pollent) { +void grpc_call_stack_set_pollset_or_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_call_stack* call_stack, + grpc_polling_entity* pollent) { size_t count = call_stack->count; - grpc_call_element *call_elems; - char *user_data; + grpc_call_element* call_elems; + char* user_data; size_t i; call_elems = CALL_ELEMS_FROM_STACK(call_stack); - user_data = ((char *)call_elems) + + user_data = ((char*)call_elems) + ROUND_UP_TO_ALIGNMENT_SIZE(count * sizeof(grpc_call_element)); /* init per-filter data */ @@ -212,13 +211,13 @@ void grpc_call_stack_set_pollset_or_pollset_set(grpc_exec_ctx *exec_ctx, } void grpc_call_stack_ignore_set_pollset_or_pollset_set( - grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_polling_entity *pollent) {} + grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_polling_entity* pollent) {} -void grpc_call_stack_destroy(grpc_exec_ctx *exec_ctx, grpc_call_stack *stack, - const grpc_call_final_info *final_info, - grpc_closure *then_schedule_closure) { - grpc_call_element *elems = CALL_ELEMS_FROM_STACK(stack); +void grpc_call_stack_destroy(grpc_exec_ctx* exec_ctx, grpc_call_stack* stack, + const grpc_call_final_info* final_info, + grpc_closure* then_schedule_closure) { + grpc_call_element* elems = CALL_ELEMS_FROM_STACK(stack); size_t count = stack->count; size_t i; @@ -226,37 +225,37 @@ void grpc_call_stack_destroy(grpc_exec_ctx *exec_ctx, grpc_call_stack *stack, for (i = 0; i < count; i++) { elems[i].filter->destroy_call_elem( exec_ctx, &elems[i], final_info, - i == count - 1 ? then_schedule_closure : NULL); + i == count - 1 ? then_schedule_closure : nullptr); } } -void grpc_call_next_op(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_transport_stream_op_batch *op) { - grpc_call_element *next_elem = elem + 1; +void grpc_call_next_op(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_transport_stream_op_batch* op) { + grpc_call_element* next_elem = elem + 1; GRPC_CALL_LOG_OP(GPR_INFO, next_elem, op); next_elem->filter->start_transport_stream_op_batch(exec_ctx, next_elem, op); } -void grpc_channel_next_get_info(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - const grpc_channel_info *channel_info) { - grpc_channel_element *next_elem = elem + 1; +void grpc_channel_next_get_info(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + const grpc_channel_info* channel_info) { + grpc_channel_element* next_elem = elem + 1; next_elem->filter->get_channel_info(exec_ctx, next_elem, channel_info); } -void grpc_channel_next_op(grpc_exec_ctx *exec_ctx, grpc_channel_element *elem, - grpc_transport_op *op) { - grpc_channel_element *next_elem = elem + 1; +void grpc_channel_next_op(grpc_exec_ctx* exec_ctx, grpc_channel_element* elem, + grpc_transport_op* op) { + grpc_channel_element* next_elem = elem + 1; next_elem->filter->start_transport_op(exec_ctx, next_elem, op); } -grpc_channel_stack *grpc_channel_stack_from_top_element( - grpc_channel_element *elem) { - return (grpc_channel_stack *)((char *)(elem)-ROUND_UP_TO_ALIGNMENT_SIZE( +grpc_channel_stack* grpc_channel_stack_from_top_element( + grpc_channel_element* elem) { + return (grpc_channel_stack*)((char*)(elem)-ROUND_UP_TO_ALIGNMENT_SIZE( sizeof(grpc_channel_stack))); } -grpc_call_stack *grpc_call_stack_from_top_element(grpc_call_element *elem) { - return (grpc_call_stack *)((char *)(elem)-ROUND_UP_TO_ALIGNMENT_SIZE( +grpc_call_stack* grpc_call_stack_from_top_element(grpc_call_element* elem) { + return (grpc_call_stack*)((char*)(elem)-ROUND_UP_TO_ALIGNMENT_SIZE( sizeof(grpc_call_stack))); } diff --git a/src/core/lib/channel/channel_stack.h b/src/core/lib/channel/channel_stack.h index 5c00c098894..1b6e5396a56 100644 --- a/src/core/lib/channel/channel_stack.h +++ b/src/core/lib/channel/channel_stack.h @@ -45,10 +45,6 @@ #include "src/core/lib/support/arena.h" #include "src/core/lib/transport/transport.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_channel_element grpc_channel_element; typedef struct grpc_call_element grpc_call_element; @@ -56,23 +52,23 @@ typedef struct grpc_channel_stack grpc_channel_stack; typedef struct grpc_call_stack grpc_call_stack; typedef struct { - grpc_channel_stack *channel_stack; - const grpc_channel_args *channel_args; + grpc_channel_stack* channel_stack; + const grpc_channel_args* channel_args; /** Transport, iff it is known */ - grpc_transport *optional_transport; + grpc_transport* optional_transport; int is_first; int is_last; } grpc_channel_element_args; typedef struct { - grpc_call_stack *call_stack; - const void *server_transport_data; - grpc_call_context_element *context; + grpc_call_stack* call_stack; + const void* server_transport_data; + grpc_call_context_element* context; grpc_slice path; gpr_timespec start_time; grpc_millis deadline; - gpr_arena *arena; - grpc_call_combiner *call_combiner; + gpr_arena* arena; + grpc_call_combiner* call_combiner; } grpc_call_element_args; typedef struct { @@ -84,6 +80,7 @@ typedef struct { typedef struct { grpc_call_stats stats; grpc_status_code final_status; + const char** error_string; } grpc_call_final_info; /* Channel filters specify: @@ -99,14 +96,14 @@ typedef struct { typedef struct { /* Called to eg. send/receive data on a call. See grpc_call_next_op on how to call the next element in the stack */ - void (*start_transport_stream_op_batch)(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_transport_stream_op_batch *op); + void (*start_transport_stream_op_batch)(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_transport_stream_op_batch* op); /* Called to handle channel level operations - e.g. new calls, or transport closure. See grpc_channel_next_op on how to call the next element in the stack */ - void (*start_transport_op)(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, grpc_transport_op *op); + void (*start_transport_op)(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, grpc_transport_op* op); /* sizeof(per call data) */ size_t sizeof_call_data; @@ -119,21 +116,21 @@ typedef struct { transport and is on the server. Most filters want to ignore this argument. Implementations may assume that elem->call_data is all zeros. */ - grpc_error *(*init_call_elem)(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - const grpc_call_element_args *args); - void (*set_pollset_or_pollset_set)(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_polling_entity *pollent); + grpc_error* (*init_call_elem)(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + const grpc_call_element_args* args); + void (*set_pollset_or_pollset_set)(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_polling_entity* pollent); /* Destroy per call data. The filter does not need to do any chaining. The bottom filter of a stack will be passed a non-NULL pointer to \a then_schedule_closure that should be passed to GRPC_CLOSURE_SCHED when destruction is complete. \a final_info contains data about the completed call, mainly for reporting purposes. */ - void (*destroy_call_elem)(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - const grpc_call_final_info *final_info, - grpc_closure *then_schedule_closure); + void (*destroy_call_elem)(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + const grpc_call_final_info* final_info, + grpc_closure* then_schedule_closure); /* sizeof(per channel data) */ size_t sizeof_channel_data; @@ -144,36 +141,36 @@ typedef struct { useful for asserting correct configuration by upper layer code. The filter does not need to do any chaining. Implementations may assume that elem->call_data is all zeros. */ - grpc_error *(*init_channel_elem)(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_channel_element_args *args); + grpc_error* (*init_channel_elem)(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_channel_element_args* args); /* Destroy per channel data. The filter does not need to do any chaining */ - void (*destroy_channel_elem)(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem); + void (*destroy_channel_elem)(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem); /* Implement grpc_channel_get_info() */ - void (*get_channel_info)(grpc_exec_ctx *exec_ctx, grpc_channel_element *elem, - const grpc_channel_info *channel_info); + void (*get_channel_info)(grpc_exec_ctx* exec_ctx, grpc_channel_element* elem, + const grpc_channel_info* channel_info); /* The name of this filter */ - const char *name; + const char* name; } grpc_channel_filter; /* A channel_element tracks its filter and the filter requested memory within a channel allocation */ struct grpc_channel_element { - const grpc_channel_filter *filter; - void *channel_data; + const grpc_channel_filter* filter; + void* channel_data; }; /* A call_element tracks its filter, the filter requested memory within a channel allocation, and the filter requested memory within a call allocation */ struct grpc_call_element { - const grpc_channel_filter *filter; - void *channel_data; - void *call_data; + const grpc_channel_filter* filter; + void* channel_data; + void* call_data; }; /* A channel stack tracks a set of related filters for one channel, and @@ -198,40 +195,40 @@ struct grpc_call_stack { }; /* Get a channel element given a channel stack and its index */ -grpc_channel_element *grpc_channel_stack_element(grpc_channel_stack *stack, +grpc_channel_element* grpc_channel_stack_element(grpc_channel_stack* stack, size_t i); /* Get the last channel element in a channel stack */ -grpc_channel_element *grpc_channel_stack_last_element( - grpc_channel_stack *stack); +grpc_channel_element* grpc_channel_stack_last_element( + grpc_channel_stack* stack); /* Get a call stack element given a call stack and an index */ -grpc_call_element *grpc_call_stack_element(grpc_call_stack *stack, size_t i); +grpc_call_element* grpc_call_stack_element(grpc_call_stack* stack, size_t i); /* Determine memory required for a channel stack containing a set of filters */ -size_t grpc_channel_stack_size(const grpc_channel_filter **filters, +size_t grpc_channel_stack_size(const grpc_channel_filter** filters, size_t filter_count); /* Initialize a channel stack given some filters */ -grpc_error *grpc_channel_stack_init( - grpc_exec_ctx *exec_ctx, int initial_refs, grpc_iomgr_cb_func destroy, - void *destroy_arg, const grpc_channel_filter **filters, size_t filter_count, - const grpc_channel_args *args, grpc_transport *optional_transport, - const char *name, grpc_channel_stack *stack); +grpc_error* grpc_channel_stack_init( + grpc_exec_ctx* exec_ctx, int initial_refs, grpc_iomgr_cb_func destroy, + void* destroy_arg, const grpc_channel_filter** filters, size_t filter_count, + const grpc_channel_args* args, grpc_transport* optional_transport, + const char* name, grpc_channel_stack* stack); /* Destroy a channel stack */ -void grpc_channel_stack_destroy(grpc_exec_ctx *exec_ctx, - grpc_channel_stack *stack); +void grpc_channel_stack_destroy(grpc_exec_ctx* exec_ctx, + grpc_channel_stack* stack); /* Initialize a call stack given a channel stack. transport_server_data is expected to be NULL on a client, or an opaque transport owned pointer on the server. */ -grpc_error *grpc_call_stack_init(grpc_exec_ctx *exec_ctx, - grpc_channel_stack *channel_stack, +grpc_error* grpc_call_stack_init(grpc_exec_ctx* exec_ctx, + grpc_channel_stack* channel_stack, int initial_refs, grpc_iomgr_cb_func destroy, - void *destroy_arg, - const grpc_call_element_args *elem_args); + void* destroy_arg, + const grpc_call_element_args* elem_args); /* Set a pollset or a pollset_set for a call stack: must occur before the first * op is started */ -void grpc_call_stack_set_pollset_or_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_call_stack *call_stack, - grpc_polling_entity *pollent); +void grpc_call_stack_set_pollset_or_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_call_stack* call_stack, + grpc_polling_entity* pollent); #ifndef NDEBUG #define GRPC_CALL_STACK_REF(call_stack, reason) \ @@ -254,44 +251,40 @@ void grpc_call_stack_set_pollset_or_pollset_set(grpc_exec_ctx *exec_ctx, #endif /* Destroy a call stack */ -void grpc_call_stack_destroy(grpc_exec_ctx *exec_ctx, grpc_call_stack *stack, - const grpc_call_final_info *final_info, - grpc_closure *then_schedule_closure); +void grpc_call_stack_destroy(grpc_exec_ctx* exec_ctx, grpc_call_stack* stack, + const grpc_call_final_info* final_info, + grpc_closure* then_schedule_closure); /* Ignore set pollset{_set} - used by filters if they don't care about pollsets * at all. Does nothing. */ void grpc_call_stack_ignore_set_pollset_or_pollset_set( - grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_polling_entity *pollent); + grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_polling_entity* pollent); /* Call the next operation in a call stack */ -void grpc_call_next_op(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_transport_stream_op_batch *op); +void grpc_call_next_op(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_transport_stream_op_batch* op); /* Call the next operation (depending on call directionality) in a channel stack */ -void grpc_channel_next_op(grpc_exec_ctx *exec_ctx, grpc_channel_element *elem, - grpc_transport_op *op); +void grpc_channel_next_op(grpc_exec_ctx* exec_ctx, grpc_channel_element* elem, + grpc_transport_op* op); /* Pass through a request to get_channel_info() to the next child element */ -void grpc_channel_next_get_info(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - const grpc_channel_info *channel_info); +void grpc_channel_next_get_info(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + const grpc_channel_info* channel_info); /* Given the top element of a channel stack, get the channel stack itself */ -grpc_channel_stack *grpc_channel_stack_from_top_element( - grpc_channel_element *elem); +grpc_channel_stack* grpc_channel_stack_from_top_element( + grpc_channel_element* elem); /* Given the top element of a call stack, get the call stack itself */ -grpc_call_stack *grpc_call_stack_from_top_element(grpc_call_element *elem); +grpc_call_stack* grpc_call_stack_from_top_element(grpc_call_element* elem); -void grpc_call_log_op(const char *file, int line, gpr_log_severity severity, - grpc_call_element *elem, - grpc_transport_stream_op_batch *op); +void grpc_call_log_op(const char* file, int line, gpr_log_severity severity, + grpc_call_element* elem, + grpc_transport_stream_op_batch* op); -extern grpc_tracer_flag grpc_trace_channel; +extern grpc_core::TraceFlag grpc_trace_channel; #define GRPC_CALL_LOG_OP(sev, elem, op) \ - if (GRPC_TRACER_ON(grpc_trace_channel)) grpc_call_log_op(sev, elem, op) - -#ifdef __cplusplus -} -#endif + if (grpc_trace_channel.enabled()) grpc_call_log_op(sev, elem, op) #endif /* GRPC_CORE_LIB_CHANNEL_CHANNEL_STACK_H */ diff --git a/src/core/lib/channel/channel_stack_builder.cc b/src/core/lib/channel/channel_stack_builder.cc index b663ebfb522..77b7854f94d 100644 --- a/src/core/lib/channel/channel_stack_builder.cc +++ b/src/core/lib/channel/channel_stack_builder.cc @@ -23,15 +23,15 @@ #include #include -grpc_tracer_flag grpc_trace_channel_stack_builder = - GRPC_TRACER_INITIALIZER(false, "channel_stack_builder"); +grpc_core::TraceFlag grpc_trace_channel_stack_builder(false, + "channel_stack_builder"); typedef struct filter_node { - struct filter_node *next; - struct filter_node *prev; - const grpc_channel_filter *filter; + struct filter_node* next; + struct filter_node* prev; + const grpc_channel_filter* filter; grpc_post_filter_create_init_func init; - void *init_arg; + void* init_arg; } filter_node; struct grpc_channel_stack_builder { @@ -39,23 +39,23 @@ struct grpc_channel_stack_builder { filter_node begin; filter_node end; // various set/get-able parameters - grpc_channel_args *args; - grpc_transport *transport; - char *target; - const char *name; + grpc_channel_args* args; + grpc_transport* transport; + char* target; + const char* name; }; struct grpc_channel_stack_builder_iterator { - grpc_channel_stack_builder *builder; - filter_node *node; + grpc_channel_stack_builder* builder; + filter_node* node; }; -grpc_channel_stack_builder *grpc_channel_stack_builder_create(void) { - grpc_channel_stack_builder *b = - (grpc_channel_stack_builder *)gpr_zalloc(sizeof(*b)); +grpc_channel_stack_builder* grpc_channel_stack_builder_create(void) { + grpc_channel_stack_builder* b = + (grpc_channel_stack_builder*)gpr_zalloc(sizeof(*b)); - b->begin.filter = NULL; - b->end.filter = NULL; + b->begin.filter = nullptr; + b->end.filter = nullptr; b->begin.next = &b->end; b->begin.prev = &b->end; b->end.next = &b->begin; @@ -64,76 +64,76 @@ grpc_channel_stack_builder *grpc_channel_stack_builder_create(void) { return b; } -void grpc_channel_stack_builder_set_target(grpc_channel_stack_builder *b, - const char *target) { +void grpc_channel_stack_builder_set_target(grpc_channel_stack_builder* b, + const char* target) { gpr_free(b->target); b->target = gpr_strdup(target); } -const char *grpc_channel_stack_builder_get_target( - grpc_channel_stack_builder *b) { +const char* grpc_channel_stack_builder_get_target( + grpc_channel_stack_builder* b) { return b->target; } -static grpc_channel_stack_builder_iterator *create_iterator_at_filter_node( - grpc_channel_stack_builder *builder, filter_node *node) { - grpc_channel_stack_builder_iterator *it = - (grpc_channel_stack_builder_iterator *)gpr_malloc(sizeof(*it)); +static grpc_channel_stack_builder_iterator* create_iterator_at_filter_node( + grpc_channel_stack_builder* builder, filter_node* node) { + grpc_channel_stack_builder_iterator* it = + (grpc_channel_stack_builder_iterator*)gpr_malloc(sizeof(*it)); it->builder = builder; it->node = node; return it; } void grpc_channel_stack_builder_iterator_destroy( - grpc_channel_stack_builder_iterator *it) { + grpc_channel_stack_builder_iterator* it) { gpr_free(it); } -grpc_channel_stack_builder_iterator * +grpc_channel_stack_builder_iterator* grpc_channel_stack_builder_create_iterator_at_first( - grpc_channel_stack_builder *builder) { + grpc_channel_stack_builder* builder) { return create_iterator_at_filter_node(builder, &builder->begin); } -grpc_channel_stack_builder_iterator * +grpc_channel_stack_builder_iterator* grpc_channel_stack_builder_create_iterator_at_last( - grpc_channel_stack_builder *builder) { + grpc_channel_stack_builder* builder) { return create_iterator_at_filter_node(builder, &builder->end); } bool grpc_channel_stack_builder_iterator_is_end( - grpc_channel_stack_builder_iterator *iterator) { + grpc_channel_stack_builder_iterator* iterator) { return iterator->node == &iterator->builder->end; } -const char *grpc_channel_stack_builder_iterator_filter_name( - grpc_channel_stack_builder_iterator *iterator) { - if (iterator->node->filter == NULL) return NULL; +const char* grpc_channel_stack_builder_iterator_filter_name( + grpc_channel_stack_builder_iterator* iterator) { + if (iterator->node->filter == nullptr) return nullptr; return iterator->node->filter->name; } bool grpc_channel_stack_builder_move_next( - grpc_channel_stack_builder_iterator *iterator) { + grpc_channel_stack_builder_iterator* iterator) { if (iterator->node == &iterator->builder->end) return false; iterator->node = iterator->node->next; return true; } bool grpc_channel_stack_builder_move_prev( - grpc_channel_stack_builder_iterator *iterator) { + grpc_channel_stack_builder_iterator* iterator) { if (iterator->node == &iterator->builder->begin) return false; iterator->node = iterator->node->prev; return true; } -grpc_channel_stack_builder_iterator *grpc_channel_stack_builder_iterator_find( - grpc_channel_stack_builder *builder, const char *filter_name) { - GPR_ASSERT(filter_name != NULL); - grpc_channel_stack_builder_iterator *it = +grpc_channel_stack_builder_iterator* grpc_channel_stack_builder_iterator_find( + grpc_channel_stack_builder* builder, const char* filter_name) { + GPR_ASSERT(filter_name != nullptr); + grpc_channel_stack_builder_iterator* it = grpc_channel_stack_builder_create_iterator_at_first(builder); while (grpc_channel_stack_builder_move_next(it)) { if (grpc_channel_stack_builder_iterator_is_end(it)) break; - const char *filter_name_at_it = + const char* filter_name_at_it = grpc_channel_stack_builder_iterator_filter_name(it); if (strcmp(filter_name, filter_name_at_it) == 0) break; } @@ -141,43 +141,43 @@ grpc_channel_stack_builder_iterator *grpc_channel_stack_builder_iterator_find( } bool grpc_channel_stack_builder_move_prev( - grpc_channel_stack_builder_iterator *iterator); + grpc_channel_stack_builder_iterator* iterator); -void grpc_channel_stack_builder_set_name(grpc_channel_stack_builder *builder, - const char *name) { - GPR_ASSERT(builder->name == NULL); +void grpc_channel_stack_builder_set_name(grpc_channel_stack_builder* builder, + const char* name) { + GPR_ASSERT(builder->name == nullptr); builder->name = name; } void grpc_channel_stack_builder_set_channel_arguments( - grpc_exec_ctx *exec_ctx, grpc_channel_stack_builder *builder, - const grpc_channel_args *args) { - if (builder->args != NULL) { + grpc_exec_ctx* exec_ctx, grpc_channel_stack_builder* builder, + const grpc_channel_args* args) { + if (builder->args != nullptr) { grpc_channel_args_destroy(exec_ctx, builder->args); } builder->args = grpc_channel_args_copy(args); } void grpc_channel_stack_builder_set_transport( - grpc_channel_stack_builder *builder, grpc_transport *transport) { - GPR_ASSERT(builder->transport == NULL); + grpc_channel_stack_builder* builder, grpc_transport* transport) { + GPR_ASSERT(builder->transport == nullptr); builder->transport = transport; } -grpc_transport *grpc_channel_stack_builder_get_transport( - grpc_channel_stack_builder *builder) { +grpc_transport* grpc_channel_stack_builder_get_transport( + grpc_channel_stack_builder* builder) { return builder->transport; } -const grpc_channel_args *grpc_channel_stack_builder_get_channel_arguments( - grpc_channel_stack_builder *builder) { +const grpc_channel_args* grpc_channel_stack_builder_get_channel_arguments( + grpc_channel_stack_builder* builder) { return builder->args; } bool grpc_channel_stack_builder_append_filter( - grpc_channel_stack_builder *builder, const grpc_channel_filter *filter, - grpc_post_filter_create_init_func post_init_func, void *user_data) { - grpc_channel_stack_builder_iterator *it = + grpc_channel_stack_builder* builder, const grpc_channel_filter* filter, + grpc_post_filter_create_init_func post_init_func, void* user_data) { + grpc_channel_stack_builder_iterator* it = grpc_channel_stack_builder_create_iterator_at_last(builder); bool ok = grpc_channel_stack_builder_add_filter_before( it, filter, post_init_func, user_data); @@ -186,8 +186,8 @@ bool grpc_channel_stack_builder_append_filter( } bool grpc_channel_stack_builder_remove_filter( - grpc_channel_stack_builder *builder, const char *filter_name) { - grpc_channel_stack_builder_iterator *it = + grpc_channel_stack_builder* builder, const char* filter_name) { + grpc_channel_stack_builder_iterator* it = grpc_channel_stack_builder_iterator_find(builder, filter_name); if (grpc_channel_stack_builder_iterator_is_end(it)) { grpc_channel_stack_builder_iterator_destroy(it); @@ -201,9 +201,9 @@ bool grpc_channel_stack_builder_remove_filter( } bool grpc_channel_stack_builder_prepend_filter( - grpc_channel_stack_builder *builder, const grpc_channel_filter *filter, - grpc_post_filter_create_init_func post_init_func, void *user_data) { - grpc_channel_stack_builder_iterator *it = + grpc_channel_stack_builder* builder, const grpc_channel_filter* filter, + grpc_post_filter_create_init_func post_init_func, void* user_data) { + grpc_channel_stack_builder_iterator* it = grpc_channel_stack_builder_create_iterator_at_first(builder); bool ok = grpc_channel_stack_builder_add_filter_after( it, filter, post_init_func, user_data); @@ -211,10 +211,10 @@ bool grpc_channel_stack_builder_prepend_filter( return ok; } -static void add_after(filter_node *before, const grpc_channel_filter *filter, +static void add_after(filter_node* before, const grpc_channel_filter* filter, grpc_post_filter_create_init_func post_init_func, - void *user_data) { - filter_node *new_node = (filter_node *)gpr_malloc(sizeof(*new_node)); + void* user_data) { + filter_node* new_node = (filter_node*)gpr_malloc(sizeof(*new_node)); new_node->next = before->next; new_node->prev = before; new_node->next->prev = new_node->prev->next = new_node; @@ -224,53 +224,53 @@ static void add_after(filter_node *before, const grpc_channel_filter *filter, } bool grpc_channel_stack_builder_add_filter_before( - grpc_channel_stack_builder_iterator *iterator, - const grpc_channel_filter *filter, - grpc_post_filter_create_init_func post_init_func, void *user_data) { + grpc_channel_stack_builder_iterator* iterator, + const grpc_channel_filter* filter, + grpc_post_filter_create_init_func post_init_func, void* user_data) { if (iterator->node == &iterator->builder->begin) return false; add_after(iterator->node->prev, filter, post_init_func, user_data); return true; } bool grpc_channel_stack_builder_add_filter_after( - grpc_channel_stack_builder_iterator *iterator, - const grpc_channel_filter *filter, - grpc_post_filter_create_init_func post_init_func, void *user_data) { + grpc_channel_stack_builder_iterator* iterator, + const grpc_channel_filter* filter, + grpc_post_filter_create_init_func post_init_func, void* user_data) { if (iterator->node == &iterator->builder->end) return false; add_after(iterator->node, filter, post_init_func, user_data); return true; } -void grpc_channel_stack_builder_destroy(grpc_exec_ctx *exec_ctx, - grpc_channel_stack_builder *builder) { - filter_node *p = builder->begin.next; +void grpc_channel_stack_builder_destroy(grpc_exec_ctx* exec_ctx, + grpc_channel_stack_builder* builder) { + filter_node* p = builder->begin.next; while (p != &builder->end) { - filter_node *next = p->next; + filter_node* next = p->next; gpr_free(p); p = next; } - if (builder->args != NULL) { + if (builder->args != nullptr) { grpc_channel_args_destroy(exec_ctx, builder->args); } gpr_free(builder->target); gpr_free(builder); } -grpc_error *grpc_channel_stack_builder_finish( - grpc_exec_ctx *exec_ctx, grpc_channel_stack_builder *builder, +grpc_error* grpc_channel_stack_builder_finish( + grpc_exec_ctx* exec_ctx, grpc_channel_stack_builder* builder, size_t prefix_bytes, int initial_refs, grpc_iomgr_cb_func destroy, - void *destroy_arg, void **result) { + void* destroy_arg, void** result) { // count the number of filters size_t num_filters = 0; - for (filter_node *p = builder->begin.next; p != &builder->end; p = p->next) { + for (filter_node* p = builder->begin.next; p != &builder->end; p = p->next) { num_filters++; } // create an array of filters - const grpc_channel_filter **filters = - (const grpc_channel_filter **)gpr_malloc(sizeof(*filters) * num_filters); + const grpc_channel_filter** filters = + (const grpc_channel_filter**)gpr_malloc(sizeof(*filters) * num_filters); size_t i = 0; - for (filter_node *p = builder->begin.next; p != &builder->end; p = p->next) { + for (filter_node* p = builder->begin.next; p != &builder->end; p = p->next) { filters[i++] = p->filter; } @@ -280,24 +280,24 @@ grpc_error *grpc_channel_stack_builder_finish( // allocate memory, with prefix_bytes followed by channel_stack_size *result = gpr_zalloc(prefix_bytes + channel_stack_size); // fetch a pointer to the channel stack - grpc_channel_stack *channel_stack = - (grpc_channel_stack *)((char *)(*result) + prefix_bytes); + grpc_channel_stack* channel_stack = + (grpc_channel_stack*)((char*)(*result) + prefix_bytes); // and initialize it - grpc_error *error = grpc_channel_stack_init( + grpc_error* error = grpc_channel_stack_init( exec_ctx, initial_refs, destroy, - destroy_arg == NULL ? *result : destroy_arg, filters, num_filters, + destroy_arg == nullptr ? *result : destroy_arg, filters, num_filters, builder->args, builder->transport, builder->name, channel_stack); if (error != GRPC_ERROR_NONE) { grpc_channel_stack_destroy(exec_ctx, channel_stack); gpr_free(*result); - *result = NULL; + *result = nullptr; } else { // run post-initialization functions i = 0; - for (filter_node *p = builder->begin.next; p != &builder->end; + for (filter_node* p = builder->begin.next; p != &builder->end; p = p->next) { - if (p->init != NULL) { + if (p->init != nullptr) { p->init(channel_stack, grpc_channel_stack_element(channel_stack, i), p->init_arg); } @@ -306,7 +306,7 @@ grpc_error *grpc_channel_stack_builder_finish( } grpc_channel_stack_builder_destroy(exec_ctx, builder); - gpr_free((grpc_channel_filter **)filters); + gpr_free((grpc_channel_filter**)filters); return error; } diff --git a/src/core/lib/channel/channel_stack_builder.h b/src/core/lib/channel/channel_stack_builder.h index fdff2a2b6db..10019542b18 100644 --- a/src/core/lib/channel/channel_stack_builder.h +++ b/src/core/lib/channel/channel_stack_builder.h @@ -24,10 +24,6 @@ #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_stack.h" -#ifdef __cplusplus -extern "C" { -#endif - /// grpc_channel_stack_builder offers a programmatic interface to selected /// and order channel filters typedef struct grpc_channel_stack_builder grpc_channel_stack_builder; @@ -35,135 +31,131 @@ typedef struct grpc_channel_stack_builder_iterator grpc_channel_stack_builder_iterator; /// Create a new channel stack builder -grpc_channel_stack_builder *grpc_channel_stack_builder_create(void); +grpc_channel_stack_builder* grpc_channel_stack_builder_create(void); /// Assign a name to the channel stack: \a name must be statically allocated -void grpc_channel_stack_builder_set_name(grpc_channel_stack_builder *builder, - const char *name); +void grpc_channel_stack_builder_set_name(grpc_channel_stack_builder* builder, + const char* name); /// Set the target uri -void grpc_channel_stack_builder_set_target(grpc_channel_stack_builder *b, - const char *target); +void grpc_channel_stack_builder_set_target(grpc_channel_stack_builder* b, + const char* target); -const char *grpc_channel_stack_builder_get_target( - grpc_channel_stack_builder *b); +const char* grpc_channel_stack_builder_get_target( + grpc_channel_stack_builder* b); /// Attach \a transport to the builder (does not take ownership) void grpc_channel_stack_builder_set_transport( - grpc_channel_stack_builder *builder, grpc_transport *transport); + grpc_channel_stack_builder* builder, grpc_transport* transport); /// Fetch attached transport -grpc_transport *grpc_channel_stack_builder_get_transport( - grpc_channel_stack_builder *builder); +grpc_transport* grpc_channel_stack_builder_get_transport( + grpc_channel_stack_builder* builder); /// Set channel arguments: copies args void grpc_channel_stack_builder_set_channel_arguments( - grpc_exec_ctx *exec_ctx, grpc_channel_stack_builder *builder, - const grpc_channel_args *args); + grpc_exec_ctx* exec_ctx, grpc_channel_stack_builder* builder, + const grpc_channel_args* args); /// Return a borrowed pointer to the channel arguments -const grpc_channel_args *grpc_channel_stack_builder_get_channel_arguments( - grpc_channel_stack_builder *builder); +const grpc_channel_args* grpc_channel_stack_builder_get_channel_arguments( + grpc_channel_stack_builder* builder); /// Begin iterating over already defined filters in the builder at the beginning -grpc_channel_stack_builder_iterator * +grpc_channel_stack_builder_iterator* grpc_channel_stack_builder_create_iterator_at_first( - grpc_channel_stack_builder *builder); + grpc_channel_stack_builder* builder); /// Begin iterating over already defined filters in the builder at the end -grpc_channel_stack_builder_iterator * +grpc_channel_stack_builder_iterator* grpc_channel_stack_builder_create_iterator_at_last( - grpc_channel_stack_builder *builder); + grpc_channel_stack_builder* builder); /// Is an iterator at the first element? bool grpc_channel_stack_builder_iterator_is_first( - grpc_channel_stack_builder_iterator *iterator); + grpc_channel_stack_builder_iterator* iterator); /// Is an iterator at the end? bool grpc_channel_stack_builder_iterator_is_end( - grpc_channel_stack_builder_iterator *iterator); + grpc_channel_stack_builder_iterator* iterator); /// What is the name of the filter at this iterator position? -const char *grpc_channel_stack_builder_iterator_filter_name( - grpc_channel_stack_builder_iterator *iterator); +const char* grpc_channel_stack_builder_iterator_filter_name( + grpc_channel_stack_builder_iterator* iterator); /// Move an iterator to the next item bool grpc_channel_stack_builder_move_next( - grpc_channel_stack_builder_iterator *iterator); + grpc_channel_stack_builder_iterator* iterator); /// Move an iterator to the previous item bool grpc_channel_stack_builder_move_prev( - grpc_channel_stack_builder_iterator *iterator); + grpc_channel_stack_builder_iterator* iterator); /// Return an iterator at \a filter_name, or at the end of the list if not /// found. -grpc_channel_stack_builder_iterator *grpc_channel_stack_builder_iterator_find( - grpc_channel_stack_builder *builder, const char *filter_name); +grpc_channel_stack_builder_iterator* grpc_channel_stack_builder_iterator_find( + grpc_channel_stack_builder* builder, const char* filter_name); typedef void (*grpc_post_filter_create_init_func)( - grpc_channel_stack *channel_stack, grpc_channel_element *elem, void *arg); + grpc_channel_stack* channel_stack, grpc_channel_element* elem, void* arg); /// Add \a filter to the stack, after \a iterator. /// Call \a post_init_func(..., \a user_data) once the channel stack is /// created. bool grpc_channel_stack_builder_add_filter_after( - grpc_channel_stack_builder_iterator *iterator, - const grpc_channel_filter *filter, + grpc_channel_stack_builder_iterator* iterator, + const grpc_channel_filter* filter, grpc_post_filter_create_init_func post_init_func, - void *user_data) GRPC_MUST_USE_RESULT; + void* user_data) GRPC_MUST_USE_RESULT; /// Add \a filter to the stack, before \a iterator. /// Call \a post_init_func(..., \a user_data) once the channel stack is /// created. bool grpc_channel_stack_builder_add_filter_before( - grpc_channel_stack_builder_iterator *iterator, - const grpc_channel_filter *filter, + grpc_channel_stack_builder_iterator* iterator, + const grpc_channel_filter* filter, grpc_post_filter_create_init_func post_init_func, - void *user_data) GRPC_MUST_USE_RESULT; + void* user_data) GRPC_MUST_USE_RESULT; /// Add \a filter to the beginning of the filter list. /// Call \a post_init_func(..., \a user_data) once the channel stack is /// created. bool grpc_channel_stack_builder_prepend_filter( - grpc_channel_stack_builder *builder, const grpc_channel_filter *filter, + grpc_channel_stack_builder* builder, const grpc_channel_filter* filter, grpc_post_filter_create_init_func post_init_func, - void *user_data) GRPC_MUST_USE_RESULT; + void* user_data) GRPC_MUST_USE_RESULT; /// Add \a filter to the end of the filter list. /// Call \a post_init_func(..., \a user_data) once the channel stack is /// created. bool grpc_channel_stack_builder_append_filter( - grpc_channel_stack_builder *builder, const grpc_channel_filter *filter, + grpc_channel_stack_builder* builder, const grpc_channel_filter* filter, grpc_post_filter_create_init_func post_init_func, - void *user_data) GRPC_MUST_USE_RESULT; + void* user_data) GRPC_MUST_USE_RESULT; /// Remove any filter whose name is \a filter_name from \a builder. Returns true /// if \a filter_name was not found. bool grpc_channel_stack_builder_remove_filter( - grpc_channel_stack_builder *builder, const char *filter_name); + grpc_channel_stack_builder* builder, const char* filter_name); /// Terminate iteration and destroy \a iterator void grpc_channel_stack_builder_iterator_destroy( - grpc_channel_stack_builder_iterator *iterator); + grpc_channel_stack_builder_iterator* iterator); /// Destroy the builder, return the freshly minted channel stack in \a result. /// Allocates \a prefix_bytes bytes before the channel stack /// Returns the base pointer of the allocated block /// \a initial_refs, \a destroy, \a destroy_arg are as per /// grpc_channel_stack_init -grpc_error *grpc_channel_stack_builder_finish( - grpc_exec_ctx *exec_ctx, grpc_channel_stack_builder *builder, +grpc_error* grpc_channel_stack_builder_finish( + grpc_exec_ctx* exec_ctx, grpc_channel_stack_builder* builder, size_t prefix_bytes, int initial_refs, grpc_iomgr_cb_func destroy, - void *destroy_arg, void **result); + void* destroy_arg, void** result); /// Destroy the builder without creating a channel stack -void grpc_channel_stack_builder_destroy(grpc_exec_ctx *exec_ctx, - grpc_channel_stack_builder *builder); - -extern grpc_tracer_flag grpc_trace_channel_stack_builder; +void grpc_channel_stack_builder_destroy(grpc_exec_ctx* exec_ctx, + grpc_channel_stack_builder* builder); -#ifdef __cplusplus -} -#endif +extern grpc_core::TraceFlag grpc_trace_channel_stack_builder; #endif /* GRPC_CORE_LIB_CHANNEL_CHANNEL_STACK_BUILDER_H */ diff --git a/src/core/lib/channel/connected_channel.cc b/src/core/lib/channel/connected_channel.cc index 4f37908958d..af2f88ab2e4 100644 --- a/src/core/lib/channel/connected_channel.cc +++ b/src/core/lib/channel/connected_channel.cc @@ -33,41 +33,41 @@ #define MAX_BUFFER_LENGTH 8192 typedef struct connected_channel_channel_data { - grpc_transport *transport; + grpc_transport* transport; } channel_data; typedef struct { grpc_closure closure; - grpc_closure *original_closure; - grpc_call_combiner *call_combiner; - const char *reason; + grpc_closure* original_closure; + grpc_call_combiner* call_combiner; + const char* reason; } callback_state; typedef struct connected_channel_call_data { - grpc_call_combiner *call_combiner; + grpc_call_combiner* call_combiner; // Closures used for returning results on the call combiner. callback_state on_complete[6]; // Max number of pending batches. callback_state recv_initial_metadata_ready; callback_state recv_message_ready; } call_data; -static void run_in_call_combiner(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - callback_state *state = (callback_state *)arg; +static void run_in_call_combiner(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + callback_state* state = (callback_state*)arg; GRPC_CALL_COMBINER_START(exec_ctx, state->call_combiner, state->original_closure, GRPC_ERROR_REF(error), state->reason); } -static void run_cancel_in_call_combiner(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { +static void run_cancel_in_call_combiner(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { run_in_call_combiner(exec_ctx, arg, error); gpr_free(arg); } -static void intercept_callback(call_data *calld, callback_state *state, - bool free_when_done, const char *reason, - grpc_closure **original_closure) { +static void intercept_callback(call_data* calld, callback_state* state, + bool free_when_done, const char* reason, + grpc_closure** original_closure) { state->original_closure = *original_closure; state->call_combiner = calld->call_combiner; state->reason = reason; @@ -77,39 +77,39 @@ static void intercept_callback(call_data *calld, callback_state *state, state, grpc_schedule_on_exec_ctx); } -static callback_state *get_state_for_batch( - call_data *calld, grpc_transport_stream_op_batch *batch) { +static callback_state* get_state_for_batch( + call_data* calld, grpc_transport_stream_op_batch* batch) { if (batch->send_initial_metadata) return &calld->on_complete[0]; if (batch->send_message) return &calld->on_complete[1]; if (batch->send_trailing_metadata) return &calld->on_complete[2]; if (batch->recv_initial_metadata) return &calld->on_complete[3]; if (batch->recv_message) return &calld->on_complete[4]; if (batch->recv_trailing_metadata) return &calld->on_complete[5]; - GPR_UNREACHABLE_CODE(return NULL); + GPR_UNREACHABLE_CODE(return nullptr); } /* We perform a small hack to locate transport data alongside the connected channel data in call allocations, to allow everything to be pulled in minimal cache line requests */ -#define TRANSPORT_STREAM_FROM_CALL_DATA(calld) ((grpc_stream *)((calld) + 1)) +#define TRANSPORT_STREAM_FROM_CALL_DATA(calld) ((grpc_stream*)((calld) + 1)) #define CALL_DATA_FROM_TRANSPORT_STREAM(transport_stream) \ - (((call_data *)(transport_stream)) - 1) + (((call_data*)(transport_stream)) - 1) /* Intercept a call operation and either push it directly up or translate it into transport stream operations */ static void con_start_transport_stream_op_batch( - grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_transport_stream_op_batch *batch) { - call_data *calld = (call_data *)elem->call_data; - channel_data *chand = (channel_data *)elem->channel_data; + grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_transport_stream_op_batch* batch) { + call_data* calld = (call_data*)elem->call_data; + channel_data* chand = (channel_data*)elem->channel_data; if (batch->recv_initial_metadata) { - callback_state *state = &calld->recv_initial_metadata_ready; + callback_state* state = &calld->recv_initial_metadata_ready; intercept_callback( calld, state, false, "recv_initial_metadata_ready", &batch->payload->recv_initial_metadata.recv_initial_metadata_ready); } if (batch->recv_message) { - callback_state *state = &calld->recv_message_ready; + callback_state* state = &calld->recv_message_ready; intercept_callback(calld, state, false, "recv_message_ready", &batch->payload->recv_message.recv_message_ready); } @@ -119,11 +119,11 @@ static void con_start_transport_stream_op_batch( // calld->on_complete like we can for the other ops. However, // cancellation isn't in the fast path, so we just allocate a new // closure for each one. - callback_state *state = (callback_state *)gpr_malloc(sizeof(*state)); + callback_state* state = (callback_state*)gpr_malloc(sizeof(*state)); intercept_callback(calld, state, true, "on_complete (cancel_stream)", &batch->on_complete); } else { - callback_state *state = get_state_for_batch(calld, batch); + callback_state* state = get_state_for_batch(calld, batch); intercept_callback(calld, state, false, "on_complete", &batch->on_complete); } grpc_transport_perform_stream_op(exec_ctx, chand->transport, @@ -133,19 +133,19 @@ static void con_start_transport_stream_op_batch( "passed batch to transport"); } -static void con_start_transport_op(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_transport_op *op) { - channel_data *chand = (channel_data *)elem->channel_data; +static void con_start_transport_op(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_transport_op* op) { + channel_data* chand = (channel_data*)elem->channel_data; grpc_transport_perform_op(exec_ctx, chand->transport, op); } /* Constructor for call_data */ -static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - const grpc_call_element_args *args) { - call_data *calld = (call_data *)elem->call_data; - channel_data *chand = (channel_data *)elem->channel_data; +static grpc_error* init_call_elem(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + const grpc_call_element_args* args) { + call_data* calld = (call_data*)elem->call_data; + channel_data* chand = (channel_data*)elem->channel_data; calld->call_combiner = args->call_combiner; int r = grpc_transport_init_stream( exec_ctx, chand->transport, TRANSPORT_STREAM_FROM_CALL_DATA(calld), @@ -155,49 +155,49 @@ static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, "transport stream initialization failed"); } -static void set_pollset_or_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_polling_entity *pollent) { - call_data *calld = (call_data *)elem->call_data; - channel_data *chand = (channel_data *)elem->channel_data; +static void set_pollset_or_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_polling_entity* pollent) { + call_data* calld = (call_data*)elem->call_data; + channel_data* chand = (channel_data*)elem->channel_data; grpc_transport_set_pops(exec_ctx, chand->transport, TRANSPORT_STREAM_FROM_CALL_DATA(calld), pollent); } /* Destructor for call_data */ -static void destroy_call_elem(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - const grpc_call_final_info *final_info, - grpc_closure *then_schedule_closure) { - call_data *calld = (call_data *)elem->call_data; - channel_data *chand = (channel_data *)elem->channel_data; +static void destroy_call_elem(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + const grpc_call_final_info* final_info, + grpc_closure* then_schedule_closure) { + call_data* calld = (call_data*)elem->call_data; + channel_data* chand = (channel_data*)elem->channel_data; grpc_transport_destroy_stream(exec_ctx, chand->transport, TRANSPORT_STREAM_FROM_CALL_DATA(calld), then_schedule_closure); } /* Constructor for channel_data */ -static grpc_error *init_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_channel_element_args *args) { - channel_data *cd = (channel_data *)elem->channel_data; +static grpc_error* init_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_channel_element_args* args) { + channel_data* cd = (channel_data*)elem->channel_data; GPR_ASSERT(args->is_last); - cd->transport = NULL; + cd->transport = nullptr; return GRPC_ERROR_NONE; } /* Destructor for channel_data */ -static void destroy_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem) { - channel_data *cd = (channel_data *)elem->channel_data; +static void destroy_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem) { + channel_data* cd = (channel_data*)elem->channel_data; if (cd->transport) { grpc_transport_destroy(exec_ctx, cd->transport); } } /* No-op. */ -static void con_get_channel_info(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - const grpc_channel_info *channel_info) {} +static void con_get_channel_info(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + const grpc_channel_info* channel_info) {} const grpc_channel_filter grpc_connected_filter = { con_start_transport_stream_op_batch, @@ -213,12 +213,12 @@ const grpc_channel_filter grpc_connected_filter = { "connected", }; -static void bind_transport(grpc_channel_stack *channel_stack, - grpc_channel_element *elem, void *t) { - channel_data *cd = (channel_data *)elem->channel_data; +static void bind_transport(grpc_channel_stack* channel_stack, + grpc_channel_element* elem, void* t) { + channel_data* cd = (channel_data*)elem->channel_data; GPR_ASSERT(elem->filter == &grpc_connected_filter); - GPR_ASSERT(cd->transport == NULL); - cd->transport = (grpc_transport *)t; + GPR_ASSERT(cd->transport == nullptr); + cd->transport = (grpc_transport*)t; /* HACK(ctiller): increase call stack size for the channel to make space for channel data. We need a cleaner (but performant) way to do this, @@ -227,20 +227,20 @@ static void bind_transport(grpc_channel_stack *channel_stack, the last call element, and the last call element MUST be the connected channel. */ channel_stack->call_stack_size += - grpc_transport_stream_size((grpc_transport *)t); + grpc_transport_stream_size((grpc_transport*)t); } -bool grpc_add_connected_filter(grpc_exec_ctx *exec_ctx, - grpc_channel_stack_builder *builder, - void *arg_must_be_null) { - GPR_ASSERT(arg_must_be_null == NULL); - grpc_transport *t = grpc_channel_stack_builder_get_transport(builder); - GPR_ASSERT(t != NULL); +bool grpc_add_connected_filter(grpc_exec_ctx* exec_ctx, + grpc_channel_stack_builder* builder, + void* arg_must_be_null) { + GPR_ASSERT(arg_must_be_null == nullptr); + grpc_transport* t = grpc_channel_stack_builder_get_transport(builder); + GPR_ASSERT(t != nullptr); return grpc_channel_stack_builder_append_filter( builder, &grpc_connected_filter, bind_transport, t); } -grpc_stream *grpc_connected_channel_get_stream(grpc_call_element *elem) { - call_data *calld = (call_data *)elem->call_data; +grpc_stream* grpc_connected_channel_get_stream(grpc_call_element* elem) { + call_data* calld = (call_data*)elem->call_data; return TRANSPORT_STREAM_FROM_CALL_DATA(calld); } diff --git a/src/core/lib/channel/connected_channel.h b/src/core/lib/channel/connected_channel.h index 4615727baa1..cab8aad1543 100644 --- a/src/core/lib/channel/connected_channel.h +++ b/src/core/lib/channel/connected_channel.h @@ -21,21 +21,13 @@ #include "src/core/lib/channel/channel_stack_builder.h" -#ifdef __cplusplus -extern "C" { -#endif - extern const grpc_channel_filter grpc_connected_filter; -bool grpc_add_connected_filter(grpc_exec_ctx *exec_ctx, - grpc_channel_stack_builder *builder, - void *arg_must_be_null); +bool grpc_add_connected_filter(grpc_exec_ctx* exec_ctx, + grpc_channel_stack_builder* builder, + void* arg_must_be_null); /* Debug helper to dig the transport stream out of a call element */ -grpc_stream *grpc_connected_channel_get_stream(grpc_call_element *elem); - -#ifdef __cplusplus -} -#endif +grpc_stream* grpc_connected_channel_get_stream(grpc_call_element* elem); #endif /* GRPC_CORE_LIB_CHANNEL_CONNECTED_CHANNEL_H */ diff --git a/src/core/lib/channel/context.h b/src/core/lib/channel/context.h index 191bd63351c..5daf48a9a9e 100644 --- a/src/core/lib/channel/context.h +++ b/src/core/lib/channel/context.h @@ -42,8 +42,8 @@ typedef enum { } grpc_context_index; typedef struct { - void *value; - void (*destroy)(void *); + void* value; + void (*destroy)(void*); } grpc_call_context_element; #endif /* GRPC_CORE_LIB_CHANNEL_CONTEXT_H */ diff --git a/src/core/lib/channel/handshaker.cc b/src/core/lib/channel/handshaker.cc index b27ee37e5b3..58c30b165b6 100644 --- a/src/core/lib/channel/handshaker.cc +++ b/src/core/lib/channel/handshaker.cc @@ -93,8 +93,8 @@ grpc_handshake_manager* grpc_handshake_manager_create() { void grpc_handshake_manager_pending_list_add(grpc_handshake_manager** head, grpc_handshake_manager* mgr) { - GPR_ASSERT(mgr->prev == NULL); - GPR_ASSERT(mgr->next == NULL); + GPR_ASSERT(mgr->prev == nullptr); + GPR_ASSERT(mgr->next == nullptr); mgr->next = *head; if (*head) { (*head)->prev = mgr; @@ -104,10 +104,10 @@ void grpc_handshake_manager_pending_list_add(grpc_handshake_manager** head, void grpc_handshake_manager_pending_list_remove(grpc_handshake_manager** head, grpc_handshake_manager* mgr) { - if (mgr->next != NULL) { + if (mgr->next != nullptr) { mgr->next->prev = mgr->prev; } - if (mgr->prev != NULL) { + if (mgr->prev != nullptr) { mgr->prev->next = mgr->next; } else { GPR_ASSERT(*head == mgr); @@ -117,7 +117,7 @@ void grpc_handshake_manager_pending_list_remove(grpc_handshake_manager** head, void grpc_handshake_manager_pending_list_shutdown_all( grpc_exec_ctx* exec_ctx, grpc_handshake_manager* head, grpc_error* why) { - while (head != NULL) { + while (head != nullptr) { grpc_handshake_manager_shutdown(exec_ctx, head, GRPC_ERROR_REF(why)); head = head->next; } @@ -231,14 +231,16 @@ static void on_timeout(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { void grpc_handshake_manager_do_handshake( grpc_exec_ctx* exec_ctx, grpc_handshake_manager* mgr, - grpc_endpoint* endpoint, const grpc_channel_args* channel_args, - grpc_millis deadline, grpc_tcp_server_acceptor* acceptor, - grpc_iomgr_cb_func on_handshake_done, void* user_data) { + grpc_pollset_set* interested_parties, grpc_endpoint* endpoint, + const grpc_channel_args* channel_args, grpc_millis deadline, + grpc_tcp_server_acceptor* acceptor, grpc_iomgr_cb_func on_handshake_done, + void* user_data) { gpr_mu_lock(&mgr->mu); GPR_ASSERT(mgr->index == 0); GPR_ASSERT(!mgr->shutdown); // Construct handshaker args. These will be passed through all // handshakers and eventually be freed by the on_handshake_done callback. + mgr->args.interested_parties = interested_parties; mgr->args.endpoint = endpoint; mgr->args.args = grpc_channel_args_copy(channel_args); mgr->args.user_data = user_data; diff --git a/src/core/lib/channel/handshaker.h b/src/core/lib/channel/handshaker.h index 8ed38c15ba1..8e4114dc64c 100644 --- a/src/core/lib/channel/handshaker.h +++ b/src/core/lib/channel/handshaker.h @@ -26,10 +26,6 @@ #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/iomgr/tcp_server.h" -#ifdef __cplusplus -extern "C" { -#endif - /// Handshakers are used to perform initial handshakes on a connection /// before the client sends the initial request. Some examples of what /// a handshaker can be used for includes support for HTTP CONNECT on @@ -58,6 +54,7 @@ typedef struct grpc_handshaker grpc_handshaker; /// For the on_handshake_done callback, all members are input arguments, /// which the callback takes ownership of. typedef struct { + grpc_pollset_set* interested_parties; grpc_endpoint* endpoint; grpc_channel_args* args; grpc_slice_buffer* read_buffer; @@ -135,11 +132,13 @@ void grpc_handshake_manager_shutdown(grpc_exec_ctx* exec_ctx, grpc_error* why); /// Invokes handshakers in the order they were added. +/// \a interested_parties may be non-nullptr to provide a pollset_set that +/// may be used during handshaking. Ownership is not taken. /// Takes ownership of \a endpoint, and then passes that ownership to /// the \a on_handshake_done callback. /// Does NOT take ownership of \a channel_args. Instead, makes a copy before /// invoking the first handshaker. -/// \a acceptor will be NULL for client-side handshakers. +/// \a acceptor will be nullptr for client-side handshakers. /// /// When done, invokes \a on_handshake_done with a grpc_handshaker_args /// object as its argument. If the callback is invoked with error != @@ -148,9 +147,10 @@ void grpc_handshake_manager_shutdown(grpc_exec_ctx* exec_ctx, /// the arguments. void grpc_handshake_manager_do_handshake( grpc_exec_ctx* exec_ctx, grpc_handshake_manager* mgr, - grpc_endpoint* endpoint, const grpc_channel_args* channel_args, - grpc_millis deadline, grpc_tcp_server_acceptor* acceptor, - grpc_iomgr_cb_func on_handshake_done, void* user_data); + grpc_pollset_set* interested_parties, grpc_endpoint* endpoint, + const grpc_channel_args* channel_args, grpc_millis deadline, + grpc_tcp_server_acceptor* acceptor, grpc_iomgr_cb_func on_handshake_done, + void* user_data); /// Add \a mgr to the server side list of all pending handshake managers, the /// list starts with \a *head. @@ -168,8 +168,4 @@ void grpc_handshake_manager_pending_list_remove(grpc_handshake_manager** head, void grpc_handshake_manager_pending_list_shutdown_all( grpc_exec_ctx* exec_ctx, grpc_handshake_manager* head, grpc_error* why); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_CHANNEL_HANDSHAKER_H */ diff --git a/src/core/lib/channel/handshaker_factory.cc b/src/core/lib/channel/handshaker_factory.cc index 4deb280c60d..015006ade0e 100644 --- a/src/core/lib/channel/handshaker_factory.cc +++ b/src/core/lib/channel/handshaker_factory.cc @@ -21,19 +21,19 @@ #include void grpc_handshaker_factory_add_handshakers( - grpc_exec_ctx *exec_ctx, grpc_handshaker_factory *handshaker_factory, - const grpc_channel_args *args, grpc_handshake_manager *handshake_mgr) { - if (handshaker_factory != NULL) { - GPR_ASSERT(handshaker_factory->vtable != NULL); + grpc_exec_ctx* exec_ctx, grpc_handshaker_factory* handshaker_factory, + const grpc_channel_args* args, grpc_handshake_manager* handshake_mgr) { + if (handshaker_factory != nullptr) { + GPR_ASSERT(handshaker_factory->vtable != nullptr); handshaker_factory->vtable->add_handshakers(exec_ctx, handshaker_factory, args, handshake_mgr); } } void grpc_handshaker_factory_destroy( - grpc_exec_ctx *exec_ctx, grpc_handshaker_factory *handshaker_factory) { - if (handshaker_factory != NULL) { - GPR_ASSERT(handshaker_factory->vtable != NULL); + grpc_exec_ctx* exec_ctx, grpc_handshaker_factory* handshaker_factory) { + if (handshaker_factory != nullptr) { + GPR_ASSERT(handshaker_factory->vtable != nullptr); handshaker_factory->vtable->destroy(exec_ctx, handshaker_factory); } } diff --git a/src/core/lib/channel/handshaker_factory.h b/src/core/lib/channel/handshaker_factory.h index 59008adf057..ca7c26b50a2 100644 --- a/src/core/lib/channel/handshaker_factory.h +++ b/src/core/lib/channel/handshaker_factory.h @@ -24,36 +24,28 @@ #include "src/core/lib/channel/handshaker.h" #include "src/core/lib/iomgr/exec_ctx.h" -#ifdef __cplusplus -extern "C" { -#endif - // A handshaker factory is used to create handshakers. typedef struct grpc_handshaker_factory grpc_handshaker_factory; typedef struct { - void (*add_handshakers)(grpc_exec_ctx *exec_ctx, - grpc_handshaker_factory *handshaker_factory, - const grpc_channel_args *args, - grpc_handshake_manager *handshake_mgr); - void (*destroy)(grpc_exec_ctx *exec_ctx, - grpc_handshaker_factory *handshaker_factory); + void (*add_handshakers)(grpc_exec_ctx* exec_ctx, + grpc_handshaker_factory* handshaker_factory, + const grpc_channel_args* args, + grpc_handshake_manager* handshake_mgr); + void (*destroy)(grpc_exec_ctx* exec_ctx, + grpc_handshaker_factory* handshaker_factory); } grpc_handshaker_factory_vtable; struct grpc_handshaker_factory { - const grpc_handshaker_factory_vtable *vtable; + const grpc_handshaker_factory_vtable* vtable; }; void grpc_handshaker_factory_add_handshakers( - grpc_exec_ctx *exec_ctx, grpc_handshaker_factory *handshaker_factory, - const grpc_channel_args *args, grpc_handshake_manager *handshake_mgr); + grpc_exec_ctx* exec_ctx, grpc_handshaker_factory* handshaker_factory, + const grpc_channel_args* args, grpc_handshake_manager* handshake_mgr); void grpc_handshaker_factory_destroy( - grpc_exec_ctx *exec_ctx, grpc_handshaker_factory *handshaker_factory); - -#ifdef __cplusplus -} -#endif + grpc_exec_ctx* exec_ctx, grpc_handshaker_factory* handshaker_factory); #endif /* GRPC_CORE_LIB_CHANNEL_HANDSHAKER_FACTORY_H */ diff --git a/src/core/lib/channel/handshaker_registry.h b/src/core/lib/channel/handshaker_registry.h index ddd280bea8a..a3b2ac1dc73 100644 --- a/src/core/lib/channel/handshaker_registry.h +++ b/src/core/lib/channel/handshaker_registry.h @@ -24,10 +24,6 @@ #include "src/core/lib/channel/handshaker_factory.h" #include "src/core/lib/iomgr/exec_ctx.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef enum { HANDSHAKER_CLIENT = 0, HANDSHAKER_SERVER, @@ -49,8 +45,4 @@ void grpc_handshakers_add(grpc_exec_ctx* exec_ctx, const grpc_channel_args* args, grpc_handshake_manager* handshake_mgr); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_CHANNEL_HANDSHAKER_REGISTRY_H */ diff --git a/src/core/lib/compression/algorithm_metadata.h b/src/core/lib/compression/algorithm_metadata.h index 17caf58f69c..08feafc1bbe 100644 --- a/src/core/lib/compression/algorithm_metadata.h +++ b/src/core/lib/compression/algorithm_metadata.h @@ -22,10 +22,6 @@ #include #include "src/core/lib/transport/metadata.h" -#ifdef __cplusplus -extern "C" { -#endif - /** Return compression algorithm based metadata value */ grpc_slice grpc_compression_algorithm_slice( grpc_compression_algorithm algorithm); @@ -53,8 +49,4 @@ grpc_compression_algorithm grpc_compression_algorithm_from_slice( grpc_stream_compression_algorithm grpc_stream_compression_algorithm_from_slice( grpc_slice str); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_COMPRESSION_ALGORITHM_METADATA_H */ diff --git a/src/core/lib/compression/compression.cc b/src/core/lib/compression/compression.cc index 1cfac231295..a0d5bdcc78d 100644 --- a/src/core/lib/compression/compression.cc +++ b/src/core/lib/compression/compression.cc @@ -27,7 +27,7 @@ #include "src/core/lib/transport/static_metadata.h" int grpc_compression_algorithm_parse(grpc_slice name, - grpc_compression_algorithm *algorithm) { + grpc_compression_algorithm* algorithm) { /* we use strncmp not only because it's safer (even though in this case it * doesn't matter, given that we are comparing against string literals, but * because this way we needn't have "name" nil-terminated (useful for slice @@ -47,7 +47,7 @@ int grpc_compression_algorithm_parse(grpc_slice name, } int grpc_stream_compression_algorithm_parse( - grpc_slice name, grpc_stream_compression_algorithm *algorithm) { + grpc_slice name, grpc_stream_compression_algorithm* algorithm) { if (grpc_slice_eq(name, GRPC_MDSTR_IDENTITY)) { *algorithm = GRPC_STREAM_COMPRESS_NONE; return 1; @@ -60,7 +60,7 @@ int grpc_stream_compression_algorithm_parse( } int grpc_compression_algorithm_name(grpc_compression_algorithm algorithm, - const char **name) { + const char** name) { GRPC_API_TRACE("grpc_compression_algorithm_parse(algorithm=%d, name=%p)", 2, ((int)algorithm, name)); switch (algorithm) { @@ -80,7 +80,7 @@ int grpc_compression_algorithm_name(grpc_compression_algorithm algorithm, } int grpc_stream_compression_algorithm_name( - grpc_stream_compression_algorithm algorithm, const char **name) { + grpc_stream_compression_algorithm algorithm, const char** name) { GRPC_API_TRACE( "grpc_stream_compression_algorithm_parse(algorithm=%d, name=%p)", 2, ((int)algorithm, name)); @@ -168,7 +168,7 @@ grpc_mdelem grpc_stream_compression_encoding_mdelem( return GRPC_MDNULL; } -void grpc_compression_options_init(grpc_compression_options *opts) { +void grpc_compression_options_init(grpc_compression_options* opts) { memset(opts, 0, sizeof(*opts)); /* all enabled by default */ opts->enabled_algorithms_bitset = (1u << GRPC_COMPRESS_ALGORITHMS_COUNT) - 1; @@ -177,23 +177,23 @@ void grpc_compression_options_init(grpc_compression_options *opts) { } void grpc_compression_options_enable_algorithm( - grpc_compression_options *opts, grpc_compression_algorithm algorithm) { + grpc_compression_options* opts, grpc_compression_algorithm algorithm) { GPR_BITSET(&opts->enabled_algorithms_bitset, algorithm); } void grpc_compression_options_disable_algorithm( - grpc_compression_options *opts, grpc_compression_algorithm algorithm) { + grpc_compression_options* opts, grpc_compression_algorithm algorithm) { GPR_BITCLEAR(&opts->enabled_algorithms_bitset, algorithm); } int grpc_compression_options_is_algorithm_enabled( - const grpc_compression_options *opts, + const grpc_compression_options* opts, grpc_compression_algorithm algorithm) { return GPR_BITGET(opts->enabled_algorithms_bitset, algorithm); } int grpc_compression_options_is_stream_compression_algorithm_enabled( - const grpc_compression_options *opts, + const grpc_compression_options* opts, grpc_stream_compression_algorithm algorithm) { return GPR_BITGET(opts->enabled_stream_compression_algorithms_bitset, algorithm); diff --git a/src/core/lib/compression/message_compress.h b/src/core/lib/compression/message_compress.h index fffe175fd22..ca8ca37f8e3 100644 --- a/src/core/lib/compression/message_compress.h +++ b/src/core/lib/compression/message_compress.h @@ -22,10 +22,6 @@ #include #include -#ifdef __cplusplus -extern "C" { -#endif - /* compress 'input' to 'output' using 'algorithm'. On success, appends compressed slices to output and returns 1. On failure, appends uncompressed slices to output and returns 0. */ @@ -40,8 +36,4 @@ int grpc_msg_decompress(grpc_exec_ctx* exec_ctx, grpc_compression_algorithm algorithm, grpc_slice_buffer* input, grpc_slice_buffer* output); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_COMPRESSION_MESSAGE_COMPRESS_H */ diff --git a/src/core/lib/compression/stream_compression.cc b/src/core/lib/compression/stream_compression.cc index 7faeb0d34f0..b4b3e524d0e 100644 --- a/src/core/lib/compression/stream_compression.cc +++ b/src/core/lib/compression/stream_compression.cc @@ -21,26 +21,26 @@ #include "src/core/lib/compression/stream_compression.h" #include "src/core/lib/compression/stream_compression_gzip.h" -extern "C" const grpc_stream_compression_vtable +extern const grpc_stream_compression_vtable grpc_stream_compression_identity_vtable; -bool grpc_stream_compress(grpc_stream_compression_context *ctx, - grpc_slice_buffer *in, grpc_slice_buffer *out, - size_t *output_size, size_t max_output_size, +bool grpc_stream_compress(grpc_stream_compression_context* ctx, + grpc_slice_buffer* in, grpc_slice_buffer* out, + size_t* output_size, size_t max_output_size, grpc_stream_compression_flush flush) { return ctx->vtable->compress(ctx, in, out, output_size, max_output_size, flush); } -bool grpc_stream_decompress(grpc_stream_compression_context *ctx, - grpc_slice_buffer *in, grpc_slice_buffer *out, - size_t *output_size, size_t max_output_size, - bool *end_of_context) { +bool grpc_stream_decompress(grpc_stream_compression_context* ctx, + grpc_slice_buffer* in, grpc_slice_buffer* out, + size_t* output_size, size_t max_output_size, + bool* end_of_context) { return ctx->vtable->decompress(ctx, in, out, output_size, max_output_size, end_of_context); } -grpc_stream_compression_context *grpc_stream_compression_context_create( +grpc_stream_compression_context* grpc_stream_compression_context_create( grpc_stream_compression_method method) { switch (method) { case GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS: @@ -51,18 +51,18 @@ grpc_stream_compression_context *grpc_stream_compression_context_create( return grpc_stream_compression_gzip_vtable.context_create(method); default: gpr_log(GPR_ERROR, "Unknown stream compression method: %d", method); - return NULL; + return nullptr; } } void grpc_stream_compression_context_destroy( - grpc_stream_compression_context *ctx) { + grpc_stream_compression_context* ctx) { ctx->vtable->context_destroy(ctx); } int grpc_stream_compression_method_parse( grpc_slice value, bool is_compress, - grpc_stream_compression_method *method) { + grpc_stream_compression_method* method) { if (grpc_slice_eq(value, GRPC_MDSTR_IDENTITY)) { *method = is_compress ? GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS : GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS; diff --git a/src/core/lib/compression/stream_compression.h b/src/core/lib/compression/stream_compression.h index 6ee3ac19664..8322835c4fd 100644 --- a/src/core/lib/compression/stream_compression.h +++ b/src/core/lib/compression/stream_compression.h @@ -26,15 +26,11 @@ #include "src/core/lib/transport/static_metadata.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_stream_compression_vtable grpc_stream_compression_vtable; /* Stream compression/decompression context */ typedef struct grpc_stream_compression_context { - const grpc_stream_compression_vtable *vtable; + const grpc_stream_compression_vtable* vtable; } grpc_stream_compression_context; typedef enum grpc_stream_compression_method { @@ -53,16 +49,16 @@ typedef enum grpc_stream_compression_flush { } grpc_stream_compression_flush; struct grpc_stream_compression_vtable { - bool (*compress)(grpc_stream_compression_context *ctx, grpc_slice_buffer *in, - grpc_slice_buffer *out, size_t *output_size, + bool (*compress)(grpc_stream_compression_context* ctx, grpc_slice_buffer* in, + grpc_slice_buffer* out, size_t* output_size, size_t max_output_size, grpc_stream_compression_flush flush); - bool (*decompress)(grpc_stream_compression_context *ctx, - grpc_slice_buffer *in, grpc_slice_buffer *out, - size_t *output_size, size_t max_output_size, - bool *end_of_context); - grpc_stream_compression_context *(*context_create)( + bool (*decompress)(grpc_stream_compression_context* ctx, + grpc_slice_buffer* in, grpc_slice_buffer* out, + size_t* output_size, size_t max_output_size, + bool* end_of_context); + grpc_stream_compression_context* (*context_create)( grpc_stream_compression_method method); - void (*context_destroy)(grpc_stream_compression_context *ctx); + void (*context_destroy)(grpc_stream_compression_context* ctx); }; /** @@ -78,9 +74,9 @@ struct grpc_stream_compression_vtable { * previous compressed bytes. It allows corresponding decompression context to * be dropped when reaching this boundary. */ -bool grpc_stream_compress(grpc_stream_compression_context *ctx, - grpc_slice_buffer *in, grpc_slice_buffer *out, - size_t *output_size, size_t max_output_size, +bool grpc_stream_compress(grpc_stream_compression_context* ctx, + grpc_slice_buffer* in, grpc_slice_buffer* out, + size_t* output_size, size_t max_output_size, grpc_stream_compression_flush flush); /** @@ -90,33 +86,29 @@ bool grpc_stream_compress(grpc_stream_compression_context *ctx, * it is set to false. The total number of bytes emitted is outputed in \a * output_size. */ -bool grpc_stream_decompress(grpc_stream_compression_context *ctx, - grpc_slice_buffer *in, grpc_slice_buffer *out, - size_t *output_size, size_t max_output_size, - bool *end_of_context); +bool grpc_stream_decompress(grpc_stream_compression_context* ctx, + grpc_slice_buffer* in, grpc_slice_buffer* out, + size_t* output_size, size_t max_output_size, + bool* end_of_context); /** * Creates a stream compression context. \a pending_bytes_buffer is the input * buffer for compression/decompression operations. \a method specifies whether * the context is for compression or decompression. */ -grpc_stream_compression_context *grpc_stream_compression_context_create( +grpc_stream_compression_context* grpc_stream_compression_context_create( grpc_stream_compression_method method); /** * Destroys a stream compression context. */ void grpc_stream_compression_context_destroy( - grpc_stream_compression_context *ctx); + grpc_stream_compression_context* ctx); /** * Parse stream compression method based on algorithm name */ int grpc_stream_compression_method_parse( - grpc_slice value, bool is_compress, grpc_stream_compression_method *method); - -#ifdef __cplusplus -} -#endif + grpc_slice value, bool is_compress, grpc_stream_compression_method* method); #endif diff --git a/src/core/lib/compression/stream_compression_gzip.cc b/src/core/lib/compression/stream_compression_gzip.cc index 087b018be54..0c3fdd12698 100644 --- a/src/core/lib/compression/stream_compression_gzip.cc +++ b/src/core/lib/compression/stream_compression_gzip.cc @@ -29,13 +29,13 @@ typedef struct grpc_stream_compression_context_gzip { grpc_stream_compression_context base; z_stream zs; - int (*flate)(z_stream *zs, int flush); + int (*flate)(z_stream* zs, int flush); } grpc_stream_compression_context_gzip; -static bool gzip_flate(grpc_stream_compression_context_gzip *ctx, - grpc_slice_buffer *in, grpc_slice_buffer *out, - size_t *output_size, size_t max_output_size, int flush, - bool *end_of_context) { +static bool gzip_flate(grpc_stream_compression_context_gzip* ctx, + grpc_slice_buffer* in, grpc_slice_buffer* out, + size_t* output_size, size_t max_output_size, int flush, + bool* end_of_context) { GPR_ASSERT(flush == 0 || flush == Z_SYNC_FLUSH || flush == Z_FINISH); /* Full flush is not allowed when inflating. */ GPR_ASSERT(!(ctx->flate == inflate && (flush == Z_FINISH))); @@ -131,17 +131,17 @@ static bool gzip_flate(grpc_stream_compression_context_gzip *ctx, return true; } -static bool grpc_stream_compress_gzip(grpc_stream_compression_context *ctx, - grpc_slice_buffer *in, - grpc_slice_buffer *out, - size_t *output_size, +static bool grpc_stream_compress_gzip(grpc_stream_compression_context* ctx, + grpc_slice_buffer* in, + grpc_slice_buffer* out, + size_t* output_size, size_t max_output_size, grpc_stream_compression_flush flush) { - if (ctx == NULL) { + if (ctx == nullptr) { return false; } - grpc_stream_compression_context_gzip *gzip_ctx = - (grpc_stream_compression_context_gzip *)ctx; + grpc_stream_compression_context_gzip* gzip_ctx = + (grpc_stream_compression_context_gzip*)ctx; GPR_ASSERT(gzip_ctx->flate == deflate); int gzip_flush; switch (flush) { @@ -158,36 +158,36 @@ static bool grpc_stream_compress_gzip(grpc_stream_compression_context *ctx, gzip_flush = 0; } return gzip_flate(gzip_ctx, in, out, output_size, max_output_size, gzip_flush, - NULL); + nullptr); } -static bool grpc_stream_decompress_gzip(grpc_stream_compression_context *ctx, - grpc_slice_buffer *in, - grpc_slice_buffer *out, - size_t *output_size, +static bool grpc_stream_decompress_gzip(grpc_stream_compression_context* ctx, + grpc_slice_buffer* in, + grpc_slice_buffer* out, + size_t* output_size, size_t max_output_size, - bool *end_of_context) { - if (ctx == NULL) { + bool* end_of_context) { + if (ctx == nullptr) { return false; } - grpc_stream_compression_context_gzip *gzip_ctx = - (grpc_stream_compression_context_gzip *)ctx; + grpc_stream_compression_context_gzip* gzip_ctx = + (grpc_stream_compression_context_gzip*)ctx; GPR_ASSERT(gzip_ctx->flate == inflate); return gzip_flate(gzip_ctx, in, out, output_size, max_output_size, Z_SYNC_FLUSH, end_of_context); } -static grpc_stream_compression_context * +static grpc_stream_compression_context* grpc_stream_compression_context_create_gzip( grpc_stream_compression_method method) { GPR_ASSERT(method == GRPC_STREAM_COMPRESSION_GZIP_COMPRESS || method == GRPC_STREAM_COMPRESSION_GZIP_DECOMPRESS); - grpc_stream_compression_context_gzip *gzip_ctx = - (grpc_stream_compression_context_gzip *)gpr_zalloc( + grpc_stream_compression_context_gzip* gzip_ctx = + (grpc_stream_compression_context_gzip*)gpr_zalloc( sizeof(grpc_stream_compression_context_gzip)); int r; - if (gzip_ctx == NULL) { - return NULL; + if (gzip_ctx == nullptr) { + return nullptr; } if (method == GRPC_STREAM_COMPRESSION_GZIP_DECOMPRESS) { r = inflateInit2(&gzip_ctx->zs, 0x1F); @@ -199,20 +199,20 @@ grpc_stream_compression_context_create_gzip( } if (r != Z_OK) { gpr_free(gzip_ctx); - return NULL; + return nullptr; } gzip_ctx->base.vtable = &grpc_stream_compression_gzip_vtable; - return (grpc_stream_compression_context *)gzip_ctx; + return (grpc_stream_compression_context*)gzip_ctx; } static void grpc_stream_compression_context_destroy_gzip( - grpc_stream_compression_context *ctx) { - if (ctx == NULL) { + grpc_stream_compression_context* ctx) { + if (ctx == nullptr) { return; } - grpc_stream_compression_context_gzip *gzip_ctx = - (grpc_stream_compression_context_gzip *)ctx; + grpc_stream_compression_context_gzip* gzip_ctx = + (grpc_stream_compression_context_gzip*)ctx; if (gzip_ctx->flate == inflate) { inflateEnd(&gzip_ctx->zs); } else { diff --git a/src/core/lib/compression/stream_compression_gzip.h b/src/core/lib/compression/stream_compression_gzip.h index a3f1b0406fe..7cf49a0de93 100644 --- a/src/core/lib/compression/stream_compression_gzip.h +++ b/src/core/lib/compression/stream_compression_gzip.h @@ -21,14 +21,6 @@ #include "src/core/lib/compression/stream_compression.h" -#ifdef __cplusplus -extern "C" { -#endif - extern const grpc_stream_compression_vtable grpc_stream_compression_gzip_vtable; -#ifdef __cplusplus -} -#endif - #endif diff --git a/src/core/lib/compression/stream_compression_identity.cc b/src/core/lib/compression/stream_compression_identity.cc index 9b2e6062e17..af4051144c0 100644 --- a/src/core/lib/compression/stream_compression_identity.cc +++ b/src/core/lib/compression/stream_compression_identity.cc @@ -29,9 +29,9 @@ static grpc_stream_compression_context identity_ctx = { &grpc_stream_compression_identity_vtable}; -static void grpc_stream_compression_pass_through(grpc_slice_buffer *in, - grpc_slice_buffer *out, - size_t *output_size, +static void grpc_stream_compression_pass_through(grpc_slice_buffer* in, + grpc_slice_buffer* out, + size_t* output_size, size_t max_output_size) { if (max_output_size >= in->length) { if (output_size) { @@ -46,13 +46,13 @@ static void grpc_stream_compression_pass_through(grpc_slice_buffer *in, } } -static bool grpc_stream_compress_identity(grpc_stream_compression_context *ctx, - grpc_slice_buffer *in, - grpc_slice_buffer *out, - size_t *output_size, +static bool grpc_stream_compress_identity(grpc_stream_compression_context* ctx, + grpc_slice_buffer* in, + grpc_slice_buffer* out, + size_t* output_size, size_t max_output_size, grpc_stream_compression_flush flush) { - if (ctx == NULL) { + if (ctx == nullptr) { return false; } grpc_stream_compression_pass_through(in, out, output_size, max_output_size); @@ -60,10 +60,10 @@ static bool grpc_stream_compress_identity(grpc_stream_compression_context *ctx, } static bool grpc_stream_decompress_identity( - grpc_stream_compression_context *ctx, grpc_slice_buffer *in, - grpc_slice_buffer *out, size_t *output_size, size_t max_output_size, - bool *end_of_context) { - if (ctx == NULL) { + grpc_stream_compression_context* ctx, grpc_slice_buffer* in, + grpc_slice_buffer* out, size_t* output_size, size_t max_output_size, + bool* end_of_context) { + if (ctx == nullptr) { return false; } grpc_stream_compression_pass_through(in, out, output_size, max_output_size); @@ -73,17 +73,17 @@ static bool grpc_stream_decompress_identity( return true; } -static grpc_stream_compression_context * +static grpc_stream_compression_context* grpc_stream_compression_context_create_identity( grpc_stream_compression_method method) { GPR_ASSERT(method == GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS || method == GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS); /* No context needed in this case. Use fake context instead. */ - return (grpc_stream_compression_context *)&identity_ctx; + return (grpc_stream_compression_context*)&identity_ctx; } static void grpc_stream_compression_context_destroy_identity( - grpc_stream_compression_context *ctx) { + grpc_stream_compression_context* ctx) { return; } diff --git a/src/core/lib/compression/stream_compression_identity.h b/src/core/lib/compression/stream_compression_identity.h index 3a729fafad8..41926e949e5 100644 --- a/src/core/lib/compression/stream_compression_identity.h +++ b/src/core/lib/compression/stream_compression_identity.h @@ -21,15 +21,7 @@ #include "src/core/lib/compression/stream_compression.h" -#ifdef __cplusplus -extern "C" { -#endif - extern const grpc_stream_compression_vtable grpc_stream_compression_identity_vtable; -#ifdef __cplusplus -} -#endif - #endif diff --git a/src/core/lib/debug/stats.cc b/src/core/lib/debug/stats.cc index 4096384dd92..7d2af71c475 100644 --- a/src/core/lib/debug/stats.cc +++ b/src/core/lib/debug/stats.cc @@ -27,18 +27,18 @@ #include "src/core/lib/support/string.h" -grpc_stats_data *grpc_stats_per_cpu_storage = NULL; +grpc_stats_data* grpc_stats_per_cpu_storage = nullptr; static size_t g_num_cores; void grpc_stats_init(void) { g_num_cores = GPR_MAX(1, gpr_cpu_num_cores()); grpc_stats_per_cpu_storage = - (grpc_stats_data *)gpr_zalloc(sizeof(grpc_stats_data) * g_num_cores); + (grpc_stats_data*)gpr_zalloc(sizeof(grpc_stats_data) * g_num_cores); } void grpc_stats_shutdown(void) { gpr_free(grpc_stats_per_cpu_storage); } -void grpc_stats_collect(grpc_stats_data *output) { +void grpc_stats_collect(grpc_stats_data* output) { memset(output, 0, sizeof(*output)); for (size_t core = 0; core < g_num_cores; core++) { for (size_t i = 0; i < GRPC_STATS_COUNTER_COUNT; i++) { @@ -52,8 +52,8 @@ void grpc_stats_collect(grpc_stats_data *output) { } } -void grpc_stats_diff(const grpc_stats_data *b, const grpc_stats_data *a, - grpc_stats_data *c) { +void grpc_stats_diff(const grpc_stats_data* b, const grpc_stats_data* a, + grpc_stats_data* c) { for (size_t i = 0; i < GRPC_STATS_COUNTER_COUNT; i++) { c->counters[i] = b->counters[i] - a->counters[i]; } @@ -62,13 +62,13 @@ void grpc_stats_diff(const grpc_stats_data *b, const grpc_stats_data *a, } } -int grpc_stats_histo_find_bucket_slow(grpc_exec_ctx *exec_ctx, int value, - const int *table, int table_size) { +int grpc_stats_histo_find_bucket_slow(grpc_exec_ctx* exec_ctx, int value, + const int* table, int table_size) { GRPC_STATS_INC_HISTOGRAM_SLOW_LOOKUPS(exec_ctx); - const int *const start = table; + const int* const start = table; while (table_size > 0) { int step = table_size / 2; - const int *it = table + step; + const int* it = table + step; if (value >= *it) { table = it + 1; table_size -= step + 1; @@ -79,7 +79,7 @@ int grpc_stats_histo_find_bucket_slow(grpc_exec_ctx *exec_ctx, int value, return (int)(table - start) - 1; } -size_t grpc_stats_histo_count(const grpc_stats_data *stats, +size_t grpc_stats_histo_count(const grpc_stats_data* stats, grpc_stats_histograms histogram) { size_t sum = 0; for (int i = 0; i < grpc_stats_histo_buckets[histogram]; i++) { @@ -88,8 +88,8 @@ size_t grpc_stats_histo_count(const grpc_stats_data *stats, return sum; } -static double threshold_for_count_below(const gpr_atm *bucket_counts, - const int *bucket_boundaries, +static double threshold_for_count_below(const gpr_atm* bucket_counts, + const int* bucket_boundaries, int num_buckets, double count_below) { double count_so_far; double lower_bound; @@ -119,13 +119,13 @@ static double threshold_for_count_below(const gpr_atm *bucket_counts, should lie */ lower_bound = bucket_boundaries[lower_idx]; upper_bound = bucket_boundaries[lower_idx + 1]; - return upper_bound - - (upper_bound - lower_bound) * (count_so_far - count_below) / - (double)bucket_counts[lower_idx]; + return upper_bound - (upper_bound - lower_bound) * + (count_so_far - count_below) / + (double)bucket_counts[lower_idx]; } } -double grpc_stats_histo_percentile(const grpc_stats_data *stats, +double grpc_stats_histo_percentile(const grpc_stats_data* stats, grpc_stats_histograms histogram, double percentile) { size_t count = grpc_stats_histo_count(stats, histogram); @@ -136,9 +136,9 @@ double grpc_stats_histo_percentile(const grpc_stats_data *stats, grpc_stats_histo_buckets[histogram], (double)count * percentile / 100.0); } -char *grpc_stats_data_as_json(const grpc_stats_data *data) { +char* grpc_stats_data_as_json(const grpc_stats_data* data) { gpr_strvec v; - char *tmp; + char* tmp; bool is_first = true; gpr_strvec_init(&v); gpr_strvec_add(&v, gpr_strdup("{")); @@ -168,7 +168,7 @@ char *grpc_stats_data_as_json(const grpc_stats_data *data) { is_first = false; } gpr_strvec_add(&v, gpr_strdup("}")); - tmp = gpr_strvec_flatten(&v, NULL); + tmp = gpr_strvec_flatten(&v, nullptr); gpr_strvec_destroy(&v); return tmp; } diff --git a/src/core/lib/debug/stats.h b/src/core/lib/debug/stats.h index fec1d651e6a..55db44e0c28 100644 --- a/src/core/lib/debug/stats.h +++ b/src/core/lib/debug/stats.h @@ -23,16 +23,12 @@ #include "src/core/lib/debug/stats_data.h" #include "src/core/lib/iomgr/exec_ctx.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_stats_data { gpr_atm counters[GRPC_STATS_COUNTER_COUNT]; gpr_atm histograms[GRPC_STATS_HISTOGRAM_BUCKETS]; } grpc_stats_data; -extern grpc_stats_data *grpc_stats_per_cpu_storage; +extern grpc_stats_data* grpc_stats_per_cpu_storage; #define GRPC_THREAD_STATS_DATA(exec_ctx) \ (&grpc_stats_per_cpu_storage[(exec_ctx)->starting_cpu]) @@ -49,21 +45,17 @@ extern grpc_stats_data *grpc_stats_per_cpu_storage; void grpc_stats_init(void); void grpc_stats_shutdown(void); -void grpc_stats_collect(grpc_stats_data *output); +void grpc_stats_collect(grpc_stats_data* output); // c = b-a -void grpc_stats_diff(const grpc_stats_data *b, const grpc_stats_data *a, - grpc_stats_data *c); -char *grpc_stats_data_as_json(const grpc_stats_data *data); -int grpc_stats_histo_find_bucket_slow(grpc_exec_ctx *exec_ctx, int value, - const int *table, int table_size); -double grpc_stats_histo_percentile(const grpc_stats_data *data, +void grpc_stats_diff(const grpc_stats_data* b, const grpc_stats_data* a, + grpc_stats_data* c); +char* grpc_stats_data_as_json(const grpc_stats_data* data); +int grpc_stats_histo_find_bucket_slow(grpc_exec_ctx* exec_ctx, int value, + const int* table, int table_size); +double grpc_stats_histo_percentile(const grpc_stats_data* data, grpc_stats_histograms histogram, double percentile); -size_t grpc_stats_histo_count(const grpc_stats_data *data, +size_t grpc_stats_histo_count(const grpc_stats_data* data, grpc_stats_histograms histogram); -#ifdef __cplusplus -} -#endif - #endif diff --git a/src/core/lib/debug/stats_data.cc b/src/core/lib/debug/stats_data.cc index 5d737c56cbf..17e15f4cfbe 100644 --- a/src/core/lib/debug/stats_data.cc +++ b/src/core/lib/debug/stats_data.cc @@ -22,7 +22,7 @@ #include #include "src/core/lib/debug/stats.h" #include "src/core/lib/iomgr/exec_ctx.h" -const char *grpc_stats_counter_name[GRPC_STATS_COUNTER_COUNT] = { +const char* grpc_stats_counter_name[GRPC_STATS_COUNTER_COUNT] = { "client_calls_created", "server_calls_created", "cqs_created", @@ -120,11 +120,13 @@ const char *grpc_stats_counter_name[GRPC_STATS_COUNTER_COUNT] = { "cq_ev_queue_trylock_successes", "cq_ev_queue_transient_pop_failures", }; -const char *grpc_stats_counter_doc[GRPC_STATS_COUNTER_COUNT] = { +const char* grpc_stats_counter_doc[GRPC_STATS_COUNTER_COUNT] = { "Number of client side calls created by this process", "Number of server side calls created by this process", - "Number of completion queues created", "Number of client channels created", - "Number of client subchannels created", "Number of server channels created", + "Number of completion queues created", + "Number of client channels created", + "Number of client subchannels created", + "Number of server channels created", "Number of polling syscalls (epoll_wait, poll, etc) made by this process", "Number of sleeping syscalls made by this process", "How many polling wakeups were performed by the process (only valid for " @@ -154,7 +156,8 @@ const char *grpc_stats_counter_doc[GRPC_STATS_COUNTER_COUNT] = { "Number of batches containing receive initial metadata", "Number of batches containing receive message", "Number of batches containing receive trailing metadata", - "Number of settings frames sent", "Number of HTTP2 pings sent by process", + "Number of settings frames sent", + "Number of HTTP2 pings sent by process", "Number of HTTP2 writes initiated", "Number of HTTP2 writes offloaded to the executor from application threads", "Number of HTTP2 writes that finished seeing more data needed to be " @@ -241,7 +244,7 @@ const char *grpc_stats_counter_doc[GRPC_STATS_COUNTER_COUNT] = { "Number of times NULL was popped out of completion queue's event queue " "even though the event queue was not empty", }; -const char *grpc_stats_histogram_name[GRPC_STATS_HISTOGRAM_COUNT] = { +const char* grpc_stats_histogram_name[GRPC_STATS_HISTOGRAM_COUNT] = { "call_initial_size", "poll_events_returned", "tcp_write_size", @@ -256,7 +259,7 @@ const char *grpc_stats_histogram_name[GRPC_STATS_HISTOGRAM_COUNT] = { "http2_send_flowctl_per_write", "server_cqs_checked", }; -const char *grpc_stats_histogram_doc[GRPC_STATS_HISTOGRAM_COUNT] = { +const char* grpc_stats_histogram_doc[GRPC_STATS_HISTOGRAM_COUNT] = { "Initial size of the grpc_call arena created at call start", "How many events are called for each syscall_poll", "Number of bytes offered to each syscall_write", @@ -339,7 +342,7 @@ const uint8_t grpc_stats_table_7[102] = { 42, 42, 43, 44, 44, 45, 46, 46, 47, 48, 48, 49, 49, 50, 50, 51, 51}; const int grpc_stats_table_8[9] = {0, 1, 2, 4, 7, 13, 23, 39, 64}; const uint8_t grpc_stats_table_9[9] = {0, 0, 1, 2, 2, 3, 4, 4, 5}; -void grpc_stats_inc_call_initial_size(grpc_exec_ctx *exec_ctx, int value) { +void grpc_stats_inc_call_initial_size(grpc_exec_ctx* exec_ctx, int value) { value = GPR_CLAMP(value, 0, 262144); if (value < 6) { GRPC_STATS_INC_HISTOGRAM((exec_ctx), GRPC_STATS_HISTOGRAM_CALL_INITIAL_SIZE, @@ -364,7 +367,7 @@ void grpc_stats_inc_call_initial_size(grpc_exec_ctx *exec_ctx, int value) { grpc_stats_histo_find_bucket_slow( (exec_ctx), value, grpc_stats_table_0, 64)); } -void grpc_stats_inc_poll_events_returned(grpc_exec_ctx *exec_ctx, int value) { +void grpc_stats_inc_poll_events_returned(grpc_exec_ctx* exec_ctx, int value) { value = GPR_CLAMP(value, 0, 1024); if (value < 29) { GRPC_STATS_INC_HISTOGRAM((exec_ctx), @@ -390,7 +393,7 @@ void grpc_stats_inc_poll_events_returned(grpc_exec_ctx *exec_ctx, int value) { grpc_stats_histo_find_bucket_slow( (exec_ctx), value, grpc_stats_table_2, 128)); } -void grpc_stats_inc_tcp_write_size(grpc_exec_ctx *exec_ctx, int value) { +void grpc_stats_inc_tcp_write_size(grpc_exec_ctx* exec_ctx, int value) { value = GPR_CLAMP(value, 0, 16777216); if (value < 5) { GRPC_STATS_INC_HISTOGRAM((exec_ctx), GRPC_STATS_HISTOGRAM_TCP_WRITE_SIZE, @@ -415,7 +418,7 @@ void grpc_stats_inc_tcp_write_size(grpc_exec_ctx *exec_ctx, int value) { grpc_stats_histo_find_bucket_slow( (exec_ctx), value, grpc_stats_table_4, 64)); } -void grpc_stats_inc_tcp_write_iov_size(grpc_exec_ctx *exec_ctx, int value) { +void grpc_stats_inc_tcp_write_iov_size(grpc_exec_ctx* exec_ctx, int value) { value = GPR_CLAMP(value, 0, 1024); if (value < 13) { GRPC_STATS_INC_HISTOGRAM((exec_ctx), @@ -440,7 +443,7 @@ void grpc_stats_inc_tcp_write_iov_size(grpc_exec_ctx *exec_ctx, int value) { grpc_stats_histo_find_bucket_slow( (exec_ctx), value, grpc_stats_table_6, 64)); } -void grpc_stats_inc_tcp_read_size(grpc_exec_ctx *exec_ctx, int value) { +void grpc_stats_inc_tcp_read_size(grpc_exec_ctx* exec_ctx, int value) { value = GPR_CLAMP(value, 0, 16777216); if (value < 5) { GRPC_STATS_INC_HISTOGRAM((exec_ctx), GRPC_STATS_HISTOGRAM_TCP_READ_SIZE, @@ -465,7 +468,7 @@ void grpc_stats_inc_tcp_read_size(grpc_exec_ctx *exec_ctx, int value) { grpc_stats_histo_find_bucket_slow( (exec_ctx), value, grpc_stats_table_4, 64)); } -void grpc_stats_inc_tcp_read_offer(grpc_exec_ctx *exec_ctx, int value) { +void grpc_stats_inc_tcp_read_offer(grpc_exec_ctx* exec_ctx, int value) { value = GPR_CLAMP(value, 0, 16777216); if (value < 5) { GRPC_STATS_INC_HISTOGRAM((exec_ctx), GRPC_STATS_HISTOGRAM_TCP_READ_OFFER, @@ -490,7 +493,7 @@ void grpc_stats_inc_tcp_read_offer(grpc_exec_ctx *exec_ctx, int value) { grpc_stats_histo_find_bucket_slow( (exec_ctx), value, grpc_stats_table_4, 64)); } -void grpc_stats_inc_tcp_read_offer_iov_size(grpc_exec_ctx *exec_ctx, +void grpc_stats_inc_tcp_read_offer_iov_size(grpc_exec_ctx* exec_ctx, int value) { value = GPR_CLAMP(value, 0, 1024); if (value < 13) { @@ -517,7 +520,7 @@ void grpc_stats_inc_tcp_read_offer_iov_size(grpc_exec_ctx *exec_ctx, grpc_stats_histo_find_bucket_slow( (exec_ctx), value, grpc_stats_table_6, 64)); } -void grpc_stats_inc_http2_send_message_size(grpc_exec_ctx *exec_ctx, +void grpc_stats_inc_http2_send_message_size(grpc_exec_ctx* exec_ctx, int value) { value = GPR_CLAMP(value, 0, 16777216); if (value < 5) { @@ -545,7 +548,7 @@ void grpc_stats_inc_http2_send_message_size(grpc_exec_ctx *exec_ctx, (exec_ctx), value, grpc_stats_table_4, 64)); } void grpc_stats_inc_http2_send_initial_metadata_per_write( - grpc_exec_ctx *exec_ctx, int value) { + grpc_exec_ctx* exec_ctx, int value) { value = GPR_CLAMP(value, 0, 1024); if (value < 13) { GRPC_STATS_INC_HISTOGRAM( @@ -573,7 +576,7 @@ void grpc_stats_inc_http2_send_initial_metadata_per_write( grpc_stats_histo_find_bucket_slow((exec_ctx), value, grpc_stats_table_6, 64)); } -void grpc_stats_inc_http2_send_message_per_write(grpc_exec_ctx *exec_ctx, +void grpc_stats_inc_http2_send_message_per_write(grpc_exec_ctx* exec_ctx, int value) { value = GPR_CLAMP(value, 0, 1024); if (value < 13) { @@ -601,7 +604,7 @@ void grpc_stats_inc_http2_send_message_per_write(grpc_exec_ctx *exec_ctx, (exec_ctx), value, grpc_stats_table_6, 64)); } void grpc_stats_inc_http2_send_trailing_metadata_per_write( - grpc_exec_ctx *exec_ctx, int value) { + grpc_exec_ctx* exec_ctx, int value) { value = GPR_CLAMP(value, 0, 1024); if (value < 13) { GRPC_STATS_INC_HISTOGRAM( @@ -629,7 +632,7 @@ void grpc_stats_inc_http2_send_trailing_metadata_per_write( grpc_stats_histo_find_bucket_slow((exec_ctx), value, grpc_stats_table_6, 64)); } -void grpc_stats_inc_http2_send_flowctl_per_write(grpc_exec_ctx *exec_ctx, +void grpc_stats_inc_http2_send_flowctl_per_write(grpc_exec_ctx* exec_ctx, int value) { value = GPR_CLAMP(value, 0, 1024); if (value < 13) { @@ -656,7 +659,7 @@ void grpc_stats_inc_http2_send_flowctl_per_write(grpc_exec_ctx *exec_ctx, grpc_stats_histo_find_bucket_slow( (exec_ctx), value, grpc_stats_table_6, 64)); } -void grpc_stats_inc_server_cqs_checked(grpc_exec_ctx *exec_ctx, int value) { +void grpc_stats_inc_server_cqs_checked(grpc_exec_ctx* exec_ctx, int value) { value = GPR_CLAMP(value, 0, 64); if (value < 3) { GRPC_STATS_INC_HISTOGRAM((exec_ctx), @@ -685,13 +688,13 @@ const int grpc_stats_histo_buckets[13] = {64, 128, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 8}; const int grpc_stats_histo_start[13] = {0, 64, 192, 256, 320, 384, 448, 512, 576, 640, 704, 768, 832}; -const int *const grpc_stats_histo_bucket_boundaries[13] = { +const int* const grpc_stats_histo_bucket_boundaries[13] = { grpc_stats_table_0, grpc_stats_table_2, grpc_stats_table_4, grpc_stats_table_6, grpc_stats_table_4, grpc_stats_table_4, grpc_stats_table_6, grpc_stats_table_4, grpc_stats_table_6, grpc_stats_table_6, grpc_stats_table_6, grpc_stats_table_6, grpc_stats_table_8}; -void (*const grpc_stats_inc_histogram[13])(grpc_exec_ctx *exec_ctx, int x) = { +void (*const grpc_stats_inc_histogram[13])(grpc_exec_ctx* exec_ctx, int x) = { grpc_stats_inc_call_initial_size, grpc_stats_inc_poll_events_returned, grpc_stats_inc_tcp_write_size, diff --git a/src/core/lib/debug/stats_data.h b/src/core/lib/debug/stats_data.h index 031942df5c5..8a5bc973899 100644 --- a/src/core/lib/debug/stats_data.h +++ b/src/core/lib/debug/stats_data.h @@ -24,10 +24,6 @@ #include #include "src/core/lib/iomgr/exec_ctx.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef enum { GRPC_STATS_COUNTER_CLIENT_CALLS_CREATED, GRPC_STATS_COUNTER_SERVER_CALLS_CREATED, @@ -127,8 +123,8 @@ typedef enum { GRPC_STATS_COUNTER_CQ_EV_QUEUE_TRANSIENT_POP_FAILURES, GRPC_STATS_COUNTER_COUNT } grpc_stats_counters; -extern const char *grpc_stats_counter_name[GRPC_STATS_COUNTER_COUNT]; -extern const char *grpc_stats_counter_doc[GRPC_STATS_COUNTER_COUNT]; +extern const char* grpc_stats_counter_name[GRPC_STATS_COUNTER_COUNT]; +extern const char* grpc_stats_counter_doc[GRPC_STATS_COUNTER_COUNT]; typedef enum { GRPC_STATS_HISTOGRAM_CALL_INITIAL_SIZE, GRPC_STATS_HISTOGRAM_POLL_EVENTS_RETURNED, @@ -145,8 +141,8 @@ typedef enum { GRPC_STATS_HISTOGRAM_SERVER_CQS_CHECKED, GRPC_STATS_HISTOGRAM_COUNT } grpc_stats_histograms; -extern const char *grpc_stats_histogram_name[GRPC_STATS_HISTOGRAM_COUNT]; -extern const char *grpc_stats_histogram_doc[GRPC_STATS_HISTOGRAM_COUNT]; +extern const char* grpc_stats_histogram_name[GRPC_STATS_HISTOGRAM_COUNT]; +extern const char* grpc_stats_histogram_doc[GRPC_STATS_HISTOGRAM_COUNT]; typedef enum { GRPC_STATS_HISTOGRAM_CALL_INITIAL_SIZE_FIRST_SLOT = 0, GRPC_STATS_HISTOGRAM_CALL_INITIAL_SIZE_BUCKETS = 64, @@ -454,56 +450,52 @@ typedef enum { (exec_ctx), GRPC_STATS_COUNTER_CQ_EV_QUEUE_TRANSIENT_POP_FAILURES) #define GRPC_STATS_INC_CALL_INITIAL_SIZE(exec_ctx, value) \ grpc_stats_inc_call_initial_size((exec_ctx), (int)(value)) -void grpc_stats_inc_call_initial_size(grpc_exec_ctx *exec_ctx, int x); +void grpc_stats_inc_call_initial_size(grpc_exec_ctx* exec_ctx, int x); #define GRPC_STATS_INC_POLL_EVENTS_RETURNED(exec_ctx, value) \ grpc_stats_inc_poll_events_returned((exec_ctx), (int)(value)) -void grpc_stats_inc_poll_events_returned(grpc_exec_ctx *exec_ctx, int x); +void grpc_stats_inc_poll_events_returned(grpc_exec_ctx* exec_ctx, int x); #define GRPC_STATS_INC_TCP_WRITE_SIZE(exec_ctx, value) \ grpc_stats_inc_tcp_write_size((exec_ctx), (int)(value)) -void grpc_stats_inc_tcp_write_size(grpc_exec_ctx *exec_ctx, int x); +void grpc_stats_inc_tcp_write_size(grpc_exec_ctx* exec_ctx, int x); #define GRPC_STATS_INC_TCP_WRITE_IOV_SIZE(exec_ctx, value) \ grpc_stats_inc_tcp_write_iov_size((exec_ctx), (int)(value)) -void grpc_stats_inc_tcp_write_iov_size(grpc_exec_ctx *exec_ctx, int x); +void grpc_stats_inc_tcp_write_iov_size(grpc_exec_ctx* exec_ctx, int x); #define GRPC_STATS_INC_TCP_READ_SIZE(exec_ctx, value) \ grpc_stats_inc_tcp_read_size((exec_ctx), (int)(value)) -void grpc_stats_inc_tcp_read_size(grpc_exec_ctx *exec_ctx, int x); +void grpc_stats_inc_tcp_read_size(grpc_exec_ctx* exec_ctx, int x); #define GRPC_STATS_INC_TCP_READ_OFFER(exec_ctx, value) \ grpc_stats_inc_tcp_read_offer((exec_ctx), (int)(value)) -void grpc_stats_inc_tcp_read_offer(grpc_exec_ctx *exec_ctx, int x); +void grpc_stats_inc_tcp_read_offer(grpc_exec_ctx* exec_ctx, int x); #define GRPC_STATS_INC_TCP_READ_OFFER_IOV_SIZE(exec_ctx, value) \ grpc_stats_inc_tcp_read_offer_iov_size((exec_ctx), (int)(value)) -void grpc_stats_inc_tcp_read_offer_iov_size(grpc_exec_ctx *exec_ctx, int x); +void grpc_stats_inc_tcp_read_offer_iov_size(grpc_exec_ctx* exec_ctx, int x); #define GRPC_STATS_INC_HTTP2_SEND_MESSAGE_SIZE(exec_ctx, value) \ grpc_stats_inc_http2_send_message_size((exec_ctx), (int)(value)) -void grpc_stats_inc_http2_send_message_size(grpc_exec_ctx *exec_ctx, int x); +void grpc_stats_inc_http2_send_message_size(grpc_exec_ctx* exec_ctx, int x); #define GRPC_STATS_INC_HTTP2_SEND_INITIAL_METADATA_PER_WRITE(exec_ctx, value) \ grpc_stats_inc_http2_send_initial_metadata_per_write((exec_ctx), (int)(value)) void grpc_stats_inc_http2_send_initial_metadata_per_write( - grpc_exec_ctx *exec_ctx, int x); + grpc_exec_ctx* exec_ctx, int x); #define GRPC_STATS_INC_HTTP2_SEND_MESSAGE_PER_WRITE(exec_ctx, value) \ grpc_stats_inc_http2_send_message_per_write((exec_ctx), (int)(value)) -void grpc_stats_inc_http2_send_message_per_write(grpc_exec_ctx *exec_ctx, +void grpc_stats_inc_http2_send_message_per_write(grpc_exec_ctx* exec_ctx, int x); #define GRPC_STATS_INC_HTTP2_SEND_TRAILING_METADATA_PER_WRITE(exec_ctx, value) \ grpc_stats_inc_http2_send_trailing_metadata_per_write((exec_ctx), \ (int)(value)) void grpc_stats_inc_http2_send_trailing_metadata_per_write( - grpc_exec_ctx *exec_ctx, int x); + grpc_exec_ctx* exec_ctx, int x); #define GRPC_STATS_INC_HTTP2_SEND_FLOWCTL_PER_WRITE(exec_ctx, value) \ grpc_stats_inc_http2_send_flowctl_per_write((exec_ctx), (int)(value)) -void grpc_stats_inc_http2_send_flowctl_per_write(grpc_exec_ctx *exec_ctx, +void grpc_stats_inc_http2_send_flowctl_per_write(grpc_exec_ctx* exec_ctx, int x); #define GRPC_STATS_INC_SERVER_CQS_CHECKED(exec_ctx, value) \ grpc_stats_inc_server_cqs_checked((exec_ctx), (int)(value)) -void grpc_stats_inc_server_cqs_checked(grpc_exec_ctx *exec_ctx, int x); +void grpc_stats_inc_server_cqs_checked(grpc_exec_ctx* exec_ctx, int x); extern const int grpc_stats_histo_buckets[13]; extern const int grpc_stats_histo_start[13]; -extern const int *const grpc_stats_histo_bucket_boundaries[13]; -extern void (*const grpc_stats_inc_histogram[13])(grpc_exec_ctx *exec_ctx, +extern const int* const grpc_stats_histo_bucket_boundaries[13]; +extern void (*const grpc_stats_inc_histogram[13])(grpc_exec_ctx* exec_ctx, int x); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_DEBUG_STATS_DATA_H */ diff --git a/src/core/lib/debug/trace.cc b/src/core/lib/debug/trace.cc index 21b0d8c3a67..a76c1afb4c5 100644 --- a/src/core/lib/debug/trace.cc +++ b/src/core/lib/debug/trace.cc @@ -25,46 +25,81 @@ #include #include "src/core/lib/support/env.h" -int grpc_tracer_set_enabled(const char *name, int enabled); - -typedef struct tracer { - grpc_tracer_flag *flag; - struct tracer *next; -} tracer; -static tracer *tracers; - -#ifdef GRPC_THREADSAFE_TRACER -#define TRACER_SET(flag, on) gpr_atm_no_barrier_store(&(flag).value, (on)) -#else -#define TRACER_SET(flag, on) (flag).value = (on) -#endif - -void grpc_register_tracer(grpc_tracer_flag *flag) { - tracer *t = (tracer *)gpr_malloc(sizeof(*t)); - t->flag = flag; - t->next = tracers; - TRACER_SET(*flag, false); - tracers = t; +int grpc_tracer_set_enabled(const char* name, int enabled); + +namespace grpc_core { + +TraceFlag* TraceFlagList::root_tracer_ = nullptr; + +bool TraceFlagList::Set(const char* name, bool enabled) { + TraceFlag* t; + if (0 == strcmp(name, "all")) { + for (t = root_tracer_; t; t = t->next_tracer_) { + t->set_enabled(enabled); + } + } else if (0 == strcmp(name, "list_tracers")) { + LogAllTracers(); + } else if (0 == strcmp(name, "refcount")) { + for (t = root_tracer_; t; t = t->next_tracer_) { + if (strstr(t->name_, "refcount") != nullptr) { + t->set_enabled(enabled); + } + } + } else { + bool found = false; + for (t = root_tracer_; t; t = t->next_tracer_) { + if (0 == strcmp(name, t->name_)) { + t->set_enabled(enabled); + found = true; + } + } + if (!found) { + gpr_log(GPR_ERROR, "Unknown trace var: '%s'", name); + return false; /* early return */ + } + } + return true; +} + +void TraceFlagList::Add(TraceFlag* flag) { + flag->next_tracer_ = root_tracer_; + root_tracer_ = flag; +} + +void TraceFlagList::LogAllTracers() { + gpr_log(GPR_DEBUG, "available tracers:"); + TraceFlag* t; + for (t = root_tracer_; t != nullptr; t = t->next_tracer_) { + gpr_log(GPR_DEBUG, "\t%s", t->name_); + } } -static void add(const char *beg, const char *end, char ***ss, size_t *ns) { +// Flags register themselves on the list during construction +TraceFlag::TraceFlag(bool default_enabled, const char* name) : name_(name) { + set_enabled(default_enabled); + TraceFlagList::Add(this); +} + +} // namespace grpc_core + +static void add(const char* beg, const char* end, char*** ss, size_t* ns) { size_t n = *ns; size_t np = n + 1; - char *s; + char* s; size_t len; GPR_ASSERT(end >= beg); len = (size_t)(end - beg); - s = (char *)gpr_malloc(len + 1); + s = (char*)gpr_malloc(len + 1); memcpy(s, beg, len); s[len] = 0; - *ss = (char **)gpr_realloc(*ss, sizeof(char **) * np); + *ss = (char**)gpr_realloc(*ss, sizeof(char**) * np); (*ss)[n] = s; *ns = np; } -static void split(const char *s, char ***ss, size_t *ns) { - const char *c = strchr(s, ','); - if (c == NULL) { +static void split(const char* s, char*** ss, size_t* ns) { + const char* c = strchr(s, ','); + if (c == nullptr) { add(s, s + strlen(s), ss, ns); } else { add(s, c, ss, ns); @@ -72,17 +107,17 @@ static void split(const char *s, char ***ss, size_t *ns) { } } -static void parse(const char *s) { - char **strings = NULL; +static void parse(const char* s) { + char** strings = nullptr; size_t nstrings = 0; size_t i; split(s, &strings, &nstrings); for (i = 0; i < nstrings; i++) { if (strings[i][0] == '-') { - grpc_tracer_set_enabled(strings[i] + 1, 0); + grpc_core::TraceFlagList::Set(strings[i] + 1, false); } else { - grpc_tracer_set_enabled(strings[i], 1); + grpc_core::TraceFlagList::Set(strings[i], true); } } @@ -92,56 +127,16 @@ static void parse(const char *s) { gpr_free(strings); } -static void list_tracers() { - gpr_log(GPR_DEBUG, "available tracers:"); - tracer *t; - for (t = tracers; t; t = t->next) { - gpr_log(GPR_DEBUG, "\t%s", t->flag->name); - } -} - -void grpc_tracer_init(const char *env_var) { - char *e = gpr_getenv(env_var); - if (e != NULL) { +void grpc_tracer_init(const char* env_var) { + char* e = gpr_getenv(env_var); + if (e != nullptr) { parse(e); gpr_free(e); } } -void grpc_tracer_shutdown(void) { - while (tracers) { - tracer *t = tracers; - tracers = t->next; - gpr_free(t); - } -} +void grpc_tracer_shutdown(void) {} -int grpc_tracer_set_enabled(const char *name, int enabled) { - tracer *t; - if (0 == strcmp(name, "all")) { - for (t = tracers; t; t = t->next) { - TRACER_SET(*t->flag, enabled); - } - } else if (0 == strcmp(name, "list_tracers")) { - list_tracers(); - } else if (0 == strcmp(name, "refcount")) { - for (t = tracers; t; t = t->next) { - if (strstr(t->flag->name, "refcount") != NULL) { - TRACER_SET(*t->flag, enabled); - } - } - } else { - int found = 0; - for (t = tracers; t; t = t->next) { - if (0 == strcmp(name, t->flag->name)) { - TRACER_SET(*t->flag, enabled); - found = 1; - } - } - if (!found) { - gpr_log(GPR_ERROR, "Unknown trace var: '%s'", name); - return 0; /* early return */ - } - } - return 1; +int grpc_tracer_set_enabled(const char* name, int enabled) { + return grpc_core::TraceFlagList::Set(name, enabled != 0); } diff --git a/src/core/lib/debug/trace.h b/src/core/lib/debug/trace.h index 558ba942bbb..69ddd802222 100644 --- a/src/core/lib/debug/trace.h +++ b/src/core/lib/debug/trace.h @@ -23,9 +23,8 @@ #include #include -#ifdef __cplusplus -extern "C" { -#endif +void grpc_tracer_init(const char* env_var_name); +void grpc_tracer_shutdown(void); #if defined(__has_feature) #if __has_feature(thread_sanitizer) @@ -33,31 +32,72 @@ extern "C" { #endif #endif -typedef struct { +namespace grpc_core { + +class TraceFlag; +class TraceFlagList { + public: + static bool Set(const char* name, bool enabled); + static void Add(TraceFlag* flag); + + private: + static void LogAllTracers(); + static TraceFlag* root_tracer_; +}; + +namespace testing { +void grpc_tracer_enable_flag(grpc_core::TraceFlag* flag); +} + +class TraceFlag { + public: + TraceFlag(bool default_enabled, const char* name); + ~TraceFlag() {} + + const char* name() const { return name_; } + + bool enabled() { +#ifdef GRPC_THREADSAFE_TRACER + return gpr_atm_no_barrier_load(&value_) != 0; +#else + return value_; +#endif + } + + private: + friend void grpc_core::testing::grpc_tracer_enable_flag(TraceFlag* flag); + friend class TraceFlagList; + + void set_enabled(bool enabled) { #ifdef GRPC_THREADSAFE_TRACER - gpr_atm value; + gpr_atm_no_barrier_store(&value_, enabled); #else - bool value; + value_ = enabled; #endif - const char *name; -} grpc_tracer_flag; + } + TraceFlag* next_tracer_; + const char* const name_; #ifdef GRPC_THREADSAFE_TRACER -#define GRPC_TRACER_ON(flag) (gpr_atm_no_barrier_load(&(flag).value) != 0) -#define GRPC_TRACER_INITIALIZER(on, name) \ - { (gpr_atm)(on), (name) } + gpr_atm value_; #else -#define GRPC_TRACER_ON(flag) ((flag).value) -#define GRPC_TRACER_INITIALIZER(on, name) \ - { (on), (name) } + bool value_; #endif +}; -void grpc_register_tracer(grpc_tracer_flag *flag); -void grpc_tracer_init(const char *env_var_name); -void grpc_tracer_shutdown(void); +#ifndef NDEBUG +typedef TraceFlag DebugOnlyTraceFlag; +#else +class DebugOnlyTraceFlag { + public: + DebugOnlyTraceFlag(bool default_enabled, const char* name) {} + bool enabled() { return false; } -#ifdef __cplusplus -} + private: + void set_enabled(bool enabled) {} +}; #endif +} // namespace grpc_core + #endif /* GRPC_CORE_LIB_DEBUG_TRACE_H */ diff --git a/src/core/lib/http/format_request.cc b/src/core/lib/http/format_request.cc index 88fb0ab0b66..f3f3cbda7b2 100644 --- a/src/core/lib/http/format_request.cc +++ b/src/core/lib/http/format_request.cc @@ -28,8 +28,8 @@ #include #include "src/core/lib/support/string.h" -static void fill_common_header(const grpc_httpcli_request *request, - gpr_strvec *buf, bool connection_close) { +static void fill_common_header(const grpc_httpcli_request* request, + gpr_strvec* buf, bool connection_close) { size_t i; gpr_strvec_add(buf, gpr_strdup(request->http.path)); gpr_strvec_add(buf, gpr_strdup(" HTTP/1.0\r\n")); @@ -51,9 +51,9 @@ static void fill_common_header(const grpc_httpcli_request *request, } grpc_slice grpc_httpcli_format_get_request( - const grpc_httpcli_request *request) { + const grpc_httpcli_request* request) { gpr_strvec out; - char *flat; + char* flat; size_t flat_len; gpr_strvec_init(&out); @@ -67,11 +67,11 @@ grpc_slice grpc_httpcli_format_get_request( return grpc_slice_new(flat, flat_len, gpr_free); } -grpc_slice grpc_httpcli_format_post_request(const grpc_httpcli_request *request, - const char *body_bytes, +grpc_slice grpc_httpcli_format_post_request(const grpc_httpcli_request* request, + const char* body_bytes, size_t body_size) { gpr_strvec out; - char *tmp; + char* tmp; size_t out_len; size_t i; @@ -98,7 +98,7 @@ grpc_slice grpc_httpcli_format_post_request(const grpc_httpcli_request *request, gpr_strvec_destroy(&out); if (body_bytes) { - tmp = (char *)gpr_realloc(tmp, out_len + body_size); + tmp = (char*)gpr_realloc(tmp, out_len + body_size); memcpy(tmp + out_len, body_bytes, body_size); out_len += body_size; } @@ -107,14 +107,14 @@ grpc_slice grpc_httpcli_format_post_request(const grpc_httpcli_request *request, } grpc_slice grpc_httpcli_format_connect_request( - const grpc_httpcli_request *request) { + const grpc_httpcli_request* request) { gpr_strvec out; gpr_strvec_init(&out); gpr_strvec_add(&out, gpr_strdup("CONNECT ")); fill_common_header(request, &out, false); gpr_strvec_add(&out, gpr_strdup("\r\n")); size_t flat_len; - char *flat = gpr_strvec_flatten(&out, &flat_len); + char* flat = gpr_strvec_flatten(&out, &flat_len); gpr_strvec_destroy(&out); return grpc_slice_new(flat, flat_len, gpr_free); } diff --git a/src/core/lib/http/format_request.h b/src/core/lib/http/format_request.h index 2e77e8661a7..c1919651f96 100644 --- a/src/core/lib/http/format_request.h +++ b/src/core/lib/http/format_request.h @@ -22,19 +22,11 @@ #include #include "src/core/lib/http/httpcli.h" -#ifdef __cplusplus -extern "C" { -#endif - -grpc_slice grpc_httpcli_format_get_request(const grpc_httpcli_request *request); -grpc_slice grpc_httpcli_format_post_request(const grpc_httpcli_request *request, - const char *body_bytes, +grpc_slice grpc_httpcli_format_get_request(const grpc_httpcli_request* request); +grpc_slice grpc_httpcli_format_post_request(const grpc_httpcli_request* request, + const char* body_bytes, size_t body_size); grpc_slice grpc_httpcli_format_connect_request( - const grpc_httpcli_request *request); - -#ifdef __cplusplus -} -#endif + const grpc_httpcli_request* request); #endif /* GRPC_CORE_LIB_HTTP_FORMAT_REQUEST_H */ diff --git a/src/core/lib/http/httpcli.cc b/src/core/lib/http/httpcli.cc index c96800b85c7..73b484b06d7 100644 --- a/src/core/lib/http/httpcli.cc +++ b/src/core/lib/http/httpcli.cc @@ -39,64 +39,64 @@ typedef struct { grpc_slice request_text; grpc_http_parser parser; - grpc_resolved_addresses *addresses; + grpc_resolved_addresses* addresses; size_t next_address; - grpc_endpoint *ep; - char *host; - char *ssl_host_override; + grpc_endpoint* ep; + char* host; + char* ssl_host_override; grpc_millis deadline; int have_read_byte; - const grpc_httpcli_handshaker *handshaker; - grpc_closure *on_done; - grpc_httpcli_context *context; - grpc_polling_entity *pollent; + const grpc_httpcli_handshaker* handshaker; + grpc_closure* on_done; + grpc_httpcli_context* context; + grpc_polling_entity* pollent; grpc_iomgr_object iomgr_obj; grpc_slice_buffer incoming; grpc_slice_buffer outgoing; grpc_closure on_read; grpc_closure done_write; grpc_closure connected; - grpc_error *overall_error; - grpc_resource_quota *resource_quota; + grpc_error* overall_error; + grpc_resource_quota* resource_quota; } internal_request; -static grpc_httpcli_get_override g_get_override = NULL; -static grpc_httpcli_post_override g_post_override = NULL; +static grpc_httpcli_get_override g_get_override = nullptr; +static grpc_httpcli_post_override g_post_override = nullptr; -static void plaintext_handshake(grpc_exec_ctx *exec_ctx, void *arg, - grpc_endpoint *endpoint, const char *host, +static void plaintext_handshake(grpc_exec_ctx* exec_ctx, void* arg, + grpc_endpoint* endpoint, const char* host, grpc_millis deadline, - void (*on_done)(grpc_exec_ctx *exec_ctx, - void *arg, - grpc_endpoint *endpoint)) { + void (*on_done)(grpc_exec_ctx* exec_ctx, + void* arg, + grpc_endpoint* endpoint)) { on_done(exec_ctx, arg, endpoint); } const grpc_httpcli_handshaker grpc_httpcli_plaintext = {"http", plaintext_handshake}; -void grpc_httpcli_context_init(grpc_httpcli_context *context) { +void grpc_httpcli_context_init(grpc_httpcli_context* context) { context->pollset_set = grpc_pollset_set_create(); } -void grpc_httpcli_context_destroy(grpc_exec_ctx *exec_ctx, - grpc_httpcli_context *context) { +void grpc_httpcli_context_destroy(grpc_exec_ctx* exec_ctx, + grpc_httpcli_context* context) { grpc_pollset_set_destroy(exec_ctx, context->pollset_set); } -static void next_address(grpc_exec_ctx *exec_ctx, internal_request *req, - grpc_error *due_to_error); +static void next_address(grpc_exec_ctx* exec_ctx, internal_request* req, + grpc_error* due_to_error); -static void finish(grpc_exec_ctx *exec_ctx, internal_request *req, - grpc_error *error) { +static void finish(grpc_exec_ctx* exec_ctx, internal_request* req, + grpc_error* error) { grpc_polling_entity_del_from_pollset_set(exec_ctx, req->pollent, req->context->pollset_set); GRPC_CLOSURE_SCHED(exec_ctx, req->on_done, error); grpc_http_parser_destroy(&req->parser); - if (req->addresses != NULL) { + if (req->addresses != nullptr) { grpc_resolved_addresses_destroy(req->addresses); } - if (req->ep != NULL) { + if (req->ep != nullptr) { grpc_endpoint_destroy(exec_ctx, req->ep); } grpc_slice_unref_internal(exec_ctx, req->request_text); @@ -110,13 +110,13 @@ static void finish(grpc_exec_ctx *exec_ctx, internal_request *req, gpr_free(req); } -static void append_error(internal_request *req, grpc_error *error) { +static void append_error(internal_request* req, grpc_error* error) { if (req->overall_error == GRPC_ERROR_NONE) { req->overall_error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed HTTP/1 client request"); } - grpc_resolved_address *addr = &req->addresses->addrs[req->next_address - 1]; - char *addr_text = grpc_sockaddr_to_uri(addr); + grpc_resolved_address* addr = &req->addresses->addrs[req->next_address - 1]; + char* addr_text = grpc_sockaddr_to_uri(addr); req->overall_error = grpc_error_add_child( req->overall_error, grpc_error_set_str(error, GRPC_ERROR_STR_TARGET_ADDRESS, @@ -124,20 +124,20 @@ static void append_error(internal_request *req, grpc_error *error) { gpr_free(addr_text); } -static void do_read(grpc_exec_ctx *exec_ctx, internal_request *req) { +static void do_read(grpc_exec_ctx* exec_ctx, internal_request* req) { grpc_endpoint_read(exec_ctx, req->ep, &req->incoming, &req->on_read); } -static void on_read(grpc_exec_ctx *exec_ctx, void *user_data, - grpc_error *error) { - internal_request *req = (internal_request *)user_data; +static void on_read(grpc_exec_ctx* exec_ctx, void* user_data, + grpc_error* error) { + internal_request* req = (internal_request*)user_data; size_t i; for (i = 0; i < req->incoming.count; i++) { if (GRPC_SLICE_LENGTH(req->incoming.slices[i])) { req->have_read_byte = 1; - grpc_error *err = - grpc_http_parser_parse(&req->parser, req->incoming.slices[i], NULL); + grpc_error* err = grpc_http_parser_parse( + &req->parser, req->incoming.slices[i], nullptr); if (err != GRPC_ERROR_NONE) { finish(exec_ctx, req, err); return; @@ -154,12 +154,12 @@ static void on_read(grpc_exec_ctx *exec_ctx, void *user_data, } } -static void on_written(grpc_exec_ctx *exec_ctx, internal_request *req) { +static void on_written(grpc_exec_ctx* exec_ctx, internal_request* req) { do_read(exec_ctx, req); } -static void done_write(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { - internal_request *req = (internal_request *)arg; +static void done_write(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { + internal_request* req = (internal_request*)arg; if (error == GRPC_ERROR_NONE) { on_written(exec_ctx, req); } else { @@ -167,19 +167,20 @@ static void done_write(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { } } -static void start_write(grpc_exec_ctx *exec_ctx, internal_request *req) { +static void start_write(grpc_exec_ctx* exec_ctx, internal_request* req) { grpc_slice_ref_internal(req->request_text); grpc_slice_buffer_add(&req->outgoing, req->request_text); grpc_endpoint_write(exec_ctx, req->ep, &req->outgoing, &req->done_write); } -static void on_handshake_done(grpc_exec_ctx *exec_ctx, void *arg, - grpc_endpoint *ep) { - internal_request *req = (internal_request *)arg; +static void on_handshake_done(grpc_exec_ctx* exec_ctx, void* arg, + grpc_endpoint* ep) { + internal_request* req = (internal_request*)arg; if (!ep) { - next_address(exec_ctx, req, GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "Unexplained handshake failure")); + next_address( + exec_ctx, req, + GRPC_ERROR_CREATE_FROM_STATIC_STRING("Unexplained handshake failure")); return; } @@ -187,9 +188,9 @@ static void on_handshake_done(grpc_exec_ctx *exec_ctx, void *arg, start_write(exec_ctx, req); } -static void on_connected(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - internal_request *req = (internal_request *)arg; +static void on_connected(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + internal_request* req = (internal_request*)arg; if (!req->ep) { next_address(exec_ctx, req, GRPC_ERROR_REF(error)); @@ -201,9 +202,9 @@ static void on_connected(grpc_exec_ctx *exec_ctx, void *arg, req->deadline, on_handshake_done); } -static void next_address(grpc_exec_ctx *exec_ctx, internal_request *req, - grpc_error *error) { - grpc_resolved_address *addr; +static void next_address(grpc_exec_ctx* exec_ctx, internal_request* req, + grpc_error* error) { + grpc_resolved_address* addr; if (error != GRPC_ERROR_NONE) { append_error(req, error); } @@ -217,7 +218,7 @@ static void next_address(grpc_exec_ctx *exec_ctx, internal_request *req, GRPC_CLOSURE_INIT(&req->connected, on_connected, req, grpc_schedule_on_exec_ctx); grpc_arg arg = grpc_channel_arg_pointer_create( - (char *)GRPC_ARG_RESOURCE_QUOTA, req->resource_quota, + (char*)GRPC_ARG_RESOURCE_QUOTA, req->resource_quota, grpc_resource_quota_arg_vtable()); grpc_channel_args args = {1, &arg}; grpc_tcp_client_connect(exec_ctx, &req->connected, &req->ep, @@ -225,8 +226,8 @@ static void next_address(grpc_exec_ctx *exec_ctx, internal_request *req, req->deadline); } -static void on_resolved(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { - internal_request *req = (internal_request *)arg; +static void on_resolved(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { + internal_request* req = (internal_request*)arg; if (error != GRPC_ERROR_NONE) { finish(exec_ctx, req, GRPC_ERROR_REF(error)); return; @@ -235,16 +236,16 @@ static void on_resolved(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { next_address(exec_ctx, req, GRPC_ERROR_NONE); } -static void internal_request_begin(grpc_exec_ctx *exec_ctx, - grpc_httpcli_context *context, - grpc_polling_entity *pollent, - grpc_resource_quota *resource_quota, - const grpc_httpcli_request *request, - grpc_millis deadline, grpc_closure *on_done, - grpc_httpcli_response *response, - const char *name, grpc_slice request_text) { - internal_request *req = - (internal_request *)gpr_malloc(sizeof(internal_request)); +static void internal_request_begin(grpc_exec_ctx* exec_ctx, + grpc_httpcli_context* context, + grpc_polling_entity* pollent, + grpc_resource_quota* resource_quota, + const grpc_httpcli_request* request, + grpc_millis deadline, grpc_closure* on_done, + grpc_httpcli_response* response, + const char* name, grpc_slice request_text) { + internal_request* req = + (internal_request*)gpr_malloc(sizeof(internal_request)); memset(req, 0, sizeof(*req)); req->request_text = request_text; grpc_http_parser_init(&req->parser, GRPC_HTTP_RESPONSE, response); @@ -275,12 +276,12 @@ static void internal_request_begin(grpc_exec_ctx *exec_ctx, &req->addresses); } -void grpc_httpcli_get(grpc_exec_ctx *exec_ctx, grpc_httpcli_context *context, - grpc_polling_entity *pollent, - grpc_resource_quota *resource_quota, - const grpc_httpcli_request *request, grpc_millis deadline, - grpc_closure *on_done, grpc_httpcli_response *response) { - char *name; +void grpc_httpcli_get(grpc_exec_ctx* exec_ctx, grpc_httpcli_context* context, + grpc_polling_entity* pollent, + grpc_resource_quota* resource_quota, + const grpc_httpcli_request* request, grpc_millis deadline, + grpc_closure* on_done, grpc_httpcli_response* response) { + char* name; if (g_get_override && g_get_override(exec_ctx, request, deadline, on_done, response)) { return; @@ -292,14 +293,14 @@ void grpc_httpcli_get(grpc_exec_ctx *exec_ctx, grpc_httpcli_context *context, gpr_free(name); } -void grpc_httpcli_post(grpc_exec_ctx *exec_ctx, grpc_httpcli_context *context, - grpc_polling_entity *pollent, - grpc_resource_quota *resource_quota, - const grpc_httpcli_request *request, - const char *body_bytes, size_t body_size, - grpc_millis deadline, grpc_closure *on_done, - grpc_httpcli_response *response) { - char *name; +void grpc_httpcli_post(grpc_exec_ctx* exec_ctx, grpc_httpcli_context* context, + grpc_polling_entity* pollent, + grpc_resource_quota* resource_quota, + const grpc_httpcli_request* request, + const char* body_bytes, size_t body_size, + grpc_millis deadline, grpc_closure* on_done, + grpc_httpcli_response* response) { + char* name; if (g_post_override && g_post_override(exec_ctx, request, body_bytes, body_size, deadline, on_done, response)) { diff --git a/src/core/lib/http/httpcli.h b/src/core/lib/http/httpcli.h index 76b790fa8ac..6f675568bd0 100644 --- a/src/core/lib/http/httpcli.h +++ b/src/core/lib/http/httpcli.h @@ -32,23 +32,19 @@ /* User agent this library reports */ #define GRPC_HTTPCLI_USER_AGENT "grpc-httpcli/0.0" -#ifdef __cplusplus -extern "C" { -#endif - /* Tracks in-progress http requests TODO(ctiller): allow caching and capturing multiple requests for the same content and combining them */ typedef struct grpc_httpcli_context { - grpc_pollset_set *pollset_set; + grpc_pollset_set* pollset_set; } grpc_httpcli_context; typedef struct { - const char *default_port; - void (*handshake)(grpc_exec_ctx *exec_ctx, void *arg, grpc_endpoint *endpoint, - const char *host, grpc_millis deadline, - void (*on_done)(grpc_exec_ctx *exec_ctx, void *arg, - grpc_endpoint *endpoint)); + const char* default_port; + void (*handshake)(grpc_exec_ctx* exec_ctx, void* arg, grpc_endpoint* endpoint, + const char* host, grpc_millis deadline, + void (*on_done)(grpc_exec_ctx* exec_ctx, void* arg, + grpc_endpoint* endpoint)); } grpc_httpcli_handshaker; extern const grpc_httpcli_handshaker grpc_httpcli_plaintext; @@ -57,23 +53,23 @@ extern const grpc_httpcli_handshaker grpc_httpcli_ssl; /* A request */ typedef struct grpc_httpcli_request { /* The host name to connect to */ - char *host; + char* host; /* The host to verify in the SSL handshake (or NULL) */ - char *ssl_host_override; + char* ssl_host_override; /* The main part of the request The following headers are supplied automatically and MUST NOT be set here: Host, Connection, User-Agent */ grpc_http_request http; /* handshaker to use ssl for the request */ - const grpc_httpcli_handshaker *handshaker; + const grpc_httpcli_handshaker* handshaker; } grpc_httpcli_request; /* Expose the parser response type as a httpcli response too */ typedef struct grpc_http_response grpc_httpcli_response; -void grpc_httpcli_context_init(grpc_httpcli_context *context); -void grpc_httpcli_context_destroy(grpc_exec_ctx *exec_ctx, - grpc_httpcli_context *context); +void grpc_httpcli_context_init(grpc_httpcli_context* context); +void grpc_httpcli_context_destroy(grpc_exec_ctx* exec_ctx, + grpc_httpcli_context* context); /* Asynchronously perform a HTTP GET. 'context' specifies the http context under which to do the get @@ -84,12 +80,12 @@ void grpc_httpcli_context_destroy(grpc_exec_ctx *exec_ctx, destroyed once the call returns 'deadline' contains a deadline for the request (or gpr_inf_future) 'on_response' is a callback to report results to */ -void grpc_httpcli_get(grpc_exec_ctx *exec_ctx, grpc_httpcli_context *context, - grpc_polling_entity *pollent, - grpc_resource_quota *resource_quota, - const grpc_httpcli_request *request, grpc_millis deadline, - grpc_closure *on_complete, - grpc_httpcli_response *response); +void grpc_httpcli_get(grpc_exec_ctx* exec_ctx, grpc_httpcli_context* context, + grpc_polling_entity* pollent, + grpc_resource_quota* resource_quota, + const grpc_httpcli_request* request, grpc_millis deadline, + grpc_closure* on_complete, + grpc_httpcli_response* response); /* Asynchronously perform a HTTP POST. 'context' specifies the http context under which to do the post @@ -105,30 +101,26 @@ void grpc_httpcli_get(grpc_exec_ctx *exec_ctx, grpc_httpcli_context *context, lifetime of the request 'on_response' is a callback to report results to Does not support ?var1=val1&var2=val2 in the path. */ -void grpc_httpcli_post(grpc_exec_ctx *exec_ctx, grpc_httpcli_context *context, - grpc_polling_entity *pollent, - grpc_resource_quota *resource_quota, - const grpc_httpcli_request *request, - const char *body_bytes, size_t body_size, - grpc_millis deadline, grpc_closure *on_complete, - grpc_httpcli_response *response); +void grpc_httpcli_post(grpc_exec_ctx* exec_ctx, grpc_httpcli_context* context, + grpc_polling_entity* pollent, + grpc_resource_quota* resource_quota, + const grpc_httpcli_request* request, + const char* body_bytes, size_t body_size, + grpc_millis deadline, grpc_closure* on_complete, + grpc_httpcli_response* response); /* override functions return 1 if they handled the request, 0 otherwise */ -typedef int (*grpc_httpcli_get_override)(grpc_exec_ctx *exec_ctx, - const grpc_httpcli_request *request, +typedef int (*grpc_httpcli_get_override)(grpc_exec_ctx* exec_ctx, + const grpc_httpcli_request* request, grpc_millis deadline, - grpc_closure *on_complete, - grpc_httpcli_response *response); + grpc_closure* on_complete, + grpc_httpcli_response* response); typedef int (*grpc_httpcli_post_override)( - grpc_exec_ctx *exec_ctx, const grpc_httpcli_request *request, - const char *body_bytes, size_t body_size, grpc_millis deadline, - grpc_closure *on_complete, grpc_httpcli_response *response); + grpc_exec_ctx* exec_ctx, const grpc_httpcli_request* request, + const char* body_bytes, size_t body_size, grpc_millis deadline, + grpc_closure* on_complete, grpc_httpcli_response* response); void grpc_httpcli_set_override(grpc_httpcli_get_override get, grpc_httpcli_post_override post); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_HTTP_HTTPCLI_H */ diff --git a/src/core/lib/http/httpcli_security_connector.cc b/src/core/lib/http/httpcli_security_connector.cc index d832dacb69f..dfcaee702ba 100644 --- a/src/core/lib/http/httpcli_security_connector.cc +++ b/src/core/lib/http/httpcli_security_connector.cc @@ -34,29 +34,29 @@ typedef struct { grpc_channel_security_connector base; - tsi_ssl_client_handshaker_factory *handshaker_factory; - char *secure_peer_name; + tsi_ssl_client_handshaker_factory* handshaker_factory; + char* secure_peer_name; } grpc_httpcli_ssl_channel_security_connector; -static void httpcli_ssl_destroy(grpc_exec_ctx *exec_ctx, - grpc_security_connector *sc) { - grpc_httpcli_ssl_channel_security_connector *c = - (grpc_httpcli_ssl_channel_security_connector *)sc; - if (c->handshaker_factory != NULL) { +static void httpcli_ssl_destroy(grpc_exec_ctx* exec_ctx, + grpc_security_connector* sc) { + grpc_httpcli_ssl_channel_security_connector* c = + (grpc_httpcli_ssl_channel_security_connector*)sc; + if (c->handshaker_factory != nullptr) { tsi_ssl_client_handshaker_factory_unref(c->handshaker_factory); - c->handshaker_factory = NULL; + c->handshaker_factory = nullptr; } - if (c->secure_peer_name != NULL) gpr_free(c->secure_peer_name); + if (c->secure_peer_name != nullptr) gpr_free(c->secure_peer_name); gpr_free(sc); } -static void httpcli_ssl_add_handshakers(grpc_exec_ctx *exec_ctx, - grpc_channel_security_connector *sc, - grpc_handshake_manager *handshake_mgr) { - grpc_httpcli_ssl_channel_security_connector *c = - (grpc_httpcli_ssl_channel_security_connector *)sc; - tsi_handshaker *handshaker = NULL; - if (c->handshaker_factory != NULL) { +static void httpcli_ssl_add_handshakers(grpc_exec_ctx* exec_ctx, + grpc_channel_security_connector* sc, + grpc_handshake_manager* handshake_mgr) { + grpc_httpcli_ssl_channel_security_connector* c = + (grpc_httpcli_ssl_channel_security_connector*)sc; + tsi_handshaker* handshaker = nullptr; + if (c->handshaker_factory != nullptr) { tsi_result result = tsi_ssl_client_handshaker_factory_create_handshaker( c->handshaker_factory, c->secure_peer_name, &handshaker); if (result != TSI_OK) { @@ -70,18 +70,18 @@ static void httpcli_ssl_add_handshakers(grpc_exec_ctx *exec_ctx, exec_ctx, tsi_create_adapter_handshaker(handshaker), &sc->base)); } -static void httpcli_ssl_check_peer(grpc_exec_ctx *exec_ctx, - grpc_security_connector *sc, tsi_peer peer, - grpc_auth_context **auth_context, - grpc_closure *on_peer_checked) { - grpc_httpcli_ssl_channel_security_connector *c = - (grpc_httpcli_ssl_channel_security_connector *)sc; - grpc_error *error = GRPC_ERROR_NONE; +static void httpcli_ssl_check_peer(grpc_exec_ctx* exec_ctx, + grpc_security_connector* sc, tsi_peer peer, + grpc_auth_context** auth_context, + grpc_closure* on_peer_checked) { + grpc_httpcli_ssl_channel_security_connector* c = + (grpc_httpcli_ssl_channel_security_connector*)sc; + grpc_error* error = GRPC_ERROR_NONE; /* Check the peer name. */ - if (c->secure_peer_name != NULL && + if (c->secure_peer_name != nullptr && !tsi_ssl_peer_matches_name(&peer, c->secure_peer_name)) { - char *msg; + char* msg; gpr_asprintf(&msg, "Peer name %s is not in peer certificate", c->secure_peer_name); error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); @@ -91,12 +91,12 @@ static void httpcli_ssl_check_peer(grpc_exec_ctx *exec_ctx, tsi_peer_destruct(&peer); } -static int httpcli_ssl_cmp(grpc_security_connector *sc1, - grpc_security_connector *sc2) { - grpc_httpcli_ssl_channel_security_connector *c1 = - (grpc_httpcli_ssl_channel_security_connector *)sc1; - grpc_httpcli_ssl_channel_security_connector *c2 = - (grpc_httpcli_ssl_channel_security_connector *)sc2; +static int httpcli_ssl_cmp(grpc_security_connector* sc1, + grpc_security_connector* sc2) { + grpc_httpcli_ssl_channel_security_connector* c1 = + (grpc_httpcli_ssl_channel_security_connector*)sc1; + grpc_httpcli_ssl_channel_security_connector* c2 = + (grpc_httpcli_ssl_channel_security_connector*)sc2; return strcmp(c1->secure_peer_name, c2->secure_peer_name); } @@ -104,38 +104,38 @@ static grpc_security_connector_vtable httpcli_ssl_vtable = { httpcli_ssl_destroy, httpcli_ssl_check_peer, httpcli_ssl_cmp}; static grpc_security_status httpcli_ssl_channel_security_connector_create( - grpc_exec_ctx *exec_ctx, const char *pem_root_certs, - const char *secure_peer_name, grpc_channel_security_connector **sc) { + grpc_exec_ctx* exec_ctx, const char* pem_root_certs, + const char* secure_peer_name, grpc_channel_security_connector** sc) { tsi_result result = TSI_OK; - grpc_httpcli_ssl_channel_security_connector *c; + grpc_httpcli_ssl_channel_security_connector* c; - if (secure_peer_name != NULL && pem_root_certs == NULL) { + if (secure_peer_name != nullptr && pem_root_certs == nullptr) { gpr_log(GPR_ERROR, "Cannot assert a secure peer name without a trust root."); return GRPC_SECURITY_ERROR; } - c = (grpc_httpcli_ssl_channel_security_connector *)gpr_zalloc( + c = (grpc_httpcli_ssl_channel_security_connector*)gpr_zalloc( sizeof(grpc_httpcli_ssl_channel_security_connector)); gpr_ref_init(&c->base.base.refcount, 1); c->base.base.vtable = &httpcli_ssl_vtable; - if (secure_peer_name != NULL) { + if (secure_peer_name != nullptr) { c->secure_peer_name = gpr_strdup(secure_peer_name); } result = tsi_create_ssl_client_handshaker_factory( - NULL, pem_root_certs, NULL, NULL, 0, &c->handshaker_factory); + nullptr, pem_root_certs, nullptr, nullptr, 0, &c->handshaker_factory); if (result != TSI_OK) { gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.", tsi_result_to_string(result)); httpcli_ssl_destroy(exec_ctx, &c->base.base); - *sc = NULL; + *sc = nullptr; return GRPC_SECURITY_ERROR; } // We don't actually need a channel credentials object in this case, // but we set it to a non-NULL address so that we don't trigger // assertions in grpc_channel_security_connector_cmp(). - c->base.channel_creds = (grpc_channel_credentials *)1; + c->base.channel_creds = (grpc_channel_credentials*)1; c->base.add_handshakers = httpcli_ssl_add_handshakers; *sc = &c->base; return GRPC_SECURITY_OK; @@ -144,20 +144,20 @@ static grpc_security_status httpcli_ssl_channel_security_connector_create( /* handshaker */ typedef struct { - void (*func)(grpc_exec_ctx *exec_ctx, void *arg, grpc_endpoint *endpoint); - void *arg; - grpc_handshake_manager *handshake_mgr; + void (*func)(grpc_exec_ctx* exec_ctx, void* arg, grpc_endpoint* endpoint); + void* arg; + grpc_handshake_manager* handshake_mgr; } on_done_closure; -static void on_handshake_done(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_handshaker_args *args = (grpc_handshaker_args *)arg; - on_done_closure *c = (on_done_closure *)args->user_data; +static void on_handshake_done(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_handshaker_args* args = (grpc_handshaker_args*)arg; + on_done_closure* c = (on_done_closure*)args->user_data; if (error != GRPC_ERROR_NONE) { - const char *msg = grpc_error_string(error); + const char* msg = grpc_error_string(error); gpr_log(GPR_ERROR, "Secure transport setup failed: %s", msg); - c->func(exec_ctx, c->arg, NULL); + c->func(exec_ctx, c->arg, nullptr); } else { grpc_channel_args_destroy(exec_ctx, args->args); grpc_slice_buffer_destroy_internal(exec_ctx, args->read_buffer); @@ -168,22 +168,22 @@ static void on_handshake_done(grpc_exec_ctx *exec_ctx, void *arg, gpr_free(c); } -static void ssl_handshake(grpc_exec_ctx *exec_ctx, void *arg, - grpc_endpoint *tcp, const char *host, +static void ssl_handshake(grpc_exec_ctx* exec_ctx, void* arg, + grpc_endpoint* tcp, const char* host, grpc_millis deadline, - void (*on_done)(grpc_exec_ctx *exec_ctx, void *arg, - grpc_endpoint *endpoint)) { - on_done_closure *c = (on_done_closure *)gpr_malloc(sizeof(*c)); - const char *pem_root_certs = grpc_get_default_ssl_roots(); - if (pem_root_certs == NULL) { + void (*on_done)(grpc_exec_ctx* exec_ctx, void* arg, + grpc_endpoint* endpoint)) { + on_done_closure* c = (on_done_closure*)gpr_malloc(sizeof(*c)); + const char* pem_root_certs = grpc_get_default_ssl_roots(); + if (pem_root_certs == nullptr) { gpr_log(GPR_ERROR, "Could not get default pem root certs."); - on_done(exec_ctx, arg, NULL); + on_done(exec_ctx, arg, nullptr); gpr_free(c); return; } c->func = on_done; c->arg = arg; - grpc_channel_security_connector *sc = NULL; + grpc_channel_security_connector* sc = nullptr; GPR_ASSERT(httpcli_ssl_channel_security_connector_create( exec_ctx, pem_root_certs, host, &sc) == GRPC_SECURITY_OK); grpc_arg channel_arg = grpc_security_connector_to_arg(&sc->base); @@ -191,8 +191,9 @@ static void ssl_handshake(grpc_exec_ctx *exec_ctx, void *arg, c->handshake_mgr = grpc_handshake_manager_create(); grpc_handshakers_add(exec_ctx, HANDSHAKER_CLIENT, &args, c->handshake_mgr); grpc_handshake_manager_do_handshake( - exec_ctx, c->handshake_mgr, tcp, NULL /* channel_args */, deadline, - NULL /* acceptor */, on_handshake_done, c /* user_data */); + exec_ctx, c->handshake_mgr, nullptr /* interested_parties */, tcp, + nullptr /* channel_args */, deadline, nullptr /* acceptor */, + on_handshake_done, c /* user_data */); GRPC_SECURITY_CONNECTOR_UNREF(exec_ctx, &sc->base, "httpcli"); } diff --git a/src/core/lib/http/parser.cc b/src/core/lib/http/parser.cc index 0950bd655ef..fb4eb234a79 100644 --- a/src/core/lib/http/parser.cc +++ b/src/core/lib/http/parser.cc @@ -25,19 +25,19 @@ #include #include -grpc_tracer_flag grpc_http1_trace = GRPC_TRACER_INITIALIZER(false, "http1"); +grpc_core::TraceFlag grpc_http1_trace(false, "http1"); -static char *buf2str(void *buffer, size_t length) { - char *out = (char *)gpr_malloc(length + 1); +static char* buf2str(void* buffer, size_t length) { + char* out = (char*)gpr_malloc(length + 1); memcpy(out, buffer, length); out[length] = 0; return out; } -static grpc_error *handle_response_line(grpc_http_parser *parser) { - uint8_t *beg = parser->cur_line; - uint8_t *cur = beg; - uint8_t *end = beg + parser->cur_line_length; +static grpc_error* handle_response_line(grpc_http_parser* parser) { + uint8_t* beg = parser->cur_line; + uint8_t* cur = beg; + uint8_t* end = beg + parser->cur_line_length; if (cur == end || *cur++ != 'H') return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Expected 'H'"); @@ -75,10 +75,10 @@ static grpc_error *handle_response_line(grpc_http_parser *parser) { return GRPC_ERROR_NONE; } -static grpc_error *handle_request_line(grpc_http_parser *parser) { - uint8_t *beg = parser->cur_line; - uint8_t *cur = beg; - uint8_t *end = beg + parser->cur_line_length; +static grpc_error* handle_request_line(grpc_http_parser* parser) { + uint8_t* beg = parser->cur_line; + uint8_t* cur = beg; + uint8_t* end = beg + parser->cur_line_length; uint8_t vers_major = 0; uint8_t vers_minor = 0; @@ -137,7 +137,7 @@ static grpc_error *handle_request_line(grpc_http_parser *parser) { return GRPC_ERROR_NONE; } -static grpc_error *handle_first_line(grpc_http_parser *parser) { +static grpc_error* handle_first_line(grpc_http_parser* parser) { switch (parser->type) { case GRPC_HTTP_REQUEST: return handle_request_line(parser); @@ -148,14 +148,14 @@ static grpc_error *handle_first_line(grpc_http_parser *parser) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Should never reach here")); } -static grpc_error *add_header(grpc_http_parser *parser) { - uint8_t *beg = parser->cur_line; - uint8_t *cur = beg; - uint8_t *end = beg + parser->cur_line_length; - size_t *hdr_count = NULL; - grpc_http_header **hdrs = NULL; - grpc_http_header hdr = {NULL, NULL}; - grpc_error *error = GRPC_ERROR_NONE; +static grpc_error* add_header(grpc_http_parser* parser) { + uint8_t* beg = parser->cur_line; + uint8_t* cur = beg; + uint8_t* end = beg + parser->cur_line_length; + size_t* hdr_count = nullptr; + grpc_http_header** hdrs = nullptr; + grpc_http_header hdr = {nullptr, nullptr}; + grpc_error* error = GRPC_ERROR_NONE; GPR_ASSERT(cur != end); @@ -197,7 +197,7 @@ static grpc_error *add_header(grpc_http_parser *parser) { if (*hdr_count == parser->hdr_capacity) { parser->hdr_capacity = GPR_MAX(parser->hdr_capacity + 1, parser->hdr_capacity * 3 / 2); - *hdrs = (grpc_http_header *)gpr_realloc( + *hdrs = (grpc_http_header*)gpr_realloc( *hdrs, parser->hdr_capacity * sizeof(**hdrs)); } (*hdrs)[(*hdr_count)++] = hdr; @@ -210,9 +210,9 @@ done: return error; } -static grpc_error *finish_line(grpc_http_parser *parser, - bool *found_body_start) { - grpc_error *err; +static grpc_error* finish_line(grpc_http_parser* parser, + bool* found_body_start) { + grpc_error* err; switch (parser->state) { case GRPC_HTTP_FIRST_LINE: err = handle_first_line(parser); @@ -239,9 +239,9 @@ static grpc_error *finish_line(grpc_http_parser *parser, return GRPC_ERROR_NONE; } -static grpc_error *addbyte_body(grpc_http_parser *parser, uint8_t byte) { - size_t *body_length = NULL; - char **body = NULL; +static grpc_error* addbyte_body(grpc_http_parser* parser, uint8_t byte) { + size_t* body_length = nullptr; + char** body = nullptr; if (parser->type == GRPC_HTTP_RESPONSE) { body_length = &parser->http.response->body_length; @@ -256,7 +256,7 @@ static grpc_error *addbyte_body(grpc_http_parser *parser, uint8_t byte) { if (*body_length == parser->body_capacity) { parser->body_capacity = GPR_MAX(8, parser->body_capacity * 3 / 2); - *body = (char *)gpr_realloc((void *)*body, parser->body_capacity); + *body = (char*)gpr_realloc((void*)*body, parser->body_capacity); } (*body)[*body_length] = (char)byte; (*body_length)++; @@ -264,7 +264,7 @@ static grpc_error *addbyte_body(grpc_http_parser *parser, uint8_t byte) { return GRPC_ERROR_NONE; } -static bool check_line(grpc_http_parser *parser) { +static bool check_line(grpc_http_parser* parser) { if (parser->cur_line_length >= 2 && parser->cur_line[parser->cur_line_length - 2] == '\r' && parser->cur_line[parser->cur_line_length - 1] == '\n') { @@ -288,13 +288,13 @@ static bool check_line(grpc_http_parser *parser) { return false; } -static grpc_error *addbyte(grpc_http_parser *parser, uint8_t byte, - bool *found_body_start) { +static grpc_error* addbyte(grpc_http_parser* parser, uint8_t byte, + bool* found_body_start) { switch (parser->state) { case GRPC_HTTP_FIRST_LINE: case GRPC_HTTP_HEADERS: if (parser->cur_line_length >= GRPC_HTTP_PARSER_MAX_HEADER_LENGTH) { - if (GRPC_TRACER_ON(grpc_http1_trace)) + if (grpc_http1_trace.enabled()) gpr_log(GPR_ERROR, "HTTP header max line length (%d) exceeded", GRPC_HTTP_PARSER_MAX_HEADER_LENGTH); return GRPC_ERROR_CREATE_FROM_STATIC_STRING( @@ -312,8 +312,8 @@ static grpc_error *addbyte(grpc_http_parser *parser, uint8_t byte, GPR_UNREACHABLE_CODE(return GRPC_ERROR_NONE); } -void grpc_http_parser_init(grpc_http_parser *parser, grpc_http_type type, - void *request_or_response) { +void grpc_http_parser_init(grpc_http_parser* parser, grpc_http_type type, + void* request_or_response) { memset(parser, 0, sizeof(*parser)); parser->state = GRPC_HTTP_FIRST_LINE; parser->type = type; @@ -321,9 +321,9 @@ void grpc_http_parser_init(grpc_http_parser *parser, grpc_http_type type, parser->cur_line_end_length = 2; } -void grpc_http_parser_destroy(grpc_http_parser *parser) {} +void grpc_http_parser_destroy(grpc_http_parser* parser) {} -void grpc_http_request_destroy(grpc_http_request *request) { +void grpc_http_request_destroy(grpc_http_request* request) { size_t i; gpr_free(request->body); for (i = 0; i < request->hdr_count; i++) { @@ -335,7 +335,7 @@ void grpc_http_request_destroy(grpc_http_request *request) { gpr_free(request->path); } -void grpc_http_response_destroy(grpc_http_response *response) { +void grpc_http_response_destroy(grpc_http_response* response) { size_t i; gpr_free(response->body); for (i = 0; i < response->hdr_count; i++) { @@ -345,19 +345,19 @@ void grpc_http_response_destroy(grpc_http_response *response) { gpr_free(response->hdrs); } -grpc_error *grpc_http_parser_parse(grpc_http_parser *parser, grpc_slice slice, - size_t *start_of_body) { +grpc_error* grpc_http_parser_parse(grpc_http_parser* parser, grpc_slice slice, + size_t* start_of_body) { for (size_t i = 0; i < GRPC_SLICE_LENGTH(slice); i++) { bool found_body_start = false; - grpc_error *err = + grpc_error* err = addbyte(parser, GRPC_SLICE_START_PTR(slice)[i], &found_body_start); if (err != GRPC_ERROR_NONE) return err; - if (found_body_start && start_of_body != NULL) *start_of_body = i + 1; + if (found_body_start && start_of_body != nullptr) *start_of_body = i + 1; } return GRPC_ERROR_NONE; } -grpc_error *grpc_http_parser_eof(grpc_http_parser *parser) { +grpc_error* grpc_http_parser_eof(grpc_http_parser* parser) { if (parser->state != GRPC_HTTP_BODY) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Did not finish headers"); } diff --git a/src/core/lib/http/parser.h b/src/core/lib/http/parser.h index d2bda6ae0e4..5fef4480199 100644 --- a/src/core/lib/http/parser.h +++ b/src/core/lib/http/parser.h @@ -27,14 +27,10 @@ /* Maximum length of a header string of the form 'Key: Value\r\n' */ #define GRPC_HTTP_PARSER_MAX_HEADER_LENGTH 4096 -#ifdef __cplusplus -extern "C" { -#endif - /* A single header to be passed in a request */ typedef struct grpc_http_header { - char *key; - char *value; + char* key; + char* value; } grpc_http_header; typedef enum { @@ -57,17 +53,17 @@ typedef enum { /* A request */ typedef struct grpc_http_request { /* Method of the request (e.g. GET, POST) */ - char *method; + char* method; /* The path of the resource to fetch */ - char *path; + char* path; /* HTTP version to use */ grpc_http_version version; /* Headers attached to the request */ size_t hdr_count; - grpc_http_header *hdrs; + grpc_http_header* hdrs; /* Body: length and contents; contents are NOT null-terminated */ size_t body_length; - char *body; + char* body; } grpc_http_request; /* A response */ @@ -76,10 +72,10 @@ typedef struct grpc_http_response { int status; /* Headers: count and key/values */ size_t hdr_count; - grpc_http_header *hdrs; + grpc_http_header* hdrs; /* Body: length and contents; contents are NOT null-terminated */ size_t body_length; - char *body; + char* body; } grpc_http_response; typedef struct { @@ -87,9 +83,9 @@ typedef struct { grpc_http_type type; union { - grpc_http_response *response; - grpc_http_request *request; - void *request_or_response; + grpc_http_response* response; + grpc_http_request* request; + void* request_or_response; } http; size_t body_capacity; size_t hdr_capacity; @@ -99,22 +95,18 @@ typedef struct { size_t cur_line_end_length; } grpc_http_parser; -void grpc_http_parser_init(grpc_http_parser *parser, grpc_http_type type, - void *request_or_response); -void grpc_http_parser_destroy(grpc_http_parser *parser); +void grpc_http_parser_init(grpc_http_parser* parser, grpc_http_type type, + void* request_or_response); +void grpc_http_parser_destroy(grpc_http_parser* parser); /* Sets \a start_of_body to the offset in \a slice of the start of the body. */ -grpc_error *grpc_http_parser_parse(grpc_http_parser *parser, grpc_slice slice, - size_t *start_of_body); -grpc_error *grpc_http_parser_eof(grpc_http_parser *parser); - -void grpc_http_request_destroy(grpc_http_request *request); -void grpc_http_response_destroy(grpc_http_response *response); +grpc_error* grpc_http_parser_parse(grpc_http_parser* parser, grpc_slice slice, + size_t* start_of_body); +grpc_error* grpc_http_parser_eof(grpc_http_parser* parser); -extern grpc_tracer_flag grpc_http1_trace; +void grpc_http_request_destroy(grpc_http_request* request); +void grpc_http_response_destroy(grpc_http_response* response); -#ifdef __cplusplus -} -#endif +extern grpc_core::TraceFlag grpc_http1_trace; #endif /* GRPC_CORE_LIB_HTTP_PARSER_H */ diff --git a/src/core/lib/iomgr/block_annotate.h b/src/core/lib/iomgr/block_annotate.h index fcbfe9eb1a0..340ebcb1afa 100644 --- a/src/core/lib/iomgr/block_annotate.h +++ b/src/core/lib/iomgr/block_annotate.h @@ -19,17 +19,9 @@ #ifndef GRPC_CORE_LIB_IOMGR_BLOCK_ANNOTATE_H #define GRPC_CORE_LIB_IOMGR_BLOCK_ANNOTATE_H -#ifdef __cplusplus -extern "C" { -#endif - void gpr_thd_start_blocking_region(); void gpr_thd_end_blocking_region(); -#ifdef __cplusplus -} -#endif - /* These annotations identify the beginning and end of regions where the code may block for reasons other than synchronization functions. These include poll, epoll, and getaddrinfo. */ diff --git a/src/core/lib/iomgr/call_combiner.cc b/src/core/lib/iomgr/call_combiner.cc index d45719608b4..b5910b42e42 100644 --- a/src/core/lib/iomgr/call_combiner.cc +++ b/src/core/lib/iomgr/call_combiner.cc @@ -24,8 +24,7 @@ #include "src/core/lib/debug/stats.h" #include "src/core/lib/profiling/timers.h" -grpc_tracer_flag grpc_call_combiner_trace = - GRPC_TRACER_INITIALIZER(false, "call_combiner"); +grpc_core::TraceFlag grpc_call_combiner_trace(false, "call_combiner"); static grpc_error* decode_cancel_state_error(gpr_atm cancel_state) { if (cancel_state & 1) { @@ -63,7 +62,7 @@ void grpc_call_combiner_start(grpc_exec_ctx* exec_ctx, grpc_error* error DEBUG_ARGS, const char* reason) { GPR_TIMER_BEGIN("call_combiner_start", 0); - if (GRPC_TRACER_ON(grpc_call_combiner_trace)) { + if (grpc_call_combiner_trace.enabled()) { gpr_log(GPR_DEBUG, "==> grpc_call_combiner_start() [%p] closure=%p [" DEBUG_FMT_STR "%s] error=%s", @@ -72,7 +71,7 @@ void grpc_call_combiner_start(grpc_exec_ctx* exec_ctx, } size_t prev_size = (size_t)gpr_atm_full_fetch_add(&call_combiner->size, (gpr_atm)1); - if (GRPC_TRACER_ON(grpc_call_combiner_trace)) { + if (grpc_call_combiner_trace.enabled()) { gpr_log(GPR_DEBUG, " size: %" PRIdPTR " -> %" PRIdPTR, prev_size, prev_size + 1); } @@ -80,13 +79,13 @@ void grpc_call_combiner_start(grpc_exec_ctx* exec_ctx, if (prev_size == 0) { GRPC_STATS_INC_CALL_COMBINER_LOCKS_INITIATED(exec_ctx); GPR_TIMER_MARK("call_combiner_initiate", 0); - if (GRPC_TRACER_ON(grpc_call_combiner_trace)) { + if (grpc_call_combiner_trace.enabled()) { gpr_log(GPR_DEBUG, " EXECUTING IMMEDIATELY"); } // Queue was empty, so execute this closure immediately. GRPC_CLOSURE_SCHED(exec_ctx, closure, error); } else { - if (GRPC_TRACER_ON(grpc_call_combiner_trace)) { + if (grpc_call_combiner_trace.enabled()) { gpr_log(GPR_INFO, " QUEUING"); } // Queue was not empty, so add closure to queue. @@ -100,42 +99,42 @@ void grpc_call_combiner_stop(grpc_exec_ctx* exec_ctx, grpc_call_combiner* call_combiner DEBUG_ARGS, const char* reason) { GPR_TIMER_BEGIN("call_combiner_stop", 0); - if (GRPC_TRACER_ON(grpc_call_combiner_trace)) { + if (grpc_call_combiner_trace.enabled()) { gpr_log(GPR_DEBUG, "==> grpc_call_combiner_stop() [%p] [" DEBUG_FMT_STR "%s]", call_combiner DEBUG_FMT_ARGS, reason); } size_t prev_size = (size_t)gpr_atm_full_fetch_add(&call_combiner->size, (gpr_atm)-1); - if (GRPC_TRACER_ON(grpc_call_combiner_trace)) { + if (grpc_call_combiner_trace.enabled()) { gpr_log(GPR_DEBUG, " size: %" PRIdPTR " -> %" PRIdPTR, prev_size, prev_size - 1); } GPR_ASSERT(prev_size >= 1); if (prev_size > 1) { while (true) { - if (GRPC_TRACER_ON(grpc_call_combiner_trace)) { + if (grpc_call_combiner_trace.enabled()) { gpr_log(GPR_DEBUG, " checking queue"); } bool empty; grpc_closure* closure = (grpc_closure*)gpr_mpscq_pop_and_check_end( &call_combiner->queue, &empty); - if (closure == NULL) { + if (closure == nullptr) { // This can happen either due to a race condition within the mpscq // code or because of a race with grpc_call_combiner_start(). - if (GRPC_TRACER_ON(grpc_call_combiner_trace)) { + if (grpc_call_combiner_trace.enabled()) { gpr_log(GPR_DEBUG, " queue returned no result; checking again"); } continue; } - if (GRPC_TRACER_ON(grpc_call_combiner_trace)) { + if (grpc_call_combiner_trace.enabled()) { gpr_log(GPR_DEBUG, " EXECUTING FROM QUEUE: closure=%p error=%s", closure, grpc_error_string(closure->error_data.error)); } GRPC_CLOSURE_SCHED(exec_ctx, closure, closure->error_data.error); break; } - } else if (GRPC_TRACER_ON(grpc_call_combiner_trace)) { + } else if (grpc_call_combiner_trace.enabled()) { gpr_log(GPR_DEBUG, " queue empty"); } GPR_TIMER_END("call_combiner_stop", 0); @@ -152,7 +151,7 @@ void grpc_call_combiner_set_notify_on_cancel(grpc_exec_ctx* exec_ctx, // If error is set, invoke the cancellation closure immediately. // Otherwise, store the new closure. if (original_error != GRPC_ERROR_NONE) { - if (GRPC_TRACER_ON(grpc_call_combiner_trace)) { + if (grpc_call_combiner_trace.enabled()) { gpr_log(GPR_DEBUG, "call_combiner=%p: scheduling notify_on_cancel callback=%p " "for pre-existing cancellation", @@ -163,7 +162,7 @@ void grpc_call_combiner_set_notify_on_cancel(grpc_exec_ctx* exec_ctx, } else { if (gpr_atm_full_cas(&call_combiner->cancel_state, original_state, (gpr_atm)closure)) { - if (GRPC_TRACER_ON(grpc_call_combiner_trace)) { + if (grpc_call_combiner_trace.enabled()) { gpr_log(GPR_DEBUG, "call_combiner=%p: setting notify_on_cancel=%p", call_combiner, closure); } @@ -172,7 +171,7 @@ void grpc_call_combiner_set_notify_on_cancel(grpc_exec_ctx* exec_ctx, // up any resources they may be holding for the callback. if (original_state != 0) { closure = (grpc_closure*)original_state; - if (GRPC_TRACER_ON(grpc_call_combiner_trace)) { + if (grpc_call_combiner_trace.enabled()) { gpr_log(GPR_DEBUG, "call_combiner=%p: scheduling old cancel callback=%p", call_combiner, closure); @@ -201,7 +200,7 @@ void grpc_call_combiner_cancel(grpc_exec_ctx* exec_ctx, encode_cancel_state_error(error))) { if (original_state != 0) { grpc_closure* notify_on_cancel = (grpc_closure*)original_state; - if (GRPC_TRACER_ON(grpc_call_combiner_trace)) { + if (grpc_call_combiner_trace.enabled()) { gpr_log(GPR_DEBUG, "call_combiner=%p: scheduling notify_on_cancel callback=%p", call_combiner, notify_on_cancel); diff --git a/src/core/lib/iomgr/call_combiner.h b/src/core/lib/iomgr/call_combiner.h index 527f84fce04..c07af51c917 100644 --- a/src/core/lib/iomgr/call_combiner.h +++ b/src/core/lib/iomgr/call_combiner.h @@ -27,10 +27,6 @@ #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/support/mpscq.h" -#ifdef __cplusplus -extern "C" { -#endif - // A simple, lock-free mechanism for serializing activity related to a // single call. This is similar to a combiner but is more lightweight. // @@ -40,7 +36,7 @@ extern "C" { // when it is done with the action that was kicked off by the original // callback. -extern grpc_tracer_flag grpc_call_combiner_trace; +extern grpc_core::TraceFlag grpc_call_combiner_trace; typedef struct { gpr_atm size; // size_t, num closures in queue or currently executing @@ -122,8 +118,4 @@ void grpc_call_combiner_cancel(grpc_exec_ctx* exec_ctx, grpc_call_combiner* call_combiner, grpc_error* error); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_CALL_COMBINER_H */ diff --git a/src/core/lib/iomgr/closure.cc b/src/core/lib/iomgr/closure.cc deleted file mode 100644 index 00edefc6ae4..00000000000 --- a/src/core/lib/iomgr/closure.cc +++ /dev/null @@ -1,219 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include "src/core/lib/iomgr/closure.h" - -#include -#include -#include - -#include "src/core/lib/profiling/timers.h" - -#ifndef NDEBUG -grpc_tracer_flag grpc_trace_closure = GRPC_TRACER_INITIALIZER(false, "closure"); -#endif - -#ifndef NDEBUG -grpc_closure *grpc_closure_init(const char *file, int line, - grpc_closure *closure, grpc_iomgr_cb_func cb, - void *cb_arg, - grpc_closure_scheduler *scheduler) { -#else -grpc_closure *grpc_closure_init(grpc_closure *closure, grpc_iomgr_cb_func cb, - void *cb_arg, - grpc_closure_scheduler *scheduler) { -#endif - closure->cb = cb; - closure->cb_arg = cb_arg; - closure->scheduler = scheduler; -#ifndef NDEBUG - closure->scheduled = false; - closure->file_initiated = NULL; - closure->line_initiated = 0; - closure->run = false; - closure->file_created = file; - closure->line_created = line; -#endif - return closure; -} - -void grpc_closure_list_init(grpc_closure_list *closure_list) { - closure_list->head = closure_list->tail = NULL; -} - -bool grpc_closure_list_append(grpc_closure_list *closure_list, - grpc_closure *closure, grpc_error *error) { - if (closure == NULL) { - GRPC_ERROR_UNREF(error); - return false; - } - closure->error_data.error = error; - closure->next_data.next = NULL; - bool was_empty = (closure_list->head == NULL); - if (was_empty) { - closure_list->head = closure; - } else { - closure_list->tail->next_data.next = closure; - } - closure_list->tail = closure; - return was_empty; -} - -void grpc_closure_list_fail_all(grpc_closure_list *list, - grpc_error *forced_failure) { - for (grpc_closure *c = list->head; c != NULL; c = c->next_data.next) { - if (c->error_data.error == GRPC_ERROR_NONE) { - c->error_data.error = GRPC_ERROR_REF(forced_failure); - } - } - GRPC_ERROR_UNREF(forced_failure); -} - -bool grpc_closure_list_empty(grpc_closure_list closure_list) { - return closure_list.head == NULL; -} - -void grpc_closure_list_move(grpc_closure_list *src, grpc_closure_list *dst) { - if (src->head == NULL) { - return; - } - if (dst->head == NULL) { - *dst = *src; - } else { - dst->tail->next_data.next = src->head; - dst->tail = src->tail; - } - src->head = src->tail = NULL; -} - -typedef struct { - grpc_iomgr_cb_func cb; - void *cb_arg; - grpc_closure wrapper; -} wrapped_closure; - -static void closure_wrapper(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - wrapped_closure *wc = (wrapped_closure *)arg; - grpc_iomgr_cb_func cb = wc->cb; - void *cb_arg = wc->cb_arg; - gpr_free(wc); - cb(exec_ctx, cb_arg, error); -} - -#ifndef NDEBUG -grpc_closure *grpc_closure_create(const char *file, int line, - grpc_iomgr_cb_func cb, void *cb_arg, - grpc_closure_scheduler *scheduler) { -#else -grpc_closure *grpc_closure_create(grpc_iomgr_cb_func cb, void *cb_arg, - grpc_closure_scheduler *scheduler) { -#endif - wrapped_closure *wc = (wrapped_closure *)gpr_malloc(sizeof(*wc)); - wc->cb = cb; - wc->cb_arg = cb_arg; -#ifndef NDEBUG - grpc_closure_init(file, line, &wc->wrapper, closure_wrapper, wc, scheduler); -#else - grpc_closure_init(&wc->wrapper, closure_wrapper, wc, scheduler); -#endif - return &wc->wrapper; -} - -#ifndef NDEBUG -void grpc_closure_run(const char *file, int line, grpc_exec_ctx *exec_ctx, - grpc_closure *c, grpc_error *error) { -#else -void grpc_closure_run(grpc_exec_ctx *exec_ctx, grpc_closure *c, - grpc_error *error) { -#endif - GPR_TIMER_BEGIN("grpc_closure_run", 0); - if (c != NULL) { -#ifndef NDEBUG - c->file_initiated = file; - c->line_initiated = line; - c->run = true; -#endif - assert(c->cb); - c->scheduler->vtable->run(exec_ctx, c, error); - } else { - GRPC_ERROR_UNREF(error); - } - GPR_TIMER_END("grpc_closure_run", 0); -} - -#ifndef NDEBUG -void grpc_closure_sched(const char *file, int line, grpc_exec_ctx *exec_ctx, - grpc_closure *c, grpc_error *error) { -#else -void grpc_closure_sched(grpc_exec_ctx *exec_ctx, grpc_closure *c, - grpc_error *error) { -#endif - GPR_TIMER_BEGIN("grpc_closure_sched", 0); - if (c != NULL) { -#ifndef NDEBUG - if (c->scheduled) { - gpr_log(GPR_ERROR, - "Closure already scheduled. (closure: %p, created: [%s:%d], " - "previously scheduled at: [%s: %d] run?: %s", - c, c->file_created, c->line_created, c->file_initiated, - c->line_initiated, c->run ? "true" : "false"); - abort(); - } - c->scheduled = true; - c->file_initiated = file; - c->line_initiated = line; - c->run = false; -#endif - assert(c->cb); - c->scheduler->vtable->sched(exec_ctx, c, error); - } else { - GRPC_ERROR_UNREF(error); - } - GPR_TIMER_END("grpc_closure_sched", 0); -} - -#ifndef NDEBUG -void grpc_closure_list_sched(const char *file, int line, - grpc_exec_ctx *exec_ctx, grpc_closure_list *list) { -#else -void grpc_closure_list_sched(grpc_exec_ctx *exec_ctx, grpc_closure_list *list) { -#endif - grpc_closure *c = list->head; - while (c != NULL) { - grpc_closure *next = c->next_data.next; -#ifndef NDEBUG - if (c->scheduled) { - gpr_log(GPR_ERROR, - "Closure already scheduled. (closure: %p, created: [%s:%d], " - "previously scheduled at: [%s: %d] run?: %s", - c, c->file_created, c->line_created, c->file_initiated, - c->line_initiated, c->run ? "true" : "false"); - abort(); - } - c->scheduled = true; - c->file_initiated = file; - c->line_initiated = line; - c->run = false; -#endif - assert(c->cb); - c->scheduler->vtable->sched(exec_ctx, c, c->error_data.error); - c = next; - } - list->head = list->tail = NULL; -} diff --git a/src/core/lib/iomgr/closure.h b/src/core/lib/iomgr/closure.h index cd32a4ba381..46793dd2c5d 100644 --- a/src/core/lib/iomgr/closure.h +++ b/src/core/lib/iomgr/closure.h @@ -21,25 +21,23 @@ #include +#include #include +#include +#include #include #include "src/core/lib/iomgr/error.h" +#include "src/core/lib/profiling/timers.h" #include "src/core/lib/support/mpscq.h" -#ifdef __cplusplus -extern "C" { -#endif - struct grpc_closure; typedef struct grpc_closure grpc_closure; -#ifndef NDEBUG -extern grpc_tracer_flag grpc_trace_closure; -#endif +extern grpc_core::DebugOnlyTraceFlag grpc_trace_closure; typedef struct grpc_closure_list { - grpc_closure *head; - grpc_closure *tail; + grpc_closure* head; + grpc_closure* tail; } grpc_closure_list; /** gRPC Callback definition. @@ -49,24 +47,24 @@ typedef struct grpc_closure_list { * describing what went wrong. * Error contract: it is not the cb's job to unref this error; * the closure scheduler will do that after the cb returns */ -typedef void (*grpc_iomgr_cb_func)(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error); +typedef void (*grpc_iomgr_cb_func)(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error); typedef struct grpc_closure_scheduler grpc_closure_scheduler; typedef struct grpc_closure_scheduler_vtable { /* NOTE: for all these functions, closure->scheduler == the scheduler that was used to find this vtable */ - void (*run)(grpc_exec_ctx *exec_ctx, grpc_closure *closure, - grpc_error *error); - void (*sched)(grpc_exec_ctx *exec_ctx, grpc_closure *closure, - grpc_error *error); - const char *name; + void (*run)(grpc_exec_ctx* exec_ctx, grpc_closure* closure, + grpc_error* error); + void (*sched)(grpc_exec_ctx* exec_ctx, grpc_closure* closure, + grpc_error* error); + const char* name; } grpc_closure_scheduler_vtable; /** Abstract type that can schedule closures for execution */ struct grpc_closure_scheduler { - const grpc_closure_scheduler_vtable *vtable; + const grpc_closure_scheduler_vtable* vtable; }; /** A closure over a grpc_iomgr_cb_func. */ @@ -74,7 +72,7 @@ struct grpc_closure { /** Once queued, next indicates the next queued closure; before then, scratch * space */ union { - grpc_closure *next; + grpc_closure* next; gpr_mpscq_node atm_next; uintptr_t scratch; } next_data; @@ -83,15 +81,15 @@ struct grpc_closure { grpc_iomgr_cb_func cb; /** Arguments to be passed to "cb". */ - void *cb_arg; + void* cb_arg; - /** Scheduler to schedule against: NULL to schedule against current execution - context */ - grpc_closure_scheduler *scheduler; + /** Scheduler to schedule against: nullptr to schedule against current + execution context */ + grpc_closure_scheduler* scheduler; /** Once queued, the result of the closure. Before then: scratch space */ union { - grpc_error *error; + grpc_error* error; uintptr_t scratch; } error_data; @@ -100,109 +98,269 @@ struct grpc_closure { #ifndef NDEBUG bool scheduled; bool run; // true = run, false = scheduled - const char *file_created; + const char* file_created; int line_created; - const char *file_initiated; + const char* file_initiated; int line_initiated; #endif }; +#ifndef NDEBUG +inline grpc_closure* grpc_closure_init(const char* file, int line, + grpc_closure* closure, + grpc_iomgr_cb_func cb, void* cb_arg, + grpc_closure_scheduler* scheduler) { +#else +inline grpc_closure* grpc_closure_init(grpc_closure* closure, + grpc_iomgr_cb_func cb, void* cb_arg, + grpc_closure_scheduler* scheduler) { +#endif + closure->cb = cb; + closure->cb_arg = cb_arg; + closure->scheduler = scheduler; +#ifndef NDEBUG + closure->scheduled = false; + closure->file_initiated = nullptr; + closure->line_initiated = 0; + closure->run = false; + closure->file_created = file; + closure->line_created = line; +#endif + return closure; +} + /** Initializes \a closure with \a cb and \a cb_arg. Returns \a closure. */ #ifndef NDEBUG -grpc_closure *grpc_closure_init(const char *file, int line, - grpc_closure *closure, grpc_iomgr_cb_func cb, - void *cb_arg, - grpc_closure_scheduler *scheduler); #define GRPC_CLOSURE_INIT(closure, cb, cb_arg, scheduler) \ grpc_closure_init(__FILE__, __LINE__, closure, cb, cb_arg, scheduler) #else -grpc_closure *grpc_closure_init(grpc_closure *closure, grpc_iomgr_cb_func cb, - void *cb_arg, - grpc_closure_scheduler *scheduler); #define GRPC_CLOSURE_INIT(closure, cb, cb_arg, scheduler) \ grpc_closure_init(closure, cb, cb_arg, scheduler) #endif +namespace closure_impl { + +typedef struct { + grpc_iomgr_cb_func cb; + void* cb_arg; + grpc_closure wrapper; +} wrapped_closure; + +inline void closure_wrapper(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + wrapped_closure* wc = (wrapped_closure*)arg; + grpc_iomgr_cb_func cb = wc->cb; + void* cb_arg = wc->cb_arg; + gpr_free(wc); + cb(exec_ctx, cb_arg, error); +} + +} // namespace closure_impl + +#ifndef NDEBUG +inline grpc_closure* grpc_closure_create(const char* file, int line, + grpc_iomgr_cb_func cb, void* cb_arg, + grpc_closure_scheduler* scheduler) { +#else +inline grpc_closure* grpc_closure_create(grpc_iomgr_cb_func cb, void* cb_arg, + grpc_closure_scheduler* scheduler) { +#endif + closure_impl::wrapped_closure* wc = + (closure_impl::wrapped_closure*)gpr_malloc(sizeof(*wc)); + wc->cb = cb; + wc->cb_arg = cb_arg; +#ifndef NDEBUG + grpc_closure_init(file, line, &wc->wrapper, closure_impl::closure_wrapper, wc, + scheduler); +#else + grpc_closure_init(&wc->wrapper, closure_impl::closure_wrapper, wc, scheduler); +#endif + return &wc->wrapper; +} + /* Create a heap allocated closure: try to avoid except for very rare events */ #ifndef NDEBUG -grpc_closure *grpc_closure_create(const char *file, int line, - grpc_iomgr_cb_func cb, void *cb_arg, - grpc_closure_scheduler *scheduler); #define GRPC_CLOSURE_CREATE(cb, cb_arg, scheduler) \ grpc_closure_create(__FILE__, __LINE__, cb, cb_arg, scheduler) #else -grpc_closure *grpc_closure_create(grpc_iomgr_cb_func cb, void *cb_arg, - grpc_closure_scheduler *scheduler); #define GRPC_CLOSURE_CREATE(cb, cb_arg, scheduler) \ grpc_closure_create(cb, cb_arg, scheduler) #endif #define GRPC_CLOSURE_LIST_INIT \ - { NULL, NULL } + { nullptr, nullptr } -void grpc_closure_list_init(grpc_closure_list *list); +inline void grpc_closure_list_init(grpc_closure_list* closure_list) { + closure_list->head = closure_list->tail = nullptr; +} /** add \a closure to the end of \a list and set \a closure's result to \a error Returns true if \a list becomes non-empty */ -bool grpc_closure_list_append(grpc_closure_list *list, grpc_closure *closure, - grpc_error *error); +inline bool grpc_closure_list_append(grpc_closure_list* closure_list, + grpc_closure* closure, grpc_error* error) { + if (closure == nullptr) { + GRPC_ERROR_UNREF(error); + return false; + } + closure->error_data.error = error; + closure->next_data.next = nullptr; + bool was_empty = (closure_list->head == nullptr); + if (was_empty) { + closure_list->head = closure; + } else { + closure_list->tail->next_data.next = closure; + } + closure_list->tail = closure; + return was_empty; +} /** force all success bits in \a list to false */ -void grpc_closure_list_fail_all(grpc_closure_list *list, - grpc_error *forced_failure); +inline void grpc_closure_list_fail_all(grpc_closure_list* list, + grpc_error* forced_failure) { + for (grpc_closure* c = list->head; c != nullptr; c = c->next_data.next) { + if (c->error_data.error == GRPC_ERROR_NONE) { + c->error_data.error = GRPC_ERROR_REF(forced_failure); + } + } + GRPC_ERROR_UNREF(forced_failure); +} /** append all closures from \a src to \a dst and empty \a src. */ -void grpc_closure_list_move(grpc_closure_list *src, grpc_closure_list *dst); +inline void grpc_closure_list_move(grpc_closure_list* src, + grpc_closure_list* dst) { + if (src->head == nullptr) { + return; + } + if (dst->head == nullptr) { + *dst = *src; + } else { + dst->tail->next_data.next = src->head; + dst->tail = src->tail; + } + src->head = src->tail = nullptr; +} /** return whether \a list is empty. */ -bool grpc_closure_list_empty(grpc_closure_list list); +inline bool grpc_closure_list_empty(grpc_closure_list closure_list) { + return closure_list.head == nullptr; +} + +#ifndef NDEBUG +inline void grpc_closure_run(const char* file, int line, + grpc_exec_ctx* exec_ctx, grpc_closure* c, + grpc_error* error) { +#else +inline void grpc_closure_run(grpc_exec_ctx* exec_ctx, grpc_closure* c, + grpc_error* error) { +#endif + GPR_TIMER_BEGIN("grpc_closure_run", 0); + if (c != nullptr) { +#ifndef NDEBUG + c->file_initiated = file; + c->line_initiated = line; + c->run = true; +#endif + assert(c->cb); + c->scheduler->vtable->run(exec_ctx, c, error); + } else { + GRPC_ERROR_UNREF(error); + } + GPR_TIMER_END("grpc_closure_run", 0); +} /** Run a closure directly. Caller ensures that no locks are being held above. * Note that calling this at the end of a closure callback function itself is * by definition safe. */ #ifndef NDEBUG -void grpc_closure_run(const char *file, int line, grpc_exec_ctx *exec_ctx, - grpc_closure *closure, grpc_error *error); #define GRPC_CLOSURE_RUN(exec_ctx, closure, error) \ grpc_closure_run(__FILE__, __LINE__, exec_ctx, closure, error) #else -void grpc_closure_run(grpc_exec_ctx *exec_ctx, grpc_closure *closure, - grpc_error *error); #define GRPC_CLOSURE_RUN(exec_ctx, closure, error) \ grpc_closure_run(exec_ctx, closure, error) #endif +#ifndef NDEBUG +inline void grpc_closure_sched(const char* file, int line, + grpc_exec_ctx* exec_ctx, grpc_closure* c, + grpc_error* error) { +#else +inline void grpc_closure_sched(grpc_exec_ctx* exec_ctx, grpc_closure* c, + grpc_error* error) { +#endif + GPR_TIMER_BEGIN("grpc_closure_sched", 0); + if (c != nullptr) { +#ifndef NDEBUG + if (c->scheduled) { + gpr_log(GPR_ERROR, + "Closure already scheduled. (closure: %p, created: [%s:%d], " + "previously scheduled at: [%s: %d] run?: %s", + c, c->file_created, c->line_created, c->file_initiated, + c->line_initiated, c->run ? "true" : "false"); + abort(); + } + c->scheduled = true; + c->file_initiated = file; + c->line_initiated = line; + c->run = false; +#endif + assert(c->cb); + c->scheduler->vtable->sched(exec_ctx, c, error); + } else { + GRPC_ERROR_UNREF(error); + } + GPR_TIMER_END("grpc_closure_sched", 0); +} + /** Schedule a closure to be run. Does not need to be run from a safe point. */ #ifndef NDEBUG -void grpc_closure_sched(const char *file, int line, grpc_exec_ctx *exec_ctx, - grpc_closure *closure, grpc_error *error); #define GRPC_CLOSURE_SCHED(exec_ctx, closure, error) \ grpc_closure_sched(__FILE__, __LINE__, exec_ctx, closure, error) #else -void grpc_closure_sched(grpc_exec_ctx *exec_ctx, grpc_closure *closure, - grpc_error *error); #define GRPC_CLOSURE_SCHED(exec_ctx, closure, error) \ grpc_closure_sched(exec_ctx, closure, error) #endif +#ifndef NDEBUG +inline void grpc_closure_list_sched(const char* file, int line, + grpc_exec_ctx* exec_ctx, + grpc_closure_list* list) { +#else +inline void grpc_closure_list_sched(grpc_exec_ctx* exec_ctx, + grpc_closure_list* list) { +#endif + grpc_closure* c = list->head; + while (c != nullptr) { + grpc_closure* next = c->next_data.next; +#ifndef NDEBUG + if (c->scheduled) { + gpr_log(GPR_ERROR, + "Closure already scheduled. (closure: %p, created: [%s:%d], " + "previously scheduled at: [%s: %d] run?: %s", + c, c->file_created, c->line_created, c->file_initiated, + c->line_initiated, c->run ? "true" : "false"); + abort(); + } + c->scheduled = true; + c->file_initiated = file; + c->line_initiated = line; + c->run = false; +#endif + assert(c->cb); + c->scheduler->vtable->sched(exec_ctx, c, c->error_data.error); + c = next; + } + list->head = list->tail = nullptr; +} + /** Schedule all closures in a list to be run. Does not need to be run from a * safe point. */ #ifndef NDEBUG -void grpc_closure_list_sched(const char *file, int line, - grpc_exec_ctx *exec_ctx, - grpc_closure_list *closure_list); #define GRPC_CLOSURE_LIST_SCHED(exec_ctx, closure_list) \ grpc_closure_list_sched(__FILE__, __LINE__, exec_ctx, closure_list) #else -void grpc_closure_list_sched(grpc_exec_ctx *exec_ctx, - grpc_closure_list *closure_list); #define GRPC_CLOSURE_LIST_SCHED(exec_ctx, closure_list) \ grpc_closure_list_sched(exec_ctx, closure_list) #endif -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_CLOSURE_H */ diff --git a/src/core/lib/iomgr/combiner.cc b/src/core/lib/iomgr/combiner.cc index 53f4b7eaa7e..15c009dd779 100644 --- a/src/core/lib/iomgr/combiner.cc +++ b/src/core/lib/iomgr/combiner.cc @@ -29,21 +29,20 @@ #include "src/core/lib/iomgr/executor.h" #include "src/core/lib/profiling/timers.h" -grpc_tracer_flag grpc_combiner_trace = - GRPC_TRACER_INITIALIZER(false, "combiner"); - -#define GRPC_COMBINER_TRACE(fn) \ - do { \ - if (GRPC_TRACER_ON(grpc_combiner_trace)) { \ - fn; \ - } \ +grpc_core::TraceFlag grpc_combiner_trace(false, "combiner"); + +#define GRPC_COMBINER_TRACE(fn) \ + do { \ + if (grpc_combiner_trace.enabled()) { \ + fn; \ + } \ } while (0) #define STATE_UNORPHANED 1 #define STATE_ELEM_COUNT_LOW_BIT 2 struct grpc_combiner { - grpc_combiner *next_combiner_on_this_exec_ctx; + grpc_combiner* next_combiner_on_this_exec_ctx; grpc_closure_scheduler scheduler; grpc_closure_scheduler finally_scheduler; gpr_mpscq queue; @@ -62,20 +61,20 @@ struct grpc_combiner { gpr_refcount refs; }; -static void combiner_exec(grpc_exec_ctx *exec_ctx, grpc_closure *closure, - grpc_error *error); -static void combiner_finally_exec(grpc_exec_ctx *exec_ctx, - grpc_closure *closure, grpc_error *error); +static void combiner_exec(grpc_exec_ctx* exec_ctx, grpc_closure* closure, + grpc_error* error); +static void combiner_finally_exec(grpc_exec_ctx* exec_ctx, + grpc_closure* closure, grpc_error* error); static const grpc_closure_scheduler_vtable scheduler = { combiner_exec, combiner_exec, "combiner:immediately"}; static const grpc_closure_scheduler_vtable finally_scheduler = { combiner_finally_exec, combiner_finally_exec, "combiner:finally"}; -static void offload(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error); +static void offload(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error); -grpc_combiner *grpc_combiner_create(void) { - grpc_combiner *lock = (grpc_combiner *)gpr_zalloc(sizeof(*lock)); +grpc_combiner* grpc_combiner_create(void) { + grpc_combiner* lock = (grpc_combiner*)gpr_zalloc(sizeof(*lock)); gpr_ref_init(&lock->refs, 1); lock->scheduler.vtable = &scheduler; lock->finally_scheduler.vtable = &finally_scheduler; @@ -88,14 +87,14 @@ grpc_combiner *grpc_combiner_create(void) { return lock; } -static void really_destroy(grpc_exec_ctx *exec_ctx, grpc_combiner *lock) { +static void really_destroy(grpc_exec_ctx* exec_ctx, grpc_combiner* lock) { GRPC_COMBINER_TRACE(gpr_log(GPR_DEBUG, "C:%p really_destroy", lock)); GPR_ASSERT(gpr_atm_no_barrier_load(&lock->state) == 0); gpr_mpscq_destroy(&lock->queue); gpr_free(lock); } -static void start_destroy(grpc_exec_ctx *exec_ctx, grpc_combiner *lock) { +static void start_destroy(grpc_exec_ctx* exec_ctx, grpc_combiner* lock) { gpr_atm old_state = gpr_atm_full_fetch_add(&lock->state, -STATE_UNORPHANED); GRPC_COMBINER_TRACE(gpr_log( GPR_DEBUG, "C:%p really_destroy old_state=%" PRIdPTR, lock, old_state)); @@ -106,7 +105,7 @@ static void start_destroy(grpc_exec_ctx *exec_ctx, grpc_combiner *lock) { #ifndef NDEBUG #define GRPC_COMBINER_DEBUG_SPAM(op, delta) \ - if (GRPC_TRACER_ON(grpc_combiner_trace)) { \ + if (grpc_combiner_trace.enabled()) { \ gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, \ "C:%p %s %" PRIdPTR " --> %" PRIdPTR " %s", lock, (op), \ gpr_atm_no_barrier_load(&lock->refs.count), \ @@ -116,24 +115,24 @@ static void start_destroy(grpc_exec_ctx *exec_ctx, grpc_combiner *lock) { #define GRPC_COMBINER_DEBUG_SPAM(op, delta) #endif -void grpc_combiner_unref(grpc_exec_ctx *exec_ctx, - grpc_combiner *lock GRPC_COMBINER_DEBUG_ARGS) { +void grpc_combiner_unref(grpc_exec_ctx* exec_ctx, + grpc_combiner* lock GRPC_COMBINER_DEBUG_ARGS) { GRPC_COMBINER_DEBUG_SPAM("UNREF", -1); if (gpr_unref(&lock->refs)) { start_destroy(exec_ctx, lock); } } -grpc_combiner *grpc_combiner_ref(grpc_combiner *lock GRPC_COMBINER_DEBUG_ARGS) { +grpc_combiner* grpc_combiner_ref(grpc_combiner* lock GRPC_COMBINER_DEBUG_ARGS) { GRPC_COMBINER_DEBUG_SPAM(" REF", 1); gpr_ref(&lock->refs); return lock; } -static void push_last_on_exec_ctx(grpc_exec_ctx *exec_ctx, - grpc_combiner *lock) { - lock->next_combiner_on_this_exec_ctx = NULL; - if (exec_ctx->active_combiner == NULL) { +static void push_last_on_exec_ctx(grpc_exec_ctx* exec_ctx, + grpc_combiner* lock) { + lock->next_combiner_on_this_exec_ctx = nullptr; + if (exec_ctx->active_combiner == nullptr) { exec_ctx->active_combiner = exec_ctx->last_combiner = lock; } else { exec_ctx->last_combiner->next_combiner_on_this_exec_ctx = lock; @@ -141,24 +140,24 @@ static void push_last_on_exec_ctx(grpc_exec_ctx *exec_ctx, } } -static void push_first_on_exec_ctx(grpc_exec_ctx *exec_ctx, - grpc_combiner *lock) { +static void push_first_on_exec_ctx(grpc_exec_ctx* exec_ctx, + grpc_combiner* lock) { lock->next_combiner_on_this_exec_ctx = exec_ctx->active_combiner; exec_ctx->active_combiner = lock; - if (lock->next_combiner_on_this_exec_ctx == NULL) { + if (lock->next_combiner_on_this_exec_ctx == nullptr) { exec_ctx->last_combiner = lock; } } #define COMBINER_FROM_CLOSURE_SCHEDULER(closure, scheduler_name) \ - ((grpc_combiner *)(((char *)((closure)->scheduler)) - \ - offsetof(grpc_combiner, scheduler_name))) + ((grpc_combiner*)(((char*)((closure)->scheduler)) - \ + offsetof(grpc_combiner, scheduler_name))) -static void combiner_exec(grpc_exec_ctx *exec_ctx, grpc_closure *cl, - grpc_error *error) { +static void combiner_exec(grpc_exec_ctx* exec_ctx, grpc_closure* cl, + grpc_error* error) { GRPC_STATS_INC_COMBINER_LOCKS_SCHEDULED_ITEMS(exec_ctx); GPR_TIMER_BEGIN("combiner.execute", 0); - grpc_combiner *lock = COMBINER_FROM_CLOSURE_SCHEDULER(cl, scheduler); + grpc_combiner* lock = COMBINER_FROM_CLOSURE_SCHEDULER(cl, scheduler); gpr_atm last = gpr_atm_full_fetch_add(&lock->state, STATE_ELEM_COUNT_LOW_BIT); GRPC_COMBINER_TRACE(gpr_log(GPR_DEBUG, "C:%p grpc_combiner_execute c=%p last=%" PRIdPTR, @@ -187,30 +186,30 @@ static void combiner_exec(grpc_exec_ctx *exec_ctx, grpc_closure *cl, GPR_TIMER_END("combiner.execute", 0); } -static void move_next(grpc_exec_ctx *exec_ctx) { +static void move_next(grpc_exec_ctx* exec_ctx) { exec_ctx->active_combiner = exec_ctx->active_combiner->next_combiner_on_this_exec_ctx; - if (exec_ctx->active_combiner == NULL) { - exec_ctx->last_combiner = NULL; + if (exec_ctx->active_combiner == nullptr) { + exec_ctx->last_combiner = nullptr; } } -static void offload(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { - grpc_combiner *lock = (grpc_combiner *)arg; +static void offload(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { + grpc_combiner* lock = (grpc_combiner*)arg; push_last_on_exec_ctx(exec_ctx, lock); } -static void queue_offload(grpc_exec_ctx *exec_ctx, grpc_combiner *lock) { +static void queue_offload(grpc_exec_ctx* exec_ctx, grpc_combiner* lock) { GRPC_STATS_INC_COMBINER_LOCKS_OFFLOADED(exec_ctx); move_next(exec_ctx); GRPC_COMBINER_TRACE(gpr_log(GPR_DEBUG, "C:%p queue_offload", lock)); GRPC_CLOSURE_SCHED(exec_ctx, &lock->offload, GRPC_ERROR_NONE); } -bool grpc_combiner_continue_exec_ctx(grpc_exec_ctx *exec_ctx) { +bool grpc_combiner_continue_exec_ctx(grpc_exec_ctx* exec_ctx) { GPR_TIMER_BEGIN("combiner.continue_exec_ctx", 0); - grpc_combiner *lock = exec_ctx->active_combiner; - if (lock == NULL) { + grpc_combiner* lock = exec_ctx->active_combiner; + if (lock == nullptr) { GPR_TIMER_END("combiner.continue_exec_ctx", 0); return false; } @@ -241,10 +240,10 @@ bool grpc_combiner_continue_exec_ctx(grpc_exec_ctx *exec_ctx) { // peek to see if something new has shown up, and execute that with // priority (gpr_atm_acq_load(&lock->state) >> 1) > 1) { - gpr_mpscq_node *n = gpr_mpscq_pop(&lock->queue); + gpr_mpscq_node* n = gpr_mpscq_pop(&lock->queue); GRPC_COMBINER_TRACE( gpr_log(GPR_DEBUG, "C:%p maybe_finish_one n=%p", lock, n)); - if (n == NULL) { + if (n == nullptr) { // queue is in an inconsistent state: use this as a cue that we should // go off and do something else for a while (and come back later) GPR_TIMER_MARK("delay_busy", 0); @@ -253,8 +252,8 @@ bool grpc_combiner_continue_exec_ctx(grpc_exec_ctx *exec_ctx) { return true; } GPR_TIMER_BEGIN("combiner.exec1", 0); - grpc_closure *cl = (grpc_closure *)n; - grpc_error *cl_err = cl->error_data.error; + grpc_closure* cl = (grpc_closure*)n; + grpc_error* cl_err = cl->error_data.error; #ifndef NDEBUG cl->scheduled = false; #endif @@ -262,16 +261,16 @@ bool grpc_combiner_continue_exec_ctx(grpc_exec_ctx *exec_ctx) { GRPC_ERROR_UNREF(cl_err); GPR_TIMER_END("combiner.exec1", 0); } else { - grpc_closure *c = lock->final_list.head; - GPR_ASSERT(c != NULL); + grpc_closure* c = lock->final_list.head; + GPR_ASSERT(c != nullptr); grpc_closure_list_init(&lock->final_list); int loops = 0; - while (c != NULL) { + while (c != nullptr) { GPR_TIMER_BEGIN("combiner.exec_1final", 0); GRPC_COMBINER_TRACE( gpr_log(GPR_DEBUG, "C:%p execute_final[%d] c=%p", lock, loops, c)); - grpc_closure *next = c->next_data.next; - grpc_error *error = c->error_data.error; + grpc_closure* next = c->next_data.next; + grpc_error* error = c->error_data.error; #ifndef NDEBUG c->scheduled = false; #endif @@ -327,13 +326,13 @@ bool grpc_combiner_continue_exec_ctx(grpc_exec_ctx *exec_ctx) { return true; } -static void enqueue_finally(grpc_exec_ctx *exec_ctx, void *closure, - grpc_error *error); +static void enqueue_finally(grpc_exec_ctx* exec_ctx, void* closure, + grpc_error* error); -static void combiner_finally_exec(grpc_exec_ctx *exec_ctx, - grpc_closure *closure, grpc_error *error) { +static void combiner_finally_exec(grpc_exec_ctx* exec_ctx, + grpc_closure* closure, grpc_error* error) { GRPC_STATS_INC_COMBINER_LOCKS_SCHEDULED_FINAL_ITEMS(exec_ctx); - grpc_combiner *lock = + grpc_combiner* lock = COMBINER_FROM_CLOSURE_SCHEDULER(closure, finally_scheduler); GRPC_COMBINER_TRACE(gpr_log(GPR_DEBUG, "C:%p grpc_combiner_execute_finally c=%p; ac=%p", @@ -356,17 +355,17 @@ static void combiner_finally_exec(grpc_exec_ctx *exec_ctx, GPR_TIMER_END("combiner.execute_finally", 0); } -static void enqueue_finally(grpc_exec_ctx *exec_ctx, void *closure, - grpc_error *error) { - combiner_finally_exec(exec_ctx, (grpc_closure *)closure, +static void enqueue_finally(grpc_exec_ctx* exec_ctx, void* closure, + grpc_error* error) { + combiner_finally_exec(exec_ctx, (grpc_closure*)closure, GRPC_ERROR_REF(error)); } -grpc_closure_scheduler *grpc_combiner_scheduler(grpc_combiner *combiner) { +grpc_closure_scheduler* grpc_combiner_scheduler(grpc_combiner* combiner) { return &combiner->scheduler; } -grpc_closure_scheduler *grpc_combiner_finally_scheduler( - grpc_combiner *combiner) { +grpc_closure_scheduler* grpc_combiner_finally_scheduler( + grpc_combiner* combiner) { return &combiner->finally_scheduler; } diff --git a/src/core/lib/iomgr/combiner.h b/src/core/lib/iomgr/combiner.h index 10e5fb480db..0c055113317 100644 --- a/src/core/lib/iomgr/combiner.h +++ b/src/core/lib/iomgr/combiner.h @@ -26,10 +26,6 @@ #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/support/mpscq.h" -#ifdef __cplusplus -extern "C" { -#endif - // 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 @@ -37,7 +33,7 @@ extern "C" { // Initialize the lock, with an optional workqueue to shift load to when // necessary -grpc_combiner *grpc_combiner_create(void); +grpc_combiner* grpc_combiner_create(void); #ifndef NDEBUG #define GRPC_COMBINER_DEBUG_ARGS \ @@ -55,20 +51,16 @@ grpc_combiner *grpc_combiner_create(void); // Ref/unref the lock, for when we're sharing the lock ownership // Prefer to use the macros above -grpc_combiner *grpc_combiner_ref(grpc_combiner *lock GRPC_COMBINER_DEBUG_ARGS); -void grpc_combiner_unref(grpc_exec_ctx *exec_ctx, - grpc_combiner *lock GRPC_COMBINER_DEBUG_ARGS); +grpc_combiner* grpc_combiner_ref(grpc_combiner* lock GRPC_COMBINER_DEBUG_ARGS); +void grpc_combiner_unref(grpc_exec_ctx* exec_ctx, + grpc_combiner* lock GRPC_COMBINER_DEBUG_ARGS); // Fetch a scheduler to schedule closures against -grpc_closure_scheduler *grpc_combiner_scheduler(grpc_combiner *lock); +grpc_closure_scheduler* grpc_combiner_scheduler(grpc_combiner* lock); // Scheduler to execute \a action within the lock just prior to unlocking. -grpc_closure_scheduler *grpc_combiner_finally_scheduler(grpc_combiner *lock); +grpc_closure_scheduler* grpc_combiner_finally_scheduler(grpc_combiner* lock); -bool grpc_combiner_continue_exec_ctx(grpc_exec_ctx *exec_ctx); +bool grpc_combiner_continue_exec_ctx(grpc_exec_ctx* exec_ctx); -extern grpc_tracer_flag grpc_combiner_trace; - -#ifdef __cplusplus -} -#endif +extern grpc_core::TraceFlag grpc_combiner_trace; #endif /* GRPC_CORE_LIB_IOMGR_COMBINER_H */ diff --git a/src/core/lib/iomgr/endpoint.h b/src/core/lib/iomgr/endpoint.h index 92964e0f2dc..6ab0a6591cc 100644 --- a/src/core/lib/iomgr/endpoint.h +++ b/src/core/lib/iomgr/endpoint.h @@ -26,10 +26,6 @@ #include "src/core/lib/iomgr/pollset_set.h" #include "src/core/lib/iomgr/resource_quota.h" -#ifdef __cplusplus -extern "C" { -#endif - /* An endpoint caps a streaming channel between two communicating processes. Examples may be: a tcp socket, , or some shared memory. */ @@ -37,21 +33,21 @@ typedef struct grpc_endpoint grpc_endpoint; typedef struct grpc_endpoint_vtable grpc_endpoint_vtable; struct grpc_endpoint_vtable { - void (*read)(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_slice_buffer *slices, grpc_closure *cb); - void (*write)(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_slice_buffer *slices, grpc_closure *cb); - void (*add_to_pollset)(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_pollset *pollset); - void (*add_to_pollset_set)(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_pollset_set *pollset); - void (*delete_from_pollset_set)(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_pollset_set *pollset); - void (*shutdown)(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, grpc_error *why); - void (*destroy)(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep); - grpc_resource_user *(*get_resource_user)(grpc_endpoint *ep); - char *(*get_peer)(grpc_endpoint *ep); - int (*get_fd)(grpc_endpoint *ep); + void (*read)(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_slice_buffer* slices, grpc_closure* cb); + void (*write)(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_slice_buffer* slices, grpc_closure* cb); + void (*add_to_pollset)(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_pollset* pollset); + void (*add_to_pollset_set)(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_pollset_set* pollset); + void (*delete_from_pollset_set)(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_pollset_set* pollset); + void (*shutdown)(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, grpc_error* why); + void (*destroy)(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep); + grpc_resource_user* (*get_resource_user)(grpc_endpoint* ep); + char* (*get_peer)(grpc_endpoint* ep); + int (*get_fd)(grpc_endpoint* ep); }; /* When data is available on the connection, calls the callback with slices. @@ -59,14 +55,14 @@ struct grpc_endpoint_vtable { indicates the endpoint is closed. Valid slices may be placed into \a slices even when the callback is invoked with error != GRPC_ERROR_NONE. */ -void grpc_endpoint_read(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_slice_buffer *slices, grpc_closure *cb); +void grpc_endpoint_read(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_slice_buffer* slices, grpc_closure* cb); -char *grpc_endpoint_get_peer(grpc_endpoint *ep); +char* grpc_endpoint_get_peer(grpc_endpoint* ep); /* Get the file descriptor used by \a ep. Return -1 if \a ep is not using an fd. - */ -int grpc_endpoint_get_fd(grpc_endpoint *ep); + */ +int grpc_endpoint_get_fd(grpc_endpoint* ep); /* Write slices out to the socket. @@ -78,36 +74,32 @@ int grpc_endpoint_get_fd(grpc_endpoint *ep); No guarantee is made to the content of slices after a write EXCEPT that it is a valid slice buffer. */ -void grpc_endpoint_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_slice_buffer *slices, grpc_closure *cb); +void grpc_endpoint_write(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_slice_buffer* slices, grpc_closure* cb); /* Causes any pending and future read/write callbacks to run immediately with success==0 */ -void grpc_endpoint_shutdown(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_error *why); -void grpc_endpoint_destroy(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep); +void grpc_endpoint_shutdown(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_error* why); +void grpc_endpoint_destroy(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep); /* Add an endpoint to a pollset or pollset_set, so that when the pollset is polled, events from this endpoint are considered */ -void grpc_endpoint_add_to_pollset(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_pollset *pollset); -void grpc_endpoint_add_to_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_endpoint *ep, - grpc_pollset_set *pollset_set); +void grpc_endpoint_add_to_pollset(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_pollset* pollset); +void grpc_endpoint_add_to_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_endpoint* ep, + grpc_pollset_set* pollset_set); /* Delete an endpoint from a pollset_set */ -void grpc_endpoint_delete_from_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_endpoint *ep, - grpc_pollset_set *pollset_set); +void grpc_endpoint_delete_from_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_endpoint* ep, + grpc_pollset_set* pollset_set); -grpc_resource_user *grpc_endpoint_get_resource_user(grpc_endpoint *endpoint); +grpc_resource_user* grpc_endpoint_get_resource_user(grpc_endpoint* endpoint); struct grpc_endpoint { - const grpc_endpoint_vtable *vtable; + const grpc_endpoint_vtable* vtable; }; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_ENDPOINT_H */ diff --git a/src/core/lib/iomgr/endpoint_pair.h b/src/core/lib/iomgr/endpoint_pair.h index ee91795749b..506ffc88b4b 100644 --- a/src/core/lib/iomgr/endpoint_pair.h +++ b/src/core/lib/iomgr/endpoint_pair.h @@ -21,20 +21,12 @@ #include "src/core/lib/iomgr/endpoint.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct { - grpc_endpoint *client; - grpc_endpoint *server; + grpc_endpoint* client; + grpc_endpoint* server; } grpc_endpoint_pair; -grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(const char *name, - grpc_channel_args *args); - -#ifdef __cplusplus -} -#endif +grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(const char* name, + grpc_channel_args* args); #endif /* GRPC_CORE_LIB_IOMGR_ENDPOINT_PAIR_H */ diff --git a/src/core/lib/iomgr/endpoint_pair_posix.cc b/src/core/lib/iomgr/endpoint_pair_posix.cc index 3ade2148bac..f5f59f99173 100644 --- a/src/core/lib/iomgr/endpoint_pair_posix.cc +++ b/src/core/lib/iomgr/endpoint_pair_posix.cc @@ -47,11 +47,11 @@ static void create_sockets(int sv[2]) { GPR_ASSERT(grpc_set_socket_no_sigpipe_if_possible(sv[1]) == GRPC_ERROR_NONE); } -grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(const char *name, - grpc_channel_args *args) { +grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(const char* name, + grpc_channel_args* args) { int sv[2]; grpc_endpoint_pair p; - char *final_name; + char* final_name; create_sockets(sv); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; diff --git a/src/core/lib/iomgr/endpoint_pair_uv.cc b/src/core/lib/iomgr/endpoint_pair_uv.cc index ff72fe04926..128a947d1bb 100644 --- a/src/core/lib/iomgr/endpoint_pair_uv.cc +++ b/src/core/lib/iomgr/endpoint_pair_uv.cc @@ -26,8 +26,8 @@ #include "src/core/lib/iomgr/endpoint_pair.h" -grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(const char *name, - grpc_channel_args *args) { +grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(const char* name, + grpc_channel_args* args) { grpc_endpoint_pair endpoint_pair; // TODO(mlumish): implement this properly under libuv GPR_ASSERT(false && diff --git a/src/core/lib/iomgr/endpoint_pair_windows.cc b/src/core/lib/iomgr/endpoint_pair_windows.cc index 782fa2fd690..afa995a1c72 100644 --- a/src/core/lib/iomgr/endpoint_pair_windows.cc +++ b/src/core/lib/iomgr/endpoint_pair_windows.cc @@ -44,19 +44,19 @@ static void create_sockets(SOCKET sv[2]) { memset(&addr, 0, sizeof(addr)); addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); addr.sin_family = AF_INET; - GPR_ASSERT(bind(lst_sock, (struct sockaddr *)&addr, sizeof(addr)) != + GPR_ASSERT(bind(lst_sock, (struct sockaddr*)&addr, sizeof(addr)) != SOCKET_ERROR); GPR_ASSERT(listen(lst_sock, SOMAXCONN) != SOCKET_ERROR); - GPR_ASSERT(getsockname(lst_sock, (struct sockaddr *)&addr, &addr_len) != + GPR_ASSERT(getsockname(lst_sock, (struct sockaddr*)&addr, &addr_len) != SOCKET_ERROR); cli_sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED); GPR_ASSERT(cli_sock != INVALID_SOCKET); - GPR_ASSERT(WSAConnect(cli_sock, (struct sockaddr *)&addr, addr_len, NULL, - NULL, NULL, NULL) == 0); - svr_sock = accept(lst_sock, (struct sockaddr *)&addr, &addr_len); + GPR_ASSERT(WSAConnect(cli_sock, (struct sockaddr*)&addr, addr_len, NULL, NULL, + NULL, NULL) == 0); + svr_sock = accept(lst_sock, (struct sockaddr*)&addr, &addr_len); GPR_ASSERT(svr_sock != INVALID_SOCKET); closesocket(lst_sock); @@ -68,7 +68,7 @@ static void create_sockets(SOCKET sv[2]) { } grpc_endpoint_pair grpc_iomgr_create_endpoint_pair( - const char *name, grpc_channel_args *channel_args) { + const char* name, grpc_channel_args* channel_args) { SOCKET sv[2]; grpc_endpoint_pair p; create_sockets(sv); diff --git a/src/core/lib/iomgr/error.cc b/src/core/lib/iomgr/error.cc index 2ea6cf1301e..e6d640c106b 100644 --- a/src/core/lib/iomgr/error.cc +++ b/src/core/lib/iomgr/error.cc @@ -37,12 +37,11 @@ #include "src/core/lib/profiling/timers.h" #include "src/core/lib/slice/slice_internal.h" -#ifndef NDEBUG -grpc_tracer_flag grpc_trace_error_refcount = - GRPC_TRACER_INITIALIZER(false, "error_refcount"); -#endif +grpc_core::DebugOnlyTraceFlag grpc_trace_error_refcount(false, + "error_refcount"); +grpc_core::DebugOnlyTraceFlag grpc_trace_closure(false, "closure"); -static const char *error_int_name(grpc_error_ints key) { +static const char* error_int_name(grpc_error_ints key) { switch (key) { case GRPC_ERROR_INT_ERRNO: return "errno"; @@ -80,7 +79,7 @@ static const char *error_int_name(grpc_error_ints key) { GPR_UNREACHABLE_CODE(return "unknown"); } -static const char *error_str_name(grpc_error_strs key) { +static const char* error_str_name(grpc_error_strs key) { switch (key) { case GRPC_ERROR_STR_KEY: return "key"; @@ -112,7 +111,7 @@ static const char *error_str_name(grpc_error_strs key) { GPR_UNREACHABLE_CODE(return "unknown"); } -static const char *error_time_name(grpc_error_times key) { +static const char* error_time_name(grpc_error_times key) { switch (key) { case GRPC_ERROR_TIME_CREATED: return "created"; @@ -122,15 +121,15 @@ static const char *error_time_name(grpc_error_times key) { GPR_UNREACHABLE_CODE(return "unknown"); } -bool grpc_error_is_special(grpc_error *err) { +bool grpc_error_is_special(grpc_error* err) { return err == GRPC_ERROR_NONE || err == GRPC_ERROR_OOM || err == GRPC_ERROR_CANCELLED; } #ifndef NDEBUG -grpc_error *grpc_error_ref(grpc_error *err, const char *file, int line) { +grpc_error* grpc_error_ref(grpc_error* err, const char* file, int line) { if (grpc_error_is_special(err)) return err; - if (GRPC_TRACER_ON(grpc_trace_error_refcount)) { + if (grpc_trace_error_refcount.enabled()) { gpr_log(GPR_DEBUG, "%p: %" PRIdPTR " -> %" PRIdPTR " [%s:%d]", err, gpr_atm_no_barrier_load(&err->atomics.refs.count), gpr_atm_no_barrier_load(&err->atomics.refs.count) + 1, file, line); @@ -139,17 +138,17 @@ grpc_error *grpc_error_ref(grpc_error *err, const char *file, int line) { return err; } #else -grpc_error *grpc_error_ref(grpc_error *err) { +grpc_error* grpc_error_ref(grpc_error* err) { if (grpc_error_is_special(err)) return err; gpr_ref(&err->atomics.refs); return err; } #endif -static void unref_errs(grpc_error *err) { +static void unref_errs(grpc_error* err) { uint8_t slot = err->first_err; while (slot != UINT8_MAX) { - grpc_linked_error *lerr = (grpc_linked_error *)(err->arena + slot); + grpc_linked_error* lerr = (grpc_linked_error*)(err->arena + slot); GRPC_ERROR_UNREF(lerr->err); GPR_ASSERT(err->last_err == slot ? lerr->next == UINT8_MAX : lerr->next != UINT8_MAX); @@ -163,27 +162,27 @@ static void unref_slice(grpc_slice slice) { grpc_exec_ctx_finish(&exec_ctx); } -static void unref_strs(grpc_error *err) { +static void unref_strs(grpc_error* err) { for (size_t which = 0; which < GRPC_ERROR_STR_MAX; ++which) { uint8_t slot = err->strs[which]; if (slot != UINT8_MAX) { - unref_slice(*(grpc_slice *)(err->arena + slot)); + unref_slice(*(grpc_slice*)(err->arena + slot)); } } } -static void error_destroy(grpc_error *err) { +static void error_destroy(grpc_error* err) { GPR_ASSERT(!grpc_error_is_special(err)); unref_errs(err); unref_strs(err); - gpr_free((void *)gpr_atm_acq_load(&err->atomics.error_string)); + gpr_free((void*)gpr_atm_acq_load(&err->atomics.error_string)); gpr_free(err); } #ifndef NDEBUG -void grpc_error_unref(grpc_error *err, const char *file, int line) { +void grpc_error_unref(grpc_error* err, const char* file, int line) { if (grpc_error_is_special(err)) return; - if (GRPC_TRACER_ON(grpc_trace_error_refcount)) { + if (grpc_trace_error_refcount.enabled()) { gpr_log(GPR_DEBUG, "%p: %" PRIdPTR " -> %" PRIdPTR " [%s:%d]", err, gpr_atm_no_barrier_load(&err->atomics.refs.count), gpr_atm_no_barrier_load(&err->atomics.refs.count) - 1, file, line); @@ -193,7 +192,7 @@ void grpc_error_unref(grpc_error *err, const char *file, int line) { } } #else -void grpc_error_unref(grpc_error *err) { +void grpc_error_unref(grpc_error* err) { if (grpc_error_is_special(err)) return; if (gpr_unref(&err->atomics.refs)) { error_destroy(err); @@ -201,7 +200,7 @@ void grpc_error_unref(grpc_error *err) { } #endif -static uint8_t get_placement(grpc_error **err, size_t size) { +static uint8_t get_placement(grpc_error** err, size_t size) { GPR_ASSERT(*err); uint8_t slots = (uint8_t)(size / sizeof(intptr_t)); if ((*err)->arena_size + slots > (*err)->arena_capacity) { @@ -211,12 +210,12 @@ static uint8_t get_placement(grpc_error **err, size_t size) { return UINT8_MAX; } #ifndef NDEBUG - grpc_error *orig = *err; + grpc_error* orig = *err; #endif - *err = (grpc_error *)gpr_realloc( + *err = (grpc_error*)gpr_realloc( *err, sizeof(grpc_error) + (*err)->arena_capacity * sizeof(intptr_t)); #ifndef NDEBUG - if (GRPC_TRACER_ON(grpc_trace_error_refcount)) { + if (grpc_trace_error_refcount.enabled()) { if (*err != orig) { gpr_log(GPR_DEBUG, "realloc %p -> %p", orig, *err); } @@ -228,7 +227,7 @@ static uint8_t get_placement(grpc_error **err, size_t size) { return placement; } -static void internal_set_int(grpc_error **err, grpc_error_ints which, +static void internal_set_int(grpc_error** err, grpc_error_ints which, intptr_t value) { uint8_t slot = (*err)->ints[which]; if (slot == UINT8_MAX) { @@ -243,36 +242,36 @@ static void internal_set_int(grpc_error **err, grpc_error_ints which, (*err)->arena[slot] = value; } -static void internal_set_str(grpc_error **err, grpc_error_strs which, +static void internal_set_str(grpc_error** err, grpc_error_strs which, grpc_slice value) { uint8_t slot = (*err)->strs[which]; if (slot == UINT8_MAX) { slot = get_placement(err, sizeof(value)); if (slot == UINT8_MAX) { - const char *str = grpc_slice_to_c_string(value); + const char* str = grpc_slice_to_c_string(value); gpr_log(GPR_ERROR, "Error %p is full, dropping string {\"%s\":\"%s\"}", *err, error_str_name(which), str); - gpr_free((void *)str); + gpr_free((void*)str); return; } } else { - unref_slice(*(grpc_slice *)((*err)->arena + slot)); + unref_slice(*(grpc_slice*)((*err)->arena + slot)); } (*err)->strs[which] = slot; memcpy((*err)->arena + slot, &value, sizeof(value)); } -static char *fmt_time(gpr_timespec tm); -static void internal_set_time(grpc_error **err, grpc_error_times which, +static char* fmt_time(gpr_timespec tm); +static void internal_set_time(grpc_error** err, grpc_error_times which, gpr_timespec value) { uint8_t slot = (*err)->times[which]; if (slot == UINT8_MAX) { slot = get_placement(err, sizeof(value)); if (slot == UINT8_MAX) { - const char *time_str = fmt_time(value); + const char* time_str = fmt_time(value); gpr_log(GPR_ERROR, "Error %p is full, dropping \"%s\":\"%s\"}", *err, error_time_name(which), time_str); - gpr_free((void *)time_str); + gpr_free((void*)time_str); return; } } @@ -280,7 +279,7 @@ static void internal_set_time(grpc_error **err, grpc_error_times which, memcpy((*err)->arena + slot, &value, sizeof(value)); } -static void internal_add_error(grpc_error **err, grpc_error *new_err) { +static void internal_add_error(grpc_error** err, grpc_error* new_err) { grpc_linked_error new_last = {new_err, UINT8_MAX}; uint8_t slot = get_placement(err, sizeof(grpc_linked_error)); if (slot == UINT8_MAX) { @@ -295,8 +294,8 @@ static void internal_add_error(grpc_error **err, grpc_error *new_err) { (*err)->first_err = slot; } else { GPR_ASSERT((*err)->last_err != UINT8_MAX); - grpc_linked_error *old_last = - (grpc_linked_error *)((*err)->arena + (*err)->last_err); + grpc_linked_error* old_last = + (grpc_linked_error*)((*err)->arena + (*err)->last_err); old_last->next = slot; (*err)->last_err = slot; } @@ -316,20 +315,20 @@ static void internal_add_error(grpc_error **err, grpc_error *new_err) { // It is very common to include and extra int and string in an error #define SURPLUS_CAPACITY (2 * SLOTS_PER_INT + SLOTS_PER_TIME) -grpc_error *grpc_error_create(const char *file, int line, grpc_slice desc, - grpc_error **referencing, +grpc_error* grpc_error_create(const char* file, int line, grpc_slice desc, + grpc_error** referencing, size_t num_referencing) { GPR_TIMER_BEGIN("grpc_error_create", 0); uint8_t initial_arena_capacity = (uint8_t)( DEFAULT_ERROR_CAPACITY + (uint8_t)(num_referencing * SLOTS_PER_LINKED_ERROR) + SURPLUS_CAPACITY); - grpc_error *err = (grpc_error *)gpr_malloc( + grpc_error* err = (grpc_error*)gpr_malloc( sizeof(*err) + initial_arena_capacity * sizeof(intptr_t)); - if (err == NULL) { // TODO(ctiller): make gpr_malloc return NULL + if (err == nullptr) { // TODO(ctiller): make gpr_malloc return NULL return GRPC_ERROR_OOM; } #ifndef NDEBUG - if (GRPC_TRACER_ON(grpc_trace_error_refcount)) { + if (grpc_trace_error_refcount.enabled()) { gpr_log(GPR_DEBUG, "%p create [%s:%d]", err, file, line); } #endif @@ -364,27 +363,27 @@ grpc_error *grpc_error_create(const char *file, int line, grpc_slice desc, return err; } -static void ref_strs(grpc_error *err) { +static void ref_strs(grpc_error* err) { for (size_t i = 0; i < GRPC_ERROR_STR_MAX; ++i) { uint8_t slot = err->strs[i]; if (slot != UINT8_MAX) { - grpc_slice_ref_internal(*(grpc_slice *)(err->arena + slot)); + grpc_slice_ref_internal(*(grpc_slice*)(err->arena + slot)); } } } -static void ref_errs(grpc_error *err) { +static void ref_errs(grpc_error* err) { uint8_t slot = err->first_err; while (slot != UINT8_MAX) { - grpc_linked_error *lerr = (grpc_linked_error *)(err->arena + slot); + grpc_linked_error* lerr = (grpc_linked_error*)(err->arena + slot); GRPC_ERROR_REF(lerr->err); slot = lerr->next; } } -static grpc_error *copy_error_and_unref(grpc_error *in) { +static grpc_error* copy_error_and_unref(grpc_error* in) { GPR_TIMER_BEGIN("copy_error_and_unref", 0); - grpc_error *out; + grpc_error* out; if (grpc_error_is_special(in)) { out = GRPC_ERROR_CREATE_FROM_STATIC_STRING("unknown"); if (in == GRPC_ERROR_NONE) { @@ -408,16 +407,16 @@ static grpc_error *copy_error_and_unref(grpc_error *in) { if (in->arena_capacity - in->arena_size < (uint8_t)SLOTS_PER_STR) { new_arena_capacity = (uint8_t)(3 * new_arena_capacity / 2); } - out = (grpc_error *)gpr_malloc(sizeof(*in) + - new_arena_capacity * sizeof(intptr_t)); + out = (grpc_error*)gpr_malloc(sizeof(*in) + + new_arena_capacity * sizeof(intptr_t)); #ifndef NDEBUG - if (GRPC_TRACER_ON(grpc_trace_error_refcount)) { + if (grpc_trace_error_refcount.enabled()) { gpr_log(GPR_DEBUG, "%p create copying %p", out, in); } #endif // bulk memcpy of the rest of the struct. size_t skip = sizeof(&out->atomics); - memcpy((void *)((uintptr_t)out + skip), (void *)((uintptr_t)in + skip), + memcpy((void*)((uintptr_t)out + skip), (void*)((uintptr_t)in + skip), sizeof(*in) + (in->arena_size * sizeof(intptr_t)) - skip); // manually set the atomics and the new capacity gpr_atm_no_barrier_store(&out->atomics.error_string, 0); @@ -431,19 +430,19 @@ static grpc_error *copy_error_and_unref(grpc_error *in) { return out; } -grpc_error *grpc_error_set_int(grpc_error *src, grpc_error_ints which, +grpc_error* grpc_error_set_int(grpc_error* src, grpc_error_ints which, intptr_t value) { GPR_TIMER_BEGIN("grpc_error_set_int", 0); - grpc_error *new_err = copy_error_and_unref(src); + grpc_error* new_err = copy_error_and_unref(src); internal_set_int(&new_err, which, value); GPR_TIMER_END("grpc_error_set_int", 0); return new_err; } typedef struct { - grpc_error *error; + grpc_error* error; grpc_status_code code; - const char *msg; + const char* msg; } special_error_status_map; static special_error_status_map error_status_map[] = { {GRPC_ERROR_NONE, GRPC_STATUS_OK, ""}, @@ -451,13 +450,13 @@ static special_error_status_map error_status_map[] = { {GRPC_ERROR_OOM, GRPC_STATUS_RESOURCE_EXHAUSTED, "Out of memory"}, }; -bool grpc_error_get_int(grpc_error *err, grpc_error_ints which, intptr_t *p) { +bool grpc_error_get_int(grpc_error* err, grpc_error_ints which, intptr_t* p) { GPR_TIMER_BEGIN("grpc_error_get_int", 0); if (grpc_error_is_special(err)) { if (which == GRPC_ERROR_INT_GRPC_STATUS) { for (size_t i = 0; i < GPR_ARRAY_SIZE(error_status_map); i++) { if (error_status_map[i].error == err) { - if (p != NULL) *p = error_status_map[i].code; + if (p != nullptr) *p = error_status_map[i].code; GPR_TIMER_END("grpc_error_get_int", 0); return true; } @@ -468,7 +467,7 @@ bool grpc_error_get_int(grpc_error *err, grpc_error_ints which, intptr_t *p) { } uint8_t slot = err->ints[which]; if (slot != UINT8_MAX) { - if (p != NULL) *p = err->arena[slot]; + if (p != nullptr) *p = err->arena[slot]; GPR_TIMER_END("grpc_error_get_int", 0); return true; } @@ -476,17 +475,17 @@ bool grpc_error_get_int(grpc_error *err, grpc_error_ints which, intptr_t *p) { return false; } -grpc_error *grpc_error_set_str(grpc_error *src, grpc_error_strs which, +grpc_error* grpc_error_set_str(grpc_error* src, grpc_error_strs which, grpc_slice str) { GPR_TIMER_BEGIN("grpc_error_set_str", 0); - grpc_error *new_err = copy_error_and_unref(src); + grpc_error* new_err = copy_error_and_unref(src); internal_set_str(&new_err, which, str); GPR_TIMER_END("grpc_error_set_str", 0); return new_err; } -bool grpc_error_get_str(grpc_error *err, grpc_error_strs which, - grpc_slice *str) { +bool grpc_error_get_str(grpc_error* err, grpc_error_strs which, + grpc_slice* str) { if (grpc_error_is_special(err)) { if (which == GRPC_ERROR_STR_GRPC_MESSAGE) { for (size_t i = 0; i < GPR_ARRAY_SIZE(error_status_map); i++) { @@ -500,53 +499,53 @@ bool grpc_error_get_str(grpc_error *err, grpc_error_strs which, } uint8_t slot = err->strs[which]; if (slot != UINT8_MAX) { - *str = *(grpc_slice *)(err->arena + slot); + *str = *(grpc_slice*)(err->arena + slot); return true; } else { return false; } } -grpc_error *grpc_error_add_child(grpc_error *src, grpc_error *child) { +grpc_error* grpc_error_add_child(grpc_error* src, grpc_error* child) { GPR_TIMER_BEGIN("grpc_error_add_child", 0); - grpc_error *new_err = copy_error_and_unref(src); + grpc_error* new_err = copy_error_and_unref(src); internal_add_error(&new_err, child); GPR_TIMER_END("grpc_error_add_child", 0); return new_err; } -static const char *no_error_string = "\"No Error\""; -static const char *oom_error_string = "\"Out of memory\""; -static const char *cancelled_error_string = "\"Cancelled\""; +static const char* no_error_string = "\"No Error\""; +static const char* oom_error_string = "\"Out of memory\""; +static const char* cancelled_error_string = "\"Cancelled\""; typedef struct { - char *key; - char *value; + char* key; + char* value; } kv_pair; typedef struct { - kv_pair *kvs; + kv_pair* kvs; size_t num_kvs; size_t cap_kvs; } kv_pairs; -static void append_chr(char c, char **s, size_t *sz, size_t *cap) { +static void append_chr(char c, char** s, size_t* sz, size_t* cap) { if (*sz == *cap) { *cap = GPR_MAX(8, 3 * *cap / 2); - *s = (char *)gpr_realloc(*s, *cap); + *s = (char*)gpr_realloc(*s, *cap); } (*s)[(*sz)++] = c; } -static void append_str(const char *str, char **s, size_t *sz, size_t *cap) { - for (const char *c = str; *c; c++) { +static void append_str(const char* str, char** s, size_t* sz, size_t* cap) { + for (const char* c = str; *c; c++) { append_chr(*c, s, sz, cap); } } -static void append_esc_str(const uint8_t *str, size_t len, char **s, size_t *sz, - size_t *cap) { - static const char *hex = "0123456789abcdef"; +static void append_esc_str(const uint8_t* str, size_t len, char** s, size_t* sz, + size_t* cap) { + static const char* hex = "0123456789abcdef"; append_chr('"', s, sz, cap); for (size_t i = 0; i < len; i++, str++) { if (*str < 32 || *str >= 127) { @@ -582,28 +581,28 @@ static void append_esc_str(const uint8_t *str, size_t len, char **s, size_t *sz, append_chr('"', s, sz, cap); } -static void append_kv(kv_pairs *kvs, char *key, char *value) { +static void append_kv(kv_pairs* kvs, char* key, char* value) { if (kvs->num_kvs == kvs->cap_kvs) { kvs->cap_kvs = GPR_MAX(3 * kvs->cap_kvs / 2, 4); kvs->kvs = - (kv_pair *)gpr_realloc(kvs->kvs, sizeof(*kvs->kvs) * kvs->cap_kvs); + (kv_pair*)gpr_realloc(kvs->kvs, sizeof(*kvs->kvs) * kvs->cap_kvs); } kvs->kvs[kvs->num_kvs].key = key; kvs->kvs[kvs->num_kvs].value = value; kvs->num_kvs++; } -static char *key_int(grpc_error_ints which) { +static char* key_int(grpc_error_ints which) { return gpr_strdup(error_int_name(which)); } -static char *fmt_int(intptr_t p) { - char *s; +static char* fmt_int(intptr_t p) { + char* s; gpr_asprintf(&s, "%" PRIdPTR, p); return s; } -static void collect_ints_kvs(grpc_error *err, kv_pairs *kvs) { +static void collect_ints_kvs(grpc_error* err, kv_pairs* kvs) { for (size_t which = 0; which < GRPC_ERROR_INT_MAX; ++which) { uint8_t slot = err->ints[which]; if (slot != UINT8_MAX) { @@ -613,37 +612,37 @@ static void collect_ints_kvs(grpc_error *err, kv_pairs *kvs) { } } -static char *key_str(grpc_error_strs which) { +static char* key_str(grpc_error_strs which) { return gpr_strdup(error_str_name(which)); } -static char *fmt_str(grpc_slice slice) { - char *s = NULL; +static char* fmt_str(grpc_slice slice) { + char* s = nullptr; size_t sz = 0; size_t cap = 0; - append_esc_str((const uint8_t *)GRPC_SLICE_START_PTR(slice), + append_esc_str((const uint8_t*)GRPC_SLICE_START_PTR(slice), GRPC_SLICE_LENGTH(slice), &s, &sz, &cap); append_chr(0, &s, &sz, &cap); return s; } -static void collect_strs_kvs(grpc_error *err, kv_pairs *kvs) { +static void collect_strs_kvs(grpc_error* err, kv_pairs* kvs) { for (size_t which = 0; which < GRPC_ERROR_STR_MAX; ++which) { uint8_t slot = err->strs[which]; if (slot != UINT8_MAX) { append_kv(kvs, key_str((grpc_error_strs)which), - fmt_str(*(grpc_slice *)(err->arena + slot))); + fmt_str(*(grpc_slice*)(err->arena + slot))); } } } -static char *key_time(grpc_error_times which) { +static char* key_time(grpc_error_times which) { return gpr_strdup(error_time_name(which)); } -static char *fmt_time(gpr_timespec tm) { - char *out; - const char *pfx = "!!"; +static char* fmt_time(gpr_timespec tm) { + char* out; + const char* pfx = "!!"; switch (tm.clock_type) { case GPR_CLOCK_MONOTONIC: pfx = "@monotonic:"; @@ -662,24 +661,24 @@ static char *fmt_time(gpr_timespec tm) { return out; } -static void collect_times_kvs(grpc_error *err, kv_pairs *kvs) { +static void collect_times_kvs(grpc_error* err, kv_pairs* kvs) { for (size_t which = 0; which < GRPC_ERROR_TIME_MAX; ++which) { uint8_t slot = err->times[which]; if (slot != UINT8_MAX) { append_kv(kvs, key_time((grpc_error_times)which), - fmt_time(*(gpr_timespec *)(err->arena + slot))); + fmt_time(*(gpr_timespec*)(err->arena + slot))); } } } -static void add_errs(grpc_error *err, char **s, size_t *sz, size_t *cap) { +static void add_errs(grpc_error* err, char** s, size_t* sz, size_t* cap) { uint8_t slot = err->first_err; bool first = true; while (slot != UINT8_MAX) { - grpc_linked_error *lerr = (grpc_linked_error *)(err->arena + slot); + grpc_linked_error* lerr = (grpc_linked_error*)(err->arena + slot); if (!first) append_chr(',', s, sz, cap); first = false; - const char *e = grpc_error_string(lerr->err); + const char* e = grpc_error_string(lerr->err); append_str(e, s, sz, cap); GPR_ASSERT(err->last_err == slot ? lerr->next == UINT8_MAX : lerr->next != UINT8_MAX); @@ -687,8 +686,8 @@ static void add_errs(grpc_error *err, char **s, size_t *sz, size_t *cap) { } } -static char *errs_string(grpc_error *err) { - char *s = NULL; +static char* errs_string(grpc_error* err) { + char* s = nullptr; size_t sz = 0; size_t cap = 0; append_chr('[', &s, &sz, &cap); @@ -698,22 +697,22 @@ static char *errs_string(grpc_error *err) { return s; } -static int cmp_kvs(const void *a, const void *b) { - const kv_pair *ka = (const kv_pair *)a; - const kv_pair *kb = (const kv_pair *)b; +static int cmp_kvs(const void* a, const void* b) { + const kv_pair* ka = (const kv_pair*)a; + const kv_pair* kb = (const kv_pair*)b; return strcmp(ka->key, kb->key); } -static char *finish_kvs(kv_pairs *kvs) { - char *s = NULL; +static char* finish_kvs(kv_pairs* kvs) { + char* s = nullptr; size_t sz = 0; size_t cap = 0; append_chr('{', &s, &sz, &cap); for (size_t i = 0; i < kvs->num_kvs; i++) { if (i != 0) append_chr(',', &s, &sz, &cap); - append_esc_str((const uint8_t *)kvs->kvs[i].key, strlen(kvs->kvs[i].key), - &s, &sz, &cap); + append_esc_str((const uint8_t*)kvs->kvs[i].key, strlen(kvs->kvs[i].key), &s, + &sz, &cap); gpr_free(kvs->kvs[i].key); append_chr(':', &s, &sz, &cap); append_str(kvs->kvs[i].value, &s, &sz, &cap); @@ -726,16 +725,16 @@ static char *finish_kvs(kv_pairs *kvs) { return s; } -const char *grpc_error_string(grpc_error *err) { +const char* grpc_error_string(grpc_error* err) { GPR_TIMER_BEGIN("grpc_error_string", 0); if (err == GRPC_ERROR_NONE) return no_error_string; if (err == GRPC_ERROR_OOM) return oom_error_string; if (err == GRPC_ERROR_CANCELLED) return cancelled_error_string; - void *p = (void *)gpr_atm_acq_load(&err->atomics.error_string); - if (p != NULL) { + void* p = (void*)gpr_atm_acq_load(&err->atomics.error_string); + if (p != nullptr) { GPR_TIMER_END("grpc_error_string", 0); - return (const char *)p; + return (const char*)p; } kv_pairs kvs; @@ -750,25 +749,25 @@ const char *grpc_error_string(grpc_error *err) { qsort(kvs.kvs, kvs.num_kvs, sizeof(kv_pair), cmp_kvs); - char *out = finish_kvs(&kvs); + char* out = finish_kvs(&kvs); if (!gpr_atm_rel_cas(&err->atomics.error_string, 0, (gpr_atm)out)) { gpr_free(out); - out = (char *)gpr_atm_no_barrier_load(&err->atomics.error_string); + out = (char*)gpr_atm_no_barrier_load(&err->atomics.error_string); } GPR_TIMER_END("grpc_error_string", 0); return out; } -grpc_error *grpc_os_error(const char *file, int line, int err, - const char *call_name) { +grpc_error* grpc_os_error(const char* file, int line, int err, + const char* call_name) { return grpc_error_set_str( grpc_error_set_str( grpc_error_set_int( grpc_error_create(file, line, - grpc_slice_from_static_string("OS Error"), NULL, - 0), + grpc_slice_from_static_string("OS Error"), + nullptr, 0), GRPC_ERROR_INT_ERRNO, err), GRPC_ERROR_STR_OS_ERROR, grpc_slice_from_static_string(strerror(err))), @@ -776,10 +775,10 @@ grpc_error *grpc_os_error(const char *file, int line, int err, } #ifdef GPR_WINDOWS -grpc_error *grpc_wsa_error(const char *file, int line, int err, - const char *call_name) { - char *utf8_message = gpr_format_message(err); - grpc_error *error = grpc_error_set_str( +grpc_error* grpc_wsa_error(const char* file, int line, int err, + const char* call_name) { + char* utf8_message = gpr_format_message(err); + grpc_error* error = grpc_error_set_str( grpc_error_set_str( grpc_error_set_int( grpc_error_create(file, line, @@ -793,10 +792,10 @@ grpc_error *grpc_wsa_error(const char *file, int line, int err, } #endif -bool grpc_log_if_error(const char *what, grpc_error *error, const char *file, +bool grpc_log_if_error(const char* what, grpc_error* error, const char* file, int line) { if (error == GRPC_ERROR_NONE) return true; - const char *msg = grpc_error_string(error); + const char* msg = grpc_error_string(error); gpr_log(file, line, GPR_LOG_SEVERITY_ERROR, "%s: %s", what, msg); GRPC_ERROR_UNREF(error); return false; diff --git a/src/core/lib/iomgr/error.h b/src/core/lib/iomgr/error.h index b36330a7ab6..4759ee07919 100644 --- a/src/core/lib/iomgr/error.h +++ b/src/core/lib/iomgr/error.h @@ -24,23 +24,18 @@ #include #include +#include #include #include "src/core/lib/debug/trace.h" -#ifdef __cplusplus -extern "C" { -#endif - /// Opaque representation of an error. /// See https://github.com/grpc/grpc/blob/master/doc/core/grpc-error.md for a /// full write up of this object. typedef struct grpc_error grpc_error; -#ifndef NDEBUG -extern grpc_tracer_flag grpc_trace_error_refcount; -#endif +extern grpc_core::DebugOnlyTraceFlag grpc_trace_error_refcount; typedef enum { /// 'errno' from the operating system @@ -122,15 +117,15 @@ typedef enum { /// They are always even so that other code (particularly combiner locks, /// polling engines) can safely use the lower bit for themselves. -#define GRPC_ERROR_NONE ((grpc_error *)NULL) -#define GRPC_ERROR_OOM ((grpc_error *)2) -#define GRPC_ERROR_CANCELLED ((grpc_error *)4) +#define GRPC_ERROR_NONE ((grpc_error*)NULL) +#define GRPC_ERROR_OOM ((grpc_error*)2) +#define GRPC_ERROR_CANCELLED ((grpc_error*)4) -const char *grpc_error_string(grpc_error *error); +const char* grpc_error_string(grpc_error* error); /// Create an error - but use GRPC_ERROR_CREATE instead -grpc_error *grpc_error_create(const char *file, int line, grpc_slice desc, - grpc_error **referencing, size_t num_referencing); +grpc_error* grpc_error_create(const char* file, int line, grpc_slice desc, + grpc_error** referencing, size_t num_referencing); /// Create an error (this is the preferred way of generating an error that is /// not due to a system call - for system calls, use GRPC_OS_ERROR or /// GRPC_WSA_ERROR as appropriate) @@ -156,50 +151,52 @@ grpc_error *grpc_error_create(const char *file, int line, grpc_slice desc, errs, count) #ifndef NDEBUG -grpc_error *grpc_error_ref(grpc_error *err, const char *file, int line); -void grpc_error_unref(grpc_error *err, const char *file, int line); +grpc_error* grpc_error_ref(grpc_error* err, const char* file, int line); +void grpc_error_unref(grpc_error* err, const char* file, int line); #define GRPC_ERROR_REF(err) grpc_error_ref(err, __FILE__, __LINE__) #define GRPC_ERROR_UNREF(err) grpc_error_unref(err, __FILE__, __LINE__) #else -grpc_error *grpc_error_ref(grpc_error *err); -void grpc_error_unref(grpc_error *err); +grpc_error* grpc_error_ref(grpc_error* err); +void grpc_error_unref(grpc_error* err); #define GRPC_ERROR_REF(err) grpc_error_ref(err) #define GRPC_ERROR_UNREF(err) grpc_error_unref(err) #endif -grpc_error *grpc_error_set_int(grpc_error *src, grpc_error_ints which, +grpc_error* grpc_error_set_int(grpc_error* src, grpc_error_ints which, intptr_t value) GRPC_MUST_USE_RESULT; -bool grpc_error_get_int(grpc_error *error, grpc_error_ints which, intptr_t *p); -grpc_error *grpc_error_set_str(grpc_error *src, grpc_error_strs which, +bool grpc_error_get_int(grpc_error* error, grpc_error_ints which, intptr_t* p); +grpc_error* grpc_error_set_str(grpc_error* src, grpc_error_strs which, grpc_slice str) GRPC_MUST_USE_RESULT; /// Returns false if the specified string is not set. /// Caller does NOT own the slice. -bool grpc_error_get_str(grpc_error *error, grpc_error_strs which, - grpc_slice *s); +bool grpc_error_get_str(grpc_error* error, grpc_error_strs which, + grpc_slice* s); /// Add a child error: an error that is believed to have contributed to this /// error occurring. Allows root causing high level errors from lower level /// errors that contributed to them. -grpc_error *grpc_error_add_child(grpc_error *src, - grpc_error *child) GRPC_MUST_USE_RESULT; -grpc_error *grpc_os_error(const char *file, int line, int err, - const char *call_name) GRPC_MUST_USE_RESULT; +grpc_error* grpc_error_add_child(grpc_error* src, + grpc_error* child) GRPC_MUST_USE_RESULT; +grpc_error* grpc_os_error(const char* file, int line, int err, + const char* call_name) GRPC_MUST_USE_RESULT; + +inline grpc_error* grpc_assert_never_ok(grpc_error* error) { + GPR_ASSERT(error != GRPC_ERROR_NONE); + return error; +} + /// create an error associated with errno!=0 (an 'operating system' error) #define GRPC_OS_ERROR(err, call_name) \ - grpc_os_error(__FILE__, __LINE__, err, call_name) -grpc_error *grpc_wsa_error(const char *file, int line, int err, - const char *call_name) GRPC_MUST_USE_RESULT; + grpc_assert_never_ok(grpc_os_error(__FILE__, __LINE__, err, call_name)) +grpc_error* grpc_wsa_error(const char* file, int line, int err, + const char* call_name) GRPC_MUST_USE_RESULT; /// windows only: create an error associated with WSAGetLastError()!=0 #define GRPC_WSA_ERROR(err, call_name) \ grpc_wsa_error(__FILE__, __LINE__, err, call_name) -bool grpc_log_if_error(const char *what, grpc_error *error, const char *file, +bool grpc_log_if_error(const char* what, grpc_error* error, const char* file, int line); #define GRPC_LOG_IF_ERROR(what, error) \ grpc_log_if_error((what), (error), __FILE__, __LINE__) -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_ERROR_H */ diff --git a/src/core/lib/iomgr/error_internal.h b/src/core/lib/iomgr/error_internal.h index 8746d5d353f..6cb09c2cdbd 100644 --- a/src/core/lib/iomgr/error_internal.h +++ b/src/core/lib/iomgr/error_internal.h @@ -23,15 +23,12 @@ #include // TODO, do we need this? #include - -#ifdef __cplusplus -extern "C" { -#endif +#include "src/core/lib/iomgr/error.h" typedef struct grpc_linked_error grpc_linked_error; struct grpc_linked_error { - grpc_error *err; + grpc_error* err; uint8_t next; }; @@ -59,10 +56,6 @@ struct grpc_error { intptr_t arena[0]; }; -bool grpc_error_is_special(grpc_error *err); - -#ifdef __cplusplus -} -#endif +bool grpc_error_is_special(struct grpc_error* err); #endif /* GRPC_CORE_LIB_IOMGR_ERROR_INTERNAL_H */ diff --git a/src/core/lib/iomgr/ev_epoll1_linux.cc b/src/core/lib/iomgr/ev_epoll1_linux.cc index 6126e2771cd..0dda1d924c3 100644 --- a/src/core/lib/iomgr/ev_epoll1_linux.cc +++ b/src/core/lib/iomgr/ev_epoll1_linux.cc @@ -18,6 +18,8 @@ #include "src/core/lib/iomgr/port.h" +#include + /* This polling engine is only relevant on linux kernels supporting epoll() */ #ifdef GRPC_LINUX_EPOLL #include "src/core/lib/iomgr/ev_epoll1_linux.h" @@ -34,7 +36,6 @@ #include #include -#include #include #include #include @@ -46,6 +47,7 @@ #include "src/core/lib/iomgr/lockfree_event.h" #include "src/core/lib/iomgr/wakeup_fd_posix.h" #include "src/core/lib/profiling/timers.h" +#include "src/core/lib/support/manual_constructor.h" #include "src/core/lib/support/string.h" static grpc_wakeup_fd global_wakeup_fd; @@ -111,10 +113,10 @@ static void epoll_set_shutdown() { struct grpc_fd { int fd; - gpr_atm read_closure; - gpr_atm write_closure; + grpc_core::ManualConstructor read_closure; + grpc_core::ManualConstructor write_closure; - struct grpc_fd *freelist_next; + struct grpc_fd* freelist_next; /* The pollset that last noticed that the fd is readable. The actual type * stored in this is (grpc_pollset *) */ @@ -132,7 +134,7 @@ static void fd_global_shutdown(void); typedef enum { UNKICKED, KICKED, DESIGNATED_POLLER } kick_state; -static const char *kick_state_string(kick_state st) { +static const char* kick_state_string(kick_state st) { switch (st) { case UNKICKED: return "UNKICKED"; @@ -148,8 +150,8 @@ struct grpc_pollset_worker { kick_state state; int kick_state_mutator; // which line of code last changed kick state bool initialized_cv; - grpc_pollset_worker *next; - grpc_pollset_worker *prev; + grpc_pollset_worker* next; + grpc_pollset_worker* prev; gpr_cv cv; grpc_closure_list schedule_on_end_work; }; @@ -164,29 +166,29 @@ struct grpc_pollset_worker { typedef struct pollset_neighborhood { gpr_mu mu; - grpc_pollset *active_root; + grpc_pollset* active_root; char pad[GPR_CACHELINE_SIZE]; } pollset_neighborhood; struct grpc_pollset { gpr_mu mu; - pollset_neighborhood *neighborhood; + pollset_neighborhood* neighborhood; bool reassigning_neighborhood; - grpc_pollset_worker *root_worker; + grpc_pollset_worker* root_worker; bool kicked_without_poller; /* Set to true if the pollset is observed to have no workers available to poll */ bool seen_inactive; bool shutting_down; /* Is the pollset shutting down ? */ - grpc_closure *shutdown_closure; /* Called after after shutdown is complete */ + grpc_closure* shutdown_closure; /* Called after after shutdown is complete */ /* Number of workers who are *about-to* attach themselves to the pollset * worker list */ int begin_refs; - grpc_pollset *next; - grpc_pollset *prev; + grpc_pollset* next; + grpc_pollset* prev; }; /******************************************************************************* @@ -201,8 +203,8 @@ struct grpc_pollset_set { * Common helpers */ -static bool append_error(grpc_error **composite, grpc_error *error, - const char *desc) { +static bool append_error(grpc_error** composite, grpc_error* error, + const char* desc) { if (error == GRPC_ERROR_NONE) return true; if (*composite == GRPC_ERROR_NONE) { *composite = GRPC_ERROR_CREATE_FROM_COPIED_STRING(desc); @@ -233,7 +235,7 @@ static bool append_error(grpc_error **composite, grpc_error *error, * alarm 'epoch'). This wakeup_fd gives us something to alert on when such a * case occurs. */ -static grpc_fd *fd_freelist = NULL; +static grpc_fd* fd_freelist = nullptr; static gpr_mu fd_freelist_mu; static void fd_global_init(void) { gpr_mu_init(&fd_freelist_mu); } @@ -241,40 +243,42 @@ static void fd_global_init(void) { gpr_mu_init(&fd_freelist_mu); } static void fd_global_shutdown(void) { gpr_mu_lock(&fd_freelist_mu); gpr_mu_unlock(&fd_freelist_mu); - while (fd_freelist != NULL) { - grpc_fd *fd = fd_freelist; + while (fd_freelist != nullptr) { + grpc_fd* fd = fd_freelist; fd_freelist = fd_freelist->freelist_next; gpr_free(fd); } gpr_mu_destroy(&fd_freelist_mu); } -static grpc_fd *fd_create(int fd, const char *name) { - grpc_fd *new_fd = NULL; +static grpc_fd* fd_create(int fd, const char* name) { + grpc_fd* new_fd = nullptr; gpr_mu_lock(&fd_freelist_mu); - if (fd_freelist != NULL) { + if (fd_freelist != nullptr) { new_fd = fd_freelist; fd_freelist = fd_freelist->freelist_next; } gpr_mu_unlock(&fd_freelist_mu); - if (new_fd == NULL) { - new_fd = (grpc_fd *)gpr_malloc(sizeof(grpc_fd)); + if (new_fd == nullptr) { + new_fd = (grpc_fd*)gpr_malloc(sizeof(grpc_fd)); + new_fd->read_closure.Init(); + new_fd->write_closure.Init(); } new_fd->fd = fd; - grpc_lfev_init(&new_fd->read_closure); - grpc_lfev_init(&new_fd->write_closure); + new_fd->read_closure->InitEvent(); + new_fd->write_closure->InitEvent(); gpr_atm_no_barrier_store(&new_fd->read_notifier_pollset, (gpr_atm)NULL); - new_fd->freelist_next = NULL; + new_fd->freelist_next = nullptr; - char *fd_name; + char* fd_name; gpr_asprintf(&fd_name, "%s fd=%d", name, fd); grpc_iomgr_register_object(&new_fd->iomgr_object, fd_name); #ifndef NDEBUG - if (GRPC_TRACER_ON(grpc_trace_fd_refcount)) { + if (grpc_trace_fd_refcount.enabled()) { gpr_log(GPR_DEBUG, "FD %d %p create %s", fd, new_fd, fd_name); } #endif @@ -290,35 +294,34 @@ static grpc_fd *fd_create(int fd, const char *name) { return new_fd; } -static int fd_wrapped_fd(grpc_fd *fd) { return fd->fd; } +static int fd_wrapped_fd(grpc_fd* fd) { return fd->fd; } /* if 'releasing_fd' is true, it means that we are going to detach the internal * fd from grpc_fd structure (i.e which means we should not be calling * shutdown() syscall on that fd) */ -static void fd_shutdown_internal(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_error *why, bool releasing_fd) { - if (grpc_lfev_set_shutdown(exec_ctx, &fd->read_closure, - GRPC_ERROR_REF(why))) { +static void fd_shutdown_internal(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_error* why, bool releasing_fd) { + if (fd->read_closure->SetShutdown(exec_ctx, GRPC_ERROR_REF(why))) { if (!releasing_fd) { shutdown(fd->fd, SHUT_RDWR); } - grpc_lfev_set_shutdown(exec_ctx, &fd->write_closure, GRPC_ERROR_REF(why)); + fd->write_closure->SetShutdown(exec_ctx, GRPC_ERROR_REF(why)); } GRPC_ERROR_UNREF(why); } /* Might be called multiple times */ -static void fd_shutdown(grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_error *why) { +static void fd_shutdown(grpc_exec_ctx* exec_ctx, grpc_fd* fd, grpc_error* why) { fd_shutdown_internal(exec_ctx, fd, why, false); } -static void fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *on_done, int *release_fd, - bool already_closed, const char *reason) { - grpc_error *error = GRPC_ERROR_NONE; - bool is_release_fd = (release_fd != NULL); +static void fd_orphan(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* on_done, int* release_fd, + bool already_closed, const char* reason) { + grpc_error* error = GRPC_ERROR_NONE; + bool is_release_fd = (release_fd != nullptr); - if (!grpc_lfev_is_shutdown(&fd->read_closure)) { + if (!fd->read_closure->IsShutdown()) { fd_shutdown_internal(exec_ctx, fd, GRPC_ERROR_CREATE_FROM_COPIED_STRING(reason), is_release_fd); @@ -335,8 +338,8 @@ static void fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd, GRPC_CLOSURE_SCHED(exec_ctx, on_done, GRPC_ERROR_REF(error)); grpc_iomgr_unregister_object(&fd->iomgr_object); - grpc_lfev_destroy(&fd->read_closure); - grpc_lfev_destroy(&fd->write_closure); + fd->read_closure->DestroyEvent(); + fd->write_closure->DestroyEvent(); gpr_mu_lock(&fd_freelist_mu); fd->freelist_next = fd_freelist; @@ -344,35 +347,35 @@ static void fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd, gpr_mu_unlock(&fd_freelist_mu); } -static grpc_pollset *fd_get_read_notifier_pollset(grpc_exec_ctx *exec_ctx, - grpc_fd *fd) { +static grpc_pollset* fd_get_read_notifier_pollset(grpc_exec_ctx* exec_ctx, + grpc_fd* fd) { gpr_atm notifier = gpr_atm_acq_load(&fd->read_notifier_pollset); - return (grpc_pollset *)notifier; + return (grpc_pollset*)notifier; } -static bool fd_is_shutdown(grpc_fd *fd) { - return grpc_lfev_is_shutdown(&fd->read_closure); +static bool fd_is_shutdown(grpc_fd* fd) { + return fd->read_closure->IsShutdown(); } -static void fd_notify_on_read(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *closure) { - grpc_lfev_notify_on(exec_ctx, &fd->read_closure, closure, "read"); +static void fd_notify_on_read(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* closure) { + fd->read_closure->NotifyOn(exec_ctx, closure); } -static void fd_notify_on_write(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *closure) { - grpc_lfev_notify_on(exec_ctx, &fd->write_closure, closure, "write"); +static void fd_notify_on_write(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* closure) { + fd->write_closure->NotifyOn(exec_ctx, closure); } -static void fd_become_readable(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_pollset *notifier) { - grpc_lfev_set_ready(exec_ctx, &fd->read_closure, "read"); +static void fd_become_readable(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_pollset* notifier) { + fd->read_closure->SetReady(exec_ctx); /* Use release store to match with acquire load in fd_get_read_notifier */ gpr_atm_rel_store(&fd->read_notifier_pollset, (gpr_atm)notifier); } -static void fd_become_writable(grpc_exec_ctx *exec_ctx, grpc_fd *fd) { - grpc_lfev_set_ready(exec_ctx, &fd->write_closure, "write"); +static void fd_become_writable(grpc_exec_ctx* exec_ctx, grpc_fd* fd) { + fd->write_closure->SetReady(exec_ctx); } /******************************************************************************* @@ -385,12 +388,12 @@ GPR_TLS_DECL(g_current_thread_worker); /* The designated poller */ static gpr_atm g_active_poller; -static pollset_neighborhood *g_neighborhoods; +static pollset_neighborhood* g_neighborhoods; static size_t g_num_neighborhoods; /* Return true if first in list */ -static bool worker_insert(grpc_pollset *pollset, grpc_pollset_worker *worker) { - if (pollset->root_worker == NULL) { +static bool worker_insert(grpc_pollset* pollset, grpc_pollset_worker* worker) { + if (pollset->root_worker == nullptr) { pollset->root_worker = worker; worker->next = worker->prev = worker; return true; @@ -406,11 +409,11 @@ static bool worker_insert(grpc_pollset *pollset, grpc_pollset_worker *worker) { /* Return true if last in list */ typedef enum { EMPTIED, NEW_ROOT, REMOVED } worker_remove_result; -static worker_remove_result worker_remove(grpc_pollset *pollset, - grpc_pollset_worker *worker) { +static worker_remove_result worker_remove(grpc_pollset* pollset, + grpc_pollset_worker* worker) { if (worker == pollset->root_worker) { if (worker == worker->next) { - pollset->root_worker = NULL; + pollset->root_worker = nullptr; return EMPTIED; } else { pollset->root_worker = worker->next; @@ -429,12 +432,12 @@ static size_t choose_neighborhood(void) { return (size_t)gpr_cpu_current_cpu() % g_num_neighborhoods; } -static grpc_error *pollset_global_init(void) { +static grpc_error* pollset_global_init(void) { gpr_tls_init(&g_current_thread_pollset); gpr_tls_init(&g_current_thread_worker); gpr_atm_no_barrier_store(&g_active_poller, 0); global_wakeup_fd.read_fd = -1; - grpc_error *err = grpc_wakeup_fd_init(&global_wakeup_fd); + grpc_error* err = grpc_wakeup_fd_init(&global_wakeup_fd); if (err != GRPC_ERROR_NONE) return err; struct epoll_event ev; ev.events = (uint32_t)(EPOLLIN | EPOLLET); @@ -444,8 +447,8 @@ static grpc_error *pollset_global_init(void) { return GRPC_OS_ERROR(errno, "epoll_ctl"); } g_num_neighborhoods = GPR_CLAMP(gpr_cpu_num_cores(), 1, MAX_NEIGHBORHOODS); - g_neighborhoods = (pollset_neighborhood *)gpr_zalloc( - sizeof(*g_neighborhoods) * g_num_neighborhoods); + g_neighborhoods = (pollset_neighborhood*)gpr_zalloc(sizeof(*g_neighborhoods) * + g_num_neighborhoods); for (size_t i = 0; i < g_num_neighborhoods; i++) { gpr_mu_init(&g_neighborhoods[i].mu); } @@ -462,24 +465,24 @@ static void pollset_global_shutdown(void) { gpr_free(g_neighborhoods); } -static void pollset_init(grpc_pollset *pollset, gpr_mu **mu) { +static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) { gpr_mu_init(&pollset->mu); *mu = &pollset->mu; pollset->neighborhood = &g_neighborhoods[choose_neighborhood()]; pollset->reassigning_neighborhood = false; - pollset->root_worker = NULL; + pollset->root_worker = nullptr; pollset->kicked_without_poller = false; pollset->seen_inactive = true; pollset->shutting_down = false; - pollset->shutdown_closure = NULL; + pollset->shutdown_closure = nullptr; pollset->begin_refs = 0; - pollset->next = pollset->prev = NULL; + pollset->next = pollset->prev = nullptr; } -static void pollset_destroy(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset) { +static void pollset_destroy(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset) { gpr_mu_lock(&pollset->mu); if (!pollset->seen_inactive) { - pollset_neighborhood *neighborhood = pollset->neighborhood; + pollset_neighborhood* neighborhood = pollset->neighborhood; gpr_mu_unlock(&pollset->mu); retry_lock_neighborhood: gpr_mu_lock(&neighborhood->mu); @@ -495,7 +498,7 @@ static void pollset_destroy(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset) { pollset->next->prev = pollset->prev; if (pollset == pollset->neighborhood->active_root) { pollset->neighborhood->active_root = - pollset->next == pollset ? NULL : pollset->next; + pollset->next == pollset ? nullptr : pollset->next; } } gpr_mu_unlock(&pollset->neighborhood->mu); @@ -504,12 +507,12 @@ static void pollset_destroy(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset) { gpr_mu_destroy(&pollset->mu); } -static grpc_error *pollset_kick_all(grpc_exec_ctx *exec_ctx, - grpc_pollset *pollset) { +static grpc_error* pollset_kick_all(grpc_exec_ctx* exec_ctx, + grpc_pollset* pollset) { GPR_TIMER_BEGIN("pollset_kick_all", 0); - grpc_error *error = GRPC_ERROR_NONE; - if (pollset->root_worker != NULL) { - grpc_pollset_worker *worker = pollset->root_worker; + grpc_error* error = GRPC_ERROR_NONE; + if (pollset->root_worker != nullptr) { + grpc_pollset_worker* worker = pollset->root_worker; do { GRPC_STATS_INC_POLLSET_KICK(exec_ctx); switch (worker->state) { @@ -540,20 +543,20 @@ static grpc_error *pollset_kick_all(grpc_exec_ctx *exec_ctx, return error; } -static void pollset_maybe_finish_shutdown(grpc_exec_ctx *exec_ctx, - grpc_pollset *pollset) { - if (pollset->shutdown_closure != NULL && pollset->root_worker == NULL && +static void pollset_maybe_finish_shutdown(grpc_exec_ctx* exec_ctx, + grpc_pollset* pollset) { + if (pollset->shutdown_closure != nullptr && pollset->root_worker == nullptr && pollset->begin_refs == 0) { GPR_TIMER_MARK("pollset_finish_shutdown", 0); GRPC_CLOSURE_SCHED(exec_ctx, pollset->shutdown_closure, GRPC_ERROR_NONE); - pollset->shutdown_closure = NULL; + pollset->shutdown_closure = nullptr; } } -static void pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_closure *closure) { +static void pollset_shutdown(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_closure* closure) { GPR_TIMER_BEGIN("pollset_shutdown", 0); - GPR_ASSERT(pollset->shutdown_closure == NULL); + GPR_ASSERT(pollset->shutdown_closure == nullptr); GPR_ASSERT(!pollset->shutting_down); pollset->shutdown_closure = closure; pollset->shutting_down = true; @@ -562,7 +565,7 @@ static void pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, GPR_TIMER_END("pollset_shutdown", 0); } -static int poll_deadline_to_millis_timeout(grpc_exec_ctx *exec_ctx, +static int poll_deadline_to_millis_timeout(grpc_exec_ctx* exec_ctx, grpc_millis millis) { if (millis == GRPC_MILLIS_INF_FUTURE) return -1; grpc_millis delta = millis - grpc_exec_ctx_now(exec_ctx); @@ -583,10 +586,10 @@ static int poll_deadline_to_millis_timeout(grpc_exec_ctx *exec_ctx, NOTE ON SYNCRHONIZATION: Similar to do_epoll_wait(), this function is only called by g_active_poller thread. So there is no need for synchronization when accessing fields in g_epoll_set */ -static grpc_error *process_epoll_events(grpc_exec_ctx *exec_ctx, - grpc_pollset *pollset) { - static const char *err_desc = "process_events"; - grpc_error *error = GRPC_ERROR_NONE; +static grpc_error* process_epoll_events(grpc_exec_ctx* exec_ctx, + grpc_pollset* pollset) { + static const char* err_desc = "process_events"; + grpc_error* error = GRPC_ERROR_NONE; GPR_TIMER_BEGIN("process_epoll_events", 0); long num_events = gpr_atm_acq_load(&g_epoll_set.num_events); @@ -595,14 +598,14 @@ static grpc_error *process_epoll_events(grpc_exec_ctx *exec_ctx, (idx < MAX_EPOLL_EVENTS_HANDLED_PER_ITERATION) && cursor != num_events; idx++) { long c = cursor++; - struct epoll_event *ev = &g_epoll_set.events[c]; - void *data_ptr = ev->data.ptr; + struct epoll_event* ev = &g_epoll_set.events[c]; + void* data_ptr = ev->data.ptr; if (data_ptr == &global_wakeup_fd) { append_error(&error, grpc_wakeup_fd_consume_wakeup(&global_wakeup_fd), err_desc); } else { - grpc_fd *fd = (grpc_fd *)(data_ptr); + grpc_fd* fd = (grpc_fd*)(data_ptr); bool cancel = (ev->events & (EPOLLERR | EPOLLHUP)) != 0; bool read_ev = (ev->events & (EPOLLIN | EPOLLPRI)) != 0; bool write_ev = (ev->events & EPOLLOUT) != 0; @@ -628,7 +631,7 @@ static grpc_error *process_epoll_events(grpc_exec_ctx *exec_ctx, NOTE ON SYNCHRONIZATION: At any point of time, only the g_active_poller (i.e the designated poller thread) will be calling this function. So there is no need for any synchronization when accesing fields in g_epoll_set */ -static grpc_error *do_epoll_wait(grpc_exec_ctx *exec_ctx, grpc_pollset *ps, +static grpc_error* do_epoll_wait(grpc_exec_ctx* exec_ctx, grpc_pollset* ps, grpc_millis deadline) { GPR_TIMER_BEGIN("do_epoll_wait", 0); @@ -650,7 +653,7 @@ static grpc_error *do_epoll_wait(grpc_exec_ctx *exec_ctx, grpc_pollset *ps, GRPC_STATS_INC_POLL_EVENTS_RETURNED(exec_ctx, r); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "ps: %p poll got %d events", ps, r); } @@ -661,18 +664,18 @@ static grpc_error *do_epoll_wait(grpc_exec_ctx *exec_ctx, grpc_pollset *ps, return GRPC_ERROR_NONE; } -static bool begin_worker(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker *worker, - grpc_pollset_worker **worker_hdl, +static bool begin_worker(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker* worker, + grpc_pollset_worker** worker_hdl, grpc_millis deadline) { GPR_TIMER_BEGIN("begin_worker", 0); - if (worker_hdl != NULL) *worker_hdl = worker; + if (worker_hdl != nullptr) *worker_hdl = worker; worker->initialized_cv = false; SET_KICK_STATE(worker, UNKICKED); worker->schedule_on_end_work = (grpc_closure_list)GRPC_CLOSURE_LIST_INIT; pollset->begin_refs++; - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_ERROR, "PS:%p BEGIN_STARTS:%p", pollset, worker); } @@ -685,13 +688,13 @@ static bool begin_worker(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, pollset->reassigning_neighborhood = true; pollset->neighborhood = &g_neighborhoods[choose_neighborhood()]; } - pollset_neighborhood *neighborhood = pollset->neighborhood; + pollset_neighborhood* neighborhood = pollset->neighborhood; gpr_mu_unlock(&pollset->mu); // pollset unlocked: state may change (even worker->kick_state) retry_lock_neighborhood: gpr_mu_lock(&neighborhood->mu); gpr_mu_lock(&pollset->mu); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_ERROR, "PS:%p BEGIN_REORG:%p kick_state=%s is_reassigning=%d", pollset, worker, kick_state_string(worker->state), is_reassigning); @@ -715,7 +718,7 @@ static bool begin_worker(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, not visible in the "kick any" path yet */ if (worker->state == UNKICKED) { pollset->seen_inactive = false; - if (neighborhood->active_root == NULL) { + if (neighborhood->active_root == nullptr) { neighborhood->active_root = pollset->next = pollset->prev = pollset; /* Make this the designated poller if there isn't one already */ if (worker->state == UNKICKED && @@ -743,7 +746,7 @@ static bool begin_worker(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, worker->initialized_cv = true; gpr_cv_init(&worker->cv); while (worker->state == UNKICKED && !pollset->shutting_down) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_ERROR, "PS:%p BEGIN_WAIT:%p kick_state=%s shutdown=%d", pollset, worker, kick_state_string(worker->state), pollset->shutting_down); @@ -760,7 +763,7 @@ static bool begin_worker(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, grpc_exec_ctx_invalidate_now(exec_ctx); } - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_ERROR, "PS:%p BEGIN_DONE:%p kick_state=%s shutdown=%d " "kicked_without_poller: %d", @@ -788,24 +791,24 @@ static bool begin_worker(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, } static bool check_neighborhood_for_available_poller( - grpc_exec_ctx *exec_ctx, pollset_neighborhood *neighborhood) { + grpc_exec_ctx* exec_ctx, pollset_neighborhood* neighborhood) { GPR_TIMER_BEGIN("check_neighborhood_for_available_poller", 0); bool found_worker = false; do { - grpc_pollset *inspect = neighborhood->active_root; - if (inspect == NULL) { + grpc_pollset* inspect = neighborhood->active_root; + if (inspect == nullptr) { break; } gpr_mu_lock(&inspect->mu); GPR_ASSERT(!inspect->seen_inactive); - grpc_pollset_worker *inspect_worker = inspect->root_worker; - if (inspect_worker != NULL) { + grpc_pollset_worker* inspect_worker = inspect->root_worker; + if (inspect_worker != nullptr) { do { switch (inspect_worker->state) { case UNKICKED: if (gpr_atm_no_barrier_cas(&g_active_poller, 0, (gpr_atm)inspect_worker)) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, " .. choose next poller to be %p", inspect_worker); } @@ -816,7 +819,7 @@ static bool check_neighborhood_for_available_poller( gpr_cv_signal(&inspect_worker->cv); } } else { - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, " .. beaten to choose next poller"); } } @@ -834,17 +837,17 @@ static bool check_neighborhood_for_available_poller( } while (!found_worker && inspect_worker != inspect->root_worker); } if (!found_worker) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, " .. mark pollset %p inactive", inspect); } inspect->seen_inactive = true; if (inspect == neighborhood->active_root) { neighborhood->active_root = - inspect->next == inspect ? NULL : inspect->next; + inspect->next == inspect ? nullptr : inspect->next; } inspect->next->prev = inspect->prev; inspect->prev->next = inspect->next; - inspect->next = inspect->prev = NULL; + inspect->next = inspect->prev = nullptr; } gpr_mu_unlock(&inspect->mu); } while (!found_worker); @@ -852,21 +855,21 @@ static bool check_neighborhood_for_available_poller( return found_worker; } -static void end_worker(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker *worker, - grpc_pollset_worker **worker_hdl) { +static void end_worker(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker* worker, + grpc_pollset_worker** worker_hdl) { GPR_TIMER_BEGIN("end_worker", 0); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PS:%p END_WORKER:%p", pollset, worker); } - if (worker_hdl != NULL) *worker_hdl = NULL; + if (worker_hdl != nullptr) *worker_hdl = nullptr; /* Make sure we appear kicked */ SET_KICK_STATE(worker, KICKED); grpc_closure_list_move(&worker->schedule_on_end_work, &exec_ctx->closure_list); if (gpr_atm_no_barrier_load(&g_active_poller) == (gpr_atm)worker) { if (worker->next != worker && worker->next->state == UNKICKED) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, " .. choose next poller to be peer %p", worker); } GPR_ASSERT(worker->next->initialized_cv); @@ -887,7 +890,7 @@ static void end_worker(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, bool found_worker = false; bool scan_state[MAX_NEIGHBORHOODS]; for (size_t i = 0; !found_worker && i < g_num_neighborhoods; i++) { - pollset_neighborhood *neighborhood = + pollset_neighborhood* neighborhood = &g_neighborhoods[(poller_neighborhood_idx + i) % g_num_neighborhoods]; if (gpr_mu_trylock(&neighborhood->mu)) { @@ -901,7 +904,7 @@ static void end_worker(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, } for (size_t i = 0; !found_worker && i < g_num_neighborhoods; i++) { if (scan_state[i]) continue; - pollset_neighborhood *neighborhood = + pollset_neighborhood* neighborhood = &g_neighborhoods[(poller_neighborhood_idx + i) % g_num_neighborhoods]; gpr_mu_lock(&neighborhood->mu); @@ -920,7 +923,7 @@ static void end_worker(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, if (worker->initialized_cv) { gpr_cv_destroy(&worker->cv); } - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, " .. remove worker"); } if (EMPTIED == worker_remove(pollset, worker)) { @@ -934,12 +937,12 @@ static void end_worker(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, The function pollset_work() may temporarily release the lock (pollset->po.mu) during the course of its execution but it will always re-acquire the lock and ensure that it is held by the time the function returns */ -static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *ps, - grpc_pollset_worker **worker_hdl, +static grpc_error* pollset_work(grpc_exec_ctx* exec_ctx, grpc_pollset* ps, + grpc_pollset_worker** worker_hdl, grpc_millis deadline) { grpc_pollset_worker worker; - grpc_error *error = GRPC_ERROR_NONE; - static const char *err_desc = "pollset_work"; + grpc_error* error = GRPC_ERROR_NONE; + static const char* err_desc = "pollset_work"; GPR_TIMER_BEGIN("pollset_work", 0); if (ps->kicked_without_poller) { ps->kicked_without_poller = false; @@ -987,60 +990,60 @@ static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *ps, return error; } -static grpc_error *pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker *specific_worker) { +static grpc_error* pollset_kick(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker* specific_worker) { GPR_TIMER_BEGIN("pollset_kick", 0); GRPC_STATS_INC_POLLSET_KICK(exec_ctx); - grpc_error *ret_err = GRPC_ERROR_NONE; - if (GRPC_TRACER_ON(grpc_polling_trace)) { + grpc_error* ret_err = GRPC_ERROR_NONE; + if (grpc_polling_trace.enabled()) { gpr_strvec log; gpr_strvec_init(&log); - char *tmp; - gpr_asprintf( - &tmp, "PS:%p KICK:%p curps=%p curworker=%p root=%p", pollset, - specific_worker, (void *)gpr_tls_get(&g_current_thread_pollset), - (void *)gpr_tls_get(&g_current_thread_worker), pollset->root_worker); + char* tmp; + gpr_asprintf(&tmp, "PS:%p KICK:%p curps=%p curworker=%p root=%p", pollset, + specific_worker, (void*)gpr_tls_get(&g_current_thread_pollset), + (void*)gpr_tls_get(&g_current_thread_worker), + pollset->root_worker); gpr_strvec_add(&log, tmp); - if (pollset->root_worker != NULL) { + if (pollset->root_worker != nullptr) { gpr_asprintf(&tmp, " {kick_state=%s next=%p {kick_state=%s}}", kick_state_string(pollset->root_worker->state), pollset->root_worker->next, kick_state_string(pollset->root_worker->next->state)); gpr_strvec_add(&log, tmp); } - if (specific_worker != NULL) { + if (specific_worker != nullptr) { gpr_asprintf(&tmp, " worker_kick_state=%s", kick_state_string(specific_worker->state)); gpr_strvec_add(&log, tmp); } - tmp = gpr_strvec_flatten(&log, NULL); + tmp = gpr_strvec_flatten(&log, nullptr); gpr_strvec_destroy(&log); gpr_log(GPR_ERROR, "%s", tmp); gpr_free(tmp); } - if (specific_worker == NULL) { + if (specific_worker == nullptr) { if (gpr_tls_get(&g_current_thread_pollset) != (intptr_t)pollset) { - grpc_pollset_worker *root_worker = pollset->root_worker; - if (root_worker == NULL) { + grpc_pollset_worker* root_worker = pollset->root_worker; + if (root_worker == nullptr) { GRPC_STATS_INC_POLLSET_KICKED_WITHOUT_POLLER(exec_ctx); pollset->kicked_without_poller = true; - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_ERROR, " .. kicked_without_poller"); } goto done; } - grpc_pollset_worker *next_worker = root_worker->next; + grpc_pollset_worker* next_worker = root_worker->next; if (root_worker->state == KICKED) { GRPC_STATS_INC_POLLSET_KICKED_AGAIN(exec_ctx); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_ERROR, " .. already kicked %p", root_worker); } SET_KICK_STATE(root_worker, KICKED); goto done; } else if (next_worker->state == KICKED) { GRPC_STATS_INC_POLLSET_KICKED_AGAIN(exec_ctx); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_ERROR, " .. already kicked %p", next_worker); } SET_KICK_STATE(next_worker, KICKED); @@ -1048,10 +1051,10 @@ static grpc_error *pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, } else if (root_worker == next_worker && // only try and wake up a poller if // there is no next worker - root_worker == (grpc_pollset_worker *)gpr_atm_no_barrier_load( + root_worker == (grpc_pollset_worker*)gpr_atm_no_barrier_load( &g_active_poller)) { GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD(exec_ctx); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_ERROR, " .. kicked %p", root_worker); } SET_KICK_STATE(root_worker, KICKED); @@ -1059,7 +1062,7 @@ static grpc_error *pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, goto done; } else if (next_worker->state == UNKICKED) { GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV(exec_ctx); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_ERROR, " .. kicked %p", next_worker); } GPR_ASSERT(next_worker->initialized_cv); @@ -1068,7 +1071,7 @@ static grpc_error *pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, goto done; } else if (next_worker->state == DESIGNATED_POLLER) { if (root_worker->state != DESIGNATED_POLLER) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log( GPR_ERROR, " .. kicked root non-poller %p (initialized_cv=%d) (poller=%p)", @@ -1082,7 +1085,7 @@ static grpc_error *pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, goto done; } else { GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD(exec_ctx); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_ERROR, " .. non-root poller %p (root=%p)", next_worker, root_worker); } @@ -1098,7 +1101,7 @@ static grpc_error *pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, } } else { GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD(exec_ctx); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_ERROR, " .. kicked while waking up"); } goto done; @@ -1108,22 +1111,22 @@ static grpc_error *pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, } if (specific_worker->state == KICKED) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_ERROR, " .. specific worker already kicked"); } goto done; } else if (gpr_tls_get(&g_current_thread_worker) == (intptr_t)specific_worker) { GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD(exec_ctx); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_ERROR, " .. mark %p kicked", specific_worker); } SET_KICK_STATE(specific_worker, KICKED); goto done; } else if (specific_worker == - (grpc_pollset_worker *)gpr_atm_no_barrier_load(&g_active_poller)) { + (grpc_pollset_worker*)gpr_atm_no_barrier_load(&g_active_poller)) { GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD(exec_ctx); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_ERROR, " .. kick active poller"); } SET_KICK_STATE(specific_worker, KICKED); @@ -1131,7 +1134,7 @@ static grpc_error *pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, goto done; } else if (specific_worker->initialized_cv) { GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV(exec_ctx); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_ERROR, " .. kick waiting worker"); } SET_KICK_STATE(specific_worker, KICKED); @@ -1139,7 +1142,7 @@ static grpc_error *pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, goto done; } else { GRPC_STATS_INC_POLLSET_KICKED_AGAIN(exec_ctx); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_ERROR, " .. kick non-waiting worker"); } SET_KICK_STATE(specific_worker, KICKED); @@ -1150,39 +1153,39 @@ done: return ret_err; } -static void pollset_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_fd *fd) {} +static void pollset_add_fd(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_fd* fd) {} /******************************************************************************* * Pollset-set Definitions */ -static grpc_pollset_set *pollset_set_create(void) { - return (grpc_pollset_set *)((intptr_t)0xdeafbeef); +static grpc_pollset_set* pollset_set_create(void) { + return (grpc_pollset_set*)((intptr_t)0xdeafbeef); } -static void pollset_set_destroy(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pss) {} +static void pollset_set_destroy(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pss) {} -static void pollset_set_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset_set *pss, - grpc_fd *fd) {} +static void pollset_set_add_fd(grpc_exec_ctx* exec_ctx, grpc_pollset_set* pss, + grpc_fd* fd) {} -static void pollset_set_del_fd(grpc_exec_ctx *exec_ctx, grpc_pollset_set *pss, - grpc_fd *fd) {} +static void pollset_set_del_fd(grpc_exec_ctx* exec_ctx, grpc_pollset_set* pss, + grpc_fd* fd) {} -static void pollset_set_add_pollset(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pss, grpc_pollset *ps) {} +static void pollset_set_add_pollset(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pss, grpc_pollset* ps) {} -static void pollset_set_del_pollset(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pss, grpc_pollset *ps) {} +static void pollset_set_del_pollset(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pss, grpc_pollset* ps) {} -static void pollset_set_add_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *bag, - grpc_pollset_set *item) {} +static void pollset_set_add_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* bag, + grpc_pollset_set* item) {} -static void pollset_set_del_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *bag, - grpc_pollset_set *item) {} +static void pollset_set_del_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* bag, + grpc_pollset_set* item) {} /******************************************************************************* * Event engine binding @@ -1228,13 +1231,14 @@ static const grpc_event_engine_vtable vtable = { /* It is possible that GLIBC has epoll but the underlying kernel doesn't. * Create epoll_fd (epoll_set_init() takes care of that) to make sure epoll * support is available */ -const grpc_event_engine_vtable *grpc_init_epoll1_linux(bool explicit_request) { +const grpc_event_engine_vtable* grpc_init_epoll1_linux(bool explicit_request) { if (!grpc_has_wakeup_fd()) { - return NULL; + gpr_log(GPR_ERROR, "Skipping epoll1 because of no wakeup fd."); + return nullptr; } if (!epoll_set_init()) { - return NULL; + return nullptr; } fd_global_init(); @@ -1242,7 +1246,7 @@ const grpc_event_engine_vtable *grpc_init_epoll1_linux(bool explicit_request) { if (!GRPC_LOG_IF_ERROR("pollset_global_init", pollset_global_init())) { fd_global_shutdown(); epoll_set_shutdown(); - return NULL; + return nullptr; } return &vtable; @@ -1253,7 +1257,9 @@ const grpc_event_engine_vtable *grpc_init_epoll1_linux(bool explicit_request) { #include "src/core/lib/iomgr/ev_epoll1_linux.h" /* If GRPC_LINUX_EPOLL is not defined, it means epoll is not available. Return * NULL */ -const grpc_event_engine_vtable *grpc_init_epoll1_linux(bool explicit_request) { +const grpc_event_engine_vtable* grpc_init_epoll1_linux(bool explicit_request) { + gpr_log(GPR_ERROR, + "Skipping epoll1 becuase GRPC_LINUX_EPOLL is not defined."); return NULL; } #endif /* defined(GRPC_POSIX_SOCKET) */ diff --git a/src/core/lib/iomgr/ev_epoll1_linux.h b/src/core/lib/iomgr/ev_epoll1_linux.h index b437032b368..9a1b96bd45a 100644 --- a/src/core/lib/iomgr/ev_epoll1_linux.h +++ b/src/core/lib/iomgr/ev_epoll1_linux.h @@ -22,16 +22,8 @@ #include "src/core/lib/iomgr/ev_posix.h" #include "src/core/lib/iomgr/port.h" -#ifdef __cplusplus -extern "C" { -#endif - // a polling engine that utilizes a singleton epoll set and turnstile polling -const grpc_event_engine_vtable *grpc_init_epoll1_linux(bool explicit_request); - -#ifdef __cplusplus -} -#endif +const grpc_event_engine_vtable* grpc_init_epoll1_linux(bool explicit_request); #endif /* GRPC_CORE_LIB_IOMGR_EV_EPOLL1_LINUX_H */ diff --git a/src/core/lib/iomgr/ev_epollex_linux.cc b/src/core/lib/iomgr/ev_epollex_linux.cc index 0809d574a96..62643df697d 100644 --- a/src/core/lib/iomgr/ev_epollex_linux.cc +++ b/src/core/lib/iomgr/ev_epollex_linux.cc @@ -18,6 +18,8 @@ #include "src/core/lib/iomgr/port.h" +#include + /* This polling engine is only relevant on linux kernels supporting epoll() */ #ifdef GRPC_LINUX_EPOLL @@ -34,7 +36,6 @@ #include #include -#include #include #include #include @@ -48,6 +49,7 @@ #include "src/core/lib/iomgr/timer.h" #include "src/core/lib/iomgr/wakeup_fd_posix.h" #include "src/core/lib/profiling/timers.h" +#include "src/core/lib/support/manual_constructor.h" #include "src/core/lib/support/spinlock.h" // debug aid: create workers on the heap (allows asan to spot @@ -57,10 +59,8 @@ #define MAX_EPOLL_EVENTS 100 #define MAX_EPOLL_EVENTS_HANDLED_EACH_POLL_CALL 5 -#ifndef NDEBUG -grpc_tracer_flag grpc_trace_pollable_refcount = - GRPC_TRACER_INITIALIZER(false, "pollable_refcount"); -#endif +grpc_core::DebugOnlyTraceFlag grpc_trace_pollable_refcount(false, + "pollable_refcount"); /******************************************************************************* * pollable Declarations @@ -86,21 +86,21 @@ struct pollable { grpc_wakeup_fd wakeup; // only for type fd... one ref to the owner fd - grpc_fd *owner_fd; + grpc_fd* owner_fd; - grpc_pollset_set *pollset_set; - pollable *next; - pollable *prev; + grpc_pollset_set* pollset_set; + pollable* next; + pollable* prev; gpr_mu mu; - grpc_pollset_worker *root_worker; + grpc_pollset_worker* root_worker; int event_cursor; int event_count; struct epoll_event events[MAX_EPOLL_EVENTS]; }; -static const char *pollable_type_string(pollable_type t) { +static const char* pollable_type_string(pollable_type t) { switch (t) { case PO_MULTI: return "pollset"; @@ -112,8 +112,8 @@ static const char *pollable_type_string(pollable_type t) { return ""; } -static char *pollable_desc(pollable *p) { - char *out; +static char* pollable_desc(pollable* p) { + char* out; gpr_asprintf(&out, "type=%s epfd=%d wakeup=%d", pollable_type_string(p->type), p->epfd, p->wakeup.read_fd); return out; @@ -121,17 +121,17 @@ static char *pollable_desc(pollable *p) { /// Shared empty pollable - used by pollset to poll on until the first fd is /// added -static pollable *g_empty_pollable; +static pollable* g_empty_pollable; -static grpc_error *pollable_create(pollable_type type, pollable **p); +static grpc_error* pollable_create(pollable_type type, pollable** p); #ifdef NDEBUG -static pollable *pollable_ref(pollable *p); -static void pollable_unref(pollable *p); +static pollable* pollable_ref(pollable* p); +static void pollable_unref(pollable* p); #define POLLABLE_REF(p, r) pollable_ref(p) #define POLLABLE_UNREF(p, r) pollable_unref(p) #else -static pollable *pollable_ref(pollable *p, int line, const char *reason); -static void pollable_unref(pollable *p, int line, const char *reason); +static pollable* pollable_ref(pollable* p, int line, const char* reason); +static void pollable_unref(pollable* p, int line, const char* reason); #define POLLABLE_REF(p, r) pollable_ref((p), __LINE__, (r)) #define POLLABLE_UNREF(p, r) pollable_unref((p), __LINE__, (r)) #endif @@ -151,13 +151,13 @@ struct grpc_fd { gpr_mu orphan_mu; gpr_mu pollable_mu; - pollable *pollable_obj; + pollable* pollable_obj; - gpr_atm read_closure; - gpr_atm write_closure; + grpc_core::ManualConstructor read_closure; + grpc_core::ManualConstructor write_closure; - struct grpc_fd *freelist_next; - grpc_closure *on_done_closure; + struct grpc_fd* freelist_next; + grpc_closure* on_done_closure; /* The pollset that last noticed that the fd is readable. The actual type * stored in this is (grpc_pollset *) */ @@ -174,8 +174,8 @@ static void fd_global_shutdown(void); */ typedef struct { - grpc_pollset_worker *next; - grpc_pollset_worker *prev; + grpc_pollset_worker* next; + grpc_pollset_worker* prev; } pwlink; typedef enum { PWLINK_POLLABLE = 0, PWLINK_POLLSET, PWLINK_COUNT } pwlinks; @@ -188,18 +188,18 @@ struct grpc_pollset_worker { pid_t originator; #endif gpr_cv cv; - grpc_pollset *pollset; - pollable *pollable_obj; + grpc_pollset* pollset; + pollable* pollable_obj; pwlink links[PWLINK_COUNT]; }; struct grpc_pollset { gpr_mu mu; - pollable *active_pollable; + pollable* active_pollable; bool kicked_without_poller; - grpc_closure *shutdown_closure; - grpc_pollset_worker *root_worker; + grpc_closure* shutdown_closure; + grpc_pollset_worker* root_worker; int containing_pollset_set_count; }; @@ -210,23 +210,23 @@ struct grpc_pollset { struct grpc_pollset_set { gpr_refcount refs; gpr_mu mu; - grpc_pollset_set *parent; + grpc_pollset_set* parent; size_t pollset_count; size_t pollset_capacity; - grpc_pollset **pollsets; + grpc_pollset** pollsets; size_t fd_count; size_t fd_capacity; - grpc_fd **fds; + grpc_fd** fds; }; /******************************************************************************* * Common helpers */ -static bool append_error(grpc_error **composite, grpc_error *error, - const char *desc) { +static bool append_error(grpc_error** composite, grpc_error* error, + const char* desc) { if (error == GRPC_ERROR_NONE) return true; if (*composite == GRPC_ERROR_NONE) { *composite = GRPC_ERROR_CREATE_FROM_COPIED_STRING(desc); @@ -252,16 +252,16 @@ static bool append_error(grpc_error **composite, grpc_error *error, * becomes a spurious read notification on a reused fd. */ -static grpc_fd *fd_freelist = NULL; +static grpc_fd* fd_freelist = nullptr; static gpr_mu fd_freelist_mu; #ifndef NDEBUG #define REF_BY(fd, n, reason) ref_by(fd, n, reason, __FILE__, __LINE__) #define UNREF_BY(ec, fd, n, reason) \ unref_by(ec, fd, n, reason, __FILE__, __LINE__) -static void ref_by(grpc_fd *fd, int n, const char *reason, const char *file, +static void ref_by(grpc_fd* fd, int n, const char* reason, const char* file, int line) { - if (GRPC_TRACER_ON(grpc_trace_fd_refcount)) { + if (grpc_trace_fd_refcount.enabled()) { gpr_log(GPR_DEBUG, "FD %d %p ref %d %" PRIdPTR " -> %" PRIdPTR " [%s; %s:%d]", fd->fd, fd, n, gpr_atm_no_barrier_load(&fd->refst), @@ -270,13 +270,13 @@ static void ref_by(grpc_fd *fd, int n, const char *reason, const char *file, #else #define REF_BY(fd, n, reason) ref_by(fd, n) #define UNREF_BY(ec, fd, n, reason) unref_by(ec, fd, n) -static void ref_by(grpc_fd *fd, int n) { +static void ref_by(grpc_fd* fd, int n) { #endif GPR_ASSERT(gpr_atm_no_barrier_fetch_add(&fd->refst, n) > 0); } -static void fd_destroy(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { - grpc_fd *fd = (grpc_fd *)arg; +static void fd_destroy(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { + grpc_fd* fd = (grpc_fd*)arg; /* Add the fd to the freelist */ grpc_iomgr_unregister_object(&fd->iomgr_object); POLLABLE_UNREF(fd->pollable_obj, "fd_pollable"); @@ -286,29 +286,30 @@ static void fd_destroy(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { fd->freelist_next = fd_freelist; fd_freelist = fd; - grpc_lfev_destroy(&fd->read_closure); - grpc_lfev_destroy(&fd->write_closure); + fd->read_closure->DestroyEvent(); + fd->write_closure->DestroyEvent(); gpr_mu_unlock(&fd_freelist_mu); } #ifndef NDEBUG -static void unref_by(grpc_exec_ctx *exec_ctx, grpc_fd *fd, int n, - const char *reason, const char *file, int line) { - if (GRPC_TRACER_ON(grpc_trace_fd_refcount)) { +static void unref_by(grpc_exec_ctx* exec_ctx, grpc_fd* fd, int n, + const char* reason, const char* file, int line) { + if (grpc_trace_fd_refcount.enabled()) { gpr_log(GPR_DEBUG, "FD %d %p unref %d %" PRIdPTR " -> %" PRIdPTR " [%s; %s:%d]", fd->fd, fd, n, gpr_atm_no_barrier_load(&fd->refst), gpr_atm_no_barrier_load(&fd->refst) - n, reason, file, line); } #else -static void unref_by(grpc_exec_ctx *exec_ctx, grpc_fd *fd, int n) { +static void unref_by(grpc_exec_ctx* exec_ctx, grpc_fd* fd, int n) { #endif gpr_atm old = gpr_atm_full_fetch_add(&fd->refst, -n); if (old == n) { - GRPC_CLOSURE_SCHED(exec_ctx, GRPC_CLOSURE_CREATE(fd_destroy, fd, - grpc_schedule_on_exec_ctx), - GRPC_ERROR_NONE); + GRPC_CLOSURE_SCHED( + exec_ctx, + GRPC_CLOSURE_CREATE(fd_destroy, fd, grpc_schedule_on_exec_ctx), + GRPC_ERROR_NONE); } else { GPR_ASSERT(old > n); } @@ -319,45 +320,47 @@ static void fd_global_init(void) { gpr_mu_init(&fd_freelist_mu); } static void fd_global_shutdown(void) { gpr_mu_lock(&fd_freelist_mu); gpr_mu_unlock(&fd_freelist_mu); - while (fd_freelist != NULL) { - grpc_fd *fd = fd_freelist; + while (fd_freelist != nullptr) { + grpc_fd* fd = fd_freelist; fd_freelist = fd_freelist->freelist_next; gpr_free(fd); } gpr_mu_destroy(&fd_freelist_mu); } -static grpc_fd *fd_create(int fd, const char *name) { - grpc_fd *new_fd = NULL; +static grpc_fd* fd_create(int fd, const char* name) { + grpc_fd* new_fd = nullptr; gpr_mu_lock(&fd_freelist_mu); - if (fd_freelist != NULL) { + if (fd_freelist != nullptr) { new_fd = fd_freelist; fd_freelist = fd_freelist->freelist_next; } gpr_mu_unlock(&fd_freelist_mu); - if (new_fd == NULL) { - new_fd = (grpc_fd *)gpr_malloc(sizeof(grpc_fd)); + if (new_fd == nullptr) { + new_fd = (grpc_fd*)gpr_malloc(sizeof(grpc_fd)); + new_fd->read_closure.Init(); + new_fd->write_closure.Init(); } gpr_mu_init(&new_fd->pollable_mu); gpr_mu_init(&new_fd->orphan_mu); - new_fd->pollable_obj = NULL; + new_fd->pollable_obj = nullptr; gpr_atm_rel_store(&new_fd->refst, (gpr_atm)1); new_fd->fd = fd; - grpc_lfev_init(&new_fd->read_closure); - grpc_lfev_init(&new_fd->write_closure); + new_fd->read_closure->InitEvent(); + new_fd->write_closure->InitEvent(); gpr_atm_no_barrier_store(&new_fd->read_notifier_pollset, (gpr_atm)NULL); - new_fd->freelist_next = NULL; - new_fd->on_done_closure = NULL; + new_fd->freelist_next = nullptr; + new_fd->on_done_closure = nullptr; - char *fd_name; + char* fd_name; gpr_asprintf(&fd_name, "%s fd=%d", name, fd); grpc_iomgr_register_object(&new_fd->iomgr_object, fd_name); #ifndef NDEBUG - if (GRPC_TRACER_ON(grpc_trace_fd_refcount)) { + if (grpc_trace_fd_refcount.enabled()) { gpr_log(GPR_DEBUG, "FD %d %p create %s", fd, new_fd, fd_name); } #endif @@ -365,14 +368,14 @@ static grpc_fd *fd_create(int fd, const char *name) { return new_fd; } -static int fd_wrapped_fd(grpc_fd *fd) { +static int fd_wrapped_fd(grpc_fd* fd) { int ret_fd = fd->fd; return (gpr_atm_acq_load(&fd->refst) & 1) ? ret_fd : -1; } -static void fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *on_done, int *release_fd, - bool already_closed, const char *reason) { +static void fd_orphan(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* on_done, int* release_fd, + bool already_closed, const char* reason) { bool is_fd_closed = already_closed; gpr_mu_lock(&fd->orphan_mu); @@ -381,7 +384,7 @@ static void fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd, /* If release_fd is not NULL, we should be relinquishing control of the file descriptor fd->fd (but we still own the grpc_fd structure). */ - if (release_fd != NULL) { + if (release_fd != nullptr) { *release_fd = fd->fd; } else if (!is_fd_closed) { close(fd->fd); @@ -403,64 +406,63 @@ static void fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd, UNREF_BY(exec_ctx, fd, 2, reason); /* Drop the reference */ } -static grpc_pollset *fd_get_read_notifier_pollset(grpc_exec_ctx *exec_ctx, - grpc_fd *fd) { +static grpc_pollset* fd_get_read_notifier_pollset(grpc_exec_ctx* exec_ctx, + grpc_fd* fd) { gpr_atm notifier = gpr_atm_acq_load(&fd->read_notifier_pollset); - return (grpc_pollset *)notifier; + return (grpc_pollset*)notifier; } -static bool fd_is_shutdown(grpc_fd *fd) { - return grpc_lfev_is_shutdown(&fd->read_closure); +static bool fd_is_shutdown(grpc_fd* fd) { + return fd->read_closure->IsShutdown(); } /* Might be called multiple times */ -static void fd_shutdown(grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_error *why) { - if (grpc_lfev_set_shutdown(exec_ctx, &fd->read_closure, - GRPC_ERROR_REF(why))) { +static void fd_shutdown(grpc_exec_ctx* exec_ctx, grpc_fd* fd, grpc_error* why) { + if (fd->read_closure->SetShutdown(exec_ctx, GRPC_ERROR_REF(why))) { shutdown(fd->fd, SHUT_RDWR); - grpc_lfev_set_shutdown(exec_ctx, &fd->write_closure, GRPC_ERROR_REF(why)); + fd->write_closure->SetShutdown(exec_ctx, GRPC_ERROR_REF(why)); } GRPC_ERROR_UNREF(why); } -static void fd_notify_on_read(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *closure) { - grpc_lfev_notify_on(exec_ctx, &fd->read_closure, closure, "read"); +static void fd_notify_on_read(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* closure) { + fd->read_closure->NotifyOn(exec_ctx, closure); } -static void fd_notify_on_write(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *closure) { - grpc_lfev_notify_on(exec_ctx, &fd->write_closure, closure, "write"); +static void fd_notify_on_write(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* closure) { + fd->write_closure->NotifyOn(exec_ctx, closure); } /******************************************************************************* * Pollable Definitions */ -static grpc_error *pollable_create(pollable_type type, pollable **p) { - *p = NULL; +static grpc_error* pollable_create(pollable_type type, pollable** p) { + *p = nullptr; int epfd = epoll_create1(EPOLL_CLOEXEC); if (epfd == -1) { return GRPC_OS_ERROR(errno, "epoll_create1"); } - *p = (pollable *)gpr_malloc(sizeof(**p)); - grpc_error *err = grpc_wakeup_fd_init(&(*p)->wakeup); + *p = (pollable*)gpr_malloc(sizeof(**p)); + grpc_error* err = grpc_wakeup_fd_init(&(*p)->wakeup); if (err != GRPC_ERROR_NONE) { close(epfd); gpr_free(*p); - *p = NULL; + *p = nullptr; return err; } struct epoll_event ev; ev.events = (uint32_t)(EPOLLIN | EPOLLET); - ev.data.ptr = (void *)(1 | (intptr_t) & (*p)->wakeup); + ev.data.ptr = (void*)(1 | (intptr_t) & (*p)->wakeup); if (epoll_ctl(epfd, EPOLL_CTL_ADD, (*p)->wakeup.read_fd, &ev) != 0) { err = GRPC_OS_ERROR(errno, "epoll_ctl"); close(epfd); grpc_wakeup_fd_destroy(&(*p)->wakeup); gpr_free(*p); - *p = NULL; + *p = nullptr; return err; } @@ -468,20 +470,20 @@ static grpc_error *pollable_create(pollable_type type, pollable **p) { gpr_ref_init(&(*p)->refs, 1); gpr_mu_init(&(*p)->mu); (*p)->epfd = epfd; - (*p)->owner_fd = NULL; - (*p)->pollset_set = NULL; + (*p)->owner_fd = nullptr; + (*p)->pollset_set = nullptr; (*p)->next = (*p)->prev = *p; - (*p)->root_worker = NULL; + (*p)->root_worker = nullptr; (*p)->event_cursor = 0; (*p)->event_count = 0; return GRPC_ERROR_NONE; } #ifdef NDEBUG -static pollable *pollable_ref(pollable *p) { +static pollable* pollable_ref(pollable* p) { #else -static pollable *pollable_ref(pollable *p, int line, const char *reason) { - if (GRPC_TRACER_ON(grpc_trace_pollable_refcount)) { +static pollable* pollable_ref(pollable* p, int line, const char* reason) { + if (grpc_trace_pollable_refcount.enabled()) { int r = (int)gpr_atm_no_barrier_load(&p->refs.count); gpr_log(__FILE__, line, GPR_LOG_SEVERITY_DEBUG, "POLLABLE:%p ref %d->%d %s", p, r, r + 1, reason); @@ -492,29 +494,29 @@ static pollable *pollable_ref(pollable *p, int line, const char *reason) { } #ifdef NDEBUG -static void pollable_unref(pollable *p) { +static void pollable_unref(pollable* p) { #else -static void pollable_unref(pollable *p, int line, const char *reason) { - if (p == NULL) return; - if (GRPC_TRACER_ON(grpc_trace_pollable_refcount)) { +static void pollable_unref(pollable* p, int line, const char* reason) { + if (p == nullptr) return; + if (grpc_trace_pollable_refcount.enabled()) { int r = (int)gpr_atm_no_barrier_load(&p->refs.count); gpr_log(__FILE__, line, GPR_LOG_SEVERITY_DEBUG, "POLLABLE:%p unref %d->%d %s", p, r, r - 1, reason); } #endif - if (p != NULL && gpr_unref(&p->refs)) { + if (p != nullptr && gpr_unref(&p->refs)) { close(p->epfd); grpc_wakeup_fd_destroy(&p->wakeup); gpr_free(p); } } -static grpc_error *pollable_add_fd(pollable *p, grpc_fd *fd) { - grpc_error *error = GRPC_ERROR_NONE; - static const char *err_desc = "pollable_add_fd"; +static grpc_error* pollable_add_fd(pollable* p, grpc_fd* fd) { + grpc_error* error = GRPC_ERROR_NONE; + static const char* err_desc = "pollable_add_fd"; const int epfd = p->epfd; - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "add fd %p (%d) to pollable %p", fd, fd->fd, p); } @@ -541,7 +543,7 @@ GPR_TLS_DECL(g_current_thread_pollset); GPR_TLS_DECL(g_current_thread_worker); /* Global state management */ -static grpc_error *pollset_global_init(void) { +static grpc_error* pollset_global_init(void) { gpr_tls_init(&g_current_thread_pollset); gpr_tls_init(&g_current_thread_worker); return pollable_create(PO_EMPTY, &g_empty_pollable); @@ -554,39 +556,39 @@ static void pollset_global_shutdown(void) { } /* pollset->mu must be held while calling this function */ -static void pollset_maybe_finish_shutdown(grpc_exec_ctx *exec_ctx, - grpc_pollset *pollset) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { +static void pollset_maybe_finish_shutdown(grpc_exec_ctx* exec_ctx, + grpc_pollset* pollset) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PS:%p (pollable:%p) maybe_finish_shutdown sc=%p (target:!NULL) " "rw=%p (target:NULL) cpsc=%d (target:0)", pollset, pollset->active_pollable, pollset->shutdown_closure, pollset->root_worker, pollset->containing_pollset_set_count); } - if (pollset->shutdown_closure != NULL && pollset->root_worker == NULL && + if (pollset->shutdown_closure != nullptr && pollset->root_worker == nullptr && pollset->containing_pollset_set_count == 0) { GRPC_CLOSURE_SCHED(exec_ctx, pollset->shutdown_closure, GRPC_ERROR_NONE); - pollset->shutdown_closure = NULL; + pollset->shutdown_closure = nullptr; } } /* pollset->mu must be held before calling this function, * pollset->active_pollable->mu & specific_worker->pollable_obj->mu must not be * held */ -static grpc_error *kick_one_worker(grpc_exec_ctx *exec_ctx, - grpc_pollset_worker *specific_worker) { - pollable *p = specific_worker->pollable_obj; +static grpc_error* kick_one_worker(grpc_exec_ctx* exec_ctx, + grpc_pollset_worker* specific_worker) { + pollable* p = specific_worker->pollable_obj; grpc_core::mu_guard lock(&p->mu); - GPR_ASSERT(specific_worker != NULL); + GPR_ASSERT(specific_worker != nullptr); if (specific_worker->kicked) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PS:%p kicked_specific_but_already_kicked", p); } GRPC_STATS_INC_POLLSET_KICKED_AGAIN(exec_ctx); return GRPC_ERROR_NONE; } if (gpr_tls_get(&g_current_thread_worker) == (intptr_t)specific_worker) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PS:%p kicked_specific_but_awake", p); } GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD(exec_ctx); @@ -595,16 +597,16 @@ static grpc_error *kick_one_worker(grpc_exec_ctx *exec_ctx, } if (specific_worker == p->root_worker) { GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD(exec_ctx); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PS:%p kicked_specific_via_wakeup_fd", p); } specific_worker->kicked = true; - grpc_error *error = grpc_wakeup_fd_wakeup(&p->wakeup); + grpc_error* error = grpc_wakeup_fd_wakeup(&p->wakeup); return error; } if (specific_worker->initialized_cv) { GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV(exec_ctx); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PS:%p kicked_specific_via_cv", p); } specific_worker->kicked = true; @@ -616,21 +618,20 @@ static grpc_error *kick_one_worker(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static grpc_error *pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker *specific_worker) { +static grpc_error* pollset_kick(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker* specific_worker) { GRPC_STATS_INC_POLLSET_KICK(exec_ctx); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PS:%p kick %p tls_pollset=%p tls_worker=%p pollset.root_worker=%p", pollset, specific_worker, - (void *)gpr_tls_get(&g_current_thread_pollset), - (void *)gpr_tls_get(&g_current_thread_worker), - pollset->root_worker); + (void*)gpr_tls_get(&g_current_thread_pollset), + (void*)gpr_tls_get(&g_current_thread_worker), pollset->root_worker); } - if (specific_worker == NULL) { + if (specific_worker == nullptr) { if (gpr_tls_get(&g_current_thread_pollset) != (intptr_t)pollset) { - if (pollset->root_worker == NULL) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (pollset->root_worker == nullptr) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PS:%p kicked_any_without_poller", pollset); } GRPC_STATS_INC_POLLSET_KICKED_WITHOUT_POLLER(exec_ctx); @@ -656,7 +657,7 @@ static grpc_error *pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, exec_ctx, pollset->root_worker->links[PWLINK_POLLSET].next); } } else { - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PS:%p kicked_any_but_awake", pollset); } GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD(exec_ctx); @@ -667,12 +668,12 @@ static grpc_error *pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, } } -static grpc_error *pollset_kick_all(grpc_exec_ctx *exec_ctx, - grpc_pollset *pollset) { - grpc_error *error = GRPC_ERROR_NONE; - const char *err_desc = "pollset_kick_all"; - grpc_pollset_worker *w = pollset->root_worker; - if (w != NULL) { +static grpc_error* pollset_kick_all(grpc_exec_ctx* exec_ctx, + grpc_pollset* pollset) { + grpc_error* error = GRPC_ERROR_NONE; + const char* err_desc = "pollset_kick_all"; + grpc_pollset_worker* w = pollset->root_worker; + if (w != nullptr) { do { GRPC_STATS_INC_POLLSET_KICK(exec_ctx); append_error(&error, kick_one_worker(exec_ctx, w), err_desc); @@ -682,13 +683,13 @@ static grpc_error *pollset_kick_all(grpc_exec_ctx *exec_ctx, return error; } -static void pollset_init(grpc_pollset *pollset, gpr_mu **mu) { +static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) { gpr_mu_init(&pollset->mu); pollset->active_pollable = POLLABLE_REF(g_empty_pollable, "pollset"); *mu = &pollset->mu; } -static int poll_deadline_to_millis_timeout(grpc_exec_ctx *exec_ctx, +static int poll_deadline_to_millis_timeout(grpc_exec_ctx* exec_ctx, grpc_millis millis) { if (millis == GRPC_MILLIS_INF_FUTURE) return -1; grpc_millis delta = millis - grpc_exec_ctx_now(exec_ctx); @@ -700,9 +701,9 @@ static int poll_deadline_to_millis_timeout(grpc_exec_ctx *exec_ctx, return (int)delta; } -static void fd_become_readable(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_pollset *notifier) { - grpc_lfev_set_ready(exec_ctx, &fd->read_closure, "read"); +static void fd_become_readable(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_pollset* notifier) { + fd->read_closure->SetReady(exec_ctx); /* Note, it is possible that fd_become_readable might be called twice with different 'notifier's when an fd becomes readable and it is in two epoll @@ -713,70 +714,70 @@ static void fd_become_readable(grpc_exec_ctx *exec_ctx, grpc_fd *fd, gpr_atm_rel_store(&fd->read_notifier_pollset, (gpr_atm)notifier); } -static void fd_become_writable(grpc_exec_ctx *exec_ctx, grpc_fd *fd) { - grpc_lfev_set_ready(exec_ctx, &fd->write_closure, "write"); +static void fd_become_writable(grpc_exec_ctx* exec_ctx, grpc_fd* fd) { + fd->write_closure->SetReady(exec_ctx); } -static grpc_error *fd_get_or_become_pollable(grpc_fd *fd, pollable **p) { +static grpc_error* fd_get_or_become_pollable(grpc_fd* fd, pollable** p) { gpr_mu_lock(&fd->pollable_mu); - grpc_error *error = GRPC_ERROR_NONE; - static const char *err_desc = "fd_get_or_become_pollable"; - if (fd->pollable_obj == NULL) { + grpc_error* error = GRPC_ERROR_NONE; + static const char* err_desc = "fd_get_or_become_pollable"; + if (fd->pollable_obj == nullptr) { if (append_error(&error, pollable_create(PO_FD, &fd->pollable_obj), err_desc)) { fd->pollable_obj->owner_fd = fd; if (!append_error(&error, pollable_add_fd(fd->pollable_obj, fd), err_desc)) { POLLABLE_UNREF(fd->pollable_obj, "fd_pollable"); - fd->pollable_obj = NULL; + fd->pollable_obj = nullptr; } } } if (error == GRPC_ERROR_NONE) { - GPR_ASSERT(fd->pollable_obj != NULL); + GPR_ASSERT(fd->pollable_obj != nullptr); *p = POLLABLE_REF(fd->pollable_obj, "pollset"); } else { - GPR_ASSERT(fd->pollable_obj == NULL); - *p = NULL; + GPR_ASSERT(fd->pollable_obj == nullptr); + *p = nullptr; } gpr_mu_unlock(&fd->pollable_mu); return error; } /* pollset->po.mu lock must be held by the caller before calling this */ -static void pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_closure *closure) { - GPR_ASSERT(pollset->shutdown_closure == NULL); +static void pollset_shutdown(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_closure* closure) { + GPR_ASSERT(pollset->shutdown_closure == nullptr); pollset->shutdown_closure = closure; GRPC_LOG_IF_ERROR("pollset_shutdown", pollset_kick_all(exec_ctx, pollset)); pollset_maybe_finish_shutdown(exec_ctx, pollset); } -static grpc_error *pollable_process_events(grpc_exec_ctx *exec_ctx, - grpc_pollset *pollset, - pollable *pollable_obj, bool drain) { - static const char *err_desc = "pollset_process_events"; - grpc_error *error = GRPC_ERROR_NONE; +static grpc_error* pollable_process_events(grpc_exec_ctx* exec_ctx, + grpc_pollset* pollset, + pollable* pollable_obj, bool drain) { + static const char* err_desc = "pollset_process_events"; + grpc_error* error = GRPC_ERROR_NONE; for (int i = 0; (drain || i < MAX_EPOLL_EVENTS_HANDLED_EACH_POLL_CALL) && pollable_obj->event_cursor != pollable_obj->event_count; i++) { int n = pollable_obj->event_cursor++; - struct epoll_event *ev = &pollable_obj->events[n]; - void *data_ptr = ev->data.ptr; + struct epoll_event* ev = &pollable_obj->events[n]; + void* data_ptr = ev->data.ptr; if (1 & (intptr_t)data_ptr) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PS:%p got pollset_wakeup %p", pollset, data_ptr); } append_error(&error, grpc_wakeup_fd_consume_wakeup( - (grpc_wakeup_fd *)((~(intptr_t)1) & (intptr_t)data_ptr)), + (grpc_wakeup_fd*)((~(intptr_t)1) & (intptr_t)data_ptr)), err_desc); } else { - grpc_fd *fd = (grpc_fd *)data_ptr; + grpc_fd* fd = (grpc_fd*)data_ptr; bool cancel = (ev->events & (EPOLLERR | EPOLLHUP)) != 0; bool read_ev = (ev->events & (EPOLLIN | EPOLLPRI)) != 0; bool write_ev = (ev->events & EPOLLOUT) != 0; - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PS:%p got fd %p: cancel=%d read=%d " "write=%d", @@ -795,17 +796,17 @@ static grpc_error *pollable_process_events(grpc_exec_ctx *exec_ctx, } /* pollset_shutdown is guaranteed to be called before pollset_destroy. */ -static void pollset_destroy(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset) { +static void pollset_destroy(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset) { POLLABLE_UNREF(pollset->active_pollable, "pollset"); - pollset->active_pollable = NULL; + pollset->active_pollable = nullptr; } -static grpc_error *pollable_epoll(grpc_exec_ctx *exec_ctx, pollable *p, +static grpc_error* pollable_epoll(grpc_exec_ctx* exec_ctx, pollable* p, grpc_millis deadline) { int timeout = poll_deadline_to_millis_timeout(exec_ctx, deadline); - if (GRPC_TRACER_ON(grpc_polling_trace)) { - char *desc = pollable_desc(p); + if (grpc_polling_trace.enabled()) { + char* desc = pollable_desc(p); gpr_log(GPR_DEBUG, "POLLABLE:%p[%s] poll for %dms", p, desc, timeout); gpr_free(desc); } @@ -824,7 +825,7 @@ static grpc_error *pollable_epoll(grpc_exec_ctx *exec_ctx, pollable *p, if (r < 0) return GRPC_OS_ERROR(errno, "epoll_wait"); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "POLLABLE:%p got %d events", p, r); } @@ -835,9 +836,9 @@ static grpc_error *pollable_epoll(grpc_exec_ctx *exec_ctx, pollable *p, } /* Return true if first in list */ -static bool worker_insert(grpc_pollset_worker **root_worker, - grpc_pollset_worker *worker, pwlinks link) { - if (*root_worker == NULL) { +static bool worker_insert(grpc_pollset_worker** root_worker, + grpc_pollset_worker* worker, pwlinks link) { + if (*root_worker == nullptr) { *root_worker = worker; worker->links[link].next = worker->links[link].prev = worker; return true; @@ -853,12 +854,12 @@ static bool worker_insert(grpc_pollset_worker **root_worker, /* returns the new root IFF the root changed */ typedef enum { WRR_NEW_ROOT, WRR_EMPTIED, WRR_REMOVED } worker_remove_result; -static worker_remove_result worker_remove(grpc_pollset_worker **root_worker, - grpc_pollset_worker *worker, +static worker_remove_result worker_remove(grpc_pollset_worker** root_worker, + grpc_pollset_worker* worker, pwlinks link) { if (worker == *root_worker) { if (worker == worker->links[link].next) { - *root_worker = NULL; + *root_worker = nullptr; return WRR_EMPTIED; } else { *root_worker = worker->links[link].next; @@ -874,12 +875,12 @@ static worker_remove_result worker_remove(grpc_pollset_worker **root_worker, } /* Return true if this thread should poll */ -static bool begin_worker(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker *worker, - grpc_pollset_worker **worker_hdl, +static bool begin_worker(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker* worker, + grpc_pollset_worker** worker_hdl, grpc_millis deadline) { bool do_poll = (pollset->shutdown_closure == nullptr); - if (worker_hdl != NULL) *worker_hdl = worker; + if (worker_hdl != nullptr) *worker_hdl = worker; worker->initialized_cv = false; worker->kicked = false; worker->pollset = pollset; @@ -892,7 +893,7 @@ static bool begin_worker(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, worker->initialized_cv = true; gpr_cv_init(&worker->cv); gpr_mu_unlock(&pollset->mu); - if (GRPC_TRACER_ON(grpc_polling_trace) && + if (grpc_polling_trace.enabled() && worker->pollable_obj->root_worker != worker) { gpr_log(GPR_DEBUG, "PS:%p wait %p w=%p for %dms", pollset, worker->pollable_obj, worker, @@ -901,18 +902,18 @@ static bool begin_worker(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, while (do_poll && worker->pollable_obj->root_worker != worker) { if (gpr_cv_wait(&worker->cv, &worker->pollable_obj->mu, grpc_millis_to_timespec(deadline, GPR_CLOCK_REALTIME))) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PS:%p timeout_wait %p w=%p", pollset, worker->pollable_obj, worker); } do_poll = false; } else if (worker->kicked) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PS:%p wakeup %p w=%p", pollset, worker->pollable_obj, worker); } do_poll = false; - } else if (GRPC_TRACER_ON(grpc_polling_trace) && + } else if (grpc_polling_trace.enabled() && worker->pollable_obj->root_worker != worker) { gpr_log(GPR_DEBUG, "PS:%p spurious_wakeup %p w=%p", pollset, worker->pollable_obj, worker); @@ -927,16 +928,16 @@ static bool begin_worker(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, return do_poll; } -static void end_worker(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker *worker, - grpc_pollset_worker **worker_hdl) { +static void end_worker(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker* worker, + grpc_pollset_worker** worker_hdl) { gpr_mu_lock(&pollset->mu); gpr_mu_lock(&worker->pollable_obj->mu); switch (worker_remove(&worker->pollable_obj->root_worker, worker, PWLINK_POLLABLE)) { case WRR_NEW_ROOT: { // wakeup new poller - grpc_pollset_worker *new_root = worker->pollable_obj->root_worker; + grpc_pollset_worker* new_root = worker->pollable_obj->root_worker; GPR_ASSERT(new_root->initialized_cv); gpr_cv_signal(&new_root->cv); break; @@ -969,12 +970,12 @@ static long gettid(void) { return syscall(__NR_gettid); } The function pollset_work() may temporarily release the lock (pollset->po.mu) during the course of its execution but it will always re-acquire the lock and ensure that it is held by the time the function returns */ -static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker **worker_hdl, +static grpc_error* pollset_work(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker** worker_hdl, grpc_millis deadline) { #ifdef GRPC_EPOLLEX_CREATE_WORKERS_ON_HEAP - grpc_pollset_worker *worker = - (grpc_pollset_worker *)gpr_malloc(sizeof(*worker)); + grpc_pollset_worker* worker = + (grpc_pollset_worker*)gpr_malloc(sizeof(*worker)); #define WORKER_PTR (worker) #else grpc_pollset_worker worker; @@ -983,14 +984,15 @@ static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, #ifndef NDEBUG WORKER_PTR->originator = gettid(); #endif - if (GRPC_TRACER_ON(grpc_polling_trace)) { - gpr_log(GPR_DEBUG, "PS:%p work hdl=%p worker=%p now=%" PRIdPTR - " deadline=%" PRIdPTR " kwp=%d pollable=%p", + if (grpc_polling_trace.enabled()) { + gpr_log(GPR_DEBUG, + "PS:%p work hdl=%p worker=%p now=%" PRIdPTR " deadline=%" PRIdPTR + " kwp=%d pollable=%p", pollset, worker_hdl, WORKER_PTR, grpc_exec_ctx_now(exec_ctx), deadline, pollset->kicked_without_poller, pollset->active_pollable); } - static const char *err_desc = "pollset_work"; - grpc_error *error = GRPC_ERROR_NONE; + static const char* err_desc = "pollset_work"; + grpc_error* error = GRPC_ERROR_NONE; if (pollset->kicked_without_poller) { pollset->kicked_without_poller = false; } else { @@ -999,9 +1001,10 @@ static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, gpr_tls_set(&g_current_thread_worker, (intptr_t)WORKER_PTR); if (WORKER_PTR->pollable_obj->event_cursor == WORKER_PTR->pollable_obj->event_count) { - append_error(&error, pollable_epoll(exec_ctx, WORKER_PTR->pollable_obj, - deadline), - err_desc); + append_error( + &error, + pollable_epoll(exec_ctx, WORKER_PTR->pollable_obj, deadline), + err_desc); } append_error(&error, pollable_process_events(exec_ctx, pollset, @@ -1020,11 +1023,11 @@ static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, return error; } -static grpc_error *pollset_transition_pollable_from_empty_to_fd_locked( - grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, grpc_fd *fd) { - static const char *err_desc = "pollset_transition_pollable_from_empty_to_fd"; - grpc_error *error = GRPC_ERROR_NONE; - if (GRPC_TRACER_ON(grpc_polling_trace)) { +static grpc_error* pollset_transition_pollable_from_empty_to_fd_locked( + grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, grpc_fd* fd) { + static const char* err_desc = "pollset_transition_pollable_from_empty_to_fd"; + grpc_error* error = GRPC_ERROR_NONE; + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PS:%p add fd %p (%d); transition pollable from empty to fd", pollset, fd, fd->fd); @@ -1036,11 +1039,11 @@ static grpc_error *pollset_transition_pollable_from_empty_to_fd_locked( return error; } -static grpc_error *pollset_transition_pollable_from_fd_to_multi_locked( - grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, grpc_fd *and_add_fd) { - static const char *err_desc = "pollset_transition_pollable_from_fd_to_multi"; - grpc_error *error = GRPC_ERROR_NONE; - if (GRPC_TRACER_ON(grpc_polling_trace)) { +static grpc_error* pollset_transition_pollable_from_fd_to_multi_locked( + grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, grpc_fd* and_add_fd) { + static const char* err_desc = "pollset_transition_pollable_from_fd_to_multi"; + grpc_error* error = GRPC_ERROR_NONE; + if (grpc_polling_trace.enabled()) { gpr_log( GPR_DEBUG, "PS:%p add fd %p (%d); transition pollable from fd %p to multipoller", @@ -1048,14 +1051,14 @@ static grpc_error *pollset_transition_pollable_from_fd_to_multi_locked( pollset->active_pollable->owner_fd); } append_error(&error, pollset_kick_all(exec_ctx, pollset), err_desc); - grpc_fd *initial_fd = pollset->active_pollable->owner_fd; + grpc_fd* initial_fd = pollset->active_pollable->owner_fd; POLLABLE_UNREF(pollset->active_pollable, "pollset"); - pollset->active_pollable = NULL; + pollset->active_pollable = nullptr; if (append_error(&error, pollable_create(PO_MULTI, &pollset->active_pollable), err_desc)) { append_error(&error, pollable_add_fd(pollset->active_pollable, initial_fd), err_desc); - if (and_add_fd != NULL) { + if (and_add_fd != nullptr) { append_error(&error, pollable_add_fd(pollset->active_pollable, and_add_fd), err_desc); @@ -1065,10 +1068,10 @@ static grpc_error *pollset_transition_pollable_from_fd_to_multi_locked( } /* expects pollsets locked, flag whether fd is locked or not */ -static grpc_error *pollset_add_fd_locked(grpc_exec_ctx *exec_ctx, - grpc_pollset *pollset, grpc_fd *fd) { - grpc_error *error = GRPC_ERROR_NONE; - pollable *po_at_start = +static grpc_error* pollset_add_fd_locked(grpc_exec_ctx* exec_ctx, + grpc_pollset* pollset, grpc_fd* fd) { + grpc_error* error = GRPC_ERROR_NONE; + pollable* po_at_start = POLLABLE_REF(pollset->active_pollable, "pollset_add_fd"); switch (pollset->active_pollable->type) { case PO_EMPTY: @@ -1102,11 +1105,11 @@ static grpc_error *pollset_add_fd_locked(grpc_exec_ctx *exec_ctx, return error; } -static grpc_error *pollset_as_multipollable_locked(grpc_exec_ctx *exec_ctx, - grpc_pollset *pollset, - pollable **pollable_obj) { - grpc_error *error = GRPC_ERROR_NONE; - pollable *po_at_start = +static grpc_error* pollset_as_multipollable_locked(grpc_exec_ctx* exec_ctx, + grpc_pollset* pollset, + pollable** pollable_obj) { + grpc_error* error = GRPC_ERROR_NONE; + pollable* po_at_start = POLLABLE_REF(pollset->active_pollable, "pollset_as_multipollable"); switch (pollset->active_pollable->type) { case PO_EMPTY: @@ -1121,7 +1124,7 @@ static grpc_error *pollset_as_multipollable_locked(grpc_exec_ctx *exec_ctx, error = pollable_create(PO_MULTI, &pollset->active_pollable); } else { error = pollset_transition_pollable_from_fd_to_multi_locked( - exec_ctx, pollset, NULL); + exec_ctx, pollset, nullptr); } gpr_mu_unlock(&po_at_start->owner_fd->orphan_mu); break; @@ -1131,7 +1134,7 @@ static grpc_error *pollset_as_multipollable_locked(grpc_exec_ctx *exec_ctx, if (error != GRPC_ERROR_NONE) { POLLABLE_UNREF(pollset->active_pollable, "pollset"); pollset->active_pollable = po_at_start; - *pollable_obj = NULL; + *pollable_obj = nullptr; } else { *pollable_obj = POLLABLE_REF(pollset->active_pollable, "pollset_set"); POLLABLE_UNREF(po_at_start, "pollset_as_multipollable"); @@ -1139,10 +1142,10 @@ static grpc_error *pollset_as_multipollable_locked(grpc_exec_ctx *exec_ctx, return error; } -static void pollset_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_fd *fd) { +static void pollset_add_fd(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_fd* fd) { gpr_mu_lock(&pollset->mu); - grpc_error *error = pollset_add_fd_locked(exec_ctx, pollset, fd); + grpc_error* error = pollset_add_fd_locked(exec_ctx, pollset, fd); gpr_mu_unlock(&pollset->mu); GRPC_LOG_IF_ERROR("pollset_add_fd", error); } @@ -1151,9 +1154,9 @@ static void pollset_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, * Pollset-set Definitions */ -static grpc_pollset_set *pss_lock_adam(grpc_pollset_set *pss) { +static grpc_pollset_set* pss_lock_adam(grpc_pollset_set* pss) { gpr_mu_lock(&pss->mu); - while (pss->parent != NULL) { + while (pss->parent != nullptr) { gpr_mu_unlock(&pss->mu); pss = pss->parent; gpr_mu_lock(&pss->mu); @@ -1161,15 +1164,15 @@ static grpc_pollset_set *pss_lock_adam(grpc_pollset_set *pss) { return pss; } -static grpc_pollset_set *pollset_set_create(void) { - grpc_pollset_set *pss = (grpc_pollset_set *)gpr_zalloc(sizeof(*pss)); +static grpc_pollset_set* pollset_set_create(void) { + grpc_pollset_set* pss = (grpc_pollset_set*)gpr_zalloc(sizeof(*pss)); gpr_mu_init(&pss->mu); gpr_ref_init(&pss->refs, 1); return pss; } -static void pollset_set_unref(grpc_exec_ctx *exec_ctx, grpc_pollset_set *pss) { - if (pss == NULL) return; +static void pollset_set_unref(grpc_exec_ctx* exec_ctx, grpc_pollset_set* pss) { + if (pss == nullptr) return; if (!gpr_unref(&pss->refs)) return; pollset_set_unref(exec_ctx, pss->parent); gpr_mu_destroy(&pss->mu); @@ -1188,13 +1191,13 @@ static void pollset_set_unref(grpc_exec_ctx *exec_ctx, grpc_pollset_set *pss) { gpr_free(pss); } -static void pollset_set_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset_set *pss, - grpc_fd *fd) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { +static void pollset_set_add_fd(grpc_exec_ctx* exec_ctx, grpc_pollset_set* pss, + grpc_fd* fd) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PSS:%p: add fd %p (%d)", pss, fd, fd->fd); } - grpc_error *error = GRPC_ERROR_NONE; - static const char *err_desc = "pollset_set_add_fd"; + grpc_error* error = GRPC_ERROR_NONE; + static const char* err_desc = "pollset_set_add_fd"; pss = pss_lock_adam(pss); for (size_t i = 0; i < pss->pollset_count; i++) { append_error(&error, pollable_add_fd(pss->pollsets[i]->active_pollable, fd), @@ -1203,7 +1206,7 @@ static void pollset_set_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset_set *pss, if (pss->fd_count == pss->fd_capacity) { pss->fd_capacity = GPR_MAX(pss->fd_capacity * 2, 8); pss->fds = - (grpc_fd **)gpr_realloc(pss->fds, pss->fd_capacity * sizeof(*pss->fds)); + (grpc_fd**)gpr_realloc(pss->fds, pss->fd_capacity * sizeof(*pss->fds)); } REF_BY(fd, 2, "pollset_set"); pss->fds[pss->fd_count++] = fd; @@ -1212,9 +1215,9 @@ static void pollset_set_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset_set *pss, GRPC_LOG_IF_ERROR(err_desc, error); } -static void pollset_set_del_fd(grpc_exec_ctx *exec_ctx, grpc_pollset_set *pss, - grpc_fd *fd) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { +static void pollset_set_del_fd(grpc_exec_ctx* exec_ctx, grpc_pollset_set* pss, + grpc_fd* fd) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PSS:%p: del fd %p", pss, fd); } pss = pss_lock_adam(pss); @@ -1233,9 +1236,9 @@ static void pollset_set_del_fd(grpc_exec_ctx *exec_ctx, grpc_pollset_set *pss, gpr_mu_unlock(&pss->mu); } -static void pollset_set_del_pollset(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pss, grpc_pollset *ps) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { +static void pollset_set_del_pollset(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pss, grpc_pollset* ps) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PSS:%p: del pollset %p", pss, ps); } pss = pss_lock_adam(pss); @@ -1260,12 +1263,12 @@ static void pollset_set_del_pollset(grpc_exec_ctx *exec_ctx, // add all fds to pollables, and output a new array of unorphaned out_fds // assumes pollsets are multipollable -static grpc_error *add_fds_to_pollsets(grpc_exec_ctx *exec_ctx, grpc_fd **fds, - size_t fd_count, grpc_pollset **pollsets, +static grpc_error* add_fds_to_pollsets(grpc_exec_ctx* exec_ctx, grpc_fd** fds, + size_t fd_count, grpc_pollset** pollsets, size_t pollset_count, - const char *err_desc, grpc_fd **out_fds, - size_t *out_fd_count) { - grpc_error *error = GRPC_ERROR_NONE; + const char* err_desc, grpc_fd** out_fds, + size_t* out_fd_count) { + grpc_error* error = GRPC_ERROR_NONE; for (size_t i = 0; i < fd_count; i++) { gpr_mu_lock(&fds[i]->orphan_mu); if ((gpr_atm_no_barrier_load(&fds[i]->refst) & 1) == 0) { @@ -1284,18 +1287,18 @@ static grpc_error *add_fds_to_pollsets(grpc_exec_ctx *exec_ctx, grpc_fd **fds, return error; } -static void pollset_set_add_pollset(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pss, grpc_pollset *ps) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { +static void pollset_set_add_pollset(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pss, grpc_pollset* ps) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PSS:%p: add pollset %p", pss, ps); } - grpc_error *error = GRPC_ERROR_NONE; - static const char *err_desc = "pollset_set_add_pollset"; - pollable *pollable_obj = NULL; + grpc_error* error = GRPC_ERROR_NONE; + static const char* err_desc = "pollset_set_add_pollset"; + pollable* pollable_obj = nullptr; gpr_mu_lock(&ps->mu); if (!GRPC_LOG_IF_ERROR(err_desc, pollset_as_multipollable_locked( exec_ctx, ps, &pollable_obj))) { - GPR_ASSERT(pollable_obj == NULL); + GPR_ASSERT(pollable_obj == nullptr); gpr_mu_unlock(&ps->mu); return; } @@ -1310,7 +1313,7 @@ static void pollset_set_add_pollset(grpc_exec_ctx *exec_ctx, err_desc); if (pss->pollset_count == pss->pollset_capacity) { pss->pollset_capacity = GPR_MAX(pss->pollset_capacity * 2, 8); - pss->pollsets = (grpc_pollset **)gpr_realloc( + pss->pollsets = (grpc_pollset**)gpr_realloc( pss->pollsets, pss->pollset_capacity * sizeof(*pss->pollsets)); } pss->pollsets[pss->pollset_count++] = ps; @@ -1320,29 +1323,29 @@ static void pollset_set_add_pollset(grpc_exec_ctx *exec_ctx, GRPC_LOG_IF_ERROR(err_desc, error); } -static void pollset_set_add_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *a, - grpc_pollset_set *b) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { +static void pollset_set_add_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* a, + grpc_pollset_set* b) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PSS: merge (%p, %p)", a, b); } - grpc_error *error = GRPC_ERROR_NONE; - static const char *err_desc = "pollset_set_add_fd"; + grpc_error* error = GRPC_ERROR_NONE; + static const char* err_desc = "pollset_set_add_fd"; for (;;) { if (a == b) { // pollset ancestors are the same: nothing to do return; } if (a > b) { - GPR_SWAP(grpc_pollset_set *, a, b); + GPR_SWAP(grpc_pollset_set*, a, b); } - gpr_mu *a_mu = &a->mu; - gpr_mu *b_mu = &b->mu; + gpr_mu* a_mu = &a->mu; + gpr_mu* b_mu = &b->mu; gpr_mu_lock(a_mu); gpr_mu_lock(b_mu); - if (a->parent != NULL) { + if (a->parent != nullptr) { a = a->parent; - } else if (b->parent != NULL) { + } else if (b->parent != nullptr) { b = b->parent; } else { break; // exit loop, both pollsets locked @@ -1355,31 +1358,33 @@ static void pollset_set_add_pollset_set(grpc_exec_ctx *exec_ctx, const size_t a_size = a->fd_count + a->pollset_count; const size_t b_size = b->fd_count + b->pollset_count; if (b_size > a_size) { - GPR_SWAP(grpc_pollset_set *, a, b); + GPR_SWAP(grpc_pollset_set*, a, b); } - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "PSS: parent %p to %p", b, a); } gpr_ref(&a->refs); b->parent = a; if (a->fd_capacity < a->fd_count + b->fd_count) { a->fd_capacity = GPR_MAX(2 * a->fd_capacity, a->fd_count + b->fd_count); - a->fds = (grpc_fd **)gpr_realloc(a->fds, a->fd_capacity * sizeof(*a->fds)); + a->fds = (grpc_fd**)gpr_realloc(a->fds, a->fd_capacity * sizeof(*a->fds)); } size_t initial_a_fd_count = a->fd_count; a->fd_count = 0; - append_error(&error, add_fds_to_pollsets(exec_ctx, a->fds, initial_a_fd_count, - b->pollsets, b->pollset_count, - "merge_a2b", a->fds, &a->fd_count), - err_desc); - append_error(&error, add_fds_to_pollsets(exec_ctx, b->fds, b->fd_count, - a->pollsets, a->pollset_count, - "merge_b2a", a->fds, &a->fd_count), - err_desc); + append_error( + &error, + add_fds_to_pollsets(exec_ctx, a->fds, initial_a_fd_count, b->pollsets, + b->pollset_count, "merge_a2b", a->fds, &a->fd_count), + err_desc); + append_error( + &error, + add_fds_to_pollsets(exec_ctx, b->fds, b->fd_count, a->pollsets, + a->pollset_count, "merge_b2a", a->fds, &a->fd_count), + err_desc); if (a->pollset_capacity < a->pollset_count + b->pollset_count) { a->pollset_capacity = GPR_MAX(2 * a->pollset_capacity, a->pollset_count + b->pollset_count); - a->pollsets = (grpc_pollset **)gpr_realloc( + a->pollsets = (grpc_pollset**)gpr_realloc( a->pollsets, a->pollset_capacity * sizeof(*a->pollsets)); } if (b->pollset_count > 0) { @@ -1389,16 +1394,16 @@ static void pollset_set_add_pollset_set(grpc_exec_ctx *exec_ctx, a->pollset_count += b->pollset_count; gpr_free(b->fds); gpr_free(b->pollsets); - b->fds = NULL; - b->pollsets = NULL; + b->fds = nullptr; + b->pollsets = nullptr; b->fd_count = b->fd_capacity = b->pollset_count = b->pollset_capacity = 0; gpr_mu_unlock(&a->mu); gpr_mu_unlock(&b->mu); } -static void pollset_set_del_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *bag, - grpc_pollset_set *item) {} +static void pollset_set_del_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* bag, + grpc_pollset_set* item) {} /******************************************************************************* * Event engine binding @@ -1440,30 +1445,28 @@ static const grpc_event_engine_vtable vtable = { shutdown_engine, }; -const grpc_event_engine_vtable *grpc_init_epollex_linux( +const grpc_event_engine_vtable* grpc_init_epollex_linux( bool explicitly_requested) { if (!explicitly_requested) { - return NULL; + return nullptr; } if (!grpc_has_wakeup_fd()) { - return NULL; + gpr_log(GPR_ERROR, "Skipping epollex because of no wakeup fd."); + return nullptr; } if (!grpc_is_epollexclusive_available()) { - return NULL; + gpr_log(GPR_INFO, "Skipping epollex because it is not supported."); + return nullptr; } -#ifndef NDEBUG - grpc_register_tracer(&grpc_trace_pollable_refcount); -#endif - fd_global_init(); if (!GRPC_LOG_IF_ERROR("pollset_global_init", pollset_global_init())) { pollset_global_shutdown(); fd_global_shutdown(); - return NULL; + return nullptr; } return &vtable; @@ -1474,8 +1477,10 @@ const grpc_event_engine_vtable *grpc_init_epollex_linux( #include "src/core/lib/iomgr/ev_epollex_linux.h" /* If GRPC_LINUX_EPOLL is not defined, it means epoll is not available. Return * NULL */ -const grpc_event_engine_vtable *grpc_init_epollex_linux( +const grpc_event_engine_vtable* grpc_init_epollex_linux( bool explicitly_requested) { + gpr_log(GPR_ERROR, + "Skipping epollex becuase GRPC_LINUX_EPOLL is not defined."); return NULL; } #endif /* defined(GRPC_POSIX_SOCKET) */ diff --git a/src/core/lib/iomgr/ev_epollex_linux.h b/src/core/lib/iomgr/ev_epollex_linux.h index 2849a232835..ffa7fc7f327 100644 --- a/src/core/lib/iomgr/ev_epollex_linux.h +++ b/src/core/lib/iomgr/ev_epollex_linux.h @@ -22,15 +22,7 @@ #include "src/core/lib/iomgr/ev_posix.h" #include "src/core/lib/iomgr/port.h" -#ifdef __cplusplus -extern "C" { -#endif - -const grpc_event_engine_vtable *grpc_init_epollex_linux( +const grpc_event_engine_vtable* grpc_init_epollex_linux( bool explicitly_requested); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_EV_EPOLLEX_LINUX_H */ diff --git a/src/core/lib/iomgr/ev_epollsig_linux.cc b/src/core/lib/iomgr/ev_epollsig_linux.cc index 035bdc4cb55..12c8483b8ee 100644 --- a/src/core/lib/iomgr/ev_epollsig_linux.cc +++ b/src/core/lib/iomgr/ev_epollsig_linux.cc @@ -19,6 +19,7 @@ #include "src/core/lib/iomgr/port.h" #include +#include /* This polling engine is only relevant on linux kernels supporting epoll() */ #ifdef GRPC_LINUX_EPOLL @@ -37,7 +38,6 @@ #include #include -#include #include #include #include @@ -50,12 +50,13 @@ #include "src/core/lib/iomgr/timer.h" #include "src/core/lib/iomgr/wakeup_fd_posix.h" #include "src/core/lib/profiling/timers.h" +#include "src/core/lib/support/manual_constructor.h" -#define GRPC_POLLSET_KICK_BROADCAST ((grpc_pollset_worker *)1) +#define GRPC_POLLSET_KICK_BROADCAST ((grpc_pollset_worker*)1) -#define GRPC_POLLING_TRACE(...) \ - if (GRPC_TRACER_ON(grpc_polling_trace)) { \ - gpr_log(GPR_INFO, __VA_ARGS__); \ +#define GRPC_POLLING_TRACE(...) \ + if (grpc_polling_trace.enabled()) { \ + gpr_log(GPR_INFO, __VA_ARGS__); \ } static int grpc_wakeup_signal = -1; @@ -90,10 +91,10 @@ typedef struct poll_obj { poll_obj_type obj_type; #endif gpr_mu mu; - struct polling_island *pi; + struct polling_island* pi; } poll_obj; -const char *poll_obj_string(poll_obj_type po_type) { +const char* poll_obj_string(poll_obj_type po_type) { switch (po_type) { case POLL_OBJ_FD: return "fd"; @@ -106,11 +107,11 @@ const char *poll_obj_string(poll_obj_type po_type) { GPR_UNREACHABLE_CODE(return "UNKNOWN"); } -/******************************************************************************* - * Fd Declarations - */ + /******************************************************************************* + * Fd Declarations + */ -#define FD_FROM_PO(po) ((grpc_fd *)(po)) +#define FD_FROM_PO(po) ((grpc_fd*)(po)) struct grpc_fd { poll_obj po; @@ -127,11 +128,11 @@ struct grpc_fd { valid */ bool orphaned; - gpr_atm read_closure; - gpr_atm write_closure; + grpc_core::ManualConstructor read_closure; + grpc_core::ManualConstructor write_closure; - struct grpc_fd *freelist_next; - grpc_closure *on_done_closure; + struct grpc_fd* freelist_next; + grpc_closure* on_done_closure; /* The pollset that last noticed that the fd is readable. The actual type * stored in this is (grpc_pollset *) */ @@ -142,14 +143,14 @@ struct grpc_fd { /* Reference counting for fds */ #ifndef NDEBUG -static void fd_ref(grpc_fd *fd, const char *reason, const char *file, int line); -static void fd_unref(grpc_fd *fd, const char *reason, const char *file, +static void fd_ref(grpc_fd* fd, const char* reason, const char* file, int line); +static void fd_unref(grpc_fd* fd, const char* reason, const char* file, int line); #define GRPC_FD_REF(fd, reason) fd_ref(fd, reason, __FILE__, __LINE__) #define GRPC_FD_UNREF(fd, reason) fd_unref(fd, reason, __FILE__, __LINE__) #else -static void fd_ref(grpc_fd *fd); -static void fd_unref(grpc_fd *fd); +static void fd_ref(grpc_fd* fd); +static void fd_unref(grpc_fd* fd); #define GRPC_FD_REF(fd, reason) fd_ref(fd) #define GRPC_FD_UNREF(fd, reason) fd_unref(fd) #endif @@ -203,7 +204,7 @@ typedef struct polling_island { /* The file descriptors in the epoll set */ size_t fd_cnt; size_t fd_capacity; - grpc_fd **fds; + grpc_fd** fds; } polling_island; /******************************************************************************* @@ -215,8 +216,8 @@ struct grpc_pollset_worker { /* Used to prevent a worker from getting kicked multiple times */ gpr_atm is_kicked; - struct grpc_pollset_worker *next; - struct grpc_pollset_worker *prev; + struct grpc_pollset_worker* next; + struct grpc_pollset_worker* prev; }; struct grpc_pollset { @@ -227,7 +228,7 @@ struct grpc_pollset { bool shutting_down; /* Is the pollset shutting down ? */ bool finish_shutdown_called; /* Is the 'finish_shutdown_locked()' called ? */ - grpc_closure *shutdown_done; /* Called after after shutdown is complete */ + grpc_closure* shutdown_done; /* Called after after shutdown is complete */ }; /******************************************************************************* @@ -241,8 +242,8 @@ struct grpc_pollset_set { * Common helpers */ -static bool append_error(grpc_error **composite, grpc_error *error, - const char *desc) { +static bool append_error(grpc_error** composite, grpc_error* error, + const char* desc) { if (error == GRPC_ERROR_NONE) return true; if (*composite == GRPC_ERROR_NONE) { *composite = GRPC_ERROR_CREATE_FROM_COPIED_STRING(desc); @@ -266,10 +267,10 @@ static grpc_wakeup_fd polling_island_wakeup_fd; /* The polling island being polled right now. See comments in workqueue_maybe_wakeup for why this is tracked. */ -static __thread polling_island *g_current_thread_polling_island; +static __thread polling_island* g_current_thread_polling_island; /* Forward declaration */ -static void polling_island_delete(grpc_exec_ctx *exec_ctx, polling_island *pi); +static void polling_island_delete(grpc_exec_ctx* exec_ctx, polling_island* pi); #ifdef GRPC_TSAN /* Currently TSAN may incorrectly flag data races between epoll_ctl and @@ -282,38 +283,40 @@ static void polling_island_delete(grpc_exec_ctx *exec_ctx, polling_island *pi); gpr_atm g_epoll_sync; #endif /* defined(GRPC_TSAN) */ -static void pi_add_ref(polling_island *pi); -static void pi_unref(grpc_exec_ctx *exec_ctx, polling_island *pi); +static void pi_add_ref(polling_island* pi); +static void pi_unref(grpc_exec_ctx* exec_ctx, polling_island* pi); #ifndef NDEBUG -static void pi_add_ref_dbg(polling_island *pi, const char *reason, - const char *file, int line) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { +static void pi_add_ref_dbg(polling_island* pi, const char* reason, + const char* file, int line) { + if (grpc_polling_trace.enabled()) { gpr_atm old_cnt = gpr_atm_acq_load(&pi->ref_count); - gpr_log(GPR_DEBUG, "Add ref pi: %p, old:%" PRIdPTR " -> new:%" PRIdPTR - " (%s) - (%s, %d)", + gpr_log(GPR_DEBUG, + "Add ref pi: %p, old:%" PRIdPTR " -> new:%" PRIdPTR + " (%s) - (%s, %d)", pi, old_cnt, old_cnt + 1, reason, file, line); } pi_add_ref(pi); } -static void pi_unref_dbg(grpc_exec_ctx *exec_ctx, polling_island *pi, - const char *reason, const char *file, int line) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { +static void pi_unref_dbg(grpc_exec_ctx* exec_ctx, polling_island* pi, + const char* reason, const char* file, int line) { + if (grpc_polling_trace.enabled()) { gpr_atm old_cnt = gpr_atm_acq_load(&pi->ref_count); - gpr_log(GPR_DEBUG, "Unref pi: %p, old:%" PRIdPTR " -> new:%" PRIdPTR - " (%s) - (%s, %d)", + gpr_log(GPR_DEBUG, + "Unref pi: %p, old:%" PRIdPTR " -> new:%" PRIdPTR + " (%s) - (%s, %d)", pi, old_cnt, (old_cnt - 1), reason, file, line); } pi_unref(exec_ctx, pi); } #endif -static void pi_add_ref(polling_island *pi) { +static void pi_add_ref(polling_island* pi) { gpr_atm_no_barrier_fetch_add(&pi->ref_count, 1); } -static void pi_unref(grpc_exec_ctx *exec_ctx, polling_island *pi) { +static void pi_unref(grpc_exec_ctx* exec_ctx, polling_island* pi) { /* If ref count went to zero, delete the polling island. Note that this deletion not be done under a lock. Once the ref count goes to zero, we are guaranteed that no one else holds a reference to the @@ -323,23 +326,23 @@ static void pi_unref(grpc_exec_ctx *exec_ctx, polling_island *pi) { non-empty, we should remove a ref to the merged_to polling island */ if (1 == gpr_atm_full_fetch_add(&pi->ref_count, -1)) { - polling_island *next = (polling_island *)gpr_atm_acq_load(&pi->merged_to); + polling_island* next = (polling_island*)gpr_atm_acq_load(&pi->merged_to); polling_island_delete(exec_ctx, pi); - if (next != NULL) { + if (next != nullptr) { PI_UNREF(exec_ctx, next, "pi_delete"); /* Recursive call */ } } } /* The caller is expected to hold pi->mu lock before calling this function */ -static void polling_island_add_fds_locked(polling_island *pi, grpc_fd **fds, +static void polling_island_add_fds_locked(polling_island* pi, grpc_fd** fds, size_t fd_count, bool add_fd_refs, - grpc_error **error) { + grpc_error** error) { int err; size_t i; struct epoll_event ev; - char *err_msg; - const char *err_desc = "polling_island_add_fds"; + char* err_msg; + const char* err_desc = "polling_island_add_fds"; #ifdef GRPC_TSAN /* See the definition of g_epoll_sync for more context */ @@ -367,7 +370,7 @@ static void polling_island_add_fds_locked(polling_island *pi, grpc_fd **fds, if (pi->fd_cnt == pi->fd_capacity) { pi->fd_capacity = GPR_MAX(pi->fd_capacity + 8, pi->fd_cnt * 3 / 2); pi->fds = - (grpc_fd **)gpr_realloc(pi->fds, sizeof(grpc_fd *) * pi->fd_capacity); + (grpc_fd**)gpr_realloc(pi->fds, sizeof(grpc_fd*) * pi->fd_capacity); } pi->fds[pi->fd_cnt++] = fds[i]; @@ -378,13 +381,13 @@ static void polling_island_add_fds_locked(polling_island *pi, grpc_fd **fds, } /* The caller is expected to hold pi->mu before calling this */ -static void polling_island_add_wakeup_fd_locked(polling_island *pi, - grpc_wakeup_fd *wakeup_fd, - grpc_error **error) { +static void polling_island_add_wakeup_fd_locked(polling_island* pi, + grpc_wakeup_fd* wakeup_fd, + grpc_error** error) { struct epoll_event ev; int err; - char *err_msg; - const char *err_desc = "polling_island_add_wakeup_fd"; + char* err_msg; + const char* err_desc = "polling_island_add_wakeup_fd"; ev.events = (uint32_t)(EPOLLIN | EPOLLET); ev.data.ptr = wakeup_fd; @@ -402,16 +405,16 @@ static void polling_island_add_wakeup_fd_locked(polling_island *pi, } /* The caller is expected to hold pi->mu lock before calling this function */ -static void polling_island_remove_all_fds_locked(polling_island *pi, +static void polling_island_remove_all_fds_locked(polling_island* pi, bool remove_fd_refs, - grpc_error **error) { + grpc_error** error) { int err; size_t i; - char *err_msg; - const char *err_desc = "polling_island_remove_fds"; + char* err_msg; + const char* err_desc = "polling_island_remove_fds"; for (i = 0; i < pi->fd_cnt; i++) { - err = epoll_ctl(pi->epoll_fd, EPOLL_CTL_DEL, pi->fds[i]->fd, NULL); + err = epoll_ctl(pi->epoll_fd, EPOLL_CTL_DEL, pi->fds[i]->fd, nullptr); if (err < 0 && errno != ENOENT) { gpr_asprintf(&err_msg, "epoll_ctl (epoll_fd: %d) delete fds[%zu]: %d failed with " @@ -430,18 +433,18 @@ static void polling_island_remove_all_fds_locked(polling_island *pi, } /* The caller is expected to hold pi->mu lock before calling this function */ -static void polling_island_remove_fd_locked(polling_island *pi, grpc_fd *fd, +static void polling_island_remove_fd_locked(polling_island* pi, grpc_fd* fd, bool is_fd_closed, - grpc_error **error) { + grpc_error** error) { int err; size_t i; - char *err_msg; - const char *err_desc = "polling_island_remove_fd"; + char* err_msg; + const char* err_desc = "polling_island_remove_fd"; /* If fd is already closed, then it would have been automatically been removed from the epoll set */ if (!is_fd_closed) { - err = epoll_ctl(pi->epoll_fd, EPOLL_CTL_DEL, fd->fd, NULL); + err = epoll_ctl(pi->epoll_fd, EPOLL_CTL_DEL, fd->fd, nullptr); if (err < 0 && errno != ENOENT) { gpr_asprintf( &err_msg, @@ -462,19 +465,19 @@ static void polling_island_remove_fd_locked(polling_island *pi, grpc_fd *fd, } /* Might return NULL in case of an error */ -static polling_island *polling_island_create(grpc_exec_ctx *exec_ctx, - grpc_fd *initial_fd, - grpc_error **error) { - polling_island *pi = NULL; - const char *err_desc = "polling_island_create"; +static polling_island* polling_island_create(grpc_exec_ctx* exec_ctx, + grpc_fd* initial_fd, + grpc_error** error) { + polling_island* pi = nullptr; + const char* err_desc = "polling_island_create"; *error = GRPC_ERROR_NONE; - pi = (polling_island *)gpr_malloc(sizeof(*pi)); + pi = (polling_island*)gpr_malloc(sizeof(*pi)); gpr_mu_init(&pi->mu); pi->fd_cnt = 0; pi->fd_capacity = 0; - pi->fds = NULL; + pi->fds = nullptr; pi->epoll_fd = -1; gpr_atm_rel_store(&pi->ref_count, 0); @@ -488,19 +491,19 @@ static polling_island *polling_island_create(grpc_exec_ctx *exec_ctx, goto done; } - if (initial_fd != NULL) { + if (initial_fd != nullptr) { polling_island_add_fds_locked(pi, &initial_fd, 1, true, error); } done: if (*error != GRPC_ERROR_NONE) { polling_island_delete(exec_ctx, pi); - pi = NULL; + pi = nullptr; } return pi; } -static void polling_island_delete(grpc_exec_ctx *exec_ctx, polling_island *pi) { +static void polling_island_delete(grpc_exec_ctx* exec_ctx, polling_island* pi) { GPR_ASSERT(pi->fd_cnt == 0); if (pi->epoll_fd >= 0) { @@ -514,11 +517,11 @@ static void polling_island_delete(grpc_exec_ctx *exec_ctx, polling_island *pi) { /* Attempts to gets the last polling island in the linked list (liked by the * 'merged_to' field). Since this does not lock the polling island, there are no * guarantees that the island returned is the last island */ -static polling_island *polling_island_maybe_get_latest(polling_island *pi) { - polling_island *next = (polling_island *)gpr_atm_acq_load(&pi->merged_to); - while (next != NULL) { +static polling_island* polling_island_maybe_get_latest(polling_island* pi) { + polling_island* next = (polling_island*)gpr_atm_acq_load(&pi->merged_to); + while (next != nullptr) { pi = next; - next = (polling_island *)gpr_atm_acq_load(&pi->merged_to); + next = (polling_island*)gpr_atm_acq_load(&pi->merged_to); } return pi; @@ -533,19 +536,19 @@ static polling_island *polling_island_maybe_get_latest(polling_island *pi) { ... critical section .. ... gpr_mu_unlock(&pi_latest->mu); // NOTE: use pi_latest->mu. NOT pi->mu */ -static polling_island *polling_island_lock(polling_island *pi) { - polling_island *next = NULL; +static polling_island* polling_island_lock(polling_island* pi) { + polling_island* next = nullptr; while (true) { - next = (polling_island *)gpr_atm_acq_load(&pi->merged_to); - if (next == NULL) { + next = (polling_island*)gpr_atm_acq_load(&pi->merged_to); + if (next == nullptr) { /* Looks like 'pi' is the last node in the linked list but unless we check this by holding the pi->mu lock, we cannot be sure (i.e without the pi->mu lock, we don't prevent island merges). To be absolutely sure, check once more by holding the pi->mu lock */ gpr_mu_lock(&pi->mu); - next = (polling_island *)gpr_atm_acq_load(&pi->merged_to); - if (next == NULL) { + next = (polling_island*)gpr_atm_acq_load(&pi->merged_to); + if (next == nullptr) { /* pi is infact the last node and we have the pi->mu lock. we're done */ break; } @@ -582,11 +585,11 @@ static polling_island *polling_island_lock(polling_island *pi) { // Release locks: Always call polling_island_unlock_pair() to release locks polling_island_unlock_pair(p1, p2); */ -static void polling_island_lock_pair(polling_island **p, polling_island **q) { - polling_island *pi_1 = *p; - polling_island *pi_2 = *q; - polling_island *next_1 = NULL; - polling_island *next_2 = NULL; +static void polling_island_lock_pair(polling_island** p, polling_island** q) { + polling_island* pi_1 = *p; + polling_island* pi_2 = *q; + polling_island* next_1 = nullptr; + polling_island* next_2 = nullptr; /* The algorithm is simple: - Go to the last polling islands in the linked lists *pi_1 and *pi_2 (and @@ -603,16 +606,16 @@ static void polling_island_lock_pair(polling_island **p, polling_island **q) { - If the polling islands are the last islands, we are done. If not, release the locks and continue the process from the first step */ while (true) { - next_1 = (polling_island *)gpr_atm_acq_load(&pi_1->merged_to); - while (next_1 != NULL) { + next_1 = (polling_island*)gpr_atm_acq_load(&pi_1->merged_to); + while (next_1 != nullptr) { pi_1 = next_1; - next_1 = (polling_island *)gpr_atm_acq_load(&pi_1->merged_to); + next_1 = (polling_island*)gpr_atm_acq_load(&pi_1->merged_to); } - next_2 = (polling_island *)gpr_atm_acq_load(&pi_2->merged_to); - while (next_2 != NULL) { + next_2 = (polling_island*)gpr_atm_acq_load(&pi_2->merged_to); + while (next_2 != nullptr) { pi_2 = next_2; - next_2 = (polling_island *)gpr_atm_acq_load(&pi_2->merged_to); + next_2 = (polling_island*)gpr_atm_acq_load(&pi_2->merged_to); } if (pi_1 == pi_2) { @@ -628,9 +631,9 @@ static void polling_island_lock_pair(polling_island **p, polling_island **q) { gpr_mu_lock(&pi_1->mu); } - next_1 = (polling_island *)gpr_atm_acq_load(&pi_1->merged_to); - next_2 = (polling_island *)gpr_atm_acq_load(&pi_2->merged_to); - if (next_1 == NULL && next_2 == NULL) { + next_1 = (polling_island*)gpr_atm_acq_load(&pi_1->merged_to); + next_2 = (polling_island*)gpr_atm_acq_load(&pi_2->merged_to); + if (next_1 == nullptr && next_2 == nullptr) { break; } @@ -642,7 +645,7 @@ static void polling_island_lock_pair(polling_island **p, polling_island **q) { *q = pi_2; } -static void polling_island_unlock_pair(polling_island *p, polling_island *q) { +static void polling_island_unlock_pair(polling_island* p, polling_island* q) { if (p == q) { gpr_mu_unlock(&p->mu); } else { @@ -651,16 +654,16 @@ static void polling_island_unlock_pair(polling_island *p, polling_island *q) { } } -static polling_island *polling_island_merge(polling_island *p, - polling_island *q, - grpc_error **error) { +static polling_island* polling_island_merge(polling_island* p, + polling_island* q, + grpc_error** error) { /* Get locks on both the polling islands */ polling_island_lock_pair(&p, &q); if (p != q) { /* Make sure that p points to the polling island with fewer fds than q */ if (p->fd_cnt > q->fd_cnt) { - GPR_SWAP(polling_island *, p, q); + GPR_SWAP(polling_island*, p, q); } /* Merge p with q i.e move all the fds from p (The one with fewer fds) to q @@ -685,8 +688,8 @@ static polling_island *polling_island_merge(polling_island *p, return q; } -static grpc_error *polling_island_global_init() { - grpc_error *error = GRPC_ERROR_NONE; +static grpc_error* polling_island_global_init() { + grpc_error* error = GRPC_ERROR_NONE; error = grpc_wakeup_fd_init(&polling_island_wakeup_fd); if (error == GRPC_ERROR_NONE) { @@ -722,15 +725,15 @@ static void polling_island_global_shutdown() { * alarm 'epoch'). This wakeup_fd gives us something to alert on when such a * case occurs. */ -static grpc_fd *fd_freelist = NULL; +static grpc_fd* fd_freelist = nullptr; static gpr_mu fd_freelist_mu; #ifndef NDEBUG #define REF_BY(fd, n, reason) ref_by(fd, n, reason, __FILE__, __LINE__) #define UNREF_BY(fd, n, reason) unref_by(fd, n, reason, __FILE__, __LINE__) -static void ref_by(grpc_fd *fd, int n, const char *reason, const char *file, +static void ref_by(grpc_fd* fd, int n, const char* reason, const char* file, int line) { - if (GRPC_TRACER_ON(grpc_trace_fd_refcount)) { + if (grpc_trace_fd_refcount.enabled()) { gpr_log(GPR_DEBUG, "FD %d %p ref %d %" PRIdPTR " -> %" PRIdPTR " [%s; %s:%d]", fd->fd, fd, n, gpr_atm_no_barrier_load(&fd->refst), @@ -739,22 +742,22 @@ static void ref_by(grpc_fd *fd, int n, const char *reason, const char *file, #else #define REF_BY(fd, n, reason) ref_by(fd, n) #define UNREF_BY(fd, n, reason) unref_by(fd, n) -static void ref_by(grpc_fd *fd, int n) { +static void ref_by(grpc_fd* fd, int n) { #endif GPR_ASSERT(gpr_atm_no_barrier_fetch_add(&fd->refst, n) > 0); } #ifndef NDEBUG -static void unref_by(grpc_fd *fd, int n, const char *reason, const char *file, +static void unref_by(grpc_fd* fd, int n, const char* reason, const char* file, int line) { - if (GRPC_TRACER_ON(grpc_trace_fd_refcount)) { + if (grpc_trace_fd_refcount.enabled()) { gpr_log(GPR_DEBUG, "FD %d %p unref %d %" PRIdPTR " -> %" PRIdPTR " [%s; %s:%d]", fd->fd, fd, n, gpr_atm_no_barrier_load(&fd->refst), gpr_atm_no_barrier_load(&fd->refst) - n, reason, file, line); } #else -static void unref_by(grpc_fd *fd, int n) { +static void unref_by(grpc_fd* fd, int n) { #endif gpr_atm old = gpr_atm_full_fetch_add(&fd->refst, -n); if (old == n) { @@ -764,8 +767,8 @@ static void unref_by(grpc_fd *fd, int n) { fd_freelist = fd; grpc_iomgr_unregister_object(&fd->iomgr_object); - grpc_lfev_destroy(&fd->read_closure); - grpc_lfev_destroy(&fd->write_closure); + fd->read_closure->DestroyEvent(); + fd->write_closure->DestroyEvent(); gpr_mu_unlock(&fd_freelist_mu); } else { @@ -775,18 +778,18 @@ static void unref_by(grpc_fd *fd, int n) { /* Increment refcount by two to avoid changing the orphan bit */ #ifndef NDEBUG -static void fd_ref(grpc_fd *fd, const char *reason, const char *file, +static void fd_ref(grpc_fd* fd, const char* reason, const char* file, int line) { ref_by(fd, 2, reason, file, line); } -static void fd_unref(grpc_fd *fd, const char *reason, const char *file, +static void fd_unref(grpc_fd* fd, const char* reason, const char* file, int line) { unref_by(fd, 2, reason, file, line); } #else -static void fd_ref(grpc_fd *fd) { ref_by(fd, 2); } -static void fd_unref(grpc_fd *fd) { unref_by(fd, 2); } +static void fd_ref(grpc_fd* fd) { ref_by(fd, 2); } +static void fd_unref(grpc_fd* fd) { unref_by(fd, 2); } #endif static void fd_global_init(void) { gpr_mu_init(&fd_freelist_mu); } @@ -794,8 +797,8 @@ static void fd_global_init(void) { gpr_mu_init(&fd_freelist_mu); } static void fd_global_shutdown(void) { gpr_mu_lock(&fd_freelist_mu); gpr_mu_unlock(&fd_freelist_mu); - while (fd_freelist != NULL) { - grpc_fd *fd = fd_freelist; + while (fd_freelist != nullptr) { + grpc_fd* fd = fd_freelist; fd_freelist = fd_freelist->freelist_next; gpr_mu_destroy(&fd->po.mu); gpr_free(fd); @@ -803,26 +806,28 @@ static void fd_global_shutdown(void) { gpr_mu_destroy(&fd_freelist_mu); } -static grpc_fd *fd_create(int fd, const char *name) { - grpc_fd *new_fd = NULL; +static grpc_fd* fd_create(int fd, const char* name) { + grpc_fd* new_fd = nullptr; gpr_mu_lock(&fd_freelist_mu); - if (fd_freelist != NULL) { + if (fd_freelist != nullptr) { new_fd = fd_freelist; fd_freelist = fd_freelist->freelist_next; } gpr_mu_unlock(&fd_freelist_mu); - if (new_fd == NULL) { - new_fd = (grpc_fd *)gpr_malloc(sizeof(grpc_fd)); + if (new_fd == nullptr) { + new_fd = (grpc_fd*)gpr_malloc(sizeof(grpc_fd)); gpr_mu_init(&new_fd->po.mu); + new_fd->read_closure.Init(); + new_fd->write_closure.Init(); } /* Note: It is not really needed to get the new_fd->po.mu lock here. If this * is a newly created fd (or an fd we got from the freelist), no one else * would be holding a lock to it anyway. */ gpr_mu_lock(&new_fd->po.mu); - new_fd->po.pi = NULL; + new_fd->po.pi = nullptr; #ifndef NDEBUG new_fd->po.obj_type = POLL_OBJ_FD; #endif @@ -830,23 +835,23 @@ static grpc_fd *fd_create(int fd, const char *name) { gpr_atm_rel_store(&new_fd->refst, (gpr_atm)1); new_fd->fd = fd; new_fd->orphaned = false; - grpc_lfev_init(&new_fd->read_closure); - grpc_lfev_init(&new_fd->write_closure); + new_fd->read_closure->InitEvent(); + new_fd->write_closure->InitEvent(); gpr_atm_no_barrier_store(&new_fd->read_notifier_pollset, (gpr_atm)NULL); - new_fd->freelist_next = NULL; - new_fd->on_done_closure = NULL; + new_fd->freelist_next = nullptr; + new_fd->on_done_closure = nullptr; gpr_mu_unlock(&new_fd->po.mu); - char *fd_name; + char* fd_name; gpr_asprintf(&fd_name, "%s fd=%d", name, fd); grpc_iomgr_register_object(&new_fd->iomgr_object, fd_name); gpr_free(fd_name); return new_fd; } -static int fd_wrapped_fd(grpc_fd *fd) { +static int fd_wrapped_fd(grpc_fd* fd) { int ret_fd = -1; gpr_mu_lock(&fd->po.mu); if (!fd->orphaned) { @@ -857,11 +862,11 @@ static int fd_wrapped_fd(grpc_fd *fd) { return ret_fd; } -static void fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *on_done, int *release_fd, - bool already_closed, const char *reason) { - grpc_error *error = GRPC_ERROR_NONE; - polling_island *unref_pi = NULL; +static void fd_orphan(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* on_done, int* release_fd, + bool already_closed, const char* reason) { + grpc_error* error = GRPC_ERROR_NONE; + polling_island* unref_pi = nullptr; gpr_mu_lock(&fd->po.mu); fd->on_done_closure = on_done; @@ -878,18 +883,18 @@ static void fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - Unlock the latest polling island - Set fd->po.pi to NULL (but remove the ref on the polling island before doing this.) */ - if (fd->po.pi != NULL) { - polling_island *pi_latest = polling_island_lock(fd->po.pi); + if (fd->po.pi != nullptr) { + polling_island* pi_latest = polling_island_lock(fd->po.pi); polling_island_remove_fd_locked(pi_latest, fd, already_closed, &error); gpr_mu_unlock(&pi_latest->mu); unref_pi = fd->po.pi; - fd->po.pi = NULL; + fd->po.pi = nullptr; } /* If release_fd is not NULL, we should be relinquishing control of the file descriptor fd->fd (but we still own the grpc_fd structure). */ - if (release_fd != NULL) { + if (release_fd != nullptr) { *release_fd = fd->fd; } else { close(fd->fd); @@ -901,7 +906,7 @@ static void fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd, gpr_mu_unlock(&fd->po.mu); UNREF_BY(fd, 2, reason); /* Drop the reference */ - if (unref_pi != NULL) { + if (unref_pi != nullptr) { /* Unref stale polling island here, outside the fd lock above. The polling island owns a workqueue which owns an fd, and unreffing inside the lock can cause an eventual lock loop that makes TSAN very @@ -909,40 +914,39 @@ static void fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd, PI_UNREF(exec_ctx, unref_pi, "fd_orphan"); } if (error != GRPC_ERROR_NONE) { - const char *msg = grpc_error_string(error); + const char* msg = grpc_error_string(error); gpr_log(GPR_DEBUG, "fd_orphan: %s", msg); } GRPC_ERROR_UNREF(error); } -static grpc_pollset *fd_get_read_notifier_pollset(grpc_exec_ctx *exec_ctx, - grpc_fd *fd) { +static grpc_pollset* fd_get_read_notifier_pollset(grpc_exec_ctx* exec_ctx, + grpc_fd* fd) { gpr_atm notifier = gpr_atm_acq_load(&fd->read_notifier_pollset); - return (grpc_pollset *)notifier; + return (grpc_pollset*)notifier; } -static bool fd_is_shutdown(grpc_fd *fd) { - return grpc_lfev_is_shutdown(&fd->read_closure); +static bool fd_is_shutdown(grpc_fd* fd) { + return fd->read_closure->IsShutdown(); } /* Might be called multiple times */ -static void fd_shutdown(grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_error *why) { - if (grpc_lfev_set_shutdown(exec_ctx, &fd->read_closure, - GRPC_ERROR_REF(why))) { +static void fd_shutdown(grpc_exec_ctx* exec_ctx, grpc_fd* fd, grpc_error* why) { + if (fd->read_closure->SetShutdown(exec_ctx, GRPC_ERROR_REF(why))) { shutdown(fd->fd, SHUT_RDWR); - grpc_lfev_set_shutdown(exec_ctx, &fd->write_closure, GRPC_ERROR_REF(why)); + fd->write_closure->SetShutdown(exec_ctx, GRPC_ERROR_REF(why)); } GRPC_ERROR_UNREF(why); } -static void fd_notify_on_read(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *closure) { - grpc_lfev_notify_on(exec_ctx, &fd->read_closure, closure, "read"); +static void fd_notify_on_read(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* closure) { + fd->read_closure->NotifyOn(exec_ctx, closure); } -static void fd_notify_on_write(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *closure) { - grpc_lfev_notify_on(exec_ctx, &fd->write_closure, closure, "write"); +static void fd_notify_on_write(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* closure) { + fd->write_closure->NotifyOn(exec_ctx, closure); } /******************************************************************************* @@ -962,7 +966,7 @@ static void sig_handler(int sig_num) { static void poller_kick_init() { signal(grpc_wakeup_signal, sig_handler); } /* Global state management */ -static grpc_error *pollset_global_init(void) { +static grpc_error* pollset_global_init(void) { gpr_tls_init(&g_current_thread_pollset); gpr_tls_init(&g_current_thread_worker); poller_kick_init(); @@ -974,14 +978,14 @@ static void pollset_global_shutdown(void) { gpr_tls_destroy(&g_current_thread_worker); } -static grpc_error *pollset_worker_kick(grpc_pollset_worker *worker) { - grpc_error *err = GRPC_ERROR_NONE; +static grpc_error* pollset_worker_kick(grpc_pollset_worker* worker) { + grpc_error* err = GRPC_ERROR_NONE; /* Kick the worker only if it was not already kicked */ if (gpr_atm_no_barrier_cas(&worker->is_kicked, (gpr_atm)0, (gpr_atm)1)) { GRPC_POLLING_TRACE( "pollset_worker_kick: Kicking worker: %p (thread id: %ld)", - (void *)worker, (long int)worker->pt_id); + (void*)worker, (long int)worker->pt_id); int err_num = pthread_kill(worker->pt_id, grpc_wakeup_signal); if (err_num != 0) { err = GRPC_OS_ERROR(err_num, "pthread_kill"); @@ -992,46 +996,46 @@ static grpc_error *pollset_worker_kick(grpc_pollset_worker *worker) { /* Return 1 if the pollset has active threads in pollset_work (pollset must * be locked) */ -static int pollset_has_workers(grpc_pollset *p) { +static int pollset_has_workers(grpc_pollset* p) { return p->root_worker.next != &p->root_worker; } -static void remove_worker(grpc_pollset *p, grpc_pollset_worker *worker) { +static void remove_worker(grpc_pollset* p, grpc_pollset_worker* worker) { worker->prev->next = worker->next; worker->next->prev = worker->prev; } -static grpc_pollset_worker *pop_front_worker(grpc_pollset *p) { +static grpc_pollset_worker* pop_front_worker(grpc_pollset* p) { if (pollset_has_workers(p)) { - grpc_pollset_worker *w = p->root_worker.next; + grpc_pollset_worker* w = p->root_worker.next; remove_worker(p, w); return w; } else { - return NULL; + return nullptr; } } -static void push_back_worker(grpc_pollset *p, grpc_pollset_worker *worker) { +static void push_back_worker(grpc_pollset* p, grpc_pollset_worker* worker) { worker->next = &p->root_worker; worker->prev = worker->next->prev; worker->prev->next = worker->next->prev = worker; } -static void push_front_worker(grpc_pollset *p, grpc_pollset_worker *worker) { +static void push_front_worker(grpc_pollset* p, grpc_pollset_worker* worker) { worker->prev = &p->root_worker; worker->next = worker->prev->next; worker->prev->next = worker->next->prev = worker; } /* p->mu must be held before calling this function */ -static grpc_error *pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *p, - grpc_pollset_worker *specific_worker) { +static grpc_error* pollset_kick(grpc_exec_ctx* exec_ctx, grpc_pollset* p, + grpc_pollset_worker* specific_worker) { GPR_TIMER_BEGIN("pollset_kick", 0); - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; GRPC_STATS_INC_POLLSET_KICK(exec_ctx); - const char *err_desc = "Kick Failure"; - grpc_pollset_worker *worker = specific_worker; - if (worker != NULL) { + const char* err_desc = "Kick Failure"; + grpc_pollset_worker* worker = specific_worker; + if (worker != nullptr) { if (worker == GRPC_POLLSET_KICK_BROADCAST) { if (pollset_has_workers(p)) { GPR_TIMER_BEGIN("pollset_kick.broadcast", 0); @@ -1061,7 +1065,7 @@ static grpc_error *pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *p, GPR_TIMER_MARK("kick_anonymous", 0); worker = pop_front_worker(p); - if (worker != NULL) { + if (worker != nullptr) { GPR_TIMER_MARK("finally_kick", 0); push_back_worker(p, worker); append_error(&error, pollset_worker_kick(worker), err_desc); @@ -1076,10 +1080,10 @@ static grpc_error *pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *p, return error; } -static void pollset_init(grpc_pollset *pollset, gpr_mu **mu) { +static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) { gpr_mu_init(&pollset->po.mu); *mu = &pollset->po.mu; - pollset->po.pi = NULL; + pollset->po.pi = nullptr; #ifndef NDEBUG pollset->po.obj_type = POLL_OBJ_POLLSET; #endif @@ -1089,10 +1093,10 @@ static void pollset_init(grpc_pollset *pollset, gpr_mu **mu) { pollset->shutting_down = false; pollset->finish_shutdown_called = false; - pollset->shutdown_done = NULL; + pollset->shutdown_done = nullptr; } -static int poll_deadline_to_millis_timeout(grpc_exec_ctx *exec_ctx, +static int poll_deadline_to_millis_timeout(grpc_exec_ctx* exec_ctx, grpc_millis millis) { if (millis == GRPC_MILLIS_INF_FUTURE) return -1; grpc_millis delta = millis - grpc_exec_ctx_now(exec_ctx); @@ -1104,9 +1108,9 @@ static int poll_deadline_to_millis_timeout(grpc_exec_ctx *exec_ctx, return (int)delta; } -static void fd_become_readable(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_pollset *notifier) { - grpc_lfev_set_ready(exec_ctx, &fd->read_closure, "read"); +static void fd_become_readable(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_pollset* notifier) { + fd->read_closure->SetReady(exec_ctx); /* Note, it is possible that fd_become_readable might be called twice with different 'notifier's when an fd becomes readable and it is in two epoll @@ -1117,21 +1121,21 @@ static void fd_become_readable(grpc_exec_ctx *exec_ctx, grpc_fd *fd, gpr_atm_rel_store(&fd->read_notifier_pollset, (gpr_atm)notifier); } -static void fd_become_writable(grpc_exec_ctx *exec_ctx, grpc_fd *fd) { - grpc_lfev_set_ready(exec_ctx, &fd->write_closure, "write"); +static void fd_become_writable(grpc_exec_ctx* exec_ctx, grpc_fd* fd) { + fd->write_closure->SetReady(exec_ctx); } -static void pollset_release_polling_island(grpc_exec_ctx *exec_ctx, - grpc_pollset *ps, - const char *reason) { - if (ps->po.pi != NULL) { +static void pollset_release_polling_island(grpc_exec_ctx* exec_ctx, + grpc_pollset* ps, + const char* reason) { + if (ps->po.pi != nullptr) { PI_UNREF(exec_ctx, ps->po.pi, reason); } - ps->po.pi = NULL; + ps->po.pi = nullptr; } -static void finish_shutdown_locked(grpc_exec_ctx *exec_ctx, - grpc_pollset *pollset) { +static void finish_shutdown_locked(grpc_exec_ctx* exec_ctx, + grpc_pollset* pollset) { /* The pollset cannot have any workers if we are at this stage */ GPR_ASSERT(!pollset_has_workers(pollset)); @@ -1143,8 +1147,8 @@ static void finish_shutdown_locked(grpc_exec_ctx *exec_ctx, } /* pollset->po.mu lock must be held by the caller before calling this */ -static void pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_closure *closure) { +static void pollset_shutdown(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_closure* closure) { GPR_TIMER_BEGIN("pollset_shutdown", 0); GPR_ASSERT(!pollset->shutting_down); pollset->shutting_down = true; @@ -1165,23 +1169,23 @@ static void pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, /* pollset_shutdown is guaranteed to be called before pollset_destroy. So other * than destroying the mutexes, there is nothing special that needs to be done * here */ -static void pollset_destroy(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset) { +static void pollset_destroy(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset) { GPR_ASSERT(!pollset_has_workers(pollset)); gpr_mu_destroy(&pollset->po.mu); } #define GRPC_EPOLL_MAX_EVENTS 100 /* Note: sig_mask contains the signal mask to use *during* epoll_wait() */ -static void pollset_work_and_unlock(grpc_exec_ctx *exec_ctx, - grpc_pollset *pollset, - grpc_pollset_worker *worker, int timeout_ms, - sigset_t *sig_mask, grpc_error **error) { +static void pollset_work_and_unlock(grpc_exec_ctx* exec_ctx, + grpc_pollset* pollset, + grpc_pollset_worker* worker, int timeout_ms, + sigset_t* sig_mask, grpc_error** error) { struct epoll_event ep_ev[GRPC_EPOLL_MAX_EVENTS]; int epoll_fd = -1; int ep_rv; - polling_island *pi = NULL; - char *err_msg; - const char *err_desc = "pollset_work_and_unlock"; + polling_island* pi = nullptr; + char* err_msg; + const char* err_desc = "pollset_work_and_unlock"; GPR_TIMER_BEGIN("pollset_work_and_unlock", 0); /* We need to get the epoll_fd to wait on. The epoll_fd is in inside the @@ -1194,16 +1198,16 @@ static void pollset_work_and_unlock(grpc_exec_ctx *exec_ctx, right-away from epoll_wait() and pick up the latest polling_island the next this function (i.e pollset_work_and_unlock()) is called */ - if (pollset->po.pi == NULL) { - pollset->po.pi = polling_island_create(exec_ctx, NULL, error); - if (pollset->po.pi == NULL) { + if (pollset->po.pi == nullptr) { + pollset->po.pi = polling_island_create(exec_ctx, nullptr, error); + if (pollset->po.pi == nullptr) { GPR_TIMER_END("pollset_work_and_unlock", 0); return; /* Fatal error. We cannot continue */ } PI_ADD_REF(pollset->po.pi, "ps"); GRPC_POLLING_TRACE("pollset_work: pollset: %p created new pi: %p", - (void *)pollset, (void *)pollset->po.pi); + (void*)pollset, (void*)pollset->po.pi); } pi = polling_island_maybe_get_latest(pollset->po.pi); @@ -1243,7 +1247,7 @@ static void pollset_work_and_unlock(grpc_exec_ctx *exec_ctx, /* We were interrupted. Save an interation by doing a zero timeout epoll_wait to see if there are any other events of interest */ GRPC_POLLING_TRACE("pollset_work: pollset: %p, worker: %p received kick", - (void *)pollset, (void *)worker); + (void*)pollset, (void*)worker); ep_rv = epoll_wait(epoll_fd, ep_ev, GRPC_EPOLL_MAX_EVENTS, 0); } } @@ -1254,18 +1258,18 @@ static void pollset_work_and_unlock(grpc_exec_ctx *exec_ctx, #endif /* defined(GRPC_TSAN) */ for (int i = 0; i < ep_rv; ++i) { - void *data_ptr = ep_ev[i].data.ptr; + void* data_ptr = ep_ev[i].data.ptr; if (data_ptr == &polling_island_wakeup_fd) { GRPC_POLLING_TRACE( "pollset_work: pollset: %p, worker: %p polling island (epoll_fd: " "%d) got merged", - (void *)pollset, (void *)worker, epoll_fd); + (void*)pollset, (void*)worker, epoll_fd); /* This means that our polling island is merged with a different island. We do not have to do anything here since the subsequent call to the function pollset_work_and_unlock() will pick up the correct epoll_fd */ } else { - grpc_fd *fd = (grpc_fd *)data_ptr; + grpc_fd* fd = (grpc_fd*)data_ptr; int cancel = ep_ev[i].events & (EPOLLERR | EPOLLHUP); int read_ev = ep_ev[i].events & (EPOLLIN | EPOLLPRI); int write_ev = ep_ev[i].events & EPOLLOUT; @@ -1278,10 +1282,10 @@ static void pollset_work_and_unlock(grpc_exec_ctx *exec_ctx, } } - g_current_thread_polling_island = NULL; + g_current_thread_polling_island = nullptr; gpr_atm_no_barrier_fetch_add(&pi->poller_count, -1); - GPR_ASSERT(pi != NULL); + GPR_ASSERT(pi != nullptr); /* Before leaving, release the extra ref we added to the polling island. It is important to use "pi" here (i.e our old copy of pollset->po.pi @@ -1297,17 +1301,17 @@ static void pollset_work_and_unlock(grpc_exec_ctx *exec_ctx, The function pollset_work() may temporarily release the lock (pollset->po.mu) during the course of its execution but it will always re-acquire the lock and ensure that it is held by the time the function returns */ -static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker **worker_hdl, +static grpc_error* pollset_work(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker** worker_hdl, grpc_millis deadline) { GPR_TIMER_BEGIN("pollset_work", 0); - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; int timeout_ms = poll_deadline_to_millis_timeout(exec_ctx, deadline); sigset_t new_mask; grpc_pollset_worker worker; - worker.next = worker.prev = NULL; + worker.next = worker.prev = nullptr; worker.pt_id = pthread_self(); gpr_atm_no_barrier_store(&worker.is_kicked, (gpr_atm)0); @@ -1389,7 +1393,7 @@ static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, gpr_mu_lock(&pollset->po.mu); } - if (worker_hdl) *worker_hdl = NULL; + if (worker_hdl) *worker_hdl = nullptr; gpr_tls_set(&g_current_thread_pollset, (intptr_t)0); gpr_tls_set(&g_current_thread_worker, (intptr_t)0); @@ -1400,8 +1404,8 @@ static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, return error; } -static void add_poll_object(grpc_exec_ctx *exec_ctx, poll_obj *bag, - poll_obj_type bag_type, poll_obj *item, +static void add_poll_object(grpc_exec_ctx* exec_ctx, poll_obj* bag, + poll_obj_type bag_type, poll_obj* item, poll_obj_type item_type) { GPR_TIMER_BEGIN("add_poll_object", 0); @@ -1410,8 +1414,8 @@ static void add_poll_object(grpc_exec_ctx *exec_ctx, poll_obj *bag, GPR_ASSERT(bag->obj_type == bag_type); #endif - grpc_error *error = GRPC_ERROR_NONE; - polling_island *pi_new = NULL; + grpc_error* error = GRPC_ERROR_NONE; + polling_island* pi_new = nullptr; gpr_mu_lock(&bag->mu); gpr_mu_lock(&item->mu); @@ -1438,7 +1442,7 @@ retry: if (item->pi == bag->pi) { pi_new = item->pi; - if (pi_new == NULL) { + if (pi_new == nullptr) { /* GPR_ASSERT(item->pi == bag->pi == NULL) */ /* If we are adding an fd to a bag (i.e pollset or pollset_set), then @@ -1458,12 +1462,12 @@ retry: /* Need to reverify any assumptions made between the initial lock and getting to this branch: if they've changed, we need to throw away our work and figure things out again. */ - if (item->pi != NULL) { + if (item->pi != nullptr) { GRPC_POLLING_TRACE( "add_poll_object: Raced creating new polling island. pi_new: %p " "(fd: %d, %s: %p)", - (void *)pi_new, FD_FROM_PO(item)->fd, poll_obj_string(bag_type), - (void *)bag); + (void*)pi_new, FD_FROM_PO(item)->fd, poll_obj_string(bag_type), + (void*)bag); /* No need to lock 'pi_new' here since this is a new polling island and no one has a reference to it yet */ polling_island_remove_all_fds_locked(pi_new, true, &error); @@ -1475,27 +1479,26 @@ retry: goto retry; } } else { - pi_new = polling_island_create(exec_ctx, NULL, &error); + pi_new = polling_island_create(exec_ctx, nullptr, &error); } GRPC_POLLING_TRACE( "add_poll_object: Created new polling island. pi_new: %p (%s: %p, " "%s: %p)", - (void *)pi_new, poll_obj_string(item_type), (void *)item, - poll_obj_string(bag_type), (void *)bag); + (void*)pi_new, poll_obj_string(item_type), (void*)item, + poll_obj_string(bag_type), (void*)bag); } else { GRPC_POLLING_TRACE( "add_poll_object: Same polling island. pi: %p (%s, %s)", - (void *)pi_new, poll_obj_string(item_type), - poll_obj_string(bag_type)); + (void*)pi_new, poll_obj_string(item_type), poll_obj_string(bag_type)); } - } else if (item->pi == NULL) { + } else if (item->pi == nullptr) { /* GPR_ASSERT(bag->pi != NULL) */ /* Make pi_new point to latest pi*/ pi_new = polling_island_lock(bag->pi); if (item_type == POLL_OBJ_FD) { - grpc_fd *fd = FD_FROM_PO(item); + grpc_fd* fd = FD_FROM_PO(item); polling_island_add_fds_locked(pi_new, &fd, 1, true, &error); } @@ -1503,9 +1506,9 @@ retry: GRPC_POLLING_TRACE( "add_poll_obj: item->pi was NULL. pi_new: %p (item(%s): %p, " "bag(%s): %p)", - (void *)pi_new, poll_obj_string(item_type), (void *)item, - poll_obj_string(bag_type), (void *)bag); - } else if (bag->pi == NULL) { + (void*)pi_new, poll_obj_string(item_type), (void*)item, + poll_obj_string(bag_type), (void*)bag); + } else if (bag->pi == nullptr) { /* GPR_ASSERT(item->pi != NULL) */ /* Make pi_new to point to latest pi */ pi_new = polling_island_lock(item->pi); @@ -1513,15 +1516,15 @@ retry: GRPC_POLLING_TRACE( "add_poll_obj: bag->pi was NULL. pi_new: %p (item(%s): %p, " "bag(%s): %p)", - (void *)pi_new, poll_obj_string(item_type), (void *)item, - poll_obj_string(bag_type), (void *)bag); + (void*)pi_new, poll_obj_string(item_type), (void*)item, + poll_obj_string(bag_type), (void*)bag); } else { pi_new = polling_island_merge(item->pi, bag->pi, &error); GRPC_POLLING_TRACE( "add_poll_obj: polling islands merged. pi_new: %p (item(%s): %p, " "bag(%s): %p)", - (void *)pi_new, poll_obj_string(item_type), (void *)item, - poll_obj_string(bag_type), (void *)bag); + (void*)pi_new, poll_obj_string(item_type), (void*)item, + poll_obj_string(bag_type), (void*)bag); } /* At this point, pi_new is the polling island that both item->pi and bag->pi @@ -1529,7 +1532,7 @@ retry: if (item->pi != pi_new) { PI_ADD_REF(pi_new, poll_obj_string(item_type)); - if (item->pi != NULL) { + if (item->pi != nullptr) { PI_UNREF(exec_ctx, item->pi, poll_obj_string(item_type)); } item->pi = pi_new; @@ -1537,7 +1540,7 @@ retry: if (bag->pi != pi_new) { PI_ADD_REF(pi_new, poll_obj_string(bag_type)); - if (bag->pi != NULL) { + if (bag->pi != nullptr) { PI_UNREF(exec_ctx, bag->pi, poll_obj_string(bag_type)); } bag->pi = pi_new; @@ -1550,8 +1553,8 @@ retry: GPR_TIMER_END("add_poll_object", 0); } -static void pollset_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_fd *fd) { +static void pollset_add_fd(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_fd* fd) { add_poll_object(exec_ctx, &pollset->po, POLL_OBJ_POLLSET, &fd->po, POLL_OBJ_FD); } @@ -1560,66 +1563,66 @@ static void pollset_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, * Pollset-set Definitions */ -static grpc_pollset_set *pollset_set_create(void) { - grpc_pollset_set *pss = (grpc_pollset_set *)gpr_malloc(sizeof(*pss)); +static grpc_pollset_set* pollset_set_create(void) { + grpc_pollset_set* pss = (grpc_pollset_set*)gpr_malloc(sizeof(*pss)); gpr_mu_init(&pss->po.mu); - pss->po.pi = NULL; + pss->po.pi = nullptr; #ifndef NDEBUG pss->po.obj_type = POLL_OBJ_POLLSET_SET; #endif return pss; } -static void pollset_set_destroy(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pss) { +static void pollset_set_destroy(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pss) { gpr_mu_destroy(&pss->po.mu); - if (pss->po.pi != NULL) { + if (pss->po.pi != nullptr) { PI_UNREF(exec_ctx, pss->po.pi, "pss_destroy"); } gpr_free(pss); } -static void pollset_set_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset_set *pss, - grpc_fd *fd) { +static void pollset_set_add_fd(grpc_exec_ctx* exec_ctx, grpc_pollset_set* pss, + grpc_fd* fd) { add_poll_object(exec_ctx, &pss->po, POLL_OBJ_POLLSET_SET, &fd->po, POLL_OBJ_FD); } -static void pollset_set_del_fd(grpc_exec_ctx *exec_ctx, grpc_pollset_set *pss, - grpc_fd *fd) { +static void pollset_set_del_fd(grpc_exec_ctx* exec_ctx, grpc_pollset_set* pss, + grpc_fd* fd) { /* Nothing to do */ } -static void pollset_set_add_pollset(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pss, grpc_pollset *ps) { +static void pollset_set_add_pollset(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pss, grpc_pollset* ps) { add_poll_object(exec_ctx, &pss->po, POLL_OBJ_POLLSET_SET, &ps->po, POLL_OBJ_POLLSET); } -static void pollset_set_del_pollset(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pss, grpc_pollset *ps) { +static void pollset_set_del_pollset(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pss, grpc_pollset* ps) { /* Nothing to do */ } -static void pollset_set_add_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *bag, - grpc_pollset_set *item) { +static void pollset_set_add_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* bag, + grpc_pollset_set* item) { add_poll_object(exec_ctx, &bag->po, POLL_OBJ_POLLSET_SET, &item->po, POLL_OBJ_POLLSET_SET); } -static void pollset_set_del_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *bag, - grpc_pollset_set *item) { +static void pollset_set_del_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* bag, + grpc_pollset_set* item) { /* Nothing to do */ } /* Test helper functions * */ -void *grpc_fd_get_polling_island(grpc_fd *fd) { - polling_island *pi; +void* grpc_fd_get_polling_island(grpc_fd* fd) { + polling_island* pi; gpr_mu_lock(&fd->po.mu); pi = fd->po.pi; @@ -1628,8 +1631,8 @@ void *grpc_fd_get_polling_island(grpc_fd *fd) { return pi; } -void *grpc_pollset_get_polling_island(grpc_pollset *ps) { - polling_island *pi; +void* grpc_pollset_get_polling_island(grpc_pollset* ps) { + polling_island* pi; gpr_mu_lock(&ps->po.mu); pi = ps->po.pi; @@ -1638,9 +1641,9 @@ void *grpc_pollset_get_polling_island(grpc_pollset *ps) { return pi; } -bool grpc_are_polling_islands_equal(void *p, void *q) { - polling_island *p1 = (polling_island *)p; - polling_island *p2 = (polling_island *)q; +bool grpc_are_polling_islands_equal(void* p, void* q) { + polling_island* p1 = (polling_island*)p; + polling_island* p2 = (polling_island*)q; /* Note: polling_island_lock_pair() may change p1 and p2 to point to the latest polling islands in their respective linked lists */ @@ -1706,38 +1709,43 @@ static bool is_epoll_available() { return true; } -const grpc_event_engine_vtable *grpc_init_epollsig_linux( +const grpc_event_engine_vtable* grpc_init_epollsig_linux( bool explicit_request) { /* If use of signals is disabled, we cannot use epoll engine*/ if (is_grpc_wakeup_signal_initialized && grpc_wakeup_signal < 0) { - return NULL; + gpr_log(GPR_ERROR, "Skipping epollsig because use of signals is disabled."); + return nullptr; } if (!grpc_has_wakeup_fd()) { - return NULL; + gpr_log(GPR_ERROR, "Skipping epollsig because of no wakeup fd."); + return nullptr; } if (!is_epoll_available()) { - return NULL; + gpr_log(GPR_ERROR, "Skipping epollsig because epoll is unavailable."); + return nullptr; } if (!is_grpc_wakeup_signal_initialized) { if (explicit_request) { grpc_use_signal(SIGRTMIN + 6); } else { - return NULL; + gpr_log(GPR_ERROR, + "Skipping epollsig because uninitialized wakeup signal."); + return nullptr; } } fd_global_init(); if (!GRPC_LOG_IF_ERROR("pollset_global_init", pollset_global_init())) { - return NULL; + return nullptr; } if (!GRPC_LOG_IF_ERROR("polling_island_global_init", polling_island_global_init())) { - return NULL; + return nullptr; } return &vtable; @@ -1748,8 +1756,10 @@ const grpc_event_engine_vtable *grpc_init_epollsig_linux( #include "src/core/lib/iomgr/ev_epollsig_linux.h" /* If GRPC_LINUX_EPOLL is not defined, it means epoll is not available. Return * NULL */ -const grpc_event_engine_vtable *grpc_init_epollsig_linux( +const grpc_event_engine_vtable* grpc_init_epollsig_linux( bool explicit_request) { + gpr_log(GPR_ERROR, + "Skipping epollsig becuase GRPC_LINUX_EPOLL is not defined."); return NULL; } #endif /* defined(GRPC_POSIX_SOCKET) */ diff --git a/src/core/lib/iomgr/ev_epollsig_linux.h b/src/core/lib/iomgr/ev_epollsig_linux.h index c04ff27400b..5b8aba9d9f9 100644 --- a/src/core/lib/iomgr/ev_epollsig_linux.h +++ b/src/core/lib/iomgr/ev_epollsig_linux.h @@ -22,20 +22,12 @@ #include "src/core/lib/iomgr/ev_posix.h" #include "src/core/lib/iomgr/port.h" -#ifdef __cplusplus -extern "C" { -#endif - -const grpc_event_engine_vtable *grpc_init_epollsig_linux(bool explicit_request); +const grpc_event_engine_vtable* grpc_init_epollsig_linux(bool explicit_request); #ifdef GRPC_LINUX_EPOLL -void *grpc_fd_get_polling_island(grpc_fd *fd); -void *grpc_pollset_get_polling_island(grpc_pollset *ps); -bool grpc_are_polling_islands_equal(void *p, void *q); +void* grpc_fd_get_polling_island(grpc_fd* fd); +void* grpc_pollset_get_polling_island(grpc_pollset* ps); +bool grpc_are_polling_islands_equal(void* p, void* q); #endif /* defined(GRPC_LINUX_EPOLL) */ -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_EV_EPOLLSIG_LINUX_H */ diff --git a/src/core/lib/iomgr/ev_poll_posix.cc b/src/core/lib/iomgr/ev_poll_posix.cc index 036a35690c5..8659559f78a 100644 --- a/src/core/lib/iomgr/ev_poll_posix.cc +++ b/src/core/lib/iomgr/ev_poll_posix.cc @@ -45,17 +45,17 @@ #include "src/core/lib/profiling/timers.h" #include "src/core/lib/support/murmur_hash.h" -#define GRPC_POLLSET_KICK_BROADCAST ((grpc_pollset_worker *)1) +#define GRPC_POLLSET_KICK_BROADCAST ((grpc_pollset_worker*)1) /******************************************************************************* * FD declarations */ typedef struct grpc_fd_watcher { - struct grpc_fd_watcher *next; - struct grpc_fd_watcher *prev; - grpc_pollset *pollset; - grpc_pollset_worker *worker; - grpc_fd *fd; + struct grpc_fd_watcher* next; + struct grpc_fd_watcher* prev; + grpc_pollset* pollset; + grpc_pollset_worker* worker; + grpc_fd* fd; } grpc_fd_watcher; struct grpc_fd { @@ -71,7 +71,7 @@ struct grpc_fd { int shutdown; int closed; int released; - grpc_error *shutdown_error; + grpc_error* shutdown_error; /* The watcher list. @@ -96,18 +96,18 @@ struct grpc_fd { the inactive pollers may be kicked out of their poll loops to take that responsibility. */ grpc_fd_watcher inactive_watcher_root; - grpc_fd_watcher *read_watcher; - grpc_fd_watcher *write_watcher; + grpc_fd_watcher* read_watcher; + grpc_fd_watcher* write_watcher; - grpc_closure *read_closure; - grpc_closure *write_closure; + grpc_closure* read_closure; + grpc_closure* write_closure; - grpc_closure *on_done_closure; + grpc_closure* on_done_closure; grpc_iomgr_object iomgr_object; /* The pollset that last noticed and notified that the fd is readable */ - grpc_pollset *read_notifier_pollset; + grpc_pollset* read_notifier_pollset; }; /* Begin polling on an fd. @@ -121,35 +121,35 @@ struct grpc_fd { Polling strategies that do not need to alter their behavior depending on the fd's current interest (such as epoll) do not need to call this function. MUST NOT be called with a pollset lock taken */ -static uint32_t fd_begin_poll(grpc_fd *fd, grpc_pollset *pollset, - grpc_pollset_worker *worker, uint32_t read_mask, - uint32_t write_mask, grpc_fd_watcher *rec); +static uint32_t fd_begin_poll(grpc_fd* fd, grpc_pollset* pollset, + grpc_pollset_worker* worker, uint32_t read_mask, + uint32_t write_mask, grpc_fd_watcher* rec); /* Complete polling previously started with fd_begin_poll MUST NOT be called with a pollset lock taken if got_read or got_write are 1, also does the become_{readable,writable} as appropriate. */ -static void fd_end_poll(grpc_exec_ctx *exec_ctx, grpc_fd_watcher *rec, +static void fd_end_poll(grpc_exec_ctx* exec_ctx, grpc_fd_watcher* rec, int got_read, int got_write, - grpc_pollset *read_notifier_pollset); + grpc_pollset* read_notifier_pollset); /* Return 1 if this fd is orphaned, 0 otherwise */ -static bool fd_is_orphaned(grpc_fd *fd); +static bool fd_is_orphaned(grpc_fd* fd); #ifndef NDEBUG -static void fd_ref(grpc_fd *fd, const char *reason, const char *file, int line); -static void fd_unref(grpc_fd *fd, const char *reason, const char *file, +static void fd_ref(grpc_fd* fd, const char* reason, const char* file, int line); +static void fd_unref(grpc_fd* fd, const char* reason, const char* file, int line); #define GRPC_FD_REF(fd, reason) fd_ref(fd, reason, __FILE__, __LINE__) #define GRPC_FD_UNREF(fd, reason) fd_unref(fd, reason, __FILE__, __LINE__) #else -static void fd_ref(grpc_fd *fd); -static void fd_unref(grpc_fd *fd); +static void fd_ref(grpc_fd* fd); +static void fd_unref(grpc_fd* fd); #define GRPC_FD_REF(fd, reason) fd_ref(fd) #define GRPC_FD_UNREF(fd, reason) fd_unref(fd) #endif -#define CLOSURE_NOT_READY ((grpc_closure *)0) -#define CLOSURE_READY ((grpc_closure *)1) +#define CLOSURE_NOT_READY ((grpc_closure*)0) +#define CLOSURE_READY ((grpc_closure*)1) /******************************************************************************* * pollset declarations @@ -157,15 +157,15 @@ static void fd_unref(grpc_fd *fd); typedef struct grpc_cached_wakeup_fd { grpc_wakeup_fd fd; - struct grpc_cached_wakeup_fd *next; + struct grpc_cached_wakeup_fd* next; } grpc_cached_wakeup_fd; struct grpc_pollset_worker { - grpc_cached_wakeup_fd *wakeup_fd; + grpc_cached_wakeup_fd* wakeup_fd; int reevaluate_polling_on_wakeup; int kicked_specifically; - struct grpc_pollset_worker *next; - struct grpc_pollset_worker *prev; + struct grpc_pollset_worker* next; + struct grpc_pollset_worker* prev; }; struct grpc_pollset { @@ -174,23 +174,23 @@ struct grpc_pollset { int shutting_down; int called_shutdown; int kicked_without_pollers; - grpc_closure *shutdown_done; + grpc_closure* shutdown_done; grpc_closure_list idle_jobs; int pollset_set_count; /* all polled fds */ size_t fd_count; size_t fd_capacity; - grpc_fd **fds; + grpc_fd** fds; /* Local cache of eventfds for workers */ - grpc_cached_wakeup_fd *local_wakeup_cache; + grpc_cached_wakeup_fd* local_wakeup_cache; }; /* Add an fd to a pollset */ -static void pollset_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - struct grpc_fd *fd); +static void pollset_add_fd(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + struct grpc_fd* fd); -static void pollset_set_add_fd(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, grpc_fd *fd); +static void pollset_set_add_fd(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, grpc_fd* fd); /* Convert a timespec to milliseconds: - very small or negative poll times are clamped to zero to do a @@ -199,7 +199,7 @@ static void pollset_set_add_fd(grpc_exec_ctx *exec_ctx, - longer than a millisecond polls are rounded up to the next nearest millisecond to avoid spinning - infinite timeouts are converted to -1 */ -static int poll_deadline_to_millis_timeout(grpc_exec_ctx *exec_ctx, +static int poll_deadline_to_millis_timeout(grpc_exec_ctx* exec_ctx, grpc_millis deadline); /* Allow kick to wakeup the currently polling worker */ @@ -208,13 +208,13 @@ static int poll_deadline_to_millis_timeout(grpc_exec_ctx *exec_ctx, #define GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP 2 /* As per pollset_kick, with an extended set of flags (defined above) -- mostly for fd_posix's use. */ -static grpc_error *pollset_kick_ext(grpc_exec_ctx *exec_ctx, grpc_pollset *p, - grpc_pollset_worker *specific_worker, +static grpc_error* pollset_kick_ext(grpc_exec_ctx* exec_ctx, grpc_pollset* p, + grpc_pollset_worker* specific_worker, uint32_t flags) GRPC_MUST_USE_RESULT; /* Return 1 if the pollset has active threads in pollset_work (pollset must * be locked) */ -static bool pollset_has_workers(grpc_pollset *pollset); +static bool pollset_has_workers(grpc_pollset* pollset); /******************************************************************************* * pollset_set definitions @@ -225,15 +225,15 @@ struct grpc_pollset_set { size_t pollset_count; size_t pollset_capacity; - grpc_pollset **pollsets; + grpc_pollset** pollsets; size_t pollset_set_count; size_t pollset_set_capacity; - struct grpc_pollset_set **pollset_sets; + struct grpc_pollset_set** pollset_sets; size_t fd_count; size_t fd_capacity; - grpc_fd **fds; + grpc_fd** fds; }; /******************************************************************************* @@ -246,9 +246,9 @@ struct grpc_pollset_set { typedef struct poll_result { gpr_refcount refcount; - cv_node *watchers; + cv_node* watchers; int watchcount; - struct pollfd *fds; + struct pollfd* fds; nfds_t nfds; int retval; int err; @@ -258,11 +258,11 @@ typedef struct poll_result { typedef struct poll_args { gpr_cv trigger; int trigger_set; - struct pollfd *fds; + struct pollfd* fds; nfds_t nfds; - poll_result *result; - struct poll_args *next; - struct poll_args *prev; + poll_result* result; + struct poll_args* next; + struct poll_args* prev; } poll_args; // This is a 2-tiered cache, we mantain a hash table @@ -270,8 +270,8 @@ typedef struct poll_args { // of that call. We also maintain a freelist of inactive // poll threads. typedef struct poll_hash_table { - poll_args *free_pollers; - poll_args **active_pollers; + poll_args* free_pollers; + poll_args** active_pollers; unsigned int size; unsigned int count; } poll_hash_table; @@ -286,9 +286,9 @@ cv_fd_table g_cvfds; #ifndef NDEBUG #define REF_BY(fd, n, reason) ref_by(fd, n, reason, __FILE__, __LINE__) #define UNREF_BY(fd, n, reason) unref_by(fd, n, reason, __FILE__, __LINE__) -static void ref_by(grpc_fd *fd, int n, const char *reason, const char *file, +static void ref_by(grpc_fd* fd, int n, const char* reason, const char* file, int line) { - if (GRPC_TRACER_ON(grpc_trace_fd_refcount)) { + if (grpc_trace_fd_refcount.enabled()) { gpr_log(GPR_DEBUG, "FD %d %p ref %d %" PRIdPTR " -> %" PRIdPTR " [%s; %s:%d]", fd->fd, fd, n, gpr_atm_no_barrier_load(&fd->refst), @@ -297,22 +297,22 @@ static void ref_by(grpc_fd *fd, int n, const char *reason, const char *file, #else #define REF_BY(fd, n, reason) ref_by(fd, n) #define UNREF_BY(fd, n, reason) unref_by(fd, n) -static void ref_by(grpc_fd *fd, int n) { +static void ref_by(grpc_fd* fd, int n) { #endif GPR_ASSERT(gpr_atm_no_barrier_fetch_add(&fd->refst, n) > 0); } #ifndef NDEBUG -static void unref_by(grpc_fd *fd, int n, const char *reason, const char *file, +static void unref_by(grpc_fd* fd, int n, const char* reason, const char* file, int line) { - if (GRPC_TRACER_ON(grpc_trace_fd_refcount)) { + if (grpc_trace_fd_refcount.enabled()) { gpr_log(GPR_DEBUG, "FD %d %p unref %d %" PRIdPTR " -> %" PRIdPTR " [%s; %s:%d]", fd->fd, fd, n, gpr_atm_no_barrier_load(&fd->refst), gpr_atm_no_barrier_load(&fd->refst) - n, reason, file, line); } #else -static void unref_by(grpc_fd *fd, int n) { +static void unref_by(grpc_fd* fd, int n) { #endif gpr_atm old = gpr_atm_full_fetch_add(&fd->refst, -n); if (old == n) { @@ -325,8 +325,8 @@ static void unref_by(grpc_fd *fd, int n) { } } -static grpc_fd *fd_create(int fd, const char *name) { - grpc_fd *r = (grpc_fd *)gpr_malloc(sizeof(*r)); +static grpc_fd* fd_create(int fd, const char* name) { + grpc_fd* r = (grpc_fd*)gpr_malloc(sizeof(*r)); gpr_mu_init(&r->mu); gpr_atm_rel_store(&r->refst, 1); r->shutdown = 0; @@ -335,27 +335,27 @@ static grpc_fd *fd_create(int fd, const char *name) { r->fd = fd; r->inactive_watcher_root.next = r->inactive_watcher_root.prev = &r->inactive_watcher_root; - r->read_watcher = r->write_watcher = NULL; - r->on_done_closure = NULL; + r->read_watcher = r->write_watcher = nullptr; + r->on_done_closure = nullptr; r->closed = 0; r->released = 0; - r->read_notifier_pollset = NULL; + r->read_notifier_pollset = nullptr; - char *name2; + char* name2; gpr_asprintf(&name2, "%s fd=%d", name, fd); grpc_iomgr_register_object(&r->iomgr_object, name2); gpr_free(name2); return r; } -static bool fd_is_orphaned(grpc_fd *fd) { +static bool fd_is_orphaned(grpc_fd* fd) { return (gpr_atm_acq_load(&fd->refst) & 1) == 0; } /* Return the read-notifier pollset */ -static grpc_pollset *fd_get_read_notifier_pollset(grpc_exec_ctx *exec_ctx, - grpc_fd *fd) { - grpc_pollset *notifier = NULL; +static grpc_pollset* fd_get_read_notifier_pollset(grpc_exec_ctx* exec_ctx, + grpc_fd* fd) { + grpc_pollset* notifier = nullptr; gpr_mu_lock(&fd->mu); notifier = fd->read_notifier_pollset; @@ -364,19 +364,19 @@ static grpc_pollset *fd_get_read_notifier_pollset(grpc_exec_ctx *exec_ctx, return notifier; } -static grpc_error *pollset_kick_locked(grpc_exec_ctx *exec_ctx, - grpc_fd_watcher *watcher) { +static grpc_error* pollset_kick_locked(grpc_exec_ctx* exec_ctx, + grpc_fd_watcher* watcher) { gpr_mu_lock(&watcher->pollset->mu); GPR_ASSERT(watcher->worker); - grpc_error *err = + grpc_error* err = pollset_kick_ext(exec_ctx, watcher->pollset, watcher->worker, GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP); gpr_mu_unlock(&watcher->pollset->mu); return err; } -static void maybe_wake_one_watcher_locked(grpc_exec_ctx *exec_ctx, - grpc_fd *fd) { +static void maybe_wake_one_watcher_locked(grpc_exec_ctx* exec_ctx, + grpc_fd* fd) { if (fd->inactive_watcher_root.next != &fd->inactive_watcher_root) { pollset_kick_locked(exec_ctx, fd->inactive_watcher_root.next); } else if (fd->read_watcher) { @@ -386,8 +386,8 @@ static void maybe_wake_one_watcher_locked(grpc_exec_ctx *exec_ctx, } } -static void wake_all_watchers_locked(grpc_exec_ctx *exec_ctx, grpc_fd *fd) { - grpc_fd_watcher *watcher; +static void wake_all_watchers_locked(grpc_exec_ctx* exec_ctx, grpc_fd* fd) { + grpc_fd_watcher* watcher; for (watcher = fd->inactive_watcher_root.next; watcher != &fd->inactive_watcher_root; watcher = watcher->next) { pollset_kick_locked(exec_ctx, watcher); @@ -400,12 +400,12 @@ static void wake_all_watchers_locked(grpc_exec_ctx *exec_ctx, grpc_fd *fd) { } } -static int has_watchers(grpc_fd *fd) { - return fd->read_watcher != NULL || fd->write_watcher != NULL || +static int has_watchers(grpc_fd* fd) { + return fd->read_watcher != nullptr || fd->write_watcher != nullptr || fd->inactive_watcher_root.next != &fd->inactive_watcher_root; } -static void close_fd_locked(grpc_exec_ctx *exec_ctx, grpc_fd *fd) { +static void close_fd_locked(grpc_exec_ctx* exec_ctx, grpc_fd* fd) { fd->closed = 1; if (!fd->released) { close(fd->fd); @@ -413,7 +413,7 @@ static void close_fd_locked(grpc_exec_ctx *exec_ctx, grpc_fd *fd) { GRPC_CLOSURE_SCHED(exec_ctx, fd->on_done_closure, GRPC_ERROR_NONE); } -static int fd_wrapped_fd(grpc_fd *fd) { +static int fd_wrapped_fd(grpc_fd* fd) { if (fd->released || fd->closed) { return -1; } else { @@ -421,12 +421,12 @@ static int fd_wrapped_fd(grpc_fd *fd) { } } -static void fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *on_done, int *release_fd, - bool already_closed, const char *reason) { +static void fd_orphan(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* on_done, int* release_fd, + bool already_closed, const char* reason) { fd->on_done_closure = on_done; - fd->released = release_fd != NULL; - if (release_fd != NULL) { + fd->released = release_fd != nullptr; + if (release_fd != nullptr) { *release_fd = fd->fd; fd->released = true; } else if (already_closed) { @@ -445,22 +445,22 @@ static void fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd, /* increment refcount by two to avoid changing the orphan bit */ #ifndef NDEBUG -static void fd_ref(grpc_fd *fd, const char *reason, const char *file, +static void fd_ref(grpc_fd* fd, const char* reason, const char* file, int line) { ref_by(fd, 2, reason, file, line); } -static void fd_unref(grpc_fd *fd, const char *reason, const char *file, +static void fd_unref(grpc_fd* fd, const char* reason, const char* file, int line) { unref_by(fd, 2, reason, file, line); } #else -static void fd_ref(grpc_fd *fd) { ref_by(fd, 2); } +static void fd_ref(grpc_fd* fd) { ref_by(fd, 2); } -static void fd_unref(grpc_fd *fd) { unref_by(fd, 2); } +static void fd_unref(grpc_fd* fd) { unref_by(fd, 2); } #endif -static grpc_error *fd_shutdown_error(grpc_fd *fd) { +static grpc_error* fd_shutdown_error(grpc_fd* fd) { if (!fd->shutdown) { return GRPC_ERROR_NONE; } else { @@ -469,8 +469,8 @@ static grpc_error *fd_shutdown_error(grpc_fd *fd) { } } -static void notify_on_locked(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure **st, grpc_closure *closure) { +static void notify_on_locked(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure** st, grpc_closure* closure) { if (fd->shutdown) { GRPC_CLOSURE_SCHED(exec_ctx, closure, GRPC_ERROR_CREATE_FROM_STATIC_STRING("FD shutdown")); @@ -492,8 +492,8 @@ static void notify_on_locked(grpc_exec_ctx *exec_ctx, grpc_fd *fd, } /* returns 1 if state becomes not ready */ -static int set_ready_locked(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure **st) { +static int set_ready_locked(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure** st) { if (*st == CLOSURE_READY) { /* duplicate ready ==> ignore */ return 0; @@ -510,11 +510,11 @@ static int set_ready_locked(grpc_exec_ctx *exec_ctx, grpc_fd *fd, } static void set_read_notifier_pollset_locked( - grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_pollset *read_notifier_pollset) { + grpc_exec_ctx* exec_ctx, grpc_fd* fd, grpc_pollset* read_notifier_pollset) { fd->read_notifier_pollset = read_notifier_pollset; } -static void fd_shutdown(grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_error *why) { +static void fd_shutdown(grpc_exec_ctx* exec_ctx, grpc_fd* fd, grpc_error* why) { gpr_mu_lock(&fd->mu); /* only shutdown once */ if (!fd->shutdown) { @@ -530,32 +530,32 @@ static void fd_shutdown(grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_error *why) { gpr_mu_unlock(&fd->mu); } -static bool fd_is_shutdown(grpc_fd *fd) { +static bool fd_is_shutdown(grpc_fd* fd) { gpr_mu_lock(&fd->mu); bool r = fd->shutdown; gpr_mu_unlock(&fd->mu); return r; } -static void fd_notify_on_read(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *closure) { +static void fd_notify_on_read(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* closure) { gpr_mu_lock(&fd->mu); notify_on_locked(exec_ctx, fd, &fd->read_closure, closure); gpr_mu_unlock(&fd->mu); } -static void fd_notify_on_write(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *closure) { +static void fd_notify_on_write(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* closure) { gpr_mu_lock(&fd->mu); notify_on_locked(exec_ctx, fd, &fd->write_closure, closure); gpr_mu_unlock(&fd->mu); } -static uint32_t fd_begin_poll(grpc_fd *fd, grpc_pollset *pollset, - grpc_pollset_worker *worker, uint32_t read_mask, - uint32_t write_mask, grpc_fd_watcher *watcher) { +static uint32_t fd_begin_poll(grpc_fd* fd, grpc_pollset* pollset, + grpc_pollset_worker* worker, uint32_t read_mask, + uint32_t write_mask, grpc_fd_watcher* watcher) { uint32_t mask = 0; - grpc_closure *cur; + grpc_closure* cur; int requested; /* keep track of pollers that have requested our events, in case they change */ @@ -565,9 +565,9 @@ static uint32_t fd_begin_poll(grpc_fd *fd, grpc_pollset *pollset, /* if we are shutdown, then don't add to the watcher set */ if (fd->shutdown) { - watcher->fd = NULL; - watcher->pollset = NULL; - watcher->worker = NULL; + watcher->fd = nullptr; + watcher->pollset = nullptr; + watcher->worker = nullptr; gpr_mu_unlock(&fd->mu); GRPC_FD_UNREF(fd, "poll"); return 0; @@ -576,7 +576,7 @@ static uint32_t fd_begin_poll(grpc_fd *fd, grpc_pollset *pollset, /* if there is nobody polling for read, but we need to, then start doing so */ cur = fd->read_closure; requested = cur != CLOSURE_READY; - if (read_mask && fd->read_watcher == NULL && requested) { + if (read_mask && fd->read_watcher == nullptr && requested) { fd->read_watcher = watcher; mask |= read_mask; } @@ -584,12 +584,12 @@ static uint32_t fd_begin_poll(grpc_fd *fd, grpc_pollset *pollset, */ cur = fd->write_closure; requested = cur != CLOSURE_READY; - if (write_mask && fd->write_watcher == NULL && requested) { + if (write_mask && fd->write_watcher == nullptr && requested) { fd->write_watcher = watcher; mask |= write_mask; } /* if not polling, remember this watcher in case we need someone to later */ - if (mask == 0 && worker != NULL) { + if (mask == 0 && worker != nullptr) { watcher->next = &fd->inactive_watcher_root; watcher->prev = watcher->next->prev; watcher->next->prev = watcher->prev->next = watcher; @@ -602,14 +602,14 @@ static uint32_t fd_begin_poll(grpc_fd *fd, grpc_pollset *pollset, return mask; } -static void fd_end_poll(grpc_exec_ctx *exec_ctx, grpc_fd_watcher *watcher, +static void fd_end_poll(grpc_exec_ctx* exec_ctx, grpc_fd_watcher* watcher, int got_read, int got_write, - grpc_pollset *read_notifier_pollset) { + grpc_pollset* read_notifier_pollset) { int was_polling = 0; int kick = 0; - grpc_fd *fd = watcher->fd; + grpc_fd* fd = watcher->fd; - if (fd == NULL) { + if (fd == nullptr) { return; } @@ -621,7 +621,7 @@ static void fd_end_poll(grpc_exec_ctx *exec_ctx, grpc_fd_watcher *watcher, if (!got_read) { kick = 1; } - fd->read_watcher = NULL; + fd->read_watcher = nullptr; } if (watcher == fd->write_watcher) { /* remove write watcher, kick if we still need a write */ @@ -629,9 +629,9 @@ static void fd_end_poll(grpc_exec_ctx *exec_ctx, grpc_fd_watcher *watcher, if (!got_write) { kick = 1; } - fd->write_watcher = NULL; + fd->write_watcher = nullptr; } - if (!was_polling && watcher->worker != NULL) { + if (!was_polling && watcher->worker != nullptr) { /* remove from inactive list */ watcher->next->prev = watcher->prev; watcher->prev->next = watcher->next; @@ -640,7 +640,7 @@ static void fd_end_poll(grpc_exec_ctx *exec_ctx, grpc_fd_watcher *watcher, if (set_ready_locked(exec_ctx, fd, &fd->read_closure)) { kick = 1; } - if (read_notifier_pollset != NULL) { + if (read_notifier_pollset != nullptr) { set_read_notifier_pollset_locked(exec_ctx, fd, read_notifier_pollset); } } @@ -667,46 +667,46 @@ static void fd_end_poll(grpc_exec_ctx *exec_ctx, grpc_fd_watcher *watcher, GPR_TLS_DECL(g_current_thread_poller); GPR_TLS_DECL(g_current_thread_worker); -static void remove_worker(grpc_pollset *p, grpc_pollset_worker *worker) { +static void remove_worker(grpc_pollset* p, grpc_pollset_worker* worker) { worker->prev->next = worker->next; worker->next->prev = worker->prev; } -static bool pollset_has_workers(grpc_pollset *p) { +static bool pollset_has_workers(grpc_pollset* p) { return p->root_worker.next != &p->root_worker; } -static bool pollset_in_pollset_sets(grpc_pollset *p) { +static bool pollset_in_pollset_sets(grpc_pollset* p) { return p->pollset_set_count; } -static bool pollset_has_observers(grpc_pollset *p) { +static bool pollset_has_observers(grpc_pollset* p) { return pollset_has_workers(p) || pollset_in_pollset_sets(p); } -static grpc_pollset_worker *pop_front_worker(grpc_pollset *p) { +static grpc_pollset_worker* pop_front_worker(grpc_pollset* p) { if (pollset_has_workers(p)) { - grpc_pollset_worker *w = p->root_worker.next; + grpc_pollset_worker* w = p->root_worker.next; remove_worker(p, w); return w; } else { - return NULL; + return nullptr; } } -static void push_back_worker(grpc_pollset *p, grpc_pollset_worker *worker) { +static void push_back_worker(grpc_pollset* p, grpc_pollset_worker* worker) { worker->next = &p->root_worker; worker->prev = worker->next->prev; worker->prev->next = worker->next->prev = worker; } -static void push_front_worker(grpc_pollset *p, grpc_pollset_worker *worker) { +static void push_front_worker(grpc_pollset* p, grpc_pollset_worker* worker) { worker->prev = &p->root_worker; worker->next = worker->prev->next; worker->prev->next = worker->next->prev = worker; } -static void kick_append_error(grpc_error **composite, grpc_error *error) { +static void kick_append_error(grpc_error** composite, grpc_error* error) { if (error == GRPC_ERROR_NONE) return; if (*composite == GRPC_ERROR_NONE) { *composite = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Kick Failure"); @@ -714,15 +714,15 @@ static void kick_append_error(grpc_error **composite, grpc_error *error) { *composite = grpc_error_add_child(*composite, error); } -static grpc_error *pollset_kick_ext(grpc_exec_ctx *exec_ctx, grpc_pollset *p, - grpc_pollset_worker *specific_worker, +static grpc_error* pollset_kick_ext(grpc_exec_ctx* exec_ctx, grpc_pollset* p, + grpc_pollset_worker* specific_worker, uint32_t flags) { GPR_TIMER_BEGIN("pollset_kick_ext", 0); - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; GRPC_STATS_INC_POLLSET_KICK(exec_ctx); /* pollset->mu already held */ - if (specific_worker != NULL) { + if (specific_worker != nullptr) { if (specific_worker == GRPC_POLLSET_KICK_BROADCAST) { GPR_TIMER_BEGIN("pollset_kick_ext.broadcast", 0); GPR_ASSERT((flags & GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) == 0); @@ -756,7 +756,7 @@ static grpc_error *pollset_kick_ext(grpc_exec_ctx *exec_ctx, grpc_pollset *p, GPR_ASSERT((flags & GRPC_POLLSET_REEVALUATE_POLLING_ON_WAKEUP) == 0); GPR_TIMER_MARK("kick_anonymous", 0); specific_worker = pop_front_worker(p); - if (specific_worker != NULL) { + if (specific_worker != nullptr) { if (gpr_tls_get(&g_current_thread_worker) == (intptr_t)specific_worker) { GPR_TIMER_MARK("kick_anonymous_not_self", 0); push_back_worker(p, specific_worker); @@ -765,10 +765,10 @@ static grpc_error *pollset_kick_ext(grpc_exec_ctx *exec_ctx, grpc_pollset *p, gpr_tls_get(&g_current_thread_worker) == (intptr_t)specific_worker) { push_back_worker(p, specific_worker); - specific_worker = NULL; + specific_worker = nullptr; } } - if (specific_worker != NULL) { + if (specific_worker != nullptr) { GPR_TIMER_MARK("finally_kick", 0); push_back_worker(p, specific_worker); kick_append_error( @@ -785,14 +785,14 @@ static grpc_error *pollset_kick_ext(grpc_exec_ctx *exec_ctx, grpc_pollset *p, return error; } -static grpc_error *pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *p, - grpc_pollset_worker *specific_worker) { +static grpc_error* pollset_kick(grpc_exec_ctx* exec_ctx, grpc_pollset* p, + grpc_pollset_worker* specific_worker) { return pollset_kick_ext(exec_ctx, p, specific_worker, 0); } /* global state management */ -static grpc_error *pollset_global_init(void) { +static grpc_error* pollset_global_init(void) { gpr_tls_init(&g_current_thread_poller); gpr_tls_init(&g_current_thread_worker); return GRPC_ERROR_NONE; @@ -805,27 +805,27 @@ static void pollset_global_shutdown(void) { /* main interface */ -static void pollset_init(grpc_pollset *pollset, gpr_mu **mu) { +static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) { gpr_mu_init(&pollset->mu); *mu = &pollset->mu; pollset->root_worker.next = pollset->root_worker.prev = &pollset->root_worker; pollset->shutting_down = 0; pollset->called_shutdown = 0; pollset->kicked_without_pollers = 0; - pollset->idle_jobs.head = pollset->idle_jobs.tail = NULL; - pollset->local_wakeup_cache = NULL; + pollset->idle_jobs.head = pollset->idle_jobs.tail = nullptr; + pollset->local_wakeup_cache = nullptr; pollset->kicked_without_pollers = 0; pollset->fd_count = 0; pollset->fd_capacity = 0; - pollset->fds = NULL; + pollset->fds = nullptr; pollset->pollset_set_count = 0; } -static void pollset_destroy(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset) { +static void pollset_destroy(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset) { GPR_ASSERT(!pollset_has_workers(pollset)); GPR_ASSERT(pollset->idle_jobs.head == pollset->idle_jobs.tail); while (pollset->local_wakeup_cache) { - grpc_cached_wakeup_fd *next = pollset->local_wakeup_cache->next; + grpc_cached_wakeup_fd* next = pollset->local_wakeup_cache->next; grpc_wakeup_fd_destroy(&pollset->local_wakeup_cache->fd); gpr_free(pollset->local_wakeup_cache); pollset->local_wakeup_cache = next; @@ -834,8 +834,8 @@ static void pollset_destroy(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset) { gpr_mu_destroy(&pollset->mu); } -static void pollset_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_fd *fd) { +static void pollset_add_fd(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_fd* fd) { gpr_mu_lock(&pollset->mu); size_t i; /* TODO(ctiller): this is O(num_fds^2); maybe switch to a hash set here */ @@ -845,17 +845,17 @@ static void pollset_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, if (pollset->fd_count == pollset->fd_capacity) { pollset->fd_capacity = GPR_MAX(pollset->fd_capacity + 8, pollset->fd_count * 3 / 2); - pollset->fds = (grpc_fd **)gpr_realloc( - pollset->fds, sizeof(grpc_fd *) * pollset->fd_capacity); + pollset->fds = (grpc_fd**)gpr_realloc( + pollset->fds, sizeof(grpc_fd*) * pollset->fd_capacity); } pollset->fds[pollset->fd_count++] = fd; GRPC_FD_REF(fd, "multipoller"); - pollset_kick(exec_ctx, pollset, NULL); + pollset_kick(exec_ctx, pollset, nullptr); exit: gpr_mu_unlock(&pollset->mu); } -static void finish_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset) { +static void finish_shutdown(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset) { GPR_ASSERT(grpc_closure_list_empty(pollset->idle_jobs)); size_t i; for (i = 0; i < pollset->fd_count; i++) { @@ -865,7 +865,7 @@ static void finish_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset) { GRPC_CLOSURE_SCHED(exec_ctx, pollset->shutdown_done, GRPC_ERROR_NONE); } -static void work_combine_error(grpc_error **composite, grpc_error *error) { +static void work_combine_error(grpc_error** composite, grpc_error* error) { if (error == GRPC_ERROR_NONE) return; if (*composite == GRPC_ERROR_NONE) { *composite = GRPC_ERROR_CREATE_FROM_STATIC_STRING("pollset_work"); @@ -873,12 +873,12 @@ static void work_combine_error(grpc_error **composite, grpc_error *error) { *composite = grpc_error_add_child(*composite, error); } -static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker **worker_hdl, +static grpc_error* pollset_work(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker** worker_hdl, grpc_millis deadline) { grpc_pollset_worker worker; if (worker_hdl) *worker_hdl = &worker; - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; /* Avoid malloc for small number of elements. */ enum { inline_elements = 96 }; @@ -892,14 +892,14 @@ static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, int keep_polling = 0; GPR_TIMER_BEGIN("pollset_work", 0); /* this must happen before we (potentially) drop pollset->mu */ - worker.next = worker.prev = NULL; + worker.next = worker.prev = nullptr; worker.reevaluate_polling_on_wakeup = 0; - if (pollset->local_wakeup_cache != NULL) { + if (pollset->local_wakeup_cache != nullptr) { worker.wakeup_fd = pollset->local_wakeup_cache; pollset->local_wakeup_cache = worker.wakeup_fd->next; } else { worker.wakeup_fd = - (grpc_cached_wakeup_fd *)gpr_malloc(sizeof(*worker.wakeup_fd)); + (grpc_cached_wakeup_fd*)gpr_malloc(sizeof(*worker.wakeup_fd)); error = grpc_wakeup_fd_init(&worker.wakeup_fd->fd); if (error != GRPC_ERROR_NONE) { GRPC_LOG_IF_ERROR("pollset_work", GRPC_ERROR_REF(error)); @@ -941,8 +941,8 @@ static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, int r; size_t i, fd_count; nfds_t pfd_count; - grpc_fd_watcher *watchers; - struct pollfd *pfds; + grpc_fd_watcher* watchers; + struct pollfd* pfds; timeout = poll_deadline_to_millis_timeout(exec_ctx, deadline); @@ -953,9 +953,9 @@ static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, /* Allocate one buffer to hold both pfds and watchers arrays */ const size_t pfd_size = sizeof(*pfds) * (pollset->fd_count + 2); const size_t watch_size = sizeof(*watchers) * (pollset->fd_count + 2); - void *buf = gpr_malloc(pfd_size + watch_size); - pfds = (struct pollfd *)buf; - watchers = (grpc_fd_watcher *)(void *)((char *)buf + pfd_size); + void* buf = gpr_malloc(pfd_size + watch_size); + pfds = (struct pollfd*)buf; + watchers = (grpc_fd_watcher*)(void*)((char*)buf + pfd_size); } fd_count = 0; @@ -979,7 +979,7 @@ static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, gpr_mu_unlock(&pollset->mu); for (i = 1; i < pfd_count; i++) { - grpc_fd *fd = watchers[i].fd; + grpc_fd* fd = watchers[i].fd; pfds[i].events = (short)fd_begin_poll(fd, pollset, &worker, POLLIN, POLLOUT, &watchers[i]); GRPC_FD_UNREF(fd, "multipoller_start"); @@ -992,7 +992,7 @@ static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, r = grpc_poll_function(pfds, pfd_count, timeout); GRPC_SCHEDULING_END_BLOCKING_REGION_WITH_EXEC_CTX(exec_ctx); - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "%p poll=%d", pollset, r); } @@ -1002,8 +1002,8 @@ static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, } for (i = 1; i < pfd_count; i++) { - if (watchers[i].fd == NULL) { - fd_end_poll(exec_ctx, &watchers[i], 0, 0, NULL); + if (watchers[i].fd == nullptr) { + fd_end_poll(exec_ctx, &watchers[i], 0, 0, nullptr); } else { // Wake up all the file descriptors, if we have an invalid one // we can identify it on the next pollset_work() @@ -1012,21 +1012,21 @@ static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, } } else if (r == 0) { for (i = 1; i < pfd_count; i++) { - fd_end_poll(exec_ctx, &watchers[i], 0, 0, NULL); + fd_end_poll(exec_ctx, &watchers[i], 0, 0, nullptr); } } else { if (pfds[0].revents & POLLIN_CHECK) { - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "%p: got_wakeup", pollset); } work_combine_error( &error, grpc_wakeup_fd_consume_wakeup(&worker.wakeup_fd->fd)); } for (i = 1; i < pfd_count; i++) { - if (watchers[i].fd == NULL) { - fd_end_poll(exec_ctx, &watchers[i], 0, 0, NULL); + if (watchers[i].fd == nullptr) { + fd_end_poll(exec_ctx, &watchers[i], 0, 0, nullptr); } else { - if (GRPC_TRACER_ON(grpc_polling_trace)) { + if (grpc_polling_trace.enabled()) { gpr_log(GPR_DEBUG, "%p got_event: %d r:%d w:%d [%d]", pollset, pfds[i].fd, (pfds[i].revents & POLLIN_CHECK) != 0, (pfds[i].revents & POLLOUT_CHECK) != 0, pfds[i].revents); @@ -1083,7 +1083,7 @@ static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, /* check shutdown conditions */ if (pollset->shutting_down) { if (pollset_has_workers(pollset)) { - pollset_kick(exec_ctx, pollset, NULL); + pollset_kick(exec_ctx, pollset, nullptr); } else if (!pollset->called_shutdown && !pollset_has_observers(pollset)) { pollset->called_shutdown = 1; gpr_mu_unlock(&pollset->mu); @@ -1101,14 +1101,14 @@ static grpc_error *pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, gpr_mu_lock(&pollset->mu); } } - if (worker_hdl) *worker_hdl = NULL; + if (worker_hdl) *worker_hdl = nullptr; GPR_TIMER_END("pollset_work", 0); GRPC_LOG_IF_ERROR("pollset_work", GRPC_ERROR_REF(error)); return error; } -static void pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_closure *closure) { +static void pollset_shutdown(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_closure* closure) { GPR_ASSERT(!pollset->shutting_down); pollset->shutting_down = 1; pollset->shutdown_done = closure; @@ -1122,7 +1122,7 @@ static void pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, } } -static int poll_deadline_to_millis_timeout(grpc_exec_ctx *exec_ctx, +static int poll_deadline_to_millis_timeout(grpc_exec_ctx* exec_ctx, grpc_millis deadline) { if (deadline == GRPC_MILLIS_INF_FUTURE) return -1; if (deadline == 0) return 0; @@ -1136,22 +1136,22 @@ static int poll_deadline_to_millis_timeout(grpc_exec_ctx *exec_ctx, * pollset_set_posix.c */ -static grpc_pollset_set *pollset_set_create(void) { - grpc_pollset_set *pollset_set = - (grpc_pollset_set *)gpr_zalloc(sizeof(*pollset_set)); +static grpc_pollset_set* pollset_set_create(void) { + grpc_pollset_set* pollset_set = + (grpc_pollset_set*)gpr_zalloc(sizeof(*pollset_set)); gpr_mu_init(&pollset_set->mu); return pollset_set; } -static void pollset_set_destroy(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set) { +static void pollset_set_destroy(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set) { size_t i; gpr_mu_destroy(&pollset_set->mu); for (i = 0; i < pollset_set->fd_count; i++) { GRPC_FD_UNREF(pollset_set->fds[i], "pollset_set"); } for (i = 0; i < pollset_set->pollset_count; i++) { - grpc_pollset *pollset = pollset_set->pollsets[i]; + grpc_pollset* pollset = pollset_set->pollsets[i]; gpr_mu_lock(&pollset->mu); pollset->pollset_set_count--; /* check shutdown */ @@ -1170,9 +1170,9 @@ static void pollset_set_destroy(grpc_exec_ctx *exec_ctx, gpr_free(pollset_set); } -static void pollset_set_add_pollset(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, - grpc_pollset *pollset) { +static void pollset_set_add_pollset(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, + grpc_pollset* pollset) { size_t i, j; gpr_mu_lock(&pollset->mu); pollset->pollset_set_count++; @@ -1181,7 +1181,7 @@ static void pollset_set_add_pollset(grpc_exec_ctx *exec_ctx, if (pollset_set->pollset_count == pollset_set->pollset_capacity) { pollset_set->pollset_capacity = GPR_MAX(8, 2 * pollset_set->pollset_capacity); - pollset_set->pollsets = (grpc_pollset **)gpr_realloc( + pollset_set->pollsets = (grpc_pollset**)gpr_realloc( pollset_set->pollsets, pollset_set->pollset_capacity * sizeof(*pollset_set->pollsets)); } @@ -1198,15 +1198,15 @@ static void pollset_set_add_pollset(grpc_exec_ctx *exec_ctx, gpr_mu_unlock(&pollset_set->mu); } -static void pollset_set_del_pollset(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, - grpc_pollset *pollset) { +static void pollset_set_del_pollset(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, + grpc_pollset* pollset) { size_t i; gpr_mu_lock(&pollset_set->mu); for (i = 0; i < pollset_set->pollset_count; i++) { if (pollset_set->pollsets[i] == pollset) { pollset_set->pollset_count--; - GPR_SWAP(grpc_pollset *, pollset_set->pollsets[i], + GPR_SWAP(grpc_pollset*, pollset_set->pollsets[i], pollset_set->pollsets[pollset_set->pollset_count]); break; } @@ -1225,14 +1225,14 @@ static void pollset_set_del_pollset(grpc_exec_ctx *exec_ctx, } } -static void pollset_set_add_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *bag, - grpc_pollset_set *item) { +static void pollset_set_add_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* bag, + grpc_pollset_set* item) { size_t i, j; gpr_mu_lock(&bag->mu); if (bag->pollset_set_count == bag->pollset_set_capacity) { bag->pollset_set_capacity = GPR_MAX(8, 2 * bag->pollset_set_capacity); - bag->pollset_sets = (grpc_pollset_set **)gpr_realloc( + bag->pollset_sets = (grpc_pollset_set**)gpr_realloc( bag->pollset_sets, bag->pollset_set_capacity * sizeof(*bag->pollset_sets)); } @@ -1249,15 +1249,15 @@ static void pollset_set_add_pollset_set(grpc_exec_ctx *exec_ctx, gpr_mu_unlock(&bag->mu); } -static void pollset_set_del_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *bag, - grpc_pollset_set *item) { +static void pollset_set_del_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* bag, + grpc_pollset_set* item) { size_t i; gpr_mu_lock(&bag->mu); for (i = 0; i < bag->pollset_set_count; i++) { if (bag->pollset_sets[i] == item) { bag->pollset_set_count--; - GPR_SWAP(grpc_pollset_set *, bag->pollset_sets[i], + GPR_SWAP(grpc_pollset_set*, bag->pollset_sets[i], bag->pollset_sets[bag->pollset_set_count]); break; } @@ -1265,13 +1265,13 @@ static void pollset_set_del_pollset_set(grpc_exec_ctx *exec_ctx, gpr_mu_unlock(&bag->mu); } -static void pollset_set_add_fd(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, grpc_fd *fd) { +static void pollset_set_add_fd(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, grpc_fd* fd) { size_t i; gpr_mu_lock(&pollset_set->mu); if (pollset_set->fd_count == pollset_set->fd_capacity) { pollset_set->fd_capacity = GPR_MAX(8, 2 * pollset_set->fd_capacity); - pollset_set->fds = (grpc_fd **)gpr_realloc( + pollset_set->fds = (grpc_fd**)gpr_realloc( pollset_set->fds, pollset_set->fd_capacity * sizeof(*pollset_set->fds)); } GRPC_FD_REF(fd, "pollset_set"); @@ -1285,14 +1285,14 @@ static void pollset_set_add_fd(grpc_exec_ctx *exec_ctx, gpr_mu_unlock(&pollset_set->mu); } -static void pollset_set_del_fd(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, grpc_fd *fd) { +static void pollset_set_del_fd(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, grpc_fd* fd) { size_t i; gpr_mu_lock(&pollset_set->mu); for (i = 0; i < pollset_set->fd_count; i++) { if (pollset_set->fds[i] == fd) { pollset_set->fd_count--; - GPR_SWAP(grpc_fd *, pollset_set->fds[i], + GPR_SWAP(grpc_fd*, pollset_set->fds[i], pollset_set->fds[pollset_set->fd_count]); GRPC_FD_UNREF(fd, "pollset_set"); break; @@ -1308,10 +1308,10 @@ static void pollset_set_del_fd(grpc_exec_ctx *exec_ctx, * Condition Variable polling extensions */ -static void run_poll(void *args); -static void cache_poller_locked(poll_args *args); +static void run_poll(void* args); +static void cache_poller_locked(poll_args* args); -static void cache_insert_locked(poll_args *args) { +static void cache_insert_locked(poll_args* args) { uint32_t key = gpr_murmur_hash3(args->fds, args->nfds * sizeof(struct pollfd), 0xDEADBEEF); key = key % poll_cache.size; @@ -1319,18 +1319,18 @@ static void cache_insert_locked(poll_args *args) { poll_cache.active_pollers[key]->prev = args; } args->next = poll_cache.active_pollers[key]; - args->prev = NULL; + args->prev = nullptr; poll_cache.active_pollers[key] = args; poll_cache.count++; } -static void init_result(poll_args *pargs) { - pargs->result = (poll_result *)gpr_malloc(sizeof(poll_result)); +static void init_result(poll_args* pargs) { + pargs->result = (poll_result*)gpr_malloc(sizeof(poll_result)); gpr_ref_init(&pargs->result->refcount, 1); - pargs->result->watchers = NULL; + pargs->result->watchers = nullptr; pargs->result->watchcount = 0; pargs->result->fds = - (struct pollfd *)gpr_malloc(sizeof(struct pollfd) * pargs->nfds); + (struct pollfd*)gpr_malloc(sizeof(struct pollfd) * pargs->nfds); memcpy(pargs->result->fds, pargs->fds, sizeof(struct pollfd) * pargs->nfds); pargs->result->nfds = pargs->nfds; pargs->result->retval = 0; @@ -1340,11 +1340,11 @@ static void init_result(poll_args *pargs) { // Creates a poll_args object for a given arguments to poll(). // This object may return a poll_args in the cache. -static poll_args *get_poller_locked(struct pollfd *fds, nfds_t count) { +static poll_args* get_poller_locked(struct pollfd* fds, nfds_t count) { uint32_t key = gpr_murmur_hash3(fds, count * sizeof(struct pollfd), 0xDEADBEEF); key = key % poll_cache.size; - poll_args *curr = poll_cache.active_pollers[key]; + poll_args* curr = poll_cache.active_pollers[key]; while (curr) { if (curr->nfds == count && memcmp(curr->fds, fds, count * sizeof(struct pollfd)) == 0) { @@ -1355,26 +1355,26 @@ static poll_args *get_poller_locked(struct pollfd *fds, nfds_t count) { } if (poll_cache.free_pollers) { - poll_args *pargs = poll_cache.free_pollers; + poll_args* pargs = poll_cache.free_pollers; poll_cache.free_pollers = pargs->next; if (poll_cache.free_pollers) { - poll_cache.free_pollers->prev = NULL; + poll_cache.free_pollers->prev = nullptr; } pargs->fds = fds; pargs->nfds = count; - pargs->next = NULL; - pargs->prev = NULL; + pargs->next = nullptr; + pargs->prev = nullptr; init_result(pargs); cache_poller_locked(pargs); return pargs; } - poll_args *pargs = (poll_args *)gpr_malloc(sizeof(struct poll_args)); + poll_args* pargs = (poll_args*)gpr_malloc(sizeof(struct poll_args)); gpr_cv_init(&pargs->trigger); pargs->fds = fds; pargs->nfds = count; - pargs->next = NULL; - pargs->prev = NULL; + pargs->next = nullptr; + pargs->prev = nullptr; pargs->trigger_set = 0; init_result(pargs); cache_poller_locked(pargs); @@ -1386,7 +1386,7 @@ static poll_args *get_poller_locked(struct pollfd *fds, nfds_t count) { return pargs; } -static void cache_delete_locked(poll_args *args) { +static void cache_delete_locked(poll_args* args) { if (!args->prev) { uint32_t key = gpr_murmur_hash3( args->fds, args->nfds * sizeof(struct pollfd), 0xDEADBEEF); @@ -1405,25 +1405,25 @@ static void cache_delete_locked(poll_args *args) { if (poll_cache.free_pollers) { poll_cache.free_pollers->prev = args; } - args->prev = NULL; + args->prev = nullptr; args->next = poll_cache.free_pollers; gpr_free(args->fds); poll_cache.free_pollers = args; } -static void cache_poller_locked(poll_args *args) { +static void cache_poller_locked(poll_args* args) { if (poll_cache.count + 1 > poll_cache.size / 2) { - poll_args **old_active_pollers = poll_cache.active_pollers; + poll_args** old_active_pollers = poll_cache.active_pollers; poll_cache.size = poll_cache.size * 2; poll_cache.count = 0; poll_cache.active_pollers = - (poll_args **)gpr_malloc(sizeof(void *) * poll_cache.size); + (poll_args**)gpr_malloc(sizeof(void*) * poll_cache.size); for (unsigned int i = 0; i < poll_cache.size; i++) { - poll_cache.active_pollers[i] = NULL; + poll_cache.active_pollers[i] = nullptr; } for (unsigned int i = 0; i < poll_cache.size / 2; i++) { - poll_args *curr = old_active_pollers[i]; - poll_args *next = NULL; + poll_args* curr = old_active_pollers[i]; + poll_args* next = nullptr; while (curr) { next = curr->next; cache_insert_locked(curr); @@ -1436,7 +1436,7 @@ static void cache_poller_locked(poll_args *args) { cache_insert_locked(args); } -static void cache_destroy_locked(poll_args *args) { +static void cache_destroy_locked(poll_args* args) { if (args->next) { args->next->prev = args->prev; } @@ -1450,7 +1450,7 @@ static void cache_destroy_locked(poll_args *args) { gpr_free(args); } -static void decref_poll_result(poll_result *res) { +static void decref_poll_result(poll_result* res) { if (gpr_unref(&res->refcount)) { GPR_ASSERT(!res->watchers); gpr_free(res->fds); @@ -1458,7 +1458,7 @@ static void decref_poll_result(poll_result *res) { } } -void remove_cvn(cv_node **head, cv_node *target) { +void remove_cvn(cv_node** head, cv_node* target) { if (target->next) { target->next->prev = target->prev; } @@ -1473,17 +1473,17 @@ void remove_cvn(cv_node **head, cv_node *target) { gpr_timespec thread_grace; // Poll in a background thread -static void run_poll(void *args) { - poll_args *pargs = (poll_args *)args; +static void run_poll(void* args) { + poll_args* pargs = (poll_args*)args; while (1) { - poll_result *result = pargs->result; + poll_result* result = pargs->result; int retval = g_cvfds.poll(result->fds, result->nfds, CV_POLL_PERIOD_MS); gpr_mu_lock(&g_cvfds.mu); if (retval != 0) { result->completed = 1; result->retval = retval; result->err = errno; - cv_node *watcher = result->watchers; + cv_node* watcher = result->watchers; while (watcher) { gpr_cv_signal(watcher->cv); watcher = watcher->next; @@ -1514,27 +1514,27 @@ static void run_poll(void *args) { } // This function overrides poll() to handle condition variable wakeup fds -static int cvfd_poll(struct pollfd *fds, nfds_t nfds, int timeout) { +static int cvfd_poll(struct pollfd* fds, nfds_t nfds, int timeout) { unsigned int i; int res, idx; - cv_node *pollcv; + cv_node* pollcv; int skip_poll = 0; nfds_t nsockfds = 0; - poll_result *result = NULL; + poll_result* result = nullptr; gpr_mu_lock(&g_cvfds.mu); - pollcv = (cv_node *)gpr_malloc(sizeof(cv_node)); - pollcv->next = NULL; + pollcv = (cv_node*)gpr_malloc(sizeof(cv_node)); + pollcv->next = nullptr; gpr_cv pollcv_cv; gpr_cv_init(&pollcv_cv); pollcv->cv = &pollcv_cv; - cv_node *fd_cvs = (cv_node *)gpr_malloc(nfds * sizeof(cv_node)); + cv_node* fd_cvs = (cv_node*)gpr_malloc(nfds * sizeof(cv_node)); for (i = 0; i < nfds; i++) { fds[i].revents = 0; if (fds[i].fd < 0 && (fds[i].events & POLLIN)) { idx = GRPC_FD_TO_IDX(fds[i].fd); fd_cvs[i].cv = &pollcv_cv; - fd_cvs[i].prev = NULL; + fd_cvs[i].prev = nullptr; fd_cvs[i].next = g_cvfds.cvfds[idx].cvs; if (g_cvfds.cvfds[idx].cvs) { g_cvfds.cvfds[idx].cvs->prev = &(fd_cvs[i]); @@ -1559,8 +1559,8 @@ static int cvfd_poll(struct pollfd *fds, nfds_t nfds, int timeout) { res = 0; if (!skip_poll && nsockfds > 0) { - struct pollfd *pollfds = - (struct pollfd *)gpr_malloc(sizeof(struct pollfd) * nsockfds); + struct pollfd* pollfds = + (struct pollfd*)gpr_malloc(sizeof(struct pollfd) * nsockfds); idx = 0; for (i = 0; i < nfds; i++) { if (fds[i].fd >= 0) { @@ -1570,10 +1570,10 @@ static int cvfd_poll(struct pollfd *fds, nfds_t nfds, int timeout) { idx++; } } - poll_args *pargs = get_poller_locked(pollfds, nsockfds); + poll_args* pargs = get_poller_locked(pollfds, nsockfds); result = pargs->result; pollcv->next = result->watchers; - pollcv->prev = NULL; + pollcv->prev = nullptr; if (result->watchers) { result->watchers->prev = pollcv; } @@ -1623,13 +1623,12 @@ static void global_cv_fd_table_init() { gpr_cv_init(&g_cvfds.shutdown_cv); gpr_ref_init(&g_cvfds.pollcount, 1); g_cvfds.size = CV_DEFAULT_TABLE_SIZE; - g_cvfds.cvfds = - (fd_node *)gpr_malloc(sizeof(fd_node) * CV_DEFAULT_TABLE_SIZE); - g_cvfds.free_fds = NULL; + g_cvfds.cvfds = (fd_node*)gpr_malloc(sizeof(fd_node) * CV_DEFAULT_TABLE_SIZE); + g_cvfds.free_fds = nullptr; thread_grace = gpr_time_from_millis(POLLCV_THREAD_GRACE_MS, GPR_TIMESPAN); for (int i = 0; i < CV_DEFAULT_TABLE_SIZE; i++) { g_cvfds.cvfds[i].is_set = 0; - g_cvfds.cvfds[i].cvs = NULL; + g_cvfds.cvfds[i].cvs = nullptr; g_cvfds.cvfds[i].next_free = g_cvfds.free_fds; g_cvfds.free_fds = &g_cvfds.cvfds[i]; } @@ -1640,10 +1639,10 @@ static void global_cv_fd_table_init() { // Initialize the cache poll_cache.size = 32; poll_cache.count = 0; - poll_cache.free_pollers = NULL; - poll_cache.active_pollers = (poll_args **)gpr_malloc(sizeof(void *) * 32); + poll_cache.free_pollers = nullptr; + poll_cache.active_pollers = (poll_args**)gpr_malloc(sizeof(void*) * 32); for (unsigned int i = 0; i < poll_cache.size; i++) { - poll_cache.active_pollers[i] = NULL; + poll_cache.active_pollers[i] = nullptr; } gpr_mu_unlock(&g_cvfds.mu); @@ -1711,23 +1710,24 @@ static const grpc_event_engine_vtable vtable = { shutdown_engine, }; -const grpc_event_engine_vtable *grpc_init_poll_posix(bool explicit_request) { +const grpc_event_engine_vtable* grpc_init_poll_posix(bool explicit_request) { if (!grpc_has_wakeup_fd()) { - return NULL; + gpr_log(GPR_ERROR, "Skipping poll because of no wakeup fd."); + return nullptr; } if (!GRPC_LOG_IF_ERROR("pollset_global_init", pollset_global_init())) { - return NULL; + return nullptr; } return &vtable; } -const grpc_event_engine_vtable *grpc_init_poll_cv_posix(bool explicit_request) { +const grpc_event_engine_vtable* grpc_init_poll_cv_posix(bool explicit_request) { global_cv_fd_table_init(); grpc_enable_cv_wakeup_fds(1); if (!GRPC_LOG_IF_ERROR("pollset_global_init", pollset_global_init())) { global_cv_fd_table_shutdown(); grpc_enable_cv_wakeup_fds(0); - return NULL; + return nullptr; } return &vtable; } diff --git a/src/core/lib/iomgr/ev_poll_posix.h b/src/core/lib/iomgr/ev_poll_posix.h index 861257204b5..f6bc624d4fd 100644 --- a/src/core/lib/iomgr/ev_poll_posix.h +++ b/src/core/lib/iomgr/ev_poll_posix.h @@ -21,15 +21,7 @@ #include "src/core/lib/iomgr/ev_posix.h" -#ifdef __cplusplus -extern "C" { -#endif - -const grpc_event_engine_vtable *grpc_init_poll_posix(bool explicit_request); -const grpc_event_engine_vtable *grpc_init_poll_cv_posix(bool explicit_request); - -#ifdef __cplusplus -} -#endif +const grpc_event_engine_vtable* grpc_init_poll_posix(bool explicit_request); +const grpc_event_engine_vtable* grpc_init_poll_cv_posix(bool explicit_request); #endif /* GRPC_CORE_LIB_IOMGR_EV_POLL_POSIX_H */ diff --git a/src/core/lib/iomgr/ev_posix.cc b/src/core/lib/iomgr/ev_posix.cc index 677ee675a6a..031c97564a5 100644 --- a/src/core/lib/iomgr/ev_posix.cc +++ b/src/core/lib/iomgr/ev_posix.cc @@ -36,13 +36,9 @@ #include "src/core/lib/iomgr/ev_poll_posix.h" #include "src/core/lib/support/env.h" -grpc_tracer_flag grpc_polling_trace = - GRPC_TRACER_INITIALIZER(false, "polling"); /* Disabled by default */ - -#ifndef NDEBUG -grpc_tracer_flag grpc_trace_fd_refcount = - GRPC_TRACER_INITIALIZER(false, "fd_refcount"); -#endif +grpc_core::TraceFlag grpc_polling_trace(false, + "polling"); /* Disabled by default */ +grpc_core::DebugOnlyTraceFlag grpc_trace_fd_refcount(false, "fd_refcount"); /** Default poll() function - a pointer so that it can be overridden by some * tests */ @@ -50,21 +46,19 @@ grpc_poll_function_type grpc_poll_function = poll; grpc_wakeup_fd grpc_global_wakeup_fd; -static const grpc_event_engine_vtable *g_event_engine; -static const char *g_poll_strategy_name = NULL; +static const grpc_event_engine_vtable* g_event_engine; +static const char* g_poll_strategy_name = nullptr; -typedef const grpc_event_engine_vtable *(*event_engine_factory_fn)( +typedef const grpc_event_engine_vtable* (*event_engine_factory_fn)( bool explicit_request); typedef struct { - const char *name; + const char* name; event_engine_factory_fn factory; } event_engine_factory; namespace { -extern "C" { - grpc_poll_function_type real_poll_function; int dummy_poll(struct pollfd fds[], nfds_t nfds, int timeout) { @@ -76,9 +70,8 @@ int dummy_poll(struct pollfd fds[], nfds_t nfds, int timeout) { return -1; } } -} // extern "C" -const grpc_event_engine_vtable *init_non_polling(bool explicit_request) { +const grpc_event_engine_vtable* init_non_polling(bool explicit_request) { if (!explicit_request) { return nullptr; } @@ -97,24 +90,24 @@ static const event_engine_factory g_factories[] = { {"poll-cv", grpc_init_poll_cv_posix}, {"none", init_non_polling}, }; -static void add(const char *beg, const char *end, char ***ss, size_t *ns) { +static void add(const char* beg, const char* end, char*** ss, size_t* ns) { size_t n = *ns; size_t np = n + 1; - char *s; + char* s; size_t len; GPR_ASSERT(end >= beg); len = (size_t)(end - beg); - s = (char *)gpr_malloc(len + 1); + s = (char*)gpr_malloc(len + 1); memcpy(s, beg, len); s[len] = 0; - *ss = (char **)gpr_realloc(*ss, sizeof(char **) * np); + *ss = (char**)gpr_realloc(*ss, sizeof(char**) * np); (*ss)[n] = s; *ns = np; } -static void split(const char *s, char ***ss, size_t *ns) { - const char *c = strchr(s, ','); - if (c == NULL) { +static void split(const char* s, char*** ss, size_t* ns) { + const char* c = strchr(s, ','); + if (c == nullptr) { add(s, s + strlen(s), ss, ns); } else { add(s, c, ss, ns); @@ -122,11 +115,11 @@ static void split(const char *s, char ***ss, size_t *ns) { } } -static bool is(const char *want, const char *have) { +static bool is(const char* want, const char* have) { return 0 == strcmp(want, "all") || 0 == strcmp(want, have); } -static void try_engine(const char *engine) { +static void try_engine(const char* engine) { for (size_t i = 0; i < GPR_ARRAY_SIZE(g_factories); i++) { if (is(engine, g_factories[i].name)) { if ((g_event_engine = g_factories[i].factory( @@ -141,30 +134,28 @@ static void try_engine(const char *engine) { /* This should be used for testing purposes ONLY */ void grpc_set_event_engine_test_only( - const grpc_event_engine_vtable *ev_engine) { + const grpc_event_engine_vtable* ev_engine) { g_event_engine = ev_engine; } -const grpc_event_engine_vtable *grpc_get_event_engine_test_only() { +const grpc_event_engine_vtable* grpc_get_event_engine_test_only() { return g_event_engine; } /* Call this only after calling grpc_event_engine_init() */ -const char *grpc_get_poll_strategy_name() { return g_poll_strategy_name; } +const char* grpc_get_poll_strategy_name() { return g_poll_strategy_name; } void grpc_event_engine_init(void) { - grpc_register_tracer(&grpc_polling_trace); - - char *s = gpr_getenv("GRPC_POLL_STRATEGY"); - if (s == NULL) { + char* s = gpr_getenv("GRPC_POLL_STRATEGY"); + if (s == nullptr) { s = gpr_strdup("all"); } - char **strings = NULL; + char** strings = nullptr; size_t nstrings = 0; split(s, &strings, &nstrings); - for (size_t i = 0; g_event_engine == NULL && i < nstrings; i++) { + for (size_t i = 0; g_event_engine == nullptr && i < nstrings; i++) { try_engine(strings[i]); } @@ -172,122 +163,122 @@ void grpc_event_engine_init(void) { gpr_free(strings[i]); } gpr_free(strings); - gpr_free(s); - if (g_event_engine == NULL) { - gpr_log(GPR_ERROR, "No event engine could be initialized"); + if (g_event_engine == nullptr) { + gpr_log(GPR_ERROR, "No event engine could be initialized from %s", s); abort(); } + gpr_free(s); } void grpc_event_engine_shutdown(void) { g_event_engine->shutdown_engine(); - g_event_engine = NULL; + g_event_engine = nullptr; } -grpc_fd *grpc_fd_create(int fd, const char *name) { +grpc_fd* grpc_fd_create(int fd, const char* name) { return g_event_engine->fd_create(fd, name); } -int grpc_fd_wrapped_fd(grpc_fd *fd) { +int grpc_fd_wrapped_fd(grpc_fd* fd) { return g_event_engine->fd_wrapped_fd(fd); } -void grpc_fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_closure *on_done, - int *release_fd, bool already_closed, const char *reason) { +void grpc_fd_orphan(grpc_exec_ctx* exec_ctx, grpc_fd* fd, grpc_closure* on_done, + int* release_fd, bool already_closed, const char* reason) { g_event_engine->fd_orphan(exec_ctx, fd, on_done, release_fd, already_closed, reason); } -void grpc_fd_shutdown(grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_error *why) { +void grpc_fd_shutdown(grpc_exec_ctx* exec_ctx, grpc_fd* fd, grpc_error* why) { g_event_engine->fd_shutdown(exec_ctx, fd, why); } -bool grpc_fd_is_shutdown(grpc_fd *fd) { +bool grpc_fd_is_shutdown(grpc_fd* fd) { return g_event_engine->fd_is_shutdown(fd); } -void grpc_fd_notify_on_read(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *closure) { +void grpc_fd_notify_on_read(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* closure) { g_event_engine->fd_notify_on_read(exec_ctx, fd, closure); } -void grpc_fd_notify_on_write(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *closure) { +void grpc_fd_notify_on_write(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* closure) { g_event_engine->fd_notify_on_write(exec_ctx, fd, closure); } size_t grpc_pollset_size(void) { return g_event_engine->pollset_size; } -void grpc_pollset_init(grpc_pollset *pollset, gpr_mu **mu) { +void grpc_pollset_init(grpc_pollset* pollset, gpr_mu** mu) { g_event_engine->pollset_init(pollset, mu); } -void grpc_pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_closure *closure) { +void grpc_pollset_shutdown(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_closure* closure) { g_event_engine->pollset_shutdown(exec_ctx, pollset, closure); } -void grpc_pollset_destroy(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset) { +void grpc_pollset_destroy(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset) { g_event_engine->pollset_destroy(exec_ctx, pollset); } -grpc_error *grpc_pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker **worker, +grpc_error* grpc_pollset_work(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker** worker, grpc_millis deadline) { return g_event_engine->pollset_work(exec_ctx, pollset, worker, deadline); } -grpc_error *grpc_pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker *specific_worker) { +grpc_error* grpc_pollset_kick(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker* specific_worker) { return g_event_engine->pollset_kick(exec_ctx, pollset, specific_worker); } -void grpc_pollset_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - struct grpc_fd *fd) { +void grpc_pollset_add_fd(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + struct grpc_fd* fd) { g_event_engine->pollset_add_fd(exec_ctx, pollset, fd); } -grpc_pollset_set *grpc_pollset_set_create(void) { +grpc_pollset_set* grpc_pollset_set_create(void) { return g_event_engine->pollset_set_create(); } -void grpc_pollset_set_destroy(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set) { +void grpc_pollset_set_destroy(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set) { g_event_engine->pollset_set_destroy(exec_ctx, pollset_set); } -void grpc_pollset_set_add_pollset(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, - grpc_pollset *pollset) { +void grpc_pollset_set_add_pollset(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, + grpc_pollset* pollset) { g_event_engine->pollset_set_add_pollset(exec_ctx, pollset_set, pollset); } -void grpc_pollset_set_del_pollset(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, - grpc_pollset *pollset) { +void grpc_pollset_set_del_pollset(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, + grpc_pollset* pollset) { g_event_engine->pollset_set_del_pollset(exec_ctx, pollset_set, pollset); } -void grpc_pollset_set_add_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *bag, - grpc_pollset_set *item) { +void grpc_pollset_set_add_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* bag, + grpc_pollset_set* item) { g_event_engine->pollset_set_add_pollset_set(exec_ctx, bag, item); } -void grpc_pollset_set_del_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *bag, - grpc_pollset_set *item) { +void grpc_pollset_set_del_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* bag, + grpc_pollset_set* item) { g_event_engine->pollset_set_del_pollset_set(exec_ctx, bag, item); } -void grpc_pollset_set_add_fd(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, grpc_fd *fd) { +void grpc_pollset_set_add_fd(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, grpc_fd* fd) { g_event_engine->pollset_set_add_fd(exec_ctx, pollset_set, fd); } -void grpc_pollset_set_del_fd(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, grpc_fd *fd) { +void grpc_pollset_set_del_fd(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, grpc_fd* fd) { g_event_engine->pollset_set_del_fd(exec_ctx, pollset_set, fd); } diff --git a/src/core/lib/iomgr/ev_posix.h b/src/core/lib/iomgr/ev_posix.h index bc4456c2a29..16fa10ca568 100644 --- a/src/core/lib/iomgr/ev_posix.h +++ b/src/core/lib/iomgr/ev_posix.h @@ -27,61 +27,57 @@ #include "src/core/lib/iomgr/pollset_set.h" #include "src/core/lib/iomgr/wakeup_fd_posix.h" -#ifdef __cplusplus -extern "C" { -#endif - -extern grpc_tracer_flag grpc_polling_trace; /* Disabled by default */ +extern grpc_core::TraceFlag grpc_polling_trace; /* Disabled by default */ typedef struct grpc_fd grpc_fd; typedef struct grpc_event_engine_vtable { size_t pollset_size; - grpc_fd *(*fd_create)(int fd, const char *name); - int (*fd_wrapped_fd)(grpc_fd *fd); - void (*fd_orphan)(grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_closure *on_done, - int *release_fd, bool already_closed, const char *reason); - void (*fd_shutdown)(grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_error *why); - void (*fd_notify_on_read)(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *closure); - void (*fd_notify_on_write)(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *closure); - bool (*fd_is_shutdown)(grpc_fd *fd); - grpc_pollset *(*fd_get_read_notifier_pollset)(grpc_exec_ctx *exec_ctx, - grpc_fd *fd); - - void (*pollset_init)(grpc_pollset *pollset, gpr_mu **mu); - void (*pollset_shutdown)(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_closure *closure); - void (*pollset_destroy)(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset); - grpc_error *(*pollset_work)(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker **worker, + grpc_fd* (*fd_create)(int fd, const char* name); + int (*fd_wrapped_fd)(grpc_fd* fd); + void (*fd_orphan)(grpc_exec_ctx* exec_ctx, grpc_fd* fd, grpc_closure* on_done, + int* release_fd, bool already_closed, const char* reason); + void (*fd_shutdown)(grpc_exec_ctx* exec_ctx, grpc_fd* fd, grpc_error* why); + void (*fd_notify_on_read)(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* closure); + void (*fd_notify_on_write)(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* closure); + bool (*fd_is_shutdown)(grpc_fd* fd); + grpc_pollset* (*fd_get_read_notifier_pollset)(grpc_exec_ctx* exec_ctx, + grpc_fd* fd); + + void (*pollset_init)(grpc_pollset* pollset, gpr_mu** mu); + void (*pollset_shutdown)(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_closure* closure); + void (*pollset_destroy)(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset); + grpc_error* (*pollset_work)(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker** worker, grpc_millis deadline); - grpc_error *(*pollset_kick)(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker *specific_worker); - void (*pollset_add_fd)(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - struct grpc_fd *fd); - - grpc_pollset_set *(*pollset_set_create)(void); - void (*pollset_set_destroy)(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set); - void (*pollset_set_add_pollset)(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, - grpc_pollset *pollset); - void (*pollset_set_del_pollset)(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, - grpc_pollset *pollset); - void (*pollset_set_add_pollset_set)(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *bag, - grpc_pollset_set *item); - void (*pollset_set_del_pollset_set)(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *bag, - grpc_pollset_set *item); - void (*pollset_set_add_fd)(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, grpc_fd *fd); - void (*pollset_set_del_fd)(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, grpc_fd *fd); + grpc_error* (*pollset_kick)(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker* specific_worker); + void (*pollset_add_fd)(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + struct grpc_fd* fd); + + grpc_pollset_set* (*pollset_set_create)(void); + void (*pollset_set_destroy)(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set); + void (*pollset_set_add_pollset)(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, + grpc_pollset* pollset); + void (*pollset_set_del_pollset)(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, + grpc_pollset* pollset); + void (*pollset_set_add_pollset_set)(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* bag, + grpc_pollset_set* item); + void (*pollset_set_del_pollset_set)(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* bag, + grpc_pollset_set* item); + void (*pollset_set_add_fd)(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, grpc_fd* fd); + void (*pollset_set_del_fd)(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, grpc_fd* fd); void (*shutdown_engine)(void); } grpc_event_engine_vtable; @@ -90,15 +86,15 @@ void grpc_event_engine_init(void); void grpc_event_engine_shutdown(void); /* Return the name of the poll strategy */ -const char *grpc_get_poll_strategy_name(); +const char* grpc_get_poll_strategy_name(); /* Create a wrapped file descriptor. Requires fd is a non-blocking file descriptor. This takes ownership of closing fd. */ -grpc_fd *grpc_fd_create(int fd, const char *name); +grpc_fd* grpc_fd_create(int fd, const char* name); /* Return the wrapped fd, or -1 if it has been released or closed. */ -int grpc_fd_wrapped_fd(grpc_fd *fd); +int grpc_fd_wrapped_fd(grpc_fd* fd); /* Releases fd to be asynchronously destroyed. on_done is called when the underlying file descriptor is definitely close()d. @@ -107,14 +103,14 @@ int grpc_fd_wrapped_fd(grpc_fd *fd); Requires: *fd initialized; no outstanding notify_on_read or notify_on_write. MUST NOT be called with a pollset lock taken */ -void grpc_fd_orphan(grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_closure *on_done, - int *release_fd, bool already_closed, const char *reason); +void grpc_fd_orphan(grpc_exec_ctx* exec_ctx, grpc_fd* fd, grpc_closure* on_done, + int* release_fd, bool already_closed, const char* reason); /* Has grpc_fd_shutdown been called on an fd? */ -bool grpc_fd_is_shutdown(grpc_fd *fd); +bool grpc_fd_is_shutdown(grpc_fd* fd); /* Cause any current and future callbacks to fail. */ -void grpc_fd_shutdown(grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_error *why); +void grpc_fd_shutdown(grpc_exec_ctx* exec_ctx, grpc_fd* fd, grpc_error* why); /* Register read interest, causing read_cb to be called once when fd becomes readable, on deadline specified by deadline, or on shutdown triggered by @@ -129,41 +125,37 @@ void grpc_fd_shutdown(grpc_exec_ctx *exec_ctx, grpc_fd *fd, grpc_error *why); underlying platform. This means that users must drain fd in read_cb before calling notify_on_read again. Users are also expected to handle spurious events, i.e read_cb is called while nothing can be readable from fd */ -void grpc_fd_notify_on_read(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *closure); +void grpc_fd_notify_on_read(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* closure); /* Exactly the same semantics as above, except based on writable events. */ -void grpc_fd_notify_on_write(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - grpc_closure *closure); +void grpc_fd_notify_on_write(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + grpc_closure* closure); /* Return the read notifier pollset from the fd */ -grpc_pollset *grpc_fd_get_read_notifier_pollset(grpc_exec_ctx *exec_ctx, - grpc_fd *fd); +grpc_pollset* grpc_fd_get_read_notifier_pollset(grpc_exec_ctx* exec_ctx, + grpc_fd* fd); /* pollset_posix functions */ /* Add an fd to a pollset */ -void grpc_pollset_add_fd(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - struct grpc_fd *fd); +void grpc_pollset_add_fd(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + struct grpc_fd* fd); /* pollset_set_posix functions */ -void grpc_pollset_set_add_fd(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, grpc_fd *fd); -void grpc_pollset_set_del_fd(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, grpc_fd *fd); +void grpc_pollset_set_add_fd(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, grpc_fd* fd); +void grpc_pollset_set_del_fd(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, grpc_fd* fd); /* override to allow tests to hook poll() usage */ -typedef int (*grpc_poll_function_type)(struct pollfd *, nfds_t, int); +typedef int (*grpc_poll_function_type)(struct pollfd*, nfds_t, int); extern grpc_poll_function_type grpc_poll_function; /* WARNING: The following two functions should be used for testing purposes * ONLY */ -void grpc_set_event_engine_test_only(const grpc_event_engine_vtable *); -const grpc_event_engine_vtable *grpc_get_event_engine_test_only(); - -#ifdef __cplusplus -} -#endif +void grpc_set_event_engine_test_only(const grpc_event_engine_vtable*); +const grpc_event_engine_vtable* grpc_get_event_engine_test_only(); #endif /* GRPC_CORE_LIB_IOMGR_EV_POSIX_H */ diff --git a/src/core/lib/iomgr/ev_windows.cc b/src/core/lib/iomgr/ev_windows.cc index c24dfaeaf7c..697697d0b00 100644 --- a/src/core/lib/iomgr/ev_windows.cc +++ b/src/core/lib/iomgr/ev_windows.cc @@ -22,7 +22,7 @@ #include "src/core/lib/debug/trace.h" -grpc_tracer_flag grpc_polling_trace = - GRPC_TRACER_INITIALIZER(false, "polling"); /* Disabled by default */ +grpc_core::TraceFlag grpc_polling_trace(false, + "polling"); /* Disabled by default */ #endif // GRPC_WINSOCK_SOCKET diff --git a/src/core/lib/iomgr/exec_ctx.cc b/src/core/lib/iomgr/exec_ctx.cc index 0394a00f3e3..17774563421 100644 --- a/src/core/lib/iomgr/exec_ctx.cc +++ b/src/core/lib/iomgr/exec_ctx.cc @@ -25,7 +25,7 @@ #include "src/core/lib/iomgr/combiner.h" #include "src/core/lib/profiling/timers.h" -bool grpc_exec_ctx_ready_to_finish(grpc_exec_ctx *exec_ctx) { +bool grpc_exec_ctx_ready_to_finish(grpc_exec_ctx* exec_ctx) { if ((exec_ctx->flags & GRPC_EXEC_CTX_FLAG_IS_FINISHED) == 0) { if (exec_ctx->check_ready_to_finish(exec_ctx, exec_ctx->check_ready_to_finish_arg)) { @@ -38,29 +38,29 @@ bool grpc_exec_ctx_ready_to_finish(grpc_exec_ctx *exec_ctx) { } } -bool grpc_never_ready_to_finish(grpc_exec_ctx *exec_ctx, void *arg_ignored) { +bool grpc_never_ready_to_finish(grpc_exec_ctx* exec_ctx, void* arg_ignored) { return false; } -bool grpc_always_ready_to_finish(grpc_exec_ctx *exec_ctx, void *arg_ignored) { +bool grpc_always_ready_to_finish(grpc_exec_ctx* exec_ctx, void* arg_ignored) { return true; } -bool grpc_exec_ctx_has_work(grpc_exec_ctx *exec_ctx) { - return exec_ctx->active_combiner != NULL || +bool grpc_exec_ctx_has_work(grpc_exec_ctx* exec_ctx) { + return exec_ctx->active_combiner != nullptr || !grpc_closure_list_empty(exec_ctx->closure_list); } -void grpc_exec_ctx_finish(grpc_exec_ctx *exec_ctx) { +void grpc_exec_ctx_finish(grpc_exec_ctx* exec_ctx) { exec_ctx->flags |= GRPC_EXEC_CTX_FLAG_IS_FINISHED; grpc_exec_ctx_flush(exec_ctx); } -static void exec_ctx_run(grpc_exec_ctx *exec_ctx, grpc_closure *closure, - grpc_error *error) { +static void exec_ctx_run(grpc_exec_ctx* exec_ctx, grpc_closure* closure, + grpc_error* error) { #ifndef NDEBUG closure->scheduled = false; - if (GRPC_TRACER_ON(grpc_trace_closure)) { + if (grpc_trace_closure.enabled()) { gpr_log(GPR_DEBUG, "running closure %p: created [%s:%d]: %s [%s:%d]", closure, closure->file_created, closure->line_created, closure->run ? "run" : "scheduled", closure->file_initiated, @@ -69,23 +69,23 @@ static void exec_ctx_run(grpc_exec_ctx *exec_ctx, grpc_closure *closure, #endif closure->cb(exec_ctx, closure->cb_arg, error); #ifndef NDEBUG - if (GRPC_TRACER_ON(grpc_trace_closure)) { + if (grpc_trace_closure.enabled()) { gpr_log(GPR_DEBUG, "closure %p finished", closure); } #endif GRPC_ERROR_UNREF(error); } -bool grpc_exec_ctx_flush(grpc_exec_ctx *exec_ctx) { +bool grpc_exec_ctx_flush(grpc_exec_ctx* exec_ctx) { bool did_something = 0; GPR_TIMER_BEGIN("grpc_exec_ctx_flush", 0); for (;;) { if (!grpc_closure_list_empty(exec_ctx->closure_list)) { - grpc_closure *c = exec_ctx->closure_list.head; - exec_ctx->closure_list.head = exec_ctx->closure_list.tail = NULL; - while (c != NULL) { - grpc_closure *next = c->next_data.next; - grpc_error *error = c->error_data.error; + grpc_closure* c = exec_ctx->closure_list.head; + exec_ctx->closure_list.head = exec_ctx->closure_list.tail = nullptr; + while (c != nullptr) { + grpc_closure* next = c->next_data.next; + grpc_error* error = c->error_data.error; did_something = true; exec_ctx_run(exec_ctx, c, error); c = next; @@ -94,33 +94,26 @@ bool grpc_exec_ctx_flush(grpc_exec_ctx *exec_ctx) { break; } } - GPR_ASSERT(exec_ctx->active_combiner == NULL); + GPR_ASSERT(exec_ctx->active_combiner == nullptr); GPR_TIMER_END("grpc_exec_ctx_flush", 0); return did_something; } -static void exec_ctx_sched(grpc_exec_ctx *exec_ctx, grpc_closure *closure, - grpc_error *error) { +static void exec_ctx_sched(grpc_exec_ctx* exec_ctx, grpc_closure* closure, + grpc_error* error) { grpc_closure_list_append(&exec_ctx->closure_list, closure, error); } -static gpr_timespec - g_start_time[GPR_TIMESPAN + 1]; // assumes GPR_TIMESPAN is the - // last enum value in - // gpr_clock_type +static gpr_timespec g_start_time; void grpc_exec_ctx_global_init(void) { - for (int i = 0; i < GPR_TIMESPAN; i++) { - g_start_time[i] = gpr_now((gpr_clock_type)i); - } - // allows uniform treatment in conversion functions - g_start_time[GPR_TIMESPAN] = gpr_time_0(GPR_TIMESPAN); + g_start_time = gpr_now(GPR_CLOCK_MONOTONIC); } void grpc_exec_ctx_global_shutdown(void) {} static gpr_atm timespec_to_atm_round_down(gpr_timespec ts) { - ts = gpr_time_sub(ts, g_start_time[ts.clock_type]); + ts = gpr_time_sub(ts, g_start_time); double x = GPR_MS_PER_SEC * (double)ts.tv_sec + (double)ts.tv_nsec / GPR_NS_PER_MS; if (x < 0) return 0; @@ -129,7 +122,7 @@ static gpr_atm timespec_to_atm_round_down(gpr_timespec ts) { } static gpr_atm timespec_to_atm_round_up(gpr_timespec ts) { - ts = gpr_time_sub(ts, g_start_time[ts.clock_type]); + ts = gpr_time_sub(ts, g_start_time); double x = GPR_MS_PER_SEC * (double)ts.tv_sec + (double)ts.tv_nsec / GPR_NS_PER_MS + (double)(GPR_NS_PER_SEC - 1) / (double)GPR_NS_PER_SEC; @@ -138,7 +131,7 @@ static gpr_atm timespec_to_atm_round_up(gpr_timespec ts) { return (gpr_atm)x; } -grpc_millis grpc_exec_ctx_now(grpc_exec_ctx *exec_ctx) { +grpc_millis grpc_exec_ctx_now(grpc_exec_ctx* exec_ctx) { if (!exec_ctx->now_is_valid) { exec_ctx->now = timespec_to_atm_round_down(gpr_now(GPR_CLOCK_MONOTONIC)); exec_ctx->now_is_valid = true; @@ -146,7 +139,7 @@ grpc_millis grpc_exec_ctx_now(grpc_exec_ctx *exec_ctx) { return exec_ctx->now; } -void grpc_exec_ctx_invalidate_now(grpc_exec_ctx *exec_ctx) { +void grpc_exec_ctx_invalidate_now(grpc_exec_ctx* exec_ctx) { exec_ctx->now_is_valid = false; } @@ -164,19 +157,21 @@ gpr_timespec grpc_millis_to_timespec(grpc_millis millis, if (clock_type == GPR_TIMESPAN) { return gpr_time_from_millis(millis, GPR_TIMESPAN); } - return gpr_time_add(g_start_time[clock_type], + return gpr_time_add(gpr_convert_clock_type(g_start_time, clock_type), gpr_time_from_millis(millis, GPR_TIMESPAN)); } grpc_millis grpc_timespec_to_millis_round_down(gpr_timespec ts) { - return timespec_to_atm_round_down(ts); + return timespec_to_atm_round_down( + gpr_convert_clock_type(ts, g_start_time.clock_type)); } grpc_millis grpc_timespec_to_millis_round_up(gpr_timespec ts) { - return timespec_to_atm_round_up(ts); + return timespec_to_atm_round_up( + gpr_convert_clock_type(ts, g_start_time.clock_type)); } static const grpc_closure_scheduler_vtable exec_ctx_scheduler_vtable = { exec_ctx_run, exec_ctx_sched, "exec_ctx"}; static grpc_closure_scheduler exec_ctx_scheduler = {&exec_ctx_scheduler_vtable}; -grpc_closure_scheduler *grpc_schedule_on_exec_ctx = &exec_ctx_scheduler; +grpc_closure_scheduler* grpc_schedule_on_exec_ctx = &exec_ctx_scheduler; diff --git a/src/core/lib/iomgr/exec_ctx.h b/src/core/lib/iomgr/exec_ctx.h index 44b9be7aa99..b415d2c2556 100644 --- a/src/core/lib/iomgr/exec_ctx.h +++ b/src/core/lib/iomgr/exec_ctx.h @@ -24,10 +24,6 @@ #include "src/core/lib/iomgr/closure.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef gpr_atm grpc_millis; #define GRPC_MILLIS_INF_FUTURE GPR_ATM_MAX @@ -68,13 +64,13 @@ typedef struct grpc_combiner grpc_combiner; struct grpc_exec_ctx { grpc_closure_list closure_list; /** currently active combiner: updated only via combiner.c */ - grpc_combiner *active_combiner; + grpc_combiner* active_combiner; /** last active combiner in the active combiner list */ - grpc_combiner *last_combiner; + grpc_combiner* last_combiner; uintptr_t flags; unsigned starting_cpu; - void *check_ready_to_finish_arg; - bool (*check_ready_to_finish)(grpc_exec_ctx *exec_ctx, void *arg); + void* check_ready_to_finish_arg; + bool (*check_ready_to_finish)(grpc_exec_ctx* exec_ctx, void* arg); bool now_is_valid; grpc_millis now; @@ -93,39 +89,35 @@ struct grpc_exec_ctx { #define GRPC_EXEC_CTX_INIT \ GRPC_EXEC_CTX_INITIALIZER(GRPC_EXEC_CTX_FLAG_IS_FINISHED, NULL, NULL) -extern grpc_closure_scheduler *grpc_schedule_on_exec_ctx; +extern grpc_closure_scheduler* grpc_schedule_on_exec_ctx; -bool grpc_exec_ctx_has_work(grpc_exec_ctx *exec_ctx); +bool grpc_exec_ctx_has_work(grpc_exec_ctx* exec_ctx); /** Flush any work that has been enqueued onto this grpc_exec_ctx. * Caller must guarantee that no interfering locks are held. * Returns true if work was performed, false otherwise. */ -bool grpc_exec_ctx_flush(grpc_exec_ctx *exec_ctx); +bool grpc_exec_ctx_flush(grpc_exec_ctx* exec_ctx); /** Finish any pending work for a grpc_exec_ctx. Must be called before * the instance is destroyed, or work may be lost. */ -void grpc_exec_ctx_finish(grpc_exec_ctx *exec_ctx); +void grpc_exec_ctx_finish(grpc_exec_ctx* exec_ctx); /** Returns true if we'd like to leave this execution context as soon as possible: useful for deciding whether to do something more or not depending on outside context */ -bool grpc_exec_ctx_ready_to_finish(grpc_exec_ctx *exec_ctx); +bool grpc_exec_ctx_ready_to_finish(grpc_exec_ctx* exec_ctx); /** A finish check that is never ready to finish */ -bool grpc_never_ready_to_finish(grpc_exec_ctx *exec_ctx, void *arg_ignored); +bool grpc_never_ready_to_finish(grpc_exec_ctx* exec_ctx, void* arg_ignored); /** A finish check that is always ready to finish */ -bool grpc_always_ready_to_finish(grpc_exec_ctx *exec_ctx, void *arg_ignored); +bool grpc_always_ready_to_finish(grpc_exec_ctx* exec_ctx, void* arg_ignored); void grpc_exec_ctx_global_init(void); void grpc_exec_ctx_global_init(void); void grpc_exec_ctx_global_shutdown(void); -grpc_millis grpc_exec_ctx_now(grpc_exec_ctx *exec_ctx); -void grpc_exec_ctx_invalidate_now(grpc_exec_ctx *exec_ctx); +grpc_millis grpc_exec_ctx_now(grpc_exec_ctx* exec_ctx); +void grpc_exec_ctx_invalidate_now(grpc_exec_ctx* exec_ctx); gpr_timespec grpc_millis_to_timespec(grpc_millis millis, gpr_clock_type clock); grpc_millis grpc_timespec_to_millis_round_down(gpr_timespec timespec); grpc_millis grpc_timespec_to_millis_round_up(gpr_timespec timespec); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_EXEC_CTX_H */ diff --git a/src/core/lib/iomgr/executor.cc b/src/core/lib/iomgr/executor.cc index 92c3e70301c..d8a195f0108 100644 --- a/src/core/lib/iomgr/executor.cc +++ b/src/core/lib/iomgr/executor.cc @@ -44,26 +44,25 @@ typedef struct { gpr_thd_id id; } thread_state; -static thread_state *g_thread_state; +static thread_state* g_thread_state; static size_t g_max_threads; static gpr_atm g_cur_threads; static gpr_spinlock g_adding_thread_lock = GPR_SPINLOCK_STATIC_INITIALIZER; GPR_TLS_DECL(g_this_thread_state); -static grpc_tracer_flag executor_trace = - GRPC_TRACER_INITIALIZER(false, "executor"); +grpc_core::TraceFlag executor_trace(false, "executor"); -static void executor_thread(void *arg); +static void executor_thread(void* arg); -static size_t run_closures(grpc_exec_ctx *exec_ctx, grpc_closure_list list) { +static size_t run_closures(grpc_exec_ctx* exec_ctx, grpc_closure_list list) { size_t n = 0; - grpc_closure *c = list.head; - while (c != NULL) { - grpc_closure *next = c->next_data.next; - grpc_error *error = c->error_data.error; - if (GRPC_TRACER_ON(executor_trace)) { + grpc_closure* c = list.head; + while (c != nullptr) { + grpc_closure* next = c->next_data.next; + grpc_error* error = c->error_data.error; + if (executor_trace.enabled()) { #ifndef NDEBUG gpr_log(GPR_DEBUG, "EXECUTOR: run %p [created by %s:%d]", c, c->file_created, c->line_created); @@ -88,7 +87,7 @@ bool grpc_executor_is_threaded() { return gpr_atm_no_barrier_load(&g_cur_threads) > 0; } -void grpc_executor_set_threading(grpc_exec_ctx *exec_ctx, bool threading) { +void grpc_executor_set_threading(grpc_exec_ctx* exec_ctx, bool threading) { gpr_atm cur_threads = gpr_atm_no_barrier_load(&g_cur_threads); if (threading) { if (cur_threads > 0) return; @@ -96,7 +95,7 @@ void grpc_executor_set_threading(grpc_exec_ctx *exec_ctx, bool threading) { gpr_atm_no_barrier_store(&g_cur_threads, 1); gpr_tls_init(&g_this_thread_state); g_thread_state = - (thread_state *)gpr_zalloc(sizeof(thread_state) * g_max_threads); + (thread_state*)gpr_zalloc(sizeof(thread_state) * g_max_threads); for (size_t i = 0; i < g_max_threads; i++) { gpr_mu_init(&g_thread_state[i].mu); gpr_cv_init(&g_thread_state[i].cv); @@ -133,26 +132,25 @@ void grpc_executor_set_threading(grpc_exec_ctx *exec_ctx, bool threading) { } } -void grpc_executor_init(grpc_exec_ctx *exec_ctx) { - grpc_register_tracer(&executor_trace); +void grpc_executor_init(grpc_exec_ctx* exec_ctx) { gpr_atm_no_barrier_store(&g_cur_threads, 0); grpc_executor_set_threading(exec_ctx, true); } -void grpc_executor_shutdown(grpc_exec_ctx *exec_ctx) { +void grpc_executor_shutdown(grpc_exec_ctx* exec_ctx) { grpc_executor_set_threading(exec_ctx, false); } -static void executor_thread(void *arg) { - thread_state *ts = (thread_state *)arg; +static void executor_thread(void* arg) { + thread_state* ts = (thread_state*)arg; gpr_tls_set(&g_this_thread_state, (intptr_t)ts); grpc_exec_ctx exec_ctx = - GRPC_EXEC_CTX_INITIALIZER(0, grpc_never_ready_to_finish, NULL); + GRPC_EXEC_CTX_INITIALIZER(0, grpc_never_ready_to_finish, nullptr); size_t subtract_depth = 0; for (;;) { - if (GRPC_TRACER_ON(executor_trace)) { + if (executor_trace.enabled()) { gpr_log(GPR_DEBUG, "EXECUTOR[%d]: step (sub_depth=%" PRIdPTR ")", (int)(ts - g_thread_state), subtract_depth); } @@ -163,7 +161,7 @@ static void executor_thread(void *arg) { gpr_cv_wait(&ts->cv, &ts->mu, gpr_inf_future(GPR_CLOCK_REALTIME)); } if (ts->shutdown) { - if (GRPC_TRACER_ON(executor_trace)) { + if (executor_trace.enabled()) { gpr_log(GPR_DEBUG, "EXECUTOR[%d]: shutdown", (int)(ts - g_thread_state)); } @@ -174,7 +172,7 @@ static void executor_thread(void *arg) { grpc_closure_list exec = ts->elems; ts->elems = GRPC_CLOSURE_LIST_INIT; gpr_mu_unlock(&ts->mu); - if (GRPC_TRACER_ON(executor_trace)) { + if (executor_trace.enabled()) { gpr_log(GPR_DEBUG, "EXECUTOR[%d]: execute", (int)(ts - g_thread_state)); } @@ -184,8 +182,8 @@ static void executor_thread(void *arg) { grpc_exec_ctx_finish(&exec_ctx); } -static void executor_push(grpc_exec_ctx *exec_ctx, grpc_closure *closure, - grpc_error *error, bool is_short) { +static void executor_push(grpc_exec_ctx* exec_ctx, grpc_closure* closure, + grpc_error* error, bool is_short) { bool retry_push; if (is_short) { GRPC_STATS_INC_EXECUTOR_SCHEDULED_SHORT_ITEMS(exec_ctx); @@ -196,7 +194,7 @@ static void executor_push(grpc_exec_ctx *exec_ctx, grpc_closure *closure, retry_push = false; size_t cur_thread_count = (size_t)gpr_atm_no_barrier_load(&g_cur_threads); if (cur_thread_count == 0) { - if (GRPC_TRACER_ON(executor_trace)) { + if (executor_trace.enabled()) { #ifndef NDEBUG gpr_log(GPR_DEBUG, "EXECUTOR: schedule %p (created %s:%d) inline", closure, closure->file_created, closure->line_created); @@ -207,17 +205,17 @@ static void executor_push(grpc_exec_ctx *exec_ctx, grpc_closure *closure, grpc_closure_list_append(&exec_ctx->closure_list, closure, error); return; } - thread_state *ts = (thread_state *)gpr_tls_get(&g_this_thread_state); - if (ts == NULL) { + thread_state* ts = (thread_state*)gpr_tls_get(&g_this_thread_state); + if (ts == nullptr) { ts = &g_thread_state[GPR_HASH_POINTER(exec_ctx, cur_thread_count)]; } else { GRPC_STATS_INC_EXECUTOR_SCHEDULED_TO_SELF(exec_ctx); } - thread_state *orig_ts = ts; + thread_state* orig_ts = ts; bool try_new_thread; for (;;) { - if (GRPC_TRACER_ON(executor_trace)) { + if (executor_trace.enabled()) { #ifndef NDEBUG gpr_log( GPR_DEBUG, @@ -276,13 +274,13 @@ static void executor_push(grpc_exec_ctx *exec_ctx, grpc_closure *closure, } while (retry_push); } -static void executor_push_short(grpc_exec_ctx *exec_ctx, grpc_closure *closure, - grpc_error *error) { +static void executor_push_short(grpc_exec_ctx* exec_ctx, grpc_closure* closure, + grpc_error* error) { executor_push(exec_ctx, closure, error, true); } -static void executor_push_long(grpc_exec_ctx *exec_ctx, grpc_closure *closure, - grpc_error *error) { +static void executor_push_long(grpc_exec_ctx* exec_ctx, grpc_closure* closure, + grpc_error* error) { executor_push(exec_ctx, closure, error, false); } @@ -295,7 +293,7 @@ static const grpc_closure_scheduler_vtable executor_vtable_long = { executor_push_long, executor_push_long, "executor"}; static grpc_closure_scheduler executor_scheduler_long = {&executor_vtable_long}; -grpc_closure_scheduler *grpc_executor_scheduler( +grpc_closure_scheduler* grpc_executor_scheduler( grpc_executor_job_length length) { return length == GRPC_EXECUTOR_SHORT ? &executor_scheduler_short : &executor_scheduler_long; diff --git a/src/core/lib/iomgr/executor.h b/src/core/lib/iomgr/executor.h index ef5ac56c832..d349083eebe 100644 --- a/src/core/lib/iomgr/executor.h +++ b/src/core/lib/iomgr/executor.h @@ -21,10 +21,6 @@ #include "src/core/lib/iomgr/closure.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef enum { GRPC_EXECUTOR_SHORT, GRPC_EXECUTOR_LONG @@ -35,22 +31,18 @@ typedef enum { * This mechanism is meant to outsource work (grpc_closure instances) to a * thread, for those cases where blocking isn't an option but there isn't a * non-blocking solution available. */ -void grpc_executor_init(grpc_exec_ctx *exec_ctx); +void grpc_executor_init(grpc_exec_ctx* exec_ctx); -grpc_closure_scheduler *grpc_executor_scheduler(grpc_executor_job_length); +grpc_closure_scheduler* grpc_executor_scheduler(grpc_executor_job_length); /** Shutdown the executor, running all pending work as part of the call */ -void grpc_executor_shutdown(grpc_exec_ctx *exec_ctx); +void grpc_executor_shutdown(grpc_exec_ctx* exec_ctx); /** Is the executor multi-threaded? */ bool grpc_executor_is_threaded(); /* enable/disable threading - must be called after grpc_executor_init and before grpc_executor_shutdown */ -void grpc_executor_set_threading(grpc_exec_ctx *exec_ctx, bool enable); - -#ifdef __cplusplus -} -#endif +void grpc_executor_set_threading(grpc_exec_ctx* exec_ctx, bool enable); #endif /* GRPC_CORE_LIB_IOMGR_EXECUTOR_H */ diff --git a/src/core/lib/iomgr/fork_posix.cc b/src/core/lib/iomgr/fork_posix.cc new file mode 100644 index 00000000000..f3cfd141b6a --- /dev/null +++ b/src/core/lib/iomgr/fork_posix.cc @@ -0,0 +1,90 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include "src/core/lib/iomgr/port.h" + +#ifdef GRPC_POSIX_FORK + +#include + +#include +#include +#include +#include + +#include "src/core/lib/iomgr/ev_posix.h" +#include "src/core/lib/iomgr/executor.h" +#include "src/core/lib/iomgr/timer_manager.h" +#include "src/core/lib/iomgr/wakeup_fd_posix.h" +#include "src/core/lib/support/env.h" +#include "src/core/lib/support/fork.h" +#include "src/core/lib/support/thd_internal.h" +#include "src/core/lib/surface/init.h" + +/* + * NOTE: FORKING IS NOT GENERALLY SUPPORTED, THIS IS ONLY INTENDED TO WORK + * AROUND VERY SPECIFIC USE CASES. + */ + +void grpc_prefork() { + if (!grpc_fork_support_enabled()) { + gpr_log(GPR_ERROR, + "Fork support not enabled; try running with the " + "environment variable GRPC_ENABLE_FORK_SUPPORT=1"); + return; + } + if (grpc_is_initialized()) { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_timer_manager_set_threading(false); + grpc_executor_set_threading(&exec_ctx, false); + grpc_exec_ctx_finish(&exec_ctx); + if (!gpr_await_threads( + gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), + gpr_time_from_seconds(3, GPR_TIMESPAN)))) { + gpr_log(GPR_ERROR, "gRPC thread still active! Cannot fork!"); + } + } +} + +void grpc_postfork_parent() { + if (grpc_is_initialized()) { + grpc_timer_manager_set_threading(true); + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_executor_set_threading(&exec_ctx, true); + grpc_exec_ctx_finish(&exec_ctx); + } +} + +void grpc_postfork_child() { + if (grpc_is_initialized()) { + grpc_timer_manager_set_threading(true); + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_executor_set_threading(&exec_ctx, true); + grpc_exec_ctx_finish(&exec_ctx); + } +} + +void grpc_fork_handlers_auto_register() { + if (grpc_fork_support_enabled()) { +#ifdef GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK + pthread_atfork(grpc_prefork, grpc_postfork_parent, grpc_postfork_child); +#endif // GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK + } +} + +#endif // GRPC_POSIX_FORK diff --git a/src/node/tools/index.js b/src/core/lib/iomgr/fork_windows.cc similarity index 54% rename from src/node/tools/index.js rename to src/core/lib/iomgr/fork_windows.cc index b81d625dfef..f9986f33c75 100644 --- a/src/node/tools/index.js +++ b/src/core/lib/iomgr/fork_windows.cc @@ -1,6 +1,6 @@ /* * - * Copyright 2015 gRPC authors. + * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,24 @@ * */ -'use strict'; +#include "src/core/lib/iomgr/port.h" -/** - * package.json requires this file to be present. In the future, this can - * export useful information about the included tools. +#ifndef GRPC_POSIX_FORK + +#include +#include + +/* + * NOTE: FORKING IS NOT GENERALLY SUPPORTED, THIS IS ONLY INTENDED TO WORK + * AROUND VERY SPECIFIC USE CASES. */ -module.exports = {}; +void grpc_prefork() { gpr_log(GPR_ERROR, "Forking not supported on Windows"); } + +void grpc_postfork_parent() {} + +void grpc_postfork_child() {} + +void grpc_fork_handlers_auto_register() {} + +#endif // GRPC_POSIX_FORK diff --git a/src/core/lib/iomgr/gethostname.h b/src/core/lib/iomgr/gethostname.h index f335fea586d..9f10b4afa78 100644 --- a/src/core/lib/iomgr/gethostname.h +++ b/src/core/lib/iomgr/gethostname.h @@ -19,16 +19,8 @@ #ifndef GRPC_CORE_LIB_IOMGR_GETHOSTNAME_H #define GRPC_CORE_LIB_IOMGR_GETHOSTNAME_H -#ifdef __cplusplus -extern "C" { -#endif - // Returns the hostname of the local machine. // Caller takes ownership of result. -char *grpc_gethostname(); - -#ifdef __cplusplus -} -#endif +char* grpc_gethostname(); #endif /* GRPC_CORE_LIB_IOMGR_GETHOSTNAME_H */ diff --git a/src/core/lib/iomgr/gethostname_fallback.cc b/src/core/lib/iomgr/gethostname_fallback.cc index e6f4c2f7607..81e2c7aeec0 100644 --- a/src/core/lib/iomgr/gethostname_fallback.cc +++ b/src/core/lib/iomgr/gethostname_fallback.cc @@ -23,6 +23,6 @@ #include -char *grpc_gethostname() { return NULL; } +char* grpc_gethostname() { return NULL; } #endif // GRPC_GETHOSTNAME_FALLBACK diff --git a/src/core/lib/iomgr/gethostname_host_name_max.cc b/src/core/lib/iomgr/gethostname_host_name_max.cc index cdaf097c3ef..24871609165 100644 --- a/src/core/lib/iomgr/gethostname_host_name_max.cc +++ b/src/core/lib/iomgr/gethostname_host_name_max.cc @@ -26,11 +26,11 @@ #include -char *grpc_gethostname() { - char *hostname = (char *)gpr_malloc(HOST_NAME_MAX); +char* grpc_gethostname() { + char* hostname = (char*)gpr_malloc(HOST_NAME_MAX); if (gethostname(hostname, HOST_NAME_MAX) != 0) { gpr_free(hostname); - return NULL; + return nullptr; } return hostname; } diff --git a/src/core/lib/iomgr/gethostname_sysconf.cc b/src/core/lib/iomgr/gethostname_sysconf.cc index 8441e0615ec..e099fbd3888 100644 --- a/src/core/lib/iomgr/gethostname_sysconf.cc +++ b/src/core/lib/iomgr/gethostname_sysconf.cc @@ -25,9 +25,9 @@ #include -char *grpc_gethostname() { +char* grpc_gethostname() { size_t host_name_max = (size_t)sysconf(_SC_HOST_NAME_MAX); - char *hostname = (char *)gpr_malloc(host_name_max); + char* hostname = (char*)gpr_malloc(host_name_max); if (gethostname(hostname, host_name_max) != 0) { gpr_free(hostname); return NULL; diff --git a/src/core/lib/iomgr/iocp_windows.cc b/src/core/lib/iomgr/iocp_windows.cc index 78185cc084e..6bbe5669c7c 100644 --- a/src/core/lib/iomgr/iocp_windows.cc +++ b/src/core/lib/iomgr/iocp_windows.cc @@ -42,7 +42,7 @@ static gpr_atm g_custom_events = 0; static HANDLE g_iocp; -static DWORD deadline_to_millis_timeout(grpc_exec_ctx *exec_ctx, +static DWORD deadline_to_millis_timeout(grpc_exec_ctx* exec_ctx, grpc_millis deadline) { if (deadline == GRPC_MILLIS_INF_FUTURE) { return INFINITE; @@ -54,15 +54,15 @@ static DWORD deadline_to_millis_timeout(grpc_exec_ctx *exec_ctx, return static_cast(deadline - now); } -grpc_iocp_work_status grpc_iocp_work(grpc_exec_ctx *exec_ctx, +grpc_iocp_work_status grpc_iocp_work(grpc_exec_ctx* exec_ctx, grpc_millis deadline) { BOOL success; DWORD bytes = 0; DWORD flags = 0; ULONG_PTR completion_key; LPOVERLAPPED overlapped; - grpc_winsocket *socket; - grpc_winsocket_callback_info *info; + grpc_winsocket* socket; + grpc_winsocket_callback_info* info; GRPC_STATS_INC_SYSCALL_POLL(exec_ctx); success = GetQueuedCompletionStatus(g_iocp, &bytes, &completion_key, &overlapped, @@ -82,7 +82,7 @@ grpc_iocp_work_status grpc_iocp_work(grpc_exec_ctx *exec_ctx, abort(); } - socket = (grpc_winsocket *)completion_key; + socket = (grpc_winsocket*)completion_key; if (overlapped == &socket->write_info.overlapped) { info = &socket->write_info; } else if (overlapped == &socket->read_info.overlapped) { @@ -134,13 +134,13 @@ void grpc_iocp_shutdown(void) { GPR_ASSERT(CloseHandle(g_iocp)); } -void grpc_iocp_add_socket(grpc_winsocket *socket) { +void grpc_iocp_add_socket(grpc_winsocket* socket) { HANDLE ret; if (socket->added_to_iocp) return; ret = CreateIoCompletionPort((HANDLE)socket->socket, g_iocp, (uintptr_t)socket, 0); if (!ret) { - char *utf8_message = gpr_format_message(WSAGetLastError()); + char* utf8_message = gpr_format_message(WSAGetLastError()); gpr_log(GPR_ERROR, "Unable to add socket to iocp: %s", utf8_message); gpr_free(utf8_message); __debugbreak(); diff --git a/src/core/lib/iomgr/iocp_windows.h b/src/core/lib/iomgr/iocp_windows.h index 4efbc94645a..0e9c3481f7e 100644 --- a/src/core/lib/iomgr/iocp_windows.h +++ b/src/core/lib/iomgr/iocp_windows.h @@ -21,11 +21,11 @@ #include -#include "src/core/lib/iomgr/socket_windows.h" +#include "src/core/lib/iomgr/port.h" -#ifdef __cplusplus -extern "C" { -#endif +#ifdef GRPC_WINSOCK_SOCKET + +#include "src/core/lib/iomgr/socket_windows.h" typedef enum { GRPC_IOCP_WORK_WORK, @@ -33,16 +33,14 @@ typedef enum { GRPC_IOCP_WORK_KICK } grpc_iocp_work_status; -grpc_iocp_work_status grpc_iocp_work(grpc_exec_ctx *exec_ctx, +grpc_iocp_work_status grpc_iocp_work(grpc_exec_ctx* exec_ctx, grpc_millis deadline); void grpc_iocp_init(void); void grpc_iocp_kick(void); void grpc_iocp_flush(void); void grpc_iocp_shutdown(void); -void grpc_iocp_add_socket(grpc_winsocket *); +void grpc_iocp_add_socket(grpc_winsocket*); -#ifdef __cplusplus -} #endif #endif /* GRPC_CORE_LIB_IOMGR_IOCP_WINDOWS_H */ diff --git a/src/core/lib/iomgr/iomgr.cc b/src/core/lib/iomgr/iomgr.cc index d6a5b4a76c7..e077b35014f 100644 --- a/src/core/lib/iomgr/iomgr.cc +++ b/src/core/lib/iomgr/iomgr.cc @@ -45,7 +45,7 @@ static gpr_cv g_rcv; static int g_shutdown; static grpc_iomgr_object g_root_object; -void grpc_iomgr_init(grpc_exec_ctx *exec_ctx) { +void grpc_iomgr_init(grpc_exec_ctx* exec_ctx) { g_shutdown = 0; gpr_mu_init(&g_mu); gpr_cv_init(&g_rcv); @@ -53,15 +53,15 @@ void grpc_iomgr_init(grpc_exec_ctx *exec_ctx) { grpc_executor_init(exec_ctx); grpc_timer_list_init(exec_ctx); g_root_object.next = g_root_object.prev = &g_root_object; - g_root_object.name = (char *)"root"; + g_root_object.name = (char*)"root"; grpc_network_status_init(); grpc_iomgr_platform_init(); } -void grpc_iomgr_start(grpc_exec_ctx *exec_ctx) { grpc_timer_manager_init(); } +void grpc_iomgr_start(grpc_exec_ctx* exec_ctx) { grpc_timer_manager_init(); } static size_t count_objects(void) { - grpc_iomgr_object *obj; + grpc_iomgr_object* obj; size_t n = 0; for (obj = g_root_object.next; obj != &g_root_object; obj = obj->next) { n++; @@ -69,14 +69,14 @@ static size_t count_objects(void) { return n; } -static void dump_objects(const char *kind) { - grpc_iomgr_object *obj; +static void dump_objects(const char* kind) { + grpc_iomgr_object* obj; for (obj = g_root_object.next; obj != &g_root_object; obj = obj->next) { gpr_log(GPR_DEBUG, "%s OBJECT: %s %p", kind, obj->name, obj); } } -void grpc_iomgr_shutdown(grpc_exec_ctx *exec_ctx) { +void grpc_iomgr_shutdown(grpc_exec_ctx* exec_ctx) { gpr_timespec shutdown_deadline = gpr_time_add( gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_seconds(10, GPR_TIMESPAN)); gpr_timespec last_warning_time = gpr_now(GPR_CLOCK_REALTIME); @@ -100,7 +100,7 @@ void grpc_iomgr_shutdown(grpc_exec_ctx *exec_ctx) { } exec_ctx->now_is_valid = true; exec_ctx->now = GRPC_MILLIS_INF_FUTURE; - if (grpc_timer_check(exec_ctx, NULL) == GRPC_TIMERS_FIRED) { + if (grpc_timer_check(exec_ctx, nullptr) == GRPC_TIMERS_FIRED) { gpr_mu_unlock(&g_mu); grpc_exec_ctx_flush(exec_ctx); grpc_iomgr_platform_flush(); @@ -109,9 +109,10 @@ void grpc_iomgr_shutdown(grpc_exec_ctx *exec_ctx) { } if (g_root_object.next != &g_root_object) { if (grpc_iomgr_abort_on_leaks()) { - gpr_log(GPR_DEBUG, "Failed to free %" PRIuPTR - " iomgr objects before shutdown deadline: " - "memory leaks are likely", + gpr_log(GPR_DEBUG, + "Failed to free %" PRIuPTR + " iomgr objects before shutdown deadline: " + "memory leaks are likely", count_objects()); dump_objects("LEAKED"); abort(); @@ -121,9 +122,10 @@ void grpc_iomgr_shutdown(grpc_exec_ctx *exec_ctx) { if (gpr_cv_wait(&g_rcv, &g_mu, short_deadline)) { if (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), shutdown_deadline) > 0) { if (g_root_object.next != &g_root_object) { - gpr_log(GPR_DEBUG, "Failed to free %" PRIuPTR - " iomgr objects before shutdown deadline: " - "memory leaks are likely", + gpr_log(GPR_DEBUG, + "Failed to free %" PRIuPTR + " iomgr objects before shutdown deadline: " + "memory leaks are likely", count_objects()); dump_objects("LEAKED"); } @@ -148,7 +150,7 @@ void grpc_iomgr_shutdown(grpc_exec_ctx *exec_ctx) { gpr_cv_destroy(&g_rcv); } -void grpc_iomgr_register_object(grpc_iomgr_object *obj, const char *name) { +void grpc_iomgr_register_object(grpc_iomgr_object* obj, const char* name) { obj->name = gpr_strdup(name); gpr_mu_lock(&g_mu); obj->next = &g_root_object; @@ -157,7 +159,7 @@ void grpc_iomgr_register_object(grpc_iomgr_object *obj, const char *name) { gpr_mu_unlock(&g_mu); } -void grpc_iomgr_unregister_object(grpc_iomgr_object *obj) { +void grpc_iomgr_unregister_object(grpc_iomgr_object* obj) { gpr_mu_lock(&g_mu); obj->next->prev = obj->prev; obj->prev->next = obj->next; @@ -167,7 +169,7 @@ void grpc_iomgr_unregister_object(grpc_iomgr_object *obj) { } bool grpc_iomgr_abort_on_leaks(void) { - char *env = gpr_getenv("GRPC_ABORT_ON_LEAKS"); + char* env = gpr_getenv("GRPC_ABORT_ON_LEAKS"); bool should_we = gpr_is_true(env); gpr_free(env); return should_we; diff --git a/src/core/lib/iomgr/iomgr.h b/src/core/lib/iomgr/iomgr.h index 6c0a08b9183..2f00c0343de 100644 --- a/src/core/lib/iomgr/iomgr.h +++ b/src/core/lib/iomgr/iomgr.h @@ -22,22 +22,14 @@ #include #include "src/core/lib/iomgr/port.h" -#ifdef __cplusplus -extern "C" { -#endif - /** Initializes the iomgr. */ -void grpc_iomgr_init(grpc_exec_ctx *exec_ctx); +void grpc_iomgr_init(grpc_exec_ctx* exec_ctx); /** Starts any background threads for iomgr. */ -void grpc_iomgr_start(grpc_exec_ctx *exec_ctx); +void grpc_iomgr_start(grpc_exec_ctx* exec_ctx); /** Signals the intention to shutdown the iomgr. Expects to be able to flush * exec_ctx. */ -void grpc_iomgr_shutdown(grpc_exec_ctx *exec_ctx); - -#ifdef __cplusplus -} -#endif +void grpc_iomgr_shutdown(grpc_exec_ctx* exec_ctx); #endif /* GRPC_CORE_LIB_IOMGR_IOMGR_H */ diff --git a/src/core/lib/iomgr/iomgr_internal.h b/src/core/lib/iomgr/iomgr_internal.h index 52db37c89ae..20b3cb70d0b 100644 --- a/src/core/lib/iomgr/iomgr_internal.h +++ b/src/core/lib/iomgr/iomgr_internal.h @@ -23,18 +23,14 @@ #include "src/core/lib/iomgr/iomgr.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_iomgr_object { - char *name; - struct grpc_iomgr_object *next; - struct grpc_iomgr_object *prev; + char* name; + struct grpc_iomgr_object* next; + struct grpc_iomgr_object* prev; } grpc_iomgr_object; -void grpc_iomgr_register_object(grpc_iomgr_object *obj, const char *name); -void grpc_iomgr_unregister_object(grpc_iomgr_object *obj); +void grpc_iomgr_register_object(grpc_iomgr_object* obj, const char* name); +void grpc_iomgr_unregister_object(grpc_iomgr_object* obj); void grpc_iomgr_platform_init(void); /** flush any globally queued work from iomgr */ @@ -44,8 +40,4 @@ void grpc_iomgr_platform_shutdown(void); bool grpc_iomgr_abort_on_leaks(void); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_IOMGR_INTERNAL_H */ diff --git a/src/core/lib/iomgr/iomgr_posix.cc b/src/core/lib/iomgr/iomgr_posix.cc index f5875a247ee..f8f6fe23536 100644 --- a/src/core/lib/iomgr/iomgr_posix.cc +++ b/src/core/lib/iomgr/iomgr_posix.cc @@ -28,7 +28,6 @@ void grpc_iomgr_platform_init(void) { grpc_wakeup_fd_global_init(); grpc_event_engine_init(); - grpc_register_tracer(&grpc_tcp_trace); } void grpc_iomgr_platform_flush(void) {} diff --git a/src/core/lib/iomgr/iomgr_uv.cc b/src/core/lib/iomgr/iomgr_uv.cc index df5d23af3bb..b8a10f2ae88 100644 --- a/src/core/lib/iomgr/iomgr_uv.cc +++ b/src/core/lib/iomgr/iomgr_uv.cc @@ -31,7 +31,7 @@ gpr_thd_id g_init_thread; void grpc_iomgr_platform_init(void) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_pollset_global_init(); - grpc_register_tracer(&grpc_tcp_trace); + grpc_executor_set_threading(&exec_ctx, false); g_init_thread = gpr_thd_currentid(); grpc_exec_ctx_finish(&exec_ctx); diff --git a/src/core/lib/iomgr/iomgr_uv.h b/src/core/lib/iomgr/iomgr_uv.h index bc42ca8c1c0..3b4daaa73ba 100644 --- a/src/core/lib/iomgr/iomgr_uv.h +++ b/src/core/lib/iomgr/iomgr_uv.h @@ -23,18 +23,10 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /* The thread ID of the thread on which grpc was initialized. Used to verify * that all calls into libuv are made on that same thread */ extern gpr_thd_id g_init_thread; -#ifdef __cplusplus -} -#endif - #ifdef GRPC_UV_THREAD_CHECK #define GRPC_UV_ASSERT_SAME_THREAD() \ GPR_ASSERT(gpr_thd_currentid() == g_init_thread) diff --git a/src/core/lib/iomgr/is_epollexclusive_available.cc b/src/core/lib/iomgr/is_epollexclusive_available.cc index d08844c0dfd..e5803532e76 100644 --- a/src/core/lib/iomgr/is_epollexclusive_available.cc +++ b/src/core/lib/iomgr/is_epollexclusive_available.cc @@ -62,7 +62,7 @@ bool grpc_is_epollexclusive_available(void) { EPOLLEXCLUSIVE enabled kernels - specifically the combination of EPOLLONESHOT and EPOLLEXCLUSIVE */ ev.events = (uint32_t)(EPOLLET | EPOLLIN | EPOLLEXCLUSIVE | EPOLLONESHOT); - ev.data.ptr = NULL; + ev.data.ptr = nullptr; if (epoll_ctl(fd, EPOLL_CTL_ADD, evfd, &ev) != 0) { if (errno != EINVAL) { if (!logged_why_not) { diff --git a/src/core/lib/iomgr/load_file.cc b/src/core/lib/iomgr/load_file.cc index 5cb4099ea49..4a05de1410c 100644 --- a/src/core/lib/iomgr/load_file.cc +++ b/src/core/lib/iomgr/load_file.cc @@ -28,18 +28,18 @@ #include "src/core/lib/iomgr/block_annotate.h" #include "src/core/lib/support/string.h" -grpc_error *grpc_load_file(const char *filename, int add_null_terminator, - grpc_slice *output) { - unsigned char *contents = NULL; +grpc_error* grpc_load_file(const char* filename, int add_null_terminator, + grpc_slice* output) { + unsigned char* contents = nullptr; size_t contents_size = 0; grpc_slice result = grpc_empty_slice(); - FILE *file; + FILE* file; size_t bytes_read = 0; - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; GRPC_SCHEDULING_START_BLOCKING_REGION; file = fopen(filename, "rb"); - if (file == NULL) { + if (file == nullptr) { error = GRPC_OS_ERROR(errno, "fopen"); goto end; } @@ -47,8 +47,8 @@ grpc_error *grpc_load_file(const char *filename, int add_null_terminator, /* Converting to size_t on the assumption that it will not fail */ contents_size = (size_t)ftell(file); fseek(file, 0, SEEK_SET); - contents = (unsigned char *)gpr_malloc(contents_size + - (add_null_terminator ? 1 : 0)); + contents = + (unsigned char*)gpr_malloc(contents_size + (add_null_terminator ? 1 : 0)); bytes_read = fread(contents, 1, contents_size, file); if (bytes_read < contents_size) { error = GRPC_OS_ERROR(errno, "fread"); @@ -62,9 +62,9 @@ grpc_error *grpc_load_file(const char *filename, int add_null_terminator, end: *output = result; - if (file != NULL) fclose(file); + if (file != nullptr) fclose(file); if (error != GRPC_ERROR_NONE) { - grpc_error *error_out = + grpc_error* error_out = grpc_error_set_str(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Failed to load file", &error, 1), GRPC_ERROR_STR_FILENAME, diff --git a/src/core/lib/iomgr/load_file.h b/src/core/lib/iomgr/load_file.h index db1ffb3d63b..a7336527ce9 100644 --- a/src/core/lib/iomgr/load_file.h +++ b/src/core/lib/iomgr/load_file.h @@ -25,17 +25,9 @@ #include "src/core/lib/iomgr/error.h" -#ifdef __cplusplus -extern "C" { -#endif - /* Loads the content of a file into a slice. add_null_terminator will add a NULL terminator if non-zero. */ -grpc_error *grpc_load_file(const char *filename, int add_null_terminator, - grpc_slice *slice); - -#ifdef __cplusplus -} -#endif +grpc_error* grpc_load_file(const char* filename, int add_null_terminator, + grpc_slice* slice); #endif /* GRPC_CORE_LIB_IOMGR_LOAD_FILE_H */ diff --git a/src/core/lib/iomgr/lockfree_event.cc b/src/core/lib/iomgr/lockfree_event.cc index f967b22ba99..f0e798e8d8a 100644 --- a/src/core/lib/iomgr/lockfree_event.cc +++ b/src/core/lib/iomgr/lockfree_event.cc @@ -22,96 +22,102 @@ #include "src/core/lib/debug/trace.h" -extern grpc_tracer_flag grpc_polling_trace; +extern grpc_core::TraceFlag grpc_polling_trace; /* 'state' holds the to call when the fd is readable or writable respectively. It can contain one of the following values: - CLOSURE_READY : The fd has an I/O event of interest but there is no + kClosureReady : The fd has an I/O event of interest but there is no closure yet to execute - CLOSURE_NOT_READY : The fd has no I/O event of interest + kClosureNotReady : The fd has no I/O event of interest closure ptr : The closure to be executed when the fd has an I/O event of interest - shutdown_error | FD_SHUTDOWN_BIT : - 'shutdown_error' field ORed with FD_SHUTDOWN_BIT. + shutdown_error | kShutdownBit : + 'shutdown_error' field ORed with kShutdownBit. This indicates that the fd is shutdown. Since all memory allocations are word-aligned, the lower two bits of the shutdown_error pointer are always 0. So - it is safe to OR these with FD_SHUTDOWN_BIT + it is safe to OR these with kShutdownBit Valid state transitions: - <-----3------ CLOSURE_NOT_READY ----1----> CLOSURE_READY + <-----3------ kClosureNotReady -----1-------> kClosureReady | | ^ | ^ | | | | | | | | | | +--------------4----------+ 6 +---------2---------------+ | | | | | v | - +-----5-------> [shutdown_error | FD_SHUTDOWN_BIT] <----7---------+ + +-----5-------> [shutdown_error | kShutdownBit] <-------7---------+ - For 1, 4 : See grpc_lfev_set_ready() function - For 2, 3 : See grpc_lfev_notify_on() function - For 5,6,7: See grpc_lfev_set_shutdown() function */ + For 1, 4 : See SetReady() function + For 2, 3 : See NotifyOn() function + For 5,6,7: See SetShutdown() function */ -#define CLOSURE_NOT_READY ((gpr_atm)0) -#define CLOSURE_READY ((gpr_atm)2) +namespace grpc_core { -#define FD_SHUTDOWN_BIT ((gpr_atm)1) +LockfreeEvent::LockfreeEvent() { InitEvent(); } -void grpc_lfev_init(gpr_atm *state) { - gpr_atm_no_barrier_store(state, CLOSURE_NOT_READY); -} +void LockfreeEvent::InitEvent() { + /* Perform an atomic store to start the state machine. -void grpc_lfev_destroy(gpr_atm *state) { - gpr_atm curr = gpr_atm_no_barrier_load(state); - if (curr & FD_SHUTDOWN_BIT) { - GRPC_ERROR_UNREF((grpc_error *)(curr & ~FD_SHUTDOWN_BIT)); - } else { - GPR_ASSERT(curr == CLOSURE_NOT_READY || curr == CLOSURE_READY); - } + Note carefully that LockfreeEvent *MAY* be used whilst in a destroyed + state, while a file descriptor is on a freelist. In such a state it may + be SetReady'd, and so we need to perform an atomic operation here to + ensure no races */ + gpr_atm_no_barrier_store(&state_, kClosureNotReady); } -bool grpc_lfev_is_shutdown(gpr_atm *state) { - gpr_atm curr = gpr_atm_no_barrier_load(state); - return (curr & FD_SHUTDOWN_BIT) != 0; +void LockfreeEvent::DestroyEvent() { + gpr_atm curr; + do { + curr = gpr_atm_no_barrier_load(&state_); + if (curr & kShutdownBit) { + GRPC_ERROR_UNREF((grpc_error*)(curr & ~kShutdownBit)); + } else { + GPR_ASSERT(curr == kClosureNotReady || curr == kClosureReady); + } + /* we CAS in a shutdown, no error value here. If this event is interacted + with post-deletion (see the note in the constructor) we want the bit + pattern to prevent error retention in a deleted object */ + } while (!gpr_atm_no_barrier_cas(&state_, curr, + kShutdownBit /* shutdown, no error */)); } -void grpc_lfev_notify_on(grpc_exec_ctx *exec_ctx, gpr_atm *state, - grpc_closure *closure, const char *variable) { +void LockfreeEvent::NotifyOn(grpc_exec_ctx* exec_ctx, grpc_closure* closure) { while (true) { - gpr_atm curr = gpr_atm_no_barrier_load(state); - if (GRPC_TRACER_ON(grpc_polling_trace)) { - gpr_log(GPR_ERROR, "lfev_notify_on[%s]: %p curr=%p closure=%p", variable, - state, (void *)curr, closure); + gpr_atm curr = gpr_atm_no_barrier_load(&state_); + if (grpc_polling_trace.enabled()) { + gpr_log(GPR_ERROR, "LockfreeEvent::NotifyOn: %p curr=%p closure=%p", this, + (void*)curr, closure); } switch (curr) { - case CLOSURE_NOT_READY: { - /* CLOSURE_NOT_READY -> . + case kClosureNotReady: { + /* kClosureNotReady -> . We're guaranteed by API that there's an acquire barrier before here, so there's no need to double-dip and this can be a release-only. The release itself pairs with the acquire half of a set_ready full barrier. */ - if (gpr_atm_rel_cas(state, CLOSURE_NOT_READY, (gpr_atm)closure)) { + if (gpr_atm_rel_cas(&state_, kClosureNotReady, (gpr_atm)closure)) { return; /* Successful. Return */ } break; /* retry */ } - case CLOSURE_READY: { - /* Change the state to CLOSURE_NOT_READY. Schedule the closure if + case kClosureReady: { + /* Change the state to kClosureNotReady. Schedule the closure if successful. If not, the state most likely transitioned to shutdown. We should retry. This can be a no-barrier cas since the state is being transitioned to - CLOSURE_NOT_READY; set_ready and set_shutdown do not schedule any + kClosureNotReady; set_ready and set_shutdown do not schedule any closure when transitioning out of CLOSURE_NO_READY state (i.e there is no other code that needs to 'happen-after' this) */ - if (gpr_atm_no_barrier_cas(state, CLOSURE_READY, CLOSURE_NOT_READY)) { + if (gpr_atm_no_barrier_cas(&state_, kClosureReady, kClosureNotReady)) { GRPC_CLOSURE_SCHED(exec_ctx, closure, GRPC_ERROR_NONE); return; /* Successful. Return */ } @@ -123,8 +129,8 @@ void grpc_lfev_notify_on(grpc_exec_ctx *exec_ctx, gpr_atm *state, /* 'curr' is either a closure or the fd is shutdown(in which case 'curr' contains a pointer to the shutdown-error). If the fd is shutdown, schedule the closure with the shutdown error */ - if ((curr & FD_SHUTDOWN_BIT) > 0) { - grpc_error *shutdown_err = (grpc_error *)(curr & ~FD_SHUTDOWN_BIT); + if ((curr & kShutdownBit) > 0) { + grpc_error* shutdown_err = (grpc_error*)(curr & ~kShutdownBit); GRPC_CLOSURE_SCHED(exec_ctx, closure, GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "FD Shutdown", &shutdown_err, 1)); @@ -133,7 +139,8 @@ void grpc_lfev_notify_on(grpc_exec_ctx *exec_ctx, gpr_atm *state, /* There is already a closure!. This indicates a bug in the code */ gpr_log(GPR_ERROR, - "notify_on called with a previous callback still pending"); + "LockfreeEvent::NotifyOn: notify_on called with a previous " + "callback still pending"); abort(); } } @@ -142,22 +149,22 @@ void grpc_lfev_notify_on(grpc_exec_ctx *exec_ctx, gpr_atm *state, GPR_UNREACHABLE_CODE(return ); } -bool grpc_lfev_set_shutdown(grpc_exec_ctx *exec_ctx, gpr_atm *state, - grpc_error *shutdown_err) { - gpr_atm new_state = (gpr_atm)shutdown_err | FD_SHUTDOWN_BIT; +bool LockfreeEvent::SetShutdown(grpc_exec_ctx* exec_ctx, + grpc_error* shutdown_err) { + gpr_atm new_state = (gpr_atm)shutdown_err | kShutdownBit; while (true) { - gpr_atm curr = gpr_atm_no_barrier_load(state); - if (GRPC_TRACER_ON(grpc_polling_trace)) { - gpr_log(GPR_ERROR, "lfev_set_shutdown: %p curr=%p err=%s", state, - (void *)curr, grpc_error_string(shutdown_err)); + gpr_atm curr = gpr_atm_no_barrier_load(&state_); + if (grpc_polling_trace.enabled()) { + gpr_log(GPR_ERROR, "LockfreeEvent::SetShutdown: %p curr=%p err=%s", + &state_, (void*)curr, grpc_error_string(shutdown_err)); } switch (curr) { - case CLOSURE_READY: - case CLOSURE_NOT_READY: + case kClosureReady: + case kClosureNotReady: /* Need a full barrier here so that the initial load in notify_on doesn't need a barrier */ - if (gpr_atm_full_cas(state, curr, new_state)) { + if (gpr_atm_full_cas(&state_, curr, new_state)) { return true; /* early out */ } break; /* retry */ @@ -166,7 +173,7 @@ bool grpc_lfev_set_shutdown(grpc_exec_ctx *exec_ctx, gpr_atm *state, /* 'curr' is either a closure or the fd is already shutdown */ /* If fd is already shutdown, we are done */ - if ((curr & FD_SHUTDOWN_BIT) > 0) { + if ((curr & kShutdownBit) > 0) { GRPC_ERROR_UNREF(shutdown_err); return false; } @@ -176,8 +183,8 @@ bool grpc_lfev_set_shutdown(grpc_exec_ctx *exec_ctx, gpr_atm *state, Needs an acquire to pair with setting the closure (and get a happens-after on that edge), and a release to pair with anything loading the shutdown state. */ - if (gpr_atm_full_cas(state, curr, new_state)) { - GRPC_CLOSURE_SCHED(exec_ctx, (grpc_closure *)curr, + if (gpr_atm_full_cas(&state_, curr, new_state)) { + GRPC_CLOSURE_SCHED(exec_ctx, (grpc_closure*)curr, GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "FD Shutdown", &shutdown_err, 1)); return true; @@ -193,26 +200,25 @@ bool grpc_lfev_set_shutdown(grpc_exec_ctx *exec_ctx, gpr_atm *state, GPR_UNREACHABLE_CODE(return false); } -void grpc_lfev_set_ready(grpc_exec_ctx *exec_ctx, gpr_atm *state, - const char *variable) { +void LockfreeEvent::SetReady(grpc_exec_ctx* exec_ctx) { while (true) { - gpr_atm curr = gpr_atm_no_barrier_load(state); + gpr_atm curr = gpr_atm_no_barrier_load(&state_); - if (GRPC_TRACER_ON(grpc_polling_trace)) { - gpr_log(GPR_ERROR, "lfev_set_ready[%s]: %p curr=%p", variable, state, - (void *)curr); + if (grpc_polling_trace.enabled()) { + gpr_log(GPR_ERROR, "LockfreeEvent::SetReady: %p curr=%p", &state_, + (void*)curr); } switch (curr) { - case CLOSURE_READY: { + case kClosureReady: { /* Already ready. We are done here */ return; } - case CLOSURE_NOT_READY: { + case kClosureNotReady: { /* No barrier required as we're transitioning to a state that does not involve a closure */ - if (gpr_atm_no_barrier_cas(state, CLOSURE_NOT_READY, CLOSURE_READY)) { + if (gpr_atm_no_barrier_cas(&state_, kClosureNotReady, kClosureReady)) { return; /* early out */ } break; /* retry */ @@ -220,15 +226,15 @@ void grpc_lfev_set_ready(grpc_exec_ctx *exec_ctx, gpr_atm *state, default: { /* 'curr' is either a closure or the fd is shutdown */ - if ((curr & FD_SHUTDOWN_BIT) > 0) { + if ((curr & kShutdownBit) > 0) { /* The fd is shutdown. Do nothing */ return; } /* Full cas: acquire pairs with this cas' release in the event of a spurious set_ready; release pairs with this or the acquire in notify_on (or set_shutdown) */ - else if (gpr_atm_full_cas(state, curr, CLOSURE_NOT_READY)) { - GRPC_CLOSURE_SCHED(exec_ctx, (grpc_closure *)curr, GRPC_ERROR_NONE); + else if (gpr_atm_full_cas(&state_, curr, kClosureNotReady)) { + GRPC_CLOSURE_SCHED(exec_ctx, (grpc_closure*)curr, GRPC_ERROR_NONE); return; } /* else the state changed again (only possible by either a racing @@ -239,3 +245,5 @@ void grpc_lfev_set_ready(grpc_exec_ctx *exec_ctx, gpr_atm *state, } } } + +} // namespace grpc_core diff --git a/src/core/lib/iomgr/lockfree_event.h b/src/core/lib/iomgr/lockfree_event.h index 02229e569ef..aec67a3399a 100644 --- a/src/core/lib/iomgr/lockfree_event.h +++ b/src/core/lib/iomgr/lockfree_event.h @@ -25,24 +25,35 @@ #include "src/core/lib/iomgr/exec_ctx.h" -#ifdef __cplusplus -extern "C" { -#endif - -void grpc_lfev_init(gpr_atm *state); -void grpc_lfev_destroy(gpr_atm *state); -bool grpc_lfev_is_shutdown(gpr_atm *state); - -void grpc_lfev_notify_on(grpc_exec_ctx *exec_ctx, gpr_atm *state, - grpc_closure *closure, const char *variable); -/* Returns true on first successful shutdown */ -bool grpc_lfev_set_shutdown(grpc_exec_ctx *exec_ctx, gpr_atm *state, - grpc_error *shutdown_err); -void grpc_lfev_set_ready(grpc_exec_ctx *exec_ctx, gpr_atm *state, - const char *variable); - -#ifdef __cplusplus -} -#endif +namespace grpc_core { + +class LockfreeEvent { + public: + LockfreeEvent(); + + LockfreeEvent(const LockfreeEvent&) = delete; + LockfreeEvent& operator=(const LockfreeEvent&) = delete; + + // These methods are used to initialize and destroy the internal state. These + // cannot be done in constructor and destructor because SetReady may be called + // when the event is destroyed and put in a freelist. + void InitEvent(); + void DestroyEvent(); + + bool IsShutdown() const { + return (gpr_atm_no_barrier_load(&state_) & kShutdownBit) != 0; + } + + void NotifyOn(grpc_exec_ctx* exec_ctx, grpc_closure* closure); + bool SetShutdown(grpc_exec_ctx* exec_ctx, grpc_error* error); + void SetReady(grpc_exec_ctx* exec_ctx); + + private: + enum State { kClosureNotReady = 0, kClosureReady = 2, kShutdownBit = 1 }; + + gpr_atm state_; +}; + +} // namespace grpc_core #endif /* GRPC_CORE_LIB_IOMGR_LOCKFREE_EVENT_H */ diff --git a/src/core/lib/iomgr/network_status_tracker.cc b/src/core/lib/iomgr/network_status_tracker.cc index 57a7faa9f1c..73f8fbf9fb7 100644 --- a/src/core/lib/iomgr/network_status_tracker.cc +++ b/src/core/lib/iomgr/network_status_tracker.cc @@ -27,8 +27,8 @@ void grpc_network_status_init(void) { void grpc_destroy_network_status_monitor() {} -void grpc_network_status_register_endpoint(grpc_endpoint *ep) { (void)ep; } +void grpc_network_status_register_endpoint(grpc_endpoint* ep) { (void)ep; } -void grpc_network_status_unregister_endpoint(grpc_endpoint *ep) { (void)ep; } +void grpc_network_status_unregister_endpoint(grpc_endpoint* ep) { (void)ep; } void grpc_network_status_shutdown_all_endpoints() {} diff --git a/src/core/lib/iomgr/network_status_tracker.h b/src/core/lib/iomgr/network_status_tracker.h index cba38d4530f..32244d9b77a 100644 --- a/src/core/lib/iomgr/network_status_tracker.h +++ b/src/core/lib/iomgr/network_status_tracker.h @@ -20,19 +20,11 @@ #define GRPC_CORE_LIB_IOMGR_NETWORK_STATUS_TRACKER_H #include "src/core/lib/iomgr/endpoint.h" -#ifdef __cplusplus -extern "C" { -#endif - void grpc_network_status_init(void); void grpc_network_status_shutdown(void); -void grpc_network_status_register_endpoint(grpc_endpoint *ep); -void grpc_network_status_unregister_endpoint(grpc_endpoint *ep); +void grpc_network_status_register_endpoint(grpc_endpoint* ep); +void grpc_network_status_unregister_endpoint(grpc_endpoint* ep); void grpc_network_status_shutdown_all_endpoints(); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_NETWORK_STATUS_TRACKER_H */ diff --git a/src/core/lib/iomgr/polling_entity.cc b/src/core/lib/iomgr/polling_entity.cc index 8591a5518e3..0ee4ea1255b 100644 --- a/src/core/lib/iomgr/polling_entity.cc +++ b/src/core/lib/iomgr/polling_entity.cc @@ -22,7 +22,7 @@ #include "src/core/lib/iomgr/polling_entity.h" grpc_polling_entity grpc_polling_entity_create_from_pollset_set( - grpc_pollset_set *pollset_set) { + grpc_pollset_set* pollset_set) { grpc_polling_entity pollent; pollent.pollent.pollset_set = pollset_set; pollent.tag = GRPC_POLLS_POLLSET_SET; @@ -30,40 +30,40 @@ grpc_polling_entity grpc_polling_entity_create_from_pollset_set( } grpc_polling_entity grpc_polling_entity_create_from_pollset( - grpc_pollset *pollset) { + grpc_pollset* pollset) { grpc_polling_entity pollent; pollent.pollent.pollset = pollset; pollent.tag = GRPC_POLLS_POLLSET; return pollent; } -grpc_pollset *grpc_polling_entity_pollset(grpc_polling_entity *pollent) { +grpc_pollset* grpc_polling_entity_pollset(grpc_polling_entity* pollent) { if (pollent->tag == GRPC_POLLS_POLLSET) { return pollent->pollent.pollset; } - return NULL; + return nullptr; } -grpc_pollset_set *grpc_polling_entity_pollset_set( - grpc_polling_entity *pollent) { +grpc_pollset_set* grpc_polling_entity_pollset_set( + grpc_polling_entity* pollent) { if (pollent->tag == GRPC_POLLS_POLLSET_SET) { return pollent->pollent.pollset_set; } - return NULL; + return nullptr; } -bool grpc_polling_entity_is_empty(const grpc_polling_entity *pollent) { +bool grpc_polling_entity_is_empty(const grpc_polling_entity* pollent) { return pollent->tag == GRPC_POLLS_NONE; } -void grpc_polling_entity_add_to_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_polling_entity *pollent, - grpc_pollset_set *pss_dst) { +void grpc_polling_entity_add_to_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_polling_entity* pollent, + grpc_pollset_set* pss_dst) { if (pollent->tag == GRPC_POLLS_POLLSET) { - GPR_ASSERT(pollent->pollent.pollset != NULL); + GPR_ASSERT(pollent->pollent.pollset != nullptr); grpc_pollset_set_add_pollset(exec_ctx, pss_dst, pollent->pollent.pollset); } else if (pollent->tag == GRPC_POLLS_POLLSET_SET) { - GPR_ASSERT(pollent->pollent.pollset_set != NULL); + GPR_ASSERT(pollent->pollent.pollset_set != nullptr); grpc_pollset_set_add_pollset_set(exec_ctx, pss_dst, pollent->pollent.pollset_set); } else { @@ -72,14 +72,14 @@ void grpc_polling_entity_add_to_pollset_set(grpc_exec_ctx *exec_ctx, } } -void grpc_polling_entity_del_from_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_polling_entity *pollent, - grpc_pollset_set *pss_dst) { +void grpc_polling_entity_del_from_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_polling_entity* pollent, + grpc_pollset_set* pss_dst) { if (pollent->tag == GRPC_POLLS_POLLSET) { - GPR_ASSERT(pollent->pollent.pollset != NULL); + GPR_ASSERT(pollent->pollent.pollset != nullptr); grpc_pollset_set_del_pollset(exec_ctx, pss_dst, pollent->pollent.pollset); } else if (pollent->tag == GRPC_POLLS_POLLSET_SET) { - GPR_ASSERT(pollent->pollent.pollset_set != NULL); + GPR_ASSERT(pollent->pollent.pollset_set != nullptr); grpc_pollset_set_del_pollset_set(exec_ctx, pss_dst, pollent->pollent.pollset_set); } else { diff --git a/src/core/lib/iomgr/polling_entity.h b/src/core/lib/iomgr/polling_entity.h index 009f968fac4..dbe579e60d9 100644 --- a/src/core/lib/iomgr/polling_entity.h +++ b/src/core/lib/iomgr/polling_entity.h @@ -22,10 +22,6 @@ #include "src/core/lib/iomgr/pollset.h" #include "src/core/lib/iomgr/pollset_set.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef enum grpc_pollset_tag { GRPC_POLLS_NONE, GRPC_POLLS_POLLSET, @@ -38,38 +34,35 @@ typedef enum grpc_pollset_tag { typedef struct grpc_polling_entity { union { - grpc_pollset *pollset; - grpc_pollset_set *pollset_set; + grpc_pollset* pollset; + grpc_pollset_set* pollset_set; } pollent; grpc_pollset_tag tag; } grpc_polling_entity; grpc_polling_entity grpc_polling_entity_create_from_pollset_set( - grpc_pollset_set *pollset_set); + grpc_pollset_set* pollset_set); grpc_polling_entity grpc_polling_entity_create_from_pollset( - grpc_pollset *pollset); + grpc_pollset* pollset); /** If \a pollent contains a pollset, return it. Otherwise, return NULL */ -grpc_pollset *grpc_polling_entity_pollset(grpc_polling_entity *pollent); +grpc_pollset* grpc_polling_entity_pollset(grpc_polling_entity* pollent); /** If \a pollent contains a pollset_set, return it. Otherwise, return NULL */ -grpc_pollset_set *grpc_polling_entity_pollset_set(grpc_polling_entity *pollent); +grpc_pollset_set* grpc_polling_entity_pollset_set(grpc_polling_entity* pollent); -bool grpc_polling_entity_is_empty(const grpc_polling_entity *pollent); +bool grpc_polling_entity_is_empty(const grpc_polling_entity* pollent); /** Add the pollset or pollset_set in \a pollent to the destination pollset_set * \a * pss_dst */ -void grpc_polling_entity_add_to_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_polling_entity *pollent, - grpc_pollset_set *pss_dst); +void grpc_polling_entity_add_to_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_polling_entity* pollent, + grpc_pollset_set* pss_dst); /** Delete the pollset or pollset_set in \a pollent from the destination * pollset_set \a * pss_dst */ -void grpc_polling_entity_del_from_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_polling_entity *pollent, - grpc_pollset_set *pss_dst); -#ifdef __cplusplus -} -#endif +void grpc_polling_entity_del_from_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_polling_entity* pollent, + grpc_pollset_set* pss_dst); #endif /* GRPC_CORE_LIB_IOMGR_POLLING_ENTITY_H */ diff --git a/src/core/lib/iomgr/pollset.h b/src/core/lib/iomgr/pollset.h index 799fae154cf..d5d78f3101f 100644 --- a/src/core/lib/iomgr/pollset.h +++ b/src/core/lib/iomgr/pollset.h @@ -25,13 +25,7 @@ #include "src/core/lib/iomgr/exec_ctx.h" -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef NDEBUG -extern grpc_tracer_flag grpc_trace_fd_refcount; -#endif +extern grpc_core::DebugOnlyTraceFlag grpc_trace_fd_refcount; /* A grpc_pollset is a set of file descriptors that a higher level item is interested in. For example: @@ -45,12 +39,12 @@ typedef struct grpc_pollset_worker grpc_pollset_worker; size_t grpc_pollset_size(void); /* Initialize a pollset: assumes *pollset contains all zeros */ -void grpc_pollset_init(grpc_pollset *pollset, gpr_mu **mu); +void grpc_pollset_init(grpc_pollset* pollset, gpr_mu** mu); /* Begin shutting down the pollset, and call closure when done. * pollset's mutex must be held */ -void grpc_pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_closure *closure); -void grpc_pollset_destroy(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset); +void grpc_pollset_shutdown(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_closure* closure); +void grpc_pollset_destroy(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset); /* Do some work on a pollset. May involve invoking asynchronous callbacks, or actually polling file @@ -74,18 +68,14 @@ void grpc_pollset_destroy(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset); May call grpc_closure_list_run on grpc_closure_list, without holding the pollset lock */ -grpc_error *grpc_pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker **worker, +grpc_error* grpc_pollset_work(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker** worker, grpc_millis deadline) GRPC_MUST_USE_RESULT; /* Break one polling thread out of polling work for this pollset. If specific_worker is non-NULL, then kick that worker. */ -grpc_error *grpc_pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker *specific_worker) +grpc_error* grpc_pollset_kick(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker* specific_worker) GRPC_MUST_USE_RESULT; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_POLLSET_H */ diff --git a/src/core/lib/iomgr/pollset_set.h b/src/core/lib/iomgr/pollset_set.h index 5455eda02fd..089c15cc949 100644 --- a/src/core/lib/iomgr/pollset_set.h +++ b/src/core/lib/iomgr/pollset_set.h @@ -21,10 +21,6 @@ #include "src/core/lib/iomgr/pollset.h" -#ifdef __cplusplus -extern "C" { -#endif - /* A grpc_pollset_set is a set of pollsets that are interested in an action. Adding a pollset to a pollset_set automatically adds any fd's (etc) that have been registered with the set_set to that pollset. @@ -32,24 +28,20 @@ extern "C" { typedef struct grpc_pollset_set grpc_pollset_set; -grpc_pollset_set *grpc_pollset_set_create(void); -void grpc_pollset_set_destroy(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set); -void grpc_pollset_set_add_pollset(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, - grpc_pollset *pollset); -void grpc_pollset_set_del_pollset(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *pollset_set, - grpc_pollset *pollset); -void grpc_pollset_set_add_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *bag, - grpc_pollset_set *item); -void grpc_pollset_set_del_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_pollset_set *bag, - grpc_pollset_set *item); - -#ifdef __cplusplus -} -#endif +grpc_pollset_set* grpc_pollset_set_create(void); +void grpc_pollset_set_destroy(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set); +void grpc_pollset_set_add_pollset(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, + grpc_pollset* pollset); +void grpc_pollset_set_del_pollset(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* pollset_set, + grpc_pollset* pollset); +void grpc_pollset_set_add_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* bag, + grpc_pollset_set* item); +void grpc_pollset_set_del_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_pollset_set* bag, + grpc_pollset_set* item); #endif /* GRPC_CORE_LIB_IOMGR_POLLSET_SET_H */ diff --git a/src/core/lib/iomgr/pollset_uv.cc b/src/core/lib/iomgr/pollset_uv.cc index b9901bf8efd..16132f3a809 100644 --- a/src/core/lib/iomgr/pollset_uv.cc +++ b/src/core/lib/iomgr/pollset_uv.cc @@ -34,13 +34,10 @@ #include "src/core/lib/debug/trace.h" -#ifndef NDEBUG -grpc_tracer_flag grpc_trace_fd_refcount = - GRPC_TRACER_INITIALIZER(false, "fd_refcount"); -#endif +grpc_core::DebugOnlyTraceFlag grpc_trace_fd_refcount(false, "fd_refcount"); struct grpc_pollset { - uv_timer_t timer; + uv_timer_t* timer; int shutting_down; }; @@ -55,17 +52,17 @@ gpr_mu grpc_polling_mu; immediately in the next loop iteration. Note: In the future, if there is a bug that involves missing wakeups in the future, try adding a uv_async_t to kick the loop differently */ -uv_timer_t *dummy_uv_handle; +uv_timer_t* dummy_uv_handle; size_t grpc_pollset_size() { return sizeof(grpc_pollset); } -void dummy_timer_cb(uv_timer_t *handle) {} +void dummy_timer_cb(uv_timer_t* handle) {} -void dummy_handle_close_cb(uv_handle_t *handle) { gpr_free(handle); } +void dummy_handle_close_cb(uv_handle_t* handle) { gpr_free(handle); } void grpc_pollset_global_init(void) { gpr_mu_init(&grpc_polling_mu); - dummy_uv_handle = (uv_timer_t *)gpr_malloc(sizeof(uv_timer_t)); + dummy_uv_handle = (uv_timer_t*)gpr_malloc(sizeof(uv_timer_t)); uv_timer_init(uv_default_loop(), dummy_uv_handle); grpc_pollset_work_run_loop = 1; } @@ -73,22 +70,26 @@ void grpc_pollset_global_init(void) { void grpc_pollset_global_shutdown(void) { GRPC_UV_ASSERT_SAME_THREAD(); gpr_mu_destroy(&grpc_polling_mu); - uv_close((uv_handle_t *)dummy_uv_handle, dummy_handle_close_cb); + uv_close((uv_handle_t*)dummy_uv_handle, dummy_handle_close_cb); } -static void timer_run_cb(uv_timer_t *timer) {} +static void timer_run_cb(uv_timer_t* timer) {} -static void timer_close_cb(uv_handle_t *handle) { handle->data = (void *)1; } +static void timer_close_cb(uv_handle_t* handle) { + handle->data = (void*)1; + gpr_free(handle); +} -void grpc_pollset_init(grpc_pollset *pollset, gpr_mu **mu) { +void grpc_pollset_init(grpc_pollset* pollset, gpr_mu** mu) { GRPC_UV_ASSERT_SAME_THREAD(); *mu = &grpc_polling_mu; - uv_timer_init(uv_default_loop(), &pollset->timer); + pollset->timer = (uv_timer_t*)gpr_malloc(sizeof(uv_timer_t)); + uv_timer_init(uv_default_loop(), pollset->timer); pollset->shutting_down = 0; } -void grpc_pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_closure *closure) { +void grpc_pollset_shutdown(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_closure* closure) { GPR_ASSERT(!pollset->shutting_down); GRPC_UV_ASSERT_SAME_THREAD(); pollset->shutting_down = 1; @@ -102,20 +103,20 @@ void grpc_pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, GRPC_CLOSURE_SCHED(exec_ctx, closure, GRPC_ERROR_NONE); } -void grpc_pollset_destroy(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset) { +void grpc_pollset_destroy(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset) { GRPC_UV_ASSERT_SAME_THREAD(); - uv_close((uv_handle_t *)&pollset->timer, timer_close_cb); + uv_close((uv_handle_t*)pollset->timer, timer_close_cb); // timer.data is a boolean indicating that the timer has finished closing - pollset->timer.data = (void *)0; + pollset->timer->data = (void*)0; if (grpc_pollset_work_run_loop) { - while (!pollset->timer.data) { + while (!pollset->timer->data) { uv_run(uv_default_loop(), UV_RUN_NOWAIT); } } } -grpc_error *grpc_pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker **worker_hdl, +grpc_error* grpc_pollset_work(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker** worker_hdl, grpc_millis deadline) { uint64_t timeout; GRPC_UV_ASSERT_SAME_THREAD(); @@ -130,11 +131,11 @@ grpc_error *grpc_pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, /* We special-case timeout=0 so that we don't bother with the timer when the loop won't block anyway */ if (timeout > 0) { - uv_timer_start(&pollset->timer, timer_run_cb, timeout, 0); + uv_timer_start(pollset->timer, timer_run_cb, timeout, 0); /* Run until there is some I/O activity or the timer triggers. It doesn't matter which happens */ uv_run(uv_default_loop(), UV_RUN_ONCE); - uv_timer_stop(&pollset->timer); + uv_timer_stop(pollset->timer); } else { uv_run(uv_default_loop(), UV_RUN_NOWAIT); } @@ -146,8 +147,8 @@ grpc_error *grpc_pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, return GRPC_ERROR_NONE; } -grpc_error *grpc_pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker *specific_worker) { +grpc_error* grpc_pollset_kick(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker* specific_worker) { GRPC_UV_ASSERT_SAME_THREAD(); uv_timer_start(dummy_uv_handle, dummy_timer_cb, 0, 0); return GRPC_ERROR_NONE; diff --git a/src/core/lib/iomgr/pollset_uv.h b/src/core/lib/iomgr/pollset_uv.h index 5cc9faf4ff1..566c110ca6c 100644 --- a/src/core/lib/iomgr/pollset_uv.h +++ b/src/core/lib/iomgr/pollset_uv.h @@ -19,17 +19,9 @@ #ifndef GRPC_CORE_LIB_IOMGR_POLLSET_UV_H #define GRPC_CORE_LIB_IOMGR_POLLSET_UV_H -#ifdef __cplusplus -extern "C" { -#endif - extern int grpc_pollset_work_run_loop; void grpc_pollset_global_init(void); void grpc_pollset_global_shutdown(void); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_POLLSET_UV_H */ diff --git a/src/core/lib/iomgr/pollset_windows.cc b/src/core/lib/iomgr/pollset_windows.cc index bb4df83fc13..95dd7d7ddda 100644 --- a/src/core/lib/iomgr/pollset_windows.cc +++ b/src/core/lib/iomgr/pollset_windows.cc @@ -28,15 +28,12 @@ #include "src/core/lib/iomgr/pollset.h" #include "src/core/lib/iomgr/pollset_windows.h" -#define GRPC_POLLSET_KICK_BROADCAST ((grpc_pollset_worker *)1) +#define GRPC_POLLSET_KICK_BROADCAST ((grpc_pollset_worker*)1) -#ifndef NDEBUG -grpc_tracer_flag grpc_trace_fd_refcount = - GRPC_TRACER_INITIALIZER(false, "fd_refcount"); -#endif +grpc_core::DebugOnlyTraceFlag grpc_trace_fd_refcount(false, "fd_refcount"); gpr_mu grpc_polling_mu; -static grpc_pollset_worker *g_active_poller; +static grpc_pollset_worker* g_active_poller; static grpc_pollset_worker g_global_root_worker; void grpc_pollset_global_init(void) { @@ -49,22 +46,22 @@ void grpc_pollset_global_init(void) { void grpc_pollset_global_shutdown(void) { gpr_mu_destroy(&grpc_polling_mu); } -static void remove_worker(grpc_pollset_worker *worker, +static void remove_worker(grpc_pollset_worker* worker, grpc_pollset_worker_link_type type) { worker->links[type].prev->links[type].next = worker->links[type].next; worker->links[type].next->links[type].prev = worker->links[type].prev; worker->links[type].next = worker->links[type].prev = worker; } -static int has_workers(grpc_pollset_worker *root, +static int has_workers(grpc_pollset_worker* root, grpc_pollset_worker_link_type type) { return root->links[type].next != root; } -static grpc_pollset_worker *pop_front_worker( - grpc_pollset_worker *root, grpc_pollset_worker_link_type type) { +static grpc_pollset_worker* pop_front_worker( + grpc_pollset_worker* root, grpc_pollset_worker_link_type type) { if (has_workers(root, type)) { - grpc_pollset_worker *w = root->links[type].next; + grpc_pollset_worker* w = root->links[type].next; remove_worker(w, type); return w; } else { @@ -72,9 +69,9 @@ static grpc_pollset_worker *pop_front_worker( } } -static void push_front_worker(grpc_pollset_worker *root, +static void push_front_worker(grpc_pollset_worker* root, grpc_pollset_worker_link_type type, - grpc_pollset_worker *worker) { + grpc_pollset_worker* worker) { worker->links[type].prev = root; worker->links[type].next = worker->links[type].prev->links[type].next; worker->links[type].prev->links[type].next = @@ -88,15 +85,15 @@ size_t grpc_pollset_size(void) { return sizeof(grpc_pollset); } set of features for the sake of the rest of grpc. But grpc_pollset_work won't actually do any polling, and return as quickly as possible. */ -void grpc_pollset_init(grpc_pollset *pollset, gpr_mu **mu) { +void grpc_pollset_init(grpc_pollset* pollset, gpr_mu** mu) { *mu = &grpc_polling_mu; pollset->root_worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].next = pollset->root_worker.links[GRPC_POLLSET_WORKER_LINK_POLLSET].prev = &pollset->root_worker; } -void grpc_pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_closure *closure) { +void grpc_pollset_shutdown(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_closure* closure) { pollset->shutting_down = 1; grpc_pollset_kick(exec_ctx, pollset, GRPC_POLLSET_KICK_BROADCAST); if (!pollset->is_iocp_worker) { @@ -106,10 +103,10 @@ void grpc_pollset_shutdown(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, } } -void grpc_pollset_destroy(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset) {} +void grpc_pollset_destroy(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset) {} -grpc_error *grpc_pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker **worker_hdl, +grpc_error* grpc_pollset_work(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker** worker_hdl, grpc_millis deadline) { grpc_pollset_worker worker; if (worker_hdl) *worker_hdl = &worker; @@ -124,7 +121,7 @@ grpc_error *grpc_pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, gpr_cv_init(&worker.cv); if (!pollset->kicked_without_pollers && !pollset->shutting_down) { if (g_active_poller == NULL) { - grpc_pollset_worker *next_worker; + grpc_pollset_worker* next_worker; /* become poller */ pollset->is_iocp_worker = 1; g_active_poller = &worker; @@ -161,8 +158,10 @@ grpc_error *grpc_pollset_work(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, while (!worker.kicked) { if (gpr_cv_wait(&worker.cv, &grpc_polling_mu, grpc_millis_to_timespec(deadline, GPR_CLOCK_REALTIME))) { + grpc_exec_ctx_invalidate_now(exec_ctx); break; } + grpc_exec_ctx_invalidate_now(exec_ctx); } } else { pollset->kicked_without_pollers = 0; @@ -182,8 +181,8 @@ done: return GRPC_ERROR_NONE; } -grpc_error *grpc_pollset_kick(grpc_exec_ctx *exec_ctx, grpc_pollset *p, - grpc_pollset_worker *specific_worker) { +grpc_error* grpc_pollset_kick(grpc_exec_ctx* exec_ctx, grpc_pollset* p, + grpc_pollset_worker* specific_worker) { if (specific_worker != NULL) { if (specific_worker == GRPC_POLLSET_KICK_BROADCAST) { for (specific_worker = diff --git a/src/core/lib/iomgr/pollset_windows.h b/src/core/lib/iomgr/pollset_windows.h index 2479b25286d..93fe7d669ba 100644 --- a/src/core/lib/iomgr/pollset_windows.h +++ b/src/core/lib/iomgr/pollset_windows.h @@ -21,11 +21,10 @@ #include -#include "src/core/lib/iomgr/socket_windows.h" +#include "src/core/lib/iomgr/port.h" -#ifdef __cplusplus -extern "C" { -#endif +#ifdef GRPC_WINSOCK_SOCKET +#include "src/core/lib/iomgr/socket_windows.h" /* There isn't really any such thing as a pollset under Windows, due to the nature of the IO completion ports. A Windows "pollset" is merely a mutex @@ -39,8 +38,8 @@ typedef enum { } grpc_pollset_worker_link_type; typedef struct grpc_pollset_worker_link { - struct grpc_pollset_worker *next; - struct grpc_pollset_worker *prev; + struct grpc_pollset_worker* next; + struct grpc_pollset_worker* prev; } grpc_pollset_worker_link; struct grpc_pollset; @@ -49,7 +48,7 @@ typedef struct grpc_pollset grpc_pollset; typedef struct grpc_pollset_worker { gpr_cv cv; int kicked; - struct grpc_pollset *pollset; + struct grpc_pollset* pollset; grpc_pollset_worker_link links[GRPC_POLLSET_WORKER_LINK_TYPES]; } grpc_pollset_worker; @@ -58,14 +57,12 @@ struct grpc_pollset { int kicked_without_pollers; int is_iocp_worker; grpc_pollset_worker root_worker; - grpc_closure *on_shutdown; + grpc_closure* on_shutdown; }; void grpc_pollset_global_init(void); void grpc_pollset_global_shutdown(void); -#ifdef __cplusplus -} #endif #endif /* GRPC_CORE_LIB_IOMGR_POLLSET_WINDOWS_H */ diff --git a/src/core/lib/iomgr/port.h b/src/core/lib/iomgr/port.h index 1cc6d984910..9fae8c00528 100644 --- a/src/core/lib/iomgr/port.h +++ b/src/core/lib/iomgr/port.h @@ -30,6 +30,7 @@ #define GRPC_HAVE_IP_PKTINFO 1 #define GRPC_HAVE_MSG_NOSIGNAL 1 #define GRPC_HAVE_UNIX_SOCKET 1 +#define GRPC_POSIX_FORK 1 #define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1 #define GRPC_POSIX_SOCKET 1 #define GRPC_POSIX_SOCKETADDR 1 @@ -59,6 +60,7 @@ #define GRPC_HAVE_MSG_NOSIGNAL 1 #define GRPC_HAVE_UNIX_SOCKET 1 #define GRPC_LINUX_MULTIPOLL_WITH_EPOLL 1 +#define GRPC_POSIX_FORK 1 #define GRPC_POSIX_HOST_NAME_MAX 1 #define GRPC_POSIX_SOCKET 1 #define GRPC_POSIX_SOCKETADDR 1 @@ -90,6 +92,7 @@ #define GRPC_HAVE_SO_NOSIGPIPE 1 #define GRPC_HAVE_UNIX_SOCKET 1 #define GRPC_MSG_IOVLEN_TYPE int +#define GRPC_POSIX_FORK 1 #define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1 #define GRPC_POSIX_SOCKET 1 #define GRPC_POSIX_SOCKETADDR 1 @@ -103,6 +106,7 @@ #define GRPC_HAVE_IPV6_RECVPKTINFO 1 #define GRPC_HAVE_SO_NOSIGPIPE 1 #define GRPC_HAVE_UNIX_SOCKET 1 +#define GRPC_POSIX_FORK 1 #define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1 #define GRPC_POSIX_SOCKET 1 #define GRPC_POSIX_SOCKETADDR 1 diff --git a/src/core/lib/iomgr/resolve_address.h b/src/core/lib/iomgr/resolve_address.h index 5f0634299e0..5105020404b 100644 --- a/src/core/lib/iomgr/resolve_address.h +++ b/src/core/lib/iomgr/resolve_address.h @@ -25,10 +25,6 @@ #define GRPC_MAX_SOCKADDR_SIZE 128 -#ifdef __cplusplus -extern "C" { -#endif - typedef struct { char addr[GRPC_MAX_SOCKADDR_SIZE]; size_t len; @@ -36,28 +32,24 @@ typedef struct { typedef struct { size_t naddrs; - grpc_resolved_address *addrs; + grpc_resolved_address* addrs; } grpc_resolved_addresses; /* Asynchronously resolve addr. Use default_port if a port isn't designated in addr, otherwise use the port in addr. */ /* TODO(ctiller): add a timeout here */ -extern void (*grpc_resolve_address)(grpc_exec_ctx *exec_ctx, const char *addr, - const char *default_port, - grpc_pollset_set *interested_parties, - grpc_closure *on_done, - grpc_resolved_addresses **addresses); +extern void (*grpc_resolve_address)(grpc_exec_ctx* exec_ctx, const char* addr, + const char* default_port, + grpc_pollset_set* interested_parties, + grpc_closure* on_done, + grpc_resolved_addresses** addresses); /* Destroy resolved addresses */ -void grpc_resolved_addresses_destroy(grpc_resolved_addresses *addresses); +void grpc_resolved_addresses_destroy(grpc_resolved_addresses* addresses); /* Resolve addr in a blocking fashion. Returns NULL on failure. On success, result must be freed with grpc_resolved_addresses_destroy. */ -extern grpc_error *(*grpc_blocking_resolve_address)( - const char *name, const char *default_port, - grpc_resolved_addresses **addresses); - -#ifdef __cplusplus -} -#endif +extern grpc_error* (*grpc_blocking_resolve_address)( + const char* name, const char* default_port, + grpc_resolved_addresses** addresses); #endif /* GRPC_CORE_LIB_IOMGR_RESOLVE_ADDRESS_H */ diff --git a/src/core/lib/iomgr/resolve_address_posix.cc b/src/core/lib/iomgr/resolve_address_posix.cc index 1b783495dfc..fb5fa9d4226 100644 --- a/src/core/lib/iomgr/resolve_address_posix.cc +++ b/src/core/lib/iomgr/resolve_address_posix.cc @@ -39,16 +39,16 @@ #include "src/core/lib/iomgr/unix_sockets_posix.h" #include "src/core/lib/support/string.h" -static grpc_error *blocking_resolve_address_impl( - const char *name, const char *default_port, - grpc_resolved_addresses **addresses) { +static grpc_error* blocking_resolve_address_impl( + const char* name, const char* default_port, + grpc_resolved_addresses** addresses) { struct addrinfo hints; - struct addrinfo *result = NULL, *resp; - char *host; - char *port; + struct addrinfo *result = nullptr, *resp; + char* host; + char* port; int s; size_t i; - grpc_error *err; + grpc_error* err; if (name[0] == 'u' && name[1] == 'n' && name[2] == 'i' && name[3] == 'x' && name[4] == ':' && name[5] != 0) { @@ -57,14 +57,14 @@ static grpc_error *blocking_resolve_address_impl( /* parse name, splitting it into host and port parts */ gpr_split_host_port(name, &host, &port); - if (host == NULL) { + if (host == nullptr) { err = grpc_error_set_str( GRPC_ERROR_CREATE_FROM_STATIC_STRING("unparseable host:port"), GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(name)); goto done; } - if (port == NULL) { - if (default_port == NULL) { + if (port == nullptr) { + if (default_port == nullptr) { err = grpc_error_set_str( GRPC_ERROR_CREATE_FROM_STATIC_STRING("no port in name"), GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(name)); @@ -85,7 +85,7 @@ static grpc_error *blocking_resolve_address_impl( if (s != 0) { /* Retry if well-known service name is recognized */ - const char *svc[][2] = {{"http", "80"}, {"https", "443"}}; + const char* svc[][2] = {{"http", "80"}, {"https", "443"}}; for (i = 0; i < GPR_ARRAY_SIZE(svc); i++) { if (strcmp(port, svc[i][0]) == 0) { GRPC_SCHEDULING_START_BLOCKING_REGION; @@ -113,15 +113,15 @@ static grpc_error *blocking_resolve_address_impl( /* Success path: set addrs non-NULL, fill it in */ *addresses = - (grpc_resolved_addresses *)gpr_malloc(sizeof(grpc_resolved_addresses)); + (grpc_resolved_addresses*)gpr_malloc(sizeof(grpc_resolved_addresses)); (*addresses)->naddrs = 0; - for (resp = result; resp != NULL; resp = resp->ai_next) { + for (resp = result; resp != nullptr; resp = resp->ai_next) { (*addresses)->naddrs++; } - (*addresses)->addrs = (grpc_resolved_address *)gpr_malloc( + (*addresses)->addrs = (grpc_resolved_address*)gpr_malloc( sizeof(grpc_resolved_address) * (*addresses)->naddrs); i = 0; - for (resp = result; resp != NULL; resp = resp->ai_next) { + for (resp = result; resp != nullptr; resp = resp->ai_next) { memcpy(&(*addresses)->addrs[i].addr, resp->ai_addr, resp->ai_addrlen); (*addresses)->addrs[i].len = resp->ai_addrlen; i++; @@ -137,24 +137,24 @@ done: return err; } -grpc_error *(*grpc_blocking_resolve_address)( - const char *name, const char *default_port, - grpc_resolved_addresses **addresses) = blocking_resolve_address_impl; +grpc_error* (*grpc_blocking_resolve_address)( + const char* name, const char* default_port, + grpc_resolved_addresses** addresses) = blocking_resolve_address_impl; typedef struct { - char *name; - char *default_port; - grpc_closure *on_done; - grpc_resolved_addresses **addrs_out; + char* name; + char* default_port; + grpc_closure* on_done; + grpc_resolved_addresses** addrs_out; grpc_closure request_closure; - void *arg; + void* arg; } request; /* Callback to be passed to grpc_executor to asynch-ify * grpc_blocking_resolve_address */ -static void do_request_thread(grpc_exec_ctx *exec_ctx, void *rp, - grpc_error *error) { - request *r = (request *)rp; +static void do_request_thread(grpc_exec_ctx* exec_ctx, void* rp, + grpc_error* error) { + request* r = (request*)rp; GRPC_CLOSURE_SCHED( exec_ctx, r->on_done, grpc_blocking_resolve_address(r->name, r->default_port, r->addrs_out)); @@ -163,19 +163,19 @@ static void do_request_thread(grpc_exec_ctx *exec_ctx, void *rp, gpr_free(r); } -void grpc_resolved_addresses_destroy(grpc_resolved_addresses *addrs) { - if (addrs != NULL) { +void grpc_resolved_addresses_destroy(grpc_resolved_addresses* addrs) { + if (addrs != nullptr) { gpr_free(addrs->addrs); } gpr_free(addrs); } -static void resolve_address_impl(grpc_exec_ctx *exec_ctx, const char *name, - const char *default_port, - grpc_pollset_set *interested_parties, - grpc_closure *on_done, - grpc_resolved_addresses **addrs) { - request *r = (request *)gpr_malloc(sizeof(request)); +static void resolve_address_impl(grpc_exec_ctx* exec_ctx, const char* name, + const char* default_port, + grpc_pollset_set* interested_parties, + grpc_closure* on_done, + grpc_resolved_addresses** addrs) { + request* r = (request*)gpr_malloc(sizeof(request)); GRPC_CLOSURE_INIT(&r->request_closure, do_request_thread, r, grpc_executor_scheduler(GRPC_EXECUTOR_SHORT)); r->name = gpr_strdup(name); @@ -186,8 +186,8 @@ static void resolve_address_impl(grpc_exec_ctx *exec_ctx, const char *name, } void (*grpc_resolve_address)( - grpc_exec_ctx *exec_ctx, const char *name, const char *default_port, - grpc_pollset_set *interested_parties, grpc_closure *on_done, - grpc_resolved_addresses **addrs) = resolve_address_impl; + grpc_exec_ctx* exec_ctx, const char* name, const char* default_port, + grpc_pollset_set* interested_parties, grpc_closure* on_done, + grpc_resolved_addresses** addrs) = resolve_address_impl; #endif diff --git a/src/core/lib/iomgr/resolve_address_uv.cc b/src/core/lib/iomgr/resolve_address_uv.cc index 4f7f234877d..6d09fd1d022 100644 --- a/src/core/lib/iomgr/resolve_address_uv.cc +++ b/src/core/lib/iomgr/resolve_address_uv.cc @@ -38,23 +38,23 @@ #include typedef struct request { - grpc_closure *on_done; - grpc_resolved_addresses **addresses; - struct addrinfo *hints; - char *host; - char *port; + grpc_closure* on_done; + grpc_resolved_addresses** addresses; + struct addrinfo* hints; + char* host; + char* port; } request; -static int retry_named_port_failure(int status, request *r, +static int retry_named_port_failure(int status, request* r, uv_getaddrinfo_cb getaddrinfo_cb) { if (status != 0) { // This loop is copied from resolve_address_posix.c - const char *svc[][2] = {{"http", "80"}, {"https", "443"}}; + const char* svc[][2] = {{"http", "80"}, {"https", "443"}}; for (size_t i = 0; i < GPR_ARRAY_SIZE(svc); i++) { if (strcmp(r->port, svc[i][0]) == 0) { int retry_status; - uv_getaddrinfo_t *req = - (uv_getaddrinfo_t *)gpr_malloc(sizeof(uv_getaddrinfo_t)); + uv_getaddrinfo_t* req = + (uv_getaddrinfo_t*)gpr_malloc(sizeof(uv_getaddrinfo_t)); req->data = r; r->port = gpr_strdup(svc[i][1]); retry_status = uv_getaddrinfo(uv_default_loop(), req, getaddrinfo_cb, @@ -73,12 +73,12 @@ static int retry_named_port_failure(int status, request *r, return 1; } -static grpc_error *handle_addrinfo_result(int status, struct addrinfo *result, - grpc_resolved_addresses **addresses) { - struct addrinfo *resp; +static grpc_error* handle_addrinfo_result(int status, struct addrinfo* result, + grpc_resolved_addresses** addresses) { + struct addrinfo* resp; size_t i; if (status != 0) { - grpc_error *error; + grpc_error* error; *addresses = NULL; error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("getaddrinfo failed"); error = @@ -87,12 +87,12 @@ static grpc_error *handle_addrinfo_result(int status, struct addrinfo *result, return error; } (*addresses) = - (grpc_resolved_addresses *)gpr_malloc(sizeof(grpc_resolved_addresses)); + (grpc_resolved_addresses*)gpr_malloc(sizeof(grpc_resolved_addresses)); (*addresses)->naddrs = 0; for (resp = result; resp != NULL; resp = resp->ai_next) { (*addresses)->naddrs++; } - (*addresses)->addrs = (grpc_resolved_address *)gpr_malloc( + (*addresses)->addrs = (grpc_resolved_address*)gpr_malloc( sizeof(grpc_resolved_address) * (*addresses)->naddrs); i = 0; for (resp = result; resp != NULL; resp = resp->ai_next) { @@ -103,7 +103,7 @@ static grpc_error *handle_addrinfo_result(int status, struct addrinfo *result, { for (i = 0; i < (*addresses)->naddrs; i++) { - char *buf; + char* buf; grpc_sockaddr_to_string(&buf, &(*addresses)->addrs[i], 0); gpr_free(buf); } @@ -111,13 +111,13 @@ static grpc_error *handle_addrinfo_result(int status, struct addrinfo *result, return GRPC_ERROR_NONE; } -static void getaddrinfo_callback(uv_getaddrinfo_t *req, int status, - struct addrinfo *res) { - request *r = (request *)req->data; +static void getaddrinfo_callback(uv_getaddrinfo_t* req, int status, + struct addrinfo* res) { + request* r = (request*)req->data; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - grpc_error *error; + grpc_error* error; int retry_status; - char *port = r->port; + char* port = r->port; gpr_free(req); retry_status = retry_named_port_failure(status, r, getaddrinfo_callback); @@ -139,14 +139,14 @@ static void getaddrinfo_callback(uv_getaddrinfo_t *req, int status, uv_freeaddrinfo(res); } -static grpc_error *try_split_host_port(const char *name, - const char *default_port, char **host, - char **port) { +static grpc_error* try_split_host_port(const char* name, + const char* default_port, char** host, + char** port) { /* parse name, splitting it into host and port parts */ - grpc_error *error; + grpc_error* error; gpr_split_host_port(name, host, port); if (*host == NULL) { - char *msg; + char* msg; gpr_asprintf(&msg, "unparseable host:port: '%s'", name); error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); @@ -155,7 +155,7 @@ static grpc_error *try_split_host_port(const char *name, if (*port == NULL) { // TODO(murgatroid99): add tests for this case if (default_port == NULL) { - char *msg; + char* msg; gpr_asprintf(&msg, "no port in name '%s'", name); error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); @@ -166,15 +166,15 @@ static grpc_error *try_split_host_port(const char *name, return GRPC_ERROR_NONE; } -static grpc_error *blocking_resolve_address_impl( - const char *name, const char *default_port, - grpc_resolved_addresses **addresses) { - char *host; - char *port; +static grpc_error* blocking_resolve_address_impl( + const char* name, const char* default_port, + grpc_resolved_addresses** addresses) { + char* host; + char* port; struct addrinfo hints; uv_getaddrinfo_t req; int s; - grpc_error *err; + grpc_error* err; int retry_status; request r; @@ -213,28 +213,28 @@ done: return err; } -grpc_error *(*grpc_blocking_resolve_address)( - const char *name, const char *default_port, - grpc_resolved_addresses **addresses) = blocking_resolve_address_impl; +grpc_error* (*grpc_blocking_resolve_address)( + const char* name, const char* default_port, + grpc_resolved_addresses** addresses) = blocking_resolve_address_impl; -void grpc_resolved_addresses_destroy(grpc_resolved_addresses *addrs) { +void grpc_resolved_addresses_destroy(grpc_resolved_addresses* addrs) { if (addrs != NULL) { gpr_free(addrs->addrs); } gpr_free(addrs); } -static void resolve_address_impl(grpc_exec_ctx *exec_ctx, const char *name, - const char *default_port, - grpc_pollset_set *interested_parties, - grpc_closure *on_done, - grpc_resolved_addresses **addrs) { - uv_getaddrinfo_t *req = NULL; - request *r = NULL; - struct addrinfo *hints = NULL; - char *host = NULL; - char *port = NULL; - grpc_error *err; +static void resolve_address_impl(grpc_exec_ctx* exec_ctx, const char* name, + const char* default_port, + grpc_pollset_set* interested_parties, + grpc_closure* on_done, + grpc_resolved_addresses** addrs) { + uv_getaddrinfo_t* req = NULL; + request* r = NULL; + struct addrinfo* hints = NULL; + char* host = NULL; + char* port = NULL; + grpc_error* err; int s; GRPC_UV_ASSERT_SAME_THREAD(); err = try_split_host_port(name, default_port, &host, &port); @@ -244,16 +244,16 @@ static void resolve_address_impl(grpc_exec_ctx *exec_ctx, const char *name, gpr_free(port); return; } - r = (request *)gpr_malloc(sizeof(request)); + r = (request*)gpr_malloc(sizeof(request)); r->on_done = on_done; r->addresses = addrs; r->host = host; r->port = port; - req = (uv_getaddrinfo_t *)gpr_malloc(sizeof(uv_getaddrinfo_t)); + req = (uv_getaddrinfo_t*)gpr_malloc(sizeof(uv_getaddrinfo_t)); req->data = r; /* Call getaddrinfo */ - hints = (addrinfo *)gpr_malloc(sizeof(struct addrinfo)); + hints = (addrinfo*)gpr_malloc(sizeof(struct addrinfo)); memset(hints, 0, sizeof(struct addrinfo)); hints->ai_family = AF_UNSPEC; /* ipv4 or ipv6 */ hints->ai_socktype = SOCK_STREAM; /* stream socket */ @@ -278,8 +278,8 @@ static void resolve_address_impl(grpc_exec_ctx *exec_ctx, const char *name, } void (*grpc_resolve_address)( - grpc_exec_ctx *exec_ctx, const char *name, const char *default_port, - grpc_pollset_set *interested_parties, grpc_closure *on_done, - grpc_resolved_addresses **addrs) = resolve_address_impl; + grpc_exec_ctx* exec_ctx, const char* name, const char* default_port, + grpc_pollset_set* interested_parties, grpc_closure* on_done, + grpc_resolved_addresses** addrs) = resolve_address_impl; #endif /* GRPC_UV */ diff --git a/src/core/lib/iomgr/resolve_address_windows.cc b/src/core/lib/iomgr/resolve_address_windows.cc index 451f01a701e..d9fc17a9f40 100644 --- a/src/core/lib/iomgr/resolve_address_windows.cc +++ b/src/core/lib/iomgr/resolve_address_windows.cc @@ -41,28 +41,28 @@ #include "src/core/lib/support/string.h" typedef struct { - char *name; - char *default_port; + char* name; + char* default_port; grpc_closure request_closure; - grpc_closure *on_done; - grpc_resolved_addresses **addresses; + grpc_closure* on_done; + grpc_resolved_addresses** addresses; } request; -static grpc_error *blocking_resolve_address_impl( - const char *name, const char *default_port, - grpc_resolved_addresses **addresses) { +static grpc_error* blocking_resolve_address_impl( + const char* name, const char* default_port, + grpc_resolved_addresses** addresses) { struct addrinfo hints; struct addrinfo *result = NULL, *resp; - char *host; - char *port; + char* host; + char* port; int s; size_t i; - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; /* parse name, splitting it into host and port parts */ gpr_split_host_port(name, &host, &port); if (host == NULL) { - char *msg; + char* msg; gpr_asprintf(&msg, "unparseable host:port: '%s'", name); error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); @@ -70,7 +70,7 @@ static grpc_error *blocking_resolve_address_impl( } if (port == NULL) { if (default_port == NULL) { - char *msg; + char* msg; gpr_asprintf(&msg, "no port in name '%s'", name); error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); @@ -95,12 +95,12 @@ static grpc_error *blocking_resolve_address_impl( /* Success path: set addrs non-NULL, fill it in */ (*addresses) = - (grpc_resolved_addresses *)gpr_malloc(sizeof(grpc_resolved_addresses)); + (grpc_resolved_addresses*)gpr_malloc(sizeof(grpc_resolved_addresses)); (*addresses)->naddrs = 0; for (resp = result; resp != NULL; resp = resp->ai_next) { (*addresses)->naddrs++; } - (*addresses)->addrs = (grpc_resolved_address *)gpr_malloc( + (*addresses)->addrs = (grpc_resolved_address*)gpr_malloc( sizeof(grpc_resolved_address) * (*addresses)->naddrs); i = 0; for (resp = result; resp != NULL; resp = resp->ai_next) { @@ -111,7 +111,7 @@ static grpc_error *blocking_resolve_address_impl( { for (i = 0; i < (*addresses)->naddrs; i++) { - char *buf; + char* buf; grpc_sockaddr_to_string(&buf, &(*addresses)->addrs[i], 0); gpr_free(buf); } @@ -126,15 +126,15 @@ done: return error; } -grpc_error *(*grpc_blocking_resolve_address)( - const char *name, const char *default_port, - grpc_resolved_addresses **addresses) = blocking_resolve_address_impl; +grpc_error* (*grpc_blocking_resolve_address)( + const char* name, const char* default_port, + grpc_resolved_addresses** addresses) = blocking_resolve_address_impl; /* Callback to be passed to grpc_executor to asynch-ify * grpc_blocking_resolve_address */ -static void do_request_thread(grpc_exec_ctx *exec_ctx, void *rp, - grpc_error *error) { - request *r = (request *)rp; +static void do_request_thread(grpc_exec_ctx* exec_ctx, void* rp, + grpc_error* error) { + request* r = (request*)rp; if (error == GRPC_ERROR_NONE) { error = grpc_blocking_resolve_address(r->name, r->default_port, r->addresses); @@ -147,19 +147,19 @@ static void do_request_thread(grpc_exec_ctx *exec_ctx, void *rp, gpr_free(r); } -void grpc_resolved_addresses_destroy(grpc_resolved_addresses *addrs) { +void grpc_resolved_addresses_destroy(grpc_resolved_addresses* addrs) { if (addrs != NULL) { gpr_free(addrs->addrs); } gpr_free(addrs); } -static void resolve_address_impl(grpc_exec_ctx *exec_ctx, const char *name, - const char *default_port, - grpc_pollset_set *interested_parties, - grpc_closure *on_done, - grpc_resolved_addresses **addresses) { - request *r = (request *)gpr_malloc(sizeof(request)); +static void resolve_address_impl(grpc_exec_ctx* exec_ctx, const char* name, + const char* default_port, + grpc_pollset_set* interested_parties, + grpc_closure* on_done, + grpc_resolved_addresses** addresses) { + request* r = (request*)gpr_malloc(sizeof(request)); GRPC_CLOSURE_INIT(&r->request_closure, do_request_thread, r, grpc_executor_scheduler(GRPC_EXECUTOR_SHORT)); r->name = gpr_strdup(name); @@ -170,8 +170,8 @@ static void resolve_address_impl(grpc_exec_ctx *exec_ctx, const char *name, } void (*grpc_resolve_address)( - grpc_exec_ctx *exec_ctx, const char *name, const char *default_port, - grpc_pollset_set *interested_parties, grpc_closure *on_done, - grpc_resolved_addresses **addresses) = resolve_address_impl; + grpc_exec_ctx* exec_ctx, const char* name, const char* default_port, + grpc_pollset_set* interested_parties, grpc_closure* on_done, + grpc_resolved_addresses** addresses) = resolve_address_impl; #endif diff --git a/src/core/lib/iomgr/resource_quota.cc b/src/core/lib/iomgr/resource_quota.cc index ecb5747da86..ccd8d9f379c 100644 --- a/src/core/lib/iomgr/resource_quota.cc +++ b/src/core/lib/iomgr/resource_quota.cc @@ -31,15 +31,14 @@ #include "src/core/lib/iomgr/combiner.h" -grpc_tracer_flag grpc_resource_quota_trace = - GRPC_TRACER_INITIALIZER(false, "resource_quota"); +grpc_core::TraceFlag grpc_resource_quota_trace(false, "resource_quota"); #define MEMORY_USAGE_ESTIMATION_MAX 65536 /* Internal linked list pointers for a resource user */ typedef struct { - grpc_resource_user *next; - grpc_resource_user *prev; + grpc_resource_user* next; + grpc_resource_user* prev; } grpc_resource_user_link; /* Resource users are kept in (potentially) several intrusive linked lists @@ -60,7 +59,7 @@ typedef enum { struct grpc_resource_user { /* The quota this resource user consumes from */ - grpc_resource_quota *resource_quota; + grpc_resource_quota* resource_quota; /* Closure to schedule an allocation under the resource quota combiner lock */ grpc_closure allocate_closure; @@ -97,10 +96,10 @@ struct grpc_resource_user { /* Reclaimers: index 0 is the benign reclaimer, 1 is the destructive reclaimer */ - grpc_closure *reclaimers[2]; + grpc_closure* reclaimers[2]; /* Reclaimers just posted: once we're in the combiner lock, we'll move them to the array above */ - grpc_closure *new_reclaimers[2]; + grpc_closure* new_reclaimers[2]; /* Trampoline closures to finish reclamation and re-enter the quota combiner lock */ grpc_closure post_reclaimer_closure[2]; @@ -113,7 +112,7 @@ struct grpc_resource_user { grpc_resource_user_link links[GRPC_RULIST_COUNT]; /* The name of this resource user, for debugging/tracing */ - char *name; + char* name; }; struct grpc_resource_quota { @@ -126,7 +125,7 @@ struct grpc_resource_quota { /* Master combiner lock: all activity on a quota executes under this combiner * (so no mutex is needed for this data structure) */ - grpc_combiner *combiner; + grpc_combiner* combiner; /* Size of the resource quota */ int64_t size; /* Amount of free memory in the resource quota */ @@ -146,27 +145,27 @@ struct grpc_resource_quota { /* This is only really usable for debugging: it's always a stale pointer, but a stale pointer that might just be fresh enough to guide us to where the reclamation system is stuck */ - grpc_closure *debug_only_last_initiated_reclaimer; - grpc_resource_user *debug_only_last_reclaimer_resource_user; + grpc_closure* debug_only_last_initiated_reclaimer; + grpc_resource_user* debug_only_last_reclaimer_resource_user; /* Roots of all resource user lists */ - grpc_resource_user *roots[GRPC_RULIST_COUNT]; + grpc_resource_user* roots[GRPC_RULIST_COUNT]; - char *name; + char* name; }; -static void ru_unref_by(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user, gpr_atm amount); +static void ru_unref_by(grpc_exec_ctx* exec_ctx, + grpc_resource_user* resource_user, gpr_atm amount); /******************************************************************************* * list management */ -static void rulist_add_head(grpc_resource_user *resource_user, +static void rulist_add_head(grpc_resource_user* resource_user, grpc_rulist list) { - grpc_resource_quota *resource_quota = resource_user->resource_quota; - grpc_resource_user **root = &resource_quota->roots[list]; - if (*root == NULL) { + grpc_resource_quota* resource_quota = resource_user->resource_quota; + grpc_resource_user** root = &resource_quota->roots[list]; + if (*root == nullptr) { *root = resource_user; resource_user->links[list].next = resource_user->links[list].prev = resource_user; @@ -179,11 +178,11 @@ static void rulist_add_head(grpc_resource_user *resource_user, } } -static void rulist_add_tail(grpc_resource_user *resource_user, +static void rulist_add_tail(grpc_resource_user* resource_user, grpc_rulist list) { - grpc_resource_quota *resource_quota = resource_user->resource_quota; - grpc_resource_user **root = &resource_quota->roots[list]; - if (*root == NULL) { + grpc_resource_quota* resource_quota = resource_user->resource_quota; + grpc_resource_user** root = &resource_quota->roots[list]; + if (*root == nullptr) { *root = resource_user; resource_user->links[list].next = resource_user->links[list].prev = resource_user; @@ -195,20 +194,20 @@ static void rulist_add_tail(grpc_resource_user *resource_user, } } -static bool rulist_empty(grpc_resource_quota *resource_quota, +static bool rulist_empty(grpc_resource_quota* resource_quota, grpc_rulist list) { - return resource_quota->roots[list] == NULL; + return resource_quota->roots[list] == nullptr; } -static grpc_resource_user *rulist_pop_head(grpc_resource_quota *resource_quota, +static grpc_resource_user* rulist_pop_head(grpc_resource_quota* resource_quota, grpc_rulist list) { - grpc_resource_user **root = &resource_quota->roots[list]; - grpc_resource_user *resource_user = *root; - if (resource_user == NULL) { - return NULL; + grpc_resource_user** root = &resource_quota->roots[list]; + grpc_resource_user* resource_user = *root; + if (resource_user == nullptr) { + return nullptr; } if (resource_user->links[list].next == resource_user) { - *root = NULL; + *root = nullptr; } else { resource_user->links[list].next->links[list].prev = resource_user->links[list].prev; @@ -216,39 +215,39 @@ static grpc_resource_user *rulist_pop_head(grpc_resource_quota *resource_quota, resource_user->links[list].next; *root = resource_user->links[list].next; } - resource_user->links[list].next = resource_user->links[list].prev = NULL; + resource_user->links[list].next = resource_user->links[list].prev = nullptr; return resource_user; } -static void rulist_remove(grpc_resource_user *resource_user, grpc_rulist list) { - if (resource_user->links[list].next == NULL) return; - grpc_resource_quota *resource_quota = resource_user->resource_quota; +static void rulist_remove(grpc_resource_user* resource_user, grpc_rulist list) { + if (resource_user->links[list].next == nullptr) return; + grpc_resource_quota* resource_quota = resource_user->resource_quota; if (resource_quota->roots[list] == resource_user) { resource_quota->roots[list] = resource_user->links[list].next; if (resource_quota->roots[list] == resource_user) { - resource_quota->roots[list] = NULL; + resource_quota->roots[list] = nullptr; } } resource_user->links[list].next->links[list].prev = resource_user->links[list].prev; resource_user->links[list].prev->links[list].next = resource_user->links[list].next; - resource_user->links[list].next = resource_user->links[list].prev = NULL; + resource_user->links[list].next = resource_user->links[list].prev = nullptr; } /******************************************************************************* * resource quota state machine */ -static bool rq_alloc(grpc_exec_ctx *exec_ctx, - grpc_resource_quota *resource_quota); +static bool rq_alloc(grpc_exec_ctx* exec_ctx, + grpc_resource_quota* resource_quota); static bool rq_reclaim_from_per_user_free_pool( - grpc_exec_ctx *exec_ctx, grpc_resource_quota *resource_quota); -static bool rq_reclaim(grpc_exec_ctx *exec_ctx, - grpc_resource_quota *resource_quota, bool destructive); + grpc_exec_ctx* exec_ctx, grpc_resource_quota* resource_quota); +static bool rq_reclaim(grpc_exec_ctx* exec_ctx, + grpc_resource_quota* resource_quota, bool destructive); -static void rq_step(grpc_exec_ctx *exec_ctx, void *rq, grpc_error *error) { - grpc_resource_quota *resource_quota = (grpc_resource_quota *)rq; +static void rq_step(grpc_exec_ctx* exec_ctx, void* rq, grpc_error* error) { + grpc_resource_quota* resource_quota = (grpc_resource_quota*)rq; resource_quota->step_scheduled = false; do { if (rq_alloc(exec_ctx, resource_quota)) goto done; @@ -262,8 +261,8 @@ done: grpc_resource_quota_unref_internal(exec_ctx, resource_quota); } -static void rq_step_sched(grpc_exec_ctx *exec_ctx, - grpc_resource_quota *resource_quota) { +static void rq_step_sched(grpc_exec_ctx* exec_ctx, + grpc_resource_quota* resource_quota) { if (resource_quota->step_scheduled) return; resource_quota->step_scheduled = true; grpc_resource_quota_ref_internal(resource_quota); @@ -273,13 +272,12 @@ static void rq_step_sched(grpc_exec_ctx *exec_ctx, /* update the atomically available resource estimate - use no barriers since timeliness of delivery really doesn't matter much */ -static void rq_update_estimate(grpc_resource_quota *resource_quota) { +static void rq_update_estimate(grpc_resource_quota* resource_quota) { gpr_atm memory_usage_estimation = MEMORY_USAGE_ESTIMATION_MAX; if (resource_quota->size != 0) { memory_usage_estimation = - GPR_CLAMP((gpr_atm)((1.0 - - ((double)resource_quota->free_pool) / - ((double)resource_quota->size)) * + GPR_CLAMP((gpr_atm)((1.0 - ((double)resource_quota->free_pool) / + ((double)resource_quota->size)) * MEMORY_USAGE_ESTIMATION_MAX), 0, MEMORY_USAGE_ESTIMATION_MAX); } @@ -288,15 +286,16 @@ static void rq_update_estimate(grpc_resource_quota *resource_quota) { } /* returns true if all allocations are completed */ -static bool rq_alloc(grpc_exec_ctx *exec_ctx, - grpc_resource_quota *resource_quota) { - grpc_resource_user *resource_user; +static bool rq_alloc(grpc_exec_ctx* exec_ctx, + grpc_resource_quota* resource_quota) { + grpc_resource_user* resource_user; while ((resource_user = rulist_pop_head(resource_quota, GRPC_RULIST_AWAITING_ALLOCATION))) { gpr_mu_lock(&resource_user->mu); - if (GRPC_TRACER_ON(grpc_resource_quota_trace)) { - gpr_log(GPR_DEBUG, "RQ: check allocation for user %p shutdown=%" PRIdPTR - " free_pool=%" PRId64, + if (grpc_resource_quota_trace.enabled()) { + gpr_log(GPR_DEBUG, + "RQ: check allocation for user %p shutdown=%" PRIdPTR + " free_pool=%" PRId64, resource_user, gpr_atm_no_barrier_load(&resource_user->shutdown), resource_user->free_pool); } @@ -319,13 +318,14 @@ static bool rq_alloc(grpc_exec_ctx *exec_ctx, resource_user->free_pool = 0; resource_quota->free_pool -= amt; rq_update_estimate(resource_quota); - if (GRPC_TRACER_ON(grpc_resource_quota_trace)) { - gpr_log(GPR_DEBUG, "RQ %s %s: grant alloc %" PRId64 - " bytes; rq_free_pool -> %" PRId64, + if (grpc_resource_quota_trace.enabled()) { + gpr_log(GPR_DEBUG, + "RQ %s %s: grant alloc %" PRId64 + " bytes; rq_free_pool -> %" PRId64, resource_quota->name, resource_user->name, amt, resource_quota->free_pool); } - } else if (GRPC_TRACER_ON(grpc_resource_quota_trace) && + } else if (grpc_resource_quota_trace.enabled() && resource_user->free_pool >= 0) { gpr_log(GPR_DEBUG, "RQ %s %s: discard already satisfied alloc request", resource_quota->name, resource_user->name); @@ -346,8 +346,8 @@ static bool rq_alloc(grpc_exec_ctx *exec_ctx, /* returns true if any memory could be reclaimed from buffers */ static bool rq_reclaim_from_per_user_free_pool( - grpc_exec_ctx *exec_ctx, grpc_resource_quota *resource_quota) { - grpc_resource_user *resource_user; + grpc_exec_ctx* exec_ctx, grpc_resource_quota* resource_quota) { + grpc_resource_user* resource_user; while ((resource_user = rulist_pop_head(resource_quota, GRPC_RULIST_NON_EMPTY_FREE_POOL))) { gpr_mu_lock(&resource_user->mu); @@ -356,9 +356,10 @@ static bool rq_reclaim_from_per_user_free_pool( resource_user->free_pool = 0; resource_quota->free_pool += amt; rq_update_estimate(resource_quota); - if (GRPC_TRACER_ON(grpc_resource_quota_trace)) { - gpr_log(GPR_DEBUG, "RQ %s %s: reclaim_from_per_user_free_pool %" PRId64 - " bytes; rq_free_pool -> %" PRId64, + if (grpc_resource_quota_trace.enabled()) { + gpr_log(GPR_DEBUG, + "RQ %s %s: reclaim_from_per_user_free_pool %" PRId64 + " bytes; rq_free_pool -> %" PRId64, resource_quota->name, resource_user->name, amt, resource_quota->free_pool); } @@ -372,25 +373,25 @@ static bool rq_reclaim_from_per_user_free_pool( } /* returns true if reclamation is proceeding */ -static bool rq_reclaim(grpc_exec_ctx *exec_ctx, - grpc_resource_quota *resource_quota, bool destructive) { +static bool rq_reclaim(grpc_exec_ctx* exec_ctx, + grpc_resource_quota* resource_quota, bool destructive) { if (resource_quota->reclaiming) return true; grpc_rulist list = destructive ? GRPC_RULIST_RECLAIMER_DESTRUCTIVE : GRPC_RULIST_RECLAIMER_BENIGN; - grpc_resource_user *resource_user = rulist_pop_head(resource_quota, list); - if (resource_user == NULL) return false; - if (GRPC_TRACER_ON(grpc_resource_quota_trace)) { + grpc_resource_user* resource_user = rulist_pop_head(resource_quota, list); + if (resource_user == nullptr) return false; + if (grpc_resource_quota_trace.enabled()) { gpr_log(GPR_DEBUG, "RQ %s %s: initiate %s reclamation", resource_quota->name, resource_user->name, destructive ? "destructive" : "benign"); } resource_quota->reclaiming = true; grpc_resource_quota_ref_internal(resource_quota); - grpc_closure *c = resource_user->reclaimers[destructive]; + grpc_closure* c = resource_user->reclaimers[destructive]; GPR_ASSERT(c); resource_quota->debug_only_last_reclaimer_resource_user = resource_user; resource_quota->debug_only_last_initiated_reclaimer = c; - resource_user->reclaimers[destructive] = NULL; + resource_user->reclaimers[destructive] = nullptr; GRPC_CLOSURE_RUN(exec_ctx, c, GRPC_ERROR_NONE); return true; } @@ -402,17 +403,17 @@ static bool rq_reclaim(grpc_exec_ctx *exec_ctx, typedef struct { grpc_slice_refcount base; gpr_refcount refs; - grpc_resource_user *resource_user; + grpc_resource_user* resource_user; size_t size; } ru_slice_refcount; -static void ru_slice_ref(void *p) { - ru_slice_refcount *rc = (ru_slice_refcount *)p; +static void ru_slice_ref(void* p) { + ru_slice_refcount* rc = (ru_slice_refcount*)p; gpr_ref(&rc->refs); } -static void ru_slice_unref(grpc_exec_ctx *exec_ctx, void *p) { - ru_slice_refcount *rc = (ru_slice_refcount *)p; +static void ru_slice_unref(grpc_exec_ctx* exec_ctx, void* p) { + ru_slice_refcount* rc = (ru_slice_refcount*)p; if (gpr_unref(&rc->refs)) { grpc_resource_user_free(exec_ctx, rc->resource_user, rc->size); gpr_free(rc); @@ -423,10 +424,10 @@ static const grpc_slice_refcount_vtable ru_slice_vtable = { ru_slice_ref, ru_slice_unref, grpc_slice_default_eq_impl, grpc_slice_default_hash_impl}; -static grpc_slice ru_slice_create(grpc_resource_user *resource_user, +static grpc_slice ru_slice_create(grpc_resource_user* resource_user, size_t size) { - ru_slice_refcount *rc = - (ru_slice_refcount *)gpr_malloc(sizeof(ru_slice_refcount) + size); + ru_slice_refcount* rc = + (ru_slice_refcount*)gpr_malloc(sizeof(ru_slice_refcount) + size); rc->base.vtable = &ru_slice_vtable; rc->base.sub_refcount = &rc->base; gpr_ref_init(&rc->refs, 1); @@ -434,7 +435,7 @@ static grpc_slice ru_slice_create(grpc_resource_user *resource_user, rc->size = size; grpc_slice slice; slice.refcount = &rc->base; - slice.data.refcounted.bytes = (uint8_t *)(rc + 1); + slice.data.refcounted.bytes = (uint8_t*)(rc + 1); slice.data.refcounted.length = size; return slice; } @@ -444,8 +445,8 @@ static grpc_slice ru_slice_create(grpc_resource_user *resource_user, * the combiner */ -static void ru_allocate(grpc_exec_ctx *exec_ctx, void *ru, grpc_error *error) { - grpc_resource_user *resource_user = (grpc_resource_user *)ru; +static void ru_allocate(grpc_exec_ctx* exec_ctx, void* ru, grpc_error* error) { + grpc_resource_user* resource_user = (grpc_resource_user*)ru; if (rulist_empty(resource_user->resource_quota, GRPC_RULIST_AWAITING_ALLOCATION)) { rq_step_sched(exec_ctx, resource_user->resource_quota); @@ -453,9 +454,9 @@ static void ru_allocate(grpc_exec_ctx *exec_ctx, void *ru, grpc_error *error) { rulist_add_tail(resource_user, GRPC_RULIST_AWAITING_ALLOCATION); } -static void ru_add_to_free_pool(grpc_exec_ctx *exec_ctx, void *ru, - grpc_error *error) { - grpc_resource_user *resource_user = (grpc_resource_user *)ru; +static void ru_add_to_free_pool(grpc_exec_ctx* exec_ctx, void* ru, + grpc_error* error) { + grpc_resource_user* resource_user = (grpc_resource_user*)ru; if (!rulist_empty(resource_user->resource_quota, GRPC_RULIST_AWAITING_ALLOCATION) && rulist_empty(resource_user->resource_quota, @@ -465,13 +466,13 @@ static void ru_add_to_free_pool(grpc_exec_ctx *exec_ctx, void *ru, rulist_add_tail(resource_user, GRPC_RULIST_NON_EMPTY_FREE_POOL); } -static bool ru_post_reclaimer(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user, +static bool ru_post_reclaimer(grpc_exec_ctx* exec_ctx, + grpc_resource_user* resource_user, bool destructive) { - grpc_closure *closure = resource_user->new_reclaimers[destructive]; - GPR_ASSERT(closure != NULL); - resource_user->new_reclaimers[destructive] = NULL; - GPR_ASSERT(resource_user->reclaimers[destructive] == NULL); + grpc_closure* closure = resource_user->new_reclaimers[destructive]; + GPR_ASSERT(closure != nullptr); + resource_user->new_reclaimers[destructive] = nullptr; + GPR_ASSERT(resource_user->reclaimers[destructive] == nullptr); if (gpr_atm_acq_load(&resource_user->shutdown) > 0) { GRPC_CLOSURE_SCHED(exec_ctx, closure, GRPC_ERROR_CANCELLED); return false; @@ -480,9 +481,9 @@ static bool ru_post_reclaimer(grpc_exec_ctx *exec_ctx, return true; } -static void ru_post_benign_reclaimer(grpc_exec_ctx *exec_ctx, void *ru, - grpc_error *error) { - grpc_resource_user *resource_user = (grpc_resource_user *)ru; +static void ru_post_benign_reclaimer(grpc_exec_ctx* exec_ctx, void* ru, + grpc_error* error) { + grpc_resource_user* resource_user = (grpc_resource_user*)ru; if (!ru_post_reclaimer(exec_ctx, resource_user, false)) return; if (!rulist_empty(resource_user->resource_quota, GRPC_RULIST_AWAITING_ALLOCATION) && @@ -495,9 +496,9 @@ static void ru_post_benign_reclaimer(grpc_exec_ctx *exec_ctx, void *ru, rulist_add_tail(resource_user, GRPC_RULIST_RECLAIMER_BENIGN); } -static void ru_post_destructive_reclaimer(grpc_exec_ctx *exec_ctx, void *ru, - grpc_error *error) { - grpc_resource_user *resource_user = (grpc_resource_user *)ru; +static void ru_post_destructive_reclaimer(grpc_exec_ctx* exec_ctx, void* ru, + grpc_error* error) { + grpc_resource_user* resource_user = (grpc_resource_user*)ru; if (!ru_post_reclaimer(exec_ctx, resource_user, true)) return; if (!rulist_empty(resource_user->resource_quota, GRPC_RULIST_AWAITING_ALLOCATION) && @@ -512,17 +513,17 @@ static void ru_post_destructive_reclaimer(grpc_exec_ctx *exec_ctx, void *ru, rulist_add_tail(resource_user, GRPC_RULIST_RECLAIMER_DESTRUCTIVE); } -static void ru_shutdown(grpc_exec_ctx *exec_ctx, void *ru, grpc_error *error) { - if (GRPC_TRACER_ON(grpc_resource_quota_trace)) { +static void ru_shutdown(grpc_exec_ctx* exec_ctx, void* ru, grpc_error* error) { + if (grpc_resource_quota_trace.enabled()) { gpr_log(GPR_DEBUG, "RU shutdown %p", ru); } - grpc_resource_user *resource_user = (grpc_resource_user *)ru; + grpc_resource_user* resource_user = (grpc_resource_user*)ru; GRPC_CLOSURE_SCHED(exec_ctx, resource_user->reclaimers[0], GRPC_ERROR_CANCELLED); GRPC_CLOSURE_SCHED(exec_ctx, resource_user->reclaimers[1], GRPC_ERROR_CANCELLED); - resource_user->reclaimers[0] = NULL; - resource_user->reclaimers[1] = NULL; + resource_user->reclaimers[0] = nullptr; + resource_user->reclaimers[1] = nullptr; rulist_remove(resource_user, GRPC_RULIST_RECLAIMER_BENIGN); rulist_remove(resource_user, GRPC_RULIST_RECLAIMER_DESTRUCTIVE); if (resource_user->allocating) { @@ -530,8 +531,8 @@ static void ru_shutdown(grpc_exec_ctx *exec_ctx, void *ru, grpc_error *error) { } } -static void ru_destroy(grpc_exec_ctx *exec_ctx, void *ru, grpc_error *error) { - grpc_resource_user *resource_user = (grpc_resource_user *)ru; +static void ru_destroy(grpc_exec_ctx* exec_ctx, void* ru, grpc_error* error) { + grpc_resource_user* resource_user = (grpc_resource_user*)ru; GPR_ASSERT(gpr_atm_no_barrier_load(&resource_user->refs) == 0); for (int i = 0; i < GRPC_RULIST_COUNT; i++) { rulist_remove(resource_user, (grpc_rulist)i); @@ -550,10 +551,10 @@ static void ru_destroy(grpc_exec_ctx *exec_ctx, void *ru, grpc_error *error) { gpr_free(resource_user); } -static void ru_allocated_slices(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_resource_user_slice_allocator *slice_allocator = - (grpc_resource_user_slice_allocator *)arg; +static void ru_allocated_slices(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_resource_user_slice_allocator* slice_allocator = + (grpc_resource_user_slice_allocator*)arg; if (error == GRPC_ERROR_NONE) { for (size_t i = 0; i < slice_allocator->count; i++) { grpc_slice_buffer_add_indexed( @@ -571,12 +572,12 @@ static void ru_allocated_slices(grpc_exec_ctx *exec_ctx, void *arg, typedef struct { int64_t size; - grpc_resource_quota *resource_quota; + grpc_resource_quota* resource_quota; grpc_closure closure; } rq_resize_args; -static void rq_resize(grpc_exec_ctx *exec_ctx, void *args, grpc_error *error) { - rq_resize_args *a = (rq_resize_args *)args; +static void rq_resize(grpc_exec_ctx* exec_ctx, void* args, grpc_error* error) { + rq_resize_args* a = (rq_resize_args*)args; int64_t delta = a->size - a->resource_quota->size; a->resource_quota->size += delta; a->resource_quota->free_pool += delta; @@ -586,9 +587,9 @@ static void rq_resize(grpc_exec_ctx *exec_ctx, void *args, grpc_error *error) { gpr_free(a); } -static void rq_reclamation_done(grpc_exec_ctx *exec_ctx, void *rq, - grpc_error *error) { - grpc_resource_quota *resource_quota = (grpc_resource_quota *)rq; +static void rq_reclamation_done(grpc_exec_ctx* exec_ctx, void* rq, + grpc_error* error) { + grpc_resource_quota* resource_quota = (grpc_resource_quota*)rq; resource_quota->reclaiming = false; rq_step_sched(exec_ctx, resource_quota); grpc_resource_quota_unref_internal(exec_ctx, resource_quota); @@ -599,9 +600,9 @@ static void rq_reclamation_done(grpc_exec_ctx *exec_ctx, void *rq, */ /* Public API */ -grpc_resource_quota *grpc_resource_quota_create(const char *name) { - grpc_resource_quota *resource_quota = - (grpc_resource_quota *)gpr_malloc(sizeof(*resource_quota)); +grpc_resource_quota* grpc_resource_quota_create(const char* name) { + grpc_resource_quota* resource_quota = + (grpc_resource_quota*)gpr_malloc(sizeof(*resource_quota)); gpr_ref_init(&resource_quota->refs, 1); resource_quota->combiner = grpc_combiner_create(); resource_quota->free_pool = INT64_MAX; @@ -610,7 +611,7 @@ grpc_resource_quota *grpc_resource_quota_create(const char *name) { resource_quota->step_scheduled = false; resource_quota->reclaiming = false; gpr_atm_no_barrier_store(&resource_quota->memory_usage_estimation, 0); - if (name != NULL) { + if (name != nullptr) { resource_quota->name = gpr_strdup(name); } else { gpr_asprintf(&resource_quota->name, "anonymous_pool_%" PRIxPTR, @@ -622,13 +623,13 @@ grpc_resource_quota *grpc_resource_quota_create(const char *name) { rq_reclamation_done, resource_quota, grpc_combiner_scheduler(resource_quota->combiner)); for (int i = 0; i < GRPC_RULIST_COUNT; i++) { - resource_quota->roots[i] = NULL; + resource_quota->roots[i] = nullptr; } return resource_quota; } -void grpc_resource_quota_unref_internal(grpc_exec_ctx *exec_ctx, - grpc_resource_quota *resource_quota) { +void grpc_resource_quota_unref_internal(grpc_exec_ctx* exec_ctx, + grpc_resource_quota* resource_quota) { if (gpr_unref(&resource_quota->refs)) { GRPC_COMBINER_UNREF(exec_ctx, resource_quota->combiner, "resource_quota"); gpr_free(resource_quota->name); @@ -637,35 +638,35 @@ void grpc_resource_quota_unref_internal(grpc_exec_ctx *exec_ctx, } /* Public API */ -void grpc_resource_quota_unref(grpc_resource_quota *resource_quota) { +void grpc_resource_quota_unref(grpc_resource_quota* resource_quota) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_resource_quota_unref_internal(&exec_ctx, resource_quota); grpc_exec_ctx_finish(&exec_ctx); } -grpc_resource_quota *grpc_resource_quota_ref_internal( - grpc_resource_quota *resource_quota) { +grpc_resource_quota* grpc_resource_quota_ref_internal( + grpc_resource_quota* resource_quota) { gpr_ref(&resource_quota->refs); return resource_quota; } /* Public API */ -void grpc_resource_quota_ref(grpc_resource_quota *resource_quota) { +void grpc_resource_quota_ref(grpc_resource_quota* resource_quota) { grpc_resource_quota_ref_internal(resource_quota); } double grpc_resource_quota_get_memory_pressure( - grpc_resource_quota *resource_quota) { + grpc_resource_quota* resource_quota) { return ((double)(gpr_atm_no_barrier_load( &resource_quota->memory_usage_estimation))) / ((double)MEMORY_USAGE_ESTIMATION_MAX); } /* Public API */ -void grpc_resource_quota_resize(grpc_resource_quota *resource_quota, +void grpc_resource_quota_resize(grpc_resource_quota* resource_quota, size_t size) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - rq_resize_args *a = (rq_resize_args *)gpr_malloc(sizeof(*a)); + rq_resize_args* a = (rq_resize_args*)gpr_malloc(sizeof(*a)); a->resource_quota = grpc_resource_quota_ref_internal(resource_quota); a->size = (int64_t)size; gpr_atm_no_barrier_store(&resource_quota->last_size, @@ -675,7 +676,7 @@ void grpc_resource_quota_resize(grpc_resource_quota *resource_quota, grpc_exec_ctx_finish(&exec_ctx); } -size_t grpc_resource_quota_peek_size(grpc_resource_quota *resource_quota) { +size_t grpc_resource_quota_peek_size(grpc_resource_quota* resource_quota) { return (size_t)gpr_atm_no_barrier_load(&resource_quota->last_size); } @@ -683,33 +684,33 @@ size_t grpc_resource_quota_peek_size(grpc_resource_quota *resource_quota) { * grpc_resource_user channel args api */ -grpc_resource_quota *grpc_resource_quota_from_channel_args( - const grpc_channel_args *channel_args) { +grpc_resource_quota* grpc_resource_quota_from_channel_args( + const grpc_channel_args* channel_args) { for (size_t i = 0; i < channel_args->num_args; i++) { if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) { if (channel_args->args[i].type == GRPC_ARG_POINTER) { return grpc_resource_quota_ref_internal( - (grpc_resource_quota *)channel_args->args[i].value.pointer.p); + (grpc_resource_quota*)channel_args->args[i].value.pointer.p); } else { gpr_log(GPR_DEBUG, GRPC_ARG_RESOURCE_QUOTA " should be a pointer"); } } } - return grpc_resource_quota_create(NULL); + return grpc_resource_quota_create(nullptr); } -static void *rq_copy(void *rq) { - grpc_resource_quota_ref((grpc_resource_quota *)rq); +static void* rq_copy(void* rq) { + grpc_resource_quota_ref((grpc_resource_quota*)rq); return rq; } -static void rq_destroy(grpc_exec_ctx *exec_ctx, void *rq) { - grpc_resource_quota_unref_internal(exec_ctx, (grpc_resource_quota *)rq); +static void rq_destroy(grpc_exec_ctx* exec_ctx, void* rq) { + grpc_resource_quota_unref_internal(exec_ctx, (grpc_resource_quota*)rq); } -static int rq_cmp(void *a, void *b) { return GPR_ICMP(a, b); } +static int rq_cmp(void* a, void* b) { return GPR_ICMP(a, b); } -const grpc_arg_pointer_vtable *grpc_resource_quota_arg_vtable(void) { +const grpc_arg_pointer_vtable* grpc_resource_quota_arg_vtable(void) { static const grpc_arg_pointer_vtable vtable = {rq_copy, rq_destroy, rq_cmp}; return &vtable; } @@ -718,10 +719,10 @@ const grpc_arg_pointer_vtable *grpc_resource_quota_arg_vtable(void) { * grpc_resource_user api */ -grpc_resource_user *grpc_resource_user_create( - grpc_resource_quota *resource_quota, const char *name) { - grpc_resource_user *resource_user = - (grpc_resource_user *)gpr_malloc(sizeof(*resource_user)); +grpc_resource_user* grpc_resource_user_create( + grpc_resource_quota* resource_quota, const char* name) { + grpc_resource_user* resource_user = + (grpc_resource_user*)gpr_malloc(sizeof(*resource_user)); resource_user->resource_quota = grpc_resource_quota_ref_internal(resource_quota); GRPC_CLOSURE_INIT(&resource_user->allocate_closure, &ru_allocate, @@ -745,15 +746,15 @@ grpc_resource_user *grpc_resource_user_create( grpc_closure_list_init(&resource_user->on_allocated); resource_user->allocating = false; resource_user->added_to_free_pool = false; - resource_user->reclaimers[0] = NULL; - resource_user->reclaimers[1] = NULL; - resource_user->new_reclaimers[0] = NULL; - resource_user->new_reclaimers[1] = NULL; + resource_user->reclaimers[0] = nullptr; + resource_user->reclaimers[1] = nullptr; + resource_user->new_reclaimers[0] = nullptr; + resource_user->new_reclaimers[1] = nullptr; resource_user->outstanding_allocations = 0; for (int i = 0; i < GRPC_RULIST_COUNT; i++) { - resource_user->links[i].next = resource_user->links[i].prev = NULL; + resource_user->links[i].next = resource_user->links[i].prev = nullptr; } - if (name != NULL) { + if (name != nullptr) { resource_user->name = gpr_strdup(name); } else { gpr_asprintf(&resource_user->name, "anonymous_resource_user_%" PRIxPTR, @@ -762,18 +763,18 @@ grpc_resource_user *grpc_resource_user_create( return resource_user; } -grpc_resource_quota *grpc_resource_user_quota( - grpc_resource_user *resource_user) { +grpc_resource_quota* grpc_resource_user_quota( + grpc_resource_user* resource_user) { return resource_user->resource_quota; } -static void ru_ref_by(grpc_resource_user *resource_user, gpr_atm amount) { +static void ru_ref_by(grpc_resource_user* resource_user, gpr_atm amount) { GPR_ASSERT(amount > 0); GPR_ASSERT(gpr_atm_no_barrier_fetch_add(&resource_user->refs, amount) != 0); } -static void ru_unref_by(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user, gpr_atm amount) { +static void ru_unref_by(grpc_exec_ctx* exec_ctx, + grpc_resource_user* resource_user, gpr_atm amount) { GPR_ASSERT(amount > 0); gpr_atm old = gpr_atm_full_fetch_add(&resource_user->refs, -amount); GPR_ASSERT(old >= amount); @@ -783,17 +784,17 @@ static void ru_unref_by(grpc_exec_ctx *exec_ctx, } } -void grpc_resource_user_ref(grpc_resource_user *resource_user) { +void grpc_resource_user_ref(grpc_resource_user* resource_user) { ru_ref_by(resource_user, 1); } -void grpc_resource_user_unref(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user) { +void grpc_resource_user_unref(grpc_exec_ctx* exec_ctx, + grpc_resource_user* resource_user) { ru_unref_by(exec_ctx, resource_user, 1); } -void grpc_resource_user_shutdown(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user) { +void grpc_resource_user_shutdown(grpc_exec_ctx* exec_ctx, + grpc_resource_user* resource_user) { if (gpr_atm_full_fetch_add(&resource_user->shutdown, 1) == 0) { GRPC_CLOSURE_SCHED( exec_ctx, @@ -804,14 +805,14 @@ void grpc_resource_user_shutdown(grpc_exec_ctx *exec_ctx, } } -void grpc_resource_user_alloc(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user, size_t size, - grpc_closure *optional_on_done) { +void grpc_resource_user_alloc(grpc_exec_ctx* exec_ctx, + grpc_resource_user* resource_user, size_t size, + grpc_closure* optional_on_done) { gpr_mu_lock(&resource_user->mu); ru_ref_by(resource_user, (gpr_atm)size); resource_user->free_pool -= (int64_t)size; resource_user->outstanding_allocations += (int64_t)size; - if (GRPC_TRACER_ON(grpc_resource_quota_trace)) { + if (grpc_resource_quota_trace.enabled()) { gpr_log(GPR_DEBUG, "RQ %s %s: alloc %" PRIdPTR "; free_pool -> %" PRId64, resource_user->resource_quota->name, resource_user->name, size, resource_user->free_pool); @@ -831,12 +832,12 @@ void grpc_resource_user_alloc(grpc_exec_ctx *exec_ctx, gpr_mu_unlock(&resource_user->mu); } -void grpc_resource_user_free(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user, size_t size) { +void grpc_resource_user_free(grpc_exec_ctx* exec_ctx, + grpc_resource_user* resource_user, size_t size) { gpr_mu_lock(&resource_user->mu); bool was_zero_or_negative = resource_user->free_pool <= 0; resource_user->free_pool += (int64_t)size; - if (GRPC_TRACER_ON(grpc_resource_quota_trace)) { + if (grpc_resource_quota_trace.enabled()) { gpr_log(GPR_DEBUG, "RQ %s %s: free %" PRIdPTR "; free_pool -> %" PRId64, resource_user->resource_quota->name, resource_user->name, size, resource_user->free_pool); @@ -852,20 +853,20 @@ void grpc_resource_user_free(grpc_exec_ctx *exec_ctx, ru_unref_by(exec_ctx, resource_user, (gpr_atm)size); } -void grpc_resource_user_post_reclaimer(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user, +void grpc_resource_user_post_reclaimer(grpc_exec_ctx* exec_ctx, + grpc_resource_user* resource_user, bool destructive, - grpc_closure *closure) { - GPR_ASSERT(resource_user->new_reclaimers[destructive] == NULL); + grpc_closure* closure) { + GPR_ASSERT(resource_user->new_reclaimers[destructive] == nullptr); resource_user->new_reclaimers[destructive] = closure; GRPC_CLOSURE_SCHED(exec_ctx, &resource_user->post_reclaimer_closure[destructive], GRPC_ERROR_NONE); } -void grpc_resource_user_finish_reclamation(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user) { - if (GRPC_TRACER_ON(grpc_resource_quota_trace)) { +void grpc_resource_user_finish_reclamation(grpc_exec_ctx* exec_ctx, + grpc_resource_user* resource_user) { + if (grpc_resource_quota_trace.enabled()) { gpr_log(GPR_DEBUG, "RQ %s %s: reclamation complete", resource_user->resource_quota->name, resource_user->name); } @@ -875,8 +876,8 @@ void grpc_resource_user_finish_reclamation(grpc_exec_ctx *exec_ctx, } void grpc_resource_user_slice_allocator_init( - grpc_resource_user_slice_allocator *slice_allocator, - grpc_resource_user *resource_user, grpc_iomgr_cb_func cb, void *p) { + grpc_resource_user_slice_allocator* slice_allocator, + grpc_resource_user* resource_user, grpc_iomgr_cb_func cb, void* p) { GRPC_CLOSURE_INIT(&slice_allocator->on_allocated, ru_allocated_slices, slice_allocator, grpc_schedule_on_exec_ctx); GRPC_CLOSURE_INIT(&slice_allocator->on_done, cb, p, @@ -885,19 +886,12 @@ void grpc_resource_user_slice_allocator_init( } void grpc_resource_user_alloc_slices( - grpc_exec_ctx *exec_ctx, - grpc_resource_user_slice_allocator *slice_allocator, size_t length, - size_t count, grpc_slice_buffer *dest) { + grpc_exec_ctx* exec_ctx, + grpc_resource_user_slice_allocator* slice_allocator, size_t length, + size_t count, grpc_slice_buffer* dest) { slice_allocator->length = length; slice_allocator->count = count; slice_allocator->dest = dest; grpc_resource_user_alloc(exec_ctx, slice_allocator->resource_user, count * length, &slice_allocator->on_allocated); } - -grpc_slice grpc_resource_user_slice_malloc(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user, - size_t size) { - grpc_resource_user_alloc(exec_ctx, resource_user, size, NULL); - return ru_slice_create(resource_user, size); -} diff --git a/src/core/lib/iomgr/resource_quota.h b/src/core/lib/iomgr/resource_quota.h index 1d4249b7e29..787370307a8 100644 --- a/src/core/lib/iomgr/resource_quota.h +++ b/src/core/lib/iomgr/resource_quota.h @@ -24,10 +24,6 @@ #include "src/core/lib/debug/trace.h" #include "src/core/lib/iomgr/exec_ctx.h" -#ifdef __cplusplus -extern "C" { -#endif - /** \file Tracks resource usage against a pool. The current implementation tracks only memory usage, but in the future @@ -65,60 +61,60 @@ extern "C" { maintain lists of users (which users arrange to leave before they are destroyed) */ -extern grpc_tracer_flag grpc_resource_quota_trace; +extern grpc_core::TraceFlag grpc_resource_quota_trace; -grpc_resource_quota *grpc_resource_quota_ref_internal( - grpc_resource_quota *resource_quota); -void grpc_resource_quota_unref_internal(grpc_exec_ctx *exec_ctx, - grpc_resource_quota *resource_quota); -grpc_resource_quota *grpc_resource_quota_from_channel_args( - const grpc_channel_args *channel_args); +grpc_resource_quota* grpc_resource_quota_ref_internal( + grpc_resource_quota* resource_quota); +void grpc_resource_quota_unref_internal(grpc_exec_ctx* exec_ctx, + grpc_resource_quota* resource_quota); +grpc_resource_quota* grpc_resource_quota_from_channel_args( + const grpc_channel_args* channel_args); /* Return a number indicating current memory pressure: 0.0 ==> no memory usage 1.0 ==> maximum memory usage */ double grpc_resource_quota_get_memory_pressure( - grpc_resource_quota *resource_quota); + grpc_resource_quota* resource_quota); -size_t grpc_resource_quota_peek_size(grpc_resource_quota *resource_quota); +size_t grpc_resource_quota_peek_size(grpc_resource_quota* resource_quota); typedef struct grpc_resource_user grpc_resource_user; -grpc_resource_user *grpc_resource_user_create( - grpc_resource_quota *resource_quota, const char *name); +grpc_resource_user* grpc_resource_user_create( + grpc_resource_quota* resource_quota, const char* name); /* Returns a borrowed reference to the underlying resource quota for this resource user. */ -grpc_resource_quota *grpc_resource_user_quota( - grpc_resource_user *resource_user); +grpc_resource_quota* grpc_resource_user_quota( + grpc_resource_user* resource_user); -void grpc_resource_user_ref(grpc_resource_user *resource_user); -void grpc_resource_user_unref(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user); -void grpc_resource_user_shutdown(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user); +void grpc_resource_user_ref(grpc_resource_user* resource_user); +void grpc_resource_user_unref(grpc_exec_ctx* exec_ctx, + grpc_resource_user* resource_user); +void grpc_resource_user_shutdown(grpc_exec_ctx* exec_ctx, + grpc_resource_user* resource_user); /* Allocate from the resource user (and its quota). If optional_on_done is NULL, then allocate immediately. This may push the quota over-limit, at which point reclamation will kick in. If optional_on_done is non-NULL, it will be scheduled when the allocation has been granted by the quota. */ -void grpc_resource_user_alloc(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user, size_t size, - grpc_closure *optional_on_done); +void grpc_resource_user_alloc(grpc_exec_ctx* exec_ctx, + grpc_resource_user* resource_user, size_t size, + grpc_closure* optional_on_done); /* Release memory back to the quota */ -void grpc_resource_user_free(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user, size_t size); +void grpc_resource_user_free(grpc_exec_ctx* exec_ctx, + grpc_resource_user* resource_user, size_t size); /* Post a memory reclaimer to the resource user. Only one benign and one destructive reclaimer can be posted at once. When executed, the reclaimer MUST call grpc_resource_user_finish_reclamation before it completes, to return control to the resource quota. */ -void grpc_resource_user_post_reclaimer(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user, - bool destructive, grpc_closure *closure); +void grpc_resource_user_post_reclaimer(grpc_exec_ctx* exec_ctx, + grpc_resource_user* resource_user, + bool destructive, grpc_closure* closure); /* Finish a reclamation step */ -void grpc_resource_user_finish_reclamation(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user); +void grpc_resource_user_finish_reclamation(grpc_exec_ctx* exec_ctx, + grpc_resource_user* resource_user); /* Helper to allocate slices from a resource user */ typedef struct grpc_resource_user_slice_allocator { @@ -131,31 +127,27 @@ typedef struct grpc_resource_user_slice_allocator { /* Number of slices to allocate on the current request */ size_t count; /* Destination for slices to allocate on the current request */ - grpc_slice_buffer *dest; + grpc_slice_buffer* dest; /* Parent resource user */ - grpc_resource_user *resource_user; + grpc_resource_user* resource_user; } grpc_resource_user_slice_allocator; /* Initialize a slice allocator. When an allocation is completed, calls \a cb with arg \p. */ void grpc_resource_user_slice_allocator_init( - grpc_resource_user_slice_allocator *slice_allocator, - grpc_resource_user *resource_user, grpc_iomgr_cb_func cb, void *p); + grpc_resource_user_slice_allocator* slice_allocator, + grpc_resource_user* resource_user, grpc_iomgr_cb_func cb, void* p); /* Allocate \a count slices of length \a length into \a dest. Only one request can be outstanding at a time. */ void grpc_resource_user_alloc_slices( - grpc_exec_ctx *exec_ctx, - grpc_resource_user_slice_allocator *slice_allocator, size_t length, - size_t count, grpc_slice_buffer *dest); + grpc_exec_ctx* exec_ctx, + grpc_resource_user_slice_allocator* slice_allocator, size_t length, + size_t count, grpc_slice_buffer* dest); /* Allocate one slice of length \a size synchronously. */ -grpc_slice grpc_resource_user_slice_malloc(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user, +grpc_slice grpc_resource_user_slice_malloc(grpc_exec_ctx* exec_ctx, + grpc_resource_user* resource_user, size_t size); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_RESOURCE_QUOTA_H */ diff --git a/src/core/lib/iomgr/sockaddr_utils.cc b/src/core/lib/iomgr/sockaddr_utils.cc index 8a2e6ed89bc..0c0a2fe5b2e 100644 --- a/src/core/lib/iomgr/sockaddr_utils.cc +++ b/src/core/lib/iomgr/sockaddr_utils.cc @@ -36,19 +36,19 @@ static const uint8_t kV4MappedPrefix[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}; -int grpc_sockaddr_is_v4mapped(const grpc_resolved_address *resolved_addr, - grpc_resolved_address *resolved_addr4_out) { +int grpc_sockaddr_is_v4mapped(const grpc_resolved_address* resolved_addr, + grpc_resolved_address* resolved_addr4_out) { GPR_ASSERT(resolved_addr != resolved_addr4_out); - const struct sockaddr *addr = (const struct sockaddr *)resolved_addr->addr; - struct sockaddr_in *addr4_out = - resolved_addr4_out == NULL - ? NULL - : (struct sockaddr_in *)resolved_addr4_out->addr; + const struct sockaddr* addr = (const struct sockaddr*)resolved_addr->addr; + struct sockaddr_in* addr4_out = + resolved_addr4_out == nullptr + ? nullptr + : (struct sockaddr_in*)resolved_addr4_out->addr; if (addr->sa_family == AF_INET6) { - const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr; + const struct sockaddr_in6* addr6 = (const struct sockaddr_in6*)addr; if (memcmp(addr6->sin6_addr.s6_addr, kV4MappedPrefix, sizeof(kV4MappedPrefix)) == 0) { - if (resolved_addr4_out != NULL) { + if (resolved_addr4_out != nullptr) { /* Normalize ::ffff:0.0.0.0/96 to IPv4. */ memset(resolved_addr4_out, 0, sizeof(*resolved_addr4_out)); addr4_out->sin_family = AF_INET; @@ -63,14 +63,14 @@ int grpc_sockaddr_is_v4mapped(const grpc_resolved_address *resolved_addr, return 0; } -int grpc_sockaddr_to_v4mapped(const grpc_resolved_address *resolved_addr, - grpc_resolved_address *resolved_addr6_out) { +int grpc_sockaddr_to_v4mapped(const grpc_resolved_address* resolved_addr, + grpc_resolved_address* resolved_addr6_out) { GPR_ASSERT(resolved_addr != resolved_addr6_out); - const struct sockaddr *addr = (const struct sockaddr *)resolved_addr->addr; - struct sockaddr_in6 *addr6_out = - (struct sockaddr_in6 *)resolved_addr6_out->addr; + const struct sockaddr* addr = (const struct sockaddr*)resolved_addr->addr; + struct sockaddr_in6* addr6_out = + (struct sockaddr_in6*)resolved_addr6_out->addr; if (addr->sa_family == AF_INET) { - const struct sockaddr_in *addr4 = (const struct sockaddr_in *)addr; + const struct sockaddr_in* addr4 = (const struct sockaddr_in*)addr; memset(resolved_addr6_out, 0, sizeof(*resolved_addr6_out)); addr6_out->sin6_family = AF_INET6; memcpy(&addr6_out->sin6_addr.s6_addr[0], kV4MappedPrefix, 12); @@ -82,17 +82,17 @@ int grpc_sockaddr_to_v4mapped(const grpc_resolved_address *resolved_addr, return 0; } -int grpc_sockaddr_is_wildcard(const grpc_resolved_address *resolved_addr, - int *port_out) { - const struct sockaddr *addr; +int grpc_sockaddr_is_wildcard(const grpc_resolved_address* resolved_addr, + int* port_out) { + const struct sockaddr* addr; grpc_resolved_address addr4_normalized; if (grpc_sockaddr_is_v4mapped(resolved_addr, &addr4_normalized)) { resolved_addr = &addr4_normalized; } - addr = (const struct sockaddr *)resolved_addr->addr; + addr = (const struct sockaddr*)resolved_addr->addr; if (addr->sa_family == AF_INET) { /* Check for 0.0.0.0 */ - const struct sockaddr_in *addr4 = (const struct sockaddr_in *)addr; + const struct sockaddr_in* addr4 = (const struct sockaddr_in*)addr; if (addr4->sin_addr.s_addr != 0) { return 0; } @@ -100,7 +100,7 @@ int grpc_sockaddr_is_wildcard(const grpc_resolved_address *resolved_addr, return 1; } else if (addr->sa_family == AF_INET6) { /* Check for :: */ - const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr; + const struct sockaddr_in6* addr6 = (const struct sockaddr_in6*)addr; int i; for (i = 0; i < 16; i++) { if (addr6->sin6_addr.s6_addr[i] != 0) { @@ -114,15 +114,15 @@ int grpc_sockaddr_is_wildcard(const grpc_resolved_address *resolved_addr, } } -void grpc_sockaddr_make_wildcards(int port, grpc_resolved_address *wild4_out, - grpc_resolved_address *wild6_out) { +void grpc_sockaddr_make_wildcards(int port, grpc_resolved_address* wild4_out, + grpc_resolved_address* wild6_out) { grpc_sockaddr_make_wildcard4(port, wild4_out); grpc_sockaddr_make_wildcard6(port, wild6_out); } void grpc_sockaddr_make_wildcard4(int port, - grpc_resolved_address *resolved_wild_out) { - struct sockaddr_in *wild_out = (struct sockaddr_in *)resolved_wild_out->addr; + grpc_resolved_address* resolved_wild_out) { + struct sockaddr_in* wild_out = (struct sockaddr_in*)resolved_wild_out->addr; GPR_ASSERT(port >= 0 && port < 65536); memset(resolved_wild_out, 0, sizeof(*resolved_wild_out)); wild_out->sin_family = AF_INET; @@ -131,9 +131,8 @@ void grpc_sockaddr_make_wildcard4(int port, } void grpc_sockaddr_make_wildcard6(int port, - grpc_resolved_address *resolved_wild_out) { - struct sockaddr_in6 *wild_out = - (struct sockaddr_in6 *)resolved_wild_out->addr; + grpc_resolved_address* resolved_wild_out) { + struct sockaddr_in6* wild_out = (struct sockaddr_in6*)resolved_wild_out->addr; GPR_ASSERT(port >= 0 && port < 65536); memset(resolved_wild_out, 0, sizeof(*resolved_wild_out)); wild_out->sin6_family = AF_INET6; @@ -141,37 +140,37 @@ void grpc_sockaddr_make_wildcard6(int port, resolved_wild_out->len = sizeof(struct sockaddr_in6); } -int grpc_sockaddr_to_string(char **out, - const grpc_resolved_address *resolved_addr, +int grpc_sockaddr_to_string(char** out, + const grpc_resolved_address* resolved_addr, int normalize) { - const struct sockaddr *addr; + const struct sockaddr* addr; const int save_errno = errno; grpc_resolved_address addr_normalized; char ntop_buf[INET6_ADDRSTRLEN]; - const void *ip = NULL; - int port; + const void* ip = nullptr; + int port = 0; uint32_t sin6_scope_id = 0; int ret; - *out = NULL; + *out = nullptr; if (normalize && grpc_sockaddr_is_v4mapped(resolved_addr, &addr_normalized)) { resolved_addr = &addr_normalized; } - addr = (const struct sockaddr *)resolved_addr->addr; + addr = (const struct sockaddr*)resolved_addr->addr; if (addr->sa_family == AF_INET) { - const struct sockaddr_in *addr4 = (const struct sockaddr_in *)addr; + const struct sockaddr_in* addr4 = (const struct sockaddr_in*)addr; ip = &addr4->sin_addr; port = ntohs(addr4->sin_port); } else if (addr->sa_family == AF_INET6) { - const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr; + const struct sockaddr_in6* addr6 = (const struct sockaddr_in6*)addr; ip = &addr6->sin6_addr; port = ntohs(addr6->sin6_port); sin6_scope_id = addr6->sin6_scope_id; } - if (ip != NULL && - grpc_inet_ntop(addr->sa_family, ip, ntop_buf, sizeof(ntop_buf)) != NULL) { + if (ip != nullptr && grpc_inet_ntop(addr->sa_family, ip, ntop_buf, + sizeof(ntop_buf)) != nullptr) { if (sin6_scope_id != 0) { - char *host_with_scope; + char* host_with_scope; /* Enclose sin6_scope_id with the format defined in RFC 6784 section 2. */ gpr_asprintf(&host_with_scope, "%s%%25%" PRIu32, ntop_buf, sin6_scope_id); ret = gpr_join_host_port(out, host_with_scope, port); @@ -187,29 +186,29 @@ int grpc_sockaddr_to_string(char **out, return ret; } -char *grpc_sockaddr_to_uri(const grpc_resolved_address *resolved_addr) { +char* grpc_sockaddr_to_uri(const grpc_resolved_address* resolved_addr) { grpc_resolved_address addr_normalized; if (grpc_sockaddr_is_v4mapped(resolved_addr, &addr_normalized)) { resolved_addr = &addr_normalized; } - const char *scheme = grpc_sockaddr_get_uri_scheme(resolved_addr); - if (scheme == NULL || strcmp("unix", scheme) == 0) { + const char* scheme = grpc_sockaddr_get_uri_scheme(resolved_addr); + if (scheme == nullptr || strcmp("unix", scheme) == 0) { return grpc_sockaddr_to_uri_unix_if_possible(resolved_addr); } - char *path = NULL; - char *uri_str = NULL; + char* path = nullptr; + char* uri_str = nullptr; if (grpc_sockaddr_to_string(&path, resolved_addr, false /* suppress errors */) && - scheme != NULL) { + scheme != nullptr) { gpr_asprintf(&uri_str, "%s:%s", scheme, path); } gpr_free(path); - return uri_str != NULL ? uri_str : NULL; + return uri_str != nullptr ? uri_str : nullptr; } -const char *grpc_sockaddr_get_uri_scheme( - const grpc_resolved_address *resolved_addr) { - const struct sockaddr *addr = (const struct sockaddr *)resolved_addr->addr; +const char* grpc_sockaddr_get_uri_scheme( + const grpc_resolved_address* resolved_addr) { + const struct sockaddr* addr = (const struct sockaddr*)resolved_addr->addr; switch (addr->sa_family) { case AF_INET: return "ipv4"; @@ -218,21 +217,21 @@ const char *grpc_sockaddr_get_uri_scheme( case AF_UNIX: return "unix"; } - return NULL; + return nullptr; } -int grpc_sockaddr_get_family(const grpc_resolved_address *resolved_addr) { - const struct sockaddr *addr = (const struct sockaddr *)resolved_addr->addr; +int grpc_sockaddr_get_family(const grpc_resolved_address* resolved_addr) { + const struct sockaddr* addr = (const struct sockaddr*)resolved_addr->addr; return addr->sa_family; } -int grpc_sockaddr_get_port(const grpc_resolved_address *resolved_addr) { - const struct sockaddr *addr = (const struct sockaddr *)resolved_addr->addr; +int grpc_sockaddr_get_port(const grpc_resolved_address* resolved_addr) { + const struct sockaddr* addr = (const struct sockaddr*)resolved_addr->addr; switch (addr->sa_family) { case AF_INET: - return ntohs(((struct sockaddr_in *)addr)->sin_port); + return ntohs(((struct sockaddr_in*)addr)->sin_port); case AF_INET6: - return ntohs(((struct sockaddr_in6 *)addr)->sin6_port); + return ntohs(((struct sockaddr_in6*)addr)->sin6_port); default: if (grpc_is_unix_socket(resolved_addr)) { return 1; @@ -243,17 +242,17 @@ int grpc_sockaddr_get_port(const grpc_resolved_address *resolved_addr) { } } -int grpc_sockaddr_set_port(const grpc_resolved_address *resolved_addr, +int grpc_sockaddr_set_port(const grpc_resolved_address* resolved_addr, int port) { - const struct sockaddr *addr = (const struct sockaddr *)resolved_addr->addr; + const struct sockaddr* addr = (const struct sockaddr*)resolved_addr->addr; switch (addr->sa_family) { case AF_INET: GPR_ASSERT(port >= 0 && port < 65536); - ((struct sockaddr_in *)addr)->sin_port = htons((uint16_t)port); + ((struct sockaddr_in*)addr)->sin_port = htons((uint16_t)port); return 1; case AF_INET6: GPR_ASSERT(port >= 0 && port < 65536); - ((struct sockaddr_in6 *)addr)->sin6_port = htons((uint16_t)port); + ((struct sockaddr_in6*)addr)->sin6_port = htons((uint16_t)port); return 1; default: gpr_log(GPR_ERROR, "Unknown socket family %d in grpc_sockaddr_set_port", diff --git a/src/core/lib/iomgr/sockaddr_utils.h b/src/core/lib/iomgr/sockaddr_utils.h index 1fd552febbb..e3bd51a4ad2 100644 --- a/src/core/lib/iomgr/sockaddr_utils.h +++ b/src/core/lib/iomgr/sockaddr_utils.h @@ -21,42 +21,38 @@ #include "src/core/lib/iomgr/resolve_address.h" -#ifdef __cplusplus -extern "C" { -#endif - /* Returns true if addr is an IPv4-mapped IPv6 address within the ::ffff:0.0.0.0/96 range, or false otherwise. If addr4_out is non-NULL, the inner IPv4 address will be copied here when returning true. */ -int grpc_sockaddr_is_v4mapped(const grpc_resolved_address *addr, - grpc_resolved_address *addr4_out); +int grpc_sockaddr_is_v4mapped(const grpc_resolved_address* addr, + grpc_resolved_address* addr4_out); /* If addr is an AF_INET address, writes the corresponding ::ffff:0.0.0.0/96 address to addr6_out and returns true. Otherwise returns false. */ -int grpc_sockaddr_to_v4mapped(const grpc_resolved_address *addr, - grpc_resolved_address *addr6_out); +int grpc_sockaddr_to_v4mapped(const grpc_resolved_address* addr, + grpc_resolved_address* addr6_out); /* If addr is ::, 0.0.0.0, or ::ffff:0.0.0.0, writes the port number to *port_out (if not NULL) and returns true, otherwise returns false. */ -int grpc_sockaddr_is_wildcard(const grpc_resolved_address *addr, int *port_out); +int grpc_sockaddr_is_wildcard(const grpc_resolved_address* addr, int* port_out); /* Writes 0.0.0.0:port and [::]:port to separate sockaddrs. */ -void grpc_sockaddr_make_wildcards(int port, grpc_resolved_address *wild4_out, - grpc_resolved_address *wild6_out); +void grpc_sockaddr_make_wildcards(int port, grpc_resolved_address* wild4_out, + grpc_resolved_address* wild6_out); /* Writes 0.0.0.0:port. */ -void grpc_sockaddr_make_wildcard4(int port, grpc_resolved_address *wild_out); +void grpc_sockaddr_make_wildcard4(int port, grpc_resolved_address* wild_out); /* Writes [::]:port. */ -void grpc_sockaddr_make_wildcard6(int port, grpc_resolved_address *wild_out); +void grpc_sockaddr_make_wildcard6(int port, grpc_resolved_address* wild_out); /* Return the IP port number of a sockaddr */ -int grpc_sockaddr_get_port(const grpc_resolved_address *addr); +int grpc_sockaddr_get_port(const grpc_resolved_address* addr); /* Set IP port number of a sockaddr */ -int grpc_sockaddr_set_port(const grpc_resolved_address *addr, int port); +int grpc_sockaddr_set_port(const grpc_resolved_address* addr, int port); /* Converts a sockaddr into a newly-allocated human-readable string. @@ -70,19 +66,15 @@ int grpc_sockaddr_set_port(const grpc_resolved_address *addr, int port); In the unlikely event of an error, returns -1 and sets *out to NULL. The existing value of errno is always preserved. */ -int grpc_sockaddr_to_string(char **out, const grpc_resolved_address *addr, +int grpc_sockaddr_to_string(char** out, const grpc_resolved_address* addr, int normalize); /* Returns the URI string corresponding to \a addr */ -char *grpc_sockaddr_to_uri(const grpc_resolved_address *addr); +char* grpc_sockaddr_to_uri(const grpc_resolved_address* addr); /* Returns the URI scheme corresponding to \a addr */ -const char *grpc_sockaddr_get_uri_scheme(const grpc_resolved_address *addr); - -int grpc_sockaddr_get_family(const grpc_resolved_address *resolved_addr); +const char* grpc_sockaddr_get_uri_scheme(const grpc_resolved_address* addr); -#ifdef __cplusplus -} -#endif +int grpc_sockaddr_get_family(const grpc_resolved_address* resolved_addr); #endif /* GRPC_CORE_LIB_IOMGR_SOCKADDR_UTILS_H */ diff --git a/src/core/lib/iomgr/sockaddr_windows.h b/src/core/lib/iomgr/sockaddr_windows.h index cf0f6b914d3..20e37c9fc46 100644 --- a/src/core/lib/iomgr/sockaddr_windows.h +++ b/src/core/lib/iomgr/sockaddr_windows.h @@ -19,10 +19,16 @@ #ifndef GRPC_CORE_LIB_IOMGR_SOCKADDR_WINDOWS_H #define GRPC_CORE_LIB_IOMGR_SOCKADDR_WINDOWS_H +#include "src/core/lib/iomgr/port.h" + +#ifdef GRPC_WINSOCK_SOCKET + #include #include // must be included after the above #include +#endif + #endif /* GRPC_CORE_LIB_IOMGR_SOCKADDR_WINDOWS_H */ diff --git a/src/core/lib/iomgr/socket_factory_posix.cc b/src/core/lib/iomgr/socket_factory_posix.cc index 8e907703ae7..40bfecd4c25 100644 --- a/src/core/lib/iomgr/socket_factory_posix.cc +++ b/src/core/lib/iomgr/socket_factory_posix.cc @@ -27,28 +27,28 @@ #include #include -void grpc_socket_factory_init(grpc_socket_factory *factory, - const grpc_socket_factory_vtable *vtable) { +void grpc_socket_factory_init(grpc_socket_factory* factory, + const grpc_socket_factory_vtable* vtable) { factory->vtable = vtable; gpr_ref_init(&factory->refcount, 1); } -int grpc_socket_factory_socket(grpc_socket_factory *factory, int domain, +int grpc_socket_factory_socket(grpc_socket_factory* factory, int domain, int type, int protocol) { return factory->vtable->socket(factory, domain, type, protocol); } -int grpc_socket_factory_bind(grpc_socket_factory *factory, int sockfd, - const grpc_resolved_address *addr) { +int grpc_socket_factory_bind(grpc_socket_factory* factory, int sockfd, + const grpc_resolved_address* addr) { return factory->vtable->bind(factory, sockfd, addr); } -int grpc_socket_factory_compare(grpc_socket_factory *a, - grpc_socket_factory *b) { +int grpc_socket_factory_compare(grpc_socket_factory* a, + grpc_socket_factory* b) { int c = GPR_ICMP(a, b); if (c != 0) { - grpc_socket_factory *sma = a; - grpc_socket_factory *smb = b; + grpc_socket_factory* sma = a; + grpc_socket_factory* smb = b; c = GPR_ICMP(sma->vtable, smb->vtable); if (c == 0) { c = sma->vtable->compare(sma, smb); @@ -57,35 +57,35 @@ int grpc_socket_factory_compare(grpc_socket_factory *a, return c; } -grpc_socket_factory *grpc_socket_factory_ref(grpc_socket_factory *factory) { +grpc_socket_factory* grpc_socket_factory_ref(grpc_socket_factory* factory) { gpr_ref(&factory->refcount); return factory; } -void grpc_socket_factory_unref(grpc_socket_factory *factory) { +void grpc_socket_factory_unref(grpc_socket_factory* factory) { if (gpr_unref(&factory->refcount)) { factory->vtable->destroy(factory); } } -static void *socket_factory_arg_copy(void *p) { - return grpc_socket_factory_ref((grpc_socket_factory *)p); +static void* socket_factory_arg_copy(void* p) { + return grpc_socket_factory_ref((grpc_socket_factory*)p); } -static void socket_factory_arg_destroy(grpc_exec_ctx *exec_ctx, void *p) { - grpc_socket_factory_unref((grpc_socket_factory *)p); +static void socket_factory_arg_destroy(grpc_exec_ctx* exec_ctx, void* p) { + grpc_socket_factory_unref((grpc_socket_factory*)p); } -static int socket_factory_cmp(void *a, void *b) { - return grpc_socket_factory_compare((grpc_socket_factory *)a, - (grpc_socket_factory *)b); +static int socket_factory_cmp(void* a, void* b) { + return grpc_socket_factory_compare((grpc_socket_factory*)a, + (grpc_socket_factory*)b); } static const grpc_arg_pointer_vtable socket_factory_arg_vtable = { socket_factory_arg_copy, socket_factory_arg_destroy, socket_factory_cmp}; -grpc_arg grpc_socket_factory_to_arg(grpc_socket_factory *factory) { - return grpc_channel_arg_pointer_create((char *)GRPC_ARG_SOCKET_FACTORY, +grpc_arg grpc_socket_factory_to_arg(grpc_socket_factory* factory) { + return grpc_channel_arg_pointer_create((char*)GRPC_ARG_SOCKET_FACTORY, factory, &socket_factory_arg_vtable); } diff --git a/src/core/lib/iomgr/socket_factory_posix.h b/src/core/lib/iomgr/socket_factory_posix.h index a46938b06ef..af57cc5b605 100644 --- a/src/core/lib/iomgr/socket_factory_posix.h +++ b/src/core/lib/iomgr/socket_factory_posix.h @@ -23,53 +23,45 @@ #include #include "src/core/lib/iomgr/resolve_address.h" -#ifdef __cplusplus -extern "C" { -#endif - /** The virtual table of grpc_socket_factory */ typedef struct { /** Replacement for socket(2) */ - int (*socket)(grpc_socket_factory *factory, int domain, int type, + int (*socket)(grpc_socket_factory* factory, int domain, int type, int protocol); /** Replacement for bind(2) */ - int (*bind)(grpc_socket_factory *factory, int sockfd, - const grpc_resolved_address *addr); + int (*bind)(grpc_socket_factory* factory, int sockfd, + const grpc_resolved_address* addr); /** Compare socket factory \a a and \a b */ - int (*compare)(grpc_socket_factory *a, grpc_socket_factory *b); + int (*compare)(grpc_socket_factory* a, grpc_socket_factory* b); /** Destroys the socket factory instance */ - void (*destroy)(grpc_socket_factory *factory); + void (*destroy)(grpc_socket_factory* factory); } grpc_socket_factory_vtable; /** The Socket Factory interface allows changes on socket options */ struct grpc_socket_factory { - const grpc_socket_factory_vtable *vtable; + const grpc_socket_factory_vtable* vtable; gpr_refcount refcount; }; /** called by concrete implementations to initialize the base struct */ -void grpc_socket_factory_init(grpc_socket_factory *factory, - const grpc_socket_factory_vtable *vtable); +void grpc_socket_factory_init(grpc_socket_factory* factory, + const grpc_socket_factory_vtable* vtable); /** Wrap \a factory as a grpc_arg */ -grpc_arg grpc_socket_factory_to_arg(grpc_socket_factory *factory); +grpc_arg grpc_socket_factory_to_arg(grpc_socket_factory* factory); /** Perform the equivalent of a socket(2) operation using \a factory */ -int grpc_socket_factory_socket(grpc_socket_factory *factory, int domain, +int grpc_socket_factory_socket(grpc_socket_factory* factory, int domain, int type, int protocol); /** Perform the equivalent of a bind(2) operation using \a factory */ -int grpc_socket_factory_bind(grpc_socket_factory *factory, int sockfd, - const grpc_resolved_address *addr); +int grpc_socket_factory_bind(grpc_socket_factory* factory, int sockfd, + const grpc_resolved_address* addr); /** Compare if \a a and \a b are the same factory or have same settings */ -int grpc_socket_factory_compare(grpc_socket_factory *a, grpc_socket_factory *b); - -grpc_socket_factory *grpc_socket_factory_ref(grpc_socket_factory *factory); -void grpc_socket_factory_unref(grpc_socket_factory *factory); +int grpc_socket_factory_compare(grpc_socket_factory* a, grpc_socket_factory* b); -#ifdef __cplusplus -} -#endif +grpc_socket_factory* grpc_socket_factory_ref(grpc_socket_factory* factory); +void grpc_socket_factory_unref(grpc_socket_factory* factory); #endif /* GRPC_CORE_LIB_IOMGR_SOCKET_FACTORY_POSIX_H */ diff --git a/src/core/lib/iomgr/socket_mutator.cc b/src/core/lib/iomgr/socket_mutator.cc index b0435d5a076..ff6c0c70d8d 100644 --- a/src/core/lib/iomgr/socket_mutator.cc +++ b/src/core/lib/iomgr/socket_mutator.cc @@ -24,27 +24,27 @@ #include #include -void grpc_socket_mutator_init(grpc_socket_mutator *mutator, - const grpc_socket_mutator_vtable *vtable) { +void grpc_socket_mutator_init(grpc_socket_mutator* mutator, + const grpc_socket_mutator_vtable* vtable) { mutator->vtable = vtable; gpr_ref_init(&mutator->refcount, 1); } -grpc_socket_mutator *grpc_socket_mutator_ref(grpc_socket_mutator *mutator) { +grpc_socket_mutator* grpc_socket_mutator_ref(grpc_socket_mutator* mutator) { gpr_ref(&mutator->refcount); return mutator; } -bool grpc_socket_mutator_mutate_fd(grpc_socket_mutator *mutator, int fd) { +bool grpc_socket_mutator_mutate_fd(grpc_socket_mutator* mutator, int fd) { return mutator->vtable->mutate_fd(fd, mutator); } -int grpc_socket_mutator_compare(grpc_socket_mutator *a, - grpc_socket_mutator *b) { +int grpc_socket_mutator_compare(grpc_socket_mutator* a, + grpc_socket_mutator* b) { int c = GPR_ICMP(a, b); if (c != 0) { - grpc_socket_mutator *sma = a; - grpc_socket_mutator *smb = b; + grpc_socket_mutator* sma = a; + grpc_socket_mutator* smb = b; c = GPR_ICMP(sma->vtable, smb->vtable); if (c == 0) { c = sma->vtable->compare(sma, smb); @@ -53,29 +53,29 @@ int grpc_socket_mutator_compare(grpc_socket_mutator *a, return c; } -void grpc_socket_mutator_unref(grpc_socket_mutator *mutator) { +void grpc_socket_mutator_unref(grpc_socket_mutator* mutator) { if (gpr_unref(&mutator->refcount)) { mutator->vtable->destory(mutator); } } -static void *socket_mutator_arg_copy(void *p) { - return grpc_socket_mutator_ref((grpc_socket_mutator *)p); +static void* socket_mutator_arg_copy(void* p) { + return grpc_socket_mutator_ref((grpc_socket_mutator*)p); } -static void socket_mutator_arg_destroy(grpc_exec_ctx *exec_ctx, void *p) { - grpc_socket_mutator_unref((grpc_socket_mutator *)p); +static void socket_mutator_arg_destroy(grpc_exec_ctx* exec_ctx, void* p) { + grpc_socket_mutator_unref((grpc_socket_mutator*)p); } -static int socket_mutator_cmp(void *a, void *b) { - return grpc_socket_mutator_compare((grpc_socket_mutator *)a, - (grpc_socket_mutator *)b); +static int socket_mutator_cmp(void* a, void* b) { + return grpc_socket_mutator_compare((grpc_socket_mutator*)a, + (grpc_socket_mutator*)b); } static const grpc_arg_pointer_vtable socket_mutator_arg_vtable = { socket_mutator_arg_copy, socket_mutator_arg_destroy, socket_mutator_cmp}; -grpc_arg grpc_socket_mutator_to_arg(grpc_socket_mutator *mutator) { - return grpc_channel_arg_pointer_create((char *)GRPC_ARG_SOCKET_MUTATOR, +grpc_arg grpc_socket_mutator_to_arg(grpc_socket_mutator* mutator) { + return grpc_channel_arg_pointer_create((char*)GRPC_ARG_SOCKET_MUTATOR, mutator, &socket_mutator_arg_vtable); } diff --git a/src/core/lib/iomgr/socket_mutator.h b/src/core/lib/iomgr/socket_mutator.h index ba956e16f07..0a97cf657f0 100644 --- a/src/core/lib/iomgr/socket_mutator.h +++ b/src/core/lib/iomgr/socket_mutator.h @@ -24,44 +24,36 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /** The virtual table of grpc_socket_mutator */ typedef struct { /** Mutates the socket opitons of \a fd */ - bool (*mutate_fd)(int fd, grpc_socket_mutator *mutator); + bool (*mutate_fd)(int fd, grpc_socket_mutator* mutator); /** Compare socket mutator \a a and \a b */ - int (*compare)(grpc_socket_mutator *a, grpc_socket_mutator *b); + int (*compare)(grpc_socket_mutator* a, grpc_socket_mutator* b); /** Destroys the socket mutator instance */ - void (*destory)(grpc_socket_mutator *mutator); + void (*destory)(grpc_socket_mutator* mutator); } grpc_socket_mutator_vtable; /** The Socket Mutator interface allows changes on socket options */ struct grpc_socket_mutator { - const grpc_socket_mutator_vtable *vtable; + const grpc_socket_mutator_vtable* vtable; gpr_refcount refcount; }; /** called by concrete implementations to initialize the base struct */ -void grpc_socket_mutator_init(grpc_socket_mutator *mutator, - const grpc_socket_mutator_vtable *vtable); +void grpc_socket_mutator_init(grpc_socket_mutator* mutator, + const grpc_socket_mutator_vtable* vtable); /** Wrap \a mutator as a grpc_arg */ -grpc_arg grpc_socket_mutator_to_arg(grpc_socket_mutator *mutator); +grpc_arg grpc_socket_mutator_to_arg(grpc_socket_mutator* mutator); /** Perform the file descriptor mutation operation of \a mutator on \a fd */ -bool grpc_socket_mutator_mutate_fd(grpc_socket_mutator *mutator, int fd); +bool grpc_socket_mutator_mutate_fd(grpc_socket_mutator* mutator, int fd); /** Compare if \a a and \a b are the same mutator or have same settings */ -int grpc_socket_mutator_compare(grpc_socket_mutator *a, grpc_socket_mutator *b); - -grpc_socket_mutator *grpc_socket_mutator_ref(grpc_socket_mutator *mutator); -void grpc_socket_mutator_unref(grpc_socket_mutator *mutator); +int grpc_socket_mutator_compare(grpc_socket_mutator* a, grpc_socket_mutator* b); -#ifdef __cplusplus -} -#endif +grpc_socket_mutator* grpc_socket_mutator_ref(grpc_socket_mutator* mutator); +void grpc_socket_mutator_unref(grpc_socket_mutator* mutator); #endif /* GRPC_CORE_LIB_IOMGR_SOCKET_MUTATOR_H */ diff --git a/src/core/lib/iomgr/socket_utils.h b/src/core/lib/iomgr/socket_utils.h index d6c538ec6f3..9fd141b6dec 100644 --- a/src/core/lib/iomgr/socket_utils.h +++ b/src/core/lib/iomgr/socket_utils.h @@ -21,15 +21,7 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /* A wrapper for inet_ntop on POSIX systems and InetNtop on Windows systems */ -const char *grpc_inet_ntop(int af, const void *src, char *dst, size_t size); - -#ifdef __cplusplus -} -#endif +const char* grpc_inet_ntop(int af, const void* src, char* dst, size_t size); #endif /* GRPC_CORE_LIB_IOMGR_SOCKET_UTILS_H */ diff --git a/src/core/lib/iomgr/socket_utils_common_posix.cc b/src/core/lib/iomgr/socket_utils_common_posix.cc index b8e2a0cdfd8..2d4b8f0adda 100644 --- a/src/core/lib/iomgr/socket_utils_common_posix.cc +++ b/src/core/lib/iomgr/socket_utils_common_posix.cc @@ -44,7 +44,7 @@ #include "src/core/lib/support/string.h" /* set a socket to non blocking mode */ -grpc_error *grpc_set_socket_nonblocking(int fd, int non_blocking) { +grpc_error* grpc_set_socket_nonblocking(int fd, int non_blocking) { int oldflags = fcntl(fd, F_GETFL, 0); if (oldflags < 0) { return GRPC_OS_ERROR(errno, "fcntl"); @@ -63,7 +63,7 @@ grpc_error *grpc_set_socket_nonblocking(int fd, int non_blocking) { return GRPC_ERROR_NONE; } -grpc_error *grpc_set_socket_no_sigpipe_if_possible(int fd) { +grpc_error* grpc_set_socket_no_sigpipe_if_possible(int fd) { #ifdef GRPC_HAVE_SO_NOSIGPIPE int val = 1; int newval; @@ -81,7 +81,7 @@ grpc_error *grpc_set_socket_no_sigpipe_if_possible(int fd) { return GRPC_ERROR_NONE; } -grpc_error *grpc_set_socket_ip_pktinfo_if_possible(int fd) { +grpc_error* grpc_set_socket_ip_pktinfo_if_possible(int fd) { #ifdef GRPC_HAVE_IP_PKTINFO int get_local_ip = 1; if (0 != setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &get_local_ip, @@ -92,7 +92,7 @@ grpc_error *grpc_set_socket_ip_pktinfo_if_possible(int fd) { return GRPC_ERROR_NONE; } -grpc_error *grpc_set_socket_ipv6_recvpktinfo_if_possible(int fd) { +grpc_error* grpc_set_socket_ipv6_recvpktinfo_if_possible(int fd) { #ifdef GRPC_HAVE_IPV6_RECVPKTINFO int get_local_ip = 1; if (0 != setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &get_local_ip, @@ -103,14 +103,14 @@ grpc_error *grpc_set_socket_ipv6_recvpktinfo_if_possible(int fd) { return GRPC_ERROR_NONE; } -grpc_error *grpc_set_socket_sndbuf(int fd, int buffer_size_bytes) { +grpc_error* grpc_set_socket_sndbuf(int fd, int buffer_size_bytes) { return 0 == setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &buffer_size_bytes, sizeof(buffer_size_bytes)) ? GRPC_ERROR_NONE : GRPC_OS_ERROR(errno, "setsockopt(SO_SNDBUF)"); } -grpc_error *grpc_set_socket_rcvbuf(int fd, int buffer_size_bytes) { +grpc_error* grpc_set_socket_rcvbuf(int fd, int buffer_size_bytes) { return 0 == setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &buffer_size_bytes, sizeof(buffer_size_bytes)) ? GRPC_ERROR_NONE @@ -118,7 +118,7 @@ grpc_error *grpc_set_socket_rcvbuf(int fd, int buffer_size_bytes) { } /* set a socket to close on exec */ -grpc_error *grpc_set_socket_cloexec(int fd, int close_on_exec) { +grpc_error* grpc_set_socket_cloexec(int fd, int close_on_exec) { int oldflags = fcntl(fd, F_GETFD, 0); if (oldflags < 0) { return GRPC_OS_ERROR(errno, "fcntl"); @@ -138,7 +138,7 @@ grpc_error *grpc_set_socket_cloexec(int fd, int close_on_exec) { } /* set a socket to reuse old addresses */ -grpc_error *grpc_set_socket_reuse_addr(int fd, int reuse) { +grpc_error* grpc_set_socket_reuse_addr(int fd, int reuse) { int val = (reuse != 0); int newval; socklen_t intlen = sizeof(newval); @@ -156,7 +156,7 @@ grpc_error *grpc_set_socket_reuse_addr(int fd, int reuse) { } /* set a socket to reuse old addresses */ -grpc_error *grpc_set_socket_reuse_port(int fd, int reuse) { +grpc_error* grpc_set_socket_reuse_port(int fd, int reuse) { #ifndef SO_REUSEPORT return GRPC_ERROR_CREATE_FROM_STATIC_STRING( "SO_REUSEPORT unavailable on compiling system"); @@ -179,7 +179,7 @@ grpc_error *grpc_set_socket_reuse_port(int fd, int reuse) { } /* disable nagle */ -grpc_error *grpc_set_socket_low_latency(int fd, int low_latency) { +grpc_error* grpc_set_socket_low_latency(int fd, int low_latency) { int val = (low_latency != 0); int newval; socklen_t intlen = sizeof(newval); @@ -196,7 +196,7 @@ grpc_error *grpc_set_socket_low_latency(int fd, int low_latency) { } /* set a socket using a grpc_socket_mutator */ -grpc_error *grpc_set_socket_with_mutator(int fd, grpc_socket_mutator *mutator) { +grpc_error* grpc_set_socket_with_mutator(int fd, grpc_socket_mutator* mutator) { GPR_ASSERT(mutator); if (!grpc_socket_mutator_mutate_fd(mutator, fd)) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("grpc_socket_mutator failed."); @@ -217,7 +217,7 @@ static void probe_ipv6_once(void) { memset(&addr, 0, sizeof(addr)); addr.sin6_family = AF_INET6; addr.sin6_addr.s6_addr[15] = 1; /* [::1]:0 */ - if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) == 0) { + if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == 0) { g_ipv6_loopback_available = 1; } else { gpr_log(GPR_INFO, @@ -249,35 +249,35 @@ static int set_socket_dualstack(int fd) { } } -static grpc_error *error_for_fd(int fd, const grpc_resolved_address *addr) { +static grpc_error* error_for_fd(int fd, const grpc_resolved_address* addr) { if (fd >= 0) return GRPC_ERROR_NONE; - char *addr_str; + char* addr_str; grpc_sockaddr_to_string(&addr_str, addr, 0); - grpc_error *err = grpc_error_set_str(GRPC_OS_ERROR(errno, "socket"), + grpc_error* err = grpc_error_set_str(GRPC_OS_ERROR(errno, "socket"), GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(addr_str)); gpr_free(addr_str); return err; } -grpc_error *grpc_create_dualstack_socket( - const grpc_resolved_address *resolved_addr, int type, int protocol, - grpc_dualstack_mode *dsmode, int *newfd) { - return grpc_create_dualstack_socket_using_factory(NULL, resolved_addr, type, - protocol, dsmode, newfd); +grpc_error* grpc_create_dualstack_socket( + const grpc_resolved_address* resolved_addr, int type, int protocol, + grpc_dualstack_mode* dsmode, int* newfd) { + return grpc_create_dualstack_socket_using_factory( + nullptr, resolved_addr, type, protocol, dsmode, newfd); } -static int create_socket(grpc_socket_factory *factory, int domain, int type, +static int create_socket(grpc_socket_factory* factory, int domain, int type, int protocol) { - return (factory != NULL) + return (factory != nullptr) ? grpc_socket_factory_socket(factory, domain, type, protocol) : socket(domain, type, protocol); } -grpc_error *grpc_create_dualstack_socket_using_factory( - grpc_socket_factory *factory, const grpc_resolved_address *resolved_addr, - int type, int protocol, grpc_dualstack_mode *dsmode, int *newfd) { - const struct sockaddr *addr = (const struct sockaddr *)resolved_addr->addr; +grpc_error* grpc_create_dualstack_socket_using_factory( + grpc_socket_factory* factory, const grpc_resolved_address* resolved_addr, + int type, int protocol, grpc_dualstack_mode* dsmode, int* newfd) { + const struct sockaddr* addr = (const struct sockaddr*)resolved_addr->addr; int family = addr->sa_family; if (family == AF_INET6) { if (grpc_ipv6_loopback_available()) { @@ -292,7 +292,7 @@ grpc_error *grpc_create_dualstack_socket_using_factory( return GRPC_ERROR_NONE; } /* If this isn't an IPv4 address, then return whatever we've got. */ - if (!grpc_sockaddr_is_v4mapped(resolved_addr, NULL)) { + if (!grpc_sockaddr_is_v4mapped(resolved_addr, nullptr)) { *dsmode = GRPC_DSMODE_IPV6; return error_for_fd(*newfd, resolved_addr); } @@ -307,7 +307,7 @@ grpc_error *grpc_create_dualstack_socket_using_factory( return error_for_fd(*newfd, resolved_addr); } -const char *grpc_inet_ntop(int af, const void *src, char *dst, size_t size) { +const char* grpc_inet_ntop(int af, const void* src, char* dst, size_t size) { GPR_ASSERT(size <= (socklen_t)-1); return inet_ntop(af, src, dst, (socklen_t)size); } diff --git a/src/core/lib/iomgr/socket_utils_linux.cc b/src/core/lib/iomgr/socket_utils_linux.cc index e7b094d216b..12199c5c89a 100644 --- a/src/core/lib/iomgr/socket_utils_linux.cc +++ b/src/core/lib/iomgr/socket_utils_linux.cc @@ -28,15 +28,15 @@ #include #include -int grpc_accept4(int sockfd, grpc_resolved_address *resolved_addr, int nonblock, +int grpc_accept4(int sockfd, grpc_resolved_address* resolved_addr, int nonblock, int cloexec) { int flags = 0; GPR_ASSERT(sizeof(socklen_t) <= sizeof(size_t)); GPR_ASSERT(resolved_addr->len <= (socklen_t)-1); flags |= nonblock ? SOCK_NONBLOCK : 0; flags |= cloexec ? SOCK_CLOEXEC : 0; - return accept4(sockfd, (struct sockaddr *)resolved_addr->addr, - (socklen_t *)&resolved_addr->len, flags); + return accept4(sockfd, (struct sockaddr*)resolved_addr->addr, + (socklen_t*)&resolved_addr->len, flags); } #endif diff --git a/src/core/lib/iomgr/socket_utils_posix.cc b/src/core/lib/iomgr/socket_utils_posix.cc index dfd1ffd1e3c..c49cbb203bc 100644 --- a/src/core/lib/iomgr/socket_utils_posix.cc +++ b/src/core/lib/iomgr/socket_utils_posix.cc @@ -29,13 +29,13 @@ #include #include "src/core/lib/iomgr/sockaddr.h" -int grpc_accept4(int sockfd, grpc_resolved_address *resolved_addr, int nonblock, +int grpc_accept4(int sockfd, grpc_resolved_address* resolved_addr, int nonblock, int cloexec) { int fd, flags; GPR_ASSERT(sizeof(socklen_t) <= sizeof(size_t)); GPR_ASSERT(resolved_addr->len <= (socklen_t)-1); - fd = accept(sockfd, (struct sockaddr *)resolved_addr->addr, - (socklen_t *)&resolved_addr->len); + fd = accept(sockfd, (struct sockaddr*)resolved_addr->addr, + (socklen_t*)&resolved_addr->len); if (fd >= 0) { if (nonblock) { flags = fcntl(fd, F_GETFL, 0); diff --git a/src/core/lib/iomgr/socket_utils_posix.h b/src/core/lib/iomgr/socket_utils_posix.h index 73809b68d30..77df4205ff2 100644 --- a/src/core/lib/iomgr/socket_utils_posix.h +++ b/src/core/lib/iomgr/socket_utils_posix.h @@ -29,28 +29,24 @@ #include "src/core/lib/iomgr/socket_factory_posix.h" #include "src/core/lib/iomgr/socket_mutator.h" -#ifdef __cplusplus -extern "C" { -#endif - /* a wrapper for accept or accept4 */ -int grpc_accept4(int sockfd, grpc_resolved_address *resolved_addr, int nonblock, +int grpc_accept4(int sockfd, grpc_resolved_address* resolved_addr, int nonblock, int cloexec); /* set a socket to non blocking mode */ -grpc_error *grpc_set_socket_nonblocking(int fd, int non_blocking); +grpc_error* grpc_set_socket_nonblocking(int fd, int non_blocking); /* set a socket to close on exec */ -grpc_error *grpc_set_socket_cloexec(int fd, int close_on_exec); +grpc_error* grpc_set_socket_cloexec(int fd, int close_on_exec); /* set a socket to reuse old addresses */ -grpc_error *grpc_set_socket_reuse_addr(int fd, int reuse); +grpc_error* grpc_set_socket_reuse_addr(int fd, int reuse); /* disable nagle */ -grpc_error *grpc_set_socket_low_latency(int fd, int low_latency); +grpc_error* grpc_set_socket_low_latency(int fd, int low_latency); /* set SO_REUSEPORT */ -grpc_error *grpc_set_socket_reuse_port(int fd, int reuse); +grpc_error* grpc_set_socket_reuse_port(int fd, int reuse); /* Returns true if this system can create AF_INET6 sockets bound to ::1. The value is probed once, and cached for the life of the process. @@ -64,24 +60,24 @@ int grpc_ipv6_loopback_available(void); /* Tries to set SO_NOSIGPIPE if available on this platform. If SO_NO_SIGPIPE is not available, returns 1. */ -grpc_error *grpc_set_socket_no_sigpipe_if_possible(int fd); +grpc_error* grpc_set_socket_no_sigpipe_if_possible(int fd); /* Tries to set IP_PKTINFO if available on this platform. If IP_PKTINFO is not available, returns 1. */ -grpc_error *grpc_set_socket_ip_pktinfo_if_possible(int fd); +grpc_error* grpc_set_socket_ip_pktinfo_if_possible(int fd); /* Tries to set IPV6_RECVPKTINFO if available on this platform. If IPV6_RECVPKTINFO is not available, returns 1. */ -grpc_error *grpc_set_socket_ipv6_recvpktinfo_if_possible(int fd); +grpc_error* grpc_set_socket_ipv6_recvpktinfo_if_possible(int fd); /* Tries to set the socket's send buffer to given size. */ -grpc_error *grpc_set_socket_sndbuf(int fd, int buffer_size_bytes); +grpc_error* grpc_set_socket_sndbuf(int fd, int buffer_size_bytes); /* Tries to set the socket's receive buffer to given size. */ -grpc_error *grpc_set_socket_rcvbuf(int fd, int buffer_size_bytes); +grpc_error* grpc_set_socket_rcvbuf(int fd, int buffer_size_bytes); /* Tries to set the socket using a grpc_socket_mutator */ -grpc_error *grpc_set_socket_with_mutator(int fd, grpc_socket_mutator *mutator); +grpc_error* grpc_set_socket_with_mutator(int fd, grpc_socket_mutator* mutator); /* An enum to keep track of IPv4/IPv6 socket modes. @@ -122,19 +118,15 @@ extern int grpc_forbid_dualstack_sockets_for_testing; IPv4, so that bind() or connect() see the correct family. Also, it's important to distinguish between DUALSTACK and IPV6 when listening on the [::] wildcard address. */ -grpc_error *grpc_create_dualstack_socket(const grpc_resolved_address *addr, +grpc_error* grpc_create_dualstack_socket(const grpc_resolved_address* addr, int type, int protocol, - grpc_dualstack_mode *dsmode, - int *newfd); + grpc_dualstack_mode* dsmode, + int* newfd); /* Same as grpc_create_dualstack_socket(), but use the given socket factory (if non-null) to create the socket, rather than calling socket() directly. */ -grpc_error *grpc_create_dualstack_socket_using_factory( - grpc_socket_factory *factory, const grpc_resolved_address *addr, int type, - int protocol, grpc_dualstack_mode *dsmode, int *newfd); - -#ifdef __cplusplus -} -#endif +grpc_error* grpc_create_dualstack_socket_using_factory( + grpc_socket_factory* factory, const grpc_resolved_address* addr, int type, + int protocol, grpc_dualstack_mode* dsmode, int* newfd); #endif /* GRPC_CORE_LIB_IOMGR_SOCKET_UTILS_POSIX_H */ diff --git a/src/core/lib/iomgr/socket_utils_uv.cc b/src/core/lib/iomgr/socket_utils_uv.cc index 0f7de4dfad5..75316d8c248 100644 --- a/src/core/lib/iomgr/socket_utils_uv.cc +++ b/src/core/lib/iomgr/socket_utils_uv.cc @@ -26,7 +26,7 @@ #include -const char *grpc_inet_ntop(int af, const void *src, char *dst, size_t size) { +const char* grpc_inet_ntop(int af, const void* src, char* dst, size_t size) { uv_inet_ntop(af, src, dst, size); return dst; } diff --git a/src/core/lib/iomgr/socket_utils_windows.cc b/src/core/lib/iomgr/socket_utils_windows.cc index 6e85e4b61fd..0482a1783d4 100644 --- a/src/core/lib/iomgr/socket_utils_windows.cc +++ b/src/core/lib/iomgr/socket_utils_windows.cc @@ -25,9 +25,9 @@ #include -const char *grpc_inet_ntop(int af, const void *src, char *dst, size_t size) { +const char* grpc_inet_ntop(int af, const void* src, char* dst, size_t size) { /* Windows InetNtopA wants a mutable ip pointer */ - return InetNtopA(af, (void *)src, dst, size); + return InetNtopA(af, (void*)src, dst, size); } #endif /* GRPC_WINDOWS_SOCKETUTILS */ diff --git a/src/core/lib/iomgr/socket_windows.cc b/src/core/lib/iomgr/socket_windows.cc index 8c7f7cf683d..aee80f4b4c0 100644 --- a/src/core/lib/iomgr/socket_windows.cc +++ b/src/core/lib/iomgr/socket_windows.cc @@ -36,9 +36,9 @@ #include "src/core/lib/iomgr/pollset_windows.h" #include "src/core/lib/iomgr/socket_windows.h" -grpc_winsocket *grpc_winsocket_create(SOCKET socket, const char *name) { - char *final_name; - grpc_winsocket *r = (grpc_winsocket *)gpr_malloc(sizeof(grpc_winsocket)); +grpc_winsocket* grpc_winsocket_create(SOCKET socket, const char* name) { + char* final_name; + grpc_winsocket* r = (grpc_winsocket*)gpr_malloc(sizeof(grpc_winsocket)); memset(r, 0, sizeof(grpc_winsocket)); r->socket = socket; gpr_mu_init(&r->state_mu); @@ -53,7 +53,7 @@ grpc_winsocket *grpc_winsocket_create(SOCKET socket, const char *name) { operations to abort them. We need to do that this way because of the various callsites of that function, which happens to be in various mutex hold states, and that'd be unsafe to call them directly. */ -void grpc_winsocket_shutdown(grpc_winsocket *winsocket) { +void grpc_winsocket_shutdown(grpc_winsocket* winsocket) { /* Grab the function pointer for DisconnectEx for that specific socket. It may change depending on the interface. */ int status; @@ -76,7 +76,7 @@ void grpc_winsocket_shutdown(grpc_winsocket *winsocket) { if (status == 0) { DisconnectEx(winsocket->socket, NULL, 0, 0); } else { - char *utf8_message = gpr_format_message(WSAGetLastError()); + char* utf8_message = gpr_format_message(WSAGetLastError()); gpr_log(GPR_INFO, "Unable to retrieve DisconnectEx pointer : %s", utf8_message); gpr_free(utf8_message); @@ -84,19 +84,19 @@ void grpc_winsocket_shutdown(grpc_winsocket *winsocket) { closesocket(winsocket->socket); } -static void destroy(grpc_winsocket *winsocket) { +static void destroy(grpc_winsocket* winsocket) { grpc_iomgr_unregister_object(&winsocket->iomgr_object); gpr_mu_destroy(&winsocket->state_mu); gpr_free(winsocket); } -static bool check_destroyable(grpc_winsocket *winsocket) { +static bool check_destroyable(grpc_winsocket* winsocket) { return winsocket->destroy_called == true && winsocket->write_info.closure == NULL && winsocket->read_info.closure == NULL; } -void grpc_winsocket_destroy(grpc_winsocket *winsocket) { +void grpc_winsocket_destroy(grpc_winsocket* winsocket) { gpr_mu_lock(&winsocket->state_mu); GPR_ASSERT(!winsocket->destroy_called); winsocket->destroy_called = true; @@ -109,9 +109,9 @@ void grpc_winsocket_destroy(grpc_winsocket *winsocket) { -) The IOCP already completed in the background, and we need to call the callback now. -) The IOCP hasn't completed yet, and we're queuing it for later. */ -static void socket_notify_on_iocp(grpc_exec_ctx *exec_ctx, - grpc_winsocket *socket, grpc_closure *closure, - grpc_winsocket_callback_info *info) { +static void socket_notify_on_iocp(grpc_exec_ctx* exec_ctx, + grpc_winsocket* socket, grpc_closure* closure, + grpc_winsocket_callback_info* info) { GPR_ASSERT(info->closure == NULL); gpr_mu_lock(&socket->state_mu); if (info->has_pending_iocp) { @@ -123,19 +123,19 @@ static void socket_notify_on_iocp(grpc_exec_ctx *exec_ctx, gpr_mu_unlock(&socket->state_mu); } -void grpc_socket_notify_on_write(grpc_exec_ctx *exec_ctx, - grpc_winsocket *socket, - grpc_closure *closure) { +void grpc_socket_notify_on_write(grpc_exec_ctx* exec_ctx, + grpc_winsocket* socket, + grpc_closure* closure) { socket_notify_on_iocp(exec_ctx, socket, closure, &socket->write_info); } -void grpc_socket_notify_on_read(grpc_exec_ctx *exec_ctx, grpc_winsocket *socket, - grpc_closure *closure) { +void grpc_socket_notify_on_read(grpc_exec_ctx* exec_ctx, grpc_winsocket* socket, + grpc_closure* closure) { socket_notify_on_iocp(exec_ctx, socket, closure, &socket->read_info); } -void grpc_socket_become_ready(grpc_exec_ctx *exec_ctx, grpc_winsocket *socket, - grpc_winsocket_callback_info *info) { +void grpc_socket_become_ready(grpc_exec_ctx* exec_ctx, grpc_winsocket* socket, + grpc_winsocket_callback_info* info) { GPR_ASSERT(!info->has_pending_iocp); gpr_mu_lock(&socket->state_mu); if (info->closure) { diff --git a/src/core/lib/iomgr/socket_windows.h b/src/core/lib/iomgr/socket_windows.h index 84fa071e89a..04e0a89d703 100644 --- a/src/core/lib/iomgr/socket_windows.h +++ b/src/core/lib/iomgr/socket_windows.h @@ -20,6 +20,9 @@ #define GRPC_CORE_LIB_IOMGR_SOCKET_WINDOWS_H #include +#include "src/core/lib/iomgr/port.h" + +#ifdef GRPC_WINSOCK_SOCKET #include #include @@ -28,10 +31,6 @@ #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/iomgr/iomgr_internal.h" -#ifdef __cplusplus -extern "C" { -#endif - /* This holds the data for an outstanding read or write on a socket. The mutex to protect the concurrent access to that data is the one inside the winsocket wrapper. */ @@ -44,7 +43,7 @@ typedef struct grpc_winsocket_callback_info { OVERLAPPED overlapped; /* The callback information for the pending operation. May be empty if the caller hasn't registered a callback yet. */ - grpc_closure *closure; + grpc_closure* closure; /* A boolean to describe if the IO Completion Port got a notification for that operation. This will happen if the operation completed before the called had time to register a callback. We could avoid that behavior @@ -90,29 +89,27 @@ typedef struct grpc_winsocket { /* Create a wrapped windows handle. This takes ownership of it, meaning that it will be responsible for closing it. */ -grpc_winsocket *grpc_winsocket_create(SOCKET socket, const char *name); +grpc_winsocket* grpc_winsocket_create(SOCKET socket, const char* name); /* Initiate an asynchronous shutdown of the socket. Will call off any pending operation to cancel them. */ -void grpc_winsocket_shutdown(grpc_winsocket *socket); +void grpc_winsocket_shutdown(grpc_winsocket* socket); /* Destroy a socket. Should only be called if there's no pending operation. */ -void grpc_winsocket_destroy(grpc_winsocket *socket); +void grpc_winsocket_destroy(grpc_winsocket* socket); -void grpc_socket_notify_on_write(grpc_exec_ctx *exec_ctx, - grpc_winsocket *winsocket, - grpc_closure *closure); +void grpc_socket_notify_on_write(grpc_exec_ctx* exec_ctx, + grpc_winsocket* winsocket, + grpc_closure* closure); -void grpc_socket_notify_on_read(grpc_exec_ctx *exec_ctx, - grpc_winsocket *winsocket, - grpc_closure *closure); +void grpc_socket_notify_on_read(grpc_exec_ctx* exec_ctx, + grpc_winsocket* winsocket, + grpc_closure* closure); -void grpc_socket_become_ready(grpc_exec_ctx *exec_ctx, - grpc_winsocket *winsocket, - grpc_winsocket_callback_info *ci); +void grpc_socket_become_ready(grpc_exec_ctx* exec_ctx, + grpc_winsocket* winsocket, + grpc_winsocket_callback_info* ci); -#ifdef __cplusplus -} #endif #endif /* GRPC_CORE_LIB_IOMGR_SOCKET_WINDOWS_H */ diff --git a/src/core/lib/iomgr/tcp_client.h b/src/core/lib/iomgr/tcp_client.h index b2f365f2af6..75e2fe0f36c 100644 --- a/src/core/lib/iomgr/tcp_client.h +++ b/src/core/lib/iomgr/tcp_client.h @@ -25,24 +25,16 @@ #include "src/core/lib/iomgr/pollset_set.h" #include "src/core/lib/iomgr/resolve_address.h" -#ifdef __cplusplus -extern "C" { -#endif - /* Asynchronously connect to an address (specified as (addr, len)), and call cb with arg and the completed connection when done (or call cb with arg and NULL on failure). interested_parties points to a set of pollsets that would be interested in this connection being established (in order to continue their work) */ -void grpc_tcp_client_connect(grpc_exec_ctx *exec_ctx, grpc_closure *on_connect, - grpc_endpoint **endpoint, - grpc_pollset_set *interested_parties, - const grpc_channel_args *channel_args, - const grpc_resolved_address *addr, +void grpc_tcp_client_connect(grpc_exec_ctx* exec_ctx, grpc_closure* on_connect, + grpc_endpoint** endpoint, + grpc_pollset_set* interested_parties, + const grpc_channel_args* channel_args, + const grpc_resolved_address* addr, grpc_millis deadline); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_TCP_CLIENT_H */ diff --git a/src/core/lib/iomgr/tcp_client_posix.cc b/src/core/lib/iomgr/tcp_client_posix.cc index 5611dd90624..4cb2ac49d5d 100644 --- a/src/core/lib/iomgr/tcp_client_posix.cc +++ b/src/core/lib/iomgr/tcp_client_posix.cc @@ -43,25 +43,25 @@ #include "src/core/lib/iomgr/unix_sockets_posix.h" #include "src/core/lib/support/string.h" -extern grpc_tracer_flag grpc_tcp_trace; +extern grpc_core::TraceFlag grpc_tcp_trace; typedef struct { gpr_mu mu; - grpc_fd *fd; + grpc_fd* fd; grpc_timer alarm; grpc_closure on_alarm; int refs; grpc_closure write_closure; - grpc_pollset_set *interested_parties; - char *addr_str; - grpc_endpoint **ep; - grpc_closure *closure; - grpc_channel_args *channel_args; + grpc_pollset_set* interested_parties; + char* addr_str; + grpc_endpoint** ep; + grpc_closure* closure; + grpc_channel_args* channel_args; } async_connect; -static grpc_error *prepare_socket(const grpc_resolved_address *addr, int fd, - const grpc_channel_args *channel_args) { - grpc_error *err = GRPC_ERROR_NONE; +static grpc_error* prepare_socket(const grpc_resolved_address* addr, int fd, + const grpc_channel_args* channel_args) { + grpc_error* err = GRPC_ERROR_NONE; GPR_ASSERT(fd >= 0); @@ -79,8 +79,8 @@ static grpc_error *prepare_socket(const grpc_resolved_address *addr, int fd, for (size_t i = 0; i < channel_args->num_args; i++) { if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_SOCKET_MUTATOR)) { GPR_ASSERT(channel_args->args[i].type == GRPC_ARG_POINTER); - grpc_socket_mutator *mutator = - (grpc_socket_mutator *)channel_args->args[i].value.pointer.p; + grpc_socket_mutator* mutator = + (grpc_socket_mutator*)channel_args->args[i].value.pointer.p; err = grpc_set_socket_with_mutator(fd, mutator); if (err != GRPC_ERROR_NONE) goto error; } @@ -96,18 +96,19 @@ done: return err; } -static void tc_on_alarm(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { +static void tc_on_alarm(grpc_exec_ctx* exec_ctx, void* acp, grpc_error* error) { int done; - async_connect *ac = (async_connect *)acp; - if (GRPC_TRACER_ON(grpc_tcp_trace)) { - const char *str = grpc_error_string(error); + async_connect* ac = (async_connect*)acp; + if (grpc_tcp_trace.enabled()) { + const char* str = grpc_error_string(error); gpr_log(GPR_DEBUG, "CLIENT_CONNECT: %s: on_alarm: error=%s", ac->addr_str, str); } gpr_mu_lock(&ac->mu); - if (ac->fd != NULL) { - grpc_fd_shutdown(exec_ctx, ac->fd, GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "connect() timed out")); + if (ac->fd != nullptr) { + grpc_fd_shutdown( + exec_ctx, ac->fd, + GRPC_ERROR_CREATE_FROM_STATIC_STRING("connect() timed out")); } done = (--ac->refs == 0); gpr_mu_unlock(&ac->mu); @@ -119,26 +120,26 @@ static void tc_on_alarm(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { } } -grpc_endpoint *grpc_tcp_client_create_from_fd( - grpc_exec_ctx *exec_ctx, grpc_fd *fd, const grpc_channel_args *channel_args, - const char *addr_str) { +grpc_endpoint* grpc_tcp_client_create_from_fd( + grpc_exec_ctx* exec_ctx, grpc_fd* fd, const grpc_channel_args* channel_args, + const char* addr_str) { return grpc_tcp_create(exec_ctx, fd, channel_args, addr_str); } -static void on_writable(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { - async_connect *ac = (async_connect *)acp; +static void on_writable(grpc_exec_ctx* exec_ctx, void* acp, grpc_error* error) { + async_connect* ac = (async_connect*)acp; int so_error = 0; socklen_t so_error_size; int err; int done; - grpc_endpoint **ep = ac->ep; - grpc_closure *closure = ac->closure; - grpc_fd *fd; + grpc_endpoint** ep = ac->ep; + grpc_closure* closure = ac->closure; + grpc_fd* fd; GRPC_ERROR_REF(error); - if (GRPC_TRACER_ON(grpc_tcp_trace)) { - const char *str = grpc_error_string(error); + if (grpc_tcp_trace.enabled()) { + const char* str = grpc_error_string(error); gpr_log(GPR_DEBUG, "CLIENT_CONNECT: %s: on_writable: error=%s", ac->addr_str, str); } @@ -146,7 +147,7 @@ static void on_writable(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { gpr_mu_lock(&ac->mu); GPR_ASSERT(ac->fd); fd = ac->fd; - ac->fd = NULL; + ac->fd = nullptr; gpr_mu_unlock(&ac->mu); grpc_timer_cancel(exec_ctx, &ac->alarm); @@ -174,7 +175,7 @@ static void on_writable(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { grpc_pollset_set_del_fd(exec_ctx, ac->interested_parties, fd); *ep = grpc_tcp_client_create_from_fd(exec_ctx, fd, ac->channel_args, ac->addr_str); - fd = NULL; + fd = nullptr; break; case ENOBUFS: /* We will get one of these errors if we have run out of @@ -207,20 +208,20 @@ static void on_writable(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { } finish: - if (fd != NULL) { + if (fd != nullptr) { grpc_pollset_set_del_fd(exec_ctx, ac->interested_parties, fd); - grpc_fd_orphan(exec_ctx, fd, NULL, NULL, false /* already_closed */, + grpc_fd_orphan(exec_ctx, fd, nullptr, nullptr, false /* already_closed */, "tcp_client_orphan"); - fd = NULL; + fd = nullptr; } done = (--ac->refs == 0); gpr_mu_unlock(&ac->mu); if (error != GRPC_ERROR_NONE) { - char *error_descr; + char* error_descr; grpc_slice str; bool ret = grpc_error_get_str(error, GRPC_ERROR_STR_DESCRIPTION, &str); GPR_ASSERT(ret); - char *desc = grpc_slice_to_c_string(str); + char* desc = grpc_slice_to_c_string(str); gpr_asprintf(&error_descr, "Failed to connect to remote host: %s", desc); error = grpc_error_set_str(error, GRPC_ERROR_STR_DESCRIPTION, grpc_slice_from_copied_string(error_descr)); @@ -238,24 +239,24 @@ finish: GRPC_CLOSURE_SCHED(exec_ctx, closure, error); } -static void tcp_client_connect_impl(grpc_exec_ctx *exec_ctx, - grpc_closure *closure, grpc_endpoint **ep, - grpc_pollset_set *interested_parties, - const grpc_channel_args *channel_args, - const grpc_resolved_address *addr, +static void tcp_client_connect_impl(grpc_exec_ctx* exec_ctx, + grpc_closure* closure, grpc_endpoint** ep, + grpc_pollset_set* interested_parties, + const grpc_channel_args* channel_args, + const grpc_resolved_address* addr, grpc_millis deadline) { int fd; grpc_dualstack_mode dsmode; int err; - async_connect *ac; + async_connect* ac; grpc_resolved_address addr6_v4mapped; grpc_resolved_address addr4_copy; - grpc_fd *fdobj; - char *name; - char *addr_str; - grpc_error *error; + grpc_fd* fdobj; + char* name; + char* addr_str; + grpc_error* error; - *ep = NULL; + *ep = nullptr; /* Use dualstack sockets where available. */ if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) { @@ -279,8 +280,7 @@ static void tcp_client_connect_impl(grpc_exec_ctx *exec_ctx, do { GPR_ASSERT(addr->len < ~(socklen_t)0); - err = - connect(fd, (const struct sockaddr *)addr->addr, (socklen_t)addr->len); + err = connect(fd, (const struct sockaddr*)addr->addr, (socklen_t)addr->len); } while (err < 0 && errno == EINTR); addr_str = grpc_sockaddr_to_uri(addr); @@ -296,28 +296,28 @@ static void tcp_client_connect_impl(grpc_exec_ctx *exec_ctx, } if (errno != EWOULDBLOCK && errno != EINPROGRESS) { - grpc_fd_orphan(exec_ctx, fdobj, NULL, NULL, false /* already_closed */, - "tcp_client_connect_error"); + grpc_fd_orphan(exec_ctx, fdobj, nullptr, nullptr, + false /* already_closed */, "tcp_client_connect_error"); GRPC_CLOSURE_SCHED(exec_ctx, closure, GRPC_OS_ERROR(errno, "connect")); goto done; } grpc_pollset_set_add_fd(exec_ctx, interested_parties, fdobj); - ac = (async_connect *)gpr_malloc(sizeof(async_connect)); + ac = (async_connect*)gpr_malloc(sizeof(async_connect)); ac->closure = closure; ac->ep = ep; ac->fd = fdobj; ac->interested_parties = interested_parties; ac->addr_str = addr_str; - addr_str = NULL; + addr_str = nullptr; gpr_mu_init(&ac->mu); ac->refs = 2; GRPC_CLOSURE_INIT(&ac->write_closure, on_writable, ac, grpc_schedule_on_exec_ctx); ac->channel_args = grpc_channel_args_copy(channel_args); - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "CLIENT_CONNECT: %s: asynchronously connecting fd %p", ac->addr_str, fdobj); } @@ -334,19 +334,17 @@ done: } // overridden by api_fuzzer.c -extern "C" { void (*grpc_tcp_client_connect_impl)( - grpc_exec_ctx *exec_ctx, grpc_closure *closure, grpc_endpoint **ep, - grpc_pollset_set *interested_parties, const grpc_channel_args *channel_args, - const grpc_resolved_address *addr, + grpc_exec_ctx* exec_ctx, grpc_closure* closure, grpc_endpoint** ep, + grpc_pollset_set* interested_parties, const grpc_channel_args* channel_args, + const grpc_resolved_address* addr, grpc_millis deadline) = tcp_client_connect_impl; -} -void grpc_tcp_client_connect(grpc_exec_ctx *exec_ctx, grpc_closure *closure, - grpc_endpoint **ep, - grpc_pollset_set *interested_parties, - const grpc_channel_args *channel_args, - const grpc_resolved_address *addr, +void grpc_tcp_client_connect(grpc_exec_ctx* exec_ctx, grpc_closure* closure, + grpc_endpoint** ep, + grpc_pollset_set* interested_parties, + const grpc_channel_args* channel_args, + const grpc_resolved_address* addr, grpc_millis deadline) { grpc_tcp_client_connect_impl(exec_ctx, closure, ep, interested_parties, channel_args, addr, deadline); diff --git a/src/core/lib/iomgr/tcp_client_posix.h b/src/core/lib/iomgr/tcp_client_posix.h index 8740511804d..2b1fe79e902 100644 --- a/src/core/lib/iomgr/tcp_client_posix.h +++ b/src/core/lib/iomgr/tcp_client_posix.h @@ -23,16 +23,8 @@ #include "src/core/lib/iomgr/ev_posix.h" #include "src/core/lib/iomgr/tcp_client.h" -#ifdef __cplusplus -extern "C" { -#endif - -grpc_endpoint *grpc_tcp_client_create_from_fd( - grpc_exec_ctx *exec_ctx, grpc_fd *fd, const grpc_channel_args *channel_args, - const char *addr_str); - -#ifdef __cplusplus -} -#endif +grpc_endpoint* grpc_tcp_client_create_from_fd( + grpc_exec_ctx* exec_ctx, grpc_fd* fd, const grpc_channel_args* channel_args, + const char* addr_str); #endif /* GRPC_CORE_LIB_IOMGR_TCP_CLIENT_POSIX_H */ diff --git a/src/core/lib/iomgr/tcp_client_uv.cc b/src/core/lib/iomgr/tcp_client_uv.cc index f3e9366299d..5cca0c9936d 100644 --- a/src/core/lib/iomgr/tcp_client_uv.cc +++ b/src/core/lib/iomgr/tcp_client_uv.cc @@ -32,35 +32,35 @@ #include "src/core/lib/iomgr/tcp_uv.h" #include "src/core/lib/iomgr/timer.h" -extern grpc_tracer_flag grpc_tcp_trace; +extern grpc_core::TraceFlag grpc_tcp_trace; typedef struct grpc_uv_tcp_connect { uv_connect_t connect_req; grpc_timer alarm; grpc_closure on_alarm; - uv_tcp_t *tcp_handle; - grpc_closure *closure; - grpc_endpoint **endpoint; + uv_tcp_t* tcp_handle; + grpc_closure* closure; + grpc_endpoint** endpoint; int refs; - char *addr_name; - grpc_resource_quota *resource_quota; + char* addr_name; + grpc_resource_quota* resource_quota; } grpc_uv_tcp_connect; -static void uv_tcp_connect_cleanup(grpc_exec_ctx *exec_ctx, - grpc_uv_tcp_connect *connect) { +static void uv_tcp_connect_cleanup(grpc_exec_ctx* exec_ctx, + grpc_uv_tcp_connect* connect) { grpc_resource_quota_unref_internal(exec_ctx, connect->resource_quota); gpr_free(connect->addr_name); gpr_free(connect); } -static void tcp_close_callback(uv_handle_t *handle) { gpr_free(handle); } +static void tcp_close_callback(uv_handle_t* handle) { gpr_free(handle); } -static void uv_tc_on_alarm(grpc_exec_ctx *exec_ctx, void *acp, - grpc_error *error) { +static void uv_tc_on_alarm(grpc_exec_ctx* exec_ctx, void* acp, + grpc_error* error) { int done; - grpc_uv_tcp_connect *connect = (grpc_uv_tcp_connect *)acp; - if (GRPC_TRACER_ON(grpc_tcp_trace)) { - const char *str = grpc_error_string(error); + grpc_uv_tcp_connect* connect = (grpc_uv_tcp_connect*)acp; + if (grpc_tcp_trace.enabled()) { + const char* str = grpc_error_string(error); gpr_log(GPR_DEBUG, "CLIENT_CONNECT: %s: on_alarm: error=%s", connect->addr_name, str); } @@ -68,7 +68,7 @@ static void uv_tc_on_alarm(grpc_exec_ctx *exec_ctx, void *acp, /* error == NONE implies that the timer ran out, and wasn't cancelled. If it was cancelled, then the handler that cancelled it also should close the handle, if applicable */ - uv_close((uv_handle_t *)connect->tcp_handle, tcp_close_callback); + uv_close((uv_handle_t*)connect->tcp_handle, tcp_close_callback); } done = (--connect->refs == 0); if (done) { @@ -76,12 +76,12 @@ static void uv_tc_on_alarm(grpc_exec_ctx *exec_ctx, void *acp, } } -static void uv_tc_on_connect(uv_connect_t *req, int status) { - grpc_uv_tcp_connect *connect = (grpc_uv_tcp_connect *)req->data; +static void uv_tc_on_connect(uv_connect_t* req, int status) { + grpc_uv_tcp_connect* connect = (grpc_uv_tcp_connect*)req->data; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; int done; - grpc_closure *closure = connect->closure; + grpc_closure* closure = connect->closure; grpc_timer_cancel(&exec_ctx, &connect->alarm); if (status == 0) { *connect->endpoint = grpc_tcp_create( @@ -102,7 +102,7 @@ static void uv_tc_on_connect(uv_connect_t *req, int status) { error = grpc_error_set_str( error, GRPC_ERROR_STR_OS_ERROR, grpc_slice_from_static_string(uv_strerror(status))); - uv_close((uv_handle_t *)connect->tcp_handle, tcp_close_callback); + uv_close((uv_handle_t*)connect->tcp_handle, tcp_close_callback); } } done = (--connect->refs == 0); @@ -114,14 +114,14 @@ static void uv_tc_on_connect(uv_connect_t *req, int status) { grpc_exec_ctx_finish(&exec_ctx); } -static void tcp_client_connect_impl(grpc_exec_ctx *exec_ctx, - grpc_closure *closure, grpc_endpoint **ep, - grpc_pollset_set *interested_parties, - const grpc_channel_args *channel_args, - const grpc_resolved_address *resolved_addr, +static void tcp_client_connect_impl(grpc_exec_ctx* exec_ctx, + grpc_closure* closure, grpc_endpoint** ep, + grpc_pollset_set* interested_parties, + const grpc_channel_args* channel_args, + const grpc_resolved_address* resolved_addr, grpc_millis deadline) { - grpc_uv_tcp_connect *connect; - grpc_resource_quota *resource_quota = grpc_resource_quota_create(NULL); + grpc_uv_tcp_connect* connect; + grpc_resource_quota* resource_quota = grpc_resource_quota_create(NULL); (void)channel_args; (void)interested_parties; @@ -132,49 +132,46 @@ static void tcp_client_connect_impl(grpc_exec_ctx *exec_ctx, if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) { grpc_resource_quota_unref_internal(exec_ctx, resource_quota); resource_quota = grpc_resource_quota_ref_internal( - (grpc_resource_quota *)channel_args->args[i].value.pointer.p); + (grpc_resource_quota*)channel_args->args[i].value.pointer.p); } } } - connect = (grpc_uv_tcp_connect *)gpr_zalloc(sizeof(grpc_uv_tcp_connect)); + connect = (grpc_uv_tcp_connect*)gpr_zalloc(sizeof(grpc_uv_tcp_connect)); connect->closure = closure; connect->endpoint = ep; - connect->tcp_handle = (uv_tcp_t *)gpr_malloc(sizeof(uv_tcp_t)); + connect->tcp_handle = (uv_tcp_t*)gpr_malloc(sizeof(uv_tcp_t)); connect->addr_name = grpc_sockaddr_to_uri(resolved_addr); connect->resource_quota = resource_quota; uv_tcp_init(uv_default_loop(), connect->tcp_handle); connect->connect_req.data = connect; connect->refs = 2; // One for the connect operation, one for the timer. - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "CLIENT_CONNECT: %s: asynchronously connecting", connect->addr_name); } // TODO(murgatroid99): figure out what the return value here means uv_tcp_connect(&connect->connect_req, connect->tcp_handle, - (const struct sockaddr *)resolved_addr->addr, - uv_tc_on_connect); + (const struct sockaddr*)resolved_addr->addr, uv_tc_on_connect); GRPC_CLOSURE_INIT(&connect->on_alarm, uv_tc_on_alarm, connect, grpc_schedule_on_exec_ctx); grpc_timer_init(exec_ctx, &connect->alarm, deadline, &connect->on_alarm); } // overridden by api_fuzzer.c -extern "C" { void (*grpc_tcp_client_connect_impl)( - grpc_exec_ctx *exec_ctx, grpc_closure *closure, grpc_endpoint **ep, - grpc_pollset_set *interested_parties, const grpc_channel_args *channel_args, - const grpc_resolved_address *addr, + grpc_exec_ctx* exec_ctx, grpc_closure* closure, grpc_endpoint** ep, + grpc_pollset_set* interested_parties, const grpc_channel_args* channel_args, + const grpc_resolved_address* addr, grpc_millis deadline) = tcp_client_connect_impl; -} -void grpc_tcp_client_connect(grpc_exec_ctx *exec_ctx, grpc_closure *closure, - grpc_endpoint **ep, - grpc_pollset_set *interested_parties, - const grpc_channel_args *channel_args, - const grpc_resolved_address *addr, +void grpc_tcp_client_connect(grpc_exec_ctx* exec_ctx, grpc_closure* closure, + grpc_endpoint** ep, + grpc_pollset_set* interested_parties, + const grpc_channel_args* channel_args, + const grpc_resolved_address* addr, grpc_millis deadline) { grpc_tcp_client_connect_impl(exec_ctx, closure, ep, interested_parties, channel_args, addr, deadline); diff --git a/src/core/lib/iomgr/tcp_client_windows.cc b/src/core/lib/iomgr/tcp_client_windows.cc index 9adf7ee4e9c..5e30725e904 100644 --- a/src/core/lib/iomgr/tcp_client_windows.cc +++ b/src/core/lib/iomgr/tcp_client_windows.cc @@ -40,21 +40,21 @@ #include "src/core/lib/iomgr/timer.h" typedef struct { - grpc_closure *on_done; + grpc_closure* on_done; gpr_mu mu; - grpc_winsocket *socket; + grpc_winsocket* socket; grpc_timer alarm; grpc_closure on_alarm; - char *addr_name; + char* addr_name; int refs; grpc_closure on_connect; - grpc_endpoint **endpoint; - grpc_channel_args *channel_args; + grpc_endpoint** endpoint; + grpc_channel_args* channel_args; } async_connect; -static void async_connect_unlock_and_cleanup(grpc_exec_ctx *exec_ctx, - async_connect *ac, - grpc_winsocket *socket) { +static void async_connect_unlock_and_cleanup(grpc_exec_ctx* exec_ctx, + async_connect* ac, + grpc_winsocket* socket) { int done = (--ac->refs == 0); gpr_mu_unlock(&ac->mu); if (done) { @@ -66,10 +66,10 @@ static void async_connect_unlock_and_cleanup(grpc_exec_ctx *exec_ctx, if (socket != NULL) grpc_winsocket_destroy(socket); } -static void on_alarm(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { - async_connect *ac = (async_connect *)acp; +static void on_alarm(grpc_exec_ctx* exec_ctx, void* acp, grpc_error* error) { + async_connect* ac = (async_connect*)acp; gpr_mu_lock(&ac->mu); - grpc_winsocket *socket = ac->socket; + grpc_winsocket* socket = ac->socket; ac->socket = NULL; if (socket != NULL) { grpc_winsocket_shutdown(socket); @@ -77,16 +77,16 @@ static void on_alarm(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { async_connect_unlock_and_cleanup(exec_ctx, ac, socket); } -static void on_connect(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { - async_connect *ac = (async_connect *)acp; - grpc_endpoint **ep = ac->endpoint; +static void on_connect(grpc_exec_ctx* exec_ctx, void* acp, grpc_error* error) { + async_connect* ac = (async_connect*)acp; + grpc_endpoint** ep = ac->endpoint; GPR_ASSERT(*ep == NULL); - grpc_closure *on_done = ac->on_done; + grpc_closure* on_done = ac->on_done; GRPC_ERROR_REF(error); gpr_mu_lock(&ac->mu); - grpc_winsocket *socket = ac->socket; + grpc_winsocket* socket = ac->socket; ac->socket = NULL; gpr_mu_unlock(&ac->mu); @@ -123,21 +123,21 @@ static void on_connect(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { /* Tries to issue one async connection, then schedules both an IOCP notification request for the connection, and one timeout alert. */ static void tcp_client_connect_impl( - grpc_exec_ctx *exec_ctx, grpc_closure *on_done, grpc_endpoint **endpoint, - grpc_pollset_set *interested_parties, const grpc_channel_args *channel_args, - const grpc_resolved_address *addr, grpc_millis deadline) { + grpc_exec_ctx* exec_ctx, grpc_closure* on_done, grpc_endpoint** endpoint, + grpc_pollset_set* interested_parties, const grpc_channel_args* channel_args, + const grpc_resolved_address* addr, grpc_millis deadline) { SOCKET sock = INVALID_SOCKET; BOOL success; int status; grpc_resolved_address addr6_v4mapped; grpc_resolved_address local_address; - async_connect *ac; - grpc_winsocket *socket = NULL; + async_connect* ac; + grpc_winsocket* socket = NULL; LPFN_CONNECTEX ConnectEx; GUID guid = WSAID_CONNECTEX; DWORD ioctl_num_bytes; - grpc_winsocket_callback_info *info; - grpc_error *error = GRPC_ERROR_NONE; + grpc_winsocket_callback_info* info; + grpc_error* error = GRPC_ERROR_NONE; *endpoint = NULL; @@ -172,8 +172,8 @@ static void tcp_client_connect_impl( grpc_sockaddr_make_wildcard6(0, &local_address); - status = bind(sock, (struct sockaddr *)&local_address.addr, - (int)local_address.len); + status = + bind(sock, (struct sockaddr*)&local_address.addr, (int)local_address.len); if (status != 0) { error = GRPC_WSA_ERROR(WSAGetLastError(), "bind"); goto failure; @@ -181,8 +181,8 @@ static void tcp_client_connect_impl( socket = grpc_winsocket_create(sock, "client"); info = &socket->write_info; - success = ConnectEx(sock, (struct sockaddr *)&addr->addr, (int)addr->len, - NULL, 0, NULL, &info->overlapped); + success = ConnectEx(sock, (struct sockaddr*)&addr->addr, (int)addr->len, NULL, + 0, NULL, &info->overlapped); /* It wouldn't be unusual to get a success immediately. But we'll still get an IOCP notification, so let's ignore it. */ @@ -194,7 +194,7 @@ static void tcp_client_connect_impl( } } - ac = (async_connect *)gpr_malloc(sizeof(async_connect)); + ac = (async_connect*)gpr_malloc(sizeof(async_connect)); ac->on_done = on_done; ac->socket = socket; gpr_mu_init(&ac->mu); @@ -211,8 +211,8 @@ static void tcp_client_connect_impl( failure: GPR_ASSERT(error != GRPC_ERROR_NONE); - char *target_uri = grpc_sockaddr_to_uri(addr); - grpc_error *final_error = grpc_error_set_str( + char* target_uri = grpc_sockaddr_to_uri(addr); + grpc_error* final_error = grpc_error_set_str( GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING("Failed to connect", &error, 1), GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(target_uri)); @@ -226,19 +226,17 @@ failure: } // overridden by api_fuzzer.c -extern "C" { void (*grpc_tcp_client_connect_impl)( - grpc_exec_ctx *exec_ctx, grpc_closure *closure, grpc_endpoint **ep, - grpc_pollset_set *interested_parties, const grpc_channel_args *channel_args, - const grpc_resolved_address *addr, + grpc_exec_ctx* exec_ctx, grpc_closure* closure, grpc_endpoint** ep, + grpc_pollset_set* interested_parties, const grpc_channel_args* channel_args, + const grpc_resolved_address* addr, grpc_millis deadline) = tcp_client_connect_impl; -} -void grpc_tcp_client_connect(grpc_exec_ctx *exec_ctx, grpc_closure *closure, - grpc_endpoint **ep, - grpc_pollset_set *interested_parties, - const grpc_channel_args *channel_args, - const grpc_resolved_address *addr, +void grpc_tcp_client_connect(grpc_exec_ctx* exec_ctx, grpc_closure* closure, + grpc_endpoint** ep, + grpc_pollset_set* interested_parties, + const grpc_channel_args* channel_args, + const grpc_resolved_address* addr, grpc_millis deadline) { grpc_tcp_client_connect_impl(exec_ctx, closure, ep, interested_parties, channel_args, addr, deadline); diff --git a/src/core/lib/iomgr/tcp_posix.cc b/src/core/lib/iomgr/tcp_posix.cc index b7c1803ded1..d09cfca9af4 100644 --- a/src/core/lib/iomgr/tcp_posix.cc +++ b/src/core/lib/iomgr/tcp_posix.cc @@ -61,11 +61,11 @@ typedef GRPC_MSG_IOVLEN_TYPE msg_iovlen_type; typedef size_t msg_iovlen_type; #endif -grpc_tracer_flag grpc_tcp_trace = GRPC_TRACER_INITIALIZER(false, "tcp"); +grpc_core::TraceFlag grpc_tcp_trace(false, "tcp"); typedef struct { grpc_endpoint base; - grpc_fd *em_fd; + grpc_fd* em_fd; int fd; bool finished_edge; double target_length; @@ -79,59 +79,57 @@ typedef struct { /* garbage after the last read */ grpc_slice_buffer last_read_buffer; - grpc_slice_buffer *incoming_buffer; - grpc_slice_buffer *outgoing_buffer; - /** slice within outgoing_buffer to write next */ - size_t outgoing_slice_idx; - /** byte within outgoing_buffer->slices[outgoing_slice_idx] to write next */ + grpc_slice_buffer* incoming_buffer; + grpc_slice_buffer* outgoing_buffer; + /** byte within outgoing_buffer->slices[0] to write next */ size_t outgoing_byte_idx; - grpc_closure *read_cb; - grpc_closure *write_cb; - grpc_closure *release_fd_cb; - int *release_fd; + grpc_closure* read_cb; + grpc_closure* write_cb; + grpc_closure* release_fd_cb; + int* release_fd; grpc_closure read_done_closure; grpc_closure write_done_closure; - char *peer_string; + char* peer_string; - grpc_resource_user *resource_user; + grpc_resource_user* resource_user; grpc_resource_user_slice_allocator slice_allocator; } grpc_tcp; typedef struct backup_poller { - gpr_mu *pollset_mu; + gpr_mu* pollset_mu; grpc_closure run_poller; } backup_poller; -#define BACKUP_POLLER_POLLSET(b) ((grpc_pollset *)((b) + 1)) +#define BACKUP_POLLER_POLLSET(b) ((grpc_pollset*)((b) + 1)) static gpr_atm g_uncovered_notifications_pending; static gpr_atm g_backup_poller; /* backup_poller* */ -static void tcp_handle_read(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */, - grpc_error *error); -static void tcp_handle_write(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */, - grpc_error *error); -static void tcp_drop_uncovered_then_handle_write(grpc_exec_ctx *exec_ctx, - void *arg /* grpc_tcp */, - grpc_error *error); - -static void done_poller(grpc_exec_ctx *exec_ctx, void *bp, - grpc_error *error_ignored) { - backup_poller *p = (backup_poller *)bp; - if (GRPC_TRACER_ON(grpc_tcp_trace)) { +static void tcp_handle_read(grpc_exec_ctx* exec_ctx, void* arg /* grpc_tcp */, + grpc_error* error); +static void tcp_handle_write(grpc_exec_ctx* exec_ctx, void* arg /* grpc_tcp */, + grpc_error* error); +static void tcp_drop_uncovered_then_handle_write(grpc_exec_ctx* exec_ctx, + void* arg /* grpc_tcp */, + grpc_error* error); + +static void done_poller(grpc_exec_ctx* exec_ctx, void* bp, + grpc_error* error_ignored) { + backup_poller* p = (backup_poller*)bp; + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "BACKUP_POLLER:%p destroy", p); } grpc_pollset_destroy(exec_ctx, BACKUP_POLLER_POLLSET(p)); gpr_free(p); } -static void run_poller(grpc_exec_ctx *exec_ctx, void *bp, - grpc_error *error_ignored) { - backup_poller *p = (backup_poller *)bp; - if (GRPC_TRACER_ON(grpc_tcp_trace)) { +static void run_poller(grpc_exec_ctx* exec_ctx, void* bp, + grpc_error* error_ignored) { + backup_poller* p = (backup_poller*)bp; + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "BACKUP_POLLER:%p run", p); } gpr_mu_lock(p->pollset_mu); @@ -139,7 +137,7 @@ static void run_poller(grpc_exec_ctx *exec_ctx, void *bp, GRPC_STATS_INC_TCP_BACKUP_POLLER_POLLS(exec_ctx); GRPC_LOG_IF_ERROR( "backup_poller:pollset_work", - grpc_pollset_work(exec_ctx, BACKUP_POLLER_POLLSET(p), NULL, deadline)); + grpc_pollset_work(exec_ctx, BACKUP_POLLER_POLLSET(p), nullptr, deadline)); gpr_mu_unlock(p->pollset_mu); /* last "uncovered" notification is the ref that keeps us polling, if we get * there try a cas to release it */ @@ -147,47 +145,47 @@ static void run_poller(grpc_exec_ctx *exec_ctx, void *bp, gpr_atm_full_cas(&g_uncovered_notifications_pending, 1, 0)) { gpr_mu_lock(p->pollset_mu); bool cas_ok = gpr_atm_full_cas(&g_backup_poller, (gpr_atm)p, 0); - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "BACKUP_POLLER:%p done cas_ok=%d", p, cas_ok); } gpr_mu_unlock(p->pollset_mu); - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "BACKUP_POLLER:%p shutdown", p); } grpc_pollset_shutdown(exec_ctx, BACKUP_POLLER_POLLSET(p), GRPC_CLOSURE_INIT(&p->run_poller, done_poller, p, grpc_schedule_on_exec_ctx)); } else { - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "BACKUP_POLLER:%p reschedule", p); } GRPC_CLOSURE_SCHED(exec_ctx, &p->run_poller, GRPC_ERROR_NONE); } } -static void drop_uncovered(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { - backup_poller *p = (backup_poller *)gpr_atm_acq_load(&g_backup_poller); +static void drop_uncovered(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp) { + backup_poller* p = (backup_poller*)gpr_atm_acq_load(&g_backup_poller); gpr_atm old_count = gpr_atm_no_barrier_fetch_add(&g_uncovered_notifications_pending, -1); - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "BACKUP_POLLER:%p uncover cnt %d->%d", p, (int)old_count, (int)old_count - 1); } GPR_ASSERT(old_count != 1); } -static void cover_self(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { - backup_poller *p; +static void cover_self(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp) { + backup_poller* p; gpr_atm old_count = gpr_atm_no_barrier_fetch_add(&g_uncovered_notifications_pending, 2); - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "BACKUP_POLLER: cover cnt %d->%d", (int)old_count, 2 + (int)old_count); } if (old_count == 0) { GRPC_STATS_INC_TCP_BACKUP_POLLERS_CREATED(exec_ctx); - p = (backup_poller *)gpr_zalloc(sizeof(*p) + grpc_pollset_size()); - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + p = (backup_poller*)gpr_zalloc(sizeof(*p) + grpc_pollset_size()); + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "BACKUP_POLLER:%p create", p); } grpc_pollset_init(BACKUP_POLLER_POLLSET(p), &p->pollset_mu); @@ -198,11 +196,12 @@ static void cover_self(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { grpc_executor_scheduler(GRPC_EXECUTOR_LONG)), GRPC_ERROR_NONE); } else { - while ((p = (backup_poller *)gpr_atm_acq_load(&g_backup_poller)) == NULL) { + while ((p = (backup_poller*)gpr_atm_acq_load(&g_backup_poller)) == + nullptr) { // spin waiting for backup poller } } - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "BACKUP_POLLER:%p add %p", p, tcp); } grpc_pollset_add_fd(exec_ctx, BACKUP_POLLER_POLLSET(p), tcp->em_fd); @@ -211,8 +210,8 @@ static void cover_self(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { } } -static void notify_on_read(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { - if (GRPC_TRACER_ON(grpc_tcp_trace)) { +static void notify_on_read(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "TCP:%p notify_on_read", tcp); } GRPC_CLOSURE_INIT(&tcp->read_done_closure, tcp_handle_read, tcp, @@ -220,8 +219,8 @@ static void notify_on_read(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { grpc_fd_notify_on_read(exec_ctx, tcp->em_fd, &tcp->read_done_closure); } -static void notify_on_write(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { - if (GRPC_TRACER_ON(grpc_tcp_trace)) { +static void notify_on_write(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "TCP:%p notify_on_write", tcp); } cover_self(exec_ctx, tcp); @@ -231,20 +230,20 @@ static void notify_on_write(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { grpc_fd_notify_on_write(exec_ctx, tcp->em_fd, &tcp->write_done_closure); } -static void tcp_drop_uncovered_then_handle_write(grpc_exec_ctx *exec_ctx, - void *arg, grpc_error *error) { - if (GRPC_TRACER_ON(grpc_tcp_trace)) { +static void tcp_drop_uncovered_then_handle_write(grpc_exec_ctx* exec_ctx, + void* arg, grpc_error* error) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "TCP:%p got_write: %s", arg, grpc_error_string(error)); } - drop_uncovered(exec_ctx, (grpc_tcp *)arg); + drop_uncovered(exec_ctx, (grpc_tcp*)arg); tcp_handle_write(exec_ctx, arg, error); } -static void add_to_estimate(grpc_tcp *tcp, size_t bytes) { +static void add_to_estimate(grpc_tcp* tcp, size_t bytes) { tcp->bytes_read_this_round += (double)bytes; } -static void finish_estimate(grpc_tcp *tcp) { +static void finish_estimate(grpc_tcp* tcp) { /* If we read >80% of the target buffer in one read loop, increase the size of the target buffer to either the amount read, or twice its previous value */ @@ -258,8 +257,8 @@ static void finish_estimate(grpc_tcp *tcp) { tcp->bytes_read_this_round = 0; } -static size_t get_target_read_size(grpc_tcp *tcp) { - grpc_resource_quota *rq = grpc_resource_user_quota(tcp->resource_user); +static size_t get_target_read_size(grpc_tcp* tcp) { + grpc_resource_quota* rq = grpc_resource_user_quota(tcp->resource_user); double pressure = grpc_resource_quota_get_memory_pressure(rq); double target = tcp->target_length * (pressure > 0.8 ? (1.0 - pressure) / 0.2 : 1.0); @@ -276,26 +275,26 @@ static size_t get_target_read_size(grpc_tcp *tcp) { return sz; } -static grpc_error *tcp_annotate_error(grpc_error *src_error, grpc_tcp *tcp) { +static grpc_error* tcp_annotate_error(grpc_error* src_error, grpc_tcp* tcp) { return grpc_error_set_str( grpc_error_set_int(src_error, GRPC_ERROR_INT_FD, tcp->fd), GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(tcp->peer_string)); } -static void tcp_handle_read(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */, - grpc_error *error); -static void tcp_handle_write(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */, - grpc_error *error); +static void tcp_handle_read(grpc_exec_ctx* exec_ctx, void* arg /* grpc_tcp */, + grpc_error* error); +static void tcp_handle_write(grpc_exec_ctx* exec_ctx, void* arg /* grpc_tcp */, + grpc_error* error); -static void tcp_shutdown(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_error *why) { - grpc_tcp *tcp = (grpc_tcp *)ep; +static void tcp_shutdown(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_error* why) { + grpc_tcp* tcp = (grpc_tcp*)ep; grpc_fd_shutdown(exec_ctx, tcp->em_fd, why); grpc_resource_user_shutdown(exec_ctx, tcp->resource_user); } -static void tcp_free(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { +static void tcp_free(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp) { grpc_fd_orphan(exec_ctx, tcp->em_fd, tcp->release_fd_cb, tcp->release_fd, false /* already_closed */, "tcp_unref_orphan"); grpc_slice_buffer_destroy_internal(exec_ctx, &tcp->last_read_buffer); @@ -308,9 +307,9 @@ static void tcp_free(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { #define TCP_UNREF(cl, tcp, reason) \ tcp_unref((cl), (tcp), (reason), __FILE__, __LINE__) #define TCP_REF(tcp, reason) tcp_ref((tcp), (reason), __FILE__, __LINE__) -static void tcp_unref(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp, - const char *reason, const char *file, int line) { - if (GRPC_TRACER_ON(grpc_tcp_trace)) { +static void tcp_unref(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp, + const char* reason, const char* file, int line) { + if (grpc_tcp_trace.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "TCP unref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp, reason, val, @@ -321,9 +320,9 @@ static void tcp_unref(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp, } } -static void tcp_ref(grpc_tcp *tcp, const char *reason, const char *file, +static void tcp_ref(grpc_tcp* tcp, const char* reason, const char* file, int line) { - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "TCP ref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp, reason, val, @@ -334,47 +333,47 @@ static void tcp_ref(grpc_tcp *tcp, const char *reason, const char *file, #else #define TCP_UNREF(cl, tcp, reason) tcp_unref((cl), (tcp)) #define TCP_REF(tcp, reason) tcp_ref((tcp)) -static void tcp_unref(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { +static void tcp_unref(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp) { if (gpr_unref(&tcp->refcount)) { tcp_free(exec_ctx, tcp); } } -static void tcp_ref(grpc_tcp *tcp) { gpr_ref(&tcp->refcount); } +static void tcp_ref(grpc_tcp* tcp) { gpr_ref(&tcp->refcount); } #endif -static void tcp_destroy(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) { +static void tcp_destroy(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep) { grpc_network_status_unregister_endpoint(ep); - grpc_tcp *tcp = (grpc_tcp *)ep; + grpc_tcp* tcp = (grpc_tcp*)ep; grpc_slice_buffer_reset_and_unref_internal(exec_ctx, &tcp->last_read_buffer); TCP_UNREF(exec_ctx, tcp, "destroy"); } -static void call_read_cb(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp, - grpc_error *error) { - grpc_closure *cb = tcp->read_cb; +static void call_read_cb(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp, + grpc_error* error) { + grpc_closure* cb = tcp->read_cb; - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "TCP:%p call_cb %p %p:%p", tcp, cb, cb->cb, cb->cb_arg); size_t i; - const char *str = grpc_error_string(error); + const char* str = grpc_error_string(error); gpr_log(GPR_DEBUG, "read: error=%s", str); for (i = 0; i < tcp->incoming_buffer->count; i++) { - char *dump = grpc_dump_slice(tcp->incoming_buffer->slices[i], + char* dump = grpc_dump_slice(tcp->incoming_buffer->slices[i], GPR_DUMP_HEX | GPR_DUMP_ASCII); gpr_log(GPR_DEBUG, "READ %p (peer=%s): %s", tcp, tcp->peer_string, dump); gpr_free(dump); } } - tcp->read_cb = NULL; - tcp->incoming_buffer = NULL; + tcp->read_cb = nullptr; + tcp->incoming_buffer = nullptr; GRPC_CLOSURE_RUN(exec_ctx, cb, error); } #define MAX_READ_IOVEC 4 -static void tcp_do_read(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { +static void tcp_do_read(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp) { struct msghdr msg; struct iovec iov[MAX_READ_IOVEC]; ssize_t read_bytes; @@ -389,11 +388,11 @@ static void tcp_do_read(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { iov[i].iov_len = GRPC_SLICE_LENGTH(tcp->incoming_buffer->slices[i]); } - msg.msg_name = NULL; + msg.msg_name = nullptr; msg.msg_namelen = 0; msg.msg_iov = iov; msg.msg_iovlen = (msg_iovlen_type)tcp->incoming_buffer->count; - msg.msg_control = NULL; + msg.msg_control = nullptr; msg.msg_controllen = 0; msg.msg_flags = 0; @@ -447,10 +446,10 @@ static void tcp_do_read(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { GPR_TIMER_END("tcp_continue_read", 0); } -static void tcp_read_allocation_done(grpc_exec_ctx *exec_ctx, void *tcpp, - grpc_error *error) { - grpc_tcp *tcp = (grpc_tcp *)tcpp; - if (GRPC_TRACER_ON(grpc_tcp_trace)) { +static void tcp_read_allocation_done(grpc_exec_ctx* exec_ctx, void* tcpp, + grpc_error* error) { + grpc_tcp* tcp = (grpc_tcp*)tcpp; + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "TCP:%p read_allocation_done: %s", tcp, grpc_error_string(error)); } @@ -465,28 +464,28 @@ static void tcp_read_allocation_done(grpc_exec_ctx *exec_ctx, void *tcpp, } } -static void tcp_continue_read(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { +static void tcp_continue_read(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp) { size_t target_read_size = get_target_read_size(tcp); if (tcp->incoming_buffer->length < target_read_size && tcp->incoming_buffer->count < MAX_READ_IOVEC) { - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "TCP:%p alloc_slices", tcp); } grpc_resource_user_alloc_slices(exec_ctx, &tcp->slice_allocator, target_read_size, 1, tcp->incoming_buffer); } else { - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "TCP:%p do_read", tcp); } tcp_do_read(exec_ctx, tcp); } } -static void tcp_handle_read(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */, - grpc_error *error) { - grpc_tcp *tcp = (grpc_tcp *)arg; +static void tcp_handle_read(grpc_exec_ctx* exec_ctx, void* arg /* grpc_tcp */, + grpc_error* error) { + grpc_tcp* tcp = (grpc_tcp*)arg; GPR_ASSERT(!tcp->finished_edge); - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "TCP:%p got_read: %s", tcp, grpc_error_string(error)); } @@ -501,10 +500,10 @@ static void tcp_handle_read(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */, } } -static void tcp_read(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_slice_buffer *incoming_buffer, grpc_closure *cb) { - grpc_tcp *tcp = (grpc_tcp *)ep; - GPR_ASSERT(tcp->read_cb == NULL); +static void tcp_read(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_slice_buffer* incoming_buffer, grpc_closure* cb) { + grpc_tcp* tcp = (grpc_tcp*)ep; + GPR_ASSERT(tcp->read_cb == nullptr); tcp->read_cb = cb; tcp->incoming_buffer = incoming_buffer; grpc_slice_buffer_reset_and_unref_internal(exec_ctx, incoming_buffer); @@ -520,8 +519,8 @@ static void tcp_read(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, /* returns true if done, false if pending; if returning true, *error is set */ #define MAX_WRITE_IOVEC 1000 -static bool tcp_flush(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp, - grpc_error **error) { +static bool tcp_flush(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp, + grpc_error** error) { struct msghdr msg; struct iovec iov[MAX_WRITE_IOVEC]; msg_iovlen_type iov_size; @@ -531,32 +530,35 @@ static bool tcp_flush(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp, size_t unwind_slice_idx; size_t unwind_byte_idx; + // We always start at zero, because we eagerly unref and trim the slice + // buffer as we write + size_t outgoing_slice_idx = 0; + for (;;) { sending_length = 0; - unwind_slice_idx = tcp->outgoing_slice_idx; + unwind_slice_idx = outgoing_slice_idx; unwind_byte_idx = tcp->outgoing_byte_idx; - for (iov_size = 0; tcp->outgoing_slice_idx != tcp->outgoing_buffer->count && + for (iov_size = 0; outgoing_slice_idx != tcp->outgoing_buffer->count && iov_size != MAX_WRITE_IOVEC; iov_size++) { iov[iov_size].iov_base = GRPC_SLICE_START_PTR( - tcp->outgoing_buffer->slices[tcp->outgoing_slice_idx]) + + tcp->outgoing_buffer->slices[outgoing_slice_idx]) + tcp->outgoing_byte_idx; iov[iov_size].iov_len = - GRPC_SLICE_LENGTH( - tcp->outgoing_buffer->slices[tcp->outgoing_slice_idx]) - + GRPC_SLICE_LENGTH(tcp->outgoing_buffer->slices[outgoing_slice_idx]) - tcp->outgoing_byte_idx; sending_length += iov[iov_size].iov_len; - tcp->outgoing_slice_idx++; + outgoing_slice_idx++; tcp->outgoing_byte_idx = 0; } GPR_ASSERT(iov_size > 0); - msg.msg_name = NULL; + msg.msg_name = nullptr; msg.msg_namelen = 0; msg.msg_iov = iov; msg.msg_iovlen = iov_size; - msg.msg_control = NULL; + msg.msg_control = nullptr; msg.msg_controllen = 0; msg.msg_flags = 0; @@ -573,16 +575,25 @@ static bool tcp_flush(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp, if (sent_length < 0) { if (errno == EAGAIN) { - tcp->outgoing_slice_idx = unwind_slice_idx; tcp->outgoing_byte_idx = unwind_byte_idx; + // unref all and forget about all slices that have been written to this + // point + for (size_t idx = 0; idx < unwind_slice_idx; ++idx) { + grpc_slice_unref_internal( + exec_ctx, grpc_slice_buffer_take_first(tcp->outgoing_buffer)); + } return false; } else if (errno == EPIPE) { *error = grpc_error_set_int(GRPC_OS_ERROR(errno, "sendmsg"), GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE); + grpc_slice_buffer_reset_and_unref_internal(exec_ctx, + tcp->outgoing_buffer); return true; } else { *error = tcp_annotate_error(GRPC_OS_ERROR(errno, "sendmsg"), tcp); + grpc_slice_buffer_reset_and_unref_internal(exec_ctx, + tcp->outgoing_buffer); return true; } } @@ -592,9 +603,9 @@ static bool tcp_flush(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp, while (trailing > 0) { size_t slice_length; - tcp->outgoing_slice_idx--; - slice_length = GRPC_SLICE_LENGTH( - tcp->outgoing_buffer->slices[tcp->outgoing_slice_idx]); + outgoing_slice_idx--; + slice_length = + GRPC_SLICE_LENGTH(tcp->outgoing_buffer->slices[outgoing_slice_idx]); if (slice_length > trailing) { tcp->outgoing_byte_idx = slice_length - trailing; break; @@ -603,36 +614,38 @@ static bool tcp_flush(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp, } } - if (tcp->outgoing_slice_idx == tcp->outgoing_buffer->count) { + if (outgoing_slice_idx == tcp->outgoing_buffer->count) { *error = GRPC_ERROR_NONE; + grpc_slice_buffer_reset_and_unref_internal(exec_ctx, + tcp->outgoing_buffer); return true; } - }; + } } -static void tcp_handle_write(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */, - grpc_error *error) { - grpc_tcp *tcp = (grpc_tcp *)arg; - grpc_closure *cb; +static void tcp_handle_write(grpc_exec_ctx* exec_ctx, void* arg /* grpc_tcp */, + grpc_error* error) { + grpc_tcp* tcp = (grpc_tcp*)arg; + grpc_closure* cb; if (error != GRPC_ERROR_NONE) { cb = tcp->write_cb; - tcp->write_cb = NULL; + tcp->write_cb = nullptr; cb->cb(exec_ctx, cb->cb_arg, error); TCP_UNREF(exec_ctx, tcp, "write"); return; } if (!tcp_flush(exec_ctx, tcp, &error)) { - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "write: delayed"); } notify_on_write(exec_ctx, tcp); } else { cb = tcp->write_cb; - tcp->write_cb = NULL; - if (GRPC_TRACER_ON(grpc_tcp_trace)) { - const char *str = grpc_error_string(error); + tcp->write_cb = nullptr; + if (grpc_tcp_trace.enabled()) { + const char* str = grpc_error_string(error); gpr_log(GPR_DEBUG, "write: %s", str); } @@ -641,16 +654,16 @@ static void tcp_handle_write(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */, } } -static void tcp_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_slice_buffer *buf, grpc_closure *cb) { - grpc_tcp *tcp = (grpc_tcp *)ep; - grpc_error *error = GRPC_ERROR_NONE; +static void tcp_write(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_slice_buffer* buf, grpc_closure* cb) { + grpc_tcp* tcp = (grpc_tcp*)ep; + grpc_error* error = GRPC_ERROR_NONE; - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { size_t i; for (i = 0; i < buf->count; i++) { - char *data = + char* data = grpc_dump_slice(buf->slices[i], GPR_DUMP_HEX | GPR_DUMP_ASCII); gpr_log(GPR_DEBUG, "WRITE %p (peer=%s): %s", tcp, tcp->peer_string, data); gpr_free(data); @@ -658,7 +671,7 @@ static void tcp_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, } GPR_TIMER_BEGIN("tcp_write", 0); - GPR_ASSERT(tcp->write_cb == NULL); + GPR_ASSERT(tcp->write_cb == nullptr); if (buf->length == 0) { GPR_TIMER_END("tcp_write", 0); @@ -671,19 +684,18 @@ static void tcp_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, return; } tcp->outgoing_buffer = buf; - tcp->outgoing_slice_idx = 0; tcp->outgoing_byte_idx = 0; if (!tcp_flush(exec_ctx, tcp, &error)) { TCP_REF(tcp, "write"); tcp->write_cb = cb; - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "write: delayed"); } notify_on_write(exec_ctx, tcp); } else { - if (GRPC_TRACER_ON(grpc_tcp_trace)) { - const char *str = grpc_error_string(error); + if (grpc_tcp_trace.enabled()) { + const char* str = grpc_error_string(error); gpr_log(GPR_DEBUG, "write: %s", str); } GRPC_CLOSURE_SCHED(exec_ctx, cb, error); @@ -692,37 +704,37 @@ static void tcp_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, GPR_TIMER_END("tcp_write", 0); } -static void tcp_add_to_pollset(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_pollset *pollset) { - grpc_tcp *tcp = (grpc_tcp *)ep; +static void tcp_add_to_pollset(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_pollset* pollset) { + grpc_tcp* tcp = (grpc_tcp*)ep; grpc_pollset_add_fd(exec_ctx, pollset, tcp->em_fd); } -static void tcp_add_to_pollset_set(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_pollset_set *pollset_set) { - grpc_tcp *tcp = (grpc_tcp *)ep; +static void tcp_add_to_pollset_set(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_pollset_set* pollset_set) { + grpc_tcp* tcp = (grpc_tcp*)ep; grpc_pollset_set_add_fd(exec_ctx, pollset_set, tcp->em_fd); } -static void tcp_delete_from_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_endpoint *ep, - grpc_pollset_set *pollset_set) { - grpc_tcp *tcp = (grpc_tcp *)ep; +static void tcp_delete_from_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_endpoint* ep, + grpc_pollset_set* pollset_set) { + grpc_tcp* tcp = (grpc_tcp*)ep; grpc_pollset_set_del_fd(exec_ctx, pollset_set, tcp->em_fd); } -static char *tcp_get_peer(grpc_endpoint *ep) { - grpc_tcp *tcp = (grpc_tcp *)ep; +static char* tcp_get_peer(grpc_endpoint* ep) { + grpc_tcp* tcp = (grpc_tcp*)ep; return gpr_strdup(tcp->peer_string); } -static int tcp_get_fd(grpc_endpoint *ep) { - grpc_tcp *tcp = (grpc_tcp *)ep; +static int tcp_get_fd(grpc_endpoint* ep) { + grpc_tcp* tcp = (grpc_tcp*)ep; return tcp->fd; } -static grpc_resource_user *tcp_get_resource_user(grpc_endpoint *ep) { - grpc_tcp *tcp = (grpc_tcp *)ep; +static grpc_resource_user* tcp_get_resource_user(grpc_endpoint* ep) { + grpc_tcp* tcp = (grpc_tcp*)ep; return tcp->resource_user; } @@ -739,14 +751,14 @@ static const grpc_endpoint_vtable vtable = {tcp_read, #define MAX_CHUNK_SIZE 32 * 1024 * 1024 -grpc_endpoint *grpc_tcp_create(grpc_exec_ctx *exec_ctx, grpc_fd *em_fd, - const grpc_channel_args *channel_args, - const char *peer_string) { +grpc_endpoint* grpc_tcp_create(grpc_exec_ctx* exec_ctx, grpc_fd* em_fd, + const grpc_channel_args* channel_args, + const char* peer_string) { int tcp_read_chunk_size = GRPC_TCP_DEFAULT_READ_SLICE_SIZE; int tcp_max_read_chunk_size = 4 * 1024 * 1024; int tcp_min_read_chunk_size = 256; - grpc_resource_quota *resource_quota = grpc_resource_quota_create(NULL); - if (channel_args != NULL) { + grpc_resource_quota* resource_quota = grpc_resource_quota_create(nullptr); + if (channel_args != nullptr) { for (size_t i = 0; i < channel_args->num_args; i++) { if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_TCP_READ_CHUNK_SIZE)) { @@ -770,7 +782,7 @@ grpc_endpoint *grpc_tcp_create(grpc_exec_ctx *exec_ctx, grpc_fd *em_fd, strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) { grpc_resource_quota_unref_internal(exec_ctx, resource_quota); resource_quota = grpc_resource_quota_ref_internal( - (grpc_resource_quota *)channel_args->args[i].value.pointer.p); + (grpc_resource_quota*)channel_args->args[i].value.pointer.p); } } } @@ -781,15 +793,15 @@ grpc_endpoint *grpc_tcp_create(grpc_exec_ctx *exec_ctx, grpc_fd *em_fd, tcp_read_chunk_size = GPR_CLAMP(tcp_read_chunk_size, tcp_min_read_chunk_size, tcp_max_read_chunk_size); - grpc_tcp *tcp = (grpc_tcp *)gpr_malloc(sizeof(grpc_tcp)); + grpc_tcp* tcp = (grpc_tcp*)gpr_malloc(sizeof(grpc_tcp)); tcp->base.vtable = &vtable; tcp->peer_string = gpr_strdup(peer_string); tcp->fd = grpc_fd_wrapped_fd(em_fd); - tcp->read_cb = NULL; - tcp->write_cb = NULL; - tcp->release_fd_cb = NULL; - tcp->release_fd = NULL; - tcp->incoming_buffer = NULL; + tcp->read_cb = nullptr; + tcp->write_cb = nullptr; + tcp->release_fd_cb = nullptr; + tcp->release_fd = nullptr; + tcp->incoming_buffer = nullptr; tcp->target_length = (double)tcp_read_chunk_size; tcp->min_read_chunk_size = tcp_min_read_chunk_size; tcp->max_read_chunk_size = tcp_max_read_chunk_size; @@ -810,16 +822,16 @@ grpc_endpoint *grpc_tcp_create(grpc_exec_ctx *exec_ctx, grpc_fd *em_fd, return &tcp->base; } -int grpc_tcp_fd(grpc_endpoint *ep) { - grpc_tcp *tcp = (grpc_tcp *)ep; +int grpc_tcp_fd(grpc_endpoint* ep) { + grpc_tcp* tcp = (grpc_tcp*)ep; GPR_ASSERT(ep->vtable == &vtable); return grpc_fd_wrapped_fd(tcp->em_fd); } -void grpc_tcp_destroy_and_release_fd(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - int *fd, grpc_closure *done) { +void grpc_tcp_destroy_and_release_fd(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + int* fd, grpc_closure* done) { grpc_network_status_unregister_endpoint(ep); - grpc_tcp *tcp = (grpc_tcp *)ep; + grpc_tcp* tcp = (grpc_tcp*)ep; GPR_ASSERT(ep->vtable == &vtable); tcp->release_fd = fd; tcp->release_fd_cb = done; diff --git a/src/core/lib/iomgr/tcp_posix.h b/src/core/lib/iomgr/tcp_posix.h index 47e78fa67e6..09051b7ed65 100644 --- a/src/core/lib/iomgr/tcp_posix.h +++ b/src/core/lib/iomgr/tcp_posix.h @@ -33,32 +33,24 @@ #include "src/core/lib/iomgr/endpoint.h" #include "src/core/lib/iomgr/ev_posix.h" -#ifdef __cplusplus -extern "C" { -#endif - -extern grpc_tracer_flag grpc_tcp_trace; +extern grpc_core::TraceFlag grpc_tcp_trace; /* Create a tcp endpoint given a file desciptor and a read slice size. Takes ownership of fd. */ -grpc_endpoint *grpc_tcp_create(grpc_exec_ctx *exec_ctx, grpc_fd *fd, - const grpc_channel_args *args, - const char *peer_string); +grpc_endpoint* grpc_tcp_create(grpc_exec_ctx* exec_ctx, grpc_fd* fd, + const grpc_channel_args* args, + const char* peer_string); /* Return the tcp endpoint's fd, or -1 if this is not available. Does not release the fd. Requires: ep must be a tcp endpoint. */ -int grpc_tcp_fd(grpc_endpoint *ep); +int grpc_tcp_fd(grpc_endpoint* ep); /* Destroy the tcp endpoint without closing its fd. *fd will be set and done * will be called when the endpoint is destroyed. * Requires: ep must be a tcp endpoint and fd must not be NULL. */ -void grpc_tcp_destroy_and_release_fd(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - int *fd, grpc_closure *done); - -#ifdef __cplusplus -} -#endif +void grpc_tcp_destroy_and_release_fd(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + int* fd, grpc_closure* done); #endif /* GRPC_CORE_LIB_IOMGR_TCP_POSIX_H */ diff --git a/src/core/lib/iomgr/tcp_server.h b/src/core/lib/iomgr/tcp_server.h index 8f9ce3819e6..a1757a2b3ee 100644 --- a/src/core/lib/iomgr/tcp_server.h +++ b/src/core/lib/iomgr/tcp_server.h @@ -25,17 +25,13 @@ #include "src/core/lib/iomgr/endpoint.h" #include "src/core/lib/iomgr/resolve_address.h" -#ifdef __cplusplus -extern "C" { -#endif - /* Forward decl of grpc_tcp_server */ typedef struct grpc_tcp_server grpc_tcp_server; typedef struct grpc_tcp_server_acceptor { /* grpc_tcp_server_cb functions share a ref on from_server that is valid until the function returns. */ - grpc_tcp_server *from_server; + grpc_tcp_server* from_server; /* Indices that may be passed to grpc_tcp_server_port_fd(). */ unsigned port_index; unsigned fd_index; @@ -43,23 +39,23 @@ typedef struct grpc_tcp_server_acceptor { /* Called for newly connected TCP connections. Takes ownership of acceptor. */ -typedef void (*grpc_tcp_server_cb)(grpc_exec_ctx *exec_ctx, void *arg, - grpc_endpoint *ep, - grpc_pollset *accepting_pollset, - grpc_tcp_server_acceptor *acceptor); +typedef void (*grpc_tcp_server_cb)(grpc_exec_ctx* exec_ctx, void* arg, + grpc_endpoint* ep, + grpc_pollset* accepting_pollset, + grpc_tcp_server_acceptor* acceptor); /* Create a server, initially not bound to any ports. The caller owns one ref. If shutdown_complete is not NULL, it will be used by grpc_tcp_server_unref() when the ref count reaches zero. */ -grpc_error *grpc_tcp_server_create(grpc_exec_ctx *exec_ctx, - grpc_closure *shutdown_complete, - const grpc_channel_args *args, - grpc_tcp_server **server); +grpc_error* grpc_tcp_server_create(grpc_exec_ctx* exec_ctx, + grpc_closure* shutdown_complete, + const grpc_channel_args* args, + grpc_tcp_server** server); /* Start listening to bound ports */ -void grpc_tcp_server_start(grpc_exec_ctx *exec_ctx, grpc_tcp_server *server, - grpc_pollset **pollsets, size_t pollset_count, - grpc_tcp_server_cb on_accept_cb, void *cb_arg); +void grpc_tcp_server_start(grpc_exec_ctx* exec_ctx, grpc_tcp_server* server, + grpc_pollset** pollsets, size_t pollset_count, + grpc_tcp_server_cb on_accept_cb, void* cb_arg); /* Add a port to the server, returning the newly allocated port on success, or -1 on failure. @@ -70,40 +66,36 @@ void grpc_tcp_server_start(grpc_exec_ctx *exec_ctx, grpc_tcp_server *server, but not dualstack sockets. */ /* TODO(ctiller): deprecate this, and make grpc_tcp_server_add_ports to handle all of the multiple socket port matching logic in one place */ -grpc_error *grpc_tcp_server_add_port(grpc_tcp_server *s, - const grpc_resolved_address *addr, - int *out_port); +grpc_error* grpc_tcp_server_add_port(grpc_tcp_server* s, + const grpc_resolved_address* addr, + int* out_port); /* Number of fds at the given port_index, or 0 if port_index is out of bounds. */ -unsigned grpc_tcp_server_port_fd_count(grpc_tcp_server *s, unsigned port_index); +unsigned grpc_tcp_server_port_fd_count(grpc_tcp_server* s, unsigned port_index); /* Returns the file descriptor of the Mth (fd_index) listening socket of the Nth (port_index) call to add_port() on this server, or -1 if the indices are out of bounds. The file descriptor remains owned by the server, and will be cleaned up when the ref count reaches zero. */ -int grpc_tcp_server_port_fd(grpc_tcp_server *s, unsigned port_index, +int grpc_tcp_server_port_fd(grpc_tcp_server* s, unsigned port_index, unsigned fd_index); /* Ref s and return s. */ -grpc_tcp_server *grpc_tcp_server_ref(grpc_tcp_server *s); +grpc_tcp_server* grpc_tcp_server_ref(grpc_tcp_server* s); /* shutdown_starting is called when ref count has reached zero and the server is about to be destroyed. The server will be deleted after it returns. Calling grpc_tcp_server_ref() from it has no effect. */ -void grpc_tcp_server_shutdown_starting_add(grpc_tcp_server *s, - grpc_closure *shutdown_starting); +void grpc_tcp_server_shutdown_starting_add(grpc_tcp_server* s, + grpc_closure* shutdown_starting); /* If the refcount drops to zero, enqueue calls on exec_ctx to shutdown_listeners and delete s. */ -void grpc_tcp_server_unref(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s); +void grpc_tcp_server_unref(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s); /* Shutdown the fds of listeners. */ -void grpc_tcp_server_shutdown_listeners(grpc_exec_ctx *exec_ctx, - grpc_tcp_server *s); - -#ifdef __cplusplus -} -#endif +void grpc_tcp_server_shutdown_listeners(grpc_exec_ctx* exec_ctx, + grpc_tcp_server* s); #endif /* GRPC_CORE_LIB_IOMGR_TCP_SERVER_H */ diff --git a/src/core/lib/iomgr/tcp_server_posix.cc b/src/core/lib/iomgr/tcp_server_posix.cc index 06612d639cc..6fed13c6c75 100644 --- a/src/core/lib/iomgr/tcp_server_posix.cc +++ b/src/core/lib/iomgr/tcp_server_posix.cc @@ -68,16 +68,16 @@ static void init(void) { #endif } -grpc_error *grpc_tcp_server_create(grpc_exec_ctx *exec_ctx, - grpc_closure *shutdown_complete, - const grpc_channel_args *args, - grpc_tcp_server **server) { +grpc_error* grpc_tcp_server_create(grpc_exec_ctx* exec_ctx, + grpc_closure* shutdown_complete, + const grpc_channel_args* args, + grpc_tcp_server** server) { gpr_once_init(&check_init, init); - grpc_tcp_server *s = (grpc_tcp_server *)gpr_zalloc(sizeof(grpc_tcp_server)); + grpc_tcp_server* s = (grpc_tcp_server*)gpr_zalloc(sizeof(grpc_tcp_server)); s->so_reuseport = has_so_reuseport; s->expand_wildcard_addrs = false; - for (size_t i = 0; i < (args == NULL ? 0 : args->num_args); i++) { + for (size_t i = 0; i < (args == nullptr ? 0 : args->num_args); i++) { if (0 == strcmp(GRPC_ARG_ALLOW_REUSEPORT, args->args[i].key)) { if (args->args[i].type == GRPC_ARG_INTEGER) { s->so_reuseport = @@ -102,13 +102,13 @@ grpc_error *grpc_tcp_server_create(grpc_exec_ctx *exec_ctx, s->active_ports = 0; s->destroyed_ports = 0; s->shutdown = false; - s->shutdown_starting.head = NULL; - s->shutdown_starting.tail = NULL; + s->shutdown_starting.head = nullptr; + s->shutdown_starting.tail = nullptr; s->shutdown_complete = shutdown_complete; - s->on_accept_cb = NULL; - s->on_accept_cb_arg = NULL; - s->head = NULL; - s->tail = NULL; + s->on_accept_cb = nullptr; + s->on_accept_cb_arg = nullptr; + s->head = nullptr; + s->tail = nullptr; s->nports = 0; s->channel_args = grpc_channel_args_copy(args); gpr_atm_no_barrier_store(&s->next_pollset_to_assign, 0); @@ -116,18 +116,18 @@ grpc_error *grpc_tcp_server_create(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static void finish_shutdown(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { +static void finish_shutdown(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s) { gpr_mu_lock(&s->mu); GPR_ASSERT(s->shutdown); gpr_mu_unlock(&s->mu); - if (s->shutdown_complete != NULL) { + if (s->shutdown_complete != nullptr) { GRPC_CLOSURE_SCHED(exec_ctx, s->shutdown_complete, GRPC_ERROR_NONE); } gpr_mu_destroy(&s->mu); while (s->head) { - grpc_tcp_listener *sp = s->head; + grpc_tcp_listener* sp = s->head; s->head = sp->next; gpr_free(sp); } @@ -136,9 +136,9 @@ static void finish_shutdown(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { gpr_free(s); } -static void destroyed_port(grpc_exec_ctx *exec_ctx, void *server, - grpc_error *error) { - grpc_tcp_server *s = (grpc_tcp_server *)server; +static void destroyed_port(grpc_exec_ctx* exec_ctx, void* server, + grpc_error* error) { + grpc_tcp_server* s = (grpc_tcp_server*)server; gpr_mu_lock(&s->mu); s->destroyed_ports++; if (s->destroyed_ports == s->nports) { @@ -153,19 +153,19 @@ static void destroyed_port(grpc_exec_ctx *exec_ctx, void *server, /* called when all listening endpoints have been shutdown, so no further events will be received on them - at this point it's safe to destroy things */ -static void deactivated_all_ports(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { +static void deactivated_all_ports(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s) { /* delete ALL the things */ gpr_mu_lock(&s->mu); GPR_ASSERT(s->shutdown); if (s->head) { - grpc_tcp_listener *sp; + grpc_tcp_listener* sp; for (sp = s->head; sp; sp = sp->next) { grpc_unlink_if_unix_domain_socket(&sp->addr); GRPC_CLOSURE_INIT(&sp->destroyed_closure, destroyed_port, s, grpc_schedule_on_exec_ctx); - grpc_fd_orphan(exec_ctx, sp->emfd, &sp->destroyed_closure, NULL, + grpc_fd_orphan(exec_ctx, sp->emfd, &sp->destroyed_closure, nullptr, false /* already_closed */, "tcp_listener_shutdown"); } gpr_mu_unlock(&s->mu); @@ -175,7 +175,7 @@ static void deactivated_all_ports(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { } } -static void tcp_server_destroy(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { +static void tcp_server_destroy(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s) { gpr_mu_lock(&s->mu); GPR_ASSERT(!s->shutdown); @@ -183,10 +183,11 @@ static void tcp_server_destroy(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { /* shutdown all fd's */ if (s->active_ports) { - grpc_tcp_listener *sp; + grpc_tcp_listener* sp; for (sp = s->head; sp; sp = sp->next) { - grpc_fd_shutdown(exec_ctx, sp->emfd, GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "Server destroyed")); + grpc_fd_shutdown( + exec_ctx, sp->emfd, + GRPC_ERROR_CREATE_FROM_STATIC_STRING("Server destroyed")); } gpr_mu_unlock(&s->mu); } else { @@ -196,9 +197,9 @@ static void tcp_server_destroy(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { } /* event manager callback when reads are ready */ -static void on_read(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *err) { - grpc_tcp_listener *sp = (grpc_tcp_listener *)arg; - grpc_pollset *read_notifier_pollset; +static void on_read(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* err) { + grpc_tcp_listener* sp = (grpc_tcp_listener*)arg; + grpc_pollset* read_notifier_pollset; if (err != GRPC_ERROR_NONE) { goto error; } @@ -211,8 +212,8 @@ static void on_read(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *err) { /* loop until accept4 returns EAGAIN, and then re-arm notification */ for (;;) { grpc_resolved_address addr; - char *addr_str; - char *name; + char* addr_str; + char* name; addr.len = sizeof(struct sockaddr_storage); /* Note: If we ever decide to return this address to the user, remember to strip off the ::ffff:0.0.0.0/96 prefix first. */ @@ -242,17 +243,17 @@ static void on_read(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *err) { addr_str = grpc_sockaddr_to_uri(&addr); gpr_asprintf(&name, "tcp-server-connection:%s", addr_str); - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "SERVER_CONNECT: incoming connection: %s", addr_str); } - grpc_fd *fdobj = grpc_fd_create(fd, name); + grpc_fd* fdobj = grpc_fd_create(fd, name); grpc_pollset_add_fd(exec_ctx, read_notifier_pollset, fdobj); // Create acceptor. - grpc_tcp_server_acceptor *acceptor = - (grpc_tcp_server_acceptor *)gpr_malloc(sizeof(*acceptor)); + grpc_tcp_server_acceptor* acceptor = + (grpc_tcp_server_acceptor*)gpr_malloc(sizeof(*acceptor)); acceptor->from_server = sp->server; acceptor->port_index = sp->port_index; acceptor->fd_index = sp->fd_index; @@ -279,18 +280,18 @@ error: } /* Treat :: or 0.0.0.0 as a family-agnostic wildcard. */ -static grpc_error *add_wildcard_addrs_to_server(grpc_tcp_server *s, +static grpc_error* add_wildcard_addrs_to_server(grpc_tcp_server* s, unsigned port_index, int requested_port, - int *out_port) { + int* out_port) { grpc_resolved_address wild4; grpc_resolved_address wild6; unsigned fd_index = 0; grpc_dualstack_mode dsmode; - grpc_tcp_listener *sp = NULL; - grpc_tcp_listener *sp2 = NULL; - grpc_error *v6_err = GRPC_ERROR_NONE; - grpc_error *v4_err = GRPC_ERROR_NONE; + grpc_tcp_listener* sp = nullptr; + grpc_tcp_listener* sp2 = nullptr; + grpc_error* v6_err = GRPC_ERROR_NONE; + grpc_error* v4_err = GRPC_ERROR_NONE; *out_port = -1; if (grpc_tcp_server_have_ifaddrs() && s->expand_wildcard_addrs) { @@ -313,7 +314,7 @@ static grpc_error *add_wildcard_addrs_to_server(grpc_tcp_server *s, if ((v4_err = grpc_tcp_server_add_addr(s, &wild4, port_index, fd_index, &dsmode, &sp2)) == GRPC_ERROR_NONE) { *out_port = sp2->port; - if (sp != NULL) { + if (sp != nullptr) { sp2->is_sibling = 1; sp->sibling = sp2; } @@ -335,7 +336,7 @@ static grpc_error *add_wildcard_addrs_to_server(grpc_tcp_server *s, } return GRPC_ERROR_NONE; } else { - grpc_error *root_err = GRPC_ERROR_CREATE_FROM_STATIC_STRING( + grpc_error* root_err = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Failed to add any wildcard listeners"); GPR_ASSERT(v6_err != GRPC_ERROR_NONE && v4_err != GRPC_ERROR_NONE); root_err = grpc_error_add_child(root_err, v6_err); @@ -344,13 +345,13 @@ static grpc_error *add_wildcard_addrs_to_server(grpc_tcp_server *s, } } -static grpc_error *clone_port(grpc_tcp_listener *listener, unsigned count) { - grpc_tcp_listener *sp = NULL; - char *addr_str; - char *name; - grpc_error *err; +static grpc_error* clone_port(grpc_tcp_listener* listener, unsigned count) { + grpc_tcp_listener* sp = nullptr; + char* addr_str; + char* name; + grpc_error* err; - for (grpc_tcp_listener *l = listener->next; l && l->is_sibling; l = l->next) { + for (grpc_tcp_listener* l = listener->next; l && l->is_sibling; l = l->next) { l->fd_index += count; } @@ -366,7 +367,7 @@ static grpc_error *clone_port(grpc_tcp_listener *listener, unsigned count) { listener->server->nports++; grpc_sockaddr_to_string(&addr_str, &listener->addr, 1); gpr_asprintf(&name, "tcp-server-listener:%s/clone-%d", addr_str, i); - sp = (grpc_tcp_listener *)gpr_malloc(sizeof(grpc_tcp_listener)); + sp = (grpc_tcp_listener*)gpr_malloc(sizeof(grpc_tcp_listener)); sp->next = listener->next; listener->next = sp; /* sp (the new listener) is a sibling of 'listener' (the original @@ -382,7 +383,7 @@ static grpc_error *clone_port(grpc_tcp_listener *listener, unsigned count) { sp->port_index = listener->port_index; sp->fd_index = listener->fd_index + count - i; GPR_ASSERT(sp->emfd); - while (listener->server->tail->next != NULL) { + while (listener->server->tail->next != nullptr) { listener->server->tail = listener->server->tail->next; } gpr_free(addr_str); @@ -392,18 +393,18 @@ static grpc_error *clone_port(grpc_tcp_listener *listener, unsigned count) { return GRPC_ERROR_NONE; } -grpc_error *grpc_tcp_server_add_port(grpc_tcp_server *s, - const grpc_resolved_address *addr, - int *out_port) { - grpc_tcp_listener *sp; +grpc_error* grpc_tcp_server_add_port(grpc_tcp_server* s, + const grpc_resolved_address* addr, + int* out_port) { + grpc_tcp_listener* sp; grpc_resolved_address sockname_temp; grpc_resolved_address addr6_v4mapped; int requested_port = grpc_sockaddr_get_port(addr); unsigned port_index = 0; grpc_dualstack_mode dsmode; - grpc_error *err; + grpc_error* err; *out_port = -1; - if (s->tail != NULL) { + if (s->tail != nullptr) { port_index = s->tail->port_index + 1; } grpc_unlink_if_unix_domain_socket(addr); @@ -413,8 +414,8 @@ grpc_error *grpc_tcp_server_add_port(grpc_tcp_server *s, if (requested_port == 0) { for (sp = s->head; sp; sp = sp->next) { sockname_temp.len = sizeof(struct sockaddr_storage); - if (0 == getsockname(sp->fd, (struct sockaddr *)&sockname_temp.addr, - (socklen_t *)&sockname_temp.len)) { + if (0 == getsockname(sp->fd, (struct sockaddr*)&sockname_temp.addr, + (socklen_t*)&sockname_temp.len)) { int used_port = grpc_sockaddr_get_port(&sockname_temp); if (used_port > 0) { memcpy(&sockname_temp, addr, sizeof(grpc_resolved_address)); @@ -442,10 +443,10 @@ grpc_error *grpc_tcp_server_add_port(grpc_tcp_server *s, /* Return listener at port_index or NULL. Should only be called with s->mu locked. */ -static grpc_tcp_listener *get_port_index(grpc_tcp_server *s, +static grpc_tcp_listener* get_port_index(grpc_tcp_server* s, unsigned port_index) { unsigned num_ports = 0; - grpc_tcp_listener *sp; + grpc_tcp_listener* sp; for (sp = s->head; sp; sp = sp->next) { if (!sp->is_sibling) { if (++num_ports > port_index) { @@ -453,14 +454,14 @@ static grpc_tcp_listener *get_port_index(grpc_tcp_server *s, } } } - return NULL; + return nullptr; } -unsigned grpc_tcp_server_port_fd_count(grpc_tcp_server *s, +unsigned grpc_tcp_server_port_fd_count(grpc_tcp_server* s, unsigned port_index) { unsigned num_fds = 0; gpr_mu_lock(&s->mu); - grpc_tcp_listener *sp = get_port_index(s, port_index); + grpc_tcp_listener* sp = get_port_index(s, port_index); for (; sp; sp = sp->sibling) { ++num_fds; } @@ -468,10 +469,10 @@ unsigned grpc_tcp_server_port_fd_count(grpc_tcp_server *s, return num_fds; } -int grpc_tcp_server_port_fd(grpc_tcp_server *s, unsigned port_index, +int grpc_tcp_server_port_fd(grpc_tcp_server* s, unsigned port_index, unsigned fd_index) { gpr_mu_lock(&s->mu); - grpc_tcp_listener *sp = get_port_index(s, port_index); + grpc_tcp_listener* sp = get_port_index(s, port_index); for (; sp; sp = sp->sibling, --fd_index) { if (fd_index == 0) { gpr_mu_unlock(&s->mu); @@ -482,12 +483,12 @@ int grpc_tcp_server_port_fd(grpc_tcp_server *s, unsigned port_index, return -1; } -void grpc_tcp_server_start(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s, - grpc_pollset **pollsets, size_t pollset_count, +void grpc_tcp_server_start(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s, + grpc_pollset** pollsets, size_t pollset_count, grpc_tcp_server_cb on_accept_cb, - void *on_accept_cb_arg) { + void* on_accept_cb_arg) { size_t i; - grpc_tcp_listener *sp; + grpc_tcp_listener* sp; GPR_ASSERT(on_accept_cb); gpr_mu_lock(&s->mu); GPR_ASSERT(!s->on_accept_cb); @@ -497,7 +498,7 @@ void grpc_tcp_server_start(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s, s->pollsets = pollsets; s->pollset_count = pollset_count; sp = s->head; - while (sp != NULL) { + while (sp != nullptr) { if (s->so_reuseport && !grpc_is_unix_socket(&sp->addr) && pollset_count > 1) { GPR_ASSERT(GRPC_LOG_IF_ERROR( @@ -524,20 +525,20 @@ void grpc_tcp_server_start(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s, gpr_mu_unlock(&s->mu); } -grpc_tcp_server *grpc_tcp_server_ref(grpc_tcp_server *s) { +grpc_tcp_server* grpc_tcp_server_ref(grpc_tcp_server* s) { gpr_ref_non_zero(&s->refs); return s; } -void grpc_tcp_server_shutdown_starting_add(grpc_tcp_server *s, - grpc_closure *shutdown_starting) { +void grpc_tcp_server_shutdown_starting_add(grpc_tcp_server* s, + grpc_closure* shutdown_starting) { gpr_mu_lock(&s->mu); grpc_closure_list_append(&s->shutdown_starting, shutdown_starting, GRPC_ERROR_NONE); gpr_mu_unlock(&s->mu); } -void grpc_tcp_server_unref(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { +void grpc_tcp_server_unref(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s) { if (gpr_unref(&s->refs)) { grpc_tcp_server_shutdown_listeners(exec_ctx, s); gpr_mu_lock(&s->mu); @@ -547,13 +548,13 @@ void grpc_tcp_server_unref(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { } } -void grpc_tcp_server_shutdown_listeners(grpc_exec_ctx *exec_ctx, - grpc_tcp_server *s) { +void grpc_tcp_server_shutdown_listeners(grpc_exec_ctx* exec_ctx, + grpc_tcp_server* s) { gpr_mu_lock(&s->mu); s->shutdown_listeners = true; /* shutdown all fd's */ if (s->active_ports) { - grpc_tcp_listener *sp; + grpc_tcp_listener* sp; for (sp = s->head; sp; sp = sp->next) { grpc_fd_shutdown(exec_ctx, sp->emfd, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Server shutdown")); diff --git a/src/core/lib/iomgr/tcp_server_utils_posix.h b/src/core/lib/iomgr/tcp_server_utils_posix.h index 67463339608..6046f257f98 100644 --- a/src/core/lib/iomgr/tcp_server_utils_posix.h +++ b/src/core/lib/iomgr/tcp_server_utils_posix.h @@ -24,29 +24,25 @@ #include "src/core/lib/iomgr/socket_utils_posix.h" #include "src/core/lib/iomgr/tcp_server.h" -#ifdef __cplusplus -extern "C" { -#endif - /* one listening port */ typedef struct grpc_tcp_listener { int fd; - grpc_fd *emfd; - grpc_tcp_server *server; + grpc_fd* emfd; + grpc_tcp_server* server; grpc_resolved_address addr; int port; unsigned port_index; unsigned fd_index; grpc_closure read_closure; grpc_closure destroyed_closure; - struct grpc_tcp_listener *next; + struct grpc_tcp_listener* next; /* sibling is a linked list of all listeners for a given port. add_port and clone_port place all new listeners in the same sibling list. A member of the 'sibling' list is also a member of the 'next' list. The head of each sibling list has is_sibling==0, and subsequent members of sibling lists have is_sibling==1. is_sibling allows separate sibling lists to be identified while iterating through 'next'. */ - struct grpc_tcp_listener *sibling; + struct grpc_tcp_listener* sibling; int is_sibling; } grpc_tcp_listener; @@ -55,7 +51,7 @@ struct grpc_tcp_server { gpr_refcount refs; /* Called whenever accept() succeeds on a server port. */ grpc_tcp_server_cb on_accept_cb; - void *on_accept_cb_arg; + void* on_accept_cb_arg; gpr_mu mu; @@ -74,18 +70,18 @@ struct grpc_tcp_server { bool expand_wildcard_addrs; /* linked list of server ports */ - grpc_tcp_listener *head; - grpc_tcp_listener *tail; + grpc_tcp_listener* head; + grpc_tcp_listener* tail; unsigned nports; /* List of closures passed to shutdown_starting_add(). */ grpc_closure_list shutdown_starting; /* shutdown callback */ - grpc_closure *shutdown_complete; + grpc_closure* shutdown_complete; /* all pollsets interested in new connections */ - grpc_pollset **pollsets; + grpc_pollset** pollsets; /* number of pollsets in the pollsets array */ size_t pollset_count; @@ -93,36 +89,32 @@ struct grpc_tcp_server { gpr_atm next_pollset_to_assign; /* channel args for this server */ - grpc_channel_args *channel_args; + grpc_channel_args* channel_args; }; /* If successful, add a listener to \a s for \a addr, set \a dsmode for the socket, and return the \a listener. */ -grpc_error *grpc_tcp_server_add_addr(grpc_tcp_server *s, - const grpc_resolved_address *addr, +grpc_error* grpc_tcp_server_add_addr(grpc_tcp_server* s, + const grpc_resolved_address* addr, unsigned port_index, unsigned fd_index, - grpc_dualstack_mode *dsmode, - grpc_tcp_listener **listener); + grpc_dualstack_mode* dsmode, + grpc_tcp_listener** listener); /* Get all addresses assigned to network interfaces on the machine and create a listener for each. requested_port is the port to use for every listener, or 0 to select one random port that will be used for every listener. Set *out_port to the port selected. Return GRPC_ERROR_NONE only if all listeners were added. */ -grpc_error *grpc_tcp_server_add_all_local_addrs(grpc_tcp_server *s, +grpc_error* grpc_tcp_server_add_all_local_addrs(grpc_tcp_server* s, unsigned port_index, int requested_port, - int *out_port); + int* out_port); /* Prepare a recently-created socket for listening. */ -grpc_error *grpc_tcp_server_prepare_socket(int fd, - const grpc_resolved_address *addr, - bool so_reuseport, int *port); +grpc_error* grpc_tcp_server_prepare_socket(int fd, + const grpc_resolved_address* addr, + bool so_reuseport, int* port); /* Ruturn true if the platform supports ifaddrs */ bool grpc_tcp_server_have_ifaddrs(void); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_TCP_SERVER_UTILS_POSIX_H */ diff --git a/src/core/lib/iomgr/tcp_server_utils_posix_common.cc b/src/core/lib/iomgr/tcp_server_utils_posix_common.cc index a828bee074a..5139760634a 100644 --- a/src/core/lib/iomgr/tcp_server_utils_posix_common.cc +++ b/src/core/lib/iomgr/tcp_server_utils_posix_common.cc @@ -46,16 +46,16 @@ static int s_max_accept_queue_size; static void init_max_accept_queue_size(void) { int n = SOMAXCONN; char buf[64]; - FILE *fp = fopen("/proc/sys/net/core/somaxconn", "r"); - if (fp == NULL) { + FILE* fp = fopen("/proc/sys/net/core/somaxconn", "r"); + if (fp == nullptr) { /* 2.4 kernel. */ s_max_accept_queue_size = SOMAXCONN; return; } if (fgets(buf, sizeof buf, fp)) { - char *end; + char* end; long i = strtol(buf, &end, 10); - if (i > 0 && i <= INT_MAX && end && *end == 0) { + if (i > 0 && i <= INT_MAX && end && *end == '\n') { n = (int)i; } } @@ -75,16 +75,16 @@ static int get_max_accept_queue_size(void) { return s_max_accept_queue_size; } -static grpc_error *add_socket_to_server(grpc_tcp_server *s, int fd, - const grpc_resolved_address *addr, +static grpc_error* add_socket_to_server(grpc_tcp_server* s, int fd, + const grpc_resolved_address* addr, unsigned port_index, unsigned fd_index, - grpc_tcp_listener **listener) { - grpc_tcp_listener *sp = NULL; + grpc_tcp_listener** listener) { + grpc_tcp_listener* sp = nullptr; int port = -1; - char *addr_str; - char *name; + char* addr_str; + char* name; - grpc_error *err = + grpc_error* err = grpc_tcp_server_prepare_socket(fd, addr, s->so_reuseport, &port); if (err == GRPC_ERROR_NONE) { GPR_ASSERT(port > 0); @@ -93,9 +93,9 @@ static grpc_error *add_socket_to_server(grpc_tcp_server *s, int fd, gpr_mu_lock(&s->mu); s->nports++; GPR_ASSERT(!s->on_accept_cb && "must add ports before starting server"); - sp = (grpc_tcp_listener *)gpr_malloc(sizeof(grpc_tcp_listener)); - sp->next = NULL; - if (s->head == NULL) { + sp = (grpc_tcp_listener*)gpr_malloc(sizeof(grpc_tcp_listener)); + sp->next = nullptr; + if (s->head == nullptr) { s->head = sp; } else { s->tail->next = sp; @@ -109,7 +109,7 @@ static grpc_error *add_socket_to_server(grpc_tcp_server *s, int fd, sp->port_index = port_index; sp->fd_index = fd_index; sp->is_sibling = 0; - sp->sibling = NULL; + sp->sibling = nullptr; GPR_ASSERT(sp->emfd); gpr_mu_unlock(&s->mu); gpr_free(addr_str); @@ -122,14 +122,14 @@ static grpc_error *add_socket_to_server(grpc_tcp_server *s, int fd, /* If successful, add a listener to s for addr, set *dsmode for the socket, and return the *listener. */ -grpc_error *grpc_tcp_server_add_addr(grpc_tcp_server *s, - const grpc_resolved_address *addr, +grpc_error* grpc_tcp_server_add_addr(grpc_tcp_server* s, + const grpc_resolved_address* addr, unsigned port_index, unsigned fd_index, - grpc_dualstack_mode *dsmode, - grpc_tcp_listener **listener) { + grpc_dualstack_mode* dsmode, + grpc_tcp_listener** listener) { grpc_resolved_address addr4_copy; int fd; - grpc_error *err = + grpc_error* err = grpc_create_dualstack_socket(addr, SOCK_STREAM, 0, dsmode, &fd); if (err != GRPC_ERROR_NONE) { return err; @@ -142,11 +142,11 @@ grpc_error *grpc_tcp_server_add_addr(grpc_tcp_server *s, } /* Prepare a recently-created socket for listening. */ -grpc_error *grpc_tcp_server_prepare_socket(int fd, - const grpc_resolved_address *addr, - bool so_reuseport, int *port) { +grpc_error* grpc_tcp_server_prepare_socket(int fd, + const grpc_resolved_address* addr, + bool so_reuseport, int* port) { grpc_resolved_address sockname_temp; - grpc_error *err = GRPC_ERROR_NONE; + grpc_error* err = GRPC_ERROR_NONE; GPR_ASSERT(fd >= 0); @@ -169,7 +169,7 @@ grpc_error *grpc_tcp_server_prepare_socket(int fd, if (err != GRPC_ERROR_NONE) goto error; GPR_ASSERT(addr->len < ~(socklen_t)0); - if (bind(fd, (struct sockaddr *)addr->addr, (socklen_t)addr->len) < 0) { + if (bind(fd, (struct sockaddr*)addr->addr, (socklen_t)addr->len) < 0) { err = GRPC_OS_ERROR(errno, "bind"); goto error; } @@ -181,8 +181,8 @@ grpc_error *grpc_tcp_server_prepare_socket(int fd, sockname_temp.len = sizeof(struct sockaddr_storage); - if (getsockname(fd, (struct sockaddr *)sockname_temp.addr, - (socklen_t *)&sockname_temp.len) < 0) { + if (getsockname(fd, (struct sockaddr*)sockname_temp.addr, + (socklen_t*)&sockname_temp.len) < 0) { err = GRPC_OS_ERROR(errno, "getsockname"); goto error; } @@ -195,7 +195,7 @@ error: if (fd >= 0) { close(fd); } - grpc_error *ret = + grpc_error* ret = grpc_error_set_int(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Unable to configure socket", &err, 1), GRPC_ERROR_INT_FD, fd); diff --git a/src/core/lib/iomgr/tcp_server_utils_posix_ifaddrs.cc b/src/core/lib/iomgr/tcp_server_utils_posix_ifaddrs.cc index a243b69f352..227bf94aa75 100644 --- a/src/core/lib/iomgr/tcp_server_utils_posix_ifaddrs.cc +++ b/src/core/lib/iomgr/tcp_server_utils_posix_ifaddrs.cc @@ -36,11 +36,11 @@ #include "src/core/lib/iomgr/sockaddr_utils.h" /* Return the listener in s with address addr or NULL. */ -static grpc_tcp_listener *find_listener_with_addr(grpc_tcp_server *s, - grpc_resolved_address *addr) { - grpc_tcp_listener *l; +static grpc_tcp_listener* find_listener_with_addr(grpc_tcp_server* s, + grpc_resolved_address* addr) { + grpc_tcp_listener* l; gpr_mu_lock(&s->mu); - for (l = s->head; l != NULL; l = l->next) { + for (l = s->head; l != nullptr; l = l->next) { if (l->addr.len != addr->len) { continue; } @@ -53,12 +53,12 @@ static grpc_tcp_listener *find_listener_with_addr(grpc_tcp_server *s, } /* Bind to "::" to get a port number not used by any address. */ -static grpc_error *get_unused_port(int *port) { +static grpc_error* get_unused_port(int* port) { grpc_resolved_address wild; grpc_sockaddr_make_wildcard6(0, &wild); grpc_dualstack_mode dsmode; int fd; - grpc_error *err = + grpc_error* err = grpc_create_dualstack_socket(&wild, SOCK_STREAM, 0, &dsmode, &fd); if (err != GRPC_ERROR_NONE) { return err; @@ -66,12 +66,12 @@ static grpc_error *get_unused_port(int *port) { if (dsmode == GRPC_DSMODE_IPV4) { grpc_sockaddr_make_wildcard4(0, &wild); } - if (bind(fd, (const struct sockaddr *)wild.addr, (socklen_t)wild.len) != 0) { + if (bind(fd, (const struct sockaddr*)wild.addr, (socklen_t)wild.len) != 0) { err = GRPC_OS_ERROR(errno, "bind"); close(fd); return err; } - if (getsockname(fd, (struct sockaddr *)wild.addr, (socklen_t *)&wild.len) != + if (getsockname(fd, (struct sockaddr*)wild.addr, (socklen_t*)&wild.len) != 0) { err = GRPC_OS_ERROR(errno, "getsockname"); close(fd); @@ -83,15 +83,15 @@ static grpc_error *get_unused_port(int *port) { : GRPC_ERROR_NONE; } -grpc_error *grpc_tcp_server_add_all_local_addrs(grpc_tcp_server *s, +grpc_error* grpc_tcp_server_add_all_local_addrs(grpc_tcp_server* s, unsigned port_index, int requested_port, - int *out_port) { - struct ifaddrs *ifa = NULL; - struct ifaddrs *ifa_it; + int* out_port) { + struct ifaddrs* ifa = nullptr; + struct ifaddrs* ifa_it; unsigned fd_index = 0; - grpc_tcp_listener *sp = NULL; - grpc_error *err = GRPC_ERROR_NONE; + grpc_tcp_listener* sp = nullptr; + grpc_error* err = GRPC_ERROR_NONE; if (requested_port == 0) { /* Note: There could be a race where some local addrs can listen on the selected port and some can't. The sane way to handle this would be to @@ -104,16 +104,16 @@ grpc_error *grpc_tcp_server_add_all_local_addrs(grpc_tcp_server *s, } gpr_log(GPR_DEBUG, "Picked unused port %d", requested_port); } - if (getifaddrs(&ifa) != 0 || ifa == NULL) { + if (getifaddrs(&ifa) != 0 || ifa == nullptr) { return GRPC_OS_ERROR(errno, "getifaddrs"); } - for (ifa_it = ifa; ifa_it != NULL; ifa_it = ifa_it->ifa_next) { + for (ifa_it = ifa; ifa_it != nullptr; ifa_it = ifa_it->ifa_next) { grpc_resolved_address addr; - char *addr_str = NULL; + char* addr_str = nullptr; grpc_dualstack_mode dsmode; - grpc_tcp_listener *new_sp = NULL; - const char *ifa_name = (ifa_it->ifa_name ? ifa_it->ifa_name : ""); - if (ifa_it->ifa_addr == NULL) { + grpc_tcp_listener* new_sp = nullptr; + const char* ifa_name = (ifa_it->ifa_name ? ifa_it->ifa_name : ""); + if (ifa_it->ifa_addr == nullptr) { continue; } else if (ifa_it->ifa_addr->sa_family == AF_INET) { addr.len = sizeof(struct sockaddr_in); @@ -136,7 +136,7 @@ grpc_error *grpc_tcp_server_add_all_local_addrs(grpc_tcp_server *s, ifa_name, ifa_it->ifa_flags, addr_str); /* We could have multiple interfaces with the same address (e.g., bonding), so look for duplicates. */ - if (find_listener_with_addr(s, &addr) != NULL) { + if (find_listener_with_addr(s, &addr) != nullptr) { gpr_log(GPR_DEBUG, "Skipping duplicate addr %s on interface %s", addr_str, ifa_name); gpr_free(addr_str); @@ -144,8 +144,8 @@ grpc_error *grpc_tcp_server_add_all_local_addrs(grpc_tcp_server *s, } if ((err = grpc_tcp_server_add_addr(s, &addr, port_index, fd_index, &dsmode, &new_sp)) != GRPC_ERROR_NONE) { - char *err_str = NULL; - grpc_error *root_err; + char* err_str = nullptr; + grpc_error* root_err; if (gpr_asprintf(&err_str, "Failed to add listener: %s", addr_str) < 0) { err_str = gpr_strdup("Failed to add listener"); } @@ -157,7 +157,7 @@ grpc_error *grpc_tcp_server_add_all_local_addrs(grpc_tcp_server *s, } else { GPR_ASSERT(requested_port == new_sp->port); ++fd_index; - if (sp != NULL) { + if (sp != nullptr) { new_sp->is_sibling = 1; sp->sibling = new_sp; } @@ -168,7 +168,7 @@ grpc_error *grpc_tcp_server_add_all_local_addrs(grpc_tcp_server *s, freeifaddrs(ifa); if (err != GRPC_ERROR_NONE) { return err; - } else if (sp == NULL) { + } else if (sp == nullptr) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("No local addresses"); } else { *out_port = sp->port; diff --git a/src/core/lib/iomgr/tcp_server_utils_posix_noifaddrs.cc b/src/core/lib/iomgr/tcp_server_utils_posix_noifaddrs.cc index 34eab20d6ac..2d72b95defd 100644 --- a/src/core/lib/iomgr/tcp_server_utils_posix_noifaddrs.cc +++ b/src/core/lib/iomgr/tcp_server_utils_posix_noifaddrs.cc @@ -22,10 +22,10 @@ #include "src/core/lib/iomgr/tcp_server_utils_posix.h" -grpc_error *grpc_tcp_server_add_all_local_addrs(grpc_tcp_server *s, +grpc_error* grpc_tcp_server_add_all_local_addrs(grpc_tcp_server* s, unsigned port_index, int requested_port, - int *out_port) { + int* out_port) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("no ifaddrs available"); } diff --git a/src/core/lib/iomgr/tcp_server_uv.cc b/src/core/lib/iomgr/tcp_server_uv.cc index 348838c495c..ffadf0b1abd 100644 --- a/src/core/lib/iomgr/tcp_server_uv.cc +++ b/src/core/lib/iomgr/tcp_server_uv.cc @@ -37,12 +37,12 @@ /* one listening port */ typedef struct grpc_tcp_listener grpc_tcp_listener; struct grpc_tcp_listener { - uv_tcp_t *handle; - grpc_tcp_server *server; + uv_tcp_t* handle; + grpc_tcp_server* server; unsigned port_index; int port; /* linked list */ - struct grpc_tcp_listener *next; + struct grpc_tcp_listener* next; bool closed; @@ -54,37 +54,37 @@ struct grpc_tcp_server { /* Called whenever accept() succeeds on a server port. */ grpc_tcp_server_cb on_accept_cb; - void *on_accept_cb_arg; + void* on_accept_cb_arg; int open_ports; /* linked list of server ports */ - grpc_tcp_listener *head; - grpc_tcp_listener *tail; + grpc_tcp_listener* head; + grpc_tcp_listener* tail; /* List of closures passed to shutdown_starting_add(). */ grpc_closure_list shutdown_starting; /* shutdown callback */ - grpc_closure *shutdown_complete; + grpc_closure* shutdown_complete; bool shutdown; - grpc_resource_quota *resource_quota; + grpc_resource_quota* resource_quota; }; -grpc_error *grpc_tcp_server_create(grpc_exec_ctx *exec_ctx, - grpc_closure *shutdown_complete, - const grpc_channel_args *args, - grpc_tcp_server **server) { - grpc_tcp_server *s = (grpc_tcp_server *)gpr_malloc(sizeof(grpc_tcp_server)); +grpc_error* grpc_tcp_server_create(grpc_exec_ctx* exec_ctx, + grpc_closure* shutdown_complete, + const grpc_channel_args* args, + grpc_tcp_server** server) { + grpc_tcp_server* s = (grpc_tcp_server*)gpr_malloc(sizeof(grpc_tcp_server)); s->resource_quota = grpc_resource_quota_create(NULL); for (size_t i = 0; i < (args == NULL ? 0 : args->num_args); i++) { if (0 == strcmp(GRPC_ARG_RESOURCE_QUOTA, args->args[i].key)) { if (args->args[i].type == GRPC_ARG_POINTER) { grpc_resource_quota_unref_internal(exec_ctx, s->resource_quota); s->resource_quota = grpc_resource_quota_ref_internal( - (grpc_resource_quota *)args->args[i].value.pointer.p); + (grpc_resource_quota*)args->args[i].value.pointer.p); } else { grpc_resource_quota_unref_internal(exec_ctx, s->resource_quota); gpr_free(s); @@ -107,26 +107,26 @@ grpc_error *grpc_tcp_server_create(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -grpc_tcp_server *grpc_tcp_server_ref(grpc_tcp_server *s) { +grpc_tcp_server* grpc_tcp_server_ref(grpc_tcp_server* s) { GRPC_UV_ASSERT_SAME_THREAD(); gpr_ref(&s->refs); return s; } -void grpc_tcp_server_shutdown_starting_add(grpc_tcp_server *s, - grpc_closure *shutdown_starting) { +void grpc_tcp_server_shutdown_starting_add(grpc_tcp_server* s, + grpc_closure* shutdown_starting) { grpc_closure_list_append(&s->shutdown_starting, shutdown_starting, GRPC_ERROR_NONE); } -static void finish_shutdown(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { +static void finish_shutdown(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s) { GPR_ASSERT(s->shutdown); if (s->shutdown_complete != NULL) { GRPC_CLOSURE_SCHED(exec_ctx, s->shutdown_complete, GRPC_ERROR_NONE); } while (s->head) { - grpc_tcp_listener *sp = s->head; + grpc_tcp_listener* sp = s->head; s->head = sp->next; sp->next = NULL; gpr_free(sp->handle); @@ -136,8 +136,8 @@ static void finish_shutdown(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { gpr_free(s); } -static void handle_close_callback(uv_handle_t *handle) { - grpc_tcp_listener *sp = (grpc_tcp_listener *)handle->data; +static void handle_close_callback(uv_handle_t* handle) { + grpc_tcp_listener* sp = (grpc_tcp_listener*)handle->data; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; sp->server->open_ports--; if (sp->server->open_ports == 0 && sp->server->shutdown) { @@ -146,16 +146,16 @@ static void handle_close_callback(uv_handle_t *handle) { grpc_exec_ctx_finish(&exec_ctx); } -static void close_listener(grpc_tcp_listener *sp) { +static void close_listener(grpc_tcp_listener* sp) { if (!sp->closed) { sp->closed = true; - uv_close((uv_handle_t *)sp->handle, handle_close_callback); + uv_close((uv_handle_t*)sp->handle, handle_close_callback); } } -static void tcp_server_destroy(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { +static void tcp_server_destroy(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s) { int immediately_done = 0; - grpc_tcp_listener *sp; + grpc_tcp_listener* sp; GPR_ASSERT(!s->shutdown); s->shutdown = true; @@ -172,7 +172,7 @@ static void tcp_server_destroy(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { } } -void grpc_tcp_server_unref(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { +void grpc_tcp_server_unref(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s) { GRPC_UV_ASSERT_SAME_THREAD(); if (gpr_unref(&s->refs)) { /* Complete shutdown_starting work before destroying. */ @@ -189,31 +189,31 @@ void grpc_tcp_server_unref(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { } } -static void finish_accept(grpc_exec_ctx *exec_ctx, grpc_tcp_listener *sp) { - grpc_tcp_server_acceptor *acceptor = - (grpc_tcp_server_acceptor *)gpr_malloc(sizeof(*acceptor)); - uv_tcp_t *client = NULL; - grpc_endpoint *ep = NULL; +static void finish_accept(grpc_exec_ctx* exec_ctx, grpc_tcp_listener* sp) { + grpc_tcp_server_acceptor* acceptor = + (grpc_tcp_server_acceptor*)gpr_malloc(sizeof(*acceptor)); + uv_tcp_t* client = NULL; + grpc_endpoint* ep = NULL; grpc_resolved_address peer_name; - char *peer_name_string; + char* peer_name_string; int err; - uv_tcp_t *server = sp->handle; + uv_tcp_t* server = sp->handle; - client = (uv_tcp_t *)gpr_malloc(sizeof(uv_tcp_t)); + client = (uv_tcp_t*)gpr_malloc(sizeof(uv_tcp_t)); uv_tcp_init(uv_default_loop(), client); // UV documentation says this is guaranteed to succeed - uv_accept((uv_stream_t *)server, (uv_stream_t *)client); + uv_accept((uv_stream_t*)server, (uv_stream_t*)client); peer_name_string = NULL; memset(&peer_name, 0, sizeof(grpc_resolved_address)); peer_name.len = sizeof(struct sockaddr_storage); - err = uv_tcp_getpeername(client, (struct sockaddr *)&peer_name.addr, - (int *)&peer_name.len); + err = uv_tcp_getpeername(client, (struct sockaddr*)&peer_name.addr, + (int*)&peer_name.len); if (err == 0) { peer_name_string = grpc_sockaddr_to_uri(&peer_name); } else { gpr_log(GPR_INFO, "uv_tcp_getpeername error: %s", uv_strerror(err)); } - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { if (peer_name_string) { gpr_log(GPR_DEBUG, "SERVER_CONNECT: %p accepted connection: %s", sp->server, peer_name_string); @@ -230,8 +230,8 @@ static void finish_accept(grpc_exec_ctx *exec_ctx, grpc_tcp_listener *sp) { gpr_free(peer_name_string); } -static void on_connect(uv_stream_t *server, int status) { - grpc_tcp_listener *sp = (grpc_tcp_listener *)server->data; +static void on_connect(uv_stream_t* server, int status) { + grpc_tcp_listener* sp = (grpc_tcp_listener*)server->data; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; if (status < 0) { @@ -247,7 +247,7 @@ static void on_connect(uv_stream_t *server, int status) { GPR_ASSERT(!sp->has_pending_connection); - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "SERVER_CONNECT: %p incoming connection", sp->server); } @@ -260,18 +260,39 @@ static void on_connect(uv_stream_t *server, int status) { grpc_exec_ctx_finish(&exec_ctx); } -static grpc_error *add_socket_to_server(grpc_tcp_server *s, uv_tcp_t *handle, - const grpc_resolved_address *addr, - unsigned port_index, - grpc_tcp_listener **listener) { - grpc_tcp_listener *sp = NULL; +static grpc_error* add_addr_to_server(grpc_tcp_server* s, + const grpc_resolved_address* addr, + unsigned port_index, + grpc_tcp_listener** listener) { + grpc_tcp_listener* sp = NULL; int port = -1; int status; - grpc_error *error; + grpc_error* error; grpc_resolved_address sockname_temp; + uv_tcp_t* handle = (uv_tcp_t*)gpr_malloc(sizeof(uv_tcp_t)); + int family = grpc_sockaddr_get_family(addr); + + status = uv_tcp_init_ex(uv_default_loop(), handle, (unsigned int)family); +#if defined(GPR_LINUX) && defined(SO_REUSEPORT) + if (family == AF_INET || family == AF_INET6) { + int fd; + uv_fileno((uv_handle_t*)handle, &fd); + int enable = 1; + setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &enable, sizeof(enable)); + } +#endif /* GPR_LINUX && SO_REUSEPORT */ + + if (status != 0) { + error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "Failed to initialize UV tcp handle"); + error = + grpc_error_set_str(error, GRPC_ERROR_STR_OS_ERROR, + grpc_slice_from_static_string(uv_strerror(status))); + return error; + } // The last argument to uv_tcp_bind is flags - status = uv_tcp_bind(handle, (struct sockaddr *)addr->addr, 0); + status = uv_tcp_bind(handle, (struct sockaddr*)addr->addr, 0); if (status != 0) { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to bind to port"); error = @@ -280,7 +301,7 @@ static grpc_error *add_socket_to_server(grpc_tcp_server *s, uv_tcp_t *handle, return error; } - status = uv_listen((uv_stream_t *)handle, SOMAXCONN, on_connect); + status = uv_listen((uv_stream_t*)handle, SOMAXCONN, on_connect); if (status != 0) { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to listen to port"); error = @@ -290,8 +311,8 @@ static grpc_error *add_socket_to_server(grpc_tcp_server *s, uv_tcp_t *handle, } sockname_temp.len = (int)sizeof(struct sockaddr_storage); - status = uv_tcp_getsockname(handle, (struct sockaddr *)&sockname_temp.addr, - (int *)&sockname_temp.len); + status = uv_tcp_getsockname(handle, (struct sockaddr*)&sockname_temp.addr, + (int*)&sockname_temp.len); if (status != 0) { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("getsockname failed"); error = @@ -304,7 +325,7 @@ static grpc_error *add_socket_to_server(grpc_tcp_server *s, uv_tcp_t *handle, GPR_ASSERT(port >= 0); GPR_ASSERT(!s->on_accept_cb && "must add ports before starting server"); - sp = (grpc_tcp_listener *)gpr_zalloc(sizeof(grpc_tcp_listener)); + sp = (grpc_tcp_listener*)gpr_zalloc(sizeof(grpc_tcp_listener)); sp->next = NULL; if (s->head == NULL) { s->head = sp; @@ -325,20 +346,48 @@ static grpc_error *add_socket_to_server(grpc_tcp_server *s, uv_tcp_t *handle, return GRPC_ERROR_NONE; } -grpc_error *grpc_tcp_server_add_port(grpc_tcp_server *s, - const grpc_resolved_address *addr, - int *port) { +static grpc_error* add_wildcard_addrs_to_server(grpc_tcp_server* s, + unsigned port_index, + int requested_port, + grpc_tcp_listener** listener) { + grpc_resolved_address wild4; + grpc_resolved_address wild6; + grpc_tcp_listener* sp = nullptr; + grpc_tcp_listener* sp2 = nullptr; + grpc_error* v6_err = GRPC_ERROR_NONE; + grpc_error* v4_err = GRPC_ERROR_NONE; + + grpc_sockaddr_make_wildcards(requested_port, &wild4, &wild6); + /* Try listening on IPv6 first. */ + if ((v6_err = add_addr_to_server(s, &wild6, port_index, &sp)) == + GRPC_ERROR_NONE) { + *listener = sp; + return GRPC_ERROR_NONE; + } + + if ((v4_err = add_addr_to_server(s, &wild4, port_index, &sp2)) == + GRPC_ERROR_NONE) { + *listener = sp2; + return GRPC_ERROR_NONE; + } + + grpc_error* root_err = GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "Failed to add any wildcard listeners"); + root_err = grpc_error_add_child(root_err, v6_err); + root_err = grpc_error_add_child(root_err, v4_err); + return root_err; +} + +grpc_error* grpc_tcp_server_add_port(grpc_tcp_server* s, + const grpc_resolved_address* addr, + int* port) { // This function is mostly copied from tcp_server_windows.c - grpc_tcp_listener *sp = NULL; - uv_tcp_t *handle; + grpc_tcp_listener* sp = NULL; grpc_resolved_address addr6_v4mapped; - grpc_resolved_address wildcard; - grpc_resolved_address *allocated_addr = NULL; + grpc_resolved_address* allocated_addr = NULL; grpc_resolved_address sockname_temp; unsigned port_index = 0; - int status; - grpc_error *error = GRPC_ERROR_NONE; - int family; + grpc_error* error = GRPC_ERROR_NONE; GRPC_UV_ASSERT_SAME_THREAD(); @@ -352,12 +401,12 @@ grpc_error *grpc_tcp_server_add_port(grpc_tcp_server *s, for (sp = s->head; sp; sp = sp->next) { sockname_temp.len = sizeof(struct sockaddr_storage); if (0 == uv_tcp_getsockname(sp->handle, - (struct sockaddr *)&sockname_temp.addr, - (int *)&sockname_temp.len)) { + (struct sockaddr*)&sockname_temp.addr, + (int*)&sockname_temp.len)) { *port = grpc_sockaddr_get_port(&sockname_temp); if (*port > 0) { - allocated_addr = (grpc_resolved_address *)gpr_malloc( - sizeof(grpc_resolved_address)); + allocated_addr = + (grpc_resolved_address*)gpr_malloc(sizeof(grpc_resolved_address)); memcpy(allocated_addr, addr, sizeof(grpc_resolved_address)); grpc_sockaddr_set_port(allocated_addr, *port); addr = allocated_addr; @@ -367,46 +416,23 @@ grpc_error *grpc_tcp_server_add_port(grpc_tcp_server *s, } } - if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) { - addr = &addr6_v4mapped; - } - /* Treat :: or 0.0.0.0 as a family-agnostic wildcard. */ if (grpc_sockaddr_is_wildcard(addr, port)) { - grpc_sockaddr_make_wildcard6(*port, &wildcard); - - addr = &wildcard; - } - - handle = (uv_tcp_t *)gpr_malloc(sizeof(uv_tcp_t)); - - family = grpc_sockaddr_get_family(addr); - status = uv_tcp_init_ex(uv_default_loop(), handle, (unsigned int)family); -#if defined(GPR_LINUX) && defined(SO_REUSEPORT) - if (family == AF_INET || family == AF_INET6) { - int fd; - uv_fileno((uv_handle_t *)handle, &fd); - int enable = 1; - setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &enable, sizeof(enable)); - } -#endif /* GPR_LINUX && SO_REUSEPORT */ - - if (status == 0) { - error = add_socket_to_server(s, handle, addr, port_index, &sp); + error = add_wildcard_addrs_to_server(s, port_index, *port, &sp); } else { - error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "Failed to initialize UV tcp handle"); - error = - grpc_error_set_str(error, GRPC_ERROR_STR_OS_ERROR, - grpc_slice_from_static_string(uv_strerror(status))); + if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) { + addr = &addr6_v4mapped; + } + + error = add_addr_to_server(s, addr, port_index, &sp); } gpr_free(allocated_addr); - if (GRPC_TRACER_ON(grpc_tcp_trace)) { - char *port_string; + if (grpc_tcp_trace.enabled()) { + char* port_string; grpc_sockaddr_to_string(&port_string, addr, 0); - const char *str = grpc_error_string(error); + const char* str = grpc_error_string(error); if (port_string) { gpr_log(GPR_DEBUG, "SERVER %p add_port %s error=%s", s, port_string, str); gpr_free(port_string); @@ -416,7 +442,7 @@ grpc_error *grpc_tcp_server_add_port(grpc_tcp_server *s, } if (error != GRPC_ERROR_NONE) { - grpc_error *error_out = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( + grpc_error* error_out = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Failed to add port to server", &error, 1); GRPC_ERROR_UNREF(error); error = error_out; @@ -428,14 +454,14 @@ grpc_error *grpc_tcp_server_add_port(grpc_tcp_server *s, return error; } -void grpc_tcp_server_start(grpc_exec_ctx *exec_ctx, grpc_tcp_server *server, - grpc_pollset **pollsets, size_t pollset_count, - grpc_tcp_server_cb on_accept_cb, void *cb_arg) { - grpc_tcp_listener *sp; +void grpc_tcp_server_start(grpc_exec_ctx* exec_ctx, grpc_tcp_server* server, + grpc_pollset** pollsets, size_t pollset_count, + grpc_tcp_server_cb on_accept_cb, void* cb_arg) { + grpc_tcp_listener* sp; (void)pollsets; (void)pollset_count; GRPC_UV_ASSERT_SAME_THREAD(); - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "SERVER_START %p", server); } GPR_ASSERT(on_accept_cb); @@ -450,7 +476,7 @@ void grpc_tcp_server_start(grpc_exec_ctx *exec_ctx, grpc_tcp_server *server, } } -void grpc_tcp_server_shutdown_listeners(grpc_exec_ctx *exec_ctx, - grpc_tcp_server *s) {} +void grpc_tcp_server_shutdown_listeners(grpc_exec_ctx* exec_ctx, + grpc_tcp_server* s) {} #endif /* GRPC_UV */ diff --git a/src/core/lib/iomgr/tcp_server_windows.cc b/src/core/lib/iomgr/tcp_server_windows.cc index f198aaaa5ba..f538194895e 100644 --- a/src/core/lib/iomgr/tcp_server_windows.cc +++ b/src/core/lib/iomgr/tcp_server_windows.cc @@ -52,11 +52,11 @@ struct grpc_tcp_listener { /* This will hold the socket for the next accept. */ SOCKET new_socket; /* The listener winsocket. */ - grpc_winsocket *socket; + grpc_winsocket* socket; /* The actual TCP port number. */ int port; unsigned port_index; - grpc_tcp_server *server; + grpc_tcp_server* server; /* The cached AcceptEx for that port. */ LPFN_ACCEPTEX AcceptEx; int shutting_down; @@ -64,7 +64,7 @@ struct grpc_tcp_listener { /* closure for socket notification of accept being ready */ grpc_closure on_accept; /* linked list */ - struct grpc_tcp_listener *next; + struct grpc_tcp_listener* next; }; /* the overall server */ @@ -72,7 +72,7 @@ struct grpc_tcp_server { gpr_refcount refs; /* Called whenever accept() succeeds on a server port. */ grpc_tcp_server_cb on_accept_cb; - void *on_accept_cb_arg; + void* on_accept_cb_arg; gpr_mu mu; @@ -80,25 +80,25 @@ struct grpc_tcp_server { int active_ports; /* linked list of server ports */ - grpc_tcp_listener *head; - grpc_tcp_listener *tail; + grpc_tcp_listener* head; + grpc_tcp_listener* tail; /* List of closures passed to shutdown_starting_add(). */ grpc_closure_list shutdown_starting; /* shutdown callback */ - grpc_closure *shutdown_complete; + grpc_closure* shutdown_complete; - grpc_channel_args *channel_args; + grpc_channel_args* channel_args; }; /* Public function. Allocates the proper data structures to hold a grpc_tcp_server. */ -grpc_error *grpc_tcp_server_create(grpc_exec_ctx *exec_ctx, - grpc_closure *shutdown_complete, - const grpc_channel_args *args, - grpc_tcp_server **server) { - grpc_tcp_server *s = (grpc_tcp_server *)gpr_malloc(sizeof(grpc_tcp_server)); +grpc_error* grpc_tcp_server_create(grpc_exec_ctx* exec_ctx, + grpc_closure* shutdown_complete, + const grpc_channel_args* args, + grpc_tcp_server** server) { + grpc_tcp_server* s = (grpc_tcp_server*)gpr_malloc(sizeof(grpc_tcp_server)); s->channel_args = grpc_channel_args_copy(args); gpr_ref_init(&s->refs, 1); gpr_mu_init(&s->mu); @@ -114,15 +114,15 @@ grpc_error *grpc_tcp_server_create(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static void destroy_server(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_tcp_server *s = (grpc_tcp_server *)arg; +static void destroy_server(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_tcp_server* s = (grpc_tcp_server*)arg; /* Now that the accepts have been aborted, we can destroy the sockets. The IOCP won't get notified on these, so we can flag them as already closed by the system. */ while (s->head) { - grpc_tcp_listener *sp = s->head; + grpc_tcp_listener* sp = s->head; s->head = sp->next; sp->next = NULL; grpc_winsocket_destroy(sp->socket); @@ -132,32 +132,33 @@ static void destroy_server(grpc_exec_ctx *exec_ctx, void *arg, gpr_free(s); } -static void finish_shutdown_locked(grpc_exec_ctx *exec_ctx, - grpc_tcp_server *s) { +static void finish_shutdown_locked(grpc_exec_ctx* exec_ctx, + grpc_tcp_server* s) { if (s->shutdown_complete != NULL) { GRPC_CLOSURE_SCHED(exec_ctx, s->shutdown_complete, GRPC_ERROR_NONE); } - GRPC_CLOSURE_SCHED(exec_ctx, GRPC_CLOSURE_CREATE(destroy_server, s, - grpc_schedule_on_exec_ctx), - GRPC_ERROR_NONE); + GRPC_CLOSURE_SCHED( + exec_ctx, + GRPC_CLOSURE_CREATE(destroy_server, s, grpc_schedule_on_exec_ctx), + GRPC_ERROR_NONE); } -grpc_tcp_server *grpc_tcp_server_ref(grpc_tcp_server *s) { +grpc_tcp_server* grpc_tcp_server_ref(grpc_tcp_server* s) { gpr_ref_non_zero(&s->refs); return s; } -void grpc_tcp_server_shutdown_starting_add(grpc_tcp_server *s, - grpc_closure *shutdown_starting) { +void grpc_tcp_server_shutdown_starting_add(grpc_tcp_server* s, + grpc_closure* shutdown_starting) { gpr_mu_lock(&s->mu); grpc_closure_list_append(&s->shutdown_starting, shutdown_starting, GRPC_ERROR_NONE); gpr_mu_unlock(&s->mu); } -static void tcp_server_destroy(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { - grpc_tcp_listener *sp; +static void tcp_server_destroy(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s) { + grpc_tcp_listener* sp; gpr_mu_lock(&s->mu); /* First, shutdown all fd's. This will queue abortion calls for all @@ -173,7 +174,7 @@ static void tcp_server_destroy(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { gpr_mu_unlock(&s->mu); } -void grpc_tcp_server_unref(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { +void grpc_tcp_server_unref(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s) { if (gpr_unref(&s->refs)) { grpc_tcp_server_shutdown_listeners(exec_ctx, s); gpr_mu_lock(&s->mu); @@ -184,11 +185,11 @@ void grpc_tcp_server_unref(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { } /* Prepare (bind) a recently-created socket for listening. */ -static grpc_error *prepare_socket(SOCKET sock, - const grpc_resolved_address *addr, - int *port) { +static grpc_error* prepare_socket(SOCKET sock, + const grpc_resolved_address* addr, + int* port) { grpc_resolved_address sockname_temp; - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; int sockname_temp_len; error = grpc_tcp_prepare_socket(sock); @@ -196,7 +197,7 @@ static grpc_error *prepare_socket(SOCKET sock, goto failure; } - if (bind(sock, (const struct sockaddr *)addr->addr, (int)addr->len) == + if (bind(sock, (const struct sockaddr*)addr->addr, (int)addr->len) == SOCKET_ERROR) { error = GRPC_WSA_ERROR(WSAGetLastError(), "bind"); goto failure; @@ -208,7 +209,7 @@ static grpc_error *prepare_socket(SOCKET sock, } sockname_temp_len = sizeof(struct sockaddr_storage); - if (getsockname(sock, (struct sockaddr *)sockname_temp.addr, + if (getsockname(sock, (struct sockaddr*)sockname_temp.addr, &sockname_temp_len) == SOCKET_ERROR) { error = GRPC_WSA_ERROR(WSAGetLastError(), "getsockname"); goto failure; @@ -220,7 +221,7 @@ static grpc_error *prepare_socket(SOCKET sock, failure: GPR_ASSERT(error != GRPC_ERROR_NONE); - char *tgtaddr = grpc_sockaddr_to_uri(addr); + char* tgtaddr = grpc_sockaddr_to_uri(addr); grpc_error_set_int( grpc_error_set_str(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Failed to prepare server socket", &error, 1), @@ -233,8 +234,8 @@ failure: return error; } -static void decrement_active_ports_and_notify_locked(grpc_exec_ctx *exec_ctx, - grpc_tcp_listener *sp) { +static void decrement_active_ports_and_notify_locked(grpc_exec_ctx* exec_ctx, + grpc_tcp_listener* sp) { sp->shutting_down = 0; GPR_ASSERT(sp->server->active_ports > 0); if (0 == --sp->server->active_ports) { @@ -244,13 +245,13 @@ static void decrement_active_ports_and_notify_locked(grpc_exec_ctx *exec_ctx, /* In order to do an async accept, we need to create a socket first which will be the one assigned to the new incoming connection. */ -static grpc_error *start_accept_locked(grpc_exec_ctx *exec_ctx, - grpc_tcp_listener *port) { +static grpc_error* start_accept_locked(grpc_exec_ctx* exec_ctx, + grpc_tcp_listener* port) { SOCKET sock = INVALID_SOCKET; BOOL success; DWORD addrlen = sizeof(struct sockaddr_in6) + 16; DWORD bytes_received = 0; - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; if (port->shutting_down) { return GRPC_ERROR_NONE; @@ -295,14 +296,14 @@ failure: } /* Event manager callback when reads are ready. */ -static void on_accept(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { - grpc_tcp_listener *sp = (grpc_tcp_listener *)arg; +static void on_accept(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { + grpc_tcp_listener* sp = (grpc_tcp_listener*)arg; SOCKET sock = sp->new_socket; - grpc_winsocket_callback_info *info = &sp->socket->read_info; - grpc_endpoint *ep = NULL; + grpc_winsocket_callback_info* info = &sp->socket->read_info; + grpc_endpoint* ep = NULL; grpc_resolved_address peer_name; - char *peer_name_string; - char *fd_name; + char* peer_name_string; + char* fd_name; DWORD transfered_bytes; DWORD flags; BOOL wsa_success; @@ -316,7 +317,7 @@ static void on_accept(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { this is necessary in the read/write case, it's useless for the accept case. We only need to adjust the pending callback count */ if (error != GRPC_ERROR_NONE) { - const char *msg = grpc_error_string(error); + const char* msg = grpc_error_string(error); gpr_log(GPR_INFO, "Skipping on_accept due to error: %s", msg); gpr_mu_unlock(&sp->server->mu); @@ -330,7 +331,7 @@ static void on_accept(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { &transfered_bytes, FALSE, &flags); if (!wsa_success) { if (!sp->shutting_down) { - char *utf8_message = gpr_format_message(WSAGetLastError()); + char* utf8_message = gpr_format_message(WSAGetLastError()); gpr_log(GPR_ERROR, "on_accept error: %s", utf8_message); gpr_free(utf8_message); } @@ -339,20 +340,19 @@ static void on_accept(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { if (!sp->shutting_down) { peer_name_string = NULL; err = setsockopt(sock, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, - (char *)&sp->socket->socket, sizeof(sp->socket->socket)); + (char*)&sp->socket->socket, sizeof(sp->socket->socket)); if (err) { - char *utf8_message = gpr_format_message(WSAGetLastError()); + char* utf8_message = gpr_format_message(WSAGetLastError()); gpr_log(GPR_ERROR, "setsockopt error: %s", utf8_message); gpr_free(utf8_message); } int peer_name_len = (int)peer_name.len; - err = - getpeername(sock, (struct sockaddr *)peer_name.addr, &peer_name_len); + err = getpeername(sock, (struct sockaddr*)peer_name.addr, &peer_name_len); peer_name.len = (size_t)peer_name_len; if (!err) { peer_name_string = grpc_sockaddr_to_uri(&peer_name); } else { - char *utf8_message = gpr_format_message(WSAGetLastError()); + char* utf8_message = gpr_format_message(WSAGetLastError()); gpr_log(GPR_ERROR, "getpeername error: %s", utf8_message); gpr_free(utf8_message); } @@ -370,8 +370,8 @@ static void on_accept(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { managed to accept a connection, and created an endpoint. */ if (ep) { // Create acceptor. - grpc_tcp_server_acceptor *acceptor = - (grpc_tcp_server_acceptor *)gpr_malloc(sizeof(*acceptor)); + grpc_tcp_server_acceptor* acceptor = + (grpc_tcp_server_acceptor*)gpr_malloc(sizeof(*acceptor)); acceptor->from_server = sp->server; acceptor->port_index = sp->port_index; acceptor->fd_index = 0; @@ -390,17 +390,17 @@ static void on_accept(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { gpr_mu_unlock(&sp->server->mu); } -static grpc_error *add_socket_to_server(grpc_tcp_server *s, SOCKET sock, - const grpc_resolved_address *addr, +static grpc_error* add_socket_to_server(grpc_tcp_server* s, SOCKET sock, + const grpc_resolved_address* addr, unsigned port_index, - grpc_tcp_listener **listener) { - grpc_tcp_listener *sp = NULL; + grpc_tcp_listener** listener) { + grpc_tcp_listener* sp = NULL; int port = -1; int status; GUID guid = WSAID_ACCEPTEX; DWORD ioctl_num_bytes; LPFN_ACCEPTEX AcceptEx; - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; /* We need to grab the AcceptEx pointer for that port, as it may be interface-dependent. We'll cache it to avoid doing that again. */ @@ -409,7 +409,7 @@ static grpc_error *add_socket_to_server(grpc_tcp_server *s, SOCKET sock, &AcceptEx, sizeof(AcceptEx), &ioctl_num_bytes, NULL, NULL); if (status != 0) { - char *utf8_message = gpr_format_message(WSAGetLastError()); + char* utf8_message = gpr_format_message(WSAGetLastError()); gpr_log(GPR_ERROR, "on_connect error: %s", utf8_message); gpr_free(utf8_message); closesocket(sock); @@ -424,7 +424,7 @@ static grpc_error *add_socket_to_server(grpc_tcp_server *s, SOCKET sock, GPR_ASSERT(port >= 0); gpr_mu_lock(&s->mu); GPR_ASSERT(!s->on_accept_cb && "must add ports before starting server"); - sp = (grpc_tcp_listener *)gpr_malloc(sizeof(grpc_tcp_listener)); + sp = (grpc_tcp_listener*)gpr_malloc(sizeof(grpc_tcp_listener)); sp->next = NULL; if (s->head == NULL) { s->head = sp; @@ -448,17 +448,17 @@ static grpc_error *add_socket_to_server(grpc_tcp_server *s, SOCKET sock, return GRPC_ERROR_NONE; } -grpc_error *grpc_tcp_server_add_port(grpc_tcp_server *s, - const grpc_resolved_address *addr, - int *port) { - grpc_tcp_listener *sp = NULL; +grpc_error* grpc_tcp_server_add_port(grpc_tcp_server* s, + const grpc_resolved_address* addr, + int* port) { + grpc_tcp_listener* sp = NULL; SOCKET sock; grpc_resolved_address addr6_v4mapped; grpc_resolved_address wildcard; - grpc_resolved_address *allocated_addr = NULL; + grpc_resolved_address* allocated_addr = NULL; grpc_resolved_address sockname_temp; unsigned port_index = 0; - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; if (s->tail != NULL) { port_index = s->tail->port_index + 1; @@ -470,13 +470,13 @@ grpc_error *grpc_tcp_server_add_port(grpc_tcp_server *s, for (sp = s->head; sp; sp = sp->next) { int sockname_temp_len = sizeof(struct sockaddr_storage); if (0 == getsockname(sp->socket->socket, - (struct sockaddr *)sockname_temp.addr, + (struct sockaddr*)sockname_temp.addr, &sockname_temp_len)) { sockname_temp.len = (size_t)sockname_temp_len; *port = grpc_sockaddr_get_port(&sockname_temp); if (*port > 0) { - allocated_addr = (grpc_resolved_address *)gpr_malloc( - sizeof(grpc_resolved_address)); + allocated_addr = + (grpc_resolved_address*)gpr_malloc(sizeof(grpc_resolved_address)); memcpy(allocated_addr, addr, sizeof(grpc_resolved_address)); grpc_sockaddr_set_port(allocated_addr, *port); addr = allocated_addr; @@ -510,7 +510,7 @@ done: gpr_free(allocated_addr); if (error != GRPC_ERROR_NONE) { - grpc_error *error_out = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( + grpc_error* error_out = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Failed to add port to server", &error, 1); GRPC_ERROR_UNREF(error); error = error_out; @@ -522,11 +522,11 @@ done: return error; } -void grpc_tcp_server_start(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s, - grpc_pollset **pollset, size_t pollset_count, +void grpc_tcp_server_start(grpc_exec_ctx* exec_ctx, grpc_tcp_server* s, + grpc_pollset** pollset, size_t pollset_count, grpc_tcp_server_cb on_accept_cb, - void *on_accept_cb_arg) { - grpc_tcp_listener *sp; + void* on_accept_cb_arg) { + grpc_tcp_listener* sp; GPR_ASSERT(on_accept_cb); gpr_mu_lock(&s->mu); GPR_ASSERT(!s->on_accept_cb); @@ -541,7 +541,7 @@ void grpc_tcp_server_start(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s, gpr_mu_unlock(&s->mu); } -void grpc_tcp_server_shutdown_listeners(grpc_exec_ctx *exec_ctx, - grpc_tcp_server *s) {} +void grpc_tcp_server_shutdown_listeners(grpc_exec_ctx* exec_ctx, + grpc_tcp_server* s) {} #endif /* GRPC_WINSOCK_SOCKET */ diff --git a/src/core/lib/iomgr/tcp_uv.cc b/src/core/lib/iomgr/tcp_uv.cc index 99b9f1ea2d3..40f4006203e 100644 --- a/src/core/lib/iomgr/tcp_uv.cc +++ b/src/core/lib/iomgr/tcp_uv.cc @@ -38,7 +38,7 @@ #include "src/core/lib/slice/slice_string_helpers.h" #include "src/core/lib/support/string.h" -grpc_tracer_flag grpc_tcp_trace = GRPC_TRACER_INITIALIZER(false, "tcp"); +grpc_core::TraceFlag grpc_tcp_trace(false, "tcp"); typedef struct { grpc_endpoint base; @@ -47,26 +47,25 @@ typedef struct { uv_write_t write_req; uv_shutdown_t shutdown_req; - uv_tcp_t *handle; + uv_tcp_t* handle; - grpc_closure *read_cb; - grpc_closure *write_cb; + grpc_closure* read_cb; + grpc_closure* write_cb; - grpc_slice read_slice; - grpc_slice_buffer *read_slices; - grpc_slice_buffer *write_slices; - uv_buf_t *write_buffers; + grpc_slice_buffer* read_slices; + grpc_slice_buffer* write_slices; + uv_buf_t* write_buffers; - grpc_resource_user *resource_user; + grpc_resource_user* resource_user; + grpc_resource_user_slice_allocator slice_allocator; bool shutting_down; - char *peer_string; - grpc_pollset *pollset; + char* peer_string; + grpc_pollset* pollset; } grpc_tcp; -static void tcp_free(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { - grpc_slice_unref_internal(exec_ctx, tcp->read_slice); +static void tcp_free(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp) { grpc_resource_user_unref(exec_ctx, tcp->resource_user); gpr_free(tcp->handle); gpr_free(tcp->peer_string); @@ -77,9 +76,9 @@ static void tcp_free(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { #define TCP_UNREF(exec_ctx, tcp, reason) \ tcp_unref((exec_ctx), (tcp), (reason), __FILE__, __LINE__) #define TCP_REF(tcp, reason) tcp_ref((tcp), (reason), __FILE__, __LINE__) -static void tcp_unref(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp, - const char *reason, const char *file, int line) { - if (GRPC_TRACER_ON(grpc_tcp_trace)) { +static void tcp_unref(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp, + const char* reason, const char* file, int line) { + if (grpc_tcp_trace.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "TCP unref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp, reason, val, @@ -90,9 +89,9 @@ static void tcp_unref(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp, } } -static void tcp_ref(grpc_tcp *tcp, const char *reason, const char *file, +static void tcp_ref(grpc_tcp* tcp, const char* reason, const char* file, int line) { - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "TCP ref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp, reason, val, @@ -103,114 +102,140 @@ static void tcp_ref(grpc_tcp *tcp, const char *reason, const char *file, #else #define TCP_UNREF(exec_ctx, tcp, reason) tcp_unref((exec_ctx), (tcp)) #define TCP_REF(tcp, reason) tcp_ref((tcp)) -static void tcp_unref(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { +static void tcp_unref(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp) { if (gpr_unref(&tcp->refcount)) { tcp_free(exec_ctx, tcp); } } -static void tcp_ref(grpc_tcp *tcp) { gpr_ref(&tcp->refcount); } +static void tcp_ref(grpc_tcp* tcp) { gpr_ref(&tcp->refcount); } #endif -static void uv_close_callback(uv_handle_t *handle) { +static void uv_close_callback(uv_handle_t* handle) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - grpc_tcp *tcp = (grpc_tcp *)handle->data; + grpc_tcp* tcp = (grpc_tcp*)handle->data; TCP_UNREF(&exec_ctx, tcp, "destroy"); grpc_exec_ctx_finish(&exec_ctx); } -static grpc_slice alloc_read_slice(grpc_exec_ctx *exec_ctx, - grpc_resource_user *resource_user) { - return grpc_resource_user_slice_malloc(exec_ctx, resource_user, - GRPC_TCP_DEFAULT_READ_SLICE_SIZE); -} - -static void alloc_uv_buf(uv_handle_t *handle, size_t suggested_size, - uv_buf_t *buf) { +static void alloc_uv_buf(uv_handle_t* handle, size_t suggested_size, + uv_buf_t* buf) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - grpc_tcp *tcp = (grpc_tcp *)handle->data; + grpc_tcp* tcp = (grpc_tcp*)handle->data; (void)suggested_size; - buf->base = (char *)GRPC_SLICE_START_PTR(tcp->read_slice); - buf->len = GRPC_SLICE_LENGTH(tcp->read_slice); + /* Before calling uv_read_start, we allocate a buffer with exactly one slice + * to tcp->read_slices and wait for the callback indicating that the + * allocation was successful. So slices[0] should always exist here */ + buf->base = (char*)GRPC_SLICE_START_PTR(tcp->read_slices->slices[0]); + buf->len = GRPC_SLICE_LENGTH(tcp->read_slices->slices[0]); grpc_exec_ctx_finish(&exec_ctx); } -static void read_callback(uv_stream_t *stream, ssize_t nread, - const uv_buf_t *buf) { - grpc_slice sub; - grpc_error *error; +static void call_read_cb(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp, + grpc_error* error) { + grpc_closure* cb = tcp->read_cb; + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "TCP:%p call_cb %p %p:%p", tcp, cb, cb->cb, cb->cb_arg); + size_t i; + const char* str = grpc_error_string(error); + gpr_log(GPR_DEBUG, "read: error=%s", str); + + for (i = 0; i < tcp->read_slices->count; i++) { + char* dump = grpc_dump_slice(tcp->read_slices->slices[i], + GPR_DUMP_HEX | GPR_DUMP_ASCII); + gpr_log(GPR_DEBUG, "READ %p (peer=%s): %s", tcp, tcp->peer_string, dump); + gpr_free(dump); + } + } + tcp->read_slices = NULL; + tcp->read_cb = NULL; + GRPC_CLOSURE_RUN(exec_ctx, cb, error); +} + +static void read_callback(uv_stream_t* stream, ssize_t nread, + const uv_buf_t* buf) { + grpc_error* error; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - grpc_tcp *tcp = (grpc_tcp *)stream->data; - grpc_closure *cb = tcp->read_cb; + grpc_tcp* tcp = (grpc_tcp*)stream->data; + grpc_slice_buffer garbage; if (nread == 0) { // Nothing happened. Wait for the next callback return; } TCP_UNREF(&exec_ctx, tcp, "read"); - tcp->read_cb = NULL; // TODO(murgatroid99): figure out what the return value here means uv_read_stop(stream); if (nread == UV_EOF) { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("EOF"); + grpc_slice_buffer_reset_and_unref_internal(&exec_ctx, tcp->read_slices); } else if (nread > 0) { // Successful read - sub = grpc_slice_sub_no_ref(tcp->read_slice, 0, (size_t)nread); - grpc_slice_buffer_add(tcp->read_slices, sub); - tcp->read_slice = alloc_read_slice(&exec_ctx, tcp->resource_user); error = GRPC_ERROR_NONE; - if (GRPC_TRACER_ON(grpc_tcp_trace)) { - size_t i; - const char *str = grpc_error_string(error); - gpr_log(GPR_DEBUG, "read: error=%s", str); - - for (i = 0; i < tcp->read_slices->count; i++) { - char *dump = grpc_dump_slice(tcp->read_slices->slices[i], - GPR_DUMP_HEX | GPR_DUMP_ASCII); - gpr_log(GPR_DEBUG, "READ %p (peer=%s): %s", tcp, tcp->peer_string, - dump); - gpr_free(dump); - } + if ((size_t)nread < tcp->read_slices->length) { + /* TODO(murgatroid99): Instead of discarding the unused part of the read + * buffer, reuse it as the next read buffer. */ + grpc_slice_buffer_init(&garbage); + grpc_slice_buffer_trim_end( + tcp->read_slices, tcp->read_slices->length - (size_t)nread, &garbage); + grpc_slice_buffer_reset_and_unref_internal(&exec_ctx, &garbage); } } else { // nread < 0: Error error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("TCP Read failed"); + grpc_slice_buffer_reset_and_unref_internal(&exec_ctx, tcp->read_slices); } - GRPC_CLOSURE_SCHED(&exec_ctx, cb, error); + call_read_cb(&exec_ctx, tcp, error); grpc_exec_ctx_finish(&exec_ctx); } -static void uv_endpoint_read(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_slice_buffer *read_slices, grpc_closure *cb) { - grpc_tcp *tcp = (grpc_tcp *)ep; +static void tcp_read_allocation_done(grpc_exec_ctx* exec_ctx, void* tcpp, + grpc_error* error) { int status; - grpc_error *error = GRPC_ERROR_NONE; + grpc_tcp* tcp = (grpc_tcp*)tcpp; + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "TCP:%p read_allocation_done: %s", tcp, + grpc_error_string(error)); + } + if (error == GRPC_ERROR_NONE) { + status = + uv_read_start((uv_stream_t*)tcp->handle, alloc_uv_buf, read_callback); + if (status != 0) { + error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("TCP Read failed at start"); + error = grpc_error_set_str( + error, GRPC_ERROR_STR_OS_ERROR, + grpc_slice_from_static_string(uv_strerror(status))); + } + } + if (error != GRPC_ERROR_NONE) { + grpc_slice_buffer_reset_and_unref_internal(exec_ctx, tcp->read_slices); + call_read_cb(exec_ctx, tcp, GRPC_ERROR_REF(error)); + TCP_UNREF(exec_ctx, tcp, "read"); + } + if (grpc_tcp_trace.enabled()) { + const char* str = grpc_error_string(error); + gpr_log(GPR_DEBUG, "Initiating read on %p: error=%s", tcp, str); + } +} + +static void uv_endpoint_read(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_slice_buffer* read_slices, grpc_closure* cb) { + grpc_tcp* tcp = (grpc_tcp*)ep; GRPC_UV_ASSERT_SAME_THREAD(); GPR_ASSERT(tcp->read_cb == NULL); tcp->read_cb = cb; tcp->read_slices = read_slices; grpc_slice_buffer_reset_and_unref_internal(exec_ctx, read_slices); TCP_REF(tcp, "read"); - // TODO(murgatroid99): figure out what the return value here means - status = - uv_read_start((uv_stream_t *)tcp->handle, alloc_uv_buf, read_callback); - if (status != 0) { - error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("TCP Read failed at start"); - error = - grpc_error_set_str(error, GRPC_ERROR_STR_OS_ERROR, - grpc_slice_from_static_string(uv_strerror(status))); - GRPC_CLOSURE_SCHED(exec_ctx, cb, error); - } - if (GRPC_TRACER_ON(grpc_tcp_trace)) { - const char *str = grpc_error_string(error); - gpr_log(GPR_DEBUG, "Initiating read on %p: error=%s", tcp, str); - } + grpc_resource_user_alloc_slices(exec_ctx, &tcp->slice_allocator, + GRPC_TCP_DEFAULT_READ_SLICE_SIZE, 1, + tcp->read_slices); } -static void write_callback(uv_write_t *req, int status) { - grpc_tcp *tcp = (grpc_tcp *)req->data; - grpc_error *error; +static void write_callback(uv_write_t* req, int status) { + grpc_tcp* tcp = (grpc_tcp*)req->data; + grpc_error* error; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - grpc_closure *cb = tcp->write_cb; + grpc_closure* cb = tcp->write_cb; tcp->write_cb = NULL; TCP_UNREF(&exec_ctx, tcp, "write"); if (status == 0) { @@ -218,33 +243,31 @@ static void write_callback(uv_write_t *req, int status) { } else { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("TCP Write failed"); } - if (GRPC_TRACER_ON(grpc_tcp_trace)) { - const char *str = grpc_error_string(error); + if (grpc_tcp_trace.enabled()) { + const char* str = grpc_error_string(error); gpr_log(GPR_DEBUG, "write complete on %p: error=%s", tcp, str); } gpr_free(tcp->write_buffers); - grpc_resource_user_free(&exec_ctx, tcp->resource_user, - sizeof(uv_buf_t) * tcp->write_slices->count); GRPC_CLOSURE_SCHED(&exec_ctx, cb, error); grpc_exec_ctx_finish(&exec_ctx); } -static void uv_endpoint_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_slice_buffer *write_slices, - grpc_closure *cb) { - grpc_tcp *tcp = (grpc_tcp *)ep; - uv_buf_t *buffers; +static void uv_endpoint_write(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_slice_buffer* write_slices, + grpc_closure* cb) { + grpc_tcp* tcp = (grpc_tcp*)ep; + uv_buf_t* buffers; unsigned int buffer_count; unsigned int i; - grpc_slice *slice; - uv_write_t *write_req; + grpc_slice* slice; + uv_write_t* write_req; GRPC_UV_ASSERT_SAME_THREAD(); - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { size_t j; for (j = 0; j < write_slices->count; j++) { - char *data = grpc_dump_slice(write_slices->slices[j], + char* data = grpc_dump_slice(write_slices->slices[j], GPR_DUMP_HEX | GPR_DUMP_ASCII); gpr_log(GPR_DEBUG, "WRITE %p (peer=%s): %s", tcp, tcp->peer_string, data); gpr_free(data); @@ -252,8 +275,9 @@ static void uv_endpoint_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, } if (tcp->shutting_down) { - GRPC_CLOSURE_SCHED(exec_ctx, cb, GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "TCP socket is shutting down")); + GRPC_CLOSURE_SCHED( + exec_ctx, cb, + GRPC_ERROR_CREATE_FROM_STATIC_STRING("TCP socket is shutting down")); return; } @@ -269,12 +293,10 @@ static void uv_endpoint_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, tcp->write_cb = cb; buffer_count = (unsigned int)tcp->write_slices->count; - buffers = (uv_buf_t *)gpr_malloc(sizeof(uv_buf_t) * buffer_count); - grpc_resource_user_alloc(exec_ctx, tcp->resource_user, - sizeof(uv_buf_t) * buffer_count, NULL); + buffers = (uv_buf_t*)gpr_malloc(sizeof(uv_buf_t) * buffer_count); for (i = 0; i < buffer_count; i++) { slice = &tcp->write_slices->slices[i]; - buffers[i].base = (char *)GRPC_SLICE_START_PTR(*slice); + buffers[i].base = (char*)GRPC_SLICE_START_PTR(*slice); buffers[i].len = GRPC_SLICE_LENGTH(*slice); } tcp->write_buffers = buffers; @@ -282,72 +304,72 @@ static void uv_endpoint_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, write_req->data = tcp; TCP_REF(tcp, "write"); // TODO(murgatroid99): figure out what the return value here means - uv_write(write_req, (uv_stream_t *)tcp->handle, buffers, buffer_count, + uv_write(write_req, (uv_stream_t*)tcp->handle, buffers, buffer_count, write_callback); } -static void uv_add_to_pollset(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_pollset *pollset) { +static void uv_add_to_pollset(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_pollset* pollset) { // No-op. We're ignoring pollsets currently (void)exec_ctx; (void)ep; (void)pollset; - grpc_tcp *tcp = (grpc_tcp *)ep; + grpc_tcp* tcp = (grpc_tcp*)ep; tcp->pollset = pollset; } -static void uv_add_to_pollset_set(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_pollset_set *pollset) { +static void uv_add_to_pollset_set(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_pollset_set* pollset) { // No-op. We're ignoring pollsets currently (void)exec_ctx; (void)ep; (void)pollset; } -static void uv_delete_from_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_endpoint *ep, - grpc_pollset_set *pollset) { +static void uv_delete_from_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_endpoint* ep, + grpc_pollset_set* pollset) { // No-op. We're ignoring pollsets currently (void)exec_ctx; (void)ep; (void)pollset; } -static void shutdown_callback(uv_shutdown_t *req, int status) {} +static void shutdown_callback(uv_shutdown_t* req, int status) {} -static void uv_endpoint_shutdown(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_error *why) { - grpc_tcp *tcp = (grpc_tcp *)ep; +static void uv_endpoint_shutdown(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_error* why) { + grpc_tcp* tcp = (grpc_tcp*)ep; if (!tcp->shutting_down) { - if (GRPC_TRACER_ON(grpc_tcp_trace)) { - const char *str = grpc_error_string(why); + if (grpc_tcp_trace.enabled()) { + const char* str = grpc_error_string(why); gpr_log(GPR_DEBUG, "TCP %p shutdown why=%s", tcp->handle, str); } tcp->shutting_down = true; - uv_shutdown_t *req = &tcp->shutdown_req; - uv_shutdown(req, (uv_stream_t *)tcp->handle, shutdown_callback); + uv_shutdown_t* req = &tcp->shutdown_req; + uv_shutdown(req, (uv_stream_t*)tcp->handle, shutdown_callback); grpc_resource_user_shutdown(exec_ctx, tcp->resource_user); } GRPC_ERROR_UNREF(why); } -static void uv_destroy(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) { +static void uv_destroy(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep) { grpc_network_status_unregister_endpoint(ep); - grpc_tcp *tcp = (grpc_tcp *)ep; - uv_close((uv_handle_t *)tcp->handle, uv_close_callback); + grpc_tcp* tcp = (grpc_tcp*)ep; + uv_close((uv_handle_t*)tcp->handle, uv_close_callback); } -static char *uv_get_peer(grpc_endpoint *ep) { - grpc_tcp *tcp = (grpc_tcp *)ep; +static char* uv_get_peer(grpc_endpoint* ep) { + grpc_tcp* tcp = (grpc_tcp*)ep; return gpr_strdup(tcp->peer_string); } -static grpc_resource_user *uv_get_resource_user(grpc_endpoint *ep) { - grpc_tcp *tcp = (grpc_tcp *)ep; +static grpc_resource_user* uv_get_resource_user(grpc_endpoint* ep) { + grpc_tcp* tcp = (grpc_tcp*)ep; return tcp->resource_user; } -static int uv_get_fd(grpc_endpoint *ep) { return -1; } +static int uv_get_fd(grpc_endpoint* ep) { return -1; } static grpc_endpoint_vtable vtable = {uv_endpoint_read, uv_endpoint_write, @@ -360,13 +382,13 @@ static grpc_endpoint_vtable vtable = {uv_endpoint_read, uv_get_peer, uv_get_fd}; -grpc_endpoint *grpc_tcp_create(uv_tcp_t *handle, - grpc_resource_quota *resource_quota, - char *peer_string) { - grpc_tcp *tcp = (grpc_tcp *)gpr_malloc(sizeof(grpc_tcp)); +grpc_endpoint* grpc_tcp_create(uv_tcp_t* handle, + grpc_resource_quota* resource_quota, + char* peer_string) { + grpc_tcp* tcp = (grpc_tcp*)gpr_malloc(sizeof(grpc_tcp)); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_log(GPR_DEBUG, "Creating TCP endpoint %p", tcp); } @@ -380,13 +402,15 @@ grpc_endpoint *grpc_tcp_create(uv_tcp_t *handle, gpr_ref_init(&tcp->refcount, 1); tcp->peer_string = gpr_strdup(peer_string); tcp->shutting_down = false; + tcp->read_slices = NULL; tcp->resource_user = grpc_resource_user_create(resource_quota, peer_string); - tcp->read_slice = alloc_read_slice(&exec_ctx, tcp->resource_user); + grpc_resource_user_slice_allocator_init( + &tcp->slice_allocator, tcp->resource_user, tcp_read_allocation_done, tcp); /* Tell network status tracking code about the new endpoint */ grpc_network_status_register_endpoint(&tcp->base); #ifndef GRPC_UV_TCP_HOLD_LOOP - uv_unref((uv_handle_t *)handle); + uv_unref((uv_handle_t*)handle); #endif grpc_exec_ctx_finish(&exec_ctx); diff --git a/src/core/lib/iomgr/tcp_uv.h b/src/core/lib/iomgr/tcp_uv.h index 3399535b421..fd6d19049ac 100644 --- a/src/core/lib/iomgr/tcp_uv.h +++ b/src/core/lib/iomgr/tcp_uv.h @@ -32,22 +32,20 @@ #include "src/core/lib/debug/trace.h" #include "src/core/lib/iomgr/endpoint.h" +#include "src/core/lib/iomgr/port.h" + +#ifdef GRPC_UV + #include -extern grpc_tracer_flag grpc_tcp_trace; +extern grpc_core::TraceFlag grpc_tcp_trace; #define GRPC_TCP_DEFAULT_READ_SLICE_SIZE 8192 -#ifdef __cplusplus -extern "C" { -#endif - -grpc_endpoint *grpc_tcp_create(uv_tcp_t *handle, - grpc_resource_quota *resource_quota, - char *peer_string); +grpc_endpoint* grpc_tcp_create(uv_tcp_t* handle, + grpc_resource_quota* resource_quota, + char* peer_string); -#ifdef __cplusplus -} -#endif +#endif /* GRPC_UV */ #endif /* GRPC_CORE_LIB_IOMGR_TCP_UV_H */ diff --git a/src/core/lib/iomgr/tcp_windows.cc b/src/core/lib/iomgr/tcp_windows.cc index 6efcff84b8b..33868cdc7a7 100644 --- a/src/core/lib/iomgr/tcp_windows.cc +++ b/src/core/lib/iomgr/tcp_windows.cc @@ -49,9 +49,9 @@ #define GRPC_FIONBIO FIONBIO #endif -grpc_tracer_flag grpc_tcp_trace = GRPC_TRACER_INITIALIZER(false, "tcp"); +grpc_core::TraceFlag grpc_tcp_trace(false, "tcp"); -static grpc_error *set_non_block(SOCKET sock) { +static grpc_error* set_non_block(SOCKET sock) { int status; uint32_t param = 1; DWORD ret; @@ -62,18 +62,18 @@ static grpc_error *set_non_block(SOCKET sock) { : GRPC_WSA_ERROR(WSAGetLastError(), "WSAIoctl(GRPC_FIONBIO)"); } -static grpc_error *set_dualstack(SOCKET sock) { +static grpc_error* set_dualstack(SOCKET sock) { int status; unsigned long param = 0; - status = setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char *)¶m, + status = setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)¶m, sizeof(param)); return status == 0 ? GRPC_ERROR_NONE : GRPC_WSA_ERROR(WSAGetLastError(), "setsockopt(IPV6_V6ONLY)"); } -grpc_error *grpc_tcp_prepare_socket(SOCKET sock) { - grpc_error *err; +grpc_error* grpc_tcp_prepare_socket(SOCKET sock) { + grpc_error* err; err = set_non_block(sock); if (err != GRPC_ERROR_NONE) return err; err = set_dualstack(sock); @@ -85,31 +85,31 @@ typedef struct grpc_tcp { /* This is our C++ class derivation emulation. */ grpc_endpoint base; /* The one socket this endpoint is using. */ - grpc_winsocket *socket; + grpc_winsocket* socket; /* Refcounting how many operations are in progress. */ gpr_refcount refcount; grpc_closure on_read; grpc_closure on_write; - grpc_closure *read_cb; - grpc_closure *write_cb; + grpc_closure* read_cb; + grpc_closure* write_cb; grpc_slice read_slice; - grpc_slice_buffer *write_slices; - grpc_slice_buffer *read_slices; + grpc_slice_buffer* write_slices; + grpc_slice_buffer* read_slices; - grpc_resource_user *resource_user; + grpc_resource_user* resource_user; /* The IO Completion Port runs from another thread. We need some mechanism to protect ourselves when requesting a shutdown. */ gpr_mu mu; int shutting_down; - grpc_error *shutdown_error; + grpc_error* shutdown_error; - char *peer_string; + char* peer_string; } grpc_tcp; -static void tcp_free(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { +static void tcp_free(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp) { grpc_winsocket_destroy(tcp->socket); gpr_mu_destroy(&tcp->mu); gpr_free(tcp->peer_string); @@ -122,9 +122,9 @@ static void tcp_free(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { #define TCP_UNREF(exec_ctx, tcp, reason) \ tcp_unref((exec_ctx), (tcp), (reason), __FILE__, __LINE__) #define TCP_REF(tcp, reason) tcp_ref((tcp), (reason), __FILE__, __LINE__) -static void tcp_unref(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp, - const char *reason, const char *file, int line) { - if (GRPC_TRACER_ON(grpc_tcp_trace)) { +static void tcp_unref(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp, + const char* reason, const char* file, int line) { + if (grpc_tcp_trace.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "TCP unref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp, reason, val, @@ -135,9 +135,9 @@ static void tcp_unref(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp, } } -static void tcp_ref(grpc_tcp *tcp, const char *reason, const char *file, +static void tcp_ref(grpc_tcp* tcp, const char* reason, const char* file, int line) { - if (GRPC_TRACER_ON(grpc_tcp_trace)) { + if (grpc_tcp_trace.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "TCP ref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp, reason, val, @@ -148,28 +148,28 @@ static void tcp_ref(grpc_tcp *tcp, const char *reason, const char *file, #else #define TCP_UNREF(exec_ctx, tcp, reason) tcp_unref((exec_ctx), (tcp)) #define TCP_REF(tcp, reason) tcp_ref((tcp)) -static void tcp_unref(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { +static void tcp_unref(grpc_exec_ctx* exec_ctx, grpc_tcp* tcp) { if (gpr_unref(&tcp->refcount)) { tcp_free(exec_ctx, tcp); } } -static void tcp_ref(grpc_tcp *tcp) { gpr_ref(&tcp->refcount); } +static void tcp_ref(grpc_tcp* tcp) { gpr_ref(&tcp->refcount); } #endif /* Asynchronous callback from the IOCP, or the background thread. */ -static void on_read(grpc_exec_ctx *exec_ctx, void *tcpp, grpc_error *error) { - grpc_tcp *tcp = (grpc_tcp *)tcpp; - grpc_closure *cb = tcp->read_cb; - grpc_winsocket *socket = tcp->socket; +static void on_read(grpc_exec_ctx* exec_ctx, void* tcpp, grpc_error* error) { + grpc_tcp* tcp = (grpc_tcp*)tcpp; + grpc_closure* cb = tcp->read_cb; + grpc_winsocket* socket = tcp->socket; grpc_slice sub; - grpc_winsocket_callback_info *info = &socket->read_info; + grpc_winsocket_callback_info* info = &socket->read_info; GRPC_ERROR_REF(error); if (error == GRPC_ERROR_NONE) { if (info->wsa_error != 0 && !tcp->shutting_down) { - char *utf8_message = gpr_format_message(info->wsa_error); + char* utf8_message = gpr_format_message(info->wsa_error); error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(utf8_message); gpr_free(utf8_message); grpc_slice_unref_internal(exec_ctx, tcp->read_slice); @@ -192,11 +192,11 @@ static void on_read(grpc_exec_ctx *exec_ctx, void *tcpp, grpc_error *error) { GRPC_CLOSURE_SCHED(exec_ctx, cb, error); } -static void win_read(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_slice_buffer *read_slices, grpc_closure *cb) { - grpc_tcp *tcp = (grpc_tcp *)ep; - grpc_winsocket *handle = tcp->socket; - grpc_winsocket_callback_info *info = &handle->read_info; +static void win_read(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_slice_buffer* read_slices, grpc_closure* cb) { + grpc_tcp* tcp = (grpc_tcp*)ep; + grpc_winsocket* handle = tcp->socket; + grpc_winsocket_callback_info* info = &handle->read_info; int status; DWORD bytes_read = 0; DWORD flags = 0; @@ -218,7 +218,7 @@ static void win_read(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, buffer.len = (ULONG)GRPC_SLICE_LENGTH( tcp->read_slice); // we know slice size fits in 32bit. - buffer.buf = (char *)GRPC_SLICE_START_PTR(tcp->read_slice); + buffer.buf = (char*)GRPC_SLICE_START_PTR(tcp->read_slice); TCP_REF(tcp, "read"); @@ -253,11 +253,11 @@ static void win_read(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, } /* Asynchronous callback from the IOCP, or the background thread. */ -static void on_write(grpc_exec_ctx *exec_ctx, void *tcpp, grpc_error *error) { - grpc_tcp *tcp = (grpc_tcp *)tcpp; - grpc_winsocket *handle = tcp->socket; - grpc_winsocket_callback_info *info = &handle->write_info; - grpc_closure *cb; +static void on_write(grpc_exec_ctx* exec_ctx, void* tcpp, grpc_error* error) { + grpc_tcp* tcp = (grpc_tcp*)tcpp; + grpc_winsocket* handle = tcp->socket; + grpc_winsocket_callback_info* info = &handle->write_info; + grpc_closure* cb; GRPC_ERROR_REF(error); @@ -279,17 +279,17 @@ static void on_write(grpc_exec_ctx *exec_ctx, void *tcpp, grpc_error *error) { } /* Initiates a write. */ -static void win_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_slice_buffer *slices, grpc_closure *cb) { - grpc_tcp *tcp = (grpc_tcp *)ep; - grpc_winsocket *socket = tcp->socket; - grpc_winsocket_callback_info *info = &socket->write_info; +static void win_write(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_slice_buffer* slices, grpc_closure* cb) { + grpc_tcp* tcp = (grpc_tcp*)ep; + grpc_winsocket* socket = tcp->socket; + grpc_winsocket_callback_info* info = &socket->write_info; unsigned i; DWORD bytes_sent; int status; WSABUF local_buffers[16]; - WSABUF *allocated = NULL; - WSABUF *buffers = local_buffers; + WSABUF* allocated = NULL; + WSABUF* buffers = local_buffers; size_t len; if (tcp->shutting_down) { @@ -304,7 +304,7 @@ static void win_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, tcp->write_slices = slices; GPR_ASSERT(tcp->write_slices->count <= UINT_MAX); if (tcp->write_slices->count > GPR_ARRAY_SIZE(local_buffers)) { - buffers = (WSABUF *)gpr_malloc(sizeof(WSABUF) * tcp->write_slices->count); + buffers = (WSABUF*)gpr_malloc(sizeof(WSABUF) * tcp->write_slices->count); allocated = buffers; } @@ -312,7 +312,7 @@ static void win_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, len = GRPC_SLICE_LENGTH(tcp->write_slices->slices[i]); GPR_ASSERT(len <= ULONG_MAX); buffers[i].len = (ULONG)len; - buffers[i].buf = (char *)GRPC_SLICE_START_PTR(tcp->write_slices->slices[i]); + buffers[i].buf = (char*)GRPC_SLICE_START_PTR(tcp->write_slices->slices[i]); } /* First, let's try a synchronous, non-blocking write. */ @@ -324,7 +324,7 @@ static void win_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, connection that has its send queue filled up. But if we don't, then we can avoid doing an async write operation at all. */ if (info->wsa_error != WSAEWOULDBLOCK) { - grpc_error *error = status == 0 + grpc_error* error = status == 0 ? GRPC_ERROR_NONE : GRPC_WSA_ERROR(info->wsa_error, "WSASend"); GRPC_CLOSURE_SCHED(exec_ctx, cb, error); @@ -355,25 +355,25 @@ static void win_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, grpc_socket_notify_on_write(exec_ctx, socket, &tcp->on_write); } -static void win_add_to_pollset(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_pollset *ps) { - grpc_tcp *tcp; +static void win_add_to_pollset(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_pollset* ps) { + grpc_tcp* tcp; (void)ps; - tcp = (grpc_tcp *)ep; + tcp = (grpc_tcp*)ep; grpc_iocp_add_socket(tcp->socket); } -static void win_add_to_pollset_set(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_pollset_set *pss) { - grpc_tcp *tcp; +static void win_add_to_pollset_set(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_pollset_set* pss) { + grpc_tcp* tcp; (void)pss; - tcp = (grpc_tcp *)ep; + tcp = (grpc_tcp*)ep; grpc_iocp_add_socket(tcp->socket); } -static void win_delete_from_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_endpoint *ep, - grpc_pollset_set *pss) {} +static void win_delete_from_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_endpoint* ep, + grpc_pollset_set* pss) {} /* Initiates a shutdown of the TCP endpoint. This will queue abort callbacks for the potential read and write operations. It is up to the caller to @@ -381,9 +381,9 @@ static void win_delete_from_pollset_set(grpc_exec_ctx *exec_ctx, we're not going to protect against these. However the IO Completion Port callback will happen from another thread, so we need to protect against concurrent access of the data structure in that regard. */ -static void win_shutdown(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, - grpc_error *why) { - grpc_tcp *tcp = (grpc_tcp *)ep; +static void win_shutdown(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep, + grpc_error* why) { + grpc_tcp* tcp = (grpc_tcp*)ep; gpr_mu_lock(&tcp->mu); /* At that point, what may happen is that we're already inside the IOCP callback. See the comments in on_read and on_write. */ @@ -398,23 +398,23 @@ static void win_shutdown(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, grpc_resource_user_shutdown(exec_ctx, tcp->resource_user); } -static void win_destroy(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) { +static void win_destroy(grpc_exec_ctx* exec_ctx, grpc_endpoint* ep) { grpc_network_status_unregister_endpoint(ep); - grpc_tcp *tcp = (grpc_tcp *)ep; + grpc_tcp* tcp = (grpc_tcp*)ep; TCP_UNREF(exec_ctx, tcp, "destroy"); } -static char *win_get_peer(grpc_endpoint *ep) { - grpc_tcp *tcp = (grpc_tcp *)ep; +static char* win_get_peer(grpc_endpoint* ep) { + grpc_tcp* tcp = (grpc_tcp*)ep; return gpr_strdup(tcp->peer_string); } -static grpc_resource_user *win_get_resource_user(grpc_endpoint *ep) { - grpc_tcp *tcp = (grpc_tcp *)ep; +static grpc_resource_user* win_get_resource_user(grpc_endpoint* ep) { + grpc_tcp* tcp = (grpc_tcp*)ep; return tcp->resource_user; } -static int win_get_fd(grpc_endpoint *ep) { return -1; } +static int win_get_fd(grpc_endpoint* ep) { return -1; } static grpc_endpoint_vtable vtable = {win_read, win_write, @@ -427,20 +427,20 @@ static grpc_endpoint_vtable vtable = {win_read, win_get_peer, win_get_fd}; -grpc_endpoint *grpc_tcp_create(grpc_exec_ctx *exec_ctx, grpc_winsocket *socket, - grpc_channel_args *channel_args, - const char *peer_string) { - grpc_resource_quota *resource_quota = grpc_resource_quota_create(NULL); +grpc_endpoint* grpc_tcp_create(grpc_exec_ctx* exec_ctx, grpc_winsocket* socket, + grpc_channel_args* channel_args, + const char* peer_string) { + grpc_resource_quota* resource_quota = grpc_resource_quota_create(NULL); if (channel_args != NULL) { for (size_t i = 0; i < channel_args->num_args; i++) { if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) { grpc_resource_quota_unref_internal(exec_ctx, resource_quota); resource_quota = grpc_resource_quota_ref_internal( - (grpc_resource_quota *)channel_args->args[i].value.pointer.p); + (grpc_resource_quota*)channel_args->args[i].value.pointer.p); } } } - grpc_tcp *tcp = (grpc_tcp *)gpr_malloc(sizeof(grpc_tcp)); + grpc_tcp* tcp = (grpc_tcp*)gpr_malloc(sizeof(grpc_tcp)); memset(tcp, 0, sizeof(grpc_tcp)); tcp->base.vtable = &vtable; tcp->socket = socket; diff --git a/src/core/lib/iomgr/tcp_windows.h b/src/core/lib/iomgr/tcp_windows.h index f3697f707c7..28287e27950 100644 --- a/src/core/lib/iomgr/tcp_windows.h +++ b/src/core/lib/iomgr/tcp_windows.h @@ -29,24 +29,21 @@ otherwise specified. */ +#include "src/core/lib/iomgr/port.h" + +#ifdef GRPC_WINSOCK_SOCKET #include "src/core/lib/iomgr/endpoint.h" #include "src/core/lib/iomgr/socket_windows.h" -#ifdef __cplusplus -extern "C" { -#endif - /* Create a tcp endpoint given a winsock handle. * Takes ownership of the handle. */ -grpc_endpoint *grpc_tcp_create(grpc_exec_ctx *exec_ctx, grpc_winsocket *socket, - grpc_channel_args *channel_args, - const char *peer_string); +grpc_endpoint* grpc_tcp_create(grpc_exec_ctx* exec_ctx, grpc_winsocket* socket, + grpc_channel_args* channel_args, + const char* peer_string); -grpc_error *grpc_tcp_prepare_socket(SOCKET sock); +grpc_error* grpc_tcp_prepare_socket(SOCKET sock); -#ifdef __cplusplus -} #endif #endif /* GRPC_CORE_LIB_IOMGR_TCP_WINDOWS_H */ diff --git a/src/core/lib/iomgr/time_averaged_stats.h b/src/core/lib/iomgr/time_averaged_stats.h index d38ed272b6d..8745f7fa13f 100644 --- a/src/core/lib/iomgr/time_averaged_stats.h +++ b/src/core/lib/iomgr/time_averaged_stats.h @@ -19,10 +19,6 @@ #ifndef GRPC_CORE_LIB_IOMGR_TIME_AVERAGED_STATS_H #define GRPC_CORE_LIB_IOMGR_TIME_AVERAGED_STATS_H -#ifdef __cplusplus -extern "C" { -#endif - /* This tracks a time-decaying weighted average. It works by collecting batches of samples and then mixing their average into a time-decaying weighted mean. It is designed for batch operations where we do many adds @@ -74,8 +70,4 @@ void grpc_time_averaged_stats_add_sample(grpc_time_averaged_stats* stats, value. */ double grpc_time_averaged_stats_update_average(grpc_time_averaged_stats* stats); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_TIME_AVERAGED_STATS_H */ diff --git a/src/core/lib/iomgr/timer.h b/src/core/lib/iomgr/timer.h index 419e834cf18..b9acce229ec 100644 --- a/src/core/lib/iomgr/timer.h +++ b/src/core/lib/iomgr/timer.h @@ -32,10 +32,6 @@ #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/iomgr/iomgr.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_timer grpc_timer; /* Initialize *timer. When expired or canceled, closure will be called with @@ -44,12 +40,12 @@ typedef struct grpc_timer grpc_timer; application code should check the error to determine how it was invoked. The application callback is also responsible for maintaining information about when to free up any user-level state. */ -void grpc_timer_init(grpc_exec_ctx *exec_ctx, grpc_timer *timer, - grpc_millis deadline, grpc_closure *closure); +void grpc_timer_init(grpc_exec_ctx* exec_ctx, grpc_timer* timer, + grpc_millis deadline, grpc_closure* closure); /* Initialize *timer without setting it. This can later be passed through the regular init or cancel */ -void grpc_timer_init_unset(grpc_timer *timer); +void grpc_timer_init_unset(grpc_timer* timer); /* Note that there is no timer destroy function. This is because the timer is a one-time occurrence with a guarantee that the callback will @@ -77,7 +73,7 @@ void grpc_timer_init_unset(grpc_timer *timer); matches this aim. Requires: cancel() must happen after init() on a given timer */ -void grpc_timer_cancel(grpc_exec_ctx *exec_ctx, grpc_timer *timer); +void grpc_timer_cancel(grpc_exec_ctx* exec_ctx, grpc_timer* timer); /* iomgr internal api for dealing with timers */ @@ -94,10 +90,10 @@ typedef enum { *next is never guaranteed to be updated on any given execution; however, with high probability at least one thread in the system will see an update at any time slice. */ -grpc_timer_check_result grpc_timer_check(grpc_exec_ctx *exec_ctx, - grpc_millis *next); -void grpc_timer_list_init(grpc_exec_ctx *exec_ctx); -void grpc_timer_list_shutdown(grpc_exec_ctx *exec_ctx); +grpc_timer_check_result grpc_timer_check(grpc_exec_ctx* exec_ctx, + grpc_millis* next); +void grpc_timer_list_init(grpc_exec_ctx* exec_ctx); +void grpc_timer_list_shutdown(grpc_exec_ctx* exec_ctx); /* Consume a kick issued by grpc_kick_poller */ void grpc_timer_consume_kick(void); @@ -106,8 +102,4 @@ void grpc_timer_consume_kick(void); void grpc_kick_poller(void); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_TIMER_H */ diff --git a/src/core/lib/iomgr/timer_generic.cc b/src/core/lib/iomgr/timer_generic.cc index b8e895de6f0..fa95c43dbe3 100644 --- a/src/core/lib/iomgr/timer_generic.cc +++ b/src/core/lib/iomgr/timer_generic.cc @@ -25,6 +25,7 @@ #include "src/core/lib/iomgr/timer.h" #include +#include #include #include #include @@ -37,17 +38,12 @@ #define INVALID_HEAP_INDEX 0xffffffffu -#define LOG2_NUM_SHARDS 5 -#define NUM_SHARDS (1 << LOG2_NUM_SHARDS) #define ADD_DEADLINE_SCALE 0.33 #define MIN_QUEUE_WINDOW_DURATION 0.01 #define MAX_QUEUE_WINDOW_DURATION 1 -extern "C" { -grpc_tracer_flag grpc_timer_trace = GRPC_TRACER_INITIALIZER(false, "timer"); -grpc_tracer_flag grpc_timer_check_trace = - GRPC_TRACER_INITIALIZER(false, "timer_check"); -} +grpc_core::TraceFlag grpc_timer_trace(false, "timer"); +grpc_core::TraceFlag grpc_timer_check_trace(false, "timer_check"); /* A "timer shard". Contains a 'heap' and a 'list' of timers. All timers with * deadlines earlier than 'queue_deadline" cap are maintained in the heap and @@ -74,14 +70,16 @@ typedef struct { grpc_timer list; } timer_shard; +static size_t g_num_shards; + /* Array of timer shards. Whenever a timer (grpc_timer *) is added, its address * is hashed to select the timer shard to add the timer to */ -static timer_shard g_shards[NUM_SHARDS]; +static timer_shard* g_shards; /* Maintains a sorted list of timer shards (sorted by their min_deadline, i.e * the deadline of the next timer in each shard). * Access to this is protected by g_shared_mutables.mu */ -static timer_shard *g_shard_queue[NUM_SHARDS]; +static timer_shard** g_shard_queue; #ifndef NDEBUG @@ -90,7 +88,7 @@ static timer_shard *g_shard_queue[NUM_SHARDS]; #define NUM_HASH_BUCKETS 1009 /* Prime number close to 1000 */ static gpr_mu g_hash_mu[NUM_HASH_BUCKETS]; /* One mutex per bucket */ -static grpc_timer *g_timer_ht[NUM_HASH_BUCKETS] = {NULL}; +static grpc_timer* g_timer_ht[NUM_HASH_BUCKETS] = {nullptr}; static void init_timer_ht() { for (int i = 0; i < NUM_HASH_BUCKETS; i++) { @@ -98,12 +96,12 @@ static void init_timer_ht() { } } -static bool is_in_ht(grpc_timer *t) { +static bool is_in_ht(grpc_timer* t) { size_t i = GPR_HASH_POINTER(t, NUM_HASH_BUCKETS); gpr_mu_lock(&g_hash_mu[i]); - grpc_timer *p = g_timer_ht[i]; - while (p != NULL && p != t) { + grpc_timer* p = g_timer_ht[i]; + while (p != nullptr && p != t) { p = p->hash_table_next; } gpr_mu_unlock(&g_hash_mu[i]); @@ -111,18 +109,18 @@ static bool is_in_ht(grpc_timer *t) { return (p == t); } -static void add_to_ht(grpc_timer *t) { +static void add_to_ht(grpc_timer* t) { GPR_ASSERT(!t->hash_table_next); size_t i = GPR_HASH_POINTER(t, NUM_HASH_BUCKETS); gpr_mu_lock(&g_hash_mu[i]); - grpc_timer *p = g_timer_ht[i]; - while (p != NULL && p != t) { + grpc_timer* p = g_timer_ht[i]; + while (p != nullptr && p != t) { p = p->hash_table_next; } if (p == t) { - grpc_closure *c = t->closure; + grpc_closure* c = t->closure; gpr_log(GPR_ERROR, "** Duplicate timer (%p) being added. Closure: (%p), created at: " "(%s:%d), scheduled at: (%s:%d) **", @@ -137,7 +135,7 @@ static void add_to_ht(grpc_timer *t) { gpr_mu_unlock(&g_hash_mu[i]); } -static void remove_from_ht(grpc_timer *t) { +static void remove_from_ht(grpc_timer* t) { size_t i = GPR_HASH_POINTER(t, NUM_HASH_BUCKETS); bool removed = false; @@ -145,9 +143,9 @@ static void remove_from_ht(grpc_timer *t) { if (g_timer_ht[i] == t) { g_timer_ht[i] = g_timer_ht[i]->hash_table_next; removed = true; - } else if (g_timer_ht[i] != NULL) { - grpc_timer *p = g_timer_ht[i]; - while (p->hash_table_next != NULL && p->hash_table_next != t) { + } else if (g_timer_ht[i] != nullptr) { + grpc_timer* p = g_timer_ht[i]; + while (p->hash_table_next != nullptr && p->hash_table_next != t) { p = p->hash_table_next; } @@ -159,7 +157,7 @@ static void remove_from_ht(grpc_timer *t) { gpr_mu_unlock(&g_hash_mu[i]); if (!removed) { - grpc_closure *c = t->closure; + grpc_closure* c = t->closure; gpr_log(GPR_ERROR, "** Removing timer (%p) that is not added to hash table. Closure " "(%p), created at: (%s:%d), scheduled at: (%s:%d) **", @@ -168,16 +166,16 @@ static void remove_from_ht(grpc_timer *t) { abort(); } - t->hash_table_next = NULL; + t->hash_table_next = nullptr; } /* If a timer is added to a timer shard (either heap or a list), it cannot * be pending. A timer is added to hash table only-if it is added to the * timer shard. * Therefore, if timer->pending is false, it cannot be in hash table */ -static void validate_non_pending_timer(grpc_timer *t) { +static void validate_non_pending_timer(grpc_timer* t) { if (!t->pending && is_in_ht(t)) { - grpc_closure *c = t->closure; + grpc_closure* c = t->closure; gpr_log(GPR_ERROR, "** gpr_timer_cancel() called on a non-pending timer (%p) which " "is in the hash table. Closure: (%p), created at: (%s:%d), " @@ -227,31 +225,34 @@ static gpr_atm saturating_add(gpr_atm a, gpr_atm b) { return a + b; } -static grpc_timer_check_result run_some_expired_timers(grpc_exec_ctx *exec_ctx, +static grpc_timer_check_result run_some_expired_timers(grpc_exec_ctx* exec_ctx, gpr_atm now, - gpr_atm *next, - grpc_error *error); + gpr_atm* next, + grpc_error* error); -static gpr_atm compute_min_deadline(timer_shard *shard) { +static gpr_atm compute_min_deadline(timer_shard* shard) { return grpc_timer_heap_is_empty(&shard->heap) ? saturating_add(shard->queue_deadline_cap, 1) : grpc_timer_heap_top(&shard->heap)->deadline; } -void grpc_timer_list_init(grpc_exec_ctx *exec_ctx) { +void grpc_timer_list_init(grpc_exec_ctx* exec_ctx) { uint32_t i; + g_num_shards = GPR_MIN(1, 2 * gpr_cpu_num_cores()); + g_shards = (timer_shard*)gpr_zalloc(g_num_shards * sizeof(*g_shards)); + g_shard_queue = + (timer_shard**)gpr_zalloc(g_num_shards * sizeof(*g_shard_queue)); + g_shared_mutables.initialized = true; g_shared_mutables.checker_mu = GPR_SPINLOCK_INITIALIZER; gpr_mu_init(&g_shared_mutables.mu); g_shared_mutables.min_timer = grpc_exec_ctx_now(exec_ctx); gpr_tls_init(&g_last_seen_min_timer); gpr_tls_set(&g_last_seen_min_timer, 0); - grpc_register_tracer(&grpc_timer_trace); - grpc_register_tracer(&grpc_timer_check_trace); - for (i = 0; i < NUM_SHARDS; i++) { - timer_shard *shard = &g_shards[i]; + for (i = 0; i < g_num_shards; i++) { + timer_shard* shard = &g_shards[i]; gpr_mu_init(&shard->mu); grpc_time_averaged_stats_init(&shard->stats, 1.0 / ADD_DEADLINE_SCALE, 0.1, 0.5); @@ -266,35 +267,37 @@ void grpc_timer_list_init(grpc_exec_ctx *exec_ctx) { INIT_TIMER_HASH_TABLE(); } -void grpc_timer_list_shutdown(grpc_exec_ctx *exec_ctx) { - int i; +void grpc_timer_list_shutdown(grpc_exec_ctx* exec_ctx) { + size_t i; run_some_expired_timers( - exec_ctx, GPR_ATM_MAX, NULL, + exec_ctx, GPR_ATM_MAX, nullptr, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Timer list shutdown")); - for (i = 0; i < NUM_SHARDS; i++) { - timer_shard *shard = &g_shards[i]; + for (i = 0; i < g_num_shards; i++) { + timer_shard* shard = &g_shards[i]; gpr_mu_destroy(&shard->mu); grpc_timer_heap_destroy(&shard->heap); } gpr_mu_destroy(&g_shared_mutables.mu); gpr_tls_destroy(&g_last_seen_min_timer); + gpr_free(g_shards); + gpr_free(g_shard_queue); g_shared_mutables.initialized = false; } /* returns true if the first element in the list */ -static void list_join(grpc_timer *head, grpc_timer *timer) { +static void list_join(grpc_timer* head, grpc_timer* timer) { timer->next = head; timer->prev = head->prev; timer->next->prev = timer->prev->next = timer; } -static void list_remove(grpc_timer *timer) { +static void list_remove(grpc_timer* timer) { timer->next->prev = timer->prev; timer->prev->next = timer->next; } static void swap_adjacent_shards_in_queue(uint32_t first_shard_queue_index) { - timer_shard *temp; + timer_shard* temp; temp = g_shard_queue[first_shard_queue_index]; g_shard_queue[first_shard_queue_index] = g_shard_queue[first_shard_queue_index + 1]; @@ -305,33 +308,33 @@ static void swap_adjacent_shards_in_queue(uint32_t first_shard_queue_index) { first_shard_queue_index + 1; } -static void note_deadline_change(timer_shard *shard) { +static void note_deadline_change(timer_shard* shard) { while (shard->shard_queue_index > 0 && shard->min_deadline < g_shard_queue[shard->shard_queue_index - 1]->min_deadline) { swap_adjacent_shards_in_queue(shard->shard_queue_index - 1); } - while (shard->shard_queue_index < NUM_SHARDS - 1 && + while (shard->shard_queue_index < g_num_shards - 1 && shard->min_deadline > g_shard_queue[shard->shard_queue_index + 1]->min_deadline) { swap_adjacent_shards_in_queue(shard->shard_queue_index); } } -void grpc_timer_init_unset(grpc_timer *timer) { timer->pending = false; } +void grpc_timer_init_unset(grpc_timer* timer) { timer->pending = false; } -void grpc_timer_init(grpc_exec_ctx *exec_ctx, grpc_timer *timer, - grpc_millis deadline, grpc_closure *closure) { +void grpc_timer_init(grpc_exec_ctx* exec_ctx, grpc_timer* timer, + grpc_millis deadline, grpc_closure* closure) { int is_first_timer = 0; - timer_shard *shard = &g_shards[GPR_HASH_POINTER(timer, NUM_SHARDS)]; + timer_shard* shard = &g_shards[GPR_HASH_POINTER(timer, g_num_shards)]; timer->closure = closure; timer->deadline = deadline; #ifndef NDEBUG - timer->hash_table_next = NULL; + timer->hash_table_next = nullptr; #endif - if (GRPC_TRACER_ON(grpc_timer_trace)) { + if (grpc_timer_trace.enabled()) { gpr_log(GPR_DEBUG, "TIMER %p: SET %" PRIdPTR " now %" PRIdPTR " call %p[%p]", timer, deadline, grpc_exec_ctx_now(exec_ctx), closure, closure->cb); @@ -367,9 +370,10 @@ void grpc_timer_init(grpc_exec_ctx *exec_ctx, grpc_timer *timer, timer->heap_index = INVALID_HEAP_INDEX; list_join(&shard->list, timer); } - if (GRPC_TRACER_ON(grpc_timer_trace)) { - gpr_log(GPR_DEBUG, " .. add to shard %d with queue_deadline_cap=%" PRIdPTR - " => is_first_timer=%s", + if (grpc_timer_trace.enabled()) { + gpr_log(GPR_DEBUG, + " .. add to shard %d with queue_deadline_cap=%" PRIdPTR + " => is_first_timer=%s", (int)(shard - g_shards), shard->queue_deadline_cap, is_first_timer ? "true" : "false"); } @@ -388,7 +392,7 @@ void grpc_timer_init(grpc_exec_ctx *exec_ctx, grpc_timer *timer, grpc_timer_check. */ if (is_first_timer) { gpr_mu_lock(&g_shared_mutables.mu); - if (GRPC_TRACER_ON(grpc_timer_trace)) { + if (grpc_timer_trace.enabled()) { gpr_log(GPR_DEBUG, " .. old shard min_deadline=%" PRIdPTR, shard->min_deadline); } @@ -410,15 +414,15 @@ void grpc_timer_consume_kick(void) { gpr_tls_set(&g_last_seen_min_timer, 0); } -void grpc_timer_cancel(grpc_exec_ctx *exec_ctx, grpc_timer *timer) { +void grpc_timer_cancel(grpc_exec_ctx* exec_ctx, grpc_timer* timer) { if (!g_shared_mutables.initialized) { /* must have already been cancelled, also the shard mutex is invalid */ return; } - timer_shard *shard = &g_shards[GPR_HASH_POINTER(timer, NUM_SHARDS)]; + timer_shard* shard = &g_shards[GPR_HASH_POINTER(timer, g_num_shards)]; gpr_mu_lock(&shard->mu); - if (GRPC_TRACER_ON(grpc_timer_trace)) { + if (grpc_timer_trace.enabled()) { gpr_log(GPR_DEBUG, "TIMER %p: CANCEL pending=%s", timer, timer->pending ? "true" : "false"); } @@ -444,7 +448,7 @@ void grpc_timer_cancel(grpc_exec_ctx *exec_ctx, grpc_timer *timer) { 'queue_deadline_cap') into into shard->heap. Returns 'true' if shard->heap has atleast ONE element REQUIRES: shard->mu locked */ -static int refill_heap(timer_shard *shard, gpr_atm now) { +static int refill_heap(timer_shard* shard, gpr_atm now) { /* Compute the new queue window width and bound by the limits: */ double computed_deadline_delta = grpc_time_averaged_stats_update_average(&shard->stats) * @@ -459,7 +463,7 @@ static int refill_heap(timer_shard *shard, gpr_atm now) { saturating_add(GPR_MAX(now, shard->queue_deadline_cap), (gpr_atm)(deadline_delta * 1000.0)); - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, " .. shard[%d]->queue_deadline_cap --> %" PRIdPTR, (int)(shard - g_shards), shard->queue_deadline_cap); } @@ -467,7 +471,7 @@ static int refill_heap(timer_shard *shard, gpr_atm now) { next = timer->next; if (timer->deadline < shard->queue_deadline_cap) { - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, " .. add timer with deadline %" PRIdPTR " to heap", timer->deadline); } @@ -481,26 +485,26 @@ static int refill_heap(timer_shard *shard, gpr_atm now) { /* This pops the next non-cancelled timer with deadline <= now from the queue, or returns NULL if there isn't one. REQUIRES: shard->mu locked */ -static grpc_timer *pop_one(timer_shard *shard, gpr_atm now) { - grpc_timer *timer; +static grpc_timer* pop_one(timer_shard* shard, gpr_atm now) { + grpc_timer* timer; for (;;) { - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, " .. shard[%d]: heap_empty=%s", (int)(shard - g_shards), grpc_timer_heap_is_empty(&shard->heap) ? "true" : "false"); } if (grpc_timer_heap_is_empty(&shard->heap)) { - if (now < shard->queue_deadline_cap) return NULL; - if (!refill_heap(shard, now)) return NULL; + if (now < shard->queue_deadline_cap) return nullptr; + if (!refill_heap(shard, now)) return nullptr; } timer = grpc_timer_heap_top(&shard->heap); - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, " .. check top timer deadline=%" PRIdPTR " now=%" PRIdPTR, timer->deadline, now); } - if (timer->deadline > now) return NULL; - if (GRPC_TRACER_ON(grpc_timer_trace)) { + if (timer->deadline > now) return nullptr; + if (grpc_timer_trace.enabled()) { gpr_log(GPR_DEBUG, "TIMER %p: FIRE %" PRIdPTR "ms late via %s scheduler", timer, now - timer->deadline, timer->closure->scheduler->vtable->name); @@ -512,11 +516,11 @@ static grpc_timer *pop_one(timer_shard *shard, gpr_atm now) { } /* REQUIRES: shard->mu unlocked */ -static size_t pop_timers(grpc_exec_ctx *exec_ctx, timer_shard *shard, - gpr_atm now, gpr_atm *new_min_deadline, - grpc_error *error) { +static size_t pop_timers(grpc_exec_ctx* exec_ctx, timer_shard* shard, + gpr_atm now, gpr_atm* new_min_deadline, + grpc_error* error) { size_t n = 0; - grpc_timer *timer; + grpc_timer* timer; gpr_mu_lock(&shard->mu); while ((timer = pop_one(shard, now))) { REMOVE_FROM_HASH_TABLE(timer); @@ -525,23 +529,23 @@ static size_t pop_timers(grpc_exec_ctx *exec_ctx, timer_shard *shard, } *new_min_deadline = compute_min_deadline(shard); gpr_mu_unlock(&shard->mu); - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, " .. shard[%d] popped %" PRIdPTR, (int)(shard - g_shards), n); } return n; } -static grpc_timer_check_result run_some_expired_timers(grpc_exec_ctx *exec_ctx, +static grpc_timer_check_result run_some_expired_timers(grpc_exec_ctx* exec_ctx, gpr_atm now, - gpr_atm *next, - grpc_error *error) { + gpr_atm* next, + grpc_error* error) { grpc_timer_check_result result = GRPC_TIMERS_NOT_CHECKED; gpr_atm min_timer = gpr_atm_no_barrier_load(&g_shared_mutables.min_timer); gpr_tls_set(&g_last_seen_min_timer, min_timer); if (now < min_timer) { - if (next != NULL) *next = GPR_MIN(*next, min_timer); + if (next != nullptr) *next = GPR_MIN(*next, min_timer); return GRPC_TIMERS_CHECKED_AND_EMPTY; } @@ -549,7 +553,7 @@ static grpc_timer_check_result run_some_expired_timers(grpc_exec_ctx *exec_ctx, gpr_mu_lock(&g_shared_mutables.mu); result = GRPC_TIMERS_CHECKED_AND_EMPTY; - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, " .. shard[%d]->min_deadline = %" PRIdPTR, (int)(g_shard_queue[0] - g_shards), g_shard_queue[0]->min_deadline); @@ -567,7 +571,7 @@ static grpc_timer_check_result run_some_expired_timers(grpc_exec_ctx *exec_ctx, result = GRPC_TIMERS_FIRED; } - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, " .. result --> %d" ", shard[%d]->min_deadline %" PRIdPTR " --> %" PRIdPTR @@ -600,8 +604,8 @@ static grpc_timer_check_result run_some_expired_timers(grpc_exec_ctx *exec_ctx, return result; } -grpc_timer_check_result grpc_timer_check(grpc_exec_ctx *exec_ctx, - grpc_millis *next) { +grpc_timer_check_result grpc_timer_check(grpc_exec_ctx* exec_ctx, + grpc_millis* next) { // prelude grpc_millis now = grpc_exec_ctx_now(exec_ctx); @@ -609,10 +613,10 @@ grpc_timer_check_result grpc_timer_check(grpc_exec_ctx *exec_ctx, mutable cacheline in the common case */ grpc_millis min_timer = gpr_tls_get(&g_last_seen_min_timer); if (now < min_timer) { - if (next != NULL) { + if (next != nullptr) { *next = GPR_MIN(*next, min_timer); } - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, "TIMER CHECK SKIP: now=%" PRIdPTR " min_timer=%" PRIdPTR, now, min_timer); @@ -620,21 +624,22 @@ grpc_timer_check_result grpc_timer_check(grpc_exec_ctx *exec_ctx, return GRPC_TIMERS_CHECKED_AND_EMPTY; } - grpc_error *shutdown_error = + grpc_error* shutdown_error = now != GRPC_MILLIS_INF_FUTURE ? GRPC_ERROR_NONE : GRPC_ERROR_CREATE_FROM_STATIC_STRING("Shutting down timer system"); // tracing - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { - char *next_str; - if (next == NULL) { + if (grpc_timer_check_trace.enabled()) { + char* next_str; + if (next == nullptr) { next_str = gpr_strdup("NULL"); } else { gpr_asprintf(&next_str, "%" PRIdPTR, *next); } - gpr_log(GPR_DEBUG, "TIMER CHECK BEGIN: now=%" PRIdPTR - " next=%s tls_min=%" PRIdPTR " glob_min=%" PRIdPTR, + gpr_log(GPR_DEBUG, + "TIMER CHECK BEGIN: now=%" PRIdPTR " next=%s tls_min=%" PRIdPTR + " glob_min=%" PRIdPTR, now, next_str, gpr_tls_get(&g_last_seen_min_timer), gpr_atm_no_barrier_load(&g_shared_mutables.min_timer)); gpr_free(next_str); @@ -643,9 +648,9 @@ grpc_timer_check_result grpc_timer_check(grpc_exec_ctx *exec_ctx, grpc_timer_check_result r = run_some_expired_timers(exec_ctx, now, next, shutdown_error); // tracing - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { - char *next_str; - if (next == NULL) { + if (grpc_timer_check_trace.enabled()) { + char* next_str; + if (next == nullptr) { next_str = gpr_strdup("NULL"); } else { gpr_asprintf(&next_str, "%" PRIdPTR, *next); diff --git a/src/core/lib/iomgr/timer_generic.h b/src/core/lib/iomgr/timer_generic.h index f0597f6ea0e..190381e904a 100644 --- a/src/core/lib/iomgr/timer_generic.h +++ b/src/core/lib/iomgr/timer_generic.h @@ -26,11 +26,11 @@ struct grpc_timer { gpr_atm deadline; uint32_t heap_index; /* INVALID_HEAP_INDEX if not in heap */ bool pending; - struct grpc_timer *next; - struct grpc_timer *prev; - grpc_closure *closure; + struct grpc_timer* next; + struct grpc_timer* prev; + grpc_closure* closure; #ifndef NDEBUG - struct grpc_timer *hash_table_next; + struct grpc_timer* hash_table_next; #endif }; diff --git a/src/core/lib/iomgr/timer_heap.cc b/src/core/lib/iomgr/timer_heap.cc index 2648d5da5dc..b350452c63f 100644 --- a/src/core/lib/iomgr/timer_heap.cc +++ b/src/core/lib/iomgr/timer_heap.cc @@ -32,7 +32,7 @@ position. This functor is called each time immediately after modifying a value in the underlying container, with the offset of the modified element as its argument. */ -static void adjust_upwards(grpc_timer **first, uint32_t i, grpc_timer *t) { +static void adjust_upwards(grpc_timer** first, uint32_t i, grpc_timer* t) { while (i > 0) { uint32_t parent = (uint32_t)(((int)i - 1) / 2); if (first[parent]->deadline <= t->deadline) break; @@ -47,17 +47,16 @@ static void adjust_upwards(grpc_timer **first, uint32_t i, grpc_timer *t) { /* Adjusts a heap so as to move a hole at position i farther away from the root, until a suitable position is found for element t. Then, copies t into that position. */ -static void adjust_downwards(grpc_timer **first, uint32_t i, uint32_t length, - grpc_timer *t) { +static void adjust_downwards(grpc_timer** first, uint32_t i, uint32_t length, + grpc_timer* t) { for (;;) { uint32_t left_child = 1u + 2u * i; if (left_child >= length) break; uint32_t right_child = left_child + 1; - uint32_t next_i = - right_child < length && - first[left_child]->deadline > first[right_child]->deadline - ? right_child - : left_child; + uint32_t next_i = right_child < length && first[left_child]->deadline > + first[right_child]->deadline + ? right_child + : left_child; if (t->deadline <= first[next_i]->deadline) break; first[i] = first[next_i]; first[i]->heap_index = i; @@ -70,16 +69,16 @@ static void adjust_downwards(grpc_timer **first, uint32_t i, uint32_t length, #define SHRINK_MIN_ELEMS 8 #define SHRINK_FULLNESS_FACTOR 2 -static void maybe_shrink(grpc_timer_heap *heap) { +static void maybe_shrink(grpc_timer_heap* heap) { if (heap->timer_count >= 8 && heap->timer_count <= heap->timer_capacity / SHRINK_FULLNESS_FACTOR / 2) { heap->timer_capacity = heap->timer_count * SHRINK_FULLNESS_FACTOR; - heap->timers = (grpc_timer **)gpr_realloc( - heap->timers, heap->timer_capacity * sizeof(grpc_timer *)); + heap->timers = (grpc_timer**)gpr_realloc( + heap->timers, heap->timer_capacity * sizeof(grpc_timer*)); } } -static void note_changed_priority(grpc_timer_heap *heap, grpc_timer *timer) { +static void note_changed_priority(grpc_timer_heap* heap, grpc_timer* timer) { uint32_t i = timer->heap_index; uint32_t parent = (uint32_t)(((int)i - 1) / 2); if (heap->timers[parent]->deadline > timer->deadline) { @@ -89,18 +88,18 @@ static void note_changed_priority(grpc_timer_heap *heap, grpc_timer *timer) { } } -void grpc_timer_heap_init(grpc_timer_heap *heap) { +void grpc_timer_heap_init(grpc_timer_heap* heap) { memset(heap, 0, sizeof(*heap)); } -void grpc_timer_heap_destroy(grpc_timer_heap *heap) { gpr_free(heap->timers); } +void grpc_timer_heap_destroy(grpc_timer_heap* heap) { gpr_free(heap->timers); } -int grpc_timer_heap_add(grpc_timer_heap *heap, grpc_timer *timer) { +int grpc_timer_heap_add(grpc_timer_heap* heap, grpc_timer* timer) { if (heap->timer_count == heap->timer_capacity) { heap->timer_capacity = GPR_MAX(heap->timer_capacity + 1, heap->timer_capacity * 3 / 2); - heap->timers = (grpc_timer **)gpr_realloc( - heap->timers, heap->timer_capacity * sizeof(grpc_timer *)); + heap->timers = (grpc_timer**)gpr_realloc( + heap->timers, heap->timer_capacity * sizeof(grpc_timer*)); } timer->heap_index = heap->timer_count; adjust_upwards(heap->timers, heap->timer_count, timer); @@ -108,7 +107,7 @@ int grpc_timer_heap_add(grpc_timer_heap *heap, grpc_timer *timer) { return timer->heap_index == 0; } -void grpc_timer_heap_remove(grpc_timer_heap *heap, grpc_timer *timer) { +void grpc_timer_heap_remove(grpc_timer_heap* heap, grpc_timer* timer) { uint32_t i = timer->heap_index; if (i == heap->timer_count - 1) { heap->timer_count--; @@ -122,15 +121,15 @@ void grpc_timer_heap_remove(grpc_timer_heap *heap, grpc_timer *timer) { note_changed_priority(heap, heap->timers[i]); } -int grpc_timer_heap_is_empty(grpc_timer_heap *heap) { +int grpc_timer_heap_is_empty(grpc_timer_heap* heap) { return heap->timer_count == 0; } -grpc_timer *grpc_timer_heap_top(grpc_timer_heap *heap) { +grpc_timer* grpc_timer_heap_top(grpc_timer_heap* heap) { return heap->timers[0]; } -void grpc_timer_heap_pop(grpc_timer_heap *heap) { +void grpc_timer_heap_pop(grpc_timer_heap* heap) { grpc_timer_heap_remove(heap, grpc_timer_heap_top(heap)); } diff --git a/src/core/lib/iomgr/timer_heap.h b/src/core/lib/iomgr/timer_heap.h index 228d038ab38..436eef55a6a 100644 --- a/src/core/lib/iomgr/timer_heap.h +++ b/src/core/lib/iomgr/timer_heap.h @@ -21,30 +21,22 @@ #include "src/core/lib/iomgr/timer.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct { - grpc_timer **timers; + grpc_timer** timers; uint32_t timer_count; uint32_t timer_capacity; } grpc_timer_heap; /* return 1 if the new timer is the first timer in the heap */ -int grpc_timer_heap_add(grpc_timer_heap *heap, grpc_timer *timer); - -void grpc_timer_heap_init(grpc_timer_heap *heap); -void grpc_timer_heap_destroy(grpc_timer_heap *heap); +int grpc_timer_heap_add(grpc_timer_heap* heap, grpc_timer* timer); -void grpc_timer_heap_remove(grpc_timer_heap *heap, grpc_timer *timer); -grpc_timer *grpc_timer_heap_top(grpc_timer_heap *heap); -void grpc_timer_heap_pop(grpc_timer_heap *heap); +void grpc_timer_heap_init(grpc_timer_heap* heap); +void grpc_timer_heap_destroy(grpc_timer_heap* heap); -int grpc_timer_heap_is_empty(grpc_timer_heap *heap); +void grpc_timer_heap_remove(grpc_timer_heap* heap, grpc_timer* timer); +grpc_timer* grpc_timer_heap_top(grpc_timer_heap* heap); +void grpc_timer_heap_pop(grpc_timer_heap* heap); -#ifdef __cplusplus -} -#endif +int grpc_timer_heap_is_empty(grpc_timer_heap* heap); #endif /* GRPC_CORE_LIB_IOMGR_TIMER_HEAP_H */ diff --git a/src/core/lib/iomgr/timer_manager.cc b/src/core/lib/iomgr/timer_manager.cc index 1248f82189a..dac74aea24e 100644 --- a/src/core/lib/iomgr/timer_manager.cc +++ b/src/core/lib/iomgr/timer_manager.cc @@ -30,10 +30,10 @@ typedef struct completed_thread { gpr_thd_id t; - struct completed_thread *next; + struct completed_thread* next; } completed_thread; -extern "C" grpc_tracer_flag grpc_timer_check_trace; +extern grpc_core::TraceFlag grpc_timer_check_trace; // global mutex static gpr_mu g_mu; @@ -48,7 +48,7 @@ static int g_thread_count; // number of threads sitting around waiting static int g_waiter_count; // linked list of threads that have completed (and need joining) -static completed_thread *g_completed_threads; +static completed_thread* g_completed_threads; // was the manager kicked by the timer system static bool g_kicked; // is there a thread waiting until the next timer should fire? @@ -59,16 +59,16 @@ static grpc_millis g_timed_waiter_deadline; // generation counter to track which thread is waiting for the next timer static uint64_t g_timed_waiter_generation; -static void timer_thread(void *completed_thread_ptr); +static void timer_thread(void* completed_thread_ptr); static void gc_completed_threads(void) { - if (g_completed_threads != NULL) { - completed_thread *to_gc = g_completed_threads; - g_completed_threads = NULL; + if (g_completed_threads != nullptr) { + completed_thread* to_gc = g_completed_threads; + g_completed_threads = nullptr; gpr_mu_unlock(&g_mu); - while (to_gc != NULL) { + while (to_gc != nullptr) { gpr_thd_join(to_gc->t); - completed_thread *next = to_gc->next; + completed_thread* next = to_gc->next; gpr_free(to_gc); to_gc = next; } @@ -81,12 +81,12 @@ static void start_timer_thread_and_unlock(void) { ++g_waiter_count; ++g_thread_count; gpr_mu_unlock(&g_mu); - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, "Spawn timer thread"); } gpr_thd_options opt = gpr_thd_options_default(); gpr_thd_options_set_joinable(&opt); - completed_thread *ct = (completed_thread *)gpr_malloc(sizeof(*ct)); + completed_thread* ct = (completed_thread*)gpr_malloc(sizeof(*ct)); // The call to gpr_thd_new() has to be under the same lock used by // gc_completed_threads(), particularly due to ct->t, which is written here // (internally by gpr_thd_new) and read there. Otherwise it's possible for ct @@ -104,7 +104,7 @@ void grpc_timer_manager_tick() { grpc_exec_ctx_finish(&exec_ctx); } -static void run_some_timers(grpc_exec_ctx *exec_ctx) { +static void run_some_timers(grpc_exec_ctx* exec_ctx) { // if there's something to execute... gpr_mu_lock(&g_mu); // remove a waiter from the pool, and start another thread if necessary @@ -115,7 +115,7 @@ static void run_some_timers(grpc_exec_ctx *exec_ctx) { // if there's no thread waiting with a timeout, kick an existing // waiter so that the next deadline is not missed if (!g_has_timed_waiter) { - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, "kick untimed waiter"); } gpr_cv_signal(&g_cv_wait); @@ -123,7 +123,7 @@ static void run_some_timers(grpc_exec_ctx *exec_ctx) { gpr_mu_unlock(&g_mu); } // without our lock, flush the exec_ctx - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, "flush exec_ctx"); } grpc_exec_ctx_flush(exec_ctx); @@ -138,7 +138,7 @@ static void run_some_timers(grpc_exec_ctx *exec_ctx) { // wait until 'next' (or forever if there is already a timed waiter in the pool) // returns true if the thread should continue executing (false if it should // shutdown) -static bool wait_until(grpc_exec_ctx *exec_ctx, grpc_millis next) { +static bool wait_until(grpc_exec_ctx* exec_ctx, grpc_millis next) { gpr_mu_lock(&g_mu); // if we're not threaded anymore, leave if (!g_threaded) { @@ -178,7 +178,7 @@ static bool wait_until(grpc_exec_ctx *exec_ctx, grpc_millis next) { g_has_timed_waiter = true; g_timed_waiter_deadline = next; - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { grpc_millis wait_time = next - grpc_exec_ctx_now(exec_ctx); gpr_log(GPR_DEBUG, "sleep for a %" PRIdPTR " milliseconds", wait_time); @@ -188,15 +188,14 @@ static bool wait_until(grpc_exec_ctx *exec_ctx, grpc_millis next) { } } - if (GRPC_TRACER_ON(grpc_timer_check_trace) && - next == GRPC_MILLIS_INF_FUTURE) { + if (grpc_timer_check_trace.enabled() && next == GRPC_MILLIS_INF_FUTURE) { gpr_log(GPR_DEBUG, "sleep until kicked"); } gpr_cv_wait(&g_cv_wait, &g_mu, grpc_millis_to_timespec(next, GPR_CLOCK_REALTIME)); - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, "wait ended: was_timed:%d kicked:%d", my_timed_waiter_generation == g_timed_waiter_generation, g_kicked); @@ -221,10 +220,11 @@ static bool wait_until(grpc_exec_ctx *exec_ctx, grpc_millis next) { return true; } -static void timer_main_loop(grpc_exec_ctx *exec_ctx) { +static void timer_main_loop(grpc_exec_ctx* exec_ctx) { for (;;) { grpc_millis next = GRPC_MILLIS_INF_FUTURE; grpc_exec_ctx_invalidate_now(exec_ctx); + // check timer state, updates next to the next time to run a check switch (grpc_timer_check(exec_ctx, &next)) { case GRPC_TIMERS_FIRED: @@ -240,7 +240,7 @@ static void timer_main_loop(grpc_exec_ctx *exec_ctx) { Consequently, we can just sleep forever here and be happy at some saved wakeup cycles. */ - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, "timers not checked: expect another thread to"); } next = GRPC_MILLIS_INF_FUTURE; @@ -254,7 +254,7 @@ static void timer_main_loop(grpc_exec_ctx *exec_ctx) { } } -static void timer_thread_cleanup(completed_thread *ct) { +static void timer_thread_cleanup(completed_thread* ct) { gpr_mu_lock(&g_mu); // terminate the thread: drop the waiter count, thread count, and let whomever // stopped the threading stuff know that we're done @@ -266,19 +266,19 @@ static void timer_thread_cleanup(completed_thread *ct) { ct->next = g_completed_threads; g_completed_threads = ct; gpr_mu_unlock(&g_mu); - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, "End timer thread"); } } -static void timer_thread(void *completed_thread_ptr) { +static void timer_thread(void* completed_thread_ptr) { // this threads exec_ctx: we try to run things through to completion here // since it's easy to spin up new threads grpc_exec_ctx exec_ctx = - GRPC_EXEC_CTX_INITIALIZER(0, grpc_never_ready_to_finish, NULL); + GRPC_EXEC_CTX_INITIALIZER(0, grpc_never_ready_to_finish, nullptr); timer_main_loop(&exec_ctx); grpc_exec_ctx_finish(&exec_ctx); - timer_thread_cleanup((completed_thread *)completed_thread_ptr); + timer_thread_cleanup((completed_thread*)completed_thread_ptr); } static void start_threads(void) { @@ -299,7 +299,7 @@ void grpc_timer_manager_init(void) { g_threaded = false; g_thread_count = 0; g_waiter_count = 0; - g_completed_threads = NULL; + g_completed_threads = nullptr; g_has_timed_waiter = false; g_timed_waiter_deadline = GRPC_MILLIS_INF_FUTURE; @@ -309,18 +309,18 @@ void grpc_timer_manager_init(void) { static void stop_threads(void) { gpr_mu_lock(&g_mu); - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, "stop timer threads: threaded=%d", g_threaded); } if (g_threaded) { g_threaded = false; gpr_cv_broadcast(&g_cv_wait); - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, "num timer threads: %d", g_thread_count); } while (g_thread_count > 0) { gpr_cv_wait(&g_cv_shutdown, &g_mu, gpr_inf_future(GPR_CLOCK_REALTIME)); - if (GRPC_TRACER_ON(grpc_timer_check_trace)) { + if (grpc_timer_check_trace.enabled()) { gpr_log(GPR_DEBUG, "num timer threads: %d", g_thread_count); } gc_completed_threads(); diff --git a/src/core/lib/iomgr/timer_manager.h b/src/core/lib/iomgr/timer_manager.h index 72960d6ffc0..0ba502928a5 100644 --- a/src/core/lib/iomgr/timer_manager.h +++ b/src/core/lib/iomgr/timer_manager.h @@ -21,10 +21,6 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /* Timer Manager tries to keep one thread waiting for the next timeout at all times */ @@ -38,8 +34,4 @@ void grpc_timer_manager_set_threading(bool enabled); * disabled */ void grpc_timer_manager_tick(void); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_TIMER_MANAGER_H */ diff --git a/src/core/lib/iomgr/timer_uv.cc b/src/core/lib/iomgr/timer_uv.cc index ccbbe357ae9..fac2026fa93 100644 --- a/src/core/lib/iomgr/timer_uv.cc +++ b/src/core/lib/iomgr/timer_uv.cc @@ -29,22 +29,19 @@ #include -extern "C" { -grpc_tracer_flag grpc_timer_trace = GRPC_TRACER_INITIALIZER(false, "timer"); -grpc_tracer_flag grpc_timer_check_trace = - GRPC_TRACER_INITIALIZER(false, "timer_check"); -} +grpc_core::TraceFlag grpc_timer_trace(false, "timer"); +grpc_core::TraceFlag grpc_timer_check_trace(false, "timer_check"); -static void timer_close_callback(uv_handle_t *handle) { gpr_free(handle); } +static void timer_close_callback(uv_handle_t* handle) { gpr_free(handle); } -static void stop_uv_timer(uv_timer_t *handle) { +static void stop_uv_timer(uv_timer_t* handle) { uv_timer_stop(handle); - uv_unref((uv_handle_t *)handle); - uv_close((uv_handle_t *)handle, timer_close_callback); + uv_unref((uv_handle_t*)handle); + uv_close((uv_handle_t*)handle, timer_close_callback); } -void run_expired_timer(uv_timer_t *handle) { - grpc_timer *timer = (grpc_timer *)handle->data; +void run_expired_timer(uv_timer_t* handle) { + grpc_timer* timer = (grpc_timer*)handle->data; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GRPC_UV_ASSERT_SAME_THREAD(); GPR_ASSERT(timer->pending); @@ -54,10 +51,10 @@ void run_expired_timer(uv_timer_t *handle) { grpc_exec_ctx_finish(&exec_ctx); } -void grpc_timer_init(grpc_exec_ctx *exec_ctx, grpc_timer *timer, - grpc_millis deadline, grpc_closure *closure) { +void grpc_timer_init(grpc_exec_ctx* exec_ctx, grpc_timer* timer, + grpc_millis deadline, grpc_closure* closure) { uint64_t timeout; - uv_timer_t *uv_timer; + uv_timer_t* uv_timer; GRPC_UV_ASSERT_SAME_THREAD(); timer->closure = closure; if (deadline <= grpc_exec_ctx_now(exec_ctx)) { @@ -67,7 +64,7 @@ void grpc_timer_init(grpc_exec_ctx *exec_ctx, grpc_timer *timer, } timer->pending = 1; timeout = (uint64_t)(deadline - grpc_exec_ctx_now(exec_ctx)); - uv_timer = (uv_timer_t *)gpr_malloc(sizeof(uv_timer_t)); + uv_timer = (uv_timer_t*)gpr_malloc(sizeof(uv_timer_t)); uv_timer_init(uv_default_loop(), uv_timer); uv_timer->data = timer; timer->uv_timer = uv_timer; @@ -75,27 +72,27 @@ void grpc_timer_init(grpc_exec_ctx *exec_ctx, grpc_timer *timer, /* We assume that gRPC timers are only used alongside other active gRPC objects, and that there will therefore always be something else keeping the uv loop alive whenever there is a timer */ - uv_unref((uv_handle_t *)uv_timer); + uv_unref((uv_handle_t*)uv_timer); } -void grpc_timer_init_unset(grpc_timer *timer) { timer->pending = 0; } +void grpc_timer_init_unset(grpc_timer* timer) { timer->pending = 0; } -void grpc_timer_cancel(grpc_exec_ctx *exec_ctx, grpc_timer *timer) { +void grpc_timer_cancel(grpc_exec_ctx* exec_ctx, grpc_timer* timer) { GRPC_UV_ASSERT_SAME_THREAD(); if (timer->pending) { timer->pending = 0; GRPC_CLOSURE_SCHED(exec_ctx, timer->closure, GRPC_ERROR_CANCELLED); - stop_uv_timer((uv_timer_t *)timer->uv_timer); + stop_uv_timer((uv_timer_t*)timer->uv_timer); } } -grpc_timer_check_result grpc_timer_check(grpc_exec_ctx *exec_ctx, - grpc_millis *next) { +grpc_timer_check_result grpc_timer_check(grpc_exec_ctx* exec_ctx, + grpc_millis* next) { return GRPC_TIMERS_NOT_CHECKED; } -void grpc_timer_list_init(grpc_exec_ctx *exec_ctx) {} -void grpc_timer_list_shutdown(grpc_exec_ctx *exec_ctx) {} +void grpc_timer_list_init(grpc_exec_ctx* exec_ctx) {} +void grpc_timer_list_shutdown(grpc_exec_ctx* exec_ctx) {} void grpc_timer_consume_kick(void) {} diff --git a/src/core/lib/iomgr/timer_uv.h b/src/core/lib/iomgr/timer_uv.h index 8a4c17c8443..214aaa600ac 100644 --- a/src/core/lib/iomgr/timer_uv.h +++ b/src/core/lib/iomgr/timer_uv.h @@ -22,10 +22,10 @@ #include "src/core/lib/iomgr/exec_ctx.h" struct grpc_timer { - grpc_closure *closure; + grpc_closure* closure; /* This is actually a uv_timer_t*, but we want to keep platform-specific types out of headers */ - void *uv_timer; + void* uv_timer; int pending; }; diff --git a/src/core/lib/iomgr/udp_server.cc b/src/core/lib/iomgr/udp_server.cc index 00b2e68bb5e..7b7d6946b12 100644 --- a/src/core/lib/iomgr/udp_server.cc +++ b/src/core/lib/iomgr/udp_server.cc @@ -47,6 +47,7 @@ #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/iomgr/error.h" #include "src/core/lib/iomgr/ev_posix.h" +#include "src/core/lib/iomgr/executor.h" #include "src/core/lib/iomgr/resolve_address.h" #include "src/core/lib/iomgr/sockaddr.h" #include "src/core/lib/iomgr/sockaddr_utils.h" @@ -59,8 +60,8 @@ typedef struct grpc_udp_listener grpc_udp_listener; struct grpc_udp_listener { int fd; - grpc_fd *emfd; - grpc_udp_server *server; + grpc_fd* emfd; + grpc_udp_server* server; grpc_resolved_address addr; grpc_closure read_closure; grpc_closure write_closure; @@ -71,15 +72,23 @@ struct grpc_udp_listener { grpc_udp_server_read_cb read_cb; grpc_udp_server_write_cb write_cb; grpc_udp_server_orphan_cb orphan_cb; + // To be scheduled on another thread to actually read/write. + grpc_closure do_read_closure; + grpc_closure do_write_closure; + grpc_closure notify_on_write_closure; // True if orphan_cb is trigered. bool orphan_notified; + // True if grpc_fd_notify_on_write() is called after on_write() call. + bool notify_on_write_armed; + // True if fd has been shutdown. + bool already_shutdown; - struct grpc_udp_listener *next; + struct grpc_udp_listener* next; }; struct shutdown_fd_args { - grpc_fd *fd; - gpr_mu *server_mu; + grpc_udp_listener* sp; + gpr_mu* server_mu; }; /* the overall server */ @@ -87,7 +96,7 @@ struct grpc_udp_server { gpr_mu mu; /* factory to use for creating and binding sockets, or NULL */ - grpc_socket_factory *socket_factory; + grpc_socket_factory* socket_factory; /* active port count: how many ports are actually still listening */ size_t active_ports; @@ -98,34 +107,34 @@ struct grpc_udp_server { int shutdown; /* linked list of server ports */ - grpc_udp_listener *head; - grpc_udp_listener *tail; + grpc_udp_listener* head; + grpc_udp_listener* tail; unsigned nports; /* shutdown callback */ - grpc_closure *shutdown_complete; + grpc_closure* shutdown_complete; /* all pollsets interested in new connections */ - grpc_pollset **pollsets; + grpc_pollset** pollsets; /* number of pollsets in the pollsets array */ size_t pollset_count; /* opaque object to pass to callbacks */ - void *user_data; + void* user_data; }; -static grpc_socket_factory *get_socket_factory(const grpc_channel_args *args) { +static grpc_socket_factory* get_socket_factory(const grpc_channel_args* args) { if (args) { - const grpc_arg *arg = grpc_channel_args_find(args, GRPC_ARG_SOCKET_FACTORY); + const grpc_arg* arg = grpc_channel_args_find(args, GRPC_ARG_SOCKET_FACTORY); if (arg) { GPR_ASSERT(arg->type == GRPC_ARG_POINTER); - return (grpc_socket_factory *)arg->value.pointer.p; + return (grpc_socket_factory*)arg->value.pointer.p; } } - return NULL; + return nullptr; } -grpc_udp_server *grpc_udp_server_create(const grpc_channel_args *args) { - grpc_udp_server *s = (grpc_udp_server *)gpr_malloc(sizeof(grpc_udp_server)); +grpc_udp_server* grpc_udp_server_create(const grpc_channel_args* args) { + grpc_udp_server* s = (grpc_udp_server*)gpr_malloc(sizeof(grpc_udp_server)); gpr_mu_init(&s->mu); s->socket_factory = get_socket_factory(args); if (s->socket_factory) { @@ -134,35 +143,45 @@ grpc_udp_server *grpc_udp_server_create(const grpc_channel_args *args) { s->active_ports = 0; s->destroyed_ports = 0; s->shutdown = 0; - s->head = NULL; - s->tail = NULL; + s->head = nullptr; + s->tail = nullptr; s->nports = 0; return s; } -static void shutdown_fd(grpc_exec_ctx *exec_ctx, void *args, - grpc_error *error) { - struct shutdown_fd_args *shutdown_args = (struct shutdown_fd_args *)args; +static void shutdown_fd(grpc_exec_ctx* exec_ctx, void* args, + grpc_error* error) { + struct shutdown_fd_args* shutdown_args = (struct shutdown_fd_args*)args; + grpc_udp_listener* sp = shutdown_args->sp; + gpr_log(GPR_DEBUG, "shutdown fd %d", sp->fd); gpr_mu_lock(shutdown_args->server_mu); - grpc_fd_shutdown(exec_ctx, shutdown_args->fd, GRPC_ERROR_REF(error)); + grpc_fd_shutdown(exec_ctx, sp->emfd, GRPC_ERROR_REF(error)); + sp->already_shutdown = true; + if (!sp->notify_on_write_armed) { + // Re-arm write notification to notify listener with error. This is + // necessary to decrement active_ports. + sp->notify_on_write_armed = true; + grpc_fd_notify_on_write(exec_ctx, sp->emfd, &sp->write_closure); + } gpr_mu_unlock(shutdown_args->server_mu); gpr_free(shutdown_args); } -static void dummy_cb(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { +static void dummy_cb(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { // No-op. } -static void finish_shutdown(grpc_exec_ctx *exec_ctx, grpc_udp_server *s) { - if (s->shutdown_complete != NULL) { +static void finish_shutdown(grpc_exec_ctx* exec_ctx, grpc_udp_server* s) { + if (s->shutdown_complete != nullptr) { GRPC_CLOSURE_SCHED(exec_ctx, s->shutdown_complete, GRPC_ERROR_NONE); } gpr_mu_destroy(&s->mu); + gpr_log(GPR_DEBUG, "Destroy all listeners."); while (s->head) { - grpc_udp_listener *sp = s->head; + grpc_udp_listener* sp = s->head; s->head = sp->next; gpr_free(sp); } @@ -174,9 +193,9 @@ static void finish_shutdown(grpc_exec_ctx *exec_ctx, grpc_udp_server *s) { gpr_free(s); } -static void destroyed_port(grpc_exec_ctx *exec_ctx, void *server, - grpc_error *error) { - grpc_udp_server *s = (grpc_udp_server *)server; +static void destroyed_port(grpc_exec_ctx* exec_ctx, void* server, + grpc_error* error) { + grpc_udp_server* s = (grpc_udp_server*)server; gpr_mu_lock(&s->mu); s->destroyed_ports++; if (s->destroyed_ports == s->nports) { @@ -190,14 +209,14 @@ static void destroyed_port(grpc_exec_ctx *exec_ctx, void *server, /* called when all listening endpoints have been shutdown, so no further events will be received on them - at this point it's safe to destroy things */ -static void deactivated_all_ports(grpc_exec_ctx *exec_ctx, grpc_udp_server *s) { +static void deactivated_all_ports(grpc_exec_ctx* exec_ctx, grpc_udp_server* s) { /* delete ALL the things */ gpr_mu_lock(&s->mu); GPR_ASSERT(s->shutdown); if (s->head) { - grpc_udp_listener *sp; + grpc_udp_listener* sp; for (sp = s->head; sp; sp = sp->next) { grpc_unlink_if_unix_domain_socket(&sp->addr); @@ -207,13 +226,14 @@ static void deactivated_all_ports(grpc_exec_ctx *exec_ctx, grpc_udp_server *s) { /* Call the orphan_cb to signal that the FD is about to be closed and * should no longer be used. Because at this point, all listening ports * have been shutdown already, no need to shutdown again.*/ - GRPC_CLOSURE_INIT(&sp->orphan_fd_closure, dummy_cb, sp->emfd, + GRPC_CLOSURE_INIT(&sp->orphan_fd_closure, dummy_cb, sp, grpc_schedule_on_exec_ctx); GPR_ASSERT(sp->orphan_cb); + gpr_log(GPR_DEBUG, "Orphan fd %d", sp->fd); sp->orphan_cb(exec_ctx, sp->emfd, &sp->orphan_fd_closure, sp->server->user_data); } - grpc_fd_orphan(exec_ctx, sp->emfd, &sp->destroyed_closure, NULL, + grpc_fd_orphan(exec_ctx, sp->emfd, &sp->destroyed_closure, nullptr, false /* already_closed */, "udp_listener_shutdown"); } gpr_mu_unlock(&s->mu); @@ -223,9 +243,9 @@ static void deactivated_all_ports(grpc_exec_ctx *exec_ctx, grpc_udp_server *s) { } } -void grpc_udp_server_destroy(grpc_exec_ctx *exec_ctx, grpc_udp_server *s, - grpc_closure *on_done) { - grpc_udp_listener *sp; +void grpc_udp_server_destroy(grpc_exec_ctx* exec_ctx, grpc_udp_server* s, + grpc_closure* on_done) { + grpc_udp_listener* sp; gpr_mu_lock(&s->mu); GPR_ASSERT(!s->shutdown); @@ -233,13 +253,14 @@ void grpc_udp_server_destroy(grpc_exec_ctx *exec_ctx, grpc_udp_server *s, s->shutdown_complete = on_done; + gpr_log(GPR_DEBUG, "start to destroy udp_server"); /* shutdown all fd's */ if (s->active_ports) { for (sp = s->head; sp; sp = sp->next) { GPR_ASSERT(sp->orphan_cb); - struct shutdown_fd_args *args = - (struct shutdown_fd_args *)gpr_malloc(sizeof(*args)); - args->fd = sp->emfd; + struct shutdown_fd_args* args = + (struct shutdown_fd_args*)gpr_malloc(sizeof(*args)); + args->sp = sp; args->server_mu = &s->mu; GRPC_CLOSURE_INIT(&sp->orphan_fd_closure, shutdown_fd, args, grpc_schedule_on_exec_ctx); @@ -254,19 +275,18 @@ void grpc_udp_server_destroy(grpc_exec_ctx *exec_ctx, grpc_udp_server *s, } } -static int bind_socket(grpc_socket_factory *socket_factory, int sockfd, - const grpc_resolved_address *addr) { - return (socket_factory != NULL) +static int bind_socket(grpc_socket_factory* socket_factory, int sockfd, + const grpc_resolved_address* addr) { + return (socket_factory != nullptr) ? grpc_socket_factory_bind(socket_factory, sockfd, addr) - : bind(sockfd, (struct sockaddr *)addr->addr, - (socklen_t)addr->len); + : bind(sockfd, (struct sockaddr*)addr->addr, (socklen_t)addr->len); } /* Prepare a recently-created socket for listening. */ -static int prepare_socket(grpc_socket_factory *socket_factory, int fd, - const grpc_resolved_address *addr) { +static int prepare_socket(grpc_socket_factory* socket_factory, int fd, + const grpc_resolved_address* addr) { grpc_resolved_address sockname_temp; - struct sockaddr *addr_ptr = (struct sockaddr *)addr->addr; + struct sockaddr* addr_ptr = (struct sockaddr*)addr->addr; /* Set send/receive socket buffers to 1 MB */ int buffer_size_bytes = 1024 * 1024; @@ -295,7 +315,7 @@ static int prepare_socket(grpc_socket_factory *socket_factory, int fd, GPR_ASSERT(addr->len < ~(socklen_t)0); if (bind_socket(socket_factory, fd, addr) < 0) { - char *addr_str; + char* addr_str; grpc_sockaddr_to_string(&addr_str, addr, 0); gpr_log(GPR_ERROR, "bind addr=%s: %s", addr_str, strerror(errno)); gpr_free(addr_str); @@ -304,8 +324,8 @@ static int prepare_socket(grpc_socket_factory *socket_factory, int fd, sockname_temp.len = sizeof(struct sockaddr_storage); - if (getsockname(fd, (struct sockaddr *)sockname_temp.addr, - (socklen_t *)&sockname_temp.len) < 0) { + if (getsockname(fd, (struct sockaddr*)sockname_temp.addr, + (socklen_t*)&sockname_temp.len) < 0) { goto error; } @@ -330,9 +350,31 @@ error: return -1; } +static void do_read(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { + grpc_udp_listener* sp = reinterpret_cast(arg); + GPR_ASSERT(sp->read_cb && error == GRPC_ERROR_NONE); + /* TODO: the reason we hold server->mu here is merely to prevent fd + * shutdown while we are reading. However, it blocks do_write(). Switch to + * read lock if available. */ + gpr_mu_lock(&sp->server->mu); + /* Tell the registered callback that data is available to read. */ + if (!sp->already_shutdown && + sp->read_cb(exec_ctx, sp->emfd, sp->server->user_data)) { + /* There maybe more packets to read. Schedule read_more_cb_ closure to run + * after finishing this event loop. */ + GRPC_CLOSURE_SCHED(exec_ctx, &sp->do_read_closure, GRPC_ERROR_NONE); + } else { + /* Finish reading all the packets, re-arm the notification event so we can + * get another chance to read. Or fd already shutdown, re-arm to get a + * notification with shutdown error. */ + grpc_fd_notify_on_read(exec_ctx, sp->emfd, &sp->read_closure); + } + gpr_mu_unlock(&sp->server->mu); +} + /* event manager callback when reads are ready */ -static void on_read(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { - grpc_udp_listener *sp = (grpc_udp_listener *)arg; +static void on_read(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { + grpc_udp_listener* sp = (grpc_udp_listener*)arg; gpr_mu_lock(&sp->server->mu); if (error != GRPC_ERROR_NONE) { @@ -344,18 +386,56 @@ static void on_read(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { } return; } - - /* Tell the registered callback that data is available to read. */ + /* Read once. If there is more data to read, off load the work to another + * thread to finish. */ GPR_ASSERT(sp->read_cb); - sp->read_cb(exec_ctx, sp->emfd, sp->server->user_data); + if (sp->read_cb(exec_ctx, sp->emfd, sp->server->user_data)) { + /* There maybe more packets to read. Schedule read_more_cb_ closure to run + * after finishing this event loop. */ + GRPC_CLOSURE_INIT(&sp->do_read_closure, do_read, arg, + grpc_executor_scheduler(GRPC_EXECUTOR_LONG)); + GRPC_CLOSURE_SCHED(exec_ctx, &sp->do_read_closure, GRPC_ERROR_NONE); + } else { + /* Finish reading all the packets, re-arm the notification event so we can + * get another chance to read. Or fd already shutdown, re-arm to get a + * notification with shutdown error. */ + grpc_fd_notify_on_read(exec_ctx, sp->emfd, &sp->read_closure); + } + gpr_mu_unlock(&sp->server->mu); +} - /* Re-arm the notification event so we get another chance to read. */ - grpc_fd_notify_on_read(exec_ctx, sp->emfd, &sp->read_closure); +// Wrapper of grpc_fd_notify_on_write() with a grpc_closure callback interface. +void fd_notify_on_write_wrapper(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_udp_listener* sp = reinterpret_cast(arg); + gpr_mu_lock(&sp->server->mu); + if (!sp->notify_on_write_armed) { + grpc_fd_notify_on_write(exec_ctx, sp->emfd, &sp->write_closure); + sp->notify_on_write_armed = true; + } + gpr_mu_unlock(&sp->server->mu); +} + +static void do_write(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { + grpc_udp_listener* sp = reinterpret_cast(arg); + gpr_mu_lock(&(sp->server->mu)); + if (sp->already_shutdown) { + // If fd has been shutdown, don't write any more and re-arm notification. + grpc_fd_notify_on_write(exec_ctx, sp->emfd, &sp->write_closure); + } else { + sp->notify_on_write_armed = false; + /* Tell the registered callback that the socket is writeable. */ + GPR_ASSERT(sp->write_cb && error == GRPC_ERROR_NONE); + GRPC_CLOSURE_INIT(&sp->notify_on_write_closure, fd_notify_on_write_wrapper, + arg, grpc_schedule_on_exec_ctx); + sp->write_cb(exec_ctx, sp->emfd, sp->server->user_data, + &sp->notify_on_write_closure); + } gpr_mu_unlock(&sp->server->mu); } -static void on_write(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { - grpc_udp_listener *sp = (grpc_udp_listener *)arg; +static void on_write(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { + grpc_udp_listener* sp = (grpc_udp_listener*)arg; gpr_mu_lock(&(sp->server->mu)); if (error != GRPC_ERROR_NONE) { @@ -368,24 +448,23 @@ static void on_write(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { return; } - /* Tell the registered callback that the socket is writeable. */ - GPR_ASSERT(sp->write_cb); - sp->write_cb(exec_ctx, sp->emfd, sp->server->user_data); + /* Schedule actual write in another thread. */ + GRPC_CLOSURE_INIT(&sp->do_write_closure, do_write, arg, + grpc_executor_scheduler(GRPC_EXECUTOR_LONG)); - /* Re-arm the notification event so we get another chance to write. */ - grpc_fd_notify_on_write(exec_ctx, sp->emfd, &sp->write_closure); + GRPC_CLOSURE_SCHED(exec_ctx, &sp->do_write_closure, GRPC_ERROR_NONE); gpr_mu_unlock(&sp->server->mu); } -static int add_socket_to_server(grpc_udp_server *s, int fd, - const grpc_resolved_address *addr, +static int add_socket_to_server(grpc_udp_server* s, int fd, + const grpc_resolved_address* addr, grpc_udp_server_read_cb read_cb, grpc_udp_server_write_cb write_cb, grpc_udp_server_orphan_cb orphan_cb) { - grpc_udp_listener *sp; + grpc_udp_listener* sp; int port; - char *addr_str; - char *name; + char* addr_str; + char* name; port = prepare_socket(s->socket_factory, fd, addr); if (port >= 0) { @@ -394,9 +473,9 @@ static int add_socket_to_server(grpc_udp_server *s, int fd, gpr_free(addr_str); gpr_mu_lock(&s->mu); s->nports++; - sp = (grpc_udp_listener *)gpr_malloc(sizeof(grpc_udp_listener)); - sp->next = NULL; - if (s->head == NULL) { + sp = (grpc_udp_listener*)gpr_malloc(sizeof(grpc_udp_listener)); + sp->next = nullptr; + if (s->head == nullptr) { s->head = sp; } else { s->tail->next = sp; @@ -410,6 +489,7 @@ static int add_socket_to_server(grpc_udp_server *s, int fd, sp->write_cb = write_cb; sp->orphan_cb = orphan_cb; sp->orphan_notified = false; + sp->already_shutdown = false; GPR_ASSERT(sp->emfd); gpr_mu_unlock(&s->mu); gpr_free(name); @@ -418,12 +498,12 @@ static int add_socket_to_server(grpc_udp_server *s, int fd, return port; } -int grpc_udp_server_add_port(grpc_udp_server *s, - const grpc_resolved_address *addr, +int grpc_udp_server_add_port(grpc_udp_server* s, + const grpc_resolved_address* addr, grpc_udp_server_read_cb read_cb, grpc_udp_server_write_cb write_cb, grpc_udp_server_orphan_cb orphan_cb) { - grpc_udp_listener *sp; + grpc_udp_listener* sp; int allocated_port1 = -1; int allocated_port2 = -1; int fd; @@ -432,7 +512,7 @@ int grpc_udp_server_add_port(grpc_udp_server *s, grpc_resolved_address wild4; grpc_resolved_address wild6; grpc_resolved_address addr4_copy; - grpc_resolved_address *allocated_addr = NULL; + grpc_resolved_address* allocated_addr = nullptr; grpc_resolved_address sockname_temp; int port; @@ -441,12 +521,12 @@ int grpc_udp_server_add_port(grpc_udp_server *s, if (grpc_sockaddr_get_port(addr) == 0) { for (sp = s->head; sp; sp = sp->next) { sockname_temp.len = sizeof(struct sockaddr_storage); - if (0 == getsockname(sp->fd, (struct sockaddr *)sockname_temp.addr, - (socklen_t *)&sockname_temp.len)) { + if (0 == getsockname(sp->fd, (struct sockaddr*)sockname_temp.addr, + (socklen_t*)&sockname_temp.len)) { port = grpc_sockaddr_get_port(&sockname_temp); if (port > 0) { - allocated_addr = (grpc_resolved_address *)gpr_malloc( - sizeof(grpc_resolved_address)); + allocated_addr = + (grpc_resolved_address*)gpr_malloc(sizeof(grpc_resolved_address)); memcpy(allocated_addr, addr, sizeof(grpc_resolved_address)); grpc_sockaddr_set_port(allocated_addr, port); addr = allocated_addr; @@ -500,8 +580,8 @@ done: return allocated_port1 >= 0 ? allocated_port1 : allocated_port2; } -int grpc_udp_server_get_fd(grpc_udp_server *s, unsigned port_index) { - grpc_udp_listener *sp; +int grpc_udp_server_get_fd(grpc_udp_server* s, unsigned port_index) { + grpc_udp_listener* sp; if (port_index >= s->nports) { return -1; } @@ -509,21 +589,22 @@ int grpc_udp_server_get_fd(grpc_udp_server *s, unsigned port_index) { for (sp = s->head; sp && port_index != 0; sp = sp->next) { --port_index; } + GPR_ASSERT(sp); // if this fails, our check earlier was bogus return sp->fd; } -void grpc_udp_server_start(grpc_exec_ctx *exec_ctx, grpc_udp_server *s, - grpc_pollset **pollsets, size_t pollset_count, - void *user_data) { +void grpc_udp_server_start(grpc_exec_ctx* exec_ctx, grpc_udp_server* s, + grpc_pollset** pollsets, size_t pollset_count, + void* user_data) { size_t i; gpr_mu_lock(&s->mu); - grpc_udp_listener *sp; + grpc_udp_listener* sp; GPR_ASSERT(s->active_ports == 0); s->pollsets = pollsets; s->user_data = user_data; sp = s->head; - while (sp != NULL) { + while (sp != nullptr) { for (i = 0; i < pollset_count; i++) { grpc_pollset_add_fd(exec_ctx, pollsets[i], sp->emfd); } @@ -533,6 +614,7 @@ void grpc_udp_server_start(grpc_exec_ctx *exec_ctx, grpc_udp_server *s, GRPC_CLOSURE_INIT(&sp->write_closure, on_write, sp, grpc_schedule_on_exec_ctx); + sp->notify_on_write_armed = true; grpc_fd_notify_on_write(exec_ctx, sp->emfd, &sp->write_closure); /* Registered for both read and write callbacks: increment active_ports diff --git a/src/core/lib/iomgr/udp_server.h b/src/core/lib/iomgr/udp_server.h index e887cb1bcf4..1bd6922de66 100644 --- a/src/core/lib/iomgr/udp_server.h +++ b/src/core/lib/iomgr/udp_server.h @@ -23,10 +23,6 @@ #include "src/core/lib/iomgr/ev_posix.h" #include "src/core/lib/iomgr/resolve_address.h" -#ifdef __cplusplus -extern "C" { -#endif - /* Forward decl of struct grpc_server */ /* This is not typedef'ed to avoid a typedef-redefinition error */ struct grpc_server; @@ -34,29 +30,32 @@ struct grpc_server; /* Forward decl of grpc_udp_server */ typedef struct grpc_udp_server grpc_udp_server; -/* Called when data is available to read from the socket. */ -typedef void (*grpc_udp_server_read_cb)(grpc_exec_ctx *exec_ctx, grpc_fd *emfd, - void *user_data); +/* Called when data is available to read from the socket. + * Return true if there is more data to read from fd. */ +typedef bool (*grpc_udp_server_read_cb)(grpc_exec_ctx* exec_ctx, grpc_fd* emfd, + void* user_data); -/* Called when the socket is writeable. */ -typedef void (*grpc_udp_server_write_cb)(grpc_exec_ctx *exec_ctx, grpc_fd *emfd, - void *user_data); +/* Called when the socket is writeable. The given closure should be scheduled + * when the socket becomes blocked next time. */ +typedef void (*grpc_udp_server_write_cb)(grpc_exec_ctx* exec_ctx, grpc_fd* emfd, + void* user_data, + grpc_closure* notify_on_write_closure); /* Called when the grpc_fd is about to be orphaned (and the FD closed). */ -typedef void (*grpc_udp_server_orphan_cb)(grpc_exec_ctx *exec_ctx, - grpc_fd *emfd, - grpc_closure *shutdown_fd_callback, - void *user_data); +typedef void (*grpc_udp_server_orphan_cb)(grpc_exec_ctx* exec_ctx, + grpc_fd* emfd, + grpc_closure* shutdown_fd_callback, + void* user_data); /* Create a server, initially not bound to any ports */ -grpc_udp_server *grpc_udp_server_create(const grpc_channel_args *args); +grpc_udp_server* grpc_udp_server_create(const grpc_channel_args* args); /* Start listening to bound ports. user_data is passed to callbacks. */ -void grpc_udp_server_start(grpc_exec_ctx *exec_ctx, grpc_udp_server *udp_server, - grpc_pollset **pollsets, size_t pollset_count, - void *user_data); +void grpc_udp_server_start(grpc_exec_ctx* exec_ctx, grpc_udp_server* udp_server, + grpc_pollset** pollsets, size_t pollset_count, + void* user_data); -int grpc_udp_server_get_fd(grpc_udp_server *s, unsigned port_index); +int grpc_udp_server_get_fd(grpc_udp_server* s, unsigned port_index); /* Add a port to the server, returning port number on success, or negative on failure. @@ -68,17 +67,13 @@ int grpc_udp_server_get_fd(grpc_udp_server *s, unsigned port_index); /* TODO(ctiller): deprecate this, and make grpc_udp_server_add_ports to handle all of the multiple socket port matching logic in one place */ -int grpc_udp_server_add_port(grpc_udp_server *s, - const grpc_resolved_address *addr, +int grpc_udp_server_add_port(grpc_udp_server* s, + const grpc_resolved_address* addr, grpc_udp_server_read_cb read_cb, grpc_udp_server_write_cb write_cb, grpc_udp_server_orphan_cb orphan_cb); -void grpc_udp_server_destroy(grpc_exec_ctx *exec_ctx, grpc_udp_server *server, - grpc_closure *on_done); - -#ifdef __cplusplus -} -#endif +void grpc_udp_server_destroy(grpc_exec_ctx* exec_ctx, grpc_udp_server* server, + grpc_closure* on_done); #endif /* GRPC_CORE_LIB_IOMGR_UDP_SERVER_H */ diff --git a/src/core/lib/iomgr/unix_sockets_posix.cc b/src/core/lib/iomgr/unix_sockets_posix.cc index 35f898f13a3..af862c00dc5 100644 --- a/src/core/lib/iomgr/unix_sockets_posix.cc +++ b/src/core/lib/iomgr/unix_sockets_posix.cc @@ -36,12 +36,13 @@ void grpc_create_socketpair_if_unix(int sv[2]) { GPR_ASSERT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0); } -grpc_error *grpc_resolve_unix_domain_address(const char *name, - grpc_resolved_addresses **addrs) { - struct sockaddr_un *un; - if (strlen(name) > GPR_ARRAY_SIZE(((struct sockaddr_un *)0)->sun_path) - 1) { - char *err_msg; - grpc_error *err; +grpc_error* grpc_resolve_unix_domain_address(const char* name, + grpc_resolved_addresses** addrs) { + struct sockaddr_un* un; + if (strlen(name) > + GPR_ARRAY_SIZE(((struct sockaddr_un*)nullptr)->sun_path) - 1) { + char* err_msg; + grpc_error* err; gpr_asprintf(&err_msg, "Path name should not have more than %" PRIuPTR " characters.", GPR_ARRAY_SIZE(un->sun_path) - 1); @@ -50,29 +51,29 @@ grpc_error *grpc_resolve_unix_domain_address(const char *name, return err; } *addrs = - (grpc_resolved_addresses *)gpr_malloc(sizeof(grpc_resolved_addresses)); + (grpc_resolved_addresses*)gpr_malloc(sizeof(grpc_resolved_addresses)); (*addrs)->naddrs = 1; (*addrs)->addrs = - (grpc_resolved_address *)gpr_malloc(sizeof(grpc_resolved_address)); - un = (struct sockaddr_un *)(*addrs)->addrs->addr; + (grpc_resolved_address*)gpr_malloc(sizeof(grpc_resolved_address)); + un = (struct sockaddr_un*)(*addrs)->addrs->addr; un->sun_family = AF_UNIX; - strcpy(un->sun_path, name); + strncpy(un->sun_path, name, sizeof(un->sun_path)); (*addrs)->addrs->len = strlen(un->sun_path) + sizeof(un->sun_family) + 1; return GRPC_ERROR_NONE; } -int grpc_is_unix_socket(const grpc_resolved_address *resolved_addr) { - const struct sockaddr *addr = (const struct sockaddr *)resolved_addr->addr; +int grpc_is_unix_socket(const grpc_resolved_address* resolved_addr) { + const struct sockaddr* addr = (const struct sockaddr*)resolved_addr->addr; return addr->sa_family == AF_UNIX; } void grpc_unlink_if_unix_domain_socket( - const grpc_resolved_address *resolved_addr) { - const struct sockaddr *addr = (const struct sockaddr *)resolved_addr->addr; + const grpc_resolved_address* resolved_addr) { + const struct sockaddr* addr = (const struct sockaddr*)resolved_addr->addr; if (addr->sa_family != AF_UNIX) { return; } - struct sockaddr_un *un = (struct sockaddr_un *)resolved_addr->addr; + struct sockaddr_un* un = (struct sockaddr_un*)resolved_addr->addr; struct stat st; if (stat(un->sun_path, &st) == 0 && (st.st_mode & S_IFMT) == S_IFSOCK) { @@ -80,15 +81,15 @@ void grpc_unlink_if_unix_domain_socket( } } -char *grpc_sockaddr_to_uri_unix_if_possible( - const grpc_resolved_address *resolved_addr) { - const struct sockaddr *addr = (const struct sockaddr *)resolved_addr->addr; +char* grpc_sockaddr_to_uri_unix_if_possible( + const grpc_resolved_address* resolved_addr) { + const struct sockaddr* addr = (const struct sockaddr*)resolved_addr->addr; if (addr->sa_family != AF_UNIX) { - return NULL; + return nullptr; } - char *result; - gpr_asprintf(&result, "unix:%s", ((struct sockaddr_un *)addr)->sun_path); + char* result; + gpr_asprintf(&result, "unix:%s", ((struct sockaddr_un*)addr)->sun_path); return result; } diff --git a/src/core/lib/iomgr/unix_sockets_posix.h b/src/core/lib/iomgr/unix_sockets_posix.h index 3e7f9c7d1e3..1c079e6e765 100644 --- a/src/core/lib/iomgr/unix_sockets_posix.h +++ b/src/core/lib/iomgr/unix_sockets_posix.h @@ -25,25 +25,17 @@ #include "src/core/lib/iomgr/resolve_address.h" -#ifdef __cplusplus -extern "C" { -#endif - void grpc_create_socketpair_if_unix(int sv[2]); -grpc_error *grpc_resolve_unix_domain_address( - const char *name, grpc_resolved_addresses **addresses); +grpc_error* grpc_resolve_unix_domain_address( + const char* name, grpc_resolved_addresses** addresses); -int grpc_is_unix_socket(const grpc_resolved_address *resolved_addr); +int grpc_is_unix_socket(const grpc_resolved_address* resolved_addr); void grpc_unlink_if_unix_domain_socket( - const grpc_resolved_address *resolved_addr); - -char *grpc_sockaddr_to_uri_unix_if_possible( - const grpc_resolved_address *resolved_addr); + const grpc_resolved_address* resolved_addr); -#ifdef __cplusplus -} -#endif +char* grpc_sockaddr_to_uri_unix_if_possible( + const grpc_resolved_address* resolved_addr); #endif /* GRPC_CORE_LIB_IOMGR_UNIX_SOCKETS_POSIX_H */ diff --git a/src/core/lib/iomgr/unix_sockets_posix_noop.cc b/src/core/lib/iomgr/unix_sockets_posix_noop.cc index e46b1c003d0..fbd9602e1b1 100644 --- a/src/core/lib/iomgr/unix_sockets_posix_noop.cc +++ b/src/core/lib/iomgr/unix_sockets_posix_noop.cc @@ -29,18 +29,18 @@ void grpc_create_socketpair_if_unix(int sv[2]) { GPR_ASSERT(0); } -grpc_error *grpc_resolve_unix_domain_address( - const char *name, grpc_resolved_addresses **addresses) { +grpc_error* grpc_resolve_unix_domain_address( + const char* name, grpc_resolved_addresses** addresses) { *addresses = NULL; return GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Unix domain sockets are not supported on Windows"); } -int grpc_is_unix_socket(const grpc_resolved_address *addr) { return false; } +int grpc_is_unix_socket(const grpc_resolved_address* addr) { return false; } -void grpc_unlink_if_unix_domain_socket(const grpc_resolved_address *addr) {} +void grpc_unlink_if_unix_domain_socket(const grpc_resolved_address* addr) {} -char *grpc_sockaddr_to_uri_unix_if_possible(const grpc_resolved_address *addr) { +char* grpc_sockaddr_to_uri_unix_if_possible(const grpc_resolved_address* addr) { return NULL; } diff --git a/src/core/lib/iomgr/wakeup_fd_cv.cc b/src/core/lib/iomgr/wakeup_fd_cv.cc index 268e0175ddb..5c1f16d3fc0 100644 --- a/src/core/lib/iomgr/wakeup_fd_cv.cc +++ b/src/core/lib/iomgr/wakeup_fd_cv.cc @@ -46,7 +46,7 @@ static grpc_error* cv_fd_init(grpc_wakeup_fd* fd_info) { (fd_node*)gpr_realloc(g_cvfds.cvfds, sizeof(fd_node) * newsize); for (i = g_cvfds.size; i < newsize; i++) { g_cvfds.cvfds[i].is_set = 0; - g_cvfds.cvfds[i].cvs = NULL; + g_cvfds.cvfds[i].cvs = nullptr; g_cvfds.cvfds[i].next_free = g_cvfds.free_fds; g_cvfds.free_fds = &g_cvfds.cvfds[i]; } @@ -55,7 +55,7 @@ static grpc_error* cv_fd_init(grpc_wakeup_fd* fd_info) { idx = (int)(g_cvfds.free_fds - g_cvfds.cvfds); g_cvfds.free_fds = g_cvfds.free_fds->next_free; - g_cvfds.cvfds[idx].cvs = NULL; + g_cvfds.cvfds[idx].cvs = nullptr; g_cvfds.cvfds[idx].is_set = 0; fd_info->read_fd = GRPC_IDX_TO_FD(idx); fd_info->write_fd = -1; diff --git a/src/core/lib/iomgr/wakeup_fd_cv.h b/src/core/lib/iomgr/wakeup_fd_cv.h index dcd7bdb560f..017e41bfa88 100644 --- a/src/core/lib/iomgr/wakeup_fd_cv.h +++ b/src/core/lib/iomgr/wakeup_fd_cv.h @@ -40,10 +40,6 @@ #define GRPC_FD_TO_IDX(fd) (-(fd)-1) #define GRPC_IDX_TO_FD(idx) (-(idx)-1) -#ifdef __cplusplus -extern "C" { -#endif - typedef struct cv_node { gpr_cv* cv; struct cv_node* next; @@ -68,8 +64,4 @@ typedef struct cv_fd_table { extern const grpc_wakeup_fd_vtable grpc_cv_wakeup_fd_vtable; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_WAKEUP_FD_CV_H */ diff --git a/src/core/lib/iomgr/wakeup_fd_pipe.h b/src/core/lib/iomgr/wakeup_fd_pipe.h index 9bbb5e2ff7b..326a0c4e01d 100644 --- a/src/core/lib/iomgr/wakeup_fd_pipe.h +++ b/src/core/lib/iomgr/wakeup_fd_pipe.h @@ -21,14 +21,6 @@ #include "src/core/lib/iomgr/wakeup_fd_posix.h" -#ifdef __cplusplus -extern "C" { -#endif - extern const grpc_wakeup_fd_vtable grpc_pipe_wakeup_fd_vtable; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_WAKEUP_FD_PIPE_H */ diff --git a/src/core/lib/iomgr/wakeup_fd_posix.cc b/src/core/lib/iomgr/wakeup_fd_posix.cc index 9af96d314b5..e8de208a25b 100644 --- a/src/core/lib/iomgr/wakeup_fd_posix.cc +++ b/src/core/lib/iomgr/wakeup_fd_posix.cc @@ -25,7 +25,7 @@ #include "src/core/lib/iomgr/wakeup_fd_pipe.h" #include "src/core/lib/iomgr/wakeup_fd_posix.h" -static const grpc_wakeup_fd_vtable *wakeup_fd_vtable = NULL; +static const grpc_wakeup_fd_vtable* wakeup_fd_vtable = nullptr; int grpc_allow_specialized_wakeup_fd = 1; int grpc_allow_pipe_wakeup_fd = 1; @@ -45,7 +45,7 @@ void grpc_wakeup_fd_global_init(void) { } } -void grpc_wakeup_fd_global_destroy(void) { wakeup_fd_vtable = NULL; } +void grpc_wakeup_fd_global_destroy(void) { wakeup_fd_vtable = nullptr; } int grpc_has_wakeup_fd(void) { return has_real_wakeup_fd; } @@ -53,28 +53,28 @@ int grpc_cv_wakeup_fds_enabled(void) { return cv_wakeup_fds_enabled; } void grpc_enable_cv_wakeup_fds(int enable) { cv_wakeup_fds_enabled = enable; } -grpc_error *grpc_wakeup_fd_init(grpc_wakeup_fd *fd_info) { +grpc_error* grpc_wakeup_fd_init(grpc_wakeup_fd* fd_info) { if (cv_wakeup_fds_enabled) { return grpc_cv_wakeup_fd_vtable.init(fd_info); } return wakeup_fd_vtable->init(fd_info); } -grpc_error *grpc_wakeup_fd_consume_wakeup(grpc_wakeup_fd *fd_info) { +grpc_error* grpc_wakeup_fd_consume_wakeup(grpc_wakeup_fd* fd_info) { if (cv_wakeup_fds_enabled) { return grpc_cv_wakeup_fd_vtable.consume(fd_info); } return wakeup_fd_vtable->consume(fd_info); } -grpc_error *grpc_wakeup_fd_wakeup(grpc_wakeup_fd *fd_info) { +grpc_error* grpc_wakeup_fd_wakeup(grpc_wakeup_fd* fd_info) { if (cv_wakeup_fds_enabled) { return grpc_cv_wakeup_fd_vtable.wakeup(fd_info); } return wakeup_fd_vtable->wakeup(fd_info); } -void grpc_wakeup_fd_destroy(grpc_wakeup_fd *fd_info) { +void grpc_wakeup_fd_destroy(grpc_wakeup_fd* fd_info) { if (cv_wakeup_fds_enabled) { grpc_cv_wakeup_fd_vtable.destroy(fd_info); } else { diff --git a/src/core/lib/iomgr/wakeup_fd_posix.h b/src/core/lib/iomgr/wakeup_fd_posix.h index ae7849f98ce..a9584d0d489 100644 --- a/src/core/lib/iomgr/wakeup_fd_posix.h +++ b/src/core/lib/iomgr/wakeup_fd_posix.h @@ -49,10 +49,6 @@ #include "src/core/lib/iomgr/error.h" -#ifdef __cplusplus -extern "C" { -#endif - void grpc_wakeup_fd_global_init(void); void grpc_wakeup_fd_global_destroy(void); @@ -95,8 +91,4 @@ void grpc_wakeup_fd_destroy(grpc_wakeup_fd* fd_info); * wakeup_fd_nospecial.c if no such implementation exists. */ extern const grpc_wakeup_fd_vtable grpc_specialized_wakeup_fd_vtable; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_IOMGR_WAKEUP_FD_POSIX_H */ diff --git a/src/core/lib/json/json.h b/src/core/lib/json/json.h index c9fdec4ecb7..bbd43025eb8 100644 --- a/src/core/lib/json/json.h +++ b/src/core/lib/json/json.h @@ -23,10 +23,6 @@ #include "src/core/lib/json/json_common.h" -#ifdef __cplusplus -extern "C" { -#endif - /* A tree-like structure to hold json values. The key and value pointers * are not owned by it. */ @@ -74,8 +70,4 @@ char* grpc_json_dump_to_string(grpc_json* json, int indent); grpc_json* grpc_json_create(grpc_json_type type); void grpc_json_destroy(grpc_json* json); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_JSON_JSON_H */ diff --git a/src/core/lib/json/json_reader.cc b/src/core/lib/json/json_reader.cc index 094a35176cf..30039419b18 100644 --- a/src/core/lib/json/json_reader.cc +++ b/src/core/lib/json/json_reader.cc @@ -24,60 +24,60 @@ #include "src/core/lib/json/json_reader.h" -static void json_reader_string_clear(grpc_json_reader *reader) { +static void json_reader_string_clear(grpc_json_reader* reader) { reader->vtable->string_clear(reader->userdata); } -static void json_reader_string_add_char(grpc_json_reader *reader, uint32_t c) { +static void json_reader_string_add_char(grpc_json_reader* reader, uint32_t c) { reader->vtable->string_add_char(reader->userdata, c); } -static void json_reader_string_add_utf32(grpc_json_reader *reader, +static void json_reader_string_add_utf32(grpc_json_reader* reader, uint32_t utf32) { reader->vtable->string_add_utf32(reader->userdata, utf32); } -static uint32_t grpc_json_reader_read_char(grpc_json_reader *reader) { +static uint32_t grpc_json_reader_read_char(grpc_json_reader* reader) { return reader->vtable->read_char(reader->userdata); } -static void json_reader_container_begins(grpc_json_reader *reader, +static void json_reader_container_begins(grpc_json_reader* reader, grpc_json_type type) { reader->vtable->container_begins(reader->userdata, type); } static grpc_json_type grpc_json_reader_container_ends( - grpc_json_reader *reader) { + grpc_json_reader* reader) { return reader->vtable->container_ends(reader->userdata); } -static void json_reader_set_key(grpc_json_reader *reader) { +static void json_reader_set_key(grpc_json_reader* reader) { reader->vtable->set_key(reader->userdata); } -static void json_reader_set_string(grpc_json_reader *reader) { +static void json_reader_set_string(grpc_json_reader* reader) { reader->vtable->set_string(reader->userdata); } -static int json_reader_set_number(grpc_json_reader *reader) { +static int json_reader_set_number(grpc_json_reader* reader) { return reader->vtable->set_number(reader->userdata); } -static void json_reader_set_true(grpc_json_reader *reader) { +static void json_reader_set_true(grpc_json_reader* reader) { reader->vtable->set_true(reader->userdata); } -static void json_reader_set_false(grpc_json_reader *reader) { +static void json_reader_set_false(grpc_json_reader* reader) { reader->vtable->set_false(reader->userdata); } -static void json_reader_set_null(grpc_json_reader *reader) { +static void json_reader_set_null(grpc_json_reader* reader) { reader->vtable->set_null(reader->userdata); } /* Call this function to initialize the reader structure. */ -void grpc_json_reader_init(grpc_json_reader *reader, - grpc_json_reader_vtable *vtable, void *userdata) { +void grpc_json_reader_init(grpc_json_reader* reader, + grpc_json_reader_vtable* vtable, void* userdata) { memset(reader, 0, sizeof(*reader)); reader->vtable = vtable; reader->userdata = userdata; @@ -85,13 +85,13 @@ void grpc_json_reader_init(grpc_json_reader *reader, reader->state = GRPC_JSON_STATE_VALUE_BEGIN; } -int grpc_json_reader_is_complete(grpc_json_reader *reader) { +int grpc_json_reader_is_complete(grpc_json_reader* reader) { return ((reader->depth == 0) && ((reader->state == GRPC_JSON_STATE_END) || (reader->state == GRPC_JSON_STATE_VALUE_END))); } -grpc_json_reader_status grpc_json_reader_run(grpc_json_reader *reader) { +grpc_json_reader_status grpc_json_reader_run(grpc_json_reader* reader) { uint32_t c, success; /* This state-machine is a strict implementation of ECMA-404 */ @@ -177,8 +177,8 @@ grpc_json_reader_status grpc_json_reader_run(grpc_json_reader *reader) { if (!success) return GRPC_JSON_PARSE_ERROR; json_reader_string_clear(reader); reader->state = GRPC_JSON_STATE_VALUE_END; - /* The missing break here is intentional. */ - /* fallthrough */ + /* The missing break here is intentional. */ + /* fallthrough */ case GRPC_JSON_STATE_VALUE_END: case GRPC_JSON_STATE_OBJECT_KEY_BEGIN: diff --git a/src/core/lib/json/json_reader.h b/src/core/lib/json/json_reader.h index 7f14a9a9c81..03185cb2b65 100644 --- a/src/core/lib/json/json_reader.h +++ b/src/core/lib/json/json_reader.h @@ -22,10 +22,6 @@ #include #include "src/core/lib/json/json_common.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef enum { GRPC_JSON_STATE_OBJECT_KEY_BEGIN, GRPC_JSON_STATE_OBJECT_KEY_STRING, @@ -71,27 +67,27 @@ struct grpc_json_reader; typedef struct grpc_json_reader_vtable { /* Clears your internal string scratchpad. */ - void (*string_clear)(void *userdata); + void (*string_clear)(void* userdata); /* Adds a char to the string scratchpad. */ - void (*string_add_char)(void *userdata, uint32_t c); + void (*string_add_char)(void* userdata, uint32_t c); /* Adds a utf32 char to the string scratchpad. */ - void (*string_add_utf32)(void *userdata, uint32_t c); + void (*string_add_utf32)(void* userdata, uint32_t c); /* Reads a character from your input. May be utf-8, 16 or 32. */ - uint32_t (*read_char)(void *userdata); + uint32_t (*read_char)(void* userdata); /* Starts a container of type GRPC_JSON_ARRAY or GRPC_JSON_OBJECT. */ - void (*container_begins)(void *userdata, grpc_json_type type); + void (*container_begins)(void* userdata, grpc_json_type type); /* Ends the current container. Must return the type of its parent. */ - grpc_json_type (*container_ends)(void *userdata); + grpc_json_type (*container_ends)(void* userdata); /* Your internal string scratchpad is an object's key. */ - void (*set_key)(void *userdata); + void (*set_key)(void* userdata); /* Your internal string scratchpad is a string value. */ - void (*set_string)(void *userdata); + void (*set_string)(void* userdata); /* Your internal string scratchpad is a numerical value. Return 1 if valid. */ - int (*set_number)(void *userdata); + int (*set_number)(void* userdata); /* Sets the values true, false or null. */ - void (*set_true)(void *userdata); - void (*set_false)(void *userdata); - void (*set_null)(void *userdata); + void (*set_true)(void* userdata); + void (*set_false)(void* userdata); + void (*set_null)(void* userdata); } grpc_json_reader_vtable; typedef struct grpc_json_reader { @@ -99,8 +95,8 @@ typedef struct grpc_json_reader { * The definition is public so you can put it on your stack. */ - void *userdata; - grpc_json_reader_vtable *vtable; + void* userdata; + grpc_json_reader_vtable* vtable; int depth; int in_object; int in_array; @@ -133,21 +129,17 @@ typedef enum { * . GRPC_JSON_INTERNAL_ERROR if the parser somehow ended into an invalid * internal state. */ -grpc_json_reader_status grpc_json_reader_run(grpc_json_reader *reader); +grpc_json_reader_status grpc_json_reader_run(grpc_json_reader* reader); /* Call this function to initialize the reader structure. */ -void grpc_json_reader_init(grpc_json_reader *reader, - grpc_json_reader_vtable *vtable, void *userdata); +void grpc_json_reader_init(grpc_json_reader* reader, + grpc_json_reader_vtable* vtable, void* userdata); /* You may call this from the read_char callback if you don't know where is the * end of your input stream, and you'd like the json reader to hint you that it * has completed reading its input, so you can return an EOF to it. Note that * there might still be trailing whitespaces after that point. */ -int grpc_json_reader_is_complete(grpc_json_reader *reader); - -#ifdef __cplusplus -} -#endif +int grpc_json_reader_is_complete(grpc_json_reader* reader); #endif /* GRPC_CORE_LIB_JSON_JSON_READER_H */ diff --git a/src/core/lib/json/json_string.cc b/src/core/lib/json/json_string.cc index 3178d2d2b49..a339eec81bf 100644 --- a/src/core/lib/json/json_string.cc +++ b/src/core/lib/json/json_string.cc @@ -38,13 +38,13 @@ * input size, and never expands it. */ typedef struct { - grpc_json *top; - grpc_json *current_container; - grpc_json *current_value; - uint8_t *input; - uint8_t *key; - uint8_t *string; - uint8_t *string_ptr; + grpc_json* top; + grpc_json* current_container; + grpc_json* current_value; + uint8_t* input; + uint8_t* key; + uint8_t* string; + uint8_t* string_ptr; size_t remaining_input; } json_reader_userdata; @@ -52,7 +52,7 @@ typedef struct { * The point is that we allocate that string in chunks of 256 bytes. */ typedef struct { - char *output; + char* output; size_t free_space; size_t string_len; size_t allocated; @@ -62,35 +62,35 @@ typedef struct { * and will enlarge it if necessary. We're only allocating chunks of 256 * bytes at a time (or multiples thereof). */ -static void json_writer_output_check(void *userdata, size_t needed) { - json_writer_userdata *state = (json_writer_userdata *)userdata; +static void json_writer_output_check(void* userdata, size_t needed) { + json_writer_userdata* state = (json_writer_userdata*)userdata; if (state->free_space >= needed) return; needed -= state->free_space; /* Round up by 256 bytes. */ needed = (needed + 0xff) & ~0xffU; - state->output = (char *)gpr_realloc(state->output, state->allocated + needed); + state->output = (char*)gpr_realloc(state->output, state->allocated + needed); state->free_space += needed; state->allocated += needed; } /* These are needed by the writer's implementation. */ -static void json_writer_output_char(void *userdata, char c) { - json_writer_userdata *state = (json_writer_userdata *)userdata; +static void json_writer_output_char(void* userdata, char c) { + json_writer_userdata* state = (json_writer_userdata*)userdata; json_writer_output_check(userdata, 1); state->output[state->string_len++] = c; state->free_space--; } -static void json_writer_output_string_with_len(void *userdata, const char *str, +static void json_writer_output_string_with_len(void* userdata, const char* str, size_t len) { - json_writer_userdata *state = (json_writer_userdata *)userdata; + json_writer_userdata* state = (json_writer_userdata*)userdata; json_writer_output_check(userdata, len); memcpy(state->output + state->string_len, str, len); state->string_len += len; state->free_space -= len; } -static void json_writer_output_string(void *userdata, const char *str) { +static void json_writer_output_string(void* userdata, const char* str) { size_t len = strlen(str); json_writer_output_string_with_len(userdata, str, len); } @@ -98,8 +98,8 @@ static void json_writer_output_string(void *userdata, const char *str) { /* The reader asks us to clear our scratchpad. In our case, we'll simply mark * the end of the current string, and advance our output pointer. */ -static void json_reader_string_clear(void *userdata) { - json_reader_userdata *state = (json_reader_userdata *)userdata; +static void json_reader_string_clear(void* userdata) { + json_reader_userdata* state = (json_reader_userdata*)userdata; if (state->string) { GPR_ASSERT(state->string_ptr < state->input); *state->string_ptr++ = 0; @@ -107,8 +107,8 @@ static void json_reader_string_clear(void *userdata) { state->string = state->string_ptr; } -static void json_reader_string_add_char(void *userdata, uint32_t c) { - json_reader_userdata *state = (json_reader_userdata *)userdata; +static void json_reader_string_add_char(void* userdata, uint32_t c) { + json_reader_userdata* state = (json_reader_userdata*)userdata; GPR_ASSERT(state->string_ptr < state->input); GPR_ASSERT(c <= 0xff); *state->string_ptr++ = (uint8_t)c; @@ -117,7 +117,7 @@ static void json_reader_string_add_char(void *userdata, uint32_t c) { /* We are converting a UTF-32 character into UTF-8 here, * as described by RFC3629. */ -static void json_reader_string_add_utf32(void *userdata, uint32_t c) { +static void json_reader_string_add_utf32(void* userdata, uint32_t c) { if (c <= 0x7f) { json_reader_string_add_char(userdata, c); } else if (c <= 0x7ff) { @@ -147,9 +147,9 @@ static void json_reader_string_add_utf32(void *userdata, uint32_t c) { /* We consider that the input may be a zero-terminated string. So we * can end up hitting eof before the end of the alleged string length. */ -static uint32_t json_reader_read_char(void *userdata) { +static uint32_t json_reader_read_char(void* userdata) { uint32_t r; - json_reader_userdata *state = (json_reader_userdata *)userdata; + json_reader_userdata* state = (json_reader_userdata*)userdata; if (state->remaining_input == 0) return GRPC_JSON_READ_CHAR_EOF; @@ -167,9 +167,9 @@ static uint32_t json_reader_read_char(void *userdata) { /* Helper function to create a new grpc_json object and link it into * our tree-in-progress inside our opaque structure. */ -static grpc_json *json_create_and_link(void *userdata, grpc_json_type type) { - json_reader_userdata *state = (json_reader_userdata *)userdata; - grpc_json *json = grpc_json_create(type); +static grpc_json* json_create_and_link(void* userdata, grpc_json_type type) { + json_reader_userdata* state = (json_reader_userdata*)userdata; + grpc_json* json = grpc_json_create(type); json->parent = state->current_container; json->prev = state->current_value; @@ -183,7 +183,7 @@ static grpc_json *json_create_and_link(void *userdata, grpc_json_type type) { json->parent->child = json; } if (json->parent->type == GRPC_JSON_OBJECT) { - json->key = (char *)state->key; + json->key = (char*)state->key; } } if (!state->top) { @@ -193,15 +193,15 @@ static grpc_json *json_create_and_link(void *userdata, grpc_json_type type) { return json; } -static void json_reader_container_begins(void *userdata, grpc_json_type type) { - json_reader_userdata *state = (json_reader_userdata *)userdata; - grpc_json *container; +static void json_reader_container_begins(void* userdata, grpc_json_type type) { + json_reader_userdata* state = (json_reader_userdata*)userdata; + grpc_json* container; GPR_ASSERT(type == GRPC_JSON_ARRAY || type == GRPC_JSON_OBJECT); container = json_create_and_link(userdata, type); state->current_container = container; - state->current_value = NULL; + state->current_value = nullptr; } /* It's important to remember that the reader is mostly stateless, so it @@ -213,9 +213,9 @@ static void json_reader_container_begins(void *userdata, grpc_json_type type) { * Also note that if we're at the top of the tree, and the last container * ends, we have to return GRPC_JSON_TOP_LEVEL. */ -static grpc_json_type json_reader_container_ends(void *userdata) { +static grpc_json_type json_reader_container_ends(void* userdata) { grpc_json_type container_type = GRPC_JSON_TOP_LEVEL; - json_reader_userdata *state = (json_reader_userdata *)userdata; + json_reader_userdata* state = (json_reader_userdata*)userdata; GPR_ASSERT(state->current_container); @@ -235,36 +235,36 @@ static grpc_json_type json_reader_container_ends(void *userdata) { * Note that in the set_number case, we're not going to try interpreting it. * We'll keep it as a string, and leave it to the caller to evaluate it. */ -static void json_reader_set_key(void *userdata) { - json_reader_userdata *state = (json_reader_userdata *)userdata; +static void json_reader_set_key(void* userdata) { + json_reader_userdata* state = (json_reader_userdata*)userdata; state->key = state->string; } -static void json_reader_set_string(void *userdata) { - json_reader_userdata *state = (json_reader_userdata *)userdata; - grpc_json *json = json_create_and_link(userdata, GRPC_JSON_STRING); - json->value = (char *)state->string; +static void json_reader_set_string(void* userdata) { + json_reader_userdata* state = (json_reader_userdata*)userdata; + grpc_json* json = json_create_and_link(userdata, GRPC_JSON_STRING); + json->value = (char*)state->string; } -static int json_reader_set_number(void *userdata) { - json_reader_userdata *state = (json_reader_userdata *)userdata; - grpc_json *json = json_create_and_link(userdata, GRPC_JSON_NUMBER); - json->value = (char *)state->string; +static int json_reader_set_number(void* userdata) { + json_reader_userdata* state = (json_reader_userdata*)userdata; + grpc_json* json = json_create_and_link(userdata, GRPC_JSON_NUMBER); + json->value = (char*)state->string; return 1; } /* The object types true, false and null are self-sufficient, and don't need * any more information beside their type. */ -static void json_reader_set_true(void *userdata) { +static void json_reader_set_true(void* userdata) { json_create_and_link(userdata, GRPC_JSON_TRUE); } -static void json_reader_set_false(void *userdata) { +static void json_reader_set_false(void* userdata) { json_create_and_link(userdata, GRPC_JSON_FALSE); } -static void json_reader_set_null(void *userdata) { +static void json_reader_set_null(void* userdata) { json_create_and_link(userdata, GRPC_JSON_NULL); } @@ -277,17 +277,17 @@ static grpc_json_reader_vtable reader_vtable = { json_reader_set_false, json_reader_set_null}; /* And finally, let's define our public API. */ -grpc_json *grpc_json_parse_string_with_len(char *input, size_t size) { +grpc_json* grpc_json_parse_string_with_len(char* input, size_t size) { grpc_json_reader reader; json_reader_userdata state; - grpc_json *json = NULL; + grpc_json* json = nullptr; grpc_json_reader_status status; - if (!input) return NULL; + if (!input) return nullptr; - state.top = state.current_container = state.current_value = NULL; - state.string = state.key = NULL; - state.string_ptr = state.input = (uint8_t *)input; + state.top = state.current_container = state.current_value = nullptr; + state.string = state.key = nullptr; + state.string_ptr = state.input = (uint8_t*)input; state.remaining_input = size; grpc_json_reader_init(&reader, &reader_vtable, &state); @@ -296,7 +296,7 @@ grpc_json *grpc_json_parse_string_with_len(char *input, size_t size) { if ((status != GRPC_JSON_DONE) && json) { grpc_json_destroy(json); - json = NULL; + json = nullptr; } return json; @@ -304,11 +304,11 @@ grpc_json *grpc_json_parse_string_with_len(char *input, size_t size) { #define UNBOUND_JSON_STRING_LENGTH 0x7fffffff -grpc_json *grpc_json_parse_string(char *input) { +grpc_json* grpc_json_parse_string(char* input) { return grpc_json_parse_string_with_len(input, UNBOUND_JSON_STRING_LENGTH); } -static void json_dump_recursive(grpc_json_writer *writer, grpc_json *json, +static void json_dump_recursive(grpc_json_writer* writer, grpc_json* json, int in_object) { while (json) { if (in_object) grpc_json_writer_object_key(writer, json->key); @@ -348,11 +348,11 @@ static grpc_json_writer_vtable writer_vtable = { json_writer_output_char, json_writer_output_string, json_writer_output_string_with_len}; -char *grpc_json_dump_to_string(grpc_json *json, int indent) { +char* grpc_json_dump_to_string(grpc_json* json, int indent) { grpc_json_writer writer; json_writer_userdata state; - state.output = NULL; + state.output = nullptr; state.free_space = state.string_len = state.allocated = 0; grpc_json_writer_init(&writer, indent, &writer_vtable, &state); diff --git a/src/core/lib/json/json_writer.cc b/src/core/lib/json/json_writer.cc index eab1bff7a61..0b9c7c30eae 100644 --- a/src/core/lib/json/json_writer.cc +++ b/src/core/lib/json/json_writer.cc @@ -22,22 +22,22 @@ #include "src/core/lib/json/json_writer.h" -static void json_writer_output_char(grpc_json_writer *writer, char c) { +static void json_writer_output_char(grpc_json_writer* writer, char c) { writer->vtable->output_char(writer->userdata, c); } -static void json_writer_output_string(grpc_json_writer *writer, - const char *str) { +static void json_writer_output_string(grpc_json_writer* writer, + const char* str) { writer->vtable->output_string(writer->userdata, str); } -static void json_writer_output_string_with_len(grpc_json_writer *writer, - const char *str, size_t len) { +static void json_writer_output_string_with_len(grpc_json_writer* writer, + const char* str, size_t len) { writer->vtable->output_string_with_len(writer->userdata, str, len); } -void grpc_json_writer_init(grpc_json_writer *writer, int indent, - grpc_json_writer_vtable *vtable, void *userdata) { +void grpc_json_writer_init(grpc_json_writer* writer, int indent, + grpc_json_writer_vtable* vtable, void* userdata) { memset(writer, 0, sizeof(*writer)); writer->container_empty = 1; writer->indent = indent; @@ -45,7 +45,7 @@ void grpc_json_writer_init(grpc_json_writer *writer, int indent, writer->userdata = userdata; } -static void json_writer_output_indent(grpc_json_writer *writer) { +static void json_writer_output_indent(grpc_json_writer* writer) { static const char spacesstr[] = " " " " @@ -73,7 +73,7 @@ static void json_writer_output_indent(grpc_json_writer *writer) { writer, spacesstr + sizeof(spacesstr) - 1 - spaces, spaces); } -static void json_writer_value_end(grpc_json_writer *writer) { +static void json_writer_value_end(grpc_json_writer* writer) { if (writer->container_empty) { writer->container_empty = 0; if ((writer->indent == 0) || (writer->depth == 0)) return; @@ -85,7 +85,7 @@ static void json_writer_value_end(grpc_json_writer *writer) { } } -static void json_writer_escape_utf16(grpc_json_writer *writer, uint16_t utf16) { +static void json_writer_escape_utf16(grpc_json_writer* writer, uint16_t utf16) { static const char hex[] = "0123456789abcdef"; json_writer_output_string_with_len(writer, "\\u", 2); @@ -95,8 +95,8 @@ static void json_writer_escape_utf16(grpc_json_writer *writer, uint16_t utf16) { json_writer_output_char(writer, hex[(utf16)&0x0f]); } -static void json_writer_escape_string(grpc_json_writer *writer, - const char *string) { +static void json_writer_escape_string(grpc_json_writer* writer, + const char* string) { json_writer_output_char(writer, '"'); for (;;) { @@ -190,7 +190,7 @@ static void json_writer_escape_string(grpc_json_writer *writer, json_writer_output_char(writer, '"'); } -void grpc_json_writer_container_begins(grpc_json_writer *writer, +void grpc_json_writer_container_begins(grpc_json_writer* writer, grpc_json_type type) { if (!writer->got_key) json_writer_value_end(writer); json_writer_output_indent(writer); @@ -200,7 +200,7 @@ void grpc_json_writer_container_begins(grpc_json_writer *writer, writer->depth++; } -void grpc_json_writer_container_ends(grpc_json_writer *writer, +void grpc_json_writer_container_ends(grpc_json_writer* writer, grpc_json_type type) { if (writer->indent && !writer->container_empty) json_writer_output_char(writer, '\n'); @@ -211,7 +211,7 @@ void grpc_json_writer_container_ends(grpc_json_writer *writer, writer->got_key = 0; } -void grpc_json_writer_object_key(grpc_json_writer *writer, const char *string) { +void grpc_json_writer_object_key(grpc_json_writer* writer, const char* string) { json_writer_value_end(writer); json_writer_output_indent(writer); json_writer_escape_string(writer, string); @@ -219,23 +219,23 @@ void grpc_json_writer_object_key(grpc_json_writer *writer, const char *string) { writer->got_key = 1; } -void grpc_json_writer_value_raw(grpc_json_writer *writer, const char *string) { +void grpc_json_writer_value_raw(grpc_json_writer* writer, const char* string) { if (!writer->got_key) json_writer_value_end(writer); json_writer_output_indent(writer); json_writer_output_string(writer, string); writer->got_key = 0; } -void grpc_json_writer_value_raw_with_len(grpc_json_writer *writer, - const char *string, size_t len) { +void grpc_json_writer_value_raw_with_len(grpc_json_writer* writer, + const char* string, size_t len) { if (!writer->got_key) json_writer_value_end(writer); json_writer_output_indent(writer); json_writer_output_string_with_len(writer, string, len); writer->got_key = 0; } -void grpc_json_writer_value_string(grpc_json_writer *writer, - const char *string) { +void grpc_json_writer_value_string(grpc_json_writer* writer, + const char* string) { if (!writer->got_key) json_writer_value_end(writer); json_writer_output_indent(writer); json_writer_escape_string(writer, string); diff --git a/src/core/lib/json/json_writer.h b/src/core/lib/json/json_writer.h index 132d1f24e85..a4f2d4daeb3 100644 --- a/src/core/lib/json/json_writer.h +++ b/src/core/lib/json/json_writer.h @@ -35,23 +35,19 @@ #include "src/core/lib/json/json_common.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_json_writer_vtable { /* Adds a character to the output stream. */ - void (*output_char)(void *userdata, char); + void (*output_char)(void* userdata, char); /* Adds a zero-terminated string to the output stream. */ - void (*output_string)(void *userdata, const char *str); + void (*output_string)(void* userdata, const char* str); /* Adds a fixed-length string to the output stream. */ - void (*output_string_with_len)(void *userdata, const char *str, size_t len); + void (*output_string_with_len)(void* userdata, const char* str, size_t len); } grpc_json_writer_vtable; typedef struct grpc_json_writer { - void *userdata; - grpc_json_writer_vtable *vtable; + void* userdata; + grpc_json_writer_vtable* vtable; int indent; int depth; int container_empty; @@ -63,28 +59,24 @@ typedef struct grpc_json_writer { * use indent=0, then the output will not have any newlines either, thus * emitting a condensed json output. */ -void grpc_json_writer_init(grpc_json_writer *writer, int indent, - grpc_json_writer_vtable *vtable, void *userdata); +void grpc_json_writer_init(grpc_json_writer* writer, int indent, + grpc_json_writer_vtable* vtable, void* userdata); /* Signals the beginning of a container. */ -void grpc_json_writer_container_begins(grpc_json_writer *writer, +void grpc_json_writer_container_begins(grpc_json_writer* writer, grpc_json_type type); /* Signals the end of a container. */ -void grpc_json_writer_container_ends(grpc_json_writer *writer, +void grpc_json_writer_container_ends(grpc_json_writer* writer, grpc_json_type type); /* Writes down an object key for the next value. */ -void grpc_json_writer_object_key(grpc_json_writer *writer, const char *string); +void grpc_json_writer_object_key(grpc_json_writer* writer, const char* string); /* Sets a raw value. Useful for numbers. */ -void grpc_json_writer_value_raw(grpc_json_writer *writer, const char *string); +void grpc_json_writer_value_raw(grpc_json_writer* writer, const char* string); /* Sets a raw value with its length. Useful for values like true or false. */ -void grpc_json_writer_value_raw_with_len(grpc_json_writer *writer, - const char *string, size_t len); +void grpc_json_writer_value_raw_with_len(grpc_json_writer* writer, + const char* string, size_t len); /* Sets a string value. It'll be escaped, and utf-8 validated. */ -void grpc_json_writer_value_string(grpc_json_writer *writer, - const char *string); - -#ifdef __cplusplus -} -#endif +void grpc_json_writer_value_string(grpc_json_writer* writer, + const char* string); #endif /* GRPC_CORE_LIB_JSON_JSON_WRITER_H */ diff --git a/src/core/lib/profiling/basic_timers.cc b/src/core/lib/profiling/basic_timers.cc index 0ae7d7f6002..3ec6280e6b0 100644 --- a/src/core/lib/profiling/basic_timers.cc +++ b/src/core/lib/profiling/basic_timers.cc @@ -36,8 +36,8 @@ typedef enum { BEGIN = '{', END = '}', MARK = '.' } marker_type; typedef struct gpr_timer_entry { gpr_timespec tm; - const char *tagstr; - const char *file; + const char* tagstr; + const char* file; short line; char type; uint8_t important; @@ -48,21 +48,21 @@ typedef struct gpr_timer_entry { typedef struct gpr_timer_log { size_t num_entries; - struct gpr_timer_log *next; - struct gpr_timer_log *prev; + struct gpr_timer_log* next; + struct gpr_timer_log* prev; gpr_timer_entry log[MAX_COUNT]; } gpr_timer_log; typedef struct gpr_timer_log_list { - gpr_timer_log *head; + gpr_timer_log* head; /* valid iff head!=NULL */ - gpr_timer_log *tail; + gpr_timer_log* tail; } gpr_timer_log_list; -static __thread gpr_timer_log *g_thread_log; +static __thread gpr_timer_log* g_thread_log; static gpr_once g_once_init = GPR_ONCE_INIT; -static FILE *output_file; -static const char *output_filename_or_null = NULL; +static FILE* output_file; +static const char* output_filename_or_null = NULL; static pthread_mutex_t g_mu; static pthread_cond_t g_cv; static gpr_timer_log_list g_in_progress_logs; @@ -73,7 +73,7 @@ static __thread int g_thread_id; static int g_next_thread_id; static int g_writing_enabled = 1; -static const char *output_filename() { +static const char* output_filename() { if (output_filename_or_null == NULL) { output_filename_or_null = gpr_getenv("LATENCY_TRACE"); if (output_filename_or_null == NULL || @@ -84,7 +84,7 @@ static const char *output_filename() { return output_filename_or_null; } -static int timer_log_push_back(gpr_timer_log_list *list, gpr_timer_log *log) { +static int timer_log_push_back(gpr_timer_log_list* list, gpr_timer_log* log) { if (list->head == NULL) { list->head = list->tail = log; log->next = log->prev = NULL; @@ -98,8 +98,8 @@ static int timer_log_push_back(gpr_timer_log_list *list, gpr_timer_log *log) { } } -static gpr_timer_log *timer_log_pop_front(gpr_timer_log_list *list) { - gpr_timer_log *out = list->head; +static gpr_timer_log* timer_log_pop_front(gpr_timer_log_list* list) { + gpr_timer_log* out = list->head; if (out != NULL) { list->head = out->next; if (list->head != NULL) { @@ -111,7 +111,7 @@ static gpr_timer_log *timer_log_pop_front(gpr_timer_log_list *list) { return out; } -static void timer_log_remove(gpr_timer_log_list *list, gpr_timer_log *log) { +static void timer_log_remove(gpr_timer_log_list* list, gpr_timer_log* log) { if (log->prev == NULL) { list->head = log->next; if (list->head != NULL) { @@ -130,13 +130,13 @@ static void timer_log_remove(gpr_timer_log_list *list, gpr_timer_log *log) { } } -static void write_log(gpr_timer_log *log) { +static void write_log(gpr_timer_log* log) { size_t i; if (output_file == NULL) { output_file = fopen(output_filename(), "w"); } for (i = 0; i < log->num_entries; i++) { - gpr_timer_entry *entry = &(log->log[i]); + gpr_timer_entry* entry = &(log->log[i]); if (gpr_time_cmp(entry->tm, gpr_time_0(entry->tm.clock_type)) < 0) { entry->tm = gpr_time_0(entry->tm.clock_type); } @@ -149,8 +149,8 @@ static void write_log(gpr_timer_log *log) { } } -static void writing_thread(void *unused) { - gpr_timer_log *log; +static void writing_thread(void* unused) { + gpr_timer_log* log; pthread_mutex_lock(&g_mu); for (;;) { while ((log = timer_log_pop_front(&g_done_logs)) == NULL && !g_shutdown) { @@ -169,8 +169,8 @@ static void writing_thread(void *unused) { } } -static void flush_logs(gpr_timer_log_list *list) { - gpr_timer_log *log; +static void flush_logs(gpr_timer_log_list* list) { + gpr_timer_log* log; while ((log = timer_log_pop_front(list)) != NULL) { write_log(log); free(log); @@ -196,7 +196,7 @@ static void finish_writing(void) { } } -void gpr_timers_set_log_filename(const char *filename) { +void gpr_timers_set_log_filename(const char* filename) { output_filename_or_null = filename; } @@ -209,7 +209,7 @@ static void init_output() { static void rotate_log() { /* Using malloc here, as this code could end up being called by gpr_malloc */ - gpr_timer_log *log = static_cast(malloc(sizeof(*log))); + gpr_timer_log* log = static_cast(malloc(sizeof(*log))); gpr_once_init(&g_once_init, init_output); log->num_entries = 0; pthread_mutex_lock(&g_mu); @@ -226,9 +226,9 @@ static void rotate_log() { g_thread_log = log; } -static void gpr_timers_log_add(const char *tagstr, marker_type type, - int important, const char *file, int line) { - gpr_timer_entry *entry; +static void gpr_timers_log_add(const char* tagstr, marker_type type, + int important, const char* file, int line) { + gpr_timer_entry* entry; if (!g_writing_enabled) { return; @@ -250,17 +250,17 @@ static void gpr_timers_log_add(const char *tagstr, marker_type type, } /* Latency profiler API implementation. */ -void gpr_timer_add_mark(const char *tagstr, int important, const char *file, +void gpr_timer_add_mark(const char* tagstr, int important, const char* file, int line) { gpr_timers_log_add(tagstr, MARK, important, file, line); } -void gpr_timer_begin(const char *tagstr, int important, const char *file, +void gpr_timer_begin(const char* tagstr, int important, const char* file, int line) { gpr_timers_log_add(tagstr, BEGIN, important, file, line); } -void gpr_timer_end(const char *tagstr, int important, const char *file, +void gpr_timer_end(const char* tagstr, int important, const char* file, int line) { gpr_timers_log_add(tagstr, END, important, file, line); } @@ -277,7 +277,7 @@ void gpr_timers_global_init(void) {} void gpr_timers_global_destroy(void) {} -void gpr_timers_set_log_filename(const char *filename) {} +void gpr_timers_set_log_filename(const char* filename) {} void gpr_timer_set_enabled(int enabled) {} #endif /* GRPC_BASIC_PROFILER */ diff --git a/src/core/lib/profiling/stap_timers.cc b/src/core/lib/profiling/stap_timers.cc index c86d74f058a..5ee1c4317c7 100644 --- a/src/core/lib/profiling/stap_timers.cc +++ b/src/core/lib/profiling/stap_timers.cc @@ -27,22 +27,22 @@ #include "src/core/lib/profiling/stap_probes.h" /* Latency profiler API implementation. */ -void gpr_timer_add_mark(int tag, const char *tagstr, void *id, const char *file, +void gpr_timer_add_mark(int tag, const char* tagstr, void* id, const char* file, int line) { _STAP_ADD_MARK(tag); } -void gpr_timer_add_important_mark(int tag, const char *tagstr, void *id, - const char *file, int line) { +void gpr_timer_add_important_mark(int tag, const char* tagstr, void* id, + const char* file, int line) { _STAP_ADD_IMPORTANT_MARK(tag); } -void gpr_timer_begin(int tag, const char *tagstr, void *id, const char *file, +void gpr_timer_begin(int tag, const char* tagstr, void* id, const char* file, int line) { _STAP_TIMING_NS_BEGIN(tag); } -void gpr_timer_end(int tag, const char *tagstr, void *id, const char *file, +void gpr_timer_end(int tag, const char* tagstr, void* id, const char* file, int line) { _STAP_TIMING_NS_END(tag); } diff --git a/src/core/lib/profiling/timers.h b/src/core/lib/profiling/timers.h index 7f02b4bf849..9f11f771e67 100644 --- a/src/core/lib/profiling/timers.h +++ b/src/core/lib/profiling/timers.h @@ -19,21 +19,17 @@ #ifndef GRPC_CORE_LIB_PROFILING_TIMERS_H #define GRPC_CORE_LIB_PROFILING_TIMERS_H -#ifdef __cplusplus -extern "C" { -#endif - void gpr_timers_global_init(void); void gpr_timers_global_destroy(void); -void gpr_timer_add_mark(const char *tagstr, int important, const char *file, +void gpr_timer_add_mark(const char* tagstr, int important, const char* file, int line); -void gpr_timer_begin(const char *tagstr, int important, const char *file, +void gpr_timer_begin(const char* tagstr, int important, const char* file, int line); -void gpr_timer_end(const char *tagstr, int important, const char *file, +void gpr_timer_end(const char* tagstr, int important, const char* file, int line); -void gpr_timers_set_log_filename(const char *filename); +void gpr_timers_set_log_filename(const char* filename); void gpr_timer_set_enabled(int enabled); @@ -84,22 +80,19 @@ void gpr_timer_set_enabled(int enabled); #endif /* at least one profiler requested. */ -#ifdef __cplusplus -} - #if (defined(GRPC_STAP_PROFILER) + defined(GRPC_BASIC_PROFILER) + \ defined(GRPC_CUSTOM_PROFILER)) namespace grpc { class ProfileScope { public: - ProfileScope(const char *desc, bool important, const char *file, int line) + ProfileScope(const char* desc, bool important, const char* file, int line) : desc_(desc) { gpr_timer_begin(desc_, important ? 1 : 0, file, line); } ~ProfileScope() { gpr_timer_end(desc_, 0, "n/a", 0); } private: - const char *const desc_; + const char* const desc_; }; } // namespace grpc @@ -111,6 +104,5 @@ class ProfileScope { do { \ } while (false) #endif -#endif #endif /* GRPC_CORE_LIB_PROFILING_TIMERS_H */ diff --git a/src/core/lib/security/context/security_context.cc b/src/core/lib/security/context/security_context.cc index 31d800b9b46..19c6148e434 100644 --- a/src/core/lib/security/context/security_context.cc +++ b/src/core/lib/security/context/security_context.cc @@ -29,26 +29,24 @@ #include #include -#ifndef NDEBUG -grpc_tracer_flag grpc_trace_auth_context_refcount = - GRPC_TRACER_INITIALIZER(false, "auth_context_refcount"); -#endif +grpc_core::DebugOnlyTraceFlag grpc_trace_auth_context_refcount( + false, "auth_context_refcount"); /* --- grpc_call --- */ -grpc_call_error grpc_call_set_credentials(grpc_call *call, - grpc_call_credentials *creds) { +grpc_call_error grpc_call_set_credentials(grpc_call* call, + grpc_call_credentials* creds) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - grpc_client_security_context *ctx = NULL; + grpc_client_security_context* ctx = nullptr; GRPC_API_TRACE("grpc_call_set_credentials(call=%p, creds=%p)", 2, (call, creds)); if (!grpc_call_is_client(call)) { gpr_log(GPR_ERROR, "Method is client-side only."); return GRPC_CALL_ERROR_NOT_ON_SERVER; } - ctx = (grpc_client_security_context *)grpc_call_context_get( + ctx = (grpc_client_security_context*)grpc_call_context_get( call, GRPC_CONTEXT_SECURITY); - if (ctx == NULL) { + if (ctx == nullptr) { ctx = grpc_client_security_context_create(); ctx->creds = grpc_call_credentials_ref(creds); grpc_call_context_set(call, GRPC_CONTEXT_SECURITY, ctx, @@ -61,37 +59,37 @@ grpc_call_error grpc_call_set_credentials(grpc_call *call, return GRPC_CALL_OK; } -grpc_auth_context *grpc_call_auth_context(grpc_call *call) { - void *sec_ctx = grpc_call_context_get(call, GRPC_CONTEXT_SECURITY); +grpc_auth_context* grpc_call_auth_context(grpc_call* call) { + void* sec_ctx = grpc_call_context_get(call, GRPC_CONTEXT_SECURITY); GRPC_API_TRACE("grpc_call_auth_context(call=%p)", 1, (call)); - if (sec_ctx == NULL) return NULL; + if (sec_ctx == nullptr) return nullptr; return grpc_call_is_client(call) ? GRPC_AUTH_CONTEXT_REF( - ((grpc_client_security_context *)sec_ctx)->auth_context, + ((grpc_client_security_context*)sec_ctx)->auth_context, "grpc_call_auth_context client") : GRPC_AUTH_CONTEXT_REF( - ((grpc_server_security_context *)sec_ctx)->auth_context, + ((grpc_server_security_context*)sec_ctx)->auth_context, "grpc_call_auth_context server"); } -void grpc_auth_context_release(grpc_auth_context *context) { +void grpc_auth_context_release(grpc_auth_context* context) { GRPC_API_TRACE("grpc_auth_context_release(context=%p)", 1, (context)); GRPC_AUTH_CONTEXT_UNREF(context, "grpc_auth_context_unref"); } /* --- grpc_client_security_context --- */ -grpc_client_security_context *grpc_client_security_context_create(void) { - return (grpc_client_security_context *)gpr_zalloc( +grpc_client_security_context* grpc_client_security_context_create(void) { + return (grpc_client_security_context*)gpr_zalloc( sizeof(grpc_client_security_context)); } -void grpc_client_security_context_destroy(void *ctx) { +void grpc_client_security_context_destroy(void* ctx) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - grpc_client_security_context *c = (grpc_client_security_context *)ctx; + grpc_client_security_context* c = (grpc_client_security_context*)ctx; grpc_call_credentials_unref(&exec_ctx, c->creds); GRPC_AUTH_CONTEXT_UNREF(c->auth_context, "client_security_context"); - if (c->extension.instance != NULL && c->extension.destroy != NULL) { + if (c->extension.instance != nullptr && c->extension.destroy != nullptr) { c->extension.destroy(c->extension.instance); } gpr_free(ctx); @@ -100,15 +98,15 @@ void grpc_client_security_context_destroy(void *ctx) { /* --- grpc_server_security_context --- */ -grpc_server_security_context *grpc_server_security_context_create(void) { - return (grpc_server_security_context *)gpr_zalloc( +grpc_server_security_context* grpc_server_security_context_create(void) { + return (grpc_server_security_context*)gpr_zalloc( sizeof(grpc_server_security_context)); } -void grpc_server_security_context_destroy(void *ctx) { - grpc_server_security_context *c = (grpc_server_security_context *)ctx; +void grpc_server_security_context_destroy(void* ctx) { + grpc_server_security_context* c = (grpc_server_security_context*)ctx; GRPC_AUTH_CONTEXT_UNREF(c->auth_context, "server_security_context"); - if (c->extension.instance != NULL && c->extension.destroy != NULL) { + if (c->extension.instance != nullptr && c->extension.destroy != nullptr) { c->extension.destroy(c->extension.instance); } gpr_free(ctx); @@ -116,13 +114,13 @@ void grpc_server_security_context_destroy(void *ctx) { /* --- grpc_auth_context --- */ -static grpc_auth_property_iterator empty_iterator = {NULL, 0, NULL}; +static grpc_auth_property_iterator empty_iterator = {nullptr, 0, nullptr}; -grpc_auth_context *grpc_auth_context_create(grpc_auth_context *chained) { - grpc_auth_context *ctx = - (grpc_auth_context *)gpr_zalloc(sizeof(grpc_auth_context)); +grpc_auth_context* grpc_auth_context_create(grpc_auth_context* chained) { + grpc_auth_context* ctx = + (grpc_auth_context*)gpr_zalloc(sizeof(grpc_auth_context)); gpr_ref_init(&ctx->refcount, 1); - if (chained != NULL) { + if (chained != nullptr) { ctx->chained = GRPC_AUTH_CONTEXT_REF(chained, "chained"); ctx->peer_identity_property_name = ctx->chained->peer_identity_property_name; @@ -131,18 +129,18 @@ grpc_auth_context *grpc_auth_context_create(grpc_auth_context *chained) { } #ifndef NDEBUG -grpc_auth_context *grpc_auth_context_ref(grpc_auth_context *ctx, - const char *file, int line, - const char *reason) { - if (ctx == NULL) return NULL; - if (GRPC_TRACER_ON(grpc_trace_auth_context_refcount)) { +grpc_auth_context* grpc_auth_context_ref(grpc_auth_context* ctx, + const char* file, int line, + const char* reason) { + if (ctx == nullptr) return nullptr; + if (grpc_trace_auth_context_refcount.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&ctx->refcount.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "AUTH_CONTEXT:%p ref %" PRIdPTR " -> %" PRIdPTR " %s", ctx, val, val + 1, reason); } #else -grpc_auth_context *grpc_auth_context_ref(grpc_auth_context *ctx) { +grpc_auth_context* grpc_auth_context_ref(grpc_auth_context* ctx) { if (ctx == NULL) return NULL; #endif gpr_ref(&ctx->refcount); @@ -150,23 +148,23 @@ grpc_auth_context *grpc_auth_context_ref(grpc_auth_context *ctx) { } #ifndef NDEBUG -void grpc_auth_context_unref(grpc_auth_context *ctx, const char *file, int line, - const char *reason) { - if (ctx == NULL) return; - if (GRPC_TRACER_ON(grpc_trace_auth_context_refcount)) { +void grpc_auth_context_unref(grpc_auth_context* ctx, const char* file, int line, + const char* reason) { + if (ctx == nullptr) return; + if (grpc_trace_auth_context_refcount.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&ctx->refcount.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "AUTH_CONTEXT:%p unref %" PRIdPTR " -> %" PRIdPTR " %s", ctx, val, val - 1, reason); } #else -void grpc_auth_context_unref(grpc_auth_context *ctx) { +void grpc_auth_context_unref(grpc_auth_context* ctx) { if (ctx == NULL) return; #endif if (gpr_unref(&ctx->refcount)) { size_t i; GRPC_AUTH_CONTEXT_UNREF(ctx->chained, "chained"); - if (ctx->properties.array != NULL) { + if (ctx->properties.array != nullptr) { for (i = 0; i < ctx->properties.count; i++) { grpc_auth_property_reset(&ctx->properties.array[i]); } @@ -176,59 +174,59 @@ void grpc_auth_context_unref(grpc_auth_context *ctx) { } } -const char *grpc_auth_context_peer_identity_property_name( - const grpc_auth_context *ctx) { +const char* grpc_auth_context_peer_identity_property_name( + const grpc_auth_context* ctx) { GRPC_API_TRACE("grpc_auth_context_peer_identity_property_name(ctx=%p)", 1, (ctx)); return ctx->peer_identity_property_name; } -int grpc_auth_context_set_peer_identity_property_name(grpc_auth_context *ctx, - const char *name) { +int grpc_auth_context_set_peer_identity_property_name(grpc_auth_context* ctx, + const char* name) { grpc_auth_property_iterator it = grpc_auth_context_find_properties_by_name(ctx, name); - const grpc_auth_property *prop = grpc_auth_property_iterator_next(&it); + const grpc_auth_property* prop = grpc_auth_property_iterator_next(&it); GRPC_API_TRACE( "grpc_auth_context_set_peer_identity_property_name(ctx=%p, name=%s)", 2, (ctx, name)); - if (prop == NULL) { + if (prop == nullptr) { gpr_log(GPR_ERROR, "Property name %s not found in auth context.", - name != NULL ? name : "NULL"); + name != nullptr ? name : "NULL"); return 0; } ctx->peer_identity_property_name = prop->name; return 1; } -int grpc_auth_context_peer_is_authenticated(const grpc_auth_context *ctx) { +int grpc_auth_context_peer_is_authenticated(const grpc_auth_context* ctx) { GRPC_API_TRACE("grpc_auth_context_peer_is_authenticated(ctx=%p)", 1, (ctx)); - return ctx->peer_identity_property_name == NULL ? 0 : 1; + return ctx->peer_identity_property_name == nullptr ? 0 : 1; } grpc_auth_property_iterator grpc_auth_context_property_iterator( - const grpc_auth_context *ctx) { + const grpc_auth_context* ctx) { grpc_auth_property_iterator it = empty_iterator; GRPC_API_TRACE("grpc_auth_context_property_iterator(ctx=%p)", 1, (ctx)); - if (ctx == NULL) return it; + if (ctx == nullptr) return it; it.ctx = ctx; return it; } -const grpc_auth_property *grpc_auth_property_iterator_next( - grpc_auth_property_iterator *it) { +const grpc_auth_property* grpc_auth_property_iterator_next( + grpc_auth_property_iterator* it) { GRPC_API_TRACE("grpc_auth_property_iterator_next(it=%p)", 1, (it)); - if (it == NULL || it->ctx == NULL) return NULL; + if (it == nullptr || it->ctx == nullptr) return nullptr; while (it->index == it->ctx->properties.count) { - if (it->ctx->chained == NULL) return NULL; + if (it->ctx->chained == nullptr) return nullptr; it->ctx = it->ctx->chained; it->index = 0; } - if (it->name == NULL) { + if (it->name == nullptr) { return &it->ctx->properties.array[it->index++]; } else { while (it->index < it->ctx->properties.count) { - const grpc_auth_property *prop = &it->ctx->properties.array[it->index++]; - GPR_ASSERT(prop->name != NULL); + const grpc_auth_property* prop = &it->ctx->properties.array[it->index++]; + GPR_ASSERT(prop->name != nullptr); if (strcmp(it->name, prop->name) == 0) { return prop; } @@ -239,55 +237,56 @@ const grpc_auth_property *grpc_auth_property_iterator_next( } grpc_auth_property_iterator grpc_auth_context_find_properties_by_name( - const grpc_auth_context *ctx, const char *name) { + const grpc_auth_context* ctx, const char* name) { grpc_auth_property_iterator it = empty_iterator; GRPC_API_TRACE("grpc_auth_context_find_properties_by_name(ctx=%p, name=%s)", 2, (ctx, name)); - if (ctx == NULL || name == NULL) return empty_iterator; + if (ctx == nullptr || name == nullptr) return empty_iterator; it.ctx = ctx; it.name = name; return it; } grpc_auth_property_iterator grpc_auth_context_peer_identity( - const grpc_auth_context *ctx) { + const grpc_auth_context* ctx) { GRPC_API_TRACE("grpc_auth_context_peer_identity(ctx=%p)", 1, (ctx)); - if (ctx == NULL) return empty_iterator; + if (ctx == nullptr) return empty_iterator; return grpc_auth_context_find_properties_by_name( ctx, ctx->peer_identity_property_name); } -static void ensure_auth_context_capacity(grpc_auth_context *ctx) { +static void ensure_auth_context_capacity(grpc_auth_context* ctx) { if (ctx->properties.count == ctx->properties.capacity) { ctx->properties.capacity = GPR_MAX(ctx->properties.capacity + 8, ctx->properties.capacity * 2); - ctx->properties.array = (grpc_auth_property *)gpr_realloc( + ctx->properties.array = (grpc_auth_property*)gpr_realloc( ctx->properties.array, ctx->properties.capacity * sizeof(grpc_auth_property)); } } -void grpc_auth_context_add_property(grpc_auth_context *ctx, const char *name, - const char *value, size_t value_length) { - grpc_auth_property *prop; +void grpc_auth_context_add_property(grpc_auth_context* ctx, const char* name, + const char* value, size_t value_length) { + grpc_auth_property* prop; GRPC_API_TRACE( "grpc_auth_context_add_property(ctx=%p, name=%s, value=%*.*s, " "value_length=%lu)", - 6, (ctx, name, (int)value_length, (int)value_length, value, - (unsigned long)value_length)); + 6, + (ctx, name, (int)value_length, (int)value_length, value, + (unsigned long)value_length)); ensure_auth_context_capacity(ctx); prop = &ctx->properties.array[ctx->properties.count++]; prop->name = gpr_strdup(name); - prop->value = (char *)gpr_malloc(value_length + 1); + prop->value = (char*)gpr_malloc(value_length + 1); memcpy(prop->value, value, value_length); prop->value[value_length] = '\0'; prop->value_length = value_length; } -void grpc_auth_context_add_cstring_property(grpc_auth_context *ctx, - const char *name, - const char *value) { - grpc_auth_property *prop; +void grpc_auth_context_add_cstring_property(grpc_auth_context* ctx, + const char* name, + const char* value) { + grpc_auth_property* prop; GRPC_API_TRACE( "grpc_auth_context_add_cstring_property(ctx=%p, name=%s, value=%s)", 3, (ctx, name, value)); @@ -298,49 +297,49 @@ void grpc_auth_context_add_cstring_property(grpc_auth_context *ctx, prop->value_length = strlen(value); } -void grpc_auth_property_reset(grpc_auth_property *property) { +void grpc_auth_property_reset(grpc_auth_property* property) { gpr_free(property->name); gpr_free(property->value); memset(property, 0, sizeof(grpc_auth_property)); } -static void auth_context_pointer_arg_destroy(grpc_exec_ctx *exec_ctx, void *p) { - GRPC_AUTH_CONTEXT_UNREF((grpc_auth_context *)p, "auth_context_pointer_arg"); +static void auth_context_pointer_arg_destroy(grpc_exec_ctx* exec_ctx, void* p) { + GRPC_AUTH_CONTEXT_UNREF((grpc_auth_context*)p, "auth_context_pointer_arg"); } -static void *auth_context_pointer_arg_copy(void *p) { - return GRPC_AUTH_CONTEXT_REF((grpc_auth_context *)p, +static void* auth_context_pointer_arg_copy(void* p) { + return GRPC_AUTH_CONTEXT_REF((grpc_auth_context*)p, "auth_context_pointer_arg"); } -static int auth_context_pointer_cmp(void *a, void *b) { return GPR_ICMP(a, b); } +static int auth_context_pointer_cmp(void* a, void* b) { return GPR_ICMP(a, b); } static const grpc_arg_pointer_vtable auth_context_pointer_vtable = { auth_context_pointer_arg_copy, auth_context_pointer_arg_destroy, auth_context_pointer_cmp}; -grpc_arg grpc_auth_context_to_arg(grpc_auth_context *p) { - return grpc_channel_arg_pointer_create((char *)GRPC_AUTH_CONTEXT_ARG, p, +grpc_arg grpc_auth_context_to_arg(grpc_auth_context* p) { + return grpc_channel_arg_pointer_create((char*)GRPC_AUTH_CONTEXT_ARG, p, &auth_context_pointer_vtable); } -grpc_auth_context *grpc_auth_context_from_arg(const grpc_arg *arg) { - if (strcmp(arg->key, GRPC_AUTH_CONTEXT_ARG) != 0) return NULL; +grpc_auth_context* grpc_auth_context_from_arg(const grpc_arg* arg) { + if (strcmp(arg->key, GRPC_AUTH_CONTEXT_ARG) != 0) return nullptr; if (arg->type != GRPC_ARG_POINTER) { gpr_log(GPR_ERROR, "Invalid type %d for arg %s", arg->type, GRPC_AUTH_CONTEXT_ARG); - return NULL; + return nullptr; } - return (grpc_auth_context *)arg->value.pointer.p; + return (grpc_auth_context*)arg->value.pointer.p; } -grpc_auth_context *grpc_find_auth_context_in_args( - const grpc_channel_args *args) { +grpc_auth_context* grpc_find_auth_context_in_args( + const grpc_channel_args* args) { size_t i; - if (args == NULL) return NULL; + if (args == nullptr) return nullptr; for (i = 0; i < args->num_args; i++) { - grpc_auth_context *p = grpc_auth_context_from_arg(&args->args[i]); - if (p != NULL) return p; + grpc_auth_context* p = grpc_auth_context_from_arg(&args->args[i]); + if (p != nullptr) return p; } - return NULL; + return nullptr; } diff --git a/src/core/lib/security/context/security_context.h b/src/core/lib/security/context/security_context.h index 0df39257a7a..34f8c2487eb 100644 --- a/src/core/lib/security/context/security_context.h +++ b/src/core/lib/security/context/security_context.h @@ -22,13 +22,7 @@ #include "src/core/lib/iomgr/pollset.h" #include "src/core/lib/security/credentials/credentials.h" -#ifndef NDEBUG -extern grpc_tracer_flag grpc_trace_auth_context_refcount; -#endif - -#ifdef __cplusplus -extern "C" { -#endif +extern grpc_core::DebugOnlyTraceFlag grpc_trace_auth_context_refcount; /* --- grpc_auth_context --- @@ -37,21 +31,21 @@ extern "C" { /* Property names are always NULL terminated. */ typedef struct { - grpc_auth_property *array; + grpc_auth_property* array; size_t count; size_t capacity; } grpc_auth_property_array; struct grpc_auth_context { - struct grpc_auth_context *chained; + struct grpc_auth_context* chained; grpc_auth_property_array properties; gpr_refcount refcount; - const char *peer_identity_property_name; - grpc_pollset *pollset; + const char* peer_identity_property_name; + grpc_pollset* pollset; }; /* Creation. */ -grpc_auth_context *grpc_auth_context_create(grpc_auth_context *chained); +grpc_auth_context* grpc_auth_context_create(grpc_auth_context* chained); /* Refcounting. */ #ifndef NDEBUG @@ -59,19 +53,19 @@ grpc_auth_context *grpc_auth_context_create(grpc_auth_context *chained); grpc_auth_context_ref((p), __FILE__, __LINE__, (r)) #define GRPC_AUTH_CONTEXT_UNREF(p, r) \ grpc_auth_context_unref((p), __FILE__, __LINE__, (r)) -grpc_auth_context *grpc_auth_context_ref(grpc_auth_context *policy, - const char *file, int line, - const char *reason); -void grpc_auth_context_unref(grpc_auth_context *policy, const char *file, - int line, const char *reason); +grpc_auth_context* grpc_auth_context_ref(grpc_auth_context* policy, + const char* file, int line, + const char* reason); +void grpc_auth_context_unref(grpc_auth_context* policy, const char* file, + int line, const char* reason); #else #define GRPC_AUTH_CONTEXT_REF(p, r) grpc_auth_context_ref((p)) #define GRPC_AUTH_CONTEXT_UNREF(p, r) grpc_auth_context_unref((p)) -grpc_auth_context *grpc_auth_context_ref(grpc_auth_context *policy); -void grpc_auth_context_unref(grpc_auth_context *policy); +grpc_auth_context* grpc_auth_context_ref(grpc_auth_context* policy); +void grpc_auth_context_unref(grpc_auth_context* policy); #endif -void grpc_auth_property_reset(grpc_auth_property *property); +void grpc_auth_property_reset(grpc_auth_property* property); /* --- grpc_security_context_extension --- @@ -79,8 +73,8 @@ void grpc_auth_property_reset(grpc_auth_property *property); later by a higher level method on a grpc_call object. */ typedef struct { - void *instance; - void (*destroy)(void *); + void* instance; + void (*destroy)(void*); } grpc_security_context_extension; /* --- grpc_client_security_context --- @@ -88,36 +82,32 @@ typedef struct { Internal client-side security context. */ typedef struct { - grpc_call_credentials *creds; - grpc_auth_context *auth_context; + grpc_call_credentials* creds; + grpc_auth_context* auth_context; grpc_security_context_extension extension; } grpc_client_security_context; -grpc_client_security_context *grpc_client_security_context_create(void); -void grpc_client_security_context_destroy(void *ctx); +grpc_client_security_context* grpc_client_security_context_create(void); +void grpc_client_security_context_destroy(void* ctx); /* --- grpc_server_security_context --- Internal server-side security context. */ typedef struct { - grpc_auth_context *auth_context; + grpc_auth_context* auth_context; grpc_security_context_extension extension; } grpc_server_security_context; -grpc_server_security_context *grpc_server_security_context_create(void); -void grpc_server_security_context_destroy(void *ctx); +grpc_server_security_context* grpc_server_security_context_create(void); +void grpc_server_security_context_destroy(void* ctx); /* --- Channel args for auth context --- */ #define GRPC_AUTH_CONTEXT_ARG "grpc.auth_context" -grpc_arg grpc_auth_context_to_arg(grpc_auth_context *c); -grpc_auth_context *grpc_auth_context_from_arg(const grpc_arg *arg); -grpc_auth_context *grpc_find_auth_context_in_args( - const grpc_channel_args *args); - -#ifdef __cplusplus -} -#endif +grpc_arg grpc_auth_context_to_arg(grpc_auth_context* c); +grpc_auth_context* grpc_auth_context_from_arg(const grpc_arg* arg); +grpc_auth_context* grpc_find_auth_context_in_args( + const grpc_channel_args* args); #endif /* GRPC_CORE_LIB_SECURITY_CONTEXT_SECURITY_CONTEXT_H */ diff --git a/src/core/lib/security/credentials/composite/composite_credentials.cc b/src/core/lib/security/credentials/composite/composite_credentials.cc index 779300ac078..93dd721240c 100644 --- a/src/core/lib/security/credentials/composite/composite_credentials.cc +++ b/src/core/lib/security/credentials/composite/composite_credentials.cc @@ -30,32 +30,32 @@ /* -- Composite call credentials. -- */ typedef struct { - grpc_composite_call_credentials *composite_creds; + grpc_composite_call_credentials* composite_creds; size_t creds_index; - grpc_polling_entity *pollent; + grpc_polling_entity* pollent; grpc_auth_metadata_context auth_md_context; - grpc_credentials_mdelem_array *md_array; - grpc_closure *on_request_metadata; + grpc_credentials_mdelem_array* md_array; + grpc_closure* on_request_metadata; grpc_closure internal_on_request_metadata; } grpc_composite_call_credentials_metadata_context; -static void composite_call_destruct(grpc_exec_ctx *exec_ctx, - grpc_call_credentials *creds) { - grpc_composite_call_credentials *c = (grpc_composite_call_credentials *)creds; +static void composite_call_destruct(grpc_exec_ctx* exec_ctx, + grpc_call_credentials* creds) { + grpc_composite_call_credentials* c = (grpc_composite_call_credentials*)creds; for (size_t i = 0; i < c->inner.num_creds; i++) { grpc_call_credentials_unref(exec_ctx, c->inner.creds_array[i]); } gpr_free(c->inner.creds_array); } -static void composite_call_metadata_cb(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_composite_call_credentials_metadata_context *ctx = - (grpc_composite_call_credentials_metadata_context *)arg; +static void composite_call_metadata_cb(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_composite_call_credentials_metadata_context* ctx = + (grpc_composite_call_credentials_metadata_context*)arg; if (error == GRPC_ERROR_NONE) { /* See if we need to get some more metadata. */ if (ctx->creds_index < ctx->composite_creds->inner.num_creds) { - grpc_call_credentials *inner_creds = + grpc_call_credentials* inner_creds = ctx->composite_creds->inner.creds_array[ctx->creds_index++]; if (grpc_call_credentials_get_request_metadata( exec_ctx, inner_creds, ctx->pollent, ctx->auth_md_context, @@ -73,13 +73,13 @@ static void composite_call_metadata_cb(grpc_exec_ctx *exec_ctx, void *arg, } static bool composite_call_get_request_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_credentials *creds, - grpc_polling_entity *pollent, grpc_auth_metadata_context auth_md_context, - grpc_credentials_mdelem_array *md_array, grpc_closure *on_request_metadata, - grpc_error **error) { - grpc_composite_call_credentials *c = (grpc_composite_call_credentials *)creds; - grpc_composite_call_credentials_metadata_context *ctx; - ctx = (grpc_composite_call_credentials_metadata_context *)gpr_zalloc( + grpc_exec_ctx* exec_ctx, grpc_call_credentials* creds, + grpc_polling_entity* pollent, grpc_auth_metadata_context auth_md_context, + grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata, + grpc_error** error) { + grpc_composite_call_credentials* c = (grpc_composite_call_credentials*)creds; + grpc_composite_call_credentials_metadata_context* ctx; + ctx = (grpc_composite_call_credentials_metadata_context*)gpr_zalloc( sizeof(grpc_composite_call_credentials_metadata_context)); ctx->composite_creds = c; ctx->pollent = pollent; @@ -90,7 +90,7 @@ static bool composite_call_get_request_metadata( composite_call_metadata_cb, ctx, grpc_schedule_on_exec_ctx); bool synchronous = true; while (ctx->creds_index < ctx->composite_creds->inner.num_creds) { - grpc_call_credentials *inner_creds = + grpc_call_credentials* inner_creds = ctx->composite_creds->inner.creds_array[ctx->creds_index++]; if (grpc_call_credentials_get_request_metadata( exec_ctx, inner_creds, ctx->pollent, ctx->auth_md_context, @@ -106,9 +106,9 @@ static bool composite_call_get_request_metadata( } static void composite_call_cancel_get_request_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_credentials *creds, - grpc_credentials_mdelem_array *md_array, grpc_error *error) { - grpc_composite_call_credentials *c = (grpc_composite_call_credentials *)creds; + grpc_exec_ctx* exec_ctx, grpc_call_credentials* creds, + grpc_credentials_mdelem_array* md_array, grpc_error* error) { + grpc_composite_call_credentials* c = (grpc_composite_call_credentials*)creds; for (size_t i = 0; i < c->inner.num_creds; ++i) { grpc_call_credentials_cancel_get_request_metadata( exec_ctx, c->inner.creds_array[i], md_array, GRPC_ERROR_REF(error)); @@ -121,9 +121,9 @@ static grpc_call_credentials_vtable composite_call_credentials_vtable = { composite_call_cancel_get_request_metadata}; static grpc_call_credentials_array get_creds_array( - grpc_call_credentials **creds_addr) { + grpc_call_credentials** creds_addr) { grpc_call_credentials_array result; - grpc_call_credentials *creds = *creds_addr; + grpc_call_credentials* creds = *creds_addr; result.creds_array = creds_addr; result.num_creds = 1; if (strcmp(creds->type, GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) == 0) { @@ -132,22 +132,22 @@ static grpc_call_credentials_array get_creds_array( return result; } -grpc_call_credentials *grpc_composite_call_credentials_create( - grpc_call_credentials *creds1, grpc_call_credentials *creds2, - void *reserved) { +grpc_call_credentials* grpc_composite_call_credentials_create( + grpc_call_credentials* creds1, grpc_call_credentials* creds2, + void* reserved) { size_t i; size_t creds_array_byte_size; grpc_call_credentials_array creds1_array; grpc_call_credentials_array creds2_array; - grpc_composite_call_credentials *c; + grpc_composite_call_credentials* c; GRPC_API_TRACE( "grpc_composite_call_credentials_create(creds1=%p, creds2=%p, " "reserved=%p)", 3, (creds1, creds2, reserved)); - GPR_ASSERT(reserved == NULL); - GPR_ASSERT(creds1 != NULL); - GPR_ASSERT(creds2 != NULL); - c = (grpc_composite_call_credentials *)gpr_zalloc( + GPR_ASSERT(reserved == nullptr); + GPR_ASSERT(creds1 != nullptr); + GPR_ASSERT(creds2 != nullptr); + c = (grpc_composite_call_credentials*)gpr_zalloc( sizeof(grpc_composite_call_credentials)); c->base.type = GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE; c->base.vtable = &composite_call_credentials_vtable; @@ -155,76 +155,77 @@ grpc_call_credentials *grpc_composite_call_credentials_create( creds1_array = get_creds_array(&creds1); creds2_array = get_creds_array(&creds2); c->inner.num_creds = creds1_array.num_creds + creds2_array.num_creds; - creds_array_byte_size = c->inner.num_creds * sizeof(grpc_call_credentials *); + creds_array_byte_size = c->inner.num_creds * sizeof(grpc_call_credentials*); c->inner.creds_array = - (grpc_call_credentials **)gpr_zalloc(creds_array_byte_size); + (grpc_call_credentials**)gpr_zalloc(creds_array_byte_size); for (i = 0; i < creds1_array.num_creds; i++) { - grpc_call_credentials *cur_creds = creds1_array.creds_array[i]; + grpc_call_credentials* cur_creds = creds1_array.creds_array[i]; c->inner.creds_array[i] = grpc_call_credentials_ref(cur_creds); } for (i = 0; i < creds2_array.num_creds; i++) { - grpc_call_credentials *cur_creds = creds2_array.creds_array[i]; + grpc_call_credentials* cur_creds = creds2_array.creds_array[i]; c->inner.creds_array[i + creds1_array.num_creds] = grpc_call_credentials_ref(cur_creds); } return &c->base; } -const grpc_call_credentials_array * -grpc_composite_call_credentials_get_credentials(grpc_call_credentials *creds) { - const grpc_composite_call_credentials *c = - (const grpc_composite_call_credentials *)creds; +const grpc_call_credentials_array* +grpc_composite_call_credentials_get_credentials(grpc_call_credentials* creds) { + const grpc_composite_call_credentials* c = + (const grpc_composite_call_credentials*)creds; GPR_ASSERT(strcmp(creds->type, GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) == 0); return &c->inner; } -grpc_call_credentials *grpc_credentials_contains_type( - grpc_call_credentials *creds, const char *type, - grpc_call_credentials **composite_creds) { +grpc_call_credentials* grpc_credentials_contains_type( + grpc_call_credentials* creds, const char* type, + grpc_call_credentials** composite_creds) { size_t i; if (strcmp(creds->type, type) == 0) { - if (composite_creds != NULL) *composite_creds = NULL; + if (composite_creds != nullptr) *composite_creds = nullptr; return creds; } else if (strcmp(creds->type, GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) == 0) { - const grpc_call_credentials_array *inner_creds_array = + const grpc_call_credentials_array* inner_creds_array = grpc_composite_call_credentials_get_credentials(creds); for (i = 0; i < inner_creds_array->num_creds; i++) { if (strcmp(type, inner_creds_array->creds_array[i]->type) == 0) { - if (composite_creds != NULL) *composite_creds = creds; + if (composite_creds != nullptr) *composite_creds = creds; return inner_creds_array->creds_array[i]; } } } - return NULL; + return nullptr; } /* -- Composite channel credentials. -- */ -static void composite_channel_destruct(grpc_exec_ctx *exec_ctx, - grpc_channel_credentials *creds) { - grpc_composite_channel_credentials *c = - (grpc_composite_channel_credentials *)creds; +static void composite_channel_destruct(grpc_exec_ctx* exec_ctx, + grpc_channel_credentials* creds) { + grpc_composite_channel_credentials* c = + (grpc_composite_channel_credentials*)creds; grpc_channel_credentials_unref(exec_ctx, c->inner_creds); grpc_call_credentials_unref(exec_ctx, c->call_creds); } static grpc_security_status composite_channel_create_security_connector( - grpc_exec_ctx *exec_ctx, grpc_channel_credentials *creds, - grpc_call_credentials *call_creds, const char *target, - const grpc_channel_args *args, grpc_channel_security_connector **sc, - grpc_channel_args **new_args) { - grpc_composite_channel_credentials *c = - (grpc_composite_channel_credentials *)creds; + grpc_exec_ctx* exec_ctx, grpc_channel_credentials* creds, + grpc_call_credentials* call_creds, const char* target, + const grpc_channel_args* args, grpc_channel_security_connector** sc, + grpc_channel_args** new_args) { + grpc_composite_channel_credentials* c = + (grpc_composite_channel_credentials*)creds; grpc_security_status status = GRPC_SECURITY_ERROR; - GPR_ASSERT(c->inner_creds != NULL && c->call_creds != NULL && - c->inner_creds->vtable != NULL && - c->inner_creds->vtable->create_security_connector != NULL); + GPR_ASSERT(c->inner_creds != nullptr && c->call_creds != nullptr && + c->inner_creds->vtable != nullptr && + c->inner_creds->vtable->create_security_connector != nullptr); /* If we are passed a call_creds, create a call composite to pass it downstream. */ - if (call_creds != NULL) { - grpc_call_credentials *composite_call_creds = - grpc_composite_call_credentials_create(c->call_creds, call_creds, NULL); + if (call_creds != nullptr) { + grpc_call_credentials* composite_call_creds = + grpc_composite_call_credentials_create(c->call_creds, call_creds, + nullptr); status = c->inner_creds->vtable->create_security_connector( exec_ctx, c->inner_creds, composite_call_creds, target, args, sc, new_args); @@ -236,11 +237,11 @@ static grpc_security_status composite_channel_create_security_connector( return status; } -static grpc_channel_credentials * +static grpc_channel_credentials* composite_channel_duplicate_without_call_credentials( - grpc_channel_credentials *creds) { - grpc_composite_channel_credentials *c = - (grpc_composite_channel_credentials *)creds; + grpc_channel_credentials* creds) { + grpc_composite_channel_credentials* c = + (grpc_composite_channel_credentials*)creds; return grpc_channel_credentials_ref(c->inner_creds); } @@ -248,12 +249,13 @@ static grpc_channel_credentials_vtable composite_channel_credentials_vtable = { composite_channel_destruct, composite_channel_create_security_connector, composite_channel_duplicate_without_call_credentials}; -grpc_channel_credentials *grpc_composite_channel_credentials_create( - grpc_channel_credentials *channel_creds, grpc_call_credentials *call_creds, - void *reserved) { - grpc_composite_channel_credentials *c = - (grpc_composite_channel_credentials *)gpr_zalloc(sizeof(*c)); - GPR_ASSERT(channel_creds != NULL && call_creds != NULL && reserved == NULL); +grpc_channel_credentials* grpc_composite_channel_credentials_create( + grpc_channel_credentials* channel_creds, grpc_call_credentials* call_creds, + void* reserved) { + grpc_composite_channel_credentials* c = + (grpc_composite_channel_credentials*)gpr_zalloc(sizeof(*c)); + GPR_ASSERT(channel_creds != nullptr && call_creds != nullptr && + reserved == nullptr); GRPC_API_TRACE( "grpc_composite_channel_credentials_create(channel_creds=%p, " "call_creds=%p, reserved=%p)", diff --git a/src/core/lib/security/credentials/composite/composite_credentials.h b/src/core/lib/security/credentials/composite/composite_credentials.h index 6e9f9a8f6fa..11990d38ff7 100644 --- a/src/core/lib/security/credentials/composite/composite_credentials.h +++ b/src/core/lib/security/credentials/composite/composite_credentials.h @@ -21,33 +21,29 @@ #include "src/core/lib/security/credentials/credentials.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct { - grpc_call_credentials **creds_array; + grpc_call_credentials** creds_array; size_t num_creds; } grpc_call_credentials_array; -const grpc_call_credentials_array * +const grpc_call_credentials_array* grpc_composite_call_credentials_get_credentials( - grpc_call_credentials *composite_creds); + grpc_call_credentials* composite_creds); /* Returns creds if creds is of the specified type or the inner creds of the specified type (if found), if the creds is of type COMPOSITE. If composite_creds is not NULL, *composite_creds will point to creds if of type COMPOSITE in case of success. */ -grpc_call_credentials *grpc_credentials_contains_type( - grpc_call_credentials *creds, const char *type, - grpc_call_credentials **composite_creds); +grpc_call_credentials* grpc_credentials_contains_type( + grpc_call_credentials* creds, const char* type, + grpc_call_credentials** composite_creds); /* -- Composite channel credentials. -- */ typedef struct { grpc_channel_credentials base; - grpc_channel_credentials *inner_creds; - grpc_call_credentials *call_creds; + grpc_channel_credentials* inner_creds; + grpc_call_credentials* call_creds; } grpc_composite_channel_credentials; /* -- Composite call credentials. -- */ @@ -57,9 +53,5 @@ typedef struct { grpc_call_credentials_array inner; } grpc_composite_call_credentials; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_COMPOSITE_COMPOSITE_CREDENTIALS_H \ - */ + */ diff --git a/src/core/lib/security/credentials/credentials.cc b/src/core/lib/security/credentials/credentials.cc index ebbf3508653..90576e69b91 100644 --- a/src/core/lib/security/credentials/credentials.cc +++ b/src/core/lib/security/credentials/credentials.cc @@ -37,65 +37,65 @@ /* -- Common. -- */ -grpc_credentials_metadata_request *grpc_credentials_metadata_request_create( - grpc_call_credentials *creds) { - grpc_credentials_metadata_request *r = - (grpc_credentials_metadata_request *)gpr_zalloc( +grpc_credentials_metadata_request* grpc_credentials_metadata_request_create( + grpc_call_credentials* creds) { + grpc_credentials_metadata_request* r = + (grpc_credentials_metadata_request*)gpr_zalloc( sizeof(grpc_credentials_metadata_request)); r->creds = grpc_call_credentials_ref(creds); return r; } void grpc_credentials_metadata_request_destroy( - grpc_exec_ctx *exec_ctx, grpc_credentials_metadata_request *r) { + grpc_exec_ctx* exec_ctx, grpc_credentials_metadata_request* r) { grpc_call_credentials_unref(exec_ctx, r->creds); grpc_http_response_destroy(&r->response); gpr_free(r); } -grpc_channel_credentials *grpc_channel_credentials_ref( - grpc_channel_credentials *creds) { - if (creds == NULL) return NULL; +grpc_channel_credentials* grpc_channel_credentials_ref( + grpc_channel_credentials* creds) { + if (creds == nullptr) return nullptr; gpr_ref(&creds->refcount); return creds; } -void grpc_channel_credentials_unref(grpc_exec_ctx *exec_ctx, - grpc_channel_credentials *creds) { - if (creds == NULL) return; +void grpc_channel_credentials_unref(grpc_exec_ctx* exec_ctx, + grpc_channel_credentials* creds) { + if (creds == nullptr) return; if (gpr_unref(&creds->refcount)) { - if (creds->vtable->destruct != NULL) { + if (creds->vtable->destruct != nullptr) { creds->vtable->destruct(exec_ctx, creds); } gpr_free(creds); } } -void grpc_channel_credentials_release(grpc_channel_credentials *creds) { +void grpc_channel_credentials_release(grpc_channel_credentials* creds) { GRPC_API_TRACE("grpc_channel_credentials_release(creds=%p)", 1, (creds)); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_channel_credentials_unref(&exec_ctx, creds); grpc_exec_ctx_finish(&exec_ctx); } -grpc_call_credentials *grpc_call_credentials_ref(grpc_call_credentials *creds) { - if (creds == NULL) return NULL; +grpc_call_credentials* grpc_call_credentials_ref(grpc_call_credentials* creds) { + if (creds == nullptr) return nullptr; gpr_ref(&creds->refcount); return creds; } -void grpc_call_credentials_unref(grpc_exec_ctx *exec_ctx, - grpc_call_credentials *creds) { - if (creds == NULL) return; +void grpc_call_credentials_unref(grpc_exec_ctx* exec_ctx, + grpc_call_credentials* creds) { + if (creds == nullptr) return; if (gpr_unref(&creds->refcount)) { - if (creds->vtable->destruct != NULL) { + if (creds->vtable->destruct != nullptr) { creds->vtable->destruct(exec_ctx, creds); } gpr_free(creds); } } -void grpc_call_credentials_release(grpc_call_credentials *creds) { +void grpc_call_credentials_release(grpc_call_credentials* creds) { GRPC_API_TRACE("grpc_call_credentials_release(creds=%p)", 1, (creds)); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_call_credentials_unref(&exec_ctx, creds); @@ -103,11 +103,11 @@ void grpc_call_credentials_release(grpc_call_credentials *creds) { } bool grpc_call_credentials_get_request_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_credentials *creds, - grpc_polling_entity *pollent, grpc_auth_metadata_context context, - grpc_credentials_mdelem_array *md_array, grpc_closure *on_request_metadata, - grpc_error **error) { - if (creds == NULL || creds->vtable->get_request_metadata == NULL) { + grpc_exec_ctx* exec_ctx, grpc_call_credentials* creds, + grpc_polling_entity* pollent, grpc_auth_metadata_context context, + grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata, + grpc_error** error) { + if (creds == nullptr || creds->vtable->get_request_metadata == nullptr) { return true; } return creds->vtable->get_request_metadata( @@ -115,32 +115,33 @@ bool grpc_call_credentials_get_request_metadata( } void grpc_call_credentials_cancel_get_request_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_credentials *creds, - grpc_credentials_mdelem_array *md_array, grpc_error *error) { - if (creds == NULL || creds->vtable->cancel_get_request_metadata == NULL) { + grpc_exec_ctx* exec_ctx, grpc_call_credentials* creds, + grpc_credentials_mdelem_array* md_array, grpc_error* error) { + if (creds == nullptr || + creds->vtable->cancel_get_request_metadata == nullptr) { return; } creds->vtable->cancel_get_request_metadata(exec_ctx, creds, md_array, error); } grpc_security_status grpc_channel_credentials_create_security_connector( - grpc_exec_ctx *exec_ctx, grpc_channel_credentials *channel_creds, - const char *target, const grpc_channel_args *args, - grpc_channel_security_connector **sc, grpc_channel_args **new_args) { - *new_args = NULL; - if (channel_creds == NULL) { + grpc_exec_ctx* exec_ctx, grpc_channel_credentials* channel_creds, + const char* target, const grpc_channel_args* args, + grpc_channel_security_connector** sc, grpc_channel_args** new_args) { + *new_args = nullptr; + if (channel_creds == nullptr) { return GRPC_SECURITY_ERROR; } - GPR_ASSERT(channel_creds->vtable->create_security_connector != NULL); + GPR_ASSERT(channel_creds->vtable->create_security_connector != nullptr); return channel_creds->vtable->create_security_connector( - exec_ctx, channel_creds, NULL, target, args, sc, new_args); + exec_ctx, channel_creds, nullptr, target, args, sc, new_args); } -grpc_channel_credentials * +grpc_channel_credentials* grpc_channel_credentials_duplicate_without_call_credentials( - grpc_channel_credentials *channel_creds) { - if (channel_creds != NULL && channel_creds->vtable != NULL && - channel_creds->vtable->duplicate_without_call_credentials != NULL) { + grpc_channel_credentials* channel_creds) { + if (channel_creds != nullptr && channel_creds->vtable != nullptr && + channel_creds->vtable->duplicate_without_call_credentials != nullptr) { return channel_creds->vtable->duplicate_without_call_credentials( channel_creds); } else { @@ -148,72 +149,73 @@ grpc_channel_credentials_duplicate_without_call_credentials( } } -static void credentials_pointer_arg_destroy(grpc_exec_ctx *exec_ctx, void *p) { - grpc_channel_credentials_unref(exec_ctx, (grpc_channel_credentials *)p); +static void credentials_pointer_arg_destroy(grpc_exec_ctx* exec_ctx, void* p) { + grpc_channel_credentials_unref(exec_ctx, (grpc_channel_credentials*)p); } -static void *credentials_pointer_arg_copy(void *p) { - return grpc_channel_credentials_ref((grpc_channel_credentials *)p); +static void* credentials_pointer_arg_copy(void* p) { + return grpc_channel_credentials_ref((grpc_channel_credentials*)p); } -static int credentials_pointer_cmp(void *a, void *b) { return GPR_ICMP(a, b); } +static int credentials_pointer_cmp(void* a, void* b) { return GPR_ICMP(a, b); } static const grpc_arg_pointer_vtable credentials_pointer_vtable = { credentials_pointer_arg_copy, credentials_pointer_arg_destroy, credentials_pointer_cmp}; grpc_arg grpc_channel_credentials_to_arg( - grpc_channel_credentials *credentials) { - return grpc_channel_arg_pointer_create((char *)GRPC_ARG_CHANNEL_CREDENTIALS, + grpc_channel_credentials* credentials) { + return grpc_channel_arg_pointer_create((char*)GRPC_ARG_CHANNEL_CREDENTIALS, credentials, &credentials_pointer_vtable); } -grpc_channel_credentials *grpc_channel_credentials_from_arg( - const grpc_arg *arg) { - if (strcmp(arg->key, GRPC_ARG_CHANNEL_CREDENTIALS)) return NULL; +grpc_channel_credentials* grpc_channel_credentials_from_arg( + const grpc_arg* arg) { + if (strcmp(arg->key, GRPC_ARG_CHANNEL_CREDENTIALS)) return nullptr; if (arg->type != GRPC_ARG_POINTER) { gpr_log(GPR_ERROR, "Invalid type %d for arg %s", arg->type, GRPC_ARG_CHANNEL_CREDENTIALS); - return NULL; + return nullptr; } - return (grpc_channel_credentials *)arg->value.pointer.p; + return (grpc_channel_credentials*)arg->value.pointer.p; } -grpc_channel_credentials *grpc_channel_credentials_find_in_args( - const grpc_channel_args *args) { +grpc_channel_credentials* grpc_channel_credentials_find_in_args( + const grpc_channel_args* args) { size_t i; - if (args == NULL) return NULL; + if (args == nullptr) return nullptr; for (i = 0; i < args->num_args; i++) { - grpc_channel_credentials *credentials = + grpc_channel_credentials* credentials = grpc_channel_credentials_from_arg(&args->args[i]); - if (credentials != NULL) return credentials; + if (credentials != nullptr) return credentials; } - return NULL; + return nullptr; } -grpc_server_credentials *grpc_server_credentials_ref( - grpc_server_credentials *creds) { - if (creds == NULL) return NULL; +grpc_server_credentials* grpc_server_credentials_ref( + grpc_server_credentials* creds) { + if (creds == nullptr) return nullptr; gpr_ref(&creds->refcount); return creds; } -void grpc_server_credentials_unref(grpc_exec_ctx *exec_ctx, - grpc_server_credentials *creds) { - if (creds == NULL) return; +void grpc_server_credentials_unref(grpc_exec_ctx* exec_ctx, + grpc_server_credentials* creds) { + if (creds == nullptr) return; if (gpr_unref(&creds->refcount)) { - if (creds->vtable->destruct != NULL) { + if (creds->vtable->destruct != nullptr) { creds->vtable->destruct(exec_ctx, creds); } - if (creds->processor.destroy != NULL && creds->processor.state != NULL) { + if (creds->processor.destroy != nullptr && + creds->processor.state != nullptr) { creds->processor.destroy(creds->processor.state); } gpr_free(creds); } } -void grpc_server_credentials_release(grpc_server_credentials *creds) { +void grpc_server_credentials_release(grpc_server_credentials* creds) { GRPC_API_TRACE("grpc_server_credentials_release(creds=%p)", 1, (creds)); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_server_credentials_unref(&exec_ctx, creds); @@ -221,9 +223,9 @@ void grpc_server_credentials_release(grpc_server_credentials *creds) { } grpc_security_status grpc_server_credentials_create_security_connector( - grpc_exec_ctx *exec_ctx, grpc_server_credentials *creds, - grpc_server_security_connector **sc) { - if (creds == NULL || creds->vtable->create_security_connector == NULL) { + grpc_exec_ctx* exec_ctx, grpc_server_credentials* creds, + grpc_server_security_connector** sc) { + if (creds == nullptr || creds->vtable->create_security_connector == nullptr) { gpr_log(GPR_ERROR, "Server credentials cannot create security context."); return GRPC_SECURITY_ERROR; } @@ -231,29 +233,30 @@ grpc_security_status grpc_server_credentials_create_security_connector( } void grpc_server_credentials_set_auth_metadata_processor( - grpc_server_credentials *creds, grpc_auth_metadata_processor processor) { + grpc_server_credentials* creds, grpc_auth_metadata_processor processor) { GRPC_API_TRACE( "grpc_server_credentials_set_auth_metadata_processor(" "creds=%p, " "processor=grpc_auth_metadata_processor { process: %p, state: %p })", - 3, (creds, (void *)(intptr_t)processor.process, processor.state)); - if (creds == NULL) return; - if (creds->processor.destroy != NULL && creds->processor.state != NULL) { + 3, (creds, (void*)(intptr_t)processor.process, processor.state)); + if (creds == nullptr) return; + if (creds->processor.destroy != nullptr && + creds->processor.state != nullptr) { creds->processor.destroy(creds->processor.state); } creds->processor = processor; } -static void server_credentials_pointer_arg_destroy(grpc_exec_ctx *exec_ctx, - void *p) { - grpc_server_credentials_unref(exec_ctx, (grpc_server_credentials *)p); +static void server_credentials_pointer_arg_destroy(grpc_exec_ctx* exec_ctx, + void* p) { + grpc_server_credentials_unref(exec_ctx, (grpc_server_credentials*)p); } -static void *server_credentials_pointer_arg_copy(void *p) { - return grpc_server_credentials_ref((grpc_server_credentials *)p); +static void* server_credentials_pointer_arg_copy(void* p) { + return grpc_server_credentials_ref((grpc_server_credentials*)p); } -static int server_credentials_pointer_cmp(void *a, void *b) { +static int server_credentials_pointer_cmp(void* a, void* b) { return GPR_ICMP(a, b); } @@ -261,29 +264,29 @@ static const grpc_arg_pointer_vtable cred_ptr_vtable = { server_credentials_pointer_arg_copy, server_credentials_pointer_arg_destroy, server_credentials_pointer_cmp}; -grpc_arg grpc_server_credentials_to_arg(grpc_server_credentials *p) { - return grpc_channel_arg_pointer_create((char *)GRPC_SERVER_CREDENTIALS_ARG, p, +grpc_arg grpc_server_credentials_to_arg(grpc_server_credentials* p) { + return grpc_channel_arg_pointer_create((char*)GRPC_SERVER_CREDENTIALS_ARG, p, &cred_ptr_vtable); } -grpc_server_credentials *grpc_server_credentials_from_arg(const grpc_arg *arg) { - if (strcmp(arg->key, GRPC_SERVER_CREDENTIALS_ARG) != 0) return NULL; +grpc_server_credentials* grpc_server_credentials_from_arg(const grpc_arg* arg) { + if (strcmp(arg->key, GRPC_SERVER_CREDENTIALS_ARG) != 0) return nullptr; if (arg->type != GRPC_ARG_POINTER) { gpr_log(GPR_ERROR, "Invalid type %d for arg %s", arg->type, GRPC_SERVER_CREDENTIALS_ARG); - return NULL; + return nullptr; } - return (grpc_server_credentials *)arg->value.pointer.p; + return (grpc_server_credentials*)arg->value.pointer.p; } -grpc_server_credentials *grpc_find_server_credentials_in_args( - const grpc_channel_args *args) { +grpc_server_credentials* grpc_find_server_credentials_in_args( + const grpc_channel_args* args) { size_t i; - if (args == NULL) return NULL; + if (args == nullptr) return nullptr; for (i = 0; i < args->num_args; i++) { - grpc_server_credentials *p = + grpc_server_credentials* p = grpc_server_credentials_from_arg(&args->args[i]); - if (p != NULL) return p; + if (p != nullptr) return p; } - return NULL; + return nullptr; } diff --git a/src/core/lib/security/credentials/credentials.h b/src/core/lib/security/credentials/credentials.h index 73e39ae039a..bc1bd11c77d 100644 --- a/src/core/lib/security/credentials/credentials.h +++ b/src/core/lib/security/credentials/credentials.h @@ -29,10 +29,6 @@ #include "src/core/lib/iomgr/polling_entity.h" #include "src/core/lib/security/transport/security_connector.h" -#ifdef __cplusplus -extern "C" { -#endif - struct grpc_http_response; /* --- Constants. --- */ @@ -77,13 +73,13 @@ typedef enum { /* --- Google utils --- */ /* It is the caller's responsibility to gpr_free the result if not NULL. */ -char *grpc_get_well_known_google_credentials_file_path(void); +char* grpc_get_well_known_google_credentials_file_path(void); /* Implementation function for the different platforms. */ -char *grpc_get_well_known_google_credentials_file_path_impl(void); +char* grpc_get_well_known_google_credentials_file_path_impl(void); /* Override for testing only. Not thread-safe */ -typedef char *(*grpc_well_known_credentials_path_getter)(void); +typedef char* (*grpc_well_known_credentials_path_getter)(void); void grpc_override_well_known_credentials_path_getter( grpc_well_known_credentials_path_getter getter); @@ -92,172 +88,168 @@ void grpc_override_well_known_credentials_path_getter( #define GRPC_ARG_CHANNEL_CREDENTIALS "grpc.channel_credentials" typedef struct { - void (*destruct)(grpc_exec_ctx *exec_ctx, grpc_channel_credentials *c); + void (*destruct)(grpc_exec_ctx* exec_ctx, grpc_channel_credentials* c); grpc_security_status (*create_security_connector)( - grpc_exec_ctx *exec_ctx, grpc_channel_credentials *c, - grpc_call_credentials *call_creds, const char *target, - const grpc_channel_args *args, grpc_channel_security_connector **sc, - grpc_channel_args **new_args); + grpc_exec_ctx* exec_ctx, grpc_channel_credentials* c, + grpc_call_credentials* call_creds, const char* target, + const grpc_channel_args* args, grpc_channel_security_connector** sc, + grpc_channel_args** new_args); - grpc_channel_credentials *(*duplicate_without_call_credentials)( - grpc_channel_credentials *c); + grpc_channel_credentials* (*duplicate_without_call_credentials)( + grpc_channel_credentials* c); } grpc_channel_credentials_vtable; struct grpc_channel_credentials { - const grpc_channel_credentials_vtable *vtable; - const char *type; + const grpc_channel_credentials_vtable* vtable; + const char* type; gpr_refcount refcount; }; -grpc_channel_credentials *grpc_channel_credentials_ref( - grpc_channel_credentials *creds); -void grpc_channel_credentials_unref(grpc_exec_ctx *exec_ctx, - grpc_channel_credentials *creds); +grpc_channel_credentials* grpc_channel_credentials_ref( + grpc_channel_credentials* creds); +void grpc_channel_credentials_unref(grpc_exec_ctx* exec_ctx, + grpc_channel_credentials* creds); /* Creates a security connector for the channel. May also create new channel args for the channel to be used in place of the passed in const args if returned non NULL. In that case the caller is responsible for destroying new_args after channel creation. */ grpc_security_status grpc_channel_credentials_create_security_connector( - grpc_exec_ctx *exec_ctx, grpc_channel_credentials *creds, - const char *target, const grpc_channel_args *args, - grpc_channel_security_connector **sc, grpc_channel_args **new_args); + grpc_exec_ctx* exec_ctx, grpc_channel_credentials* creds, + const char* target, const grpc_channel_args* args, + grpc_channel_security_connector** sc, grpc_channel_args** new_args); /* Creates a version of the channel credentials without any attached call credentials. This can be used in order to open a channel to a non-trusted gRPC load balancer. */ -grpc_channel_credentials * +grpc_channel_credentials* grpc_channel_credentials_duplicate_without_call_credentials( - grpc_channel_credentials *creds); + grpc_channel_credentials* creds); /* Util to encapsulate the channel credentials in a channel arg. */ -grpc_arg grpc_channel_credentials_to_arg(grpc_channel_credentials *credentials); +grpc_arg grpc_channel_credentials_to_arg(grpc_channel_credentials* credentials); /* Util to get the channel credentials from a channel arg. */ -grpc_channel_credentials *grpc_channel_credentials_from_arg( - const grpc_arg *arg); +grpc_channel_credentials* grpc_channel_credentials_from_arg( + const grpc_arg* arg); /* Util to find the channel credentials from channel args. */ -grpc_channel_credentials *grpc_channel_credentials_find_in_args( - const grpc_channel_args *args); +grpc_channel_credentials* grpc_channel_credentials_find_in_args( + const grpc_channel_args* args); /* --- grpc_credentials_mdelem_array. --- */ typedef struct { - grpc_mdelem *md; + grpc_mdelem* md; size_t size; } grpc_credentials_mdelem_array; /// Takes a new ref to \a md. -void grpc_credentials_mdelem_array_add(grpc_credentials_mdelem_array *list, +void grpc_credentials_mdelem_array_add(grpc_credentials_mdelem_array* list, grpc_mdelem md); /// Appends all elements from \a src to \a dst, taking a new ref to each one. -void grpc_credentials_mdelem_array_append(grpc_credentials_mdelem_array *dst, - grpc_credentials_mdelem_array *src); +void grpc_credentials_mdelem_array_append(grpc_credentials_mdelem_array* dst, + grpc_credentials_mdelem_array* src); -void grpc_credentials_mdelem_array_destroy(grpc_exec_ctx *exec_ctx, - grpc_credentials_mdelem_array *list); +void grpc_credentials_mdelem_array_destroy(grpc_exec_ctx* exec_ctx, + grpc_credentials_mdelem_array* list); /* --- grpc_call_credentials. --- */ typedef struct { - void (*destruct)(grpc_exec_ctx *exec_ctx, grpc_call_credentials *c); - bool (*get_request_metadata)(grpc_exec_ctx *exec_ctx, - grpc_call_credentials *c, - grpc_polling_entity *pollent, + void (*destruct)(grpc_exec_ctx* exec_ctx, grpc_call_credentials* c); + bool (*get_request_metadata)(grpc_exec_ctx* exec_ctx, + grpc_call_credentials* c, + grpc_polling_entity* pollent, grpc_auth_metadata_context context, - grpc_credentials_mdelem_array *md_array, - grpc_closure *on_request_metadata, - grpc_error **error); - void (*cancel_get_request_metadata)(grpc_exec_ctx *exec_ctx, - grpc_call_credentials *c, - grpc_credentials_mdelem_array *md_array, - grpc_error *error); + grpc_credentials_mdelem_array* md_array, + grpc_closure* on_request_metadata, + grpc_error** error); + void (*cancel_get_request_metadata)(grpc_exec_ctx* exec_ctx, + grpc_call_credentials* c, + grpc_credentials_mdelem_array* md_array, + grpc_error* error); } grpc_call_credentials_vtable; struct grpc_call_credentials { - const grpc_call_credentials_vtable *vtable; - const char *type; + const grpc_call_credentials_vtable* vtable; + const char* type; gpr_refcount refcount; }; -grpc_call_credentials *grpc_call_credentials_ref(grpc_call_credentials *creds); -void grpc_call_credentials_unref(grpc_exec_ctx *exec_ctx, - grpc_call_credentials *creds); +grpc_call_credentials* grpc_call_credentials_ref(grpc_call_credentials* creds); +void grpc_call_credentials_unref(grpc_exec_ctx* exec_ctx, + grpc_call_credentials* creds); /// Returns true if completed synchronously, in which case \a error will /// be set to indicate the result. Otherwise, \a on_request_metadata will /// be invoked asynchronously when complete. \a md_array will be populated /// with the resulting metadata once complete. bool grpc_call_credentials_get_request_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_credentials *creds, - grpc_polling_entity *pollent, grpc_auth_metadata_context context, - grpc_credentials_mdelem_array *md_array, grpc_closure *on_request_metadata, - grpc_error **error); + grpc_exec_ctx* exec_ctx, grpc_call_credentials* creds, + grpc_polling_entity* pollent, grpc_auth_metadata_context context, + grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata, + grpc_error** error); /// Cancels a pending asynchronous operation started by /// grpc_call_credentials_get_request_metadata() with the corresponding /// value of \a md_array. void grpc_call_credentials_cancel_get_request_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_credentials *c, - grpc_credentials_mdelem_array *md_array, grpc_error *error); + grpc_exec_ctx* exec_ctx, grpc_call_credentials* c, + grpc_credentials_mdelem_array* md_array, grpc_error* error); /* Metadata-only credentials with the specified key and value where asynchronicity can be simulated for testing. */ -grpc_call_credentials *grpc_md_only_test_credentials_create( - grpc_exec_ctx *exec_ctx, const char *md_key, const char *md_value, +grpc_call_credentials* grpc_md_only_test_credentials_create( + grpc_exec_ctx* exec_ctx, const char* md_key, const char* md_value, bool is_async); /* --- grpc_server_credentials. --- */ typedef struct { - void (*destruct)(grpc_exec_ctx *exec_ctx, grpc_server_credentials *c); + void (*destruct)(grpc_exec_ctx* exec_ctx, grpc_server_credentials* c); grpc_security_status (*create_security_connector)( - grpc_exec_ctx *exec_ctx, grpc_server_credentials *c, - grpc_server_security_connector **sc); + grpc_exec_ctx* exec_ctx, grpc_server_credentials* c, + grpc_server_security_connector** sc); } grpc_server_credentials_vtable; struct grpc_server_credentials { - const grpc_server_credentials_vtable *vtable; - const char *type; + const grpc_server_credentials_vtable* vtable; + const char* type; gpr_refcount refcount; grpc_auth_metadata_processor processor; }; grpc_security_status grpc_server_credentials_create_security_connector( - grpc_exec_ctx *exec_ctx, grpc_server_credentials *creds, - grpc_server_security_connector **sc); + grpc_exec_ctx* exec_ctx, grpc_server_credentials* creds, + grpc_server_security_connector** sc); -grpc_server_credentials *grpc_server_credentials_ref( - grpc_server_credentials *creds); +grpc_server_credentials* grpc_server_credentials_ref( + grpc_server_credentials* creds); -void grpc_server_credentials_unref(grpc_exec_ctx *exec_ctx, - grpc_server_credentials *creds); +void grpc_server_credentials_unref(grpc_exec_ctx* exec_ctx, + grpc_server_credentials* creds); #define GRPC_SERVER_CREDENTIALS_ARG "grpc.server_credentials" -grpc_arg grpc_server_credentials_to_arg(grpc_server_credentials *c); -grpc_server_credentials *grpc_server_credentials_from_arg(const grpc_arg *arg); -grpc_server_credentials *grpc_find_server_credentials_in_args( - const grpc_channel_args *args); +grpc_arg grpc_server_credentials_to_arg(grpc_server_credentials* c); +grpc_server_credentials* grpc_server_credentials_from_arg(const grpc_arg* arg); +grpc_server_credentials* grpc_find_server_credentials_in_args( + const grpc_channel_args* args); /* -- Credentials Metadata Request. -- */ typedef struct { - grpc_call_credentials *creds; + grpc_call_credentials* creds; grpc_http_response response; } grpc_credentials_metadata_request; -grpc_credentials_metadata_request *grpc_credentials_metadata_request_create( - grpc_call_credentials *creds); +grpc_credentials_metadata_request* grpc_credentials_metadata_request_create( + grpc_call_credentials* creds); void grpc_credentials_metadata_request_destroy( - grpc_exec_ctx *exec_ctx, grpc_credentials_metadata_request *r); - -#ifdef __cplusplus -} -#endif + grpc_exec_ctx* exec_ctx, grpc_credentials_metadata_request* r); #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_CREDENTIALS_H */ diff --git a/src/core/lib/security/credentials/credentials_metadata.cc b/src/core/lib/security/credentials/credentials_metadata.cc index 5ba98bda4e0..a3623fa1d68 100644 --- a/src/core/lib/security/credentials/credentials_metadata.cc +++ b/src/core/lib/security/credentials/credentials_metadata.cc @@ -24,7 +24,7 @@ #include "src/core/lib/slice/slice_internal.h" -static void mdelem_list_ensure_capacity(grpc_credentials_mdelem_array *list, +static void mdelem_list_ensure_capacity(grpc_credentials_mdelem_array* list, size_t additional_space_needed) { size_t target_size = list->size + additional_space_needed; // Find the next power of two greater than the target size (i.e., @@ -34,17 +34,17 @@ static void mdelem_list_ensure_capacity(grpc_credentials_mdelem_array *list, new_size *= 2; } list->md = - (grpc_mdelem *)gpr_realloc(list->md, sizeof(grpc_mdelem) * new_size); + (grpc_mdelem*)gpr_realloc(list->md, sizeof(grpc_mdelem) * new_size); } -void grpc_credentials_mdelem_array_add(grpc_credentials_mdelem_array *list, +void grpc_credentials_mdelem_array_add(grpc_credentials_mdelem_array* list, grpc_mdelem md) { mdelem_list_ensure_capacity(list, 1); list->md[list->size++] = GRPC_MDELEM_REF(md); } -void grpc_credentials_mdelem_array_append(grpc_credentials_mdelem_array *dst, - grpc_credentials_mdelem_array *src) { +void grpc_credentials_mdelem_array_append(grpc_credentials_mdelem_array* dst, + grpc_credentials_mdelem_array* src) { mdelem_list_ensure_capacity(dst, src->size); for (size_t i = 0; i < src->size; ++i) { dst->md[dst->size++] = GRPC_MDELEM_REF(src->md[i]); @@ -52,7 +52,7 @@ void grpc_credentials_mdelem_array_append(grpc_credentials_mdelem_array *dst, } void grpc_credentials_mdelem_array_destroy( - grpc_exec_ctx *exec_ctx, grpc_credentials_mdelem_array *list) { + grpc_exec_ctx* exec_ctx, grpc_credentials_mdelem_array* list) { for (size_t i = 0; i < list->size; ++i) { GRPC_MDELEM_UNREF(exec_ctx, list->md[i]); } diff --git a/src/core/lib/security/credentials/fake/fake_credentials.cc b/src/core/lib/security/credentials/fake/fake_credentials.cc index cf10bf24c81..a535a317eec 100644 --- a/src/core/lib/security/credentials/fake/fake_credentials.cc +++ b/src/core/lib/security/credentials/fake/fake_credentials.cc @@ -34,10 +34,10 @@ "grpc.fake_security.expected_targets" static grpc_security_status fake_transport_security_create_security_connector( - grpc_exec_ctx *exec_ctx, grpc_channel_credentials *c, - grpc_call_credentials *call_creds, const char *target, - const grpc_channel_args *args, grpc_channel_security_connector **sc, - grpc_channel_args **new_args) { + grpc_exec_ctx* exec_ctx, grpc_channel_credentials* c, + grpc_call_credentials* call_creds, const char* target, + const grpc_channel_args* args, grpc_channel_security_connector** sc, + grpc_channel_args** new_args) { *sc = grpc_fake_channel_security_connector_create(c, call_creds, target, args); return GRPC_SECURITY_OK; @@ -45,34 +45,34 @@ static grpc_security_status fake_transport_security_create_security_connector( static grpc_security_status fake_transport_security_server_create_security_connector( - grpc_exec_ctx *exec_ctx, grpc_server_credentials *c, - grpc_server_security_connector **sc) { + grpc_exec_ctx* exec_ctx, grpc_server_credentials* c, + grpc_server_security_connector** sc) { *sc = grpc_fake_server_security_connector_create(c); return GRPC_SECURITY_OK; } static grpc_channel_credentials_vtable fake_transport_security_credentials_vtable = { - NULL, fake_transport_security_create_security_connector, NULL}; + nullptr, fake_transport_security_create_security_connector, nullptr}; static grpc_server_credentials_vtable fake_transport_security_server_credentials_vtable = { - NULL, fake_transport_security_server_create_security_connector}; + nullptr, fake_transport_security_server_create_security_connector}; -grpc_channel_credentials *grpc_fake_transport_security_credentials_create( +grpc_channel_credentials* grpc_fake_transport_security_credentials_create( void) { - grpc_channel_credentials *c = - (grpc_channel_credentials *)gpr_zalloc(sizeof(grpc_channel_credentials)); + grpc_channel_credentials* c = + (grpc_channel_credentials*)gpr_zalloc(sizeof(grpc_channel_credentials)); c->type = GRPC_CHANNEL_CREDENTIALS_TYPE_FAKE_TRANSPORT_SECURITY; c->vtable = &fake_transport_security_credentials_vtable; gpr_ref_init(&c->refcount, 1); return c; } -grpc_server_credentials *grpc_fake_transport_security_server_credentials_create( +grpc_server_credentials* grpc_fake_transport_security_server_credentials_create( void) { - grpc_server_credentials *c = - (grpc_server_credentials *)gpr_malloc(sizeof(grpc_server_credentials)); + grpc_server_credentials* c = + (grpc_server_credentials*)gpr_malloc(sizeof(grpc_server_credentials)); memset(c, 0, sizeof(grpc_server_credentials)); c->type = GRPC_CHANNEL_CREDENTIALS_TYPE_FAKE_TRANSPORT_SECURITY; gpr_ref_init(&c->refcount, 1); @@ -80,36 +80,36 @@ grpc_server_credentials *grpc_fake_transport_security_server_credentials_create( return c; } -grpc_arg grpc_fake_transport_expected_targets_arg(char *expected_targets) { +grpc_arg grpc_fake_transport_expected_targets_arg(char* expected_targets) { return grpc_channel_arg_string_create( - (char *)GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS, expected_targets); + (char*)GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS, expected_targets); } -const char *grpc_fake_transport_get_expected_targets( - const grpc_channel_args *args) { - const grpc_arg *expected_target_arg = +const char* grpc_fake_transport_get_expected_targets( + const grpc_channel_args* args) { + const grpc_arg* expected_target_arg = grpc_channel_args_find(args, GRPC_ARG_FAKE_SECURITY_EXPECTED_TARGETS); - if (expected_target_arg != NULL && + if (expected_target_arg != nullptr && expected_target_arg->type == GRPC_ARG_STRING) { return expected_target_arg->value.string; } - return NULL; + return nullptr; } /* -- Metadata-only test credentials. -- */ -static void md_only_test_destruct(grpc_exec_ctx *exec_ctx, - grpc_call_credentials *creds) { - grpc_md_only_test_credentials *c = (grpc_md_only_test_credentials *)creds; +static void md_only_test_destruct(grpc_exec_ctx* exec_ctx, + grpc_call_credentials* creds) { + grpc_md_only_test_credentials* c = (grpc_md_only_test_credentials*)creds; GRPC_MDELEM_UNREF(exec_ctx, c->md); } static bool md_only_test_get_request_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_credentials *creds, - grpc_polling_entity *pollent, grpc_auth_metadata_context context, - grpc_credentials_mdelem_array *md_array, grpc_closure *on_request_metadata, - grpc_error **error) { - grpc_md_only_test_credentials *c = (grpc_md_only_test_credentials *)creds; + grpc_exec_ctx* exec_ctx, grpc_call_credentials* creds, + grpc_polling_entity* pollent, grpc_auth_metadata_context context, + grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata, + grpc_error** error) { + grpc_md_only_test_credentials* c = (grpc_md_only_test_credentials*)creds; grpc_credentials_mdelem_array_add(md_array, c->md); if (c->is_async) { GRPC_CLOSURE_SCHED(exec_ctx, on_request_metadata, GRPC_ERROR_NONE); @@ -119,8 +119,8 @@ static bool md_only_test_get_request_metadata( } static void md_only_test_cancel_get_request_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_credentials *c, - grpc_credentials_mdelem_array *md_array, grpc_error *error) { + grpc_exec_ctx* exec_ctx, grpc_call_credentials* c, + grpc_credentials_mdelem_array* md_array, grpc_error* error) { GRPC_ERROR_UNREF(error); } @@ -128,12 +128,11 @@ static grpc_call_credentials_vtable md_only_test_vtable = { md_only_test_destruct, md_only_test_get_request_metadata, md_only_test_cancel_get_request_metadata}; -grpc_call_credentials *grpc_md_only_test_credentials_create( - grpc_exec_ctx *exec_ctx, const char *md_key, const char *md_value, +grpc_call_credentials* grpc_md_only_test_credentials_create( + grpc_exec_ctx* exec_ctx, const char* md_key, const char* md_value, bool is_async) { - grpc_md_only_test_credentials *c = - (grpc_md_only_test_credentials *)gpr_zalloc( - sizeof(grpc_md_only_test_credentials)); + grpc_md_only_test_credentials* c = (grpc_md_only_test_credentials*)gpr_zalloc( + sizeof(grpc_md_only_test_credentials)); c->base.type = GRPC_CALL_CREDENTIALS_TYPE_OAUTH2; c->base.vtable = &md_only_test_vtable; gpr_ref_init(&c->base.refcount, 1); diff --git a/src/core/lib/security/credentials/fake/fake_credentials.h b/src/core/lib/security/credentials/fake/fake_credentials.h index ed3f893c58f..0e9ff155d89 100644 --- a/src/core/lib/security/credentials/fake/fake_credentials.h +++ b/src/core/lib/security/credentials/fake/fake_credentials.h @@ -21,17 +21,13 @@ #include "src/core/lib/security/credentials/credentials.h" -#ifdef __cplusplus -extern "C" { -#endif - /* -- Fake transport security credentials. -- */ /* Creates a fake transport security credentials object for testing. */ -grpc_channel_credentials *grpc_fake_transport_security_credentials_create(void); +grpc_channel_credentials* grpc_fake_transport_security_credentials_create(void); /* Creates a fake server transport security credentials object for testing. */ -grpc_server_credentials *grpc_fake_transport_security_server_credentials_create( +grpc_server_credentials* grpc_fake_transport_security_server_credentials_create( void); /* Used to verify the target names given to the fake transport security @@ -46,11 +42,11 @@ grpc_server_credentials *grpc_fake_transport_security_server_credentials_create( * That is to say, LB channels have a heading list of LB targets separated from * the list of backend targets by a semicolon. For non-LB channels, only the * latter is present. */ -grpc_arg grpc_fake_transport_expected_targets_arg(char *expected_targets); +grpc_arg grpc_fake_transport_expected_targets_arg(char* expected_targets); /* Return the value associated with the expected targets channel arg or NULL */ -const char *grpc_fake_transport_get_expected_targets( - const grpc_channel_args *args); +const char* grpc_fake_transport_get_expected_targets( + const grpc_channel_args* args); /* -- Metadata-only Test credentials. -- */ @@ -60,8 +56,4 @@ typedef struct { bool is_async; } grpc_md_only_test_credentials; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_FAKE_FAKE_CREDENTIALS_H */ diff --git a/src/core/lib/security/credentials/google_default/credentials_generic.cc b/src/core/lib/security/credentials/google_default/credentials_generic.cc index 4f79718f3d6..58ee080cf3d 100644 --- a/src/core/lib/security/credentials/google_default/credentials_generic.cc +++ b/src/core/lib/security/credentials/google_default/credentials_generic.cc @@ -25,13 +25,13 @@ #include "src/core/lib/support/env.h" #include "src/core/lib/support/string.h" -char *grpc_get_well_known_google_credentials_file_path_impl(void) { - char *result = NULL; - char *base = gpr_getenv(GRPC_GOOGLE_CREDENTIALS_PATH_ENV_VAR); - if (base == NULL) { +char* grpc_get_well_known_google_credentials_file_path_impl(void) { + char* result = nullptr; + char* base = gpr_getenv(GRPC_GOOGLE_CREDENTIALS_PATH_ENV_VAR); + if (base == nullptr) { gpr_log(GPR_ERROR, "Could not get " GRPC_GOOGLE_CREDENTIALS_ENV_VAR " environment variable."); - return NULL; + return nullptr; } gpr_asprintf(&result, "%s/%s", base, GRPC_GOOGLE_CREDENTIALS_PATH_SUFFIX); gpr_free(base); diff --git a/src/core/lib/security/credentials/google_default/google_default_credentials.cc b/src/core/lib/security/credentials/google_default/google_default_credentials.cc index 5b2ddceb4a2..f586c7b6045 100644 --- a/src/core/lib/security/credentials/google_default/google_default_credentials.cc +++ b/src/core/lib/security/credentials/google_default/google_default_credentials.cc @@ -43,10 +43,10 @@ /* -- Default credentials. -- */ -static grpc_channel_credentials *default_credentials = NULL; +static grpc_channel_credentials* default_credentials = nullptr; static int compute_engine_detection_done = 0; static gpr_mu g_state_mu; -static gpr_mu *g_polling_mu; +static gpr_mu* g_polling_mu; static gpr_once g_once = GPR_ONCE_INIT; static void init_default_credentials(void) { gpr_mu_init(&g_state_mu); } @@ -58,17 +58,17 @@ typedef struct { grpc_http_response response; } compute_engine_detector; -static void on_compute_engine_detection_http_response(grpc_exec_ctx *exec_ctx, - void *user_data, - grpc_error *error) { - compute_engine_detector *detector = (compute_engine_detector *)user_data; +static void on_compute_engine_detection_http_response(grpc_exec_ctx* exec_ctx, + void* user_data, + grpc_error* error) { + compute_engine_detector* detector = (compute_engine_detector*)user_data; if (error == GRPC_ERROR_NONE && detector->response.status == 200 && detector->response.hdr_count > 0) { /* Internet providers can return a generic response to all requests, so it is necessary to check that metadata header is present also. */ size_t i; for (i = 0; i < detector->response.hdr_count; i++) { - grpc_http_header *header = &detector->response.hdrs[i]; + grpc_http_header* header = &detector->response.hdrs[i]; if (strcmp(header->key, "Metadata-Flavor") == 0 && strcmp(header->value, "Google") == 0) { detector->success = 1; @@ -80,16 +80,16 @@ static void on_compute_engine_detection_http_response(grpc_exec_ctx *exec_ctx, detector->is_done = 1; GRPC_LOG_IF_ERROR( "Pollset kick", - grpc_pollset_kick(exec_ctx, - grpc_polling_entity_pollset(&detector->pollent), NULL)); + grpc_pollset_kick( + exec_ctx, grpc_polling_entity_pollset(&detector->pollent), nullptr)); gpr_mu_unlock(g_polling_mu); } -static void destroy_pollset(grpc_exec_ctx *exec_ctx, void *p, grpc_error *e) { - grpc_pollset_destroy(exec_ctx, (grpc_pollset *)p); +static void destroy_pollset(grpc_exec_ctx* exec_ctx, void* p, grpc_error* e) { + grpc_pollset_destroy(exec_ctx, (grpc_pollset*)p); } -static int is_stack_running_on_compute_engine(grpc_exec_ctx *exec_ctx) { +static int is_stack_running_on_compute_engine(grpc_exec_ctx* exec_ctx) { compute_engine_detector detector; grpc_httpcli_request request; grpc_httpcli_context context; @@ -99,7 +99,7 @@ static int is_stack_running_on_compute_engine(grpc_exec_ctx *exec_ctx) { on compute engine. */ grpc_millis max_detection_delay = GPR_MS_PER_SEC; - grpc_pollset *pollset = (grpc_pollset *)gpr_zalloc(grpc_pollset_size()); + grpc_pollset* pollset = (grpc_pollset*)gpr_zalloc(grpc_pollset_size()); grpc_pollset_init(pollset, &g_polling_mu); detector.pollent = grpc_polling_entity_create_from_pollset(pollset); detector.is_done = 0; @@ -107,12 +107,12 @@ static int is_stack_running_on_compute_engine(grpc_exec_ctx *exec_ctx) { memset(&detector.response, 0, sizeof(detector.response)); memset(&request, 0, sizeof(grpc_httpcli_request)); - request.host = (char *)GRPC_COMPUTE_ENGINE_DETECTION_HOST; - request.http.path = (char *)"/"; + request.host = (char*)GRPC_COMPUTE_ENGINE_DETECTION_HOST; + request.http.path = (char*)"/"; grpc_httpcli_context_init(&context); - grpc_resource_quota *resource_quota = + grpc_resource_quota* resource_quota = grpc_resource_quota_create("google_default_credentials"); grpc_httpcli_get( exec_ctx, &context, &detector.pollent, resource_quota, &request, @@ -128,7 +128,7 @@ static int is_stack_running_on_compute_engine(grpc_exec_ctx *exec_ctx) { called once for the lifetime of the process by the default credentials. */ gpr_mu_lock(g_polling_mu); while (!detector.is_done) { - grpc_pollset_worker *worker = NULL; + grpc_pollset_worker* worker = nullptr; if (!GRPC_LOG_IF_ERROR( "pollset_work", grpc_pollset_work(exec_ctx, @@ -147,7 +147,7 @@ static int is_stack_running_on_compute_engine(grpc_exec_ctx *exec_ctx) { grpc_pollset_shutdown(exec_ctx, grpc_polling_entity_pollset(&detector.pollent), &destroy_closure); - g_polling_mu = NULL; + g_polling_mu = nullptr; grpc_exec_ctx_flush(exec_ctx); gpr_free(grpc_polling_entity_pollset(&detector.pollent)); @@ -157,15 +157,15 @@ static int is_stack_running_on_compute_engine(grpc_exec_ctx *exec_ctx) { } /* Takes ownership of creds_path if not NULL. */ -static grpc_error *create_default_creds_from_path( - grpc_exec_ctx *exec_ctx, char *creds_path, grpc_call_credentials **creds) { - grpc_json *json = NULL; +static grpc_error* create_default_creds_from_path( + grpc_exec_ctx* exec_ctx, char* creds_path, grpc_call_credentials** creds) { + grpc_json* json = nullptr; grpc_auth_json_key key; grpc_auth_refresh_token token; - grpc_call_credentials *result = NULL; + grpc_call_credentials* result = nullptr; grpc_slice creds_data = grpc_empty_slice(); - grpc_error *error = GRPC_ERROR_NONE; - if (creds_path == NULL) { + grpc_error* error = GRPC_ERROR_NONE; + if (creds_path == nullptr) { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("creds_path unset"); goto end; } @@ -174,8 +174,8 @@ static grpc_error *create_default_creds_from_path( goto end; } json = grpc_json_parse_string_with_len( - (char *)GRPC_SLICE_START_PTR(creds_data), GRPC_SLICE_LENGTH(creds_data)); - if (json == NULL) { + (char*)GRPC_SLICE_START_PTR(creds_data), GRPC_SLICE_LENGTH(creds_data)); + if (json == nullptr) { error = grpc_error_set_str( GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to parse JSON"), GRPC_ERROR_STR_RAW_BYTES, grpc_slice_ref_internal(creds_data)); @@ -188,7 +188,7 @@ static grpc_error *create_default_creds_from_path( result = grpc_service_account_jwt_access_credentials_create_from_auth_json_key( exec_ctx, key, grpc_max_auth_token_lifetime()); - if (result == NULL) { + if (result == nullptr) { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "grpc_service_account_jwt_access_credentials_create_from_auth_json_" "key failed"); @@ -201,7 +201,7 @@ static grpc_error *create_default_creds_from_path( if (grpc_auth_refresh_token_is_valid(&token)) { result = grpc_refresh_token_credentials_create_from_auth_refresh_token(token); - if (result == NULL) { + if (result == nullptr) { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "grpc_refresh_token_credentials_create_from_auth_refresh_token " "failed"); @@ -210,20 +210,20 @@ static grpc_error *create_default_creds_from_path( } end: - GPR_ASSERT((result == NULL) + (error == GRPC_ERROR_NONE) == 1); - if (creds_path != NULL) gpr_free(creds_path); + GPR_ASSERT((result == nullptr) + (error == GRPC_ERROR_NONE) == 1); + if (creds_path != nullptr) gpr_free(creds_path); grpc_slice_unref_internal(exec_ctx, creds_data); - if (json != NULL) grpc_json_destroy(json); + if (json != nullptr) grpc_json_destroy(json); *creds = result; return error; } -grpc_channel_credentials *grpc_google_default_credentials_create(void) { - grpc_channel_credentials *result = NULL; - grpc_call_credentials *call_creds = NULL; - grpc_error *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( +grpc_channel_credentials* grpc_google_default_credentials_create(void) { + grpc_channel_credentials* result = nullptr; + grpc_call_credentials* call_creds = nullptr; + grpc_error* error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Failed to create Google credentials"); - grpc_error *err; + grpc_error* err; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GRPC_API_TRACE("grpc_google_default_credentials_create(void)", 0, ()); @@ -232,7 +232,7 @@ grpc_channel_credentials *grpc_google_default_credentials_create(void) { gpr_mu_lock(&g_state_mu); - if (default_credentials != NULL) { + if (default_credentials != nullptr) { result = grpc_channel_credentials_ref(default_credentials); goto end; } @@ -257,8 +257,8 @@ grpc_channel_credentials *grpc_google_default_credentials_create(void) { is_stack_running_on_compute_engine(&exec_ctx); compute_engine_detection_done = 1; if (need_compute_engine_creds) { - call_creds = grpc_google_compute_engine_credentials_create(NULL); - if (call_creds == NULL) { + call_creds = grpc_google_compute_engine_credentials_create(nullptr); + if (call_creds == nullptr) { error = grpc_error_add_child( error, GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Failed to get credentials from network")); @@ -267,17 +267,17 @@ grpc_channel_credentials *grpc_google_default_credentials_create(void) { } end: - if (result == NULL) { - if (call_creds != NULL) { + if (result == nullptr) { + if (call_creds != nullptr) { /* Blend with default ssl credentials and add a global reference so that it can be cached and re-served. */ - grpc_channel_credentials *ssl_creds = - grpc_ssl_credentials_create(NULL, NULL, NULL); + grpc_channel_credentials* ssl_creds = + grpc_ssl_credentials_create(nullptr, nullptr, nullptr); default_credentials = grpc_channel_credentials_ref( grpc_composite_channel_credentials_create(ssl_creds, call_creds, - NULL)); - GPR_ASSERT(default_credentials != NULL); + nullptr)); + GPR_ASSERT(default_credentials != nullptr); grpc_channel_credentials_unref(&exec_ctx, ssl_creds); grpc_call_credentials_unref(&exec_ctx, call_creds); result = default_credentials; @@ -286,7 +286,7 @@ end: } } gpr_mu_unlock(&g_state_mu); - if (result == NULL) { + if (result == nullptr) { GRPC_LOG_IF_ERROR("grpc_google_default_credentials_create", error); } else { GRPC_ERROR_UNREF(error); @@ -299,9 +299,9 @@ void grpc_flush_cached_google_default_credentials(void) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; gpr_once_init(&g_once, init_default_credentials); gpr_mu_lock(&g_state_mu); - if (default_credentials != NULL) { + if (default_credentials != nullptr) { grpc_channel_credentials_unref(&exec_ctx, default_credentials); - default_credentials = NULL; + default_credentials = nullptr; } compute_engine_detection_done = 0; gpr_mu_unlock(&g_state_mu); @@ -310,10 +310,10 @@ void grpc_flush_cached_google_default_credentials(void) { /* -- Well known credentials path. -- */ -static grpc_well_known_credentials_path_getter creds_path_getter = NULL; +static grpc_well_known_credentials_path_getter creds_path_getter = nullptr; -char *grpc_get_well_known_google_credentials_file_path(void) { - if (creds_path_getter != NULL) return creds_path_getter(); +char* grpc_get_well_known_google_credentials_file_path(void) { + if (creds_path_getter != nullptr) return creds_path_getter(); return grpc_get_well_known_google_credentials_file_path_impl(); } diff --git a/src/core/lib/security/credentials/google_default/google_default_credentials.h b/src/core/lib/security/credentials/google_default/google_default_credentials.h index 66677873caf..b163e486310 100644 --- a/src/core/lib/security/credentials/google_default/google_default_credentials.h +++ b/src/core/lib/security/credentials/google_default/google_default_credentials.h @@ -23,10 +23,6 @@ #include "src/core/lib/security/credentials/credentials.h" -#ifdef __cplusplus -extern "C" { -#endif - #define GRPC_GOOGLE_CLOUD_SDK_CONFIG_DIRECTORY "gcloud" #define GRPC_GOOGLE_WELL_KNOWN_CREDENTIALS_FILE \ "application_default_credentials.json" @@ -45,9 +41,5 @@ extern "C" { void grpc_flush_cached_google_default_credentials(void); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_GOOGLE_DEFAULT_GOOGLE_DEFAULT_CREDENTIALS_H \ - */ + */ diff --git a/src/core/lib/security/credentials/iam/iam_credentials.cc b/src/core/lib/security/credentials/iam/iam_credentials.cc index e9cf208c163..1741bf3068c 100644 --- a/src/core/lib/security/credentials/iam/iam_credentials.cc +++ b/src/core/lib/security/credentials/iam/iam_credentials.cc @@ -27,45 +27,45 @@ #include #include -static void iam_destruct(grpc_exec_ctx *exec_ctx, - grpc_call_credentials *creds) { - grpc_google_iam_credentials *c = (grpc_google_iam_credentials *)creds; +static void iam_destruct(grpc_exec_ctx* exec_ctx, + grpc_call_credentials* creds) { + grpc_google_iam_credentials* c = (grpc_google_iam_credentials*)creds; grpc_credentials_mdelem_array_destroy(exec_ctx, &c->md_array); } -static bool iam_get_request_metadata(grpc_exec_ctx *exec_ctx, - grpc_call_credentials *creds, - grpc_polling_entity *pollent, +static bool iam_get_request_metadata(grpc_exec_ctx* exec_ctx, + grpc_call_credentials* creds, + grpc_polling_entity* pollent, grpc_auth_metadata_context context, - grpc_credentials_mdelem_array *md_array, - grpc_closure *on_request_metadata, - grpc_error **error) { - grpc_google_iam_credentials *c = (grpc_google_iam_credentials *)creds; + grpc_credentials_mdelem_array* md_array, + grpc_closure* on_request_metadata, + grpc_error** error) { + grpc_google_iam_credentials* c = (grpc_google_iam_credentials*)creds; grpc_credentials_mdelem_array_append(md_array, &c->md_array); return true; } static void iam_cancel_get_request_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_credentials *c, - grpc_credentials_mdelem_array *md_array, grpc_error *error) { + grpc_exec_ctx* exec_ctx, grpc_call_credentials* c, + grpc_credentials_mdelem_array* md_array, grpc_error* error) { GRPC_ERROR_UNREF(error); } static grpc_call_credentials_vtable iam_vtable = { iam_destruct, iam_get_request_metadata, iam_cancel_get_request_metadata}; -grpc_call_credentials *grpc_google_iam_credentials_create( - const char *token, const char *authority_selector, void *reserved) { +grpc_call_credentials* grpc_google_iam_credentials_create( + const char* token, const char* authority_selector, void* reserved) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GRPC_API_TRACE( "grpc_iam_credentials_create(token=%s, authority_selector=%s, " "reserved=%p)", 3, (token, authority_selector, reserved)); - GPR_ASSERT(reserved == NULL); - GPR_ASSERT(token != NULL); - GPR_ASSERT(authority_selector != NULL); - grpc_google_iam_credentials *c = - (grpc_google_iam_credentials *)gpr_zalloc(sizeof(*c)); + GPR_ASSERT(reserved == nullptr); + GPR_ASSERT(token != nullptr); + GPR_ASSERT(authority_selector != nullptr); + grpc_google_iam_credentials* c = + (grpc_google_iam_credentials*)gpr_zalloc(sizeof(*c)); c->base.type = GRPC_CALL_CREDENTIALS_TYPE_IAM; c->base.vtable = &iam_vtable; gpr_ref_init(&c->base.refcount, 1); diff --git a/src/core/lib/security/credentials/jwt/json_token.cc b/src/core/lib/security/credentials/jwt/json_token.cc index 8c30353470a..a152ddcaaf6 100644 --- a/src/core/lib/security/credentials/jwt/json_token.cc +++ b/src/core/lib/security/credentials/jwt/json_token.cc @@ -52,30 +52,31 @@ gpr_timespec grpc_max_auth_token_lifetime() { /* --- Override for testing. --- */ -static grpc_jwt_encode_and_sign_override g_jwt_encode_and_sign_override = NULL; +static grpc_jwt_encode_and_sign_override g_jwt_encode_and_sign_override = + nullptr; /* --- grpc_auth_json_key. --- */ -int grpc_auth_json_key_is_valid(const grpc_auth_json_key *json_key) { - return (json_key != NULL) && +int grpc_auth_json_key_is_valid(const grpc_auth_json_key* json_key) { + return (json_key != nullptr) && strcmp(json_key->type, GRPC_AUTH_JSON_TYPE_INVALID); } -grpc_auth_json_key grpc_auth_json_key_create_from_json(const grpc_json *json) { +grpc_auth_json_key grpc_auth_json_key_create_from_json(const grpc_json* json) { grpc_auth_json_key result; - BIO *bio = NULL; - const char *prop_value; + BIO* bio = nullptr; + const char* prop_value; int success = 0; memset(&result, 0, sizeof(grpc_auth_json_key)); result.type = GRPC_AUTH_JSON_TYPE_INVALID; - if (json == NULL) { + if (json == nullptr) { gpr_log(GPR_ERROR, "Invalid json."); goto end; } prop_value = grpc_json_get_string_property(json, "type"); - if (prop_value == NULL || + if (prop_value == nullptr || strcmp(prop_value, GRPC_AUTH_JSON_TYPE_SERVICE_ACCOUNT)) { goto end; } @@ -90,7 +91,7 @@ grpc_auth_json_key grpc_auth_json_key_create_from_json(const grpc_json *json) { } prop_value = grpc_json_get_string_property(json, "private_key"); - if (prop_value == NULL) { + if (prop_value == nullptr) { goto end; } bio = BIO_new(BIO_s_mem()); @@ -99,56 +100,57 @@ grpc_auth_json_key grpc_auth_json_key_create_from_json(const grpc_json *json) { gpr_log(GPR_ERROR, "Could not write into openssl BIO."); goto end; } - result.private_key = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, (void *)""); - if (result.private_key == NULL) { + result.private_key = + PEM_read_bio_RSAPrivateKey(bio, nullptr, nullptr, (void*)""); + if (result.private_key == nullptr) { gpr_log(GPR_ERROR, "Could not deserialize private key."); goto end; } success = 1; end: - if (bio != NULL) BIO_free(bio); + if (bio != nullptr) BIO_free(bio); if (!success) grpc_auth_json_key_destruct(&result); return result; } grpc_auth_json_key grpc_auth_json_key_create_from_string( - const char *json_string) { - char *scratchpad = gpr_strdup(json_string); - grpc_json *json = grpc_json_parse_string(scratchpad); + const char* json_string) { + char* scratchpad = gpr_strdup(json_string); + grpc_json* json = grpc_json_parse_string(scratchpad); grpc_auth_json_key result = grpc_auth_json_key_create_from_json(json); - if (json != NULL) grpc_json_destroy(json); + if (json != nullptr) grpc_json_destroy(json); gpr_free(scratchpad); return result; } -void grpc_auth_json_key_destruct(grpc_auth_json_key *json_key) { - if (json_key == NULL) return; +void grpc_auth_json_key_destruct(grpc_auth_json_key* json_key) { + if (json_key == nullptr) return; json_key->type = GRPC_AUTH_JSON_TYPE_INVALID; - if (json_key->client_id != NULL) { + if (json_key->client_id != nullptr) { gpr_free(json_key->client_id); - json_key->client_id = NULL; + json_key->client_id = nullptr; } - if (json_key->private_key_id != NULL) { + if (json_key->private_key_id != nullptr) { gpr_free(json_key->private_key_id); - json_key->private_key_id = NULL; + json_key->private_key_id = nullptr; } - if (json_key->client_email != NULL) { + if (json_key->client_email != nullptr) { gpr_free(json_key->client_email); - json_key->client_email = NULL; + json_key->client_email = nullptr; } - if (json_key->private_key != NULL) { + if (json_key->private_key != nullptr) { RSA_free(json_key->private_key); - json_key->private_key = NULL; + json_key->private_key = nullptr; } } /* --- jwt encoding and signature. --- */ -static grpc_json *create_child(grpc_json *brother, grpc_json *parent, - const char *key, const char *value, +static grpc_json* create_child(grpc_json* brother, grpc_json* parent, + const char* key, const char* value, grpc_json_type type) { - grpc_json *child = grpc_json_create(type); + grpc_json* child = grpc_json_create(type); if (brother) brother->next = child; if (!parent->child) parent->child = child; child->parent = parent; @@ -157,13 +159,13 @@ static grpc_json *create_child(grpc_json *brother, grpc_json *parent, return child; } -static char *encoded_jwt_header(const char *key_id, const char *algorithm) { - grpc_json *json = grpc_json_create(GRPC_JSON_OBJECT); - grpc_json *child = NULL; - char *json_str = NULL; - char *result = NULL; +static char* encoded_jwt_header(const char* key_id, const char* algorithm) { + grpc_json* json = grpc_json_create(GRPC_JSON_OBJECT); + grpc_json* child = nullptr; + char* json_str = nullptr; + char* result = nullptr; - child = create_child(NULL, json, "alg", algorithm, GRPC_JSON_STRING); + child = create_child(nullptr, json, "alg", algorithm, GRPC_JSON_STRING); child = create_child(child, json, "typ", GRPC_JWT_TYPE, GRPC_JSON_STRING); create_child(child, json, "kid", key_id, GRPC_JSON_STRING); @@ -174,13 +176,13 @@ static char *encoded_jwt_header(const char *key_id, const char *algorithm) { return result; } -static char *encoded_jwt_claim(const grpc_auth_json_key *json_key, - const char *audience, - gpr_timespec token_lifetime, const char *scope) { - grpc_json *json = grpc_json_create(GRPC_JSON_OBJECT); - grpc_json *child = NULL; - char *json_str = NULL; - char *result = NULL; +static char* encoded_jwt_claim(const grpc_auth_json_key* json_key, + const char* audience, + gpr_timespec token_lifetime, const char* scope) { + grpc_json* json = grpc_json_create(GRPC_JSON_OBJECT); + grpc_json* child = nullptr; + char* json_str = nullptr; + char* result = nullptr; gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME); gpr_timespec expiration = gpr_time_add(now, token_lifetime); char now_str[GPR_LTOA_MIN_BUFSIZE]; @@ -192,9 +194,9 @@ static char *encoded_jwt_claim(const grpc_auth_json_key *json_key, int64_ttoa(now.tv_sec, now_str); int64_ttoa(expiration.tv_sec, expiration_str); - child = - create_child(NULL, json, "iss", json_key->client_email, GRPC_JSON_STRING); - if (scope != NULL) { + child = create_child(nullptr, json, "iss", json_key->client_email, + GRPC_JSON_STRING); + if (scope != nullptr) { child = create_child(child, json, "scope", scope, GRPC_JSON_STRING); } else { /* Unscoped JWTs need a sub field. */ @@ -213,12 +215,12 @@ static char *encoded_jwt_claim(const grpc_auth_json_key *json_key, return result; } -static char *dot_concat_and_free_strings(char *str1, char *str2) { +static char* dot_concat_and_free_strings(char* str1, char* str2) { size_t str1_len = strlen(str1); size_t str2_len = strlen(str2); size_t result_len = str1_len + 1 /* dot */ + str2_len; - char *result = (char *)gpr_malloc(result_len + 1 /* NULL terminated */); - char *current = result; + char* result = (char*)gpr_malloc(result_len + 1 /* NULL terminated */); + char* current = result; memcpy(current, str1, str1_len); current += str1_len; *(current++) = '.'; @@ -232,32 +234,32 @@ static char *dot_concat_and_free_strings(char *str1, char *str2) { return result; } -const EVP_MD *openssl_digest_from_algorithm(const char *algorithm) { +const EVP_MD* openssl_digest_from_algorithm(const char* algorithm) { if (strcmp(algorithm, GRPC_JWT_RSA_SHA256_ALGORITHM) == 0) { return EVP_sha256(); } else { gpr_log(GPR_ERROR, "Unknown algorithm %s.", algorithm); - return NULL; + return nullptr; } } -char *compute_and_encode_signature(const grpc_auth_json_key *json_key, - const char *signature_algorithm, - const char *to_sign) { - const EVP_MD *md = openssl_digest_from_algorithm(signature_algorithm); - EVP_MD_CTX *md_ctx = NULL; - EVP_PKEY *key = EVP_PKEY_new(); +char* compute_and_encode_signature(const grpc_auth_json_key* json_key, + const char* signature_algorithm, + const char* to_sign) { + const EVP_MD* md = openssl_digest_from_algorithm(signature_algorithm); + EVP_MD_CTX* md_ctx = nullptr; + EVP_PKEY* key = EVP_PKEY_new(); size_t sig_len = 0; - unsigned char *sig = NULL; - char *result = NULL; - if (md == NULL) return NULL; + unsigned char* sig = nullptr; + char* result = nullptr; + if (md == nullptr) return nullptr; md_ctx = EVP_MD_CTX_create(); - if (md_ctx == NULL) { + if (md_ctx == nullptr) { gpr_log(GPR_ERROR, "Could not create MD_CTX"); goto end; } EVP_PKEY_set1_RSA(key, json_key->private_key); - if (EVP_DigestSignInit(md_ctx, NULL, md, NULL, key) != 1) { + if (EVP_DigestSignInit(md_ctx, nullptr, md, nullptr, key) != 1) { gpr_log(GPR_ERROR, "DigestInit failed."); goto end; } @@ -265,11 +267,11 @@ char *compute_and_encode_signature(const grpc_auth_json_key *json_key, gpr_log(GPR_ERROR, "DigestUpdate failed."); goto end; } - if (EVP_DigestSignFinal(md_ctx, NULL, &sig_len) != 1) { + if (EVP_DigestSignFinal(md_ctx, nullptr, &sig_len) != 1) { gpr_log(GPR_ERROR, "DigestFinal (get signature length) failed."); goto end; } - sig = (unsigned char *)gpr_malloc(sig_len); + sig = (unsigned char*)gpr_malloc(sig_len); if (EVP_DigestSignFinal(md_ctx, sig, &sig_len) != 1) { gpr_log(GPR_ERROR, "DigestFinal (signature compute) failed."); goto end; @@ -277,27 +279,27 @@ char *compute_and_encode_signature(const grpc_auth_json_key *json_key, result = grpc_base64_encode(sig, sig_len, 1, 0); end: - if (key != NULL) EVP_PKEY_free(key); - if (md_ctx != NULL) EVP_MD_CTX_destroy(md_ctx); - if (sig != NULL) gpr_free(sig); + if (key != nullptr) EVP_PKEY_free(key); + if (md_ctx != nullptr) EVP_MD_CTX_destroy(md_ctx); + if (sig != nullptr) gpr_free(sig); return result; } -char *grpc_jwt_encode_and_sign(const grpc_auth_json_key *json_key, - const char *audience, - gpr_timespec token_lifetime, const char *scope) { - if (g_jwt_encode_and_sign_override != NULL) { +char* grpc_jwt_encode_and_sign(const grpc_auth_json_key* json_key, + const char* audience, + gpr_timespec token_lifetime, const char* scope) { + if (g_jwt_encode_and_sign_override != nullptr) { return g_jwt_encode_and_sign_override(json_key, audience, token_lifetime, scope); } else { - const char *sig_algo = GRPC_JWT_RSA_SHA256_ALGORITHM; - char *to_sign = dot_concat_and_free_strings( + const char* sig_algo = GRPC_JWT_RSA_SHA256_ALGORITHM; + char* to_sign = dot_concat_and_free_strings( encoded_jwt_header(json_key->private_key_id, sig_algo), encoded_jwt_claim(json_key, audience, token_lifetime, scope)); - char *sig = compute_and_encode_signature(json_key, sig_algo, to_sign); - if (sig == NULL) { + char* sig = compute_and_encode_signature(json_key, sig_algo, to_sign); + if (sig == nullptr) { gpr_free(to_sign); - return NULL; + return nullptr; } return dot_concat_and_free_strings(to_sign, sig); } diff --git a/src/core/lib/security/credentials/jwt/json_token.h b/src/core/lib/security/credentials/jwt/json_token.h index b923b02df6f..9b774882b76 100644 --- a/src/core/lib/security/credentials/jwt/json_token.h +++ b/src/core/lib/security/credentials/jwt/json_token.h @@ -19,10 +19,6 @@ #ifndef GRPC_CORE_LIB_SECURITY_CREDENTIALS_JWT_JSON_TOKEN_H #define GRPC_CORE_LIB_SECURITY_CREDENTIALS_JWT_JSON_TOKEN_H -#ifdef __cplusplus -extern "C" { -#endif - #include #include @@ -35,47 +31,43 @@ extern "C" { /* --- auth_json_key parsing. --- */ typedef struct { - const char *type; - char *private_key_id; - char *client_id; - char *client_email; - RSA *private_key; + const char* type; + char* private_key_id; + char* client_id; + char* client_email; + RSA* private_key; } grpc_auth_json_key; /* Returns 1 if the object is valid, 0 otherwise. */ -int grpc_auth_json_key_is_valid(const grpc_auth_json_key *json_key); +int grpc_auth_json_key_is_valid(const grpc_auth_json_key* json_key); /* Creates a json_key object from string. Returns an invalid object if a parsing error has been encountered. */ grpc_auth_json_key grpc_auth_json_key_create_from_string( - const char *json_string); + const char* json_string); /* Creates a json_key object from parsed json. Returns an invalid object if a parsing error has been encountered. */ -grpc_auth_json_key grpc_auth_json_key_create_from_json(const grpc_json *json); +grpc_auth_json_key grpc_auth_json_key_create_from_json(const grpc_json* json); /* Destructs the object. */ -void grpc_auth_json_key_destruct(grpc_auth_json_key *json_key); +void grpc_auth_json_key_destruct(grpc_auth_json_key* json_key); /* --- json token encoding and signing. --- */ /* Caller is responsible for calling gpr_free on the returned value. May return NULL on invalid input. The scope parameter may be NULL. */ -char *grpc_jwt_encode_and_sign(const grpc_auth_json_key *json_key, - const char *audience, - gpr_timespec token_lifetime, const char *scope); +char* grpc_jwt_encode_and_sign(const grpc_auth_json_key* json_key, + const char* audience, + gpr_timespec token_lifetime, const char* scope); /* Override encode_and_sign function for testing. */ -typedef char *(*grpc_jwt_encode_and_sign_override)( - const grpc_auth_json_key *json_key, const char *audience, - gpr_timespec token_lifetime, const char *scope); +typedef char* (*grpc_jwt_encode_and_sign_override)( + const grpc_auth_json_key* json_key, const char* audience, + gpr_timespec token_lifetime, const char* scope); /* Set a custom encode_and_sign override for testing. */ void grpc_jwt_encode_and_sign_set_override( grpc_jwt_encode_and_sign_override func); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_JWT_JSON_TOKEN_H */ diff --git a/src/core/lib/security/credentials/jwt/jwt_credentials.cc b/src/core/lib/security/credentials/jwt/jwt_credentials.cc index 835dd677ed8..77163c0cc17 100644 --- a/src/core/lib/security/credentials/jwt/jwt_credentials.cc +++ b/src/core/lib/security/credentials/jwt/jwt_credentials.cc @@ -30,35 +30,35 @@ #include #include -static void jwt_reset_cache(grpc_exec_ctx *exec_ctx, - grpc_service_account_jwt_access_credentials *c) { +static void jwt_reset_cache(grpc_exec_ctx* exec_ctx, + grpc_service_account_jwt_access_credentials* c) { GRPC_MDELEM_UNREF(exec_ctx, c->cached.jwt_md); c->cached.jwt_md = GRPC_MDNULL; - if (c->cached.service_url != NULL) { + if (c->cached.service_url != nullptr) { gpr_free(c->cached.service_url); - c->cached.service_url = NULL; + c->cached.service_url = nullptr; } c->cached.jwt_expiration = gpr_inf_past(GPR_CLOCK_REALTIME); } -static void jwt_destruct(grpc_exec_ctx *exec_ctx, - grpc_call_credentials *creds) { - grpc_service_account_jwt_access_credentials *c = - (grpc_service_account_jwt_access_credentials *)creds; +static void jwt_destruct(grpc_exec_ctx* exec_ctx, + grpc_call_credentials* creds) { + grpc_service_account_jwt_access_credentials* c = + (grpc_service_account_jwt_access_credentials*)creds; grpc_auth_json_key_destruct(&c->key); jwt_reset_cache(exec_ctx, c); gpr_mu_destroy(&c->cache_mu); } -static bool jwt_get_request_metadata(grpc_exec_ctx *exec_ctx, - grpc_call_credentials *creds, - grpc_polling_entity *pollent, +static bool jwt_get_request_metadata(grpc_exec_ctx* exec_ctx, + grpc_call_credentials* creds, + grpc_polling_entity* pollent, grpc_auth_metadata_context context, - grpc_credentials_mdelem_array *md_array, - grpc_closure *on_request_metadata, - grpc_error **error) { - grpc_service_account_jwt_access_credentials *c = - (grpc_service_account_jwt_access_credentials *)creds; + grpc_credentials_mdelem_array* md_array, + grpc_closure* on_request_metadata, + grpc_error** error) { + grpc_service_account_jwt_access_credentials* c = + (grpc_service_account_jwt_access_credentials*)creds; gpr_timespec refresh_threshold = gpr_time_from_seconds( GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS, GPR_TIMESPAN); @@ -66,7 +66,7 @@ static bool jwt_get_request_metadata(grpc_exec_ctx *exec_ctx, grpc_mdelem jwt_md = GRPC_MDNULL; { gpr_mu_lock(&c->cache_mu); - if (c->cached.service_url != NULL && + if (c->cached.service_url != nullptr && strcmp(c->cached.service_url, context.service_url) == 0 && !GRPC_MDISNULL(c->cached.jwt_md) && (gpr_time_cmp(gpr_time_sub(c->cached.jwt_expiration, @@ -78,14 +78,14 @@ static bool jwt_get_request_metadata(grpc_exec_ctx *exec_ctx, } if (GRPC_MDISNULL(jwt_md)) { - char *jwt = NULL; + char* jwt = nullptr; /* Generate a new jwt. */ gpr_mu_lock(&c->cache_mu); jwt_reset_cache(exec_ctx, c); jwt = grpc_jwt_encode_and_sign(&c->key, context.service_url, - c->jwt_lifetime, NULL); - if (jwt != NULL) { - char *md_value; + c->jwt_lifetime, nullptr); + if (jwt != nullptr) { + char* md_value; gpr_asprintf(&md_value, "Bearer %s", jwt); gpr_free(jwt); c->cached.jwt_expiration = @@ -111,24 +111,24 @@ static bool jwt_get_request_metadata(grpc_exec_ctx *exec_ctx, } static void jwt_cancel_get_request_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_credentials *c, - grpc_credentials_mdelem_array *md_array, grpc_error *error) { + grpc_exec_ctx* exec_ctx, grpc_call_credentials* c, + grpc_credentials_mdelem_array* md_array, grpc_error* error) { GRPC_ERROR_UNREF(error); } static grpc_call_credentials_vtable jwt_vtable = { jwt_destruct, jwt_get_request_metadata, jwt_cancel_get_request_metadata}; -grpc_call_credentials * +grpc_call_credentials* grpc_service_account_jwt_access_credentials_create_from_auth_json_key( - grpc_exec_ctx *exec_ctx, grpc_auth_json_key key, + grpc_exec_ctx* exec_ctx, grpc_auth_json_key key, gpr_timespec token_lifetime) { - grpc_service_account_jwt_access_credentials *c; + grpc_service_account_jwt_access_credentials* c; if (!grpc_auth_json_key_is_valid(&key)) { gpr_log(GPR_ERROR, "Invalid input for jwt credentials creation"); - return NULL; + return nullptr; } - c = (grpc_service_account_jwt_access_credentials *)gpr_zalloc( + c = (grpc_service_account_jwt_access_credentials*)gpr_zalloc( sizeof(grpc_service_account_jwt_access_credentials)); c->base.type = GRPC_CALL_CREDENTIALS_TYPE_JWT; gpr_ref_init(&c->base.refcount, 1); @@ -147,33 +147,33 @@ grpc_service_account_jwt_access_credentials_create_from_auth_json_key( return &c->base; } -static char *redact_private_key(const char *json_key) { - char *json_copy = gpr_strdup(json_key); - grpc_json *json = grpc_json_parse_string(json_copy); +static char* redact_private_key(const char* json_key) { + char* json_copy = gpr_strdup(json_key); + grpc_json* json = grpc_json_parse_string(json_copy); if (!json) { gpr_free(json_copy); return gpr_strdup(""); } - const char *redacted = ""; - grpc_json *current = json->child; + const char* redacted = ""; + grpc_json* current = json->child; while (current) { if (current->type == GRPC_JSON_STRING && strcmp(current->key, "private_key") == 0) { - current->value = (char *)redacted; + current->value = (char*)redacted; break; } current = current->next; } - char *clean_json = grpc_json_dump_to_string(json, 2); + char* clean_json = grpc_json_dump_to_string(json, 2); gpr_free(json_copy); grpc_json_destroy(json); return clean_json; } -grpc_call_credentials *grpc_service_account_jwt_access_credentials_create( - const char *json_key, gpr_timespec token_lifetime, void *reserved) { - if (GRPC_TRACER_ON(grpc_api_trace)) { - char *clean_json = redact_private_key(json_key); +grpc_call_credentials* grpc_service_account_jwt_access_credentials_create( + const char* json_key, gpr_timespec token_lifetime, void* reserved) { + if (grpc_api_trace.enabled()) { + char* clean_json = redact_private_key(json_key); gpr_log(GPR_INFO, "grpc_service_account_jwt_access_credentials_create(" "json_key=%s, " @@ -185,9 +185,9 @@ grpc_call_credentials *grpc_service_account_jwt_access_credentials_create( (int)token_lifetime.clock_type, reserved); gpr_free(clean_json); } - GPR_ASSERT(reserved == NULL); + GPR_ASSERT(reserved == nullptr); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - grpc_call_credentials *creds = + grpc_call_credentials* creds = grpc_service_account_jwt_access_credentials_create_from_auth_json_key( &exec_ctx, grpc_auth_json_key_create_from_string(json_key), token_lifetime); diff --git a/src/core/lib/security/credentials/jwt/jwt_credentials.h b/src/core/lib/security/credentials/jwt/jwt_credentials.h index 5cee6ed0da6..85f068aac84 100644 --- a/src/core/lib/security/credentials/jwt/jwt_credentials.h +++ b/src/core/lib/security/credentials/jwt/jwt_credentials.h @@ -22,10 +22,6 @@ #include "src/core/lib/security/credentials/credentials.h" #include "src/core/lib/security/credentials/jwt/json_token.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct { grpc_call_credentials base; @@ -34,7 +30,7 @@ typedef struct { gpr_mu cache_mu; struct { grpc_mdelem jwt_md; - char *service_url; + char* service_url; gpr_timespec jwt_expiration; } cached; @@ -44,13 +40,9 @@ typedef struct { // Private constructor for jwt credentials from an already parsed json key. // Takes ownership of the key. -grpc_call_credentials * +grpc_call_credentials* grpc_service_account_jwt_access_credentials_create_from_auth_json_key( - grpc_exec_ctx *exec_ctx, grpc_auth_json_key key, + grpc_exec_ctx* exec_ctx, grpc_auth_json_key key, gpr_timespec token_lifetime); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_JWT_JWT_CREDENTIALS_H */ diff --git a/src/core/lib/security/credentials/jwt/jwt_verifier.cc b/src/core/lib/security/credentials/jwt/jwt_verifier.cc index 39e72c195ba..3709b83c4e8 100644 --- a/src/core/lib/security/credentials/jwt/jwt_verifier.cc +++ b/src/core/lib/security/credentials/jwt/jwt_verifier.cc @@ -40,7 +40,7 @@ extern "C" { /* --- Utils. --- */ -const char *grpc_jwt_verifier_status_to_string( +const char* grpc_jwt_verifier_status_to_string( grpc_jwt_verifier_status status) { switch (status) { case GRPC_JWT_VERIFIER_OK: @@ -62,7 +62,7 @@ const char *grpc_jwt_verifier_status_to_string( } } -static const EVP_MD *evp_md_from_alg(const char *alg) { +static const EVP_MD* evp_md_from_alg(const char* alg) { if (strcmp(alg, "RS256") == 0) { return EVP_sha256(); } else if (strcmp(alg, "RS384") == 0) { @@ -70,91 +70,91 @@ static const EVP_MD *evp_md_from_alg(const char *alg) { } else if (strcmp(alg, "RS512") == 0) { return EVP_sha512(); } else { - return NULL; + return nullptr; } } -static grpc_json *parse_json_part_from_jwt(grpc_exec_ctx *exec_ctx, - const char *str, size_t len, - grpc_slice *buffer) { - grpc_json *json; +static grpc_json* parse_json_part_from_jwt(grpc_exec_ctx* exec_ctx, + const char* str, size_t len, + grpc_slice* buffer) { + grpc_json* json; *buffer = grpc_base64_decode_with_len(exec_ctx, str, len, 1); if (GRPC_SLICE_IS_EMPTY(*buffer)) { gpr_log(GPR_ERROR, "Invalid base64."); - return NULL; + return nullptr; } - json = grpc_json_parse_string_with_len((char *)GRPC_SLICE_START_PTR(*buffer), + json = grpc_json_parse_string_with_len((char*)GRPC_SLICE_START_PTR(*buffer), GRPC_SLICE_LENGTH(*buffer)); - if (json == NULL) { + if (json == nullptr) { grpc_slice_unref_internal(exec_ctx, *buffer); gpr_log(GPR_ERROR, "JSON parsing error."); } return json; } -static const char *validate_string_field(const grpc_json *json, - const char *key) { +static const char* validate_string_field(const grpc_json* json, + const char* key) { if (json->type != GRPC_JSON_STRING) { gpr_log(GPR_ERROR, "Invalid %s field [%s]", key, json->value); - return NULL; + return nullptr; } return json->value; } -static gpr_timespec validate_time_field(const grpc_json *json, - const char *key) { +static gpr_timespec validate_time_field(const grpc_json* json, + const char* key) { gpr_timespec result = gpr_time_0(GPR_CLOCK_REALTIME); if (json->type != GRPC_JSON_NUMBER) { gpr_log(GPR_ERROR, "Invalid %s field [%s]", key, json->value); return result; } - result.tv_sec = strtol(json->value, NULL, 10); + result.tv_sec = strtol(json->value, nullptr, 10); return result; } /* --- JOSE header. see http://tools.ietf.org/html/rfc7515#section-4 --- */ typedef struct { - const char *alg; - const char *kid; - const char *typ; + const char* alg; + const char* kid; + const char* typ; /* TODO(jboeuf): Add others as needed (jku, jwk, x5u, x5c and so on...). */ grpc_slice buffer; } jose_header; -static void jose_header_destroy(grpc_exec_ctx *exec_ctx, jose_header *h) { +static void jose_header_destroy(grpc_exec_ctx* exec_ctx, jose_header* h) { grpc_slice_unref_internal(exec_ctx, h->buffer); gpr_free(h); } /* Takes ownership of json and buffer. */ -static jose_header *jose_header_from_json(grpc_exec_ctx *exec_ctx, - grpc_json *json, grpc_slice buffer) { - grpc_json *cur; - jose_header *h = (jose_header *)gpr_zalloc(sizeof(jose_header)); +static jose_header* jose_header_from_json(grpc_exec_ctx* exec_ctx, + grpc_json* json, grpc_slice buffer) { + grpc_json* cur; + jose_header* h = (jose_header*)gpr_zalloc(sizeof(jose_header)); h->buffer = buffer; - for (cur = json->child; cur != NULL; cur = cur->next) { + for (cur = json->child; cur != nullptr; cur = cur->next) { if (strcmp(cur->key, "alg") == 0) { /* We only support RSA-1.5 signatures for now. Beware of this if we add HMAC support: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/ */ if (cur->type != GRPC_JSON_STRING || strncmp(cur->value, "RS", 2) || - evp_md_from_alg(cur->value) == NULL) { + evp_md_from_alg(cur->value) == nullptr) { gpr_log(GPR_ERROR, "Invalid alg field [%s]", cur->value); goto error; } h->alg = cur->value; } else if (strcmp(cur->key, "typ") == 0) { h->typ = validate_string_field(cur, "typ"); - if (h->typ == NULL) goto error; + if (h->typ == nullptr) goto error; } else if (strcmp(cur->key, "kid") == 0) { h->kid = validate_string_field(cur, "kid"); - if (h->kid == NULL) goto error; + if (h->kid == nullptr) goto error; } } - if (h->alg == NULL) { + if (h->alg == nullptr) { gpr_log(GPR_ERROR, "Missing alg field."); goto error; } @@ -165,77 +165,77 @@ static jose_header *jose_header_from_json(grpc_exec_ctx *exec_ctx, error: grpc_json_destroy(json); jose_header_destroy(exec_ctx, h); - return NULL; + return nullptr; } /* --- JWT claims. see http://tools.ietf.org/html/rfc7519#section-4.1 */ struct grpc_jwt_claims { /* Well known properties already parsed. */ - const char *sub; - const char *iss; - const char *aud; - const char *jti; + const char* sub; + const char* iss; + const char* aud; + const char* jti; gpr_timespec iat; gpr_timespec exp; gpr_timespec nbf; - grpc_json *json; + grpc_json* json; grpc_slice buffer; }; -void grpc_jwt_claims_destroy(grpc_exec_ctx *exec_ctx, grpc_jwt_claims *claims) { +void grpc_jwt_claims_destroy(grpc_exec_ctx* exec_ctx, grpc_jwt_claims* claims) { grpc_json_destroy(claims->json); grpc_slice_unref_internal(exec_ctx, claims->buffer); gpr_free(claims); } -const grpc_json *grpc_jwt_claims_json(const grpc_jwt_claims *claims) { - if (claims == NULL) return NULL; +const grpc_json* grpc_jwt_claims_json(const grpc_jwt_claims* claims) { + if (claims == nullptr) return nullptr; return claims->json; } -const char *grpc_jwt_claims_subject(const grpc_jwt_claims *claims) { - if (claims == NULL) return NULL; +const char* grpc_jwt_claims_subject(const grpc_jwt_claims* claims) { + if (claims == nullptr) return nullptr; return claims->sub; } -const char *grpc_jwt_claims_issuer(const grpc_jwt_claims *claims) { - if (claims == NULL) return NULL; +const char* grpc_jwt_claims_issuer(const grpc_jwt_claims* claims) { + if (claims == nullptr) return nullptr; return claims->iss; } -const char *grpc_jwt_claims_id(const grpc_jwt_claims *claims) { - if (claims == NULL) return NULL; +const char* grpc_jwt_claims_id(const grpc_jwt_claims* claims) { + if (claims == nullptr) return nullptr; return claims->jti; } -const char *grpc_jwt_claims_audience(const grpc_jwt_claims *claims) { - if (claims == NULL) return NULL; +const char* grpc_jwt_claims_audience(const grpc_jwt_claims* claims) { + if (claims == nullptr) return nullptr; return claims->aud; } -gpr_timespec grpc_jwt_claims_issued_at(const grpc_jwt_claims *claims) { - if (claims == NULL) return gpr_inf_past(GPR_CLOCK_REALTIME); +gpr_timespec grpc_jwt_claims_issued_at(const grpc_jwt_claims* claims) { + if (claims == nullptr) return gpr_inf_past(GPR_CLOCK_REALTIME); return claims->iat; } -gpr_timespec grpc_jwt_claims_expires_at(const grpc_jwt_claims *claims) { - if (claims == NULL) return gpr_inf_future(GPR_CLOCK_REALTIME); +gpr_timespec grpc_jwt_claims_expires_at(const grpc_jwt_claims* claims) { + if (claims == nullptr) return gpr_inf_future(GPR_CLOCK_REALTIME); return claims->exp; } -gpr_timespec grpc_jwt_claims_not_before(const grpc_jwt_claims *claims) { - if (claims == NULL) return gpr_inf_past(GPR_CLOCK_REALTIME); +gpr_timespec grpc_jwt_claims_not_before(const grpc_jwt_claims* claims) { + if (claims == nullptr) return gpr_inf_past(GPR_CLOCK_REALTIME); return claims->nbf; } /* Takes ownership of json and buffer even in case of failure. */ -grpc_jwt_claims *grpc_jwt_claims_from_json(grpc_exec_ctx *exec_ctx, - grpc_json *json, grpc_slice buffer) { - grpc_json *cur; - grpc_jwt_claims *claims = - (grpc_jwt_claims *)gpr_malloc(sizeof(grpc_jwt_claims)); +grpc_jwt_claims* grpc_jwt_claims_from_json(grpc_exec_ctx* exec_ctx, + grpc_json* json, grpc_slice buffer) { + grpc_json* cur; + grpc_jwt_claims* claims = + (grpc_jwt_claims*)gpr_malloc(sizeof(grpc_jwt_claims)); memset(claims, 0, sizeof(grpc_jwt_claims)); claims->json = json; claims->buffer = buffer; @@ -244,19 +244,19 @@ grpc_jwt_claims *grpc_jwt_claims_from_json(grpc_exec_ctx *exec_ctx, claims->exp = gpr_inf_future(GPR_CLOCK_REALTIME); /* Per the spec, all fields are optional. */ - for (cur = json->child; cur != NULL; cur = cur->next) { + for (cur = json->child; cur != nullptr; cur = cur->next) { if (strcmp(cur->key, "sub") == 0) { claims->sub = validate_string_field(cur, "sub"); - if (claims->sub == NULL) goto error; + if (claims->sub == nullptr) goto error; } else if (strcmp(cur->key, "iss") == 0) { claims->iss = validate_string_field(cur, "iss"); - if (claims->iss == NULL) goto error; + if (claims->iss == nullptr) goto error; } else if (strcmp(cur->key, "aud") == 0) { claims->aud = validate_string_field(cur, "aud"); - if (claims->aud == NULL) goto error; + if (claims->aud == nullptr) goto error; } else if (strcmp(cur->key, "jti") == 0) { claims->jti = validate_string_field(cur, "jti"); - if (claims->jti == NULL) goto error; + if (claims->jti == nullptr) goto error; } else if (strcmp(cur->key, "iat") == 0) { claims->iat = validate_time_field(cur, "iat"); if (gpr_time_cmp(claims->iat, gpr_time_0(GPR_CLOCK_REALTIME)) == 0) @@ -275,15 +275,15 @@ grpc_jwt_claims *grpc_jwt_claims_from_json(grpc_exec_ctx *exec_ctx, error: grpc_jwt_claims_destroy(exec_ctx, claims); - return NULL; + return nullptr; } -grpc_jwt_verifier_status grpc_jwt_claims_check(const grpc_jwt_claims *claims, - const char *audience) { +grpc_jwt_verifier_status grpc_jwt_claims_check(const grpc_jwt_claims* claims, + const char* audience) { gpr_timespec skewed_now; int audience_ok; - GPR_ASSERT(claims != NULL); + GPR_ASSERT(claims != nullptr); skewed_now = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), grpc_jwt_verifier_clock_skew); @@ -301,23 +301,23 @@ grpc_jwt_verifier_status grpc_jwt_claims_check(const grpc_jwt_claims *claims, /* This should be probably up to the upper layer to decide but let's harcode the 99% use case here for email issuers, where the JWT must be self issued. */ - if (grpc_jwt_issuer_email_domain(claims->iss) != NULL && - claims->sub != NULL && strcmp(claims->iss, claims->sub) != 0) { + if (grpc_jwt_issuer_email_domain(claims->iss) != nullptr && + claims->sub != nullptr && strcmp(claims->iss, claims->sub) != 0) { gpr_log(GPR_ERROR, "Email issuer (%s) cannot assert another subject (%s) than itself.", claims->iss, claims->sub); return GRPC_JWT_VERIFIER_BAD_SUBJECT; } - if (audience == NULL) { - audience_ok = claims->aud == NULL; + if (audience == nullptr) { + audience_ok = claims->aud == nullptr; } else { - audience_ok = claims->aud != NULL && strcmp(audience, claims->aud) == 0; + audience_ok = claims->aud != nullptr && strcmp(audience, claims->aud) == 0; } if (!audience_ok) { gpr_log(GPR_ERROR, "Audience mismatch: expected %s and found %s.", - audience == NULL ? "NULL" : audience, - claims->aud == NULL ? "NULL" : claims->aud); + audience == nullptr ? "NULL" : audience, + claims->aud == nullptr ? "NULL" : claims->aud); return GRPC_JWT_VERIFIER_BAD_AUDIENCE; } return GRPC_JWT_VERIFIER_OK; @@ -332,26 +332,26 @@ typedef enum { } http_response_index; typedef struct { - grpc_jwt_verifier *verifier; + grpc_jwt_verifier* verifier; grpc_polling_entity pollent; - jose_header *header; - grpc_jwt_claims *claims; - char *audience; + jose_header* header; + grpc_jwt_claims* claims; + char* audience; grpc_slice signature; grpc_slice signed_data; - void *user_data; + void* user_data; grpc_jwt_verification_done_cb user_cb; grpc_http_response responses[HTTP_RESPONSE_COUNT]; } verifier_cb_ctx; /* Takes ownership of the header, claims and signature. */ -static verifier_cb_ctx *verifier_cb_ctx_create( - grpc_jwt_verifier *verifier, grpc_pollset *pollset, jose_header *header, - grpc_jwt_claims *claims, const char *audience, grpc_slice signature, - const char *signed_jwt, size_t signed_jwt_len, void *user_data, +static verifier_cb_ctx* verifier_cb_ctx_create( + grpc_jwt_verifier* verifier, grpc_pollset* pollset, jose_header* header, + grpc_jwt_claims* claims, const char* audience, grpc_slice signature, + const char* signed_jwt, size_t signed_jwt_len, void* user_data, grpc_jwt_verification_done_cb cb) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - verifier_cb_ctx *ctx = (verifier_cb_ctx *)gpr_zalloc(sizeof(verifier_cb_ctx)); + verifier_cb_ctx* ctx = (verifier_cb_ctx*)gpr_zalloc(sizeof(verifier_cb_ctx)); ctx->verifier = verifier; ctx->pollent = grpc_polling_entity_create_from_pollset(pollset); ctx->header = header; @@ -365,9 +365,9 @@ static verifier_cb_ctx *verifier_cb_ctx_create( return ctx; } -void verifier_cb_ctx_destroy(grpc_exec_ctx *exec_ctx, verifier_cb_ctx *ctx) { - if (ctx->audience != NULL) gpr_free(ctx->audience); - if (ctx->claims != NULL) grpc_jwt_claims_destroy(exec_ctx, ctx->claims); +void verifier_cb_ctx_destroy(grpc_exec_ctx* exec_ctx, verifier_cb_ctx* ctx) { + if (ctx->audience != nullptr) gpr_free(ctx->audience); + if (ctx->claims != nullptr) grpc_jwt_claims_destroy(exec_ctx, ctx->claims); grpc_slice_unref_internal(exec_ctx, ctx->signature); grpc_slice_unref_internal(exec_ctx, ctx->signed_data); jose_header_destroy(exec_ctx, ctx->header); @@ -387,60 +387,60 @@ gpr_timespec grpc_jwt_verifier_clock_skew = {60, 0, GPR_TIMESPAN}; grpc_millis grpc_jwt_verifier_max_delay = 60 * GPR_MS_PER_SEC; typedef struct { - char *email_domain; - char *key_url_prefix; + char* email_domain; + char* key_url_prefix; } email_key_mapping; struct grpc_jwt_verifier { - email_key_mapping *mappings; + email_key_mapping* mappings; size_t num_mappings; /* Should be very few, linear search ok. */ size_t allocated_mappings; grpc_httpcli_context http_ctx; }; -static grpc_json *json_from_http(const grpc_httpcli_response *response) { - grpc_json *json = NULL; +static grpc_json* json_from_http(const grpc_httpcli_response* response) { + grpc_json* json = nullptr; - if (response == NULL) { + if (response == nullptr) { gpr_log(GPR_ERROR, "HTTP response is NULL."); - return NULL; + return nullptr; } if (response->status != 200) { gpr_log(GPR_ERROR, "Call to http server failed with error %d.", response->status); - return NULL; + return nullptr; } json = grpc_json_parse_string_with_len(response->body, response->body_length); - if (json == NULL) { + if (json == nullptr) { gpr_log(GPR_ERROR, "Invalid JSON found in response."); } return json; } -static const grpc_json *find_property_by_name(const grpc_json *json, - const char *name) { - const grpc_json *cur; - for (cur = json->child; cur != NULL; cur = cur->next) { +static const grpc_json* find_property_by_name(const grpc_json* json, + const char* name) { + const grpc_json* cur; + for (cur = json->child; cur != nullptr; cur = cur->next) { if (strcmp(cur->key, name) == 0) return cur; } - return NULL; + return nullptr; } -static EVP_PKEY *extract_pkey_from_x509(const char *x509_str) { - X509 *x509 = NULL; - EVP_PKEY *result = NULL; - BIO *bio = BIO_new(BIO_s_mem()); +static EVP_PKEY* extract_pkey_from_x509(const char* x509_str) { + X509* x509 = nullptr; + EVP_PKEY* result = nullptr; + BIO* bio = BIO_new(BIO_s_mem()); size_t len = strlen(x509_str); GPR_ASSERT(len < INT_MAX); BIO_write(bio, x509_str, (int)len); - x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL); - if (x509 == NULL) { + x509 = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr); + if (x509 == nullptr) { gpr_log(GPR_ERROR, "Unable to parse x509 cert."); goto end; } result = X509_get_pubkey(x509); - if (result == NULL) { + if (result == nullptr) { gpr_log(GPR_ERROR, "Cannot find public key in X509 cert."); } @@ -450,18 +450,18 @@ end: return result; } -static BIGNUM *bignum_from_base64(grpc_exec_ctx *exec_ctx, const char *b64) { - BIGNUM *result = NULL; +static BIGNUM* bignum_from_base64(grpc_exec_ctx* exec_ctx, const char* b64) { + BIGNUM* result = nullptr; grpc_slice bin; - if (b64 == NULL) return NULL; + if (b64 == nullptr) return nullptr; bin = grpc_base64_decode(exec_ctx, b64, 1); if (GRPC_SLICE_IS_EMPTY(bin)) { gpr_log(GPR_ERROR, "Invalid base64 for big num."); - return NULL; + return nullptr; } result = BN_bin2bn(GRPC_SLICE_START_PTR(bin), - TSI_SIZE_AS_SIZE(GRPC_SLICE_LENGTH(bin)), NULL); + TSI_SIZE_AS_SIZE(GRPC_SLICE_LENGTH(bin)), nullptr); grpc_slice_unref_internal(exec_ctx, bin); return result; } @@ -469,24 +469,24 @@ static BIGNUM *bignum_from_base64(grpc_exec_ctx *exec_ctx, const char *b64) { #if OPENSSL_VERSION_NUMBER < 0x10100000L // Provide compatibility across OpenSSL 1.02 and 1.1. -static int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d) { +static int RSA_set0_key(RSA* r, BIGNUM* n, BIGNUM* e, BIGNUM* d) { /* If the fields n and e in r are NULL, the corresponding input * parameters MUST be non-NULL for n and e. d may be * left NULL (in case only the public key is used). */ - if ((r->n == NULL && n == NULL) || (r->e == NULL && e == NULL)) { + if ((r->n == nullptr && n == nullptr) || (r->e == nullptr && e == nullptr)) { return 0; } - if (n != NULL) { + if (n != nullptr) { BN_free(r->n); r->n = n; } - if (e != NULL) { + if (e != nullptr) { BN_free(r->e); r->e = e; } - if (d != NULL) { + if (d != nullptr) { BN_free(r->d); r->d = d; } @@ -495,46 +495,46 @@ static int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d) { } #endif // OPENSSL_VERSION_NUMBER < 0x10100000L -static EVP_PKEY *pkey_from_jwk(grpc_exec_ctx *exec_ctx, const grpc_json *json, - const char *kty) { - const grpc_json *key_prop; - RSA *rsa = NULL; - EVP_PKEY *result = NULL; - BIGNUM *tmp_n = NULL; - BIGNUM *tmp_e = NULL; +static EVP_PKEY* pkey_from_jwk(grpc_exec_ctx* exec_ctx, const grpc_json* json, + const char* kty) { + const grpc_json* key_prop; + RSA* rsa = nullptr; + EVP_PKEY* result = nullptr; + BIGNUM* tmp_n = nullptr; + BIGNUM* tmp_e = nullptr; - GPR_ASSERT(kty != NULL && json != NULL); + GPR_ASSERT(kty != nullptr && json != nullptr); if (strcmp(kty, "RSA") != 0) { gpr_log(GPR_ERROR, "Unsupported key type %s.", kty); goto end; } rsa = RSA_new(); - if (rsa == NULL) { + if (rsa == nullptr) { gpr_log(GPR_ERROR, "Could not create rsa key."); goto end; } - for (key_prop = json->child; key_prop != NULL; key_prop = key_prop->next) { + for (key_prop = json->child; key_prop != nullptr; key_prop = key_prop->next) { if (strcmp(key_prop->key, "n") == 0) { tmp_n = bignum_from_base64(exec_ctx, validate_string_field(key_prop, "n")); - if (tmp_n == NULL) goto end; + if (tmp_n == nullptr) goto end; } else if (strcmp(key_prop->key, "e") == 0) { tmp_e = bignum_from_base64(exec_ctx, validate_string_field(key_prop, "e")); - if (tmp_e == NULL) goto end; + if (tmp_e == nullptr) goto end; } } - if (tmp_e == NULL || tmp_n == NULL) { + if (tmp_e == nullptr || tmp_n == nullptr) { gpr_log(GPR_ERROR, "Missing RSA public key field."); goto end; } - if (!RSA_set0_key(rsa, tmp_n, tmp_e, NULL)) { + if (!RSA_set0_key(rsa, tmp_n, tmp_e, nullptr)) { gpr_log(GPR_ERROR, "Cannot set RSA key from inputs."); goto end; } /* RSA_set0_key takes ownership on success. */ - tmp_n = NULL; - tmp_e = NULL; + tmp_n = nullptr; + tmp_e = nullptr; result = EVP_PKEY_new(); EVP_PKEY_set1_RSA(result, rsa); /* uprefs rsa. */ @@ -545,38 +545,39 @@ end: return result; } -static EVP_PKEY *find_verification_key(grpc_exec_ctx *exec_ctx, - const grpc_json *json, - const char *header_alg, - const char *header_kid) { - const grpc_json *jkey; - const grpc_json *jwk_keys; +static EVP_PKEY* find_verification_key(grpc_exec_ctx* exec_ctx, + const grpc_json* json, + const char* header_alg, + const char* header_kid) { + const grpc_json* jkey; + const grpc_json* jwk_keys; /* Try to parse the json as a JWK set: https://tools.ietf.org/html/rfc7517#section-5. */ jwk_keys = find_property_by_name(json, "keys"); - if (jwk_keys == NULL) { + if (jwk_keys == nullptr) { /* Use the google proprietary format which is: { : , : , ... } */ - const grpc_json *cur = find_property_by_name(json, header_kid); - if (cur == NULL) return NULL; + const grpc_json* cur = find_property_by_name(json, header_kid); + if (cur == nullptr) return nullptr; return extract_pkey_from_x509(cur->value); } if (jwk_keys->type != GRPC_JSON_ARRAY) { gpr_log(GPR_ERROR, "Unexpected value type of keys property in jwks key set."); - return NULL; + return nullptr; } /* Key format is specified in: https://tools.ietf.org/html/rfc7518#section-6. */ - for (jkey = jwk_keys->child; jkey != NULL; jkey = jkey->next) { - grpc_json *key_prop; - const char *alg = NULL; - const char *kid = NULL; - const char *kty = NULL; + for (jkey = jwk_keys->child; jkey != nullptr; jkey = jkey->next) { + grpc_json* key_prop; + const char* alg = nullptr; + const char* kid = nullptr; + const char* kty = nullptr; if (jkey->type != GRPC_JSON_OBJECT) continue; - for (key_prop = jkey->child; key_prop != NULL; key_prop = key_prop->next) { + for (key_prop = jkey->child; key_prop != nullptr; + key_prop = key_prop->next) { if (strcmp(key_prop->key, "alg") == 0 && key_prop->type == GRPC_JSON_STRING) { alg = key_prop->value; @@ -588,7 +589,7 @@ static EVP_PKEY *find_verification_key(grpc_exec_ctx *exec_ctx, kty = key_prop->value; } } - if (alg != NULL && kid != NULL && kty != NULL && + if (alg != nullptr && kid != nullptr && kty != nullptr && strcmp(kid, header_kid) == 0 && strcmp(alg, header_alg) == 0) { return pkey_from_jwk(exec_ctx, jkey, kty); } @@ -596,21 +597,21 @@ static EVP_PKEY *find_verification_key(grpc_exec_ctx *exec_ctx, gpr_log(GPR_ERROR, "Could not find matching key in key set for kid=%s and alg=%s", header_kid, header_alg); - return NULL; + return nullptr; } -static int verify_jwt_signature(EVP_PKEY *key, const char *alg, +static int verify_jwt_signature(EVP_PKEY* key, const char* alg, grpc_slice signature, grpc_slice signed_data) { - EVP_MD_CTX *md_ctx = EVP_MD_CTX_create(); - const EVP_MD *md = evp_md_from_alg(alg); + EVP_MD_CTX* md_ctx = EVP_MD_CTX_create(); + const EVP_MD* md = evp_md_from_alg(alg); int result = 0; - GPR_ASSERT(md != NULL); /* Checked before. */ - if (md_ctx == NULL) { + GPR_ASSERT(md != nullptr); /* Checked before. */ + if (md_ctx == nullptr) { gpr_log(GPR_ERROR, "Could not create EVP_MD_CTX."); goto end; } - if (EVP_DigestVerifyInit(md_ctx, NULL, md, NULL, key) != 1) { + if (EVP_DigestVerifyInit(md_ctx, nullptr, md, nullptr, key) != 1) { gpr_log(GPR_ERROR, "EVP_DigestVerifyInit failed."); goto end; } @@ -631,21 +632,21 @@ end: return result; } -static void on_keys_retrieved(grpc_exec_ctx *exec_ctx, void *user_data, - grpc_error *error) { - verifier_cb_ctx *ctx = (verifier_cb_ctx *)user_data; - grpc_json *json = json_from_http(&ctx->responses[HTTP_RESPONSE_KEYS]); - EVP_PKEY *verification_key = NULL; +static void on_keys_retrieved(grpc_exec_ctx* exec_ctx, void* user_data, + grpc_error* error) { + verifier_cb_ctx* ctx = (verifier_cb_ctx*)user_data; + grpc_json* json = json_from_http(&ctx->responses[HTTP_RESPONSE_KEYS]); + EVP_PKEY* verification_key = nullptr; grpc_jwt_verifier_status status = GRPC_JWT_VERIFIER_GENERIC_ERROR; - grpc_jwt_claims *claims = NULL; + grpc_jwt_claims* claims = nullptr; - if (json == NULL) { + if (json == nullptr) { status = GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; goto end; } verification_key = find_verification_key(exec_ctx, json, ctx->header->alg, ctx->header->kid); - if (verification_key == NULL) { + if (verification_key == nullptr) { gpr_log(GPR_ERROR, "Could not find verification key with kid %s.", ctx->header->kid); status = GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR; @@ -662,35 +663,35 @@ static void on_keys_retrieved(grpc_exec_ctx *exec_ctx, void *user_data, if (status == GRPC_JWT_VERIFIER_OK) { /* Pass ownership. */ claims = ctx->claims; - ctx->claims = NULL; + ctx->claims = nullptr; } end: - if (json != NULL) grpc_json_destroy(json); + if (json != nullptr) grpc_json_destroy(json); EVP_PKEY_free(verification_key); ctx->user_cb(exec_ctx, ctx->user_data, status, claims); verifier_cb_ctx_destroy(exec_ctx, ctx); } -static void on_openid_config_retrieved(grpc_exec_ctx *exec_ctx, void *user_data, - grpc_error *error) { - const grpc_json *cur; - verifier_cb_ctx *ctx = (verifier_cb_ctx *)user_data; - const grpc_http_response *response = &ctx->responses[HTTP_RESPONSE_OPENID]; - grpc_json *json = json_from_http(response); +static void on_openid_config_retrieved(grpc_exec_ctx* exec_ctx, void* user_data, + grpc_error* error) { + const grpc_json* cur; + verifier_cb_ctx* ctx = (verifier_cb_ctx*)user_data; + const grpc_http_response* response = &ctx->responses[HTTP_RESPONSE_OPENID]; + grpc_json* json = json_from_http(response); grpc_httpcli_request req; - const char *jwks_uri; - grpc_resource_quota *resource_quota = NULL; + const char* jwks_uri; + grpc_resource_quota* resource_quota = nullptr; /* TODO(jboeuf): Cache the jwks_uri in order to avoid this hop next time. */ - if (json == NULL) goto error; + if (json == nullptr) goto error; cur = find_property_by_name(json, "jwks_uri"); - if (cur == NULL) { + if (cur == nullptr) { gpr_log(GPR_ERROR, "Could not find jwks_uri in openid config."); goto error; } jwks_uri = validate_string_field(cur, "jwks_uri"); - if (jwks_uri == NULL) goto error; + if (jwks_uri == nullptr) goto error; if (strstr(jwks_uri, "https://") != jwks_uri) { gpr_log(GPR_ERROR, "Invalid non https jwks_uri: %s.", jwks_uri); goto error; @@ -698,9 +699,9 @@ static void on_openid_config_retrieved(grpc_exec_ctx *exec_ctx, void *user_data, jwks_uri += 8; req.handshaker = &grpc_httpcli_ssl; req.host = gpr_strdup(jwks_uri); - req.http.path = (char *)strchr(jwks_uri, '/'); - if (req.http.path == NULL) { - req.http.path = (char *)""; + req.http.path = (char*)strchr(jwks_uri, '/'); + if (req.http.path == nullptr) { + req.http.path = (char*)""; } else { *(req.host + (req.http.path - jwks_uri)) = '\0'; } @@ -720,29 +721,29 @@ static void on_openid_config_retrieved(grpc_exec_ctx *exec_ctx, void *user_data, return; error: - if (json != NULL) grpc_json_destroy(json); + if (json != nullptr) grpc_json_destroy(json); ctx->user_cb(exec_ctx, ctx->user_data, GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR, - NULL); + nullptr); verifier_cb_ctx_destroy(exec_ctx, ctx); } -static email_key_mapping *verifier_get_mapping(grpc_jwt_verifier *v, - const char *email_domain) { +static email_key_mapping* verifier_get_mapping(grpc_jwt_verifier* v, + const char* email_domain) { size_t i; - if (v->mappings == NULL) return NULL; + if (v->mappings == nullptr) return nullptr; for (i = 0; i < v->num_mappings; i++) { if (strcmp(email_domain, v->mappings[i].email_domain) == 0) { return &v->mappings[i]; } } - return NULL; + return nullptr; } -static void verifier_put_mapping(grpc_jwt_verifier *v, const char *email_domain, - const char *key_url_prefix) { - email_key_mapping *mapping = verifier_get_mapping(v, email_domain); +static void verifier_put_mapping(grpc_jwt_verifier* v, const char* email_domain, + const char* key_url_prefix) { + email_key_mapping* mapping = verifier_get_mapping(v, email_domain); GPR_ASSERT(v->num_mappings < v->allocated_mappings); - if (mapping != NULL) { + if (mapping != nullptr) { gpr_free(mapping->key_url_prefix); mapping->key_url_prefix = gpr_strdup(key_url_prefix); return; @@ -755,41 +756,42 @@ static void verifier_put_mapping(grpc_jwt_verifier *v, const char *email_domain, /* Very non-sophisticated way to detect an email address. Should be good enough for now... */ -const char *grpc_jwt_issuer_email_domain(const char *issuer) { - const char *at_sign = strchr(issuer, '@'); - if (at_sign == NULL) return NULL; - const char *email_domain = at_sign + 1; - if (*email_domain == '\0') return NULL; - const char *dot = strrchr(email_domain, '.'); - if (dot == NULL || dot == email_domain) return email_domain; +const char* grpc_jwt_issuer_email_domain(const char* issuer) { + const char* at_sign = strchr(issuer, '@'); + if (at_sign == nullptr) return nullptr; + const char* email_domain = at_sign + 1; + if (*email_domain == '\0') return nullptr; + const char* dot = strrchr(email_domain, '.'); + if (dot == nullptr || dot == email_domain) return email_domain; GPR_ASSERT(dot > email_domain); /* There may be a subdomain, we just want the domain. */ - dot = (const char *)gpr_memrchr((void *)email_domain, '.', - (size_t)(dot - email_domain)); - if (dot == NULL) return email_domain; + dot = (const char*)gpr_memrchr((void*)email_domain, '.', + (size_t)(dot - email_domain)); + if (dot == nullptr) return email_domain; return dot + 1; } /* Takes ownership of ctx. */ -static void retrieve_key_and_verify(grpc_exec_ctx *exec_ctx, - verifier_cb_ctx *ctx) { - const char *email_domain; - grpc_closure *http_cb; - char *path_prefix = NULL; - const char *iss; +static void retrieve_key_and_verify(grpc_exec_ctx* exec_ctx, + verifier_cb_ctx* ctx) { + const char* email_domain; + grpc_closure* http_cb; + char* path_prefix = nullptr; + const char* iss; grpc_httpcli_request req; - grpc_resource_quota *resource_quota = NULL; + grpc_resource_quota* resource_quota = nullptr; memset(&req, 0, sizeof(grpc_httpcli_request)); req.handshaker = &grpc_httpcli_ssl; http_response_index rsp_idx; - GPR_ASSERT(ctx != NULL && ctx->header != NULL && ctx->claims != NULL); + GPR_ASSERT(ctx != nullptr && ctx->header != nullptr && + ctx->claims != nullptr); iss = ctx->claims->iss; - if (ctx->header->kid == NULL) { + if (ctx->header->kid == nullptr) { gpr_log(GPR_ERROR, "Missing kid in jose header."); goto error; } - if (iss == NULL) { + if (iss == nullptr) { gpr_log(GPR_ERROR, "Missing iss in claims."); goto error; } @@ -800,17 +802,17 @@ static void retrieve_key_and_verify(grpc_exec_ctx *exec_ctx, so we will rely instead on email/url mappings if we detect such an issuer. Part 4, on the other hand is implemented by both google and salesforce. */ email_domain = grpc_jwt_issuer_email_domain(iss); - if (email_domain != NULL) { - email_key_mapping *mapping; - GPR_ASSERT(ctx->verifier != NULL); + if (email_domain != nullptr) { + email_key_mapping* mapping; + GPR_ASSERT(ctx->verifier != nullptr); mapping = verifier_get_mapping(ctx->verifier, email_domain); - if (mapping == NULL) { + if (mapping == nullptr) { gpr_log(GPR_ERROR, "Missing mapping for issuer email."); goto error; } req.host = gpr_strdup(mapping->key_url_prefix); path_prefix = strchr(req.host, '/'); - if (path_prefix == NULL) { + if (path_prefix == nullptr) { gpr_asprintf(&req.http.path, "/%s", iss); } else { *(path_prefix++) = '\0'; @@ -822,7 +824,7 @@ static void retrieve_key_and_verify(grpc_exec_ctx *exec_ctx, } else { req.host = gpr_strdup(strstr(iss, "https://") == iss ? iss + 8 : iss); path_prefix = strchr(req.host, '/'); - if (path_prefix == NULL) { + if (path_prefix == nullptr) { req.http.path = gpr_strdup(GRPC_OPENID_CONFIG_URL_SUFFIX); } else { *(path_prefix++) = 0; @@ -849,43 +851,44 @@ static void retrieve_key_and_verify(grpc_exec_ctx *exec_ctx, error: ctx->user_cb(exec_ctx, ctx->user_data, GRPC_JWT_VERIFIER_KEY_RETRIEVAL_ERROR, - NULL); + nullptr); verifier_cb_ctx_destroy(exec_ctx, ctx); } -void grpc_jwt_verifier_verify(grpc_exec_ctx *exec_ctx, - grpc_jwt_verifier *verifier, - grpc_pollset *pollset, const char *jwt, - const char *audience, +void grpc_jwt_verifier_verify(grpc_exec_ctx* exec_ctx, + grpc_jwt_verifier* verifier, + grpc_pollset* pollset, const char* jwt, + const char* audience, grpc_jwt_verification_done_cb cb, - void *user_data) { - const char *dot = NULL; - grpc_json *json; - jose_header *header = NULL; - grpc_jwt_claims *claims = NULL; + void* user_data) { + const char* dot = nullptr; + grpc_json* json; + jose_header* header = nullptr; + grpc_jwt_claims* claims = nullptr; grpc_slice header_buffer; grpc_slice claims_buffer; grpc_slice signature; size_t signed_jwt_len; - const char *cur = jwt; + const char* cur = jwt; - GPR_ASSERT(verifier != NULL && jwt != NULL && audience != NULL && cb != NULL); + GPR_ASSERT(verifier != nullptr && jwt != nullptr && audience != nullptr && + cb != nullptr); dot = strchr(cur, '.'); - if (dot == NULL) goto error; + if (dot == nullptr) goto error; json = parse_json_part_from_jwt(exec_ctx, cur, (size_t)(dot - cur), &header_buffer); - if (json == NULL) goto error; + if (json == nullptr) goto error; header = jose_header_from_json(exec_ctx, json, header_buffer); - if (header == NULL) goto error; + if (header == nullptr) goto error; cur = dot + 1; dot = strchr(cur, '.'); - if (dot == NULL) goto error; + if (dot == nullptr) goto error; json = parse_json_part_from_jwt(exec_ctx, cur, (size_t)(dot - cur), &claims_buffer); - if (json == NULL) goto error; + if (json == nullptr) goto error; claims = grpc_jwt_claims_from_json(exec_ctx, json, claims_buffer); - if (claims == NULL) goto error; + if (claims == nullptr) goto error; signed_jwt_len = (size_t)(dot - jwt); cur = dot + 1; @@ -898,26 +901,26 @@ void grpc_jwt_verifier_verify(grpc_exec_ctx *exec_ctx, return; error: - if (header != NULL) jose_header_destroy(exec_ctx, header); - if (claims != NULL) grpc_jwt_claims_destroy(exec_ctx, claims); - cb(exec_ctx, user_data, GRPC_JWT_VERIFIER_BAD_FORMAT, NULL); + if (header != nullptr) jose_header_destroy(exec_ctx, header); + if (claims != nullptr) grpc_jwt_claims_destroy(exec_ctx, claims); + cb(exec_ctx, user_data, GRPC_JWT_VERIFIER_BAD_FORMAT, nullptr); } -grpc_jwt_verifier *grpc_jwt_verifier_create( - const grpc_jwt_verifier_email_domain_key_url_mapping *mappings, +grpc_jwt_verifier* grpc_jwt_verifier_create( + const grpc_jwt_verifier_email_domain_key_url_mapping* mappings, size_t num_mappings) { - grpc_jwt_verifier *v = - (grpc_jwt_verifier *)gpr_zalloc(sizeof(grpc_jwt_verifier)); + grpc_jwt_verifier* v = + (grpc_jwt_verifier*)gpr_zalloc(sizeof(grpc_jwt_verifier)); grpc_httpcli_context_init(&v->http_ctx); /* We know at least of one mapping. */ v->allocated_mappings = 1 + num_mappings; - v->mappings = (email_key_mapping *)gpr_malloc(v->allocated_mappings * - sizeof(email_key_mapping)); + v->mappings = (email_key_mapping*)gpr_malloc(v->allocated_mappings * + sizeof(email_key_mapping)); verifier_put_mapping(v, GRPC_GOOGLE_SERVICE_ACCOUNTS_EMAIL_DOMAIN, GRPC_GOOGLE_SERVICE_ACCOUNTS_KEY_URL_PREFIX); /* User-Provided mappings. */ - if (mappings != NULL) { + if (mappings != nullptr) { size_t i; for (i = 0; i < num_mappings; i++) { verifier_put_mapping(v, mappings[i].email_domain, @@ -927,11 +930,11 @@ grpc_jwt_verifier *grpc_jwt_verifier_create( return v; } -void grpc_jwt_verifier_destroy(grpc_exec_ctx *exec_ctx, grpc_jwt_verifier *v) { +void grpc_jwt_verifier_destroy(grpc_exec_ctx* exec_ctx, grpc_jwt_verifier* v) { size_t i; - if (v == NULL) return; + if (v == nullptr) return; grpc_httpcli_context_destroy(exec_ctx, &v->http_ctx); - if (v->mappings != NULL) { + if (v->mappings != nullptr) { for (i = 0; i < v->num_mappings; i++) { gpr_free(v->mappings[i].email_domain); gpr_free(v->mappings[i].key_url_prefix); diff --git a/src/core/lib/security/credentials/jwt/jwt_verifier.h b/src/core/lib/security/credentials/jwt/jwt_verifier.h index 998365e75c8..2aacd497c7f 100644 --- a/src/core/lib/security/credentials/jwt/jwt_verifier.h +++ b/src/core/lib/security/credentials/jwt/jwt_verifier.h @@ -32,10 +32,6 @@ #define GRPC_GOOGLE_SERVICE_ACCOUNTS_KEY_URL_PREFIX \ "www.googleapis.com/robot/v1/metadata/x509" -#ifdef __cplusplus -extern "C" { -#endif - /* --- grpc_jwt_verifier_status. --- */ typedef enum { @@ -49,25 +45,25 @@ typedef enum { GRPC_JWT_VERIFIER_GENERIC_ERROR } grpc_jwt_verifier_status; -const char *grpc_jwt_verifier_status_to_string(grpc_jwt_verifier_status status); +const char* grpc_jwt_verifier_status_to_string(grpc_jwt_verifier_status status); /* --- grpc_jwt_claims. --- */ typedef struct grpc_jwt_claims grpc_jwt_claims; -void grpc_jwt_claims_destroy(grpc_exec_ctx *exec_ctx, grpc_jwt_claims *claims); +void grpc_jwt_claims_destroy(grpc_exec_ctx* exec_ctx, grpc_jwt_claims* claims); /* Returns the whole JSON tree of the claims. */ -const grpc_json *grpc_jwt_claims_json(const grpc_jwt_claims *claims); +const grpc_json* grpc_jwt_claims_json(const grpc_jwt_claims* claims); /* Access to registered claims in https://tools.ietf.org/html/rfc7519#page-9 */ -const char *grpc_jwt_claims_subject(const grpc_jwt_claims *claims); -const char *grpc_jwt_claims_issuer(const grpc_jwt_claims *claims); -const char *grpc_jwt_claims_id(const grpc_jwt_claims *claims); -const char *grpc_jwt_claims_audience(const grpc_jwt_claims *claims); -gpr_timespec grpc_jwt_claims_issued_at(const grpc_jwt_claims *claims); -gpr_timespec grpc_jwt_claims_expires_at(const grpc_jwt_claims *claims); -gpr_timespec grpc_jwt_claims_not_before(const grpc_jwt_claims *claims); +const char* grpc_jwt_claims_subject(const grpc_jwt_claims* claims); +const char* grpc_jwt_claims_issuer(const grpc_jwt_claims* claims); +const char* grpc_jwt_claims_id(const grpc_jwt_claims* claims); +const char* grpc_jwt_claims_audience(const grpc_jwt_claims* claims); +gpr_timespec grpc_jwt_claims_issued_at(const grpc_jwt_claims* claims); +gpr_timespec grpc_jwt_claims_expires_at(const grpc_jwt_claims* claims); +gpr_timespec grpc_jwt_claims_not_before(const grpc_jwt_claims* claims); /* --- grpc_jwt_verifier. --- */ @@ -75,12 +71,12 @@ typedef struct grpc_jwt_verifier grpc_jwt_verifier; typedef struct { /* The email domain is the part after the @ sign. */ - const char *email_domain; + const char* email_domain; /* The key url prefix will be used to get the public key from the issuer: https:/// Therefore the key_url_prefix must NOT contain https://. */ - const char *key_url_prefix; + const char* key_url_prefix; } grpc_jwt_verifier_email_domain_key_url_mapping; /* Globals to control the verifier. Not thread-safe. */ @@ -93,41 +89,37 @@ extern grpc_millis grpc_jwt_verifier_max_delay; A verifier object has one built-in mapping (unless overridden): GRPC_GOOGLE_SERVICE_ACCOUNTS_EMAIL_DOMAIN -> GRPC_GOOGLE_SERVICE_ACCOUNTS_KEY_URL_PREFIX.*/ -grpc_jwt_verifier *grpc_jwt_verifier_create( - const grpc_jwt_verifier_email_domain_key_url_mapping *mappings, +grpc_jwt_verifier* grpc_jwt_verifier_create( + const grpc_jwt_verifier_email_domain_key_url_mapping* mappings, size_t num_mappings); /*The verifier must not be destroyed if there are still outstanding callbacks.*/ -void grpc_jwt_verifier_destroy(grpc_exec_ctx *exec_ctx, - grpc_jwt_verifier *verifier); +void grpc_jwt_verifier_destroy(grpc_exec_ctx* exec_ctx, + grpc_jwt_verifier* verifier); /* User provided callback that will be called when the verification of the JWT is done (maybe in another thread). It is the responsibility of the callee to call grpc_jwt_claims_destroy on the claims. */ -typedef void (*grpc_jwt_verification_done_cb)(grpc_exec_ctx *exec_ctx, - void *user_data, +typedef void (*grpc_jwt_verification_done_cb)(grpc_exec_ctx* exec_ctx, + void* user_data, grpc_jwt_verifier_status status, - grpc_jwt_claims *claims); + grpc_jwt_claims* claims); /* Verifies for the JWT for the given expected audience. */ -void grpc_jwt_verifier_verify(grpc_exec_ctx *exec_ctx, - grpc_jwt_verifier *verifier, - grpc_pollset *pollset, const char *jwt, - const char *audience, +void grpc_jwt_verifier_verify(grpc_exec_ctx* exec_ctx, + grpc_jwt_verifier* verifier, + grpc_pollset* pollset, const char* jwt, + const char* audience, grpc_jwt_verification_done_cb cb, - void *user_data); + void* user_data); /* --- TESTING ONLY exposed functions. --- */ -grpc_jwt_claims *grpc_jwt_claims_from_json(grpc_exec_ctx *exec_ctx, - grpc_json *json, grpc_slice buffer); -grpc_jwt_verifier_status grpc_jwt_claims_check(const grpc_jwt_claims *claims, - const char *audience); -const char *grpc_jwt_issuer_email_domain(const char *issuer); - -#ifdef __cplusplus -} -#endif +grpc_jwt_claims* grpc_jwt_claims_from_json(grpc_exec_ctx* exec_ctx, + grpc_json* json, grpc_slice buffer); +grpc_jwt_verifier_status grpc_jwt_claims_check(const grpc_jwt_claims* claims, + const char* audience); +const char* grpc_jwt_issuer_email_domain(const char* issuer); #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_JWT_JWT_VERIFIER_H */ diff --git a/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc b/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc index 7867105f567..ccefb4db9cf 100644 --- a/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc +++ b/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc @@ -32,26 +32,26 @@ // int grpc_auth_refresh_token_is_valid( - const grpc_auth_refresh_token *refresh_token) { - return (refresh_token != NULL) && + const grpc_auth_refresh_token* refresh_token) { + return (refresh_token != nullptr) && strcmp(refresh_token->type, GRPC_AUTH_JSON_TYPE_INVALID); } grpc_auth_refresh_token grpc_auth_refresh_token_create_from_json( - const grpc_json *json) { + const grpc_json* json) { grpc_auth_refresh_token result; - const char *prop_value; + const char* prop_value; int success = 0; memset(&result, 0, sizeof(grpc_auth_refresh_token)); result.type = GRPC_AUTH_JSON_TYPE_INVALID; - if (json == NULL) { + if (json == nullptr) { gpr_log(GPR_ERROR, "Invalid json."); goto end; } prop_value = grpc_json_get_string_property(json, "type"); - if (prop_value == NULL || + if (prop_value == nullptr || strcmp(prop_value, GRPC_AUTH_JSON_TYPE_AUTHORIZED_USER)) { goto end; } @@ -72,30 +72,30 @@ end: } grpc_auth_refresh_token grpc_auth_refresh_token_create_from_string( - const char *json_string) { - char *scratchpad = gpr_strdup(json_string); - grpc_json *json = grpc_json_parse_string(scratchpad); + const char* json_string) { + char* scratchpad = gpr_strdup(json_string); + grpc_json* json = grpc_json_parse_string(scratchpad); grpc_auth_refresh_token result = grpc_auth_refresh_token_create_from_json(json); - if (json != NULL) grpc_json_destroy(json); + if (json != nullptr) grpc_json_destroy(json); gpr_free(scratchpad); return result; } -void grpc_auth_refresh_token_destruct(grpc_auth_refresh_token *refresh_token) { - if (refresh_token == NULL) return; +void grpc_auth_refresh_token_destruct(grpc_auth_refresh_token* refresh_token) { + if (refresh_token == nullptr) return; refresh_token->type = GRPC_AUTH_JSON_TYPE_INVALID; - if (refresh_token->client_id != NULL) { + if (refresh_token->client_id != nullptr) { gpr_free(refresh_token->client_id); - refresh_token->client_id = NULL; + refresh_token->client_id = nullptr; } - if (refresh_token->client_secret != NULL) { + if (refresh_token->client_secret != nullptr) { gpr_free(refresh_token->client_secret); - refresh_token->client_secret = NULL; + refresh_token->client_secret = nullptr; } - if (refresh_token->refresh_token != NULL) { + if (refresh_token->refresh_token != nullptr) { gpr_free(refresh_token->refresh_token); - refresh_token->refresh_token = NULL; + refresh_token->refresh_token = nullptr; } } @@ -103,10 +103,10 @@ void grpc_auth_refresh_token_destruct(grpc_auth_refresh_token *refresh_token) { // Oauth2 Token Fetcher credentials. // -static void oauth2_token_fetcher_destruct(grpc_exec_ctx *exec_ctx, - grpc_call_credentials *creds) { - grpc_oauth2_token_fetcher_credentials *c = - (grpc_oauth2_token_fetcher_credentials *)creds; +static void oauth2_token_fetcher_destruct(grpc_exec_ctx* exec_ctx, + grpc_call_credentials* creds) { + grpc_oauth2_token_fetcher_credentials* c = + (grpc_oauth2_token_fetcher_credentials*)creds; GRPC_MDELEM_UNREF(exec_ctx, c->access_token_md); gpr_mu_destroy(&c->mu); grpc_pollset_set_destroy(exec_ctx, @@ -116,21 +116,21 @@ static void oauth2_token_fetcher_destruct(grpc_exec_ctx *exec_ctx, grpc_credentials_status grpc_oauth2_token_fetcher_credentials_parse_server_response( - grpc_exec_ctx *exec_ctx, const grpc_http_response *response, - grpc_mdelem *token_md, grpc_millis *token_lifetime) { - char *null_terminated_body = NULL; - char *new_access_token = NULL; + grpc_exec_ctx* exec_ctx, const grpc_http_response* response, + grpc_mdelem* token_md, grpc_millis* token_lifetime) { + char* null_terminated_body = nullptr; + char* new_access_token = nullptr; grpc_credentials_status status = GRPC_CREDENTIALS_OK; - grpc_json *json = NULL; + grpc_json* json = nullptr; - if (response == NULL) { + if (response == nullptr) { gpr_log(GPR_ERROR, "Received NULL response."); status = GRPC_CREDENTIALS_ERROR; goto end; } if (response->body_length > 0) { - null_terminated_body = (char *)gpr_malloc(response->body_length + 1); + null_terminated_body = (char*)gpr_malloc(response->body_length + 1); null_terminated_body[response->body_length] = '\0'; memcpy(null_terminated_body, response->body, response->body_length); } @@ -138,16 +138,16 @@ grpc_oauth2_token_fetcher_credentials_parse_server_response( if (response->status != 200) { gpr_log(GPR_ERROR, "Call to http server ended with error %d [%s].", response->status, - null_terminated_body != NULL ? null_terminated_body : ""); + null_terminated_body != nullptr ? null_terminated_body : ""); status = GRPC_CREDENTIALS_ERROR; goto end; } else { - grpc_json *access_token = NULL; - grpc_json *token_type = NULL; - grpc_json *expires_in = NULL; - grpc_json *ptr; + grpc_json* access_token = nullptr; + grpc_json* token_type = nullptr; + grpc_json* expires_in = nullptr; + grpc_json* ptr; json = grpc_json_parse_string(null_terminated_body); - if (json == NULL) { + if (json == nullptr) { gpr_log(GPR_ERROR, "Could not parse JSON from %s", null_terminated_body); status = GRPC_CREDENTIALS_ERROR; goto end; @@ -166,24 +166,24 @@ grpc_oauth2_token_fetcher_credentials_parse_server_response( expires_in = ptr; } } - if (access_token == NULL || access_token->type != GRPC_JSON_STRING) { + if (access_token == nullptr || access_token->type != GRPC_JSON_STRING) { gpr_log(GPR_ERROR, "Missing or invalid access_token in JSON."); status = GRPC_CREDENTIALS_ERROR; goto end; } - if (token_type == NULL || token_type->type != GRPC_JSON_STRING) { + if (token_type == nullptr || token_type->type != GRPC_JSON_STRING) { gpr_log(GPR_ERROR, "Missing or invalid token_type in JSON."); status = GRPC_CREDENTIALS_ERROR; goto end; } - if (expires_in == NULL || expires_in->type != GRPC_JSON_NUMBER) { + if (expires_in == nullptr || expires_in->type != GRPC_JSON_NUMBER) { gpr_log(GPR_ERROR, "Missing or invalid expires_in in JSON."); status = GRPC_CREDENTIALS_ERROR; goto end; } gpr_asprintf(&new_access_token, "%s %s", token_type->value, access_token->value); - *token_lifetime = strtol(expires_in->value, NULL, 10) * GPR_MS_PER_SEC; + *token_lifetime = strtol(expires_in->value, nullptr, 10) * GPR_MS_PER_SEC; if (!GRPC_MDISNULL(*token_md)) GRPC_MDELEM_UNREF(exec_ctx, *token_md); *token_md = grpc_mdelem_from_slices( exec_ctx, @@ -197,20 +197,20 @@ end: GRPC_MDELEM_UNREF(exec_ctx, *token_md); *token_md = GRPC_MDNULL; } - if (null_terminated_body != NULL) gpr_free(null_terminated_body); - if (new_access_token != NULL) gpr_free(new_access_token); - if (json != NULL) grpc_json_destroy(json); + if (null_terminated_body != nullptr) gpr_free(null_terminated_body); + if (new_access_token != nullptr) gpr_free(new_access_token); + if (json != nullptr) grpc_json_destroy(json); return status; } -static void on_oauth2_token_fetcher_http_response(grpc_exec_ctx *exec_ctx, - void *user_data, - grpc_error *error) { +static void on_oauth2_token_fetcher_http_response(grpc_exec_ctx* exec_ctx, + void* user_data, + grpc_error* error) { GRPC_LOG_IF_ERROR("oauth_fetch", GRPC_ERROR_REF(error)); - grpc_credentials_metadata_request *r = - (grpc_credentials_metadata_request *)user_data; - grpc_oauth2_token_fetcher_credentials *c = - (grpc_oauth2_token_fetcher_credentials *)r->creds; + grpc_credentials_metadata_request* r = + (grpc_credentials_metadata_request*)user_data; + grpc_oauth2_token_fetcher_credentials* c = + (grpc_oauth2_token_fetcher_credentials*)r->creds; grpc_mdelem access_token_md = GRPC_MDNULL; grpc_millis token_lifetime; grpc_credentials_status status = @@ -223,12 +223,12 @@ static void on_oauth2_token_fetcher_http_response(grpc_exec_ctx *exec_ctx, c->token_expiration = status == GRPC_CREDENTIALS_OK ? grpc_exec_ctx_now(exec_ctx) + token_lifetime : 0; - grpc_oauth2_pending_get_request_metadata *pending_request = + grpc_oauth2_pending_get_request_metadata* pending_request = c->pending_requests; - c->pending_requests = NULL; + c->pending_requests = nullptr; gpr_mu_unlock(&c->mu); // Invoke callbacks for all pending requests. - while (pending_request != NULL) { + while (pending_request != nullptr) { if (status == GRPC_CREDENTIALS_OK) { grpc_credentials_mdelem_array_add(pending_request->md_array, access_token_md); @@ -240,7 +240,7 @@ static void on_oauth2_token_fetcher_http_response(grpc_exec_ctx *exec_ctx, grpc_polling_entity_del_from_pollset_set( exec_ctx, pending_request->pollent, grpc_polling_entity_pollset_set(&c->pollent)); - grpc_oauth2_pending_get_request_metadata *prev = pending_request; + grpc_oauth2_pending_get_request_metadata* prev = pending_request; pending_request = pending_request->next; gpr_free(prev); } @@ -250,12 +250,12 @@ static void on_oauth2_token_fetcher_http_response(grpc_exec_ctx *exec_ctx, } static bool oauth2_token_fetcher_get_request_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_credentials *creds, - grpc_polling_entity *pollent, grpc_auth_metadata_context context, - grpc_credentials_mdelem_array *md_array, grpc_closure *on_request_metadata, - grpc_error **error) { - grpc_oauth2_token_fetcher_credentials *c = - (grpc_oauth2_token_fetcher_credentials *)creds; + grpc_exec_ctx* exec_ctx, grpc_call_credentials* creds, + grpc_polling_entity* pollent, grpc_auth_metadata_context context, + grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata, + grpc_error** error) { + grpc_oauth2_token_fetcher_credentials* c = + (grpc_oauth2_token_fetcher_credentials*)creds; // Check if we can use the cached token. grpc_millis refresh_threshold = GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS * GPR_MS_PER_SEC; @@ -273,8 +273,8 @@ static bool oauth2_token_fetcher_get_request_metadata( } // Couldn't get the token from the cache. // Add request to c->pending_requests and start a new fetch if needed. - grpc_oauth2_pending_get_request_metadata *pending_request = - (grpc_oauth2_pending_get_request_metadata *)gpr_malloc( + grpc_oauth2_pending_get_request_metadata* pending_request = + (grpc_oauth2_pending_get_request_metadata*)gpr_malloc( sizeof(*pending_request)); pending_request->md_array = md_array; pending_request->on_request_metadata = on_request_metadata; @@ -300,18 +300,18 @@ static bool oauth2_token_fetcher_get_request_metadata( } static void oauth2_token_fetcher_cancel_get_request_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_credentials *creds, - grpc_credentials_mdelem_array *md_array, grpc_error *error) { - grpc_oauth2_token_fetcher_credentials *c = - (grpc_oauth2_token_fetcher_credentials *)creds; + grpc_exec_ctx* exec_ctx, grpc_call_credentials* creds, + grpc_credentials_mdelem_array* md_array, grpc_error* error) { + grpc_oauth2_token_fetcher_credentials* c = + (grpc_oauth2_token_fetcher_credentials*)creds; gpr_mu_lock(&c->mu); - grpc_oauth2_pending_get_request_metadata *prev = NULL; - grpc_oauth2_pending_get_request_metadata *pending_request = + grpc_oauth2_pending_get_request_metadata* prev = nullptr; + grpc_oauth2_pending_get_request_metadata* pending_request = c->pending_requests; - while (pending_request != NULL) { + while (pending_request != nullptr) { if (pending_request->md_array == md_array) { // Remove matching pending request from the list. - if (prev != NULL) { + if (prev != nullptr) { prev->next = pending_request->next; } else { c->pending_requests = pending_request->next; @@ -329,7 +329,7 @@ static void oauth2_token_fetcher_cancel_get_request_metadata( GRPC_ERROR_UNREF(error); } -static void init_oauth2_token_fetcher(grpc_oauth2_token_fetcher_credentials *c, +static void init_oauth2_token_fetcher(grpc_oauth2_token_fetcher_credentials* c, grpc_fetch_oauth2_func fetch_func) { memset(c, 0, sizeof(grpc_oauth2_token_fetcher_credentials)); c->base.type = GRPC_CALL_CREDENTIALS_TYPE_OAUTH2; @@ -351,20 +351,20 @@ static grpc_call_credentials_vtable compute_engine_vtable = { oauth2_token_fetcher_cancel_get_request_metadata}; static void compute_engine_fetch_oauth2( - grpc_exec_ctx *exec_ctx, grpc_credentials_metadata_request *metadata_req, - grpc_httpcli_context *httpcli_context, grpc_polling_entity *pollent, + grpc_exec_ctx* exec_ctx, grpc_credentials_metadata_request* metadata_req, + grpc_httpcli_context* httpcli_context, grpc_polling_entity* pollent, grpc_iomgr_cb_func response_cb, grpc_millis deadline) { - grpc_http_header header = {(char *)"Metadata-Flavor", (char *)"Google"}; + grpc_http_header header = {(char*)"Metadata-Flavor", (char*)"Google"}; grpc_httpcli_request request; memset(&request, 0, sizeof(grpc_httpcli_request)); - request.host = (char *)GRPC_COMPUTE_ENGINE_METADATA_HOST; - request.http.path = (char *)GRPC_COMPUTE_ENGINE_METADATA_TOKEN_PATH; + request.host = (char*)GRPC_COMPUTE_ENGINE_METADATA_HOST; + request.http.path = (char*)GRPC_COMPUTE_ENGINE_METADATA_TOKEN_PATH; request.http.hdr_count = 1; request.http.hdrs = &header; /* TODO(ctiller): Carry the resource_quota in ctx and share it with the host channel. This would allow us to cancel an authentication query when under extreme memory pressure. */ - grpc_resource_quota *resource_quota = + grpc_resource_quota* resource_quota = grpc_resource_quota_create("oauth2_credentials"); grpc_httpcli_get( exec_ctx, httpcli_context, pollent, resource_quota, &request, deadline, @@ -373,14 +373,14 @@ static void compute_engine_fetch_oauth2( grpc_resource_quota_unref_internal(exec_ctx, resource_quota); } -grpc_call_credentials *grpc_google_compute_engine_credentials_create( - void *reserved) { - grpc_oauth2_token_fetcher_credentials *c = - (grpc_oauth2_token_fetcher_credentials *)gpr_malloc( +grpc_call_credentials* grpc_google_compute_engine_credentials_create( + void* reserved) { + grpc_oauth2_token_fetcher_credentials* c = + (grpc_oauth2_token_fetcher_credentials*)gpr_malloc( sizeof(grpc_oauth2_token_fetcher_credentials)); GRPC_API_TRACE("grpc_compute_engine_credentials_create(reserved=%p)", 1, (reserved)); - GPR_ASSERT(reserved == NULL); + GPR_ASSERT(reserved == nullptr); init_oauth2_token_fetcher(c, compute_engine_fetch_oauth2); c->base.vtable = &compute_engine_vtable; return &c->base; @@ -390,10 +390,10 @@ grpc_call_credentials *grpc_google_compute_engine_credentials_create( // Google Refresh Token credentials. // -static void refresh_token_destruct(grpc_exec_ctx *exec_ctx, - grpc_call_credentials *creds) { - grpc_google_refresh_token_credentials *c = - (grpc_google_refresh_token_credentials *)creds; +static void refresh_token_destruct(grpc_exec_ctx* exec_ctx, + grpc_call_credentials* creds) { + grpc_google_refresh_token_credentials* c = + (grpc_google_refresh_token_credentials*)creds; grpc_auth_refresh_token_destruct(&c->refresh_token); oauth2_token_fetcher_destruct(exec_ctx, &c->base.base); } @@ -403,28 +403,28 @@ static grpc_call_credentials_vtable refresh_token_vtable = { oauth2_token_fetcher_cancel_get_request_metadata}; static void refresh_token_fetch_oauth2( - grpc_exec_ctx *exec_ctx, grpc_credentials_metadata_request *metadata_req, - grpc_httpcli_context *httpcli_context, grpc_polling_entity *pollent, + grpc_exec_ctx* exec_ctx, grpc_credentials_metadata_request* metadata_req, + grpc_httpcli_context* httpcli_context, grpc_polling_entity* pollent, grpc_iomgr_cb_func response_cb, grpc_millis deadline) { - grpc_google_refresh_token_credentials *c = - (grpc_google_refresh_token_credentials *)metadata_req->creds; - grpc_http_header header = {(char *)"Content-Type", - (char *)"application/x-www-form-urlencoded"}; + grpc_google_refresh_token_credentials* c = + (grpc_google_refresh_token_credentials*)metadata_req->creds; + grpc_http_header header = {(char*)"Content-Type", + (char*)"application/x-www-form-urlencoded"}; grpc_httpcli_request request; - char *body = NULL; + char* body = nullptr; gpr_asprintf(&body, GRPC_REFRESH_TOKEN_POST_BODY_FORMAT_STRING, c->refresh_token.client_id, c->refresh_token.client_secret, c->refresh_token.refresh_token); memset(&request, 0, sizeof(grpc_httpcli_request)); - request.host = (char *)GRPC_GOOGLE_OAUTH2_SERVICE_HOST; - request.http.path = (char *)GRPC_GOOGLE_OAUTH2_SERVICE_TOKEN_PATH; + request.host = (char*)GRPC_GOOGLE_OAUTH2_SERVICE_HOST; + request.http.path = (char*)GRPC_GOOGLE_OAUTH2_SERVICE_TOKEN_PATH; request.http.hdr_count = 1; request.http.hdrs = &header; request.handshaker = &grpc_httpcli_ssl; /* TODO(ctiller): Carry the resource_quota in ctx and share it with the host channel. This would allow us to cancel an authentication query when under extreme memory pressure. */ - grpc_resource_quota *resource_quota = + grpc_resource_quota* resource_quota = grpc_resource_quota_create("oauth2_credentials_refresh"); grpc_httpcli_post( exec_ctx, httpcli_context, pollent, resource_quota, &request, body, @@ -435,15 +435,15 @@ static void refresh_token_fetch_oauth2( gpr_free(body); } -grpc_call_credentials * +grpc_call_credentials* grpc_refresh_token_credentials_create_from_auth_refresh_token( grpc_auth_refresh_token refresh_token) { - grpc_google_refresh_token_credentials *c; + grpc_google_refresh_token_credentials* c; if (!grpc_auth_refresh_token_is_valid(&refresh_token)) { gpr_log(GPR_ERROR, "Invalid input for refresh token credentials creation"); - return NULL; + return nullptr; } - c = (grpc_google_refresh_token_credentials *)gpr_zalloc( + c = (grpc_google_refresh_token_credentials*)gpr_zalloc( sizeof(grpc_google_refresh_token_credentials)); init_oauth2_token_fetcher(&c->base, refresh_token_fetch_oauth2); c->base.base.vtable = &refresh_token_vtable; @@ -451,11 +451,11 @@ grpc_refresh_token_credentials_create_from_auth_refresh_token( return &c->base.base; } -static char *create_loggable_refresh_token(grpc_auth_refresh_token *token) { +static char* create_loggable_refresh_token(grpc_auth_refresh_token* token) { if (strcmp(token->type, GRPC_AUTH_JSON_TYPE_INVALID) == 0) { return gpr_strdup(""); } - char *loggable_token = NULL; + char* loggable_token = nullptr; gpr_asprintf(&loggable_token, "{\n type: %s\n client_id: %s\n client_secret: " "\n refresh_token: \n}", @@ -463,19 +463,19 @@ static char *create_loggable_refresh_token(grpc_auth_refresh_token *token) { return loggable_token; } -grpc_call_credentials *grpc_google_refresh_token_credentials_create( - const char *json_refresh_token, void *reserved) { +grpc_call_credentials* grpc_google_refresh_token_credentials_create( + const char* json_refresh_token, void* reserved) { grpc_auth_refresh_token token = grpc_auth_refresh_token_create_from_string(json_refresh_token); - if (GRPC_TRACER_ON(grpc_api_trace)) { - char *loggable_token = create_loggable_refresh_token(&token); + if (grpc_api_trace.enabled()) { + char* loggable_token = create_loggable_refresh_token(&token); gpr_log(GPR_INFO, "grpc_refresh_token_credentials_create(json_refresh_token=%s, " "reserved=%p)", loggable_token, reserved); gpr_free(loggable_token); } - GPR_ASSERT(reserved == NULL); + GPR_ASSERT(reserved == nullptr); return grpc_refresh_token_credentials_create_from_auth_refresh_token(token); } @@ -483,25 +483,25 @@ grpc_call_credentials *grpc_google_refresh_token_credentials_create( // Oauth2 Access Token credentials. // -static void access_token_destruct(grpc_exec_ctx *exec_ctx, - grpc_call_credentials *creds) { - grpc_access_token_credentials *c = (grpc_access_token_credentials *)creds; +static void access_token_destruct(grpc_exec_ctx* exec_ctx, + grpc_call_credentials* creds) { + grpc_access_token_credentials* c = (grpc_access_token_credentials*)creds; GRPC_MDELEM_UNREF(exec_ctx, c->access_token_md); } static bool access_token_get_request_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_credentials *creds, - grpc_polling_entity *pollent, grpc_auth_metadata_context context, - grpc_credentials_mdelem_array *md_array, grpc_closure *on_request_metadata, - grpc_error **error) { - grpc_access_token_credentials *c = (grpc_access_token_credentials *)creds; + grpc_exec_ctx* exec_ctx, grpc_call_credentials* creds, + grpc_polling_entity* pollent, grpc_auth_metadata_context context, + grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata, + grpc_error** error) { + grpc_access_token_credentials* c = (grpc_access_token_credentials*)creds; grpc_credentials_mdelem_array_add(md_array, c->access_token_md); return true; } static void access_token_cancel_get_request_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_credentials *c, - grpc_credentials_mdelem_array *md_array, grpc_error *error) { + grpc_exec_ctx* exec_ctx, grpc_call_credentials* c, + grpc_credentials_mdelem_array* md_array, grpc_error* error) { GRPC_ERROR_UNREF(error); } @@ -509,20 +509,19 @@ static grpc_call_credentials_vtable access_token_vtable = { access_token_destruct, access_token_get_request_metadata, access_token_cancel_get_request_metadata}; -grpc_call_credentials *grpc_access_token_credentials_create( - const char *access_token, void *reserved) { - grpc_access_token_credentials *c = - (grpc_access_token_credentials *)gpr_zalloc( - sizeof(grpc_access_token_credentials)); +grpc_call_credentials* grpc_access_token_credentials_create( + const char* access_token, void* reserved) { + grpc_access_token_credentials* c = (grpc_access_token_credentials*)gpr_zalloc( + sizeof(grpc_access_token_credentials)); GRPC_API_TRACE( "grpc_access_token_credentials_create(access_token=, " "reserved=%p)", 1, (reserved)); - GPR_ASSERT(reserved == NULL); + GPR_ASSERT(reserved == nullptr); c->base.type = GRPC_CALL_CREDENTIALS_TYPE_OAUTH2; c->base.vtable = &access_token_vtable; gpr_ref_init(&c->base.refcount, 1); - char *token_md_value; + char* token_md_value; gpr_asprintf(&token_md_value, "Bearer %s", access_token); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; c->access_token_md = grpc_mdelem_from_slices( diff --git a/src/core/lib/security/credentials/oauth2/oauth2_credentials.h b/src/core/lib/security/credentials/oauth2/oauth2_credentials.h index c12db896f33..627783d648f 100644 --- a/src/core/lib/security/credentials/oauth2/oauth2_credentials.h +++ b/src/core/lib/security/credentials/oauth2/oauth2_credentials.h @@ -22,52 +22,48 @@ #include "src/core/lib/json/json.h" #include "src/core/lib/security/credentials/credentials.h" -#ifdef __cplusplus -extern "C" { -#endif - // auth_refresh_token parsing. typedef struct { - const char *type; - char *client_id; - char *client_secret; - char *refresh_token; + const char* type; + char* client_id; + char* client_secret; + char* refresh_token; } grpc_auth_refresh_token; /// Returns 1 if the object is valid, 0 otherwise. int grpc_auth_refresh_token_is_valid( - const grpc_auth_refresh_token *refresh_token); + const grpc_auth_refresh_token* refresh_token); /// Creates a refresh token object from string. Returns an invalid object if a /// parsing error has been encountered. grpc_auth_refresh_token grpc_auth_refresh_token_create_from_string( - const char *json_string); + const char* json_string); /// Creates a refresh token object from parsed json. Returns an invalid object /// if a parsing error has been encountered. grpc_auth_refresh_token grpc_auth_refresh_token_create_from_json( - const grpc_json *json); + const grpc_json* json); /// Destructs the object. -void grpc_auth_refresh_token_destruct(grpc_auth_refresh_token *refresh_token); +void grpc_auth_refresh_token_destruct(grpc_auth_refresh_token* refresh_token); // -- Oauth2 Token Fetcher credentials -- // // This object is a base for credentials that need to acquire an oauth2 token // from an http service. -typedef void (*grpc_fetch_oauth2_func)(grpc_exec_ctx *exec_ctx, - grpc_credentials_metadata_request *req, - grpc_httpcli_context *http_context, - grpc_polling_entity *pollent, +typedef void (*grpc_fetch_oauth2_func)(grpc_exec_ctx* exec_ctx, + grpc_credentials_metadata_request* req, + grpc_httpcli_context* http_context, + grpc_polling_entity* pollent, grpc_iomgr_cb_func cb, grpc_millis deadline); typedef struct grpc_oauth2_pending_get_request_metadata { - grpc_credentials_mdelem_array *md_array; - grpc_closure *on_request_metadata; - grpc_polling_entity *pollent; - struct grpc_oauth2_pending_get_request_metadata *next; + grpc_credentials_mdelem_array* md_array; + grpc_closure* on_request_metadata; + grpc_polling_entity* pollent; + struct grpc_oauth2_pending_get_request_metadata* next; } grpc_oauth2_pending_get_request_metadata; typedef struct { @@ -76,7 +72,7 @@ typedef struct { grpc_mdelem access_token_md; grpc_millis token_expiration; bool token_fetch_pending; - grpc_oauth2_pending_get_request_metadata *pending_requests; + grpc_oauth2_pending_get_request_metadata* pending_requests; grpc_httpcli_context httpcli_context; grpc_fetch_oauth2_func fetch_func; grpc_polling_entity pollent; @@ -96,18 +92,14 @@ typedef struct { // Private constructor for refresh token credentials from an already parsed // refresh token. Takes ownership of the refresh token. -grpc_call_credentials * +grpc_call_credentials* grpc_refresh_token_credentials_create_from_auth_refresh_token( grpc_auth_refresh_token token); // Exposed for testing only. grpc_credentials_status grpc_oauth2_token_fetcher_credentials_parse_server_response( - grpc_exec_ctx *exec_ctx, const struct grpc_http_response *response, - grpc_mdelem *token_md, grpc_millis *token_lifetime); - -#ifdef __cplusplus -} -#endif + grpc_exec_ctx* exec_ctx, const struct grpc_http_response* response, + grpc_mdelem* token_md, grpc_millis* token_lifetime); #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_OAUTH2_OAUTH2_CREDENTIALS_H */ diff --git a/src/core/lib/security/credentials/plugin/plugin_credentials.cc b/src/core/lib/security/credentials/plugin/plugin_credentials.cc index 8106a730fea..1f1efd078d6 100644 --- a/src/core/lib/security/credentials/plugin/plugin_credentials.cc +++ b/src/core/lib/security/credentials/plugin/plugin_credentials.cc @@ -31,27 +31,26 @@ #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/validate_metadata.h" -grpc_tracer_flag grpc_plugin_credentials_trace = - GRPC_TRACER_INITIALIZER(false, "plugin_credentials"); +grpc_core::TraceFlag grpc_plugin_credentials_trace(false, "plugin_credentials"); -static void plugin_destruct(grpc_exec_ctx *exec_ctx, - grpc_call_credentials *creds) { - grpc_plugin_credentials *c = (grpc_plugin_credentials *)creds; +static void plugin_destruct(grpc_exec_ctx* exec_ctx, + grpc_call_credentials* creds) { + grpc_plugin_credentials* c = (grpc_plugin_credentials*)creds; gpr_mu_destroy(&c->mu); - if (c->plugin.state != NULL && c->plugin.destroy != NULL) { + if (c->plugin.state != nullptr && c->plugin.destroy != nullptr) { c->plugin.destroy(c->plugin.state); } } static void pending_request_remove_locked( - grpc_plugin_credentials *c, - grpc_plugin_credentials_pending_request *pending_request) { - if (pending_request->prev == NULL) { + grpc_plugin_credentials* c, + grpc_plugin_credentials_pending_request* pending_request) { + if (pending_request->prev == nullptr) { c->pending_requests = pending_request->next; } else { pending_request->prev->next = pending_request->next; } - if (pending_request->next != NULL) { + if (pending_request->next != nullptr) { pending_request->next->prev = pending_request->prev; } } @@ -62,7 +61,7 @@ static void pending_request_remove_locked( // When this returns, r->cancelled indicates whether the request was // cancelled before completion. static void pending_request_complete( - grpc_exec_ctx *exec_ctx, grpc_plugin_credentials_pending_request *r) { + grpc_exec_ctx* exec_ctx, grpc_plugin_credentials_pending_request* r) { gpr_mu_lock(&r->creds->mu); if (!r->cancelled) pending_request_remove_locked(r->creds, r); gpr_mu_unlock(&r->creds->mu); @@ -70,13 +69,13 @@ static void pending_request_complete( grpc_call_credentials_unref(exec_ctx, &r->creds->base); } -static grpc_error *process_plugin_result( - grpc_exec_ctx *exec_ctx, grpc_plugin_credentials_pending_request *r, - const grpc_metadata *md, size_t num_md, grpc_status_code status, - const char *error_details) { - grpc_error *error = GRPC_ERROR_NONE; +static grpc_error* process_plugin_result( + grpc_exec_ctx* exec_ctx, grpc_plugin_credentials_pending_request* r, + const grpc_metadata* md, size_t num_md, grpc_status_code status, + const char* error_details) { + grpc_error* error = GRPC_ERROR_NONE; if (status != GRPC_STATUS_OK) { - char *msg; + char* msg; gpr_asprintf(&msg, "Getting metadata from plugin failed with error: %s", error_details); error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); @@ -112,18 +111,18 @@ static grpc_error *process_plugin_result( return error; } -static void plugin_md_request_metadata_ready(void *request, - const grpc_metadata *md, +static void plugin_md_request_metadata_ready(void* request, + const grpc_metadata* md, size_t num_md, grpc_status_code status, - const char *error_details) { + const char* error_details) { /* called from application code */ grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INITIALIZER( GRPC_EXEC_CTX_FLAG_IS_FINISHED | GRPC_EXEC_CTX_FLAG_THREAD_RESOURCE_LOOP, - NULL, NULL); - grpc_plugin_credentials_pending_request *r = - (grpc_plugin_credentials_pending_request *)request; - if (GRPC_TRACER_ON(grpc_plugin_credentials_trace)) { + nullptr, nullptr); + grpc_plugin_credentials_pending_request* r = + (grpc_plugin_credentials_pending_request*)request; + if (grpc_plugin_credentials_trace.enabled()) { gpr_log(GPR_INFO, "plugin_credentials[%p]: request %p: plugin returned " "asynchronously", @@ -133,10 +132,10 @@ static void plugin_md_request_metadata_ready(void *request, pending_request_complete(&exec_ctx, r); // If it has not been cancelled, process it. if (!r->cancelled) { - grpc_error *error = + grpc_error* error = process_plugin_result(&exec_ctx, r, md, num_md, status, error_details); GRPC_CLOSURE_SCHED(&exec_ctx, r->on_request_metadata, error); - } else if (GRPC_TRACER_ON(grpc_plugin_credentials_trace)) { + } else if (grpc_plugin_credentials_trace.enabled()) { gpr_log(GPR_INFO, "plugin_credentials[%p]: request %p: plugin was previously " "cancelled", @@ -146,33 +145,33 @@ static void plugin_md_request_metadata_ready(void *request, grpc_exec_ctx_finish(&exec_ctx); } -static bool plugin_get_request_metadata(grpc_exec_ctx *exec_ctx, - grpc_call_credentials *creds, - grpc_polling_entity *pollent, +static bool plugin_get_request_metadata(grpc_exec_ctx* exec_ctx, + grpc_call_credentials* creds, + grpc_polling_entity* pollent, grpc_auth_metadata_context context, - grpc_credentials_mdelem_array *md_array, - grpc_closure *on_request_metadata, - grpc_error **error) { - grpc_plugin_credentials *c = (grpc_plugin_credentials *)creds; + grpc_credentials_mdelem_array* md_array, + grpc_closure* on_request_metadata, + grpc_error** error) { + grpc_plugin_credentials* c = (grpc_plugin_credentials*)creds; bool retval = true; // Synchronous return. - if (c->plugin.get_metadata != NULL) { + if (c->plugin.get_metadata != nullptr) { // Create pending_request object. - grpc_plugin_credentials_pending_request *pending_request = - (grpc_plugin_credentials_pending_request *)gpr_zalloc( + grpc_plugin_credentials_pending_request* pending_request = + (grpc_plugin_credentials_pending_request*)gpr_zalloc( sizeof(*pending_request)); pending_request->creds = c; pending_request->md_array = md_array; pending_request->on_request_metadata = on_request_metadata; // Add it to the pending list. gpr_mu_lock(&c->mu); - if (c->pending_requests != NULL) { + if (c->pending_requests != nullptr) { c->pending_requests->prev = pending_request; } pending_request->next = c->pending_requests; c->pending_requests = pending_request; gpr_mu_unlock(&c->mu); // Invoke the plugin. The callback holds a ref to us. - if (GRPC_TRACER_ON(grpc_plugin_credentials_trace)) { + if (grpc_plugin_credentials_trace.enabled()) { gpr_log(GPR_INFO, "plugin_credentials[%p]: request %p: invoking plugin", c, pending_request); } @@ -180,12 +179,12 @@ static bool plugin_get_request_metadata(grpc_exec_ctx *exec_ctx, grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX]; size_t num_creds_md = 0; grpc_status_code status = GRPC_STATUS_OK; - const char *error_details = NULL; + const char* error_details = nullptr; if (!c->plugin.get_metadata(c->plugin.state, context, plugin_md_request_metadata_ready, pending_request, creds_md, &num_creds_md, &status, &error_details)) { - if (GRPC_TRACER_ON(grpc_plugin_credentials_trace)) { + if (grpc_plugin_credentials_trace.enabled()) { gpr_log(GPR_INFO, "plugin_credentials[%p]: request %p: plugin will return " "asynchronously", @@ -200,7 +199,7 @@ static bool plugin_get_request_metadata(grpc_exec_ctx *exec_ctx, // asynchronously by plugin_cancel_get_request_metadata(), so return // false. Otherwise, process the result. if (pending_request->cancelled) { - if (GRPC_TRACER_ON(grpc_plugin_credentials_trace)) { + if (grpc_plugin_credentials_trace.enabled()) { gpr_log(GPR_INFO, "plugin_credentials[%p]: request %p was cancelled, error " "will be returned asynchronously", @@ -208,7 +207,7 @@ static bool plugin_get_request_metadata(grpc_exec_ctx *exec_ctx, } retval = false; } else { - if (GRPC_TRACER_ON(grpc_plugin_credentials_trace)) { + if (grpc_plugin_credentials_trace.enabled()) { gpr_log(GPR_INFO, "plugin_credentials[%p]: request %p: plugin returned " "synchronously", @@ -222,22 +221,22 @@ static bool plugin_get_request_metadata(grpc_exec_ctx *exec_ctx, grpc_slice_unref_internal(exec_ctx, creds_md[i].key); grpc_slice_unref_internal(exec_ctx, creds_md[i].value); } - gpr_free((void *)error_details); + gpr_free((void*)error_details); gpr_free(pending_request); } return retval; } static void plugin_cancel_get_request_metadata( - grpc_exec_ctx *exec_ctx, grpc_call_credentials *creds, - grpc_credentials_mdelem_array *md_array, grpc_error *error) { - grpc_plugin_credentials *c = (grpc_plugin_credentials *)creds; + grpc_exec_ctx* exec_ctx, grpc_call_credentials* creds, + grpc_credentials_mdelem_array* md_array, grpc_error* error) { + grpc_plugin_credentials* c = (grpc_plugin_credentials*)creds; gpr_mu_lock(&c->mu); - for (grpc_plugin_credentials_pending_request *pending_request = + for (grpc_plugin_credentials_pending_request* pending_request = c->pending_requests; - pending_request != NULL; pending_request = pending_request->next) { + pending_request != nullptr; pending_request = pending_request->next) { if (pending_request->md_array == md_array) { - if (GRPC_TRACER_ON(grpc_plugin_credentials_trace)) { + if (grpc_plugin_credentials_trace.enabled()) { gpr_log(GPR_INFO, "plugin_credentials[%p]: cancelling request %p", c, pending_request); } @@ -256,13 +255,12 @@ static grpc_call_credentials_vtable plugin_vtable = { plugin_destruct, plugin_get_request_metadata, plugin_cancel_get_request_metadata}; -grpc_call_credentials *grpc_metadata_credentials_create_from_plugin( - grpc_metadata_credentials_plugin plugin, void *reserved) { - grpc_plugin_credentials *c = - (grpc_plugin_credentials *)gpr_zalloc(sizeof(*c)); +grpc_call_credentials* grpc_metadata_credentials_create_from_plugin( + grpc_metadata_credentials_plugin plugin, void* reserved) { + grpc_plugin_credentials* c = (grpc_plugin_credentials*)gpr_zalloc(sizeof(*c)); GRPC_API_TRACE("grpc_metadata_credentials_create_from_plugin(reserved=%p)", 1, (reserved)); - GPR_ASSERT(reserved == NULL); + GPR_ASSERT(reserved == nullptr); c->base.type = plugin.type; c->base.vtable = &plugin_vtable; gpr_ref_init(&c->base.refcount, 1); diff --git a/src/core/lib/security/credentials/plugin/plugin_credentials.h b/src/core/lib/security/credentials/plugin/plugin_credentials.h index f56df9eac5a..e1467b08247 100644 --- a/src/core/lib/security/credentials/plugin/plugin_credentials.h +++ b/src/core/lib/security/credentials/plugin/plugin_credentials.h @@ -21,24 +21,24 @@ #include "src/core/lib/security/credentials/credentials.h" -extern grpc_tracer_flag grpc_plugin_credentials_trace; +extern grpc_core::TraceFlag grpc_plugin_credentials_trace; struct grpc_plugin_credentials; typedef struct grpc_plugin_credentials_pending_request { bool cancelled; - struct grpc_plugin_credentials *creds; - grpc_credentials_mdelem_array *md_array; - grpc_closure *on_request_metadata; - struct grpc_plugin_credentials_pending_request *prev; - struct grpc_plugin_credentials_pending_request *next; + struct grpc_plugin_credentials* creds; + grpc_credentials_mdelem_array* md_array; + grpc_closure* on_request_metadata; + struct grpc_plugin_credentials_pending_request* prev; + struct grpc_plugin_credentials_pending_request* next; } grpc_plugin_credentials_pending_request; typedef struct grpc_plugin_credentials { grpc_call_credentials base; grpc_metadata_credentials_plugin plugin; gpr_mu mu; - grpc_plugin_credentials_pending_request *pending_requests; + grpc_plugin_credentials_pending_request* pending_requests; } grpc_plugin_credentials; #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_PLUGIN_PLUGIN_CREDENTIALS_H */ diff --git a/src/core/lib/security/credentials/ssl/ssl_credentials.cc b/src/core/lib/security/credentials/ssl/ssl_credentials.cc index 2085e2b8e7b..39dd38cf889 100644 --- a/src/core/lib/security/credentials/ssl/ssl_credentials.cc +++ b/src/core/lib/security/credentials/ssl/ssl_credentials.cc @@ -31,33 +31,33 @@ // SSL Channel Credentials. // -void grpc_tsi_ssl_pem_key_cert_pairs_destroy(tsi_ssl_pem_key_cert_pair *kp, +void grpc_tsi_ssl_pem_key_cert_pairs_destroy(tsi_ssl_pem_key_cert_pair* kp, size_t num_key_cert_pairs) { - if (kp == NULL) return; + if (kp == nullptr) return; for (size_t i = 0; i < num_key_cert_pairs; i++) { - gpr_free((void *)kp[i].private_key); - gpr_free((void *)kp[i].cert_chain); + gpr_free((void*)kp[i].private_key); + gpr_free((void*)kp[i].cert_chain); } gpr_free(kp); } -static void ssl_destruct(grpc_exec_ctx *exec_ctx, - grpc_channel_credentials *creds) { - grpc_ssl_credentials *c = (grpc_ssl_credentials *)creds; +static void ssl_destruct(grpc_exec_ctx* exec_ctx, + grpc_channel_credentials* creds) { + grpc_ssl_credentials* c = (grpc_ssl_credentials*)creds; gpr_free(c->config.pem_root_certs); grpc_tsi_ssl_pem_key_cert_pairs_destroy(c->config.pem_key_cert_pair, 1); } static grpc_security_status ssl_create_security_connector( - grpc_exec_ctx *exec_ctx, grpc_channel_credentials *creds, - grpc_call_credentials *call_creds, const char *target, - const grpc_channel_args *args, grpc_channel_security_connector **sc, - grpc_channel_args **new_args) { - grpc_ssl_credentials *c = (grpc_ssl_credentials *)creds; + grpc_exec_ctx* exec_ctx, grpc_channel_credentials* creds, + grpc_call_credentials* call_creds, const char* target, + const grpc_channel_args* args, grpc_channel_security_connector** sc, + grpc_channel_args** new_args) { + grpc_ssl_credentials* c = (grpc_ssl_credentials*)creds; grpc_security_status status = GRPC_SECURITY_OK; - const char *overridden_target_name = NULL; + const char* overridden_target_name = nullptr; for (size_t i = 0; args && i < args->num_args; i++) { - grpc_arg *arg = &args->args[i]; + grpc_arg* arg = &args->args[i]; if (strcmp(arg->key, GRPC_SSL_TARGET_NAME_OVERRIDE_ARG) == 0 && arg->type == GRPC_ARG_STRING) { overridden_target_name = arg->value.string; @@ -71,24 +71,24 @@ static grpc_security_status ssl_create_security_connector( return status; } grpc_arg new_arg = grpc_channel_arg_string_create( - (char *)GRPC_ARG_HTTP2_SCHEME, (char *)"https"); + (char*)GRPC_ARG_HTTP2_SCHEME, (char*)"https"); *new_args = grpc_channel_args_copy_and_add(args, &new_arg, 1); return status; } static grpc_channel_credentials_vtable ssl_vtable = { - ssl_destruct, ssl_create_security_connector, NULL}; + ssl_destruct, ssl_create_security_connector, nullptr}; -static void ssl_build_config(const char *pem_root_certs, - grpc_ssl_pem_key_cert_pair *pem_key_cert_pair, - grpc_ssl_config *config) { - if (pem_root_certs != NULL) { +static void ssl_build_config(const char* pem_root_certs, + grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, + grpc_ssl_config* config) { + if (pem_root_certs != nullptr) { config->pem_root_certs = gpr_strdup(pem_root_certs); } - if (pem_key_cert_pair != NULL) { - GPR_ASSERT(pem_key_cert_pair->private_key != NULL); - GPR_ASSERT(pem_key_cert_pair->cert_chain != NULL); - config->pem_key_cert_pair = (tsi_ssl_pem_key_cert_pair *)gpr_zalloc( + if (pem_key_cert_pair != nullptr) { + GPR_ASSERT(pem_key_cert_pair->private_key != nullptr); + GPR_ASSERT(pem_key_cert_pair->cert_chain != nullptr); + config->pem_key_cert_pair = (tsi_ssl_pem_key_cert_pair*)gpr_zalloc( sizeof(tsi_ssl_pem_key_cert_pair)); config->pem_key_cert_pair->cert_chain = gpr_strdup(pem_key_cert_pair->cert_chain); @@ -97,17 +97,17 @@ static void ssl_build_config(const char *pem_root_certs, } } -grpc_channel_credentials *grpc_ssl_credentials_create( - const char *pem_root_certs, grpc_ssl_pem_key_cert_pair *pem_key_cert_pair, - void *reserved) { - grpc_ssl_credentials *c = - (grpc_ssl_credentials *)gpr_zalloc(sizeof(grpc_ssl_credentials)); +grpc_channel_credentials* grpc_ssl_credentials_create( + const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, + void* reserved) { + grpc_ssl_credentials* c = + (grpc_ssl_credentials*)gpr_zalloc(sizeof(grpc_ssl_credentials)); GRPC_API_TRACE( "grpc_ssl_credentials_create(pem_root_certs=%s, " "pem_key_cert_pair=%p, " "reserved=%p)", 3, (pem_root_certs, pem_key_cert_pair, reserved)); - GPR_ASSERT(reserved == NULL); + GPR_ASSERT(reserved == nullptr); c->base.type = GRPC_CHANNEL_CREDENTIALS_TYPE_SSL; c->base.vtable = &ssl_vtable; gpr_ref_init(&c->base.refcount, 1); @@ -121,39 +121,39 @@ grpc_channel_credentials *grpc_ssl_credentials_create( struct grpc_ssl_server_credentials_options { grpc_ssl_client_certificate_request_type client_certificate_request; - grpc_ssl_server_certificate_config *certificate_config; - grpc_ssl_server_certificate_config_fetcher *certificate_config_fetcher; + grpc_ssl_server_certificate_config* certificate_config; + grpc_ssl_server_certificate_config_fetcher* certificate_config_fetcher; }; -static void ssl_server_destruct(grpc_exec_ctx *exec_ctx, - grpc_server_credentials *creds) { - grpc_ssl_server_credentials *c = (grpc_ssl_server_credentials *)creds; +static void ssl_server_destruct(grpc_exec_ctx* exec_ctx, + grpc_server_credentials* creds) { + grpc_ssl_server_credentials* c = (grpc_ssl_server_credentials*)creds; grpc_tsi_ssl_pem_key_cert_pairs_destroy(c->config.pem_key_cert_pairs, c->config.num_key_cert_pairs); gpr_free(c->config.pem_root_certs); } static grpc_security_status ssl_server_create_security_connector( - grpc_exec_ctx *exec_ctx, grpc_server_credentials *creds, - grpc_server_security_connector **sc) { + grpc_exec_ctx* exec_ctx, grpc_server_credentials* creds, + grpc_server_security_connector** sc) { return grpc_ssl_server_security_connector_create(exec_ctx, creds, sc); } static grpc_server_credentials_vtable ssl_server_vtable = { ssl_server_destruct, ssl_server_create_security_connector}; -tsi_ssl_pem_key_cert_pair *grpc_convert_grpc_to_tsi_cert_pairs( - const grpc_ssl_pem_key_cert_pair *pem_key_cert_pairs, +tsi_ssl_pem_key_cert_pair* grpc_convert_grpc_to_tsi_cert_pairs( + const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs) { - tsi_ssl_pem_key_cert_pair *tsi_pairs = NULL; + tsi_ssl_pem_key_cert_pair* tsi_pairs = nullptr; if (num_key_cert_pairs > 0) { - GPR_ASSERT(pem_key_cert_pairs != NULL); - tsi_pairs = (tsi_ssl_pem_key_cert_pair *)gpr_zalloc( + GPR_ASSERT(pem_key_cert_pairs != nullptr); + tsi_pairs = (tsi_ssl_pem_key_cert_pair*)gpr_zalloc( num_key_cert_pairs * sizeof(tsi_ssl_pem_key_cert_pair)); } for (size_t i = 0; i < num_key_cert_pairs; i++) { - GPR_ASSERT(pem_key_cert_pairs[i].private_key != NULL); - GPR_ASSERT(pem_key_cert_pairs[i].cert_chain != NULL); + GPR_ASSERT(pem_key_cert_pairs[i].private_key != nullptr); + GPR_ASSERT(pem_key_cert_pairs[i].cert_chain != nullptr); tsi_pairs[i].cert_chain = gpr_strdup(pem_key_cert_pairs[i].cert_chain); tsi_pairs[i].private_key = gpr_strdup(pem_key_cert_pairs[i].private_key); } @@ -161,12 +161,12 @@ tsi_ssl_pem_key_cert_pair *grpc_convert_grpc_to_tsi_cert_pairs( } static void ssl_build_server_config( - const char *pem_root_certs, grpc_ssl_pem_key_cert_pair *pem_key_cert_pairs, + const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs, grpc_ssl_client_certificate_request_type client_certificate_request, - grpc_ssl_server_config *config) { + grpc_ssl_server_config* config) { config->client_certificate_request = client_certificate_request; - if (pem_root_certs != NULL) { + if (pem_root_certs != nullptr) { config->pem_root_certs = gpr_strdup(pem_root_certs); } config->pem_key_cert_pairs = grpc_convert_grpc_to_tsi_cert_pairs( @@ -174,25 +174,25 @@ static void ssl_build_server_config( config->num_key_cert_pairs = num_key_cert_pairs; } -grpc_ssl_server_certificate_config *grpc_ssl_server_certificate_config_create( - const char *pem_root_certs, - const grpc_ssl_pem_key_cert_pair *pem_key_cert_pairs, +grpc_ssl_server_certificate_config* grpc_ssl_server_certificate_config_create( + const char* pem_root_certs, + const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs) { - grpc_ssl_server_certificate_config *config = - (grpc_ssl_server_certificate_config *)gpr_zalloc( + grpc_ssl_server_certificate_config* config = + (grpc_ssl_server_certificate_config*)gpr_zalloc( sizeof(grpc_ssl_server_certificate_config)); - if (pem_root_certs != NULL) { + if (pem_root_certs != nullptr) { config->pem_root_certs = gpr_strdup(pem_root_certs); } if (num_key_cert_pairs > 0) { - GPR_ASSERT(pem_key_cert_pairs != NULL); - config->pem_key_cert_pairs = (grpc_ssl_pem_key_cert_pair *)gpr_zalloc( + GPR_ASSERT(pem_key_cert_pairs != nullptr); + config->pem_key_cert_pairs = (grpc_ssl_pem_key_cert_pair*)gpr_zalloc( num_key_cert_pairs * sizeof(grpc_ssl_pem_key_cert_pair)); } config->num_key_cert_pairs = num_key_cert_pairs; for (size_t i = 0; i < num_key_cert_pairs; i++) { - GPR_ASSERT(pem_key_cert_pairs[i].private_key != NULL); - GPR_ASSERT(pem_key_cert_pairs[i].cert_chain != NULL); + GPR_ASSERT(pem_key_cert_pairs[i].private_key != nullptr); + GPR_ASSERT(pem_key_cert_pairs[i].cert_chain != nullptr); config->pem_key_cert_pairs[i].cert_chain = gpr_strdup(pem_key_cert_pairs[i].cert_chain); config->pem_key_cert_pairs[i].private_key = @@ -202,27 +202,27 @@ grpc_ssl_server_certificate_config *grpc_ssl_server_certificate_config_create( } void grpc_ssl_server_certificate_config_destroy( - grpc_ssl_server_certificate_config *config) { - if (config == NULL) return; + grpc_ssl_server_certificate_config* config) { + if (config == nullptr) return; for (size_t i = 0; i < config->num_key_cert_pairs; i++) { - gpr_free((void *)config->pem_key_cert_pairs[i].private_key); - gpr_free((void *)config->pem_key_cert_pairs[i].cert_chain); + gpr_free((void*)config->pem_key_cert_pairs[i].private_key); + gpr_free((void*)config->pem_key_cert_pairs[i].cert_chain); } gpr_free(config->pem_key_cert_pairs); gpr_free(config->pem_root_certs); gpr_free(config); } -grpc_ssl_server_credentials_options * +grpc_ssl_server_credentials_options* grpc_ssl_server_credentials_create_options_using_config( grpc_ssl_client_certificate_request_type client_certificate_request, - grpc_ssl_server_certificate_config *config) { - grpc_ssl_server_credentials_options *options = NULL; - if (config == NULL) { + grpc_ssl_server_certificate_config* config) { + grpc_ssl_server_credentials_options* options = nullptr; + if (config == nullptr) { gpr_log(GPR_ERROR, "Certificate config must not be NULL."); goto done; } - options = (grpc_ssl_server_credentials_options *)gpr_zalloc( + options = (grpc_ssl_server_credentials_options*)gpr_zalloc( sizeof(grpc_ssl_server_credentials_options)); options->client_certificate_request = client_certificate_request; options->certificate_config = config; @@ -230,23 +230,23 @@ done: return options; } -grpc_ssl_server_credentials_options * +grpc_ssl_server_credentials_options* grpc_ssl_server_credentials_create_options_using_config_fetcher( grpc_ssl_client_certificate_request_type client_certificate_request, - grpc_ssl_server_certificate_config_callback cb, void *user_data) { - if (cb == NULL) { + grpc_ssl_server_certificate_config_callback cb, void* user_data) { + if (cb == nullptr) { gpr_log(GPR_ERROR, "Invalid certificate config callback parameter."); - return NULL; + return nullptr; } - grpc_ssl_server_certificate_config_fetcher *fetcher = - (grpc_ssl_server_certificate_config_fetcher *)gpr_zalloc( + grpc_ssl_server_certificate_config_fetcher* fetcher = + (grpc_ssl_server_certificate_config_fetcher*)gpr_zalloc( sizeof(grpc_ssl_server_certificate_config_fetcher)); fetcher->cb = cb; fetcher->user_data = user_data; - grpc_ssl_server_credentials_options *options = - (grpc_ssl_server_credentials_options *)gpr_zalloc( + grpc_ssl_server_credentials_options* options = + (grpc_ssl_server_credentials_options*)gpr_zalloc( sizeof(grpc_ssl_server_credentials_options)); options->client_certificate_request = client_certificate_request; options->certificate_config_fetcher = fetcher; @@ -254,9 +254,9 @@ grpc_ssl_server_credentials_create_options_using_config_fetcher( return options; } -grpc_server_credentials *grpc_ssl_server_credentials_create( - const char *pem_root_certs, grpc_ssl_pem_key_cert_pair *pem_key_cert_pairs, - size_t num_key_cert_pairs, int force_client_auth, void *reserved) { +grpc_server_credentials* grpc_ssl_server_credentials_create( + const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, + size_t num_key_cert_pairs, int force_client_auth, void* reserved) { return grpc_ssl_server_credentials_create_ex( pem_root_certs, pem_key_cert_pairs, num_key_cert_pairs, force_client_auth @@ -265,59 +265,60 @@ grpc_server_credentials *grpc_ssl_server_credentials_create( reserved); } -grpc_server_credentials *grpc_ssl_server_credentials_create_ex( - const char *pem_root_certs, grpc_ssl_pem_key_cert_pair *pem_key_cert_pairs, +grpc_server_credentials* grpc_ssl_server_credentials_create_ex( + const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs, grpc_ssl_client_certificate_request_type client_certificate_request, - void *reserved) { + void* reserved) { GRPC_API_TRACE( "grpc_ssl_server_credentials_create_ex(" "pem_root_certs=%s, pem_key_cert_pairs=%p, num_key_cert_pairs=%lu, " "client_certificate_request=%d, reserved=%p)", - 5, (pem_root_certs, pem_key_cert_pairs, (unsigned long)num_key_cert_pairs, - client_certificate_request, reserved)); - GPR_ASSERT(reserved == NULL); + 5, + (pem_root_certs, pem_key_cert_pairs, (unsigned long)num_key_cert_pairs, + client_certificate_request, reserved)); + GPR_ASSERT(reserved == nullptr); - grpc_ssl_server_certificate_config *cert_config = + grpc_ssl_server_certificate_config* cert_config = grpc_ssl_server_certificate_config_create( pem_root_certs, pem_key_cert_pairs, num_key_cert_pairs); - grpc_ssl_server_credentials_options *options = + grpc_ssl_server_credentials_options* options = grpc_ssl_server_credentials_create_options_using_config( client_certificate_request, cert_config); return grpc_ssl_server_credentials_create_with_options(options); } -grpc_server_credentials *grpc_ssl_server_credentials_create_with_options( - grpc_ssl_server_credentials_options *options) { - grpc_server_credentials *retval = NULL; - grpc_ssl_server_credentials *c = NULL; +grpc_server_credentials* grpc_ssl_server_credentials_create_with_options( + grpc_ssl_server_credentials_options* options) { + grpc_server_credentials* retval = nullptr; + grpc_ssl_server_credentials* c = nullptr; - if (options == NULL) { + if (options == nullptr) { gpr_log(GPR_ERROR, "Invalid options trying to create SSL server credentials."); goto done; } - if (options->certificate_config == NULL && - options->certificate_config_fetcher == NULL) { + if (options->certificate_config == nullptr && + options->certificate_config_fetcher == nullptr) { gpr_log(GPR_ERROR, "SSL server credentials options must specify either " "certificate config or fetcher."); goto done; - } else if (options->certificate_config_fetcher != NULL && - options->certificate_config_fetcher->cb == NULL) { + } else if (options->certificate_config_fetcher != nullptr && + options->certificate_config_fetcher->cb == nullptr) { gpr_log(GPR_ERROR, "Certificate config fetcher callback must not be NULL."); goto done; } - c = (grpc_ssl_server_credentials *)gpr_zalloc( + c = (grpc_ssl_server_credentials*)gpr_zalloc( sizeof(grpc_ssl_server_credentials)); c->base.type = GRPC_CHANNEL_CREDENTIALS_TYPE_SSL; gpr_ref_init(&c->base.refcount, 1); c->base.vtable = &ssl_server_vtable; - if (options->certificate_config_fetcher != NULL) { + if (options->certificate_config_fetcher != nullptr) { c->config.client_certificate_request = options->client_certificate_request; c->certificate_config_fetcher = *options->certificate_config_fetcher; } else { @@ -335,8 +336,8 @@ done: } void grpc_ssl_server_credentials_options_destroy( - grpc_ssl_server_credentials_options *o) { - if (o == NULL) return; + grpc_ssl_server_credentials_options* o) { + if (o == nullptr) return; gpr_free(o->certificate_config_fetcher); grpc_ssl_server_certificate_config_destroy(o->certificate_config); gpr_free(o); diff --git a/src/core/lib/security/credentials/ssl/ssl_credentials.h b/src/core/lib/security/credentials/ssl/ssl_credentials.h index 5542484aae6..00039058572 100644 --- a/src/core/lib/security/credentials/ssl/ssl_credentials.h +++ b/src/core/lib/security/credentials/ssl/ssl_credentials.h @@ -20,24 +20,20 @@ #include "src/core/lib/security/credentials/credentials.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct { grpc_channel_credentials base; grpc_ssl_config config; } grpc_ssl_credentials; struct grpc_ssl_server_certificate_config { - grpc_ssl_pem_key_cert_pair *pem_key_cert_pairs; + grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs; size_t num_key_cert_pairs; - char *pem_root_certs; + char* pem_root_certs; }; typedef struct { grpc_ssl_server_certificate_config_callback cb; - void *user_data; + void* user_data; } grpc_ssl_server_certificate_config_fetcher; typedef struct { @@ -46,15 +42,11 @@ typedef struct { grpc_ssl_server_certificate_config_fetcher certificate_config_fetcher; } grpc_ssl_server_credentials; -tsi_ssl_pem_key_cert_pair *grpc_convert_grpc_to_tsi_cert_pairs( - const grpc_ssl_pem_key_cert_pair *pem_key_cert_pairs, +tsi_ssl_pem_key_cert_pair* grpc_convert_grpc_to_tsi_cert_pairs( + const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs); -void grpc_tsi_ssl_pem_key_cert_pairs_destroy(tsi_ssl_pem_key_cert_pair *kp, +void grpc_tsi_ssl_pem_key_cert_pairs_destroy(tsi_ssl_pem_key_cert_pair* kp, size_t num_key_cert_pairs); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_SSL_SSL_CREDENTIALS_H */ diff --git a/src/core/lib/security/transport/auth_filters.h b/src/core/lib/security/transport/auth_filters.h index ba5df7fe70f..e999a027aeb 100644 --- a/src/core/lib/security/transport/auth_filters.h +++ b/src/core/lib/security/transport/auth_filters.h @@ -19,17 +19,17 @@ #ifndef GRPC_CORE_LIB_SECURITY_TRANSPORT_AUTH_FILTERS_H #define GRPC_CORE_LIB_SECURITY_TRANSPORT_AUTH_FILTERS_H +#include #include "src/core/lib/channel/channel_stack.h" -#ifdef __cplusplus -extern "C" { -#endif - extern const grpc_channel_filter grpc_client_auth_filter; extern const grpc_channel_filter grpc_server_auth_filter; -#ifdef __cplusplus -} -#endif +void grpc_auth_metadata_context_build( + const char* url_scheme, grpc_slice call_host, grpc_slice call_method, + grpc_auth_context* auth_context, + grpc_auth_metadata_context* auth_md_context); + +void grpc_auth_metadata_context_reset(grpc_auth_metadata_context* context); #endif /* GRPC_CORE_LIB_SECURITY_TRANSPORT_AUTH_FILTERS_H */ diff --git a/src/core/lib/security/transport/client_auth_filter.cc b/src/core/lib/security/transport/client_auth_filter.cc index a8464dbf9e7..326f4d77732 100644 --- a/src/core/lib/security/transport/client_auth_filter.cc +++ b/src/core/lib/security/transport/client_auth_filter.cc @@ -39,9 +39,9 @@ /* We can have a per-call credentials. */ typedef struct { - grpc_call_stack *owning_call; - grpc_call_combiner *call_combiner; - grpc_call_credentials *creds; + grpc_call_stack* owning_call; + grpc_call_combiner* call_combiner; + grpc_call_credentials* creds; bool have_host; bool have_method; grpc_slice host; @@ -50,7 +50,7 @@ typedef struct { network requests, they should be done under a pollset added to this pollset_set so that work can progress when this call wants work to progress */ - grpc_polling_entity *pollent; + grpc_polling_entity* pollent; grpc_credentials_mdelem_array md_array; grpc_linked_mdelem md_links[MAX_CREDENTIALS_METADATA_COUNT]; grpc_auth_metadata_context auth_md_context; @@ -61,27 +61,27 @@ typedef struct { /* We can have a per-channel credentials. */ typedef struct { - grpc_channel_security_connector *security_connector; - grpc_auth_context *auth_context; + grpc_channel_security_connector* security_connector; + grpc_auth_context* auth_context; } channel_data; -static void reset_auth_metadata_context( - grpc_auth_metadata_context *auth_md_context) { - if (auth_md_context->service_url != NULL) { - gpr_free((char *)auth_md_context->service_url); - auth_md_context->service_url = NULL; +void grpc_auth_metadata_context_reset( + grpc_auth_metadata_context* auth_md_context) { + if (auth_md_context->service_url != nullptr) { + gpr_free((char*)auth_md_context->service_url); + auth_md_context->service_url = nullptr; } - if (auth_md_context->method_name != NULL) { - gpr_free((char *)auth_md_context->method_name); - auth_md_context->method_name = NULL; + if (auth_md_context->method_name != nullptr) { + gpr_free((char*)auth_md_context->method_name); + auth_md_context->method_name = nullptr; } GRPC_AUTH_CONTEXT_UNREF( - (grpc_auth_context *)auth_md_context->channel_auth_context, + (grpc_auth_context*)auth_md_context->channel_auth_context, "grpc_auth_metadata_context"); - auth_md_context->channel_auth_context = NULL; + auth_md_context->channel_auth_context = nullptr; } -static void add_error(grpc_error **combined, grpc_error *error) { +static void add_error(grpc_error** combined, grpc_error* error) { if (error == GRPC_ERROR_NONE) return; if (*combined == GRPC_ERROR_NONE) { *combined = GRPC_ERROR_CREATE_FROM_STATIC_STRING( @@ -90,18 +90,18 @@ static void add_error(grpc_error **combined, grpc_error *error) { *combined = grpc_error_add_child(*combined, error); } -static void on_credentials_metadata(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *input_error) { - grpc_transport_stream_op_batch *batch = (grpc_transport_stream_op_batch *)arg; - grpc_call_element *elem = - (grpc_call_element *)batch->handler_private.extra_arg; - call_data *calld = (call_data *)elem->call_data; - reset_auth_metadata_context(&calld->auth_md_context); - grpc_error *error = GRPC_ERROR_REF(input_error); +static void on_credentials_metadata(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* input_error) { + grpc_transport_stream_op_batch* batch = (grpc_transport_stream_op_batch*)arg; + grpc_call_element* elem = + (grpc_call_element*)batch->handler_private.extra_arg; + call_data* calld = (call_data*)elem->call_data; + grpc_auth_metadata_context_reset(&calld->auth_md_context); + grpc_error* error = GRPC_ERROR_REF(input_error); if (error == GRPC_ERROR_NONE) { GPR_ASSERT(calld->md_array.size <= MAX_CREDENTIALS_METADATA_COUNT); GPR_ASSERT(batch->send_initial_metadata); - grpc_metadata_batch *mdb = + grpc_metadata_batch* mdb = batch->payload->send_initial_metadata.send_initial_metadata; for (size_t i = 0; i < calld->md_array.size; ++i) { add_error(&error, grpc_metadata_batch_add_tail( @@ -119,40 +119,47 @@ static void on_credentials_metadata(grpc_exec_ctx *exec_ctx, void *arg, } } -void build_auth_metadata_context(grpc_security_connector *sc, - grpc_auth_context *auth_context, - call_data *calld) { - char *service = grpc_slice_to_c_string(calld->method); - char *last_slash = strrchr(service, '/'); - char *method_name = NULL; - char *service_url = NULL; - reset_auth_metadata_context(&calld->auth_md_context); - if (last_slash == NULL) { +void grpc_auth_metadata_context_build( + const char* url_scheme, grpc_slice call_host, grpc_slice call_method, + grpc_auth_context* auth_context, + grpc_auth_metadata_context* auth_md_context) { + char* service = grpc_slice_to_c_string(call_method); + char* last_slash = strrchr(service, '/'); + char* method_name = nullptr; + char* service_url = nullptr; + grpc_auth_metadata_context_reset(auth_md_context); + if (last_slash == nullptr) { gpr_log(GPR_ERROR, "No '/' found in fully qualified method name"); service[0] = '\0'; + method_name = gpr_strdup(""); } else if (last_slash == service) { - /* No service part in fully qualified method name: will just be "/". */ - service[1] = '\0'; + method_name = gpr_strdup(""); } else { *last_slash = '\0'; method_name = gpr_strdup(last_slash + 1); } - if (method_name == NULL) method_name = gpr_strdup(""); - char *host = grpc_slice_to_c_string(calld->host); + char* host_and_port = grpc_slice_to_c_string(call_host); + if (url_scheme != nullptr && strcmp(url_scheme, GRPC_SSL_URL_SCHEME) == 0) { + /* Remove the port if it is 443. */ + char* port_delimiter = strrchr(host_and_port, ':'); + if (port_delimiter != nullptr && strcmp(port_delimiter + 1, "443") == 0) { + *port_delimiter = '\0'; + } + } gpr_asprintf(&service_url, "%s://%s%s", - sc->url_scheme == NULL ? "" : sc->url_scheme, host, service); - calld->auth_md_context.service_url = service_url; - calld->auth_md_context.method_name = method_name; - calld->auth_md_context.channel_auth_context = + url_scheme == nullptr ? "" : url_scheme, host_and_port, service); + auth_md_context->service_url = service_url; + auth_md_context->method_name = method_name; + auth_md_context->channel_auth_context = GRPC_AUTH_CONTEXT_REF(auth_context, "grpc_auth_metadata_context"); gpr_free(service); - gpr_free(host); + gpr_free(host_and_port); } -static void cancel_get_request_metadata(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_call_element *elem = (grpc_call_element *)arg; - call_data *calld = (call_data *)elem->call_data; +static void cancel_get_request_metadata(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_call_element* elem = (grpc_call_element*)arg; + call_data* calld = (call_data*)elem->call_data; if (error != GRPC_ERROR_NONE) { grpc_call_credentials_cancel_get_request_metadata( exec_ctx, calld->creds, &calld->md_array, GRPC_ERROR_REF(error)); @@ -161,29 +168,29 @@ static void cancel_get_request_metadata(grpc_exec_ctx *exec_ctx, void *arg, "cancel_get_request_metadata"); } -static void send_security_metadata(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_transport_stream_op_batch *batch) { - call_data *calld = (call_data *)elem->call_data; - channel_data *chand = (channel_data *)elem->channel_data; - grpc_client_security_context *ctx = - (grpc_client_security_context *)batch->payload +static void send_security_metadata(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_transport_stream_op_batch* batch) { + call_data* calld = (call_data*)elem->call_data; + channel_data* chand = (channel_data*)elem->channel_data; + grpc_client_security_context* ctx = + (grpc_client_security_context*)batch->payload ->context[GRPC_CONTEXT_SECURITY] .value; - grpc_call_credentials *channel_call_creds = + grpc_call_credentials* channel_call_creds = chand->security_connector->request_metadata_creds; - int call_creds_has_md = (ctx != NULL) && (ctx->creds != NULL); + int call_creds_has_md = (ctx != nullptr) && (ctx->creds != nullptr); - if (channel_call_creds == NULL && !call_creds_has_md) { + if (channel_call_creds == nullptr && !call_creds_has_md) { /* Skip sending metadata altogether. */ grpc_call_next_op(exec_ctx, elem, batch); return; } - if (channel_call_creds != NULL && call_creds_has_md) { + if (channel_call_creds != nullptr && call_creds_has_md) { calld->creds = grpc_composite_call_credentials_create(channel_call_creds, - ctx->creds, NULL); - if (calld->creds == NULL) { + ctx->creds, nullptr); + if (calld->creds == nullptr) { grpc_transport_stream_op_batch_finish_with_failure( exec_ctx, batch, grpc_error_set_int( @@ -198,14 +205,15 @@ static void send_security_metadata(grpc_exec_ctx *exec_ctx, call_creds_has_md ? ctx->creds : channel_call_creds); } - build_auth_metadata_context(&chand->security_connector->base, - chand->auth_context, calld); + grpc_auth_metadata_context_build( + chand->security_connector->base.url_scheme, calld->host, calld->method, + chand->auth_context, &calld->auth_md_context); - GPR_ASSERT(calld->pollent != NULL); + GPR_ASSERT(calld->pollent != nullptr); GRPC_CLOSURE_INIT(&calld->async_result_closure, on_credentials_metadata, batch, grpc_schedule_on_exec_ctx); - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; if (grpc_call_credentials_get_request_metadata( exec_ctx, calld->creds, calld->pollent, calld->auth_md_context, &calld->md_array, &calld->async_result_closure, &error)) { @@ -223,17 +231,17 @@ static void send_security_metadata(grpc_exec_ctx *exec_ctx, } } -static void on_host_checked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_transport_stream_op_batch *batch = (grpc_transport_stream_op_batch *)arg; - grpc_call_element *elem = - (grpc_call_element *)batch->handler_private.extra_arg; - call_data *calld = (call_data *)elem->call_data; +static void on_host_checked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_transport_stream_op_batch* batch = (grpc_transport_stream_op_batch*)arg; + grpc_call_element* elem = + (grpc_call_element*)batch->handler_private.extra_arg; + call_data* calld = (call_data*)elem->call_data; if (error == GRPC_ERROR_NONE) { send_security_metadata(exec_ctx, elem, batch); } else { - char *error_msg; - char *host = grpc_slice_to_c_string(calld->host); + char* error_msg; + char* host = grpc_slice_to_c_string(calld->host); gpr_asprintf(&error_msg, "Invalid host %s set in :authority metadata.", host); gpr_free(host); @@ -247,11 +255,11 @@ static void on_host_checked(grpc_exec_ctx *exec_ctx, void *arg, } } -static void cancel_check_call_host(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_call_element *elem = (grpc_call_element *)arg; - call_data *calld = (call_data *)elem->call_data; - channel_data *chand = (channel_data *)elem->channel_data; +static void cancel_check_call_host(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_call_element* elem = (grpc_call_element*)arg; + call_data* calld = (call_data*)elem->call_data; + channel_data* chand = (channel_data*)elem->channel_data; if (error != GRPC_ERROR_NONE) { grpc_channel_security_connector_cancel_check_call_host( exec_ctx, chand->security_connector, &calld->async_result_closure, @@ -261,24 +269,24 @@ static void cancel_check_call_host(grpc_exec_ctx *exec_ctx, void *arg, } static void auth_start_transport_stream_op_batch( - grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_transport_stream_op_batch *batch) { + grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_transport_stream_op_batch* batch) { GPR_TIMER_BEGIN("auth_start_transport_stream_op_batch", 0); /* grab pointers to our data from the call element */ - call_data *calld = (call_data *)elem->call_data; - channel_data *chand = (channel_data *)elem->channel_data; + call_data* calld = (call_data*)elem->call_data; + channel_data* chand = (channel_data*)elem->channel_data; if (!batch->cancel_stream) { - GPR_ASSERT(batch->payload->context != NULL); - if (batch->payload->context[GRPC_CONTEXT_SECURITY].value == NULL) { + GPR_ASSERT(batch->payload->context != nullptr); + if (batch->payload->context[GRPC_CONTEXT_SECURITY].value == nullptr) { batch->payload->context[GRPC_CONTEXT_SECURITY].value = grpc_client_security_context_create(); batch->payload->context[GRPC_CONTEXT_SECURITY].destroy = grpc_client_security_context_destroy; } - grpc_client_security_context *sec_ctx = - (grpc_client_security_context *)batch->payload + grpc_client_security_context* sec_ctx = + (grpc_client_security_context*)batch->payload ->context[GRPC_CONTEXT_SECURITY] .value; GRPC_AUTH_CONTEXT_UNREF(sec_ctx->auth_context, "client auth filter"); @@ -287,9 +295,9 @@ static void auth_start_transport_stream_op_batch( } if (batch->send_initial_metadata) { - for (grpc_linked_mdelem *l = batch->payload->send_initial_metadata + for (grpc_linked_mdelem* l = batch->payload->send_initial_metadata .send_initial_metadata->list.head; - l != NULL; l = l->next) { + l != nullptr; l = l->next) { grpc_mdelem md = l->md; /* Pointer comparison is OK for md_elems created from the same context. */ @@ -311,8 +319,8 @@ static void auth_start_transport_stream_op_batch( batch->handler_private.extra_arg = elem; GRPC_CLOSURE_INIT(&calld->async_result_closure, on_host_checked, batch, grpc_schedule_on_exec_ctx); - char *call_host = grpc_slice_to_c_string(calld->host); - grpc_error *error = GRPC_ERROR_NONE; + char* call_host = grpc_slice_to_c_string(calld->host); + grpc_error* error = GRPC_ERROR_NONE; if (grpc_channel_security_connector_check_call_host( exec_ctx, chand->security_connector, call_host, chand->auth_context, &calld->async_result_closure, &error)) { @@ -340,27 +348,27 @@ static void auth_start_transport_stream_op_batch( } /* Constructor for call_data */ -static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - const grpc_call_element_args *args) { - call_data *calld = (call_data *)elem->call_data; +static grpc_error* init_call_elem(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + const grpc_call_element_args* args) { + call_data* calld = (call_data*)elem->call_data; calld->owning_call = args->call_stack; calld->call_combiner = args->call_combiner; return GRPC_ERROR_NONE; } -static void set_pollset_or_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_polling_entity *pollent) { - call_data *calld = (call_data *)elem->call_data; +static void set_pollset_or_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_polling_entity* pollent) { + call_data* calld = (call_data*)elem->call_data; calld->pollent = pollent; } /* Destructor for call_data */ -static void destroy_call_elem(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - const grpc_call_final_info *final_info, - grpc_closure *ignored) { - call_data *calld = (call_data *)elem->call_data; +static void destroy_call_elem(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + const grpc_call_final_info* final_info, + grpc_closure* ignored) { + call_data* calld = (call_data*)elem->call_data; grpc_credentials_mdelem_array_destroy(exec_ctx, &calld->md_array); grpc_call_credentials_unref(exec_ctx, calld->creds); if (calld->have_host) { @@ -369,28 +377,28 @@ static void destroy_call_elem(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, if (calld->have_method) { grpc_slice_unref_internal(exec_ctx, calld->method); } - reset_auth_metadata_context(&calld->auth_md_context); + grpc_auth_metadata_context_reset(&calld->auth_md_context); } /* Constructor for channel_data */ -static grpc_error *init_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_channel_element_args *args) { - grpc_security_connector *sc = +static grpc_error* init_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_channel_element_args* args) { + grpc_security_connector* sc = grpc_security_connector_find_in_args(args->channel_args); - if (sc == NULL) { + if (sc == nullptr) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Security connector missing from client auth filter args"); } - grpc_auth_context *auth_context = + grpc_auth_context* auth_context = grpc_find_auth_context_in_args(args->channel_args); - if (auth_context == NULL) { + if (auth_context == nullptr) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Auth context missing from client auth filter args"); } /* grab pointers to our data from the channel element */ - channel_data *chand = (channel_data *)elem->channel_data; + channel_data* chand = (channel_data*)elem->channel_data; /* The first and the last filters tend to be implemented differently to handle the case that there's no 'next' filter to call on the up or down @@ -399,7 +407,7 @@ static grpc_error *init_channel_elem(grpc_exec_ctx *exec_ctx, /* initialize members */ chand->security_connector = - (grpc_channel_security_connector *)GRPC_SECURITY_CONNECTOR_REF( + (grpc_channel_security_connector*)GRPC_SECURITY_CONNECTOR_REF( sc, "client_auth_filter"); chand->auth_context = GRPC_AUTH_CONTEXT_REF(auth_context, "client_auth_filter"); @@ -407,12 +415,12 @@ static grpc_error *init_channel_elem(grpc_exec_ctx *exec_ctx, } /* Destructor for channel data */ -static void destroy_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem) { +static void destroy_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem) { /* grab pointers to our data from the channel element */ - channel_data *chand = (channel_data *)elem->channel_data; - grpc_channel_security_connector *sc = chand->security_connector; - if (sc != NULL) { + channel_data* chand = (channel_data*)elem->channel_data; + grpc_channel_security_connector* sc = chand->security_connector; + if (sc != nullptr) { GRPC_SECURITY_CONNECTOR_UNREF(exec_ctx, &sc->base, "client_auth_filter"); } GRPC_AUTH_CONTEXT_UNREF(chand->auth_context, "client_auth_filter"); diff --git a/src/core/lib/security/transport/lb_targets_info.cc b/src/core/lib/security/transport/lb_targets_info.cc index 947fc1addff..c07be358404 100644 --- a/src/core/lib/security/transport/lb_targets_info.cc +++ b/src/core/lib/security/transport/lb_targets_info.cc @@ -25,33 +25,33 @@ * secure naming purposes. */ #define GRPC_ARG_LB_SECURE_NAMING_MAP "grpc.lb_secure_naming_map" -static void *targets_info_copy(void *p) { - return grpc_slice_hash_table_ref((grpc_slice_hash_table *)p); +static void* targets_info_copy(void* p) { + return grpc_slice_hash_table_ref((grpc_slice_hash_table*)p); } -static void targets_info_destroy(grpc_exec_ctx *exec_ctx, void *p) { - grpc_slice_hash_table_unref(exec_ctx, (grpc_slice_hash_table *)p); +static void targets_info_destroy(grpc_exec_ctx* exec_ctx, void* p) { + grpc_slice_hash_table_unref(exec_ctx, (grpc_slice_hash_table*)p); } -static int targets_info_cmp(void *a, void *b) { - return grpc_slice_hash_table_cmp((const grpc_slice_hash_table *)a, - (const grpc_slice_hash_table *)b); +static int targets_info_cmp(void* a, void* b) { + return grpc_slice_hash_table_cmp((const grpc_slice_hash_table*)a, + (const grpc_slice_hash_table*)b); } static const grpc_arg_pointer_vtable server_to_balancer_names_vtable = { targets_info_copy, targets_info_destroy, targets_info_cmp}; grpc_arg grpc_lb_targets_info_create_channel_arg( - grpc_slice_hash_table *targets_info) { - return grpc_channel_arg_pointer_create((char *)GRPC_ARG_LB_SECURE_NAMING_MAP, + grpc_slice_hash_table* targets_info) { + return grpc_channel_arg_pointer_create((char*)GRPC_ARG_LB_SECURE_NAMING_MAP, targets_info, &server_to_balancer_names_vtable); } -grpc_slice_hash_table *grpc_lb_targets_info_find_in_args( - const grpc_channel_args *args) { - const grpc_arg *targets_info_arg = +grpc_slice_hash_table* grpc_lb_targets_info_find_in_args( + const grpc_channel_args* args) { + const grpc_arg* targets_info_arg = grpc_channel_args_find(args, GRPC_ARG_LB_SECURE_NAMING_MAP); - if (targets_info_arg != NULL) { + if (targets_info_arg != nullptr) { GPR_ASSERT(targets_info_arg->type == GRPC_ARG_POINTER); - return (grpc_slice_hash_table *)targets_info_arg->value.pointer.p; + return (grpc_slice_hash_table*)targets_info_arg->value.pointer.p; } - return NULL; + return nullptr; } diff --git a/src/core/lib/security/transport/lb_targets_info.h b/src/core/lib/security/transport/lb_targets_info.h index 43f0e645565..7543d3c012f 100644 --- a/src/core/lib/security/transport/lb_targets_info.h +++ b/src/core/lib/security/transport/lb_targets_info.h @@ -21,20 +21,12 @@ #include "src/core/lib/slice/slice_hash_table.h" -#ifdef __cplusplus -extern "C" { -#endif - /** Return a channel argument containing \a targets_info. */ grpc_arg grpc_lb_targets_info_create_channel_arg( - grpc_slice_hash_table *targets_info); + grpc_slice_hash_table* targets_info); /** Return the instance of targets info in \a args or NULL */ -grpc_slice_hash_table *grpc_lb_targets_info_find_in_args( - const grpc_channel_args *args); - -#ifdef __cplusplus -} -#endif +grpc_slice_hash_table* grpc_lb_targets_info_find_in_args( + const grpc_channel_args* args); #endif /* GRPC_CORE_LIB_SECURITY_TRANSPORT_LB_TARGETS_INFO_H */ diff --git a/src/core/lib/security/transport/secure_endpoint.cc b/src/core/lib/security/transport/secure_endpoint.cc index 859d04ae5a6..4cd317a06d7 100644 --- a/src/core/lib/security/transport/secure_endpoint.cc +++ b/src/core/lib/security/transport/secure_endpoint.cc @@ -40,15 +40,15 @@ typedef struct { grpc_endpoint base; - grpc_endpoint *wrapped_ep; - struct tsi_frame_protector *protector; - struct tsi_zero_copy_grpc_protector *zero_copy_protector; + grpc_endpoint* wrapped_ep; + struct tsi_frame_protector* protector; + struct tsi_zero_copy_grpc_protector* zero_copy_protector; gpr_mu protector_mu; /* saved upper level callbacks and user_data. */ - grpc_closure *read_cb; - grpc_closure *write_cb; + grpc_closure* read_cb; + grpc_closure* write_cb; grpc_closure on_read; - grpc_slice_buffer *read_buffer; + grpc_slice_buffer* read_buffer; grpc_slice_buffer source_buffer; /* saved handshaker leftover data to unprotect. */ grpc_slice_buffer leftover_bytes; @@ -61,11 +61,10 @@ typedef struct { gpr_refcount ref; } secure_endpoint; -grpc_tracer_flag grpc_trace_secure_endpoint = - GRPC_TRACER_INITIALIZER(false, "secure_endpoint"); +grpc_core::TraceFlag grpc_trace_secure_endpoint(false, "secure_endpoint"); -static void destroy(grpc_exec_ctx *exec_ctx, secure_endpoint *secure_ep) { - secure_endpoint *ep = secure_ep; +static void destroy(grpc_exec_ctx* exec_ctx, secure_endpoint* secure_ep) { + secure_endpoint* ep = secure_ep; grpc_endpoint_destroy(exec_ctx, ep->wrapped_ep); tsi_frame_protector_destroy(ep->protector); tsi_zero_copy_grpc_protector_destroy(exec_ctx, ep->zero_copy_protector); @@ -83,10 +82,10 @@ static void destroy(grpc_exec_ctx *exec_ctx, secure_endpoint *secure_ep) { secure_endpoint_unref((exec_ctx), (ep), (reason), __FILE__, __LINE__) #define SECURE_ENDPOINT_REF(ep, reason) \ secure_endpoint_ref((ep), (reason), __FILE__, __LINE__) -static void secure_endpoint_unref(grpc_exec_ctx *exec_ctx, secure_endpoint *ep, - const char *reason, const char *file, +static void secure_endpoint_unref(grpc_exec_ctx* exec_ctx, secure_endpoint* ep, + const char* reason, const char* file, int line) { - if (GRPC_TRACER_ON(grpc_trace_secure_endpoint)) { + if (grpc_trace_secure_endpoint.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&ep->ref.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "SECENDP unref %p : %s %" PRIdPTR " -> %" PRIdPTR, ep, reason, val, @@ -97,9 +96,9 @@ static void secure_endpoint_unref(grpc_exec_ctx *exec_ctx, secure_endpoint *ep, } } -static void secure_endpoint_ref(secure_endpoint *ep, const char *reason, - const char *file, int line) { - if (GRPC_TRACER_ON(grpc_trace_secure_endpoint)) { +static void secure_endpoint_ref(secure_endpoint* ep, const char* reason, + const char* file, int line) { + if (grpc_trace_secure_endpoint.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&ep->ref.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "SECENDP ref %p : %s %" PRIdPTR " -> %" PRIdPTR, ep, reason, val, @@ -111,57 +110,58 @@ static void secure_endpoint_ref(secure_endpoint *ep, const char *reason, #define SECURE_ENDPOINT_UNREF(exec_ctx, ep, reason) \ secure_endpoint_unref((exec_ctx), (ep)) #define SECURE_ENDPOINT_REF(ep, reason) secure_endpoint_ref((ep)) -static void secure_endpoint_unref(grpc_exec_ctx *exec_ctx, - secure_endpoint *ep) { +static void secure_endpoint_unref(grpc_exec_ctx* exec_ctx, + secure_endpoint* ep) { if (gpr_unref(&ep->ref)) { destroy(exec_ctx, ep); } } -static void secure_endpoint_ref(secure_endpoint *ep) { gpr_ref(&ep->ref); } +static void secure_endpoint_ref(secure_endpoint* ep) { gpr_ref(&ep->ref); } #endif -static void flush_read_staging_buffer(secure_endpoint *ep, uint8_t **cur, - uint8_t **end) { +static void flush_read_staging_buffer(secure_endpoint* ep, uint8_t** cur, + uint8_t** end) { grpc_slice_buffer_add(ep->read_buffer, ep->read_staging_buffer); ep->read_staging_buffer = GRPC_SLICE_MALLOC(STAGING_BUFFER_SIZE); *cur = GRPC_SLICE_START_PTR(ep->read_staging_buffer); *end = GRPC_SLICE_END_PTR(ep->read_staging_buffer); } -static void call_read_cb(grpc_exec_ctx *exec_ctx, secure_endpoint *ep, - grpc_error *error) { - if (GRPC_TRACER_ON(grpc_trace_secure_endpoint)) { +static void call_read_cb(grpc_exec_ctx* exec_ctx, secure_endpoint* ep, + grpc_error* error) { + if (grpc_trace_secure_endpoint.enabled()) { size_t i; for (i = 0; i < ep->read_buffer->count; i++) { - char *data = grpc_dump_slice(ep->read_buffer->slices[i], + char* data = grpc_dump_slice(ep->read_buffer->slices[i], GPR_DUMP_HEX | GPR_DUMP_ASCII); gpr_log(GPR_DEBUG, "READ %p: %s", ep, data); gpr_free(data); } } - ep->read_buffer = NULL; + ep->read_buffer = nullptr; GRPC_CLOSURE_SCHED(exec_ctx, ep->read_cb, error); SECURE_ENDPOINT_UNREF(exec_ctx, ep, "read"); } -static void on_read(grpc_exec_ctx *exec_ctx, void *user_data, - grpc_error *error) { +static void on_read(grpc_exec_ctx* exec_ctx, void* user_data, + grpc_error* error) { unsigned i; uint8_t keep_looping = 0; tsi_result result = TSI_OK; - secure_endpoint *ep = (secure_endpoint *)user_data; - uint8_t *cur = GRPC_SLICE_START_PTR(ep->read_staging_buffer); - uint8_t *end = GRPC_SLICE_END_PTR(ep->read_staging_buffer); + secure_endpoint* ep = (secure_endpoint*)user_data; + uint8_t* cur = GRPC_SLICE_START_PTR(ep->read_staging_buffer); + uint8_t* end = GRPC_SLICE_END_PTR(ep->read_staging_buffer); if (error != GRPC_ERROR_NONE) { grpc_slice_buffer_reset_and_unref_internal(exec_ctx, ep->read_buffer); - call_read_cb(exec_ctx, ep, GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( - "Secure read failed", &error, 1)); + call_read_cb(exec_ctx, ep, + GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( + "Secure read failed", &error, 1)); return; } - if (ep->zero_copy_protector != NULL) { + if (ep->zero_copy_protector != nullptr) { // Use zero-copy grpc protector to unprotect. result = tsi_zero_copy_grpc_protector_unprotect( exec_ctx, ep->zero_copy_protector, &ep->source_buffer, ep->read_buffer); @@ -170,7 +170,7 @@ static void on_read(grpc_exec_ctx *exec_ctx, void *user_data, /* TODO(yangg) check error, maybe bail out early */ for (i = 0; i < ep->source_buffer.count; i++) { grpc_slice encrypted = ep->source_buffer.slices[i]; - uint8_t *message_bytes = GRPC_SLICE_START_PTR(encrypted); + uint8_t* message_bytes = GRPC_SLICE_START_PTR(encrypted); size_t message_size = GRPC_SLICE_LENGTH(encrypted); while (message_size > 0 || keep_looping) { @@ -231,9 +231,9 @@ static void on_read(grpc_exec_ctx *exec_ctx, void *user_data, call_read_cb(exec_ctx, ep, GRPC_ERROR_NONE); } -static void endpoint_read(grpc_exec_ctx *exec_ctx, grpc_endpoint *secure_ep, - grpc_slice_buffer *slices, grpc_closure *cb) { - secure_endpoint *ep = (secure_endpoint *)secure_ep; +static void endpoint_read(grpc_exec_ctx* exec_ctx, grpc_endpoint* secure_ep, + grpc_slice_buffer* slices, grpc_closure* cb) { + secure_endpoint* ep = (secure_endpoint*)secure_ep; ep->read_cb = cb; ep->read_buffer = slices; grpc_slice_buffer_reset_and_unref_internal(exec_ctx, ep->read_buffer); @@ -250,36 +250,36 @@ static void endpoint_read(grpc_exec_ctx *exec_ctx, grpc_endpoint *secure_ep, &ep->on_read); } -static void flush_write_staging_buffer(secure_endpoint *ep, uint8_t **cur, - uint8_t **end) { +static void flush_write_staging_buffer(secure_endpoint* ep, uint8_t** cur, + uint8_t** end) { grpc_slice_buffer_add(&ep->output_buffer, ep->write_staging_buffer); ep->write_staging_buffer = GRPC_SLICE_MALLOC(STAGING_BUFFER_SIZE); *cur = GRPC_SLICE_START_PTR(ep->write_staging_buffer); *end = GRPC_SLICE_END_PTR(ep->write_staging_buffer); } -static void endpoint_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *secure_ep, - grpc_slice_buffer *slices, grpc_closure *cb) { +static void endpoint_write(grpc_exec_ctx* exec_ctx, grpc_endpoint* secure_ep, + grpc_slice_buffer* slices, grpc_closure* cb) { GPR_TIMER_BEGIN("secure_endpoint.endpoint_write", 0); unsigned i; tsi_result result = TSI_OK; - secure_endpoint *ep = (secure_endpoint *)secure_ep; - uint8_t *cur = GRPC_SLICE_START_PTR(ep->write_staging_buffer); - uint8_t *end = GRPC_SLICE_END_PTR(ep->write_staging_buffer); + secure_endpoint* ep = (secure_endpoint*)secure_ep; + uint8_t* cur = GRPC_SLICE_START_PTR(ep->write_staging_buffer); + uint8_t* end = GRPC_SLICE_END_PTR(ep->write_staging_buffer); grpc_slice_buffer_reset_and_unref_internal(exec_ctx, &ep->output_buffer); - if (GRPC_TRACER_ON(grpc_trace_secure_endpoint)) { + if (grpc_trace_secure_endpoint.enabled()) { for (i = 0; i < slices->count; i++) { - char *data = + char* data = grpc_dump_slice(slices->slices[i], GPR_DUMP_HEX | GPR_DUMP_ASCII); gpr_log(GPR_DEBUG, "WRITE %p: %s", ep, data); gpr_free(data); } } - if (ep->zero_copy_protector != NULL) { + if (ep->zero_copy_protector != nullptr) { // Use zero-copy grpc protector to protect. result = tsi_zero_copy_grpc_protector_protect( exec_ctx, ep->zero_copy_protector, slices, &ep->output_buffer); @@ -287,7 +287,7 @@ static void endpoint_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *secure_ep, // Use frame protector to protect. for (i = 0; i < slices->count; i++) { grpc_slice plain = slices->slices[i]; - uint8_t *message_bytes = GRPC_SLICE_START_PTR(plain); + uint8_t* message_bytes = GRPC_SLICE_START_PTR(plain); size_t message_size = GRPC_SLICE_LENGTH(plain); while (message_size > 0) { size_t protected_buffer_size_to_send = (size_t)(end - cur); @@ -353,52 +353,52 @@ static void endpoint_write(grpc_exec_ctx *exec_ctx, grpc_endpoint *secure_ep, GPR_TIMER_END("secure_endpoint.endpoint_write", 0); } -static void endpoint_shutdown(grpc_exec_ctx *exec_ctx, grpc_endpoint *secure_ep, - grpc_error *why) { - secure_endpoint *ep = (secure_endpoint *)secure_ep; +static void endpoint_shutdown(grpc_exec_ctx* exec_ctx, grpc_endpoint* secure_ep, + grpc_error* why) { + secure_endpoint* ep = (secure_endpoint*)secure_ep; grpc_endpoint_shutdown(exec_ctx, ep->wrapped_ep, why); } -static void endpoint_destroy(grpc_exec_ctx *exec_ctx, - grpc_endpoint *secure_ep) { - secure_endpoint *ep = (secure_endpoint *)secure_ep; +static void endpoint_destroy(grpc_exec_ctx* exec_ctx, + grpc_endpoint* secure_ep) { + secure_endpoint* ep = (secure_endpoint*)secure_ep; SECURE_ENDPOINT_UNREF(exec_ctx, ep, "destroy"); } -static void endpoint_add_to_pollset(grpc_exec_ctx *exec_ctx, - grpc_endpoint *secure_ep, - grpc_pollset *pollset) { - secure_endpoint *ep = (secure_endpoint *)secure_ep; +static void endpoint_add_to_pollset(grpc_exec_ctx* exec_ctx, + grpc_endpoint* secure_ep, + grpc_pollset* pollset) { + secure_endpoint* ep = (secure_endpoint*)secure_ep; grpc_endpoint_add_to_pollset(exec_ctx, ep->wrapped_ep, pollset); } -static void endpoint_add_to_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_endpoint *secure_ep, - grpc_pollset_set *pollset_set) { - secure_endpoint *ep = (secure_endpoint *)secure_ep; +static void endpoint_add_to_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_endpoint* secure_ep, + grpc_pollset_set* pollset_set) { + secure_endpoint* ep = (secure_endpoint*)secure_ep; grpc_endpoint_add_to_pollset_set(exec_ctx, ep->wrapped_ep, pollset_set); } -static void endpoint_delete_from_pollset_set(grpc_exec_ctx *exec_ctx, - grpc_endpoint *secure_ep, - grpc_pollset_set *pollset_set) { - secure_endpoint *ep = (secure_endpoint *)secure_ep; +static void endpoint_delete_from_pollset_set(grpc_exec_ctx* exec_ctx, + grpc_endpoint* secure_ep, + grpc_pollset_set* pollset_set) { + secure_endpoint* ep = (secure_endpoint*)secure_ep; grpc_endpoint_delete_from_pollset_set(exec_ctx, ep->wrapped_ep, pollset_set); } -static char *endpoint_get_peer(grpc_endpoint *secure_ep) { - secure_endpoint *ep = (secure_endpoint *)secure_ep; +static char* endpoint_get_peer(grpc_endpoint* secure_ep) { + secure_endpoint* ep = (secure_endpoint*)secure_ep; return grpc_endpoint_get_peer(ep->wrapped_ep); } -static int endpoint_get_fd(grpc_endpoint *secure_ep) { - secure_endpoint *ep = (secure_endpoint *)secure_ep; +static int endpoint_get_fd(grpc_endpoint* secure_ep) { + secure_endpoint* ep = (secure_endpoint*)secure_ep; return grpc_endpoint_get_fd(ep->wrapped_ep); } -static grpc_resource_user *endpoint_get_resource_user( - grpc_endpoint *secure_ep) { - secure_endpoint *ep = (secure_endpoint *)secure_ep; +static grpc_resource_user* endpoint_get_resource_user( + grpc_endpoint* secure_ep) { + secure_endpoint* ep = (secure_endpoint*)secure_ep; return grpc_endpoint_get_resource_user(ep->wrapped_ep); } @@ -413,13 +413,13 @@ static const grpc_endpoint_vtable vtable = {endpoint_read, endpoint_get_peer, endpoint_get_fd}; -grpc_endpoint *grpc_secure_endpoint_create( - struct tsi_frame_protector *protector, - struct tsi_zero_copy_grpc_protector *zero_copy_protector, - grpc_endpoint *transport, grpc_slice *leftover_slices, +grpc_endpoint* grpc_secure_endpoint_create( + struct tsi_frame_protector* protector, + struct tsi_zero_copy_grpc_protector* zero_copy_protector, + grpc_endpoint* transport, grpc_slice* leftover_slices, size_t leftover_nslices) { size_t i; - secure_endpoint *ep = (secure_endpoint *)gpr_malloc(sizeof(secure_endpoint)); + secure_endpoint* ep = (secure_endpoint*)gpr_malloc(sizeof(secure_endpoint)); ep->base.vtable = &vtable; ep->wrapped_ep = transport; ep->protector = protector; @@ -433,7 +433,7 @@ grpc_endpoint *grpc_secure_endpoint_create( ep->read_staging_buffer = GRPC_SLICE_MALLOC(STAGING_BUFFER_SIZE); grpc_slice_buffer_init(&ep->output_buffer); grpc_slice_buffer_init(&ep->source_buffer); - ep->read_buffer = NULL; + ep->read_buffer = nullptr; GRPC_CLOSURE_INIT(&ep->on_read, on_read, ep, grpc_schedule_on_exec_ctx); gpr_mu_init(&ep->protector_mu); gpr_ref_init(&ep->ref, 1); diff --git a/src/core/lib/security/transport/secure_endpoint.h b/src/core/lib/security/transport/secure_endpoint.h index 980449c03ee..b2556a01821 100644 --- a/src/core/lib/security/transport/secure_endpoint.h +++ b/src/core/lib/security/transport/secure_endpoint.h @@ -22,26 +22,18 @@ #include #include "src/core/lib/iomgr/endpoint.h" -#ifdef __cplusplus -extern "C" { -#endif - struct tsi_frame_protector; struct tsi_zero_copy_grpc_protector; -extern grpc_tracer_flag grpc_trace_secure_endpoint; +extern grpc_core::TraceFlag grpc_trace_secure_endpoint; /* Takes ownership of protector, zero_copy_protector, and to_wrap, and refs * leftover_slices. If zero_copy_protector is not NULL, protector will never be * used. */ -grpc_endpoint *grpc_secure_endpoint_create( - struct tsi_frame_protector *protector, - struct tsi_zero_copy_grpc_protector *zero_copy_protector, - grpc_endpoint *to_wrap, grpc_slice *leftover_slices, +grpc_endpoint* grpc_secure_endpoint_create( + struct tsi_frame_protector* protector, + struct tsi_zero_copy_grpc_protector* zero_copy_protector, + grpc_endpoint* to_wrap, grpc_slice* leftover_slices, size_t leftover_nslices); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SECURITY_TRANSPORT_SECURE_ENDPOINT_H */ diff --git a/src/core/lib/security/transport/security_connector.cc b/src/core/lib/security/transport/security_connector.cc index 06160d0caaf..c56e459aebd 100644 --- a/src/core/lib/security/transport/security_connector.cc +++ b/src/core/lib/security/transport/security_connector.cc @@ -44,23 +44,21 @@ #include "src/core/tsi/ssl_transport_security.h" #include "src/core/tsi/transport_security_adapter.h" -#ifndef NDEBUG -grpc_tracer_flag grpc_trace_security_connector_refcount = - GRPC_TRACER_INITIALIZER(false, "security_connector_refcount"); -#endif +grpc_core::DebugOnlyTraceFlag grpc_trace_security_connector_refcount( + false, "security_connector_refcount"); /* -- Constants. -- */ #ifndef INSTALL_PREFIX -static const char *installed_roots_path = "/usr/share/grpc/roots.pem"; +static const char* installed_roots_path = "/usr/share/grpc/roots.pem"; #else -static const char *installed_roots_path = +static const char* installed_roots_path = INSTALL_PREFIX "/share/grpc/roots.pem"; #endif /* -- Overridden default roots. -- */ -static grpc_ssl_roots_override_callback ssl_roots_override_cb = NULL; +static grpc_ssl_roots_override_callback ssl_roots_override_cb = nullptr; void grpc_set_ssl_roots_override_callback(grpc_ssl_roots_override_callback cb) { ssl_roots_override_cb = cb; @@ -74,14 +72,14 @@ void grpc_set_ssl_roots_override_callback(grpc_ssl_roots_override_callback cb) { "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384" static gpr_once cipher_suites_once = GPR_ONCE_INIT; -static const char *cipher_suites = NULL; +static const char* cipher_suites = nullptr; static void init_cipher_suites(void) { - char *overridden = gpr_getenv("GRPC_SSL_CIPHER_SUITES"); - cipher_suites = overridden != NULL ? overridden : GRPC_SSL_CIPHER_SUITES; + char* overridden = gpr_getenv("GRPC_SSL_CIPHER_SUITES"); + cipher_suites = overridden != nullptr ? overridden : GRPC_SSL_CIPHER_SUITES; } -static const char *ssl_cipher_suites(void) { +static const char* ssl_cipher_suites(void) { gpr_once_init(&cipher_suites_once, init_cipher_suites); return cipher_suites; } @@ -89,45 +87,45 @@ static const char *ssl_cipher_suites(void) { /* -- Common methods. -- */ /* Returns the first property with that name. */ -const tsi_peer_property *tsi_peer_get_property_by_name(const tsi_peer *peer, - const char *name) { +const tsi_peer_property* tsi_peer_get_property_by_name(const tsi_peer* peer, + const char* name) { size_t i; - if (peer == NULL) return NULL; + if (peer == nullptr) return nullptr; for (i = 0; i < peer->property_count; i++) { - const tsi_peer_property *property = &peer->properties[i]; - if (name == NULL && property->name == NULL) { + const tsi_peer_property* property = &peer->properties[i]; + if (name == nullptr && property->name == nullptr) { return property; } - if (name != NULL && property->name != NULL && + if (name != nullptr && property->name != nullptr && strcmp(property->name, name) == 0) { return property; } } - return NULL; + return nullptr; } void grpc_channel_security_connector_add_handshakers( - grpc_exec_ctx *exec_ctx, grpc_channel_security_connector *connector, - grpc_handshake_manager *handshake_mgr) { - if (connector != NULL) { + grpc_exec_ctx* exec_ctx, grpc_channel_security_connector* connector, + grpc_handshake_manager* handshake_mgr) { + if (connector != nullptr) { connector->add_handshakers(exec_ctx, connector, handshake_mgr); } } void grpc_server_security_connector_add_handshakers( - grpc_exec_ctx *exec_ctx, grpc_server_security_connector *connector, - grpc_handshake_manager *handshake_mgr) { - if (connector != NULL) { + grpc_exec_ctx* exec_ctx, grpc_server_security_connector* connector, + grpc_handshake_manager* handshake_mgr) { + if (connector != nullptr) { connector->add_handshakers(exec_ctx, connector, handshake_mgr); } } -void grpc_security_connector_check_peer(grpc_exec_ctx *exec_ctx, - grpc_security_connector *sc, +void grpc_security_connector_check_peer(grpc_exec_ctx* exec_ctx, + grpc_security_connector* sc, tsi_peer peer, - grpc_auth_context **auth_context, - grpc_closure *on_peer_checked) { - if (sc == NULL) { + grpc_auth_context** auth_context, + grpc_closure* on_peer_checked) { + if (sc == nullptr) { GRPC_CLOSURE_SCHED(exec_ctx, on_peer_checked, GRPC_ERROR_CREATE_FROM_STATIC_STRING( "cannot check peer -- no security connector")); @@ -137,44 +135,44 @@ void grpc_security_connector_check_peer(grpc_exec_ctx *exec_ctx, } } -int grpc_security_connector_cmp(grpc_security_connector *sc, - grpc_security_connector *other) { - if (sc == NULL || other == NULL) return GPR_ICMP(sc, other); +int grpc_security_connector_cmp(grpc_security_connector* sc, + grpc_security_connector* other) { + if (sc == nullptr || other == nullptr) return GPR_ICMP(sc, other); int c = GPR_ICMP(sc->vtable, other->vtable); if (c != 0) return c; return sc->vtable->cmp(sc, other); } -int grpc_channel_security_connector_cmp(grpc_channel_security_connector *sc1, - grpc_channel_security_connector *sc2) { - GPR_ASSERT(sc1->channel_creds != NULL); - GPR_ASSERT(sc2->channel_creds != NULL); +int grpc_channel_security_connector_cmp(grpc_channel_security_connector* sc1, + grpc_channel_security_connector* sc2) { + GPR_ASSERT(sc1->channel_creds != nullptr); + GPR_ASSERT(sc2->channel_creds != nullptr); int c = GPR_ICMP(sc1->channel_creds, sc2->channel_creds); if (c != 0) return c; c = GPR_ICMP(sc1->request_metadata_creds, sc2->request_metadata_creds); if (c != 0) return c; - c = GPR_ICMP((void *)sc1->check_call_host, (void *)sc2->check_call_host); + c = GPR_ICMP((void*)sc1->check_call_host, (void*)sc2->check_call_host); if (c != 0) return c; - c = GPR_ICMP((void *)sc1->cancel_check_call_host, - (void *)sc2->cancel_check_call_host); + c = GPR_ICMP((void*)sc1->cancel_check_call_host, + (void*)sc2->cancel_check_call_host); if (c != 0) return c; - return GPR_ICMP((void *)sc1->add_handshakers, (void *)sc2->add_handshakers); + return GPR_ICMP((void*)sc1->add_handshakers, (void*)sc2->add_handshakers); } -int grpc_server_security_connector_cmp(grpc_server_security_connector *sc1, - grpc_server_security_connector *sc2) { - GPR_ASSERT(sc1->server_creds != NULL); - GPR_ASSERT(sc2->server_creds != NULL); +int grpc_server_security_connector_cmp(grpc_server_security_connector* sc1, + grpc_server_security_connector* sc2) { + GPR_ASSERT(sc1->server_creds != nullptr); + GPR_ASSERT(sc2->server_creds != nullptr); int c = GPR_ICMP(sc1->server_creds, sc2->server_creds); if (c != 0) return c; - return GPR_ICMP((void *)sc1->add_handshakers, (void *)sc2->add_handshakers); + return GPR_ICMP((void*)sc1->add_handshakers, (void*)sc2->add_handshakers); } bool grpc_channel_security_connector_check_call_host( - grpc_exec_ctx *exec_ctx, grpc_channel_security_connector *sc, - const char *host, grpc_auth_context *auth_context, - grpc_closure *on_call_host_checked, grpc_error **error) { - if (sc == NULL || sc->check_call_host == NULL) { + grpc_exec_ctx* exec_ctx, grpc_channel_security_connector* sc, + const char* host, grpc_auth_context* auth_context, + grpc_closure* on_call_host_checked, grpc_error** error) { + if (sc == nullptr || sc->check_call_host == nullptr) { *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "cannot check call host -- no security connector"); return true; @@ -184,9 +182,9 @@ bool grpc_channel_security_connector_check_call_host( } void grpc_channel_security_connector_cancel_check_call_host( - grpc_exec_ctx *exec_ctx, grpc_channel_security_connector *sc, - grpc_closure *on_call_host_checked, grpc_error *error) { - if (sc == NULL || sc->cancel_check_call_host == NULL) { + grpc_exec_ctx* exec_ctx, grpc_channel_security_connector* sc, + grpc_closure* on_call_host_checked, grpc_error* error) { + if (sc == nullptr || sc->cancel_check_call_host == nullptr) { GRPC_ERROR_UNREF(error); return; } @@ -194,19 +192,19 @@ void grpc_channel_security_connector_cancel_check_call_host( } #ifndef NDEBUG -grpc_security_connector *grpc_security_connector_ref( - grpc_security_connector *sc, const char *file, int line, - const char *reason) { - if (sc == NULL) return NULL; - if (GRPC_TRACER_ON(grpc_trace_security_connector_refcount)) { +grpc_security_connector* grpc_security_connector_ref( + grpc_security_connector* sc, const char* file, int line, + const char* reason) { + if (sc == nullptr) return nullptr; + if (grpc_trace_security_connector_refcount.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&sc->refcount.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "SECURITY_CONNECTOR:%p ref %" PRIdPTR " -> %" PRIdPTR " %s", sc, val, val + 1, reason); } #else -grpc_security_connector *grpc_security_connector_ref( - grpc_security_connector *sc) { +grpc_security_connector* grpc_security_connector_ref( + grpc_security_connector* sc) { if (sc == NULL) return NULL; #endif gpr_ref(&sc->refcount); @@ -214,68 +212,68 @@ grpc_security_connector *grpc_security_connector_ref( } #ifndef NDEBUG -void grpc_security_connector_unref(grpc_exec_ctx *exec_ctx, - grpc_security_connector *sc, - const char *file, int line, - const char *reason) { - if (sc == NULL) return; - if (GRPC_TRACER_ON(grpc_trace_security_connector_refcount)) { +void grpc_security_connector_unref(grpc_exec_ctx* exec_ctx, + grpc_security_connector* sc, + const char* file, int line, + const char* reason) { + if (sc == nullptr) return; + if (grpc_trace_security_connector_refcount.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&sc->refcount.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "SECURITY_CONNECTOR:%p unref %" PRIdPTR " -> %" PRIdPTR " %s", sc, val, val - 1, reason); } #else -void grpc_security_connector_unref(grpc_exec_ctx *exec_ctx, - grpc_security_connector *sc) { +void grpc_security_connector_unref(grpc_exec_ctx* exec_ctx, + grpc_security_connector* sc) { if (sc == NULL) return; #endif if (gpr_unref(&sc->refcount)) sc->vtable->destroy(exec_ctx, sc); } -static void connector_arg_destroy(grpc_exec_ctx *exec_ctx, void *p) { - GRPC_SECURITY_CONNECTOR_UNREF(exec_ctx, (grpc_security_connector *)p, +static void connector_arg_destroy(grpc_exec_ctx* exec_ctx, void* p) { + GRPC_SECURITY_CONNECTOR_UNREF(exec_ctx, (grpc_security_connector*)p, "connector_arg_destroy"); } -static void *connector_arg_copy(void *p) { - return GRPC_SECURITY_CONNECTOR_REF((grpc_security_connector *)p, +static void* connector_arg_copy(void* p) { + return GRPC_SECURITY_CONNECTOR_REF((grpc_security_connector*)p, "connector_arg_copy"); } -static int connector_cmp(void *a, void *b) { - return grpc_security_connector_cmp((grpc_security_connector *)a, - (grpc_security_connector *)b); +static int connector_cmp(void* a, void* b) { + return grpc_security_connector_cmp((grpc_security_connector*)a, + (grpc_security_connector*)b); } static const grpc_arg_pointer_vtable connector_arg_vtable = { connector_arg_copy, connector_arg_destroy, connector_cmp}; -grpc_arg grpc_security_connector_to_arg(grpc_security_connector *sc) { - return grpc_channel_arg_pointer_create((char *)GRPC_ARG_SECURITY_CONNECTOR, - sc, &connector_arg_vtable); +grpc_arg grpc_security_connector_to_arg(grpc_security_connector* sc) { + return grpc_channel_arg_pointer_create((char*)GRPC_ARG_SECURITY_CONNECTOR, sc, + &connector_arg_vtable); } -grpc_security_connector *grpc_security_connector_from_arg(const grpc_arg *arg) { - if (strcmp(arg->key, GRPC_ARG_SECURITY_CONNECTOR)) return NULL; +grpc_security_connector* grpc_security_connector_from_arg(const grpc_arg* arg) { + if (strcmp(arg->key, GRPC_ARG_SECURITY_CONNECTOR)) return nullptr; if (arg->type != GRPC_ARG_POINTER) { gpr_log(GPR_ERROR, "Invalid type %d for arg %s", arg->type, GRPC_ARG_SECURITY_CONNECTOR); - return NULL; + return nullptr; } - return (grpc_security_connector *)arg->value.pointer.p; + return (grpc_security_connector*)arg->value.pointer.p; } -grpc_security_connector *grpc_security_connector_find_in_args( - const grpc_channel_args *args) { +grpc_security_connector* grpc_security_connector_find_in_args( + const grpc_channel_args* args) { size_t i; - if (args == NULL) return NULL; + if (args == nullptr) return nullptr; for (i = 0; i < args->num_args; i++) { - grpc_security_connector *sc = + grpc_security_connector* sc = grpc_security_connector_from_arg(&args->args[i]); - if (sc != NULL) return sc; + if (sc != nullptr) return sc; } - return NULL; + return nullptr; } static tsi_client_certificate_request_type @@ -306,36 +304,36 @@ get_tsi_client_certificate_request_type( typedef struct { grpc_channel_security_connector base; - char *target; - char *expected_targets; + char* target; + char* expected_targets; bool is_lb_channel; } grpc_fake_channel_security_connector; -static void fake_channel_destroy(grpc_exec_ctx *exec_ctx, - grpc_security_connector *sc) { - grpc_fake_channel_security_connector *c = - (grpc_fake_channel_security_connector *)sc; +static void fake_channel_destroy(grpc_exec_ctx* exec_ctx, + grpc_security_connector* sc) { + grpc_fake_channel_security_connector* c = + (grpc_fake_channel_security_connector*)sc; grpc_call_credentials_unref(exec_ctx, c->base.request_metadata_creds); gpr_free(c->target); gpr_free(c->expected_targets); gpr_free(c); } -static void fake_server_destroy(grpc_exec_ctx *exec_ctx, - grpc_security_connector *sc) { +static void fake_server_destroy(grpc_exec_ctx* exec_ctx, + grpc_security_connector* sc) { gpr_free(sc); } -static bool fake_check_target(const char *target_type, const char *target, - const char *set_str) { - GPR_ASSERT(target_type != NULL); - GPR_ASSERT(target != NULL); - char **set = NULL; +static bool fake_check_target(const char* target_type, const char* target, + const char* set_str) { + GPR_ASSERT(target_type != nullptr); + GPR_ASSERT(target != nullptr); + char** set = nullptr; size_t set_size = 0; gpr_string_split(set_str, ",", &set, &set_size); bool found = false; for (size_t i = 0; i < set_size; ++i) { - if (set[i] != NULL && strcmp(target, set[i]) == 0) found = true; + if (set[i] != nullptr && strcmp(target, set[i]) == 0) found = true; } for (size_t i = 0; i < set_size; ++i) { gpr_free(set[i]); @@ -344,11 +342,11 @@ static bool fake_check_target(const char *target_type, const char *target, return found; } -static void fake_secure_name_check(const char *target, - const char *expected_targets, +static void fake_secure_name_check(const char* target, + const char* expected_targets, bool is_lb_channel) { - if (expected_targets == NULL) return; - char **lbs_and_backends = NULL; + if (expected_targets == nullptr) return; + char** lbs_and_backends = nullptr; size_t lbs_and_backends_size = 0; bool success = false; gpr_string_split(expected_targets, ";", &lbs_and_backends, @@ -388,24 +386,24 @@ done: if (!success) abort(); } -static void fake_check_peer(grpc_exec_ctx *exec_ctx, - grpc_security_connector *sc, tsi_peer peer, - grpc_auth_context **auth_context, - grpc_closure *on_peer_checked) { - const char *prop_name; - grpc_error *error = GRPC_ERROR_NONE; - *auth_context = NULL; +static void fake_check_peer(grpc_exec_ctx* exec_ctx, + grpc_security_connector* sc, tsi_peer peer, + grpc_auth_context** auth_context, + grpc_closure* on_peer_checked) { + const char* prop_name; + grpc_error* error = GRPC_ERROR_NONE; + *auth_context = nullptr; if (peer.property_count != 1) { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Fake peers should only have 1 property."); goto end; } prop_name = peer.properties[0].name; - if (prop_name == NULL || + if (prop_name == nullptr || strcmp(prop_name, TSI_CERTIFICATE_TYPE_PEER_PROPERTY)) { - char *msg; + char* msg; gpr_asprintf(&msg, "Unexpected property in fake peer: %s.", - prop_name == NULL ? "" : prop_name); + prop_name == nullptr ? "" : prop_name); error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); goto end; @@ -416,7 +414,7 @@ static void fake_check_peer(grpc_exec_ctx *exec_ctx, "Invalid value for cert type property."); goto end; } - *auth_context = grpc_auth_context_create(NULL); + *auth_context = grpc_auth_context_create(nullptr); grpc_auth_context_add_cstring_property( *auth_context, GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME, GRPC_FAKE_TRANSPORT_SECURITY_TYPE); @@ -425,34 +423,34 @@ end: tsi_peer_destruct(&peer); } -static void fake_channel_check_peer(grpc_exec_ctx *exec_ctx, - grpc_security_connector *sc, tsi_peer peer, - grpc_auth_context **auth_context, - grpc_closure *on_peer_checked) { +static void fake_channel_check_peer(grpc_exec_ctx* exec_ctx, + grpc_security_connector* sc, tsi_peer peer, + grpc_auth_context** auth_context, + grpc_closure* on_peer_checked) { fake_check_peer(exec_ctx, sc, peer, auth_context, on_peer_checked); - grpc_fake_channel_security_connector *c = - (grpc_fake_channel_security_connector *)sc; + grpc_fake_channel_security_connector* c = + (grpc_fake_channel_security_connector*)sc; fake_secure_name_check(c->target, c->expected_targets, c->is_lb_channel); } -static void fake_server_check_peer(grpc_exec_ctx *exec_ctx, - grpc_security_connector *sc, tsi_peer peer, - grpc_auth_context **auth_context, - grpc_closure *on_peer_checked) { +static void fake_server_check_peer(grpc_exec_ctx* exec_ctx, + grpc_security_connector* sc, tsi_peer peer, + grpc_auth_context** auth_context, + grpc_closure* on_peer_checked) { fake_check_peer(exec_ctx, sc, peer, auth_context, on_peer_checked); } -static int fake_channel_cmp(grpc_security_connector *sc1, - grpc_security_connector *sc2) { - grpc_fake_channel_security_connector *c1 = - (grpc_fake_channel_security_connector *)sc1; - grpc_fake_channel_security_connector *c2 = - (grpc_fake_channel_security_connector *)sc2; +static int fake_channel_cmp(grpc_security_connector* sc1, + grpc_security_connector* sc2) { + grpc_fake_channel_security_connector* c1 = + (grpc_fake_channel_security_connector*)sc1; + grpc_fake_channel_security_connector* c2 = + (grpc_fake_channel_security_connector*)sc2; int c = grpc_channel_security_connector_cmp(&c1->base, &c2->base); if (c != 0) return c; c = strcmp(c1->target, c2->target); if (c != 0) return c; - if (c1->expected_targets == NULL || c2->expected_targets == NULL) { + if (c1->expected_targets == nullptr || c2->expected_targets == nullptr) { c = GPR_ICMP(c1->expected_targets, c2->expected_targets); } else { c = strcmp(c1->expected_targets, c2->expected_targets); @@ -461,31 +459,31 @@ static int fake_channel_cmp(grpc_security_connector *sc1, return GPR_ICMP(c1->is_lb_channel, c2->is_lb_channel); } -static int fake_server_cmp(grpc_security_connector *sc1, - grpc_security_connector *sc2) { +static int fake_server_cmp(grpc_security_connector* sc1, + grpc_security_connector* sc2) { return grpc_server_security_connector_cmp( - (grpc_server_security_connector *)sc1, - (grpc_server_security_connector *)sc2); + (grpc_server_security_connector*)sc1, + (grpc_server_security_connector*)sc2); } -static bool fake_channel_check_call_host(grpc_exec_ctx *exec_ctx, - grpc_channel_security_connector *sc, - const char *host, - grpc_auth_context *auth_context, - grpc_closure *on_call_host_checked, - grpc_error **error) { +static bool fake_channel_check_call_host(grpc_exec_ctx* exec_ctx, + grpc_channel_security_connector* sc, + const char* host, + grpc_auth_context* auth_context, + grpc_closure* on_call_host_checked, + grpc_error** error) { return true; } static void fake_channel_cancel_check_call_host( - grpc_exec_ctx *exec_ctx, grpc_channel_security_connector *sc, - grpc_closure *on_call_host_checked, grpc_error *error) { + grpc_exec_ctx* exec_ctx, grpc_channel_security_connector* sc, + grpc_closure* on_call_host_checked, grpc_error* error) { GRPC_ERROR_UNREF(error); } static void fake_channel_add_handshakers( - grpc_exec_ctx *exec_ctx, grpc_channel_security_connector *sc, - grpc_handshake_manager *handshake_mgr) { + grpc_exec_ctx* exec_ctx, grpc_channel_security_connector* sc, + grpc_handshake_manager* handshake_mgr) { grpc_handshake_manager_add( handshake_mgr, grpc_security_handshaker_create( @@ -493,9 +491,9 @@ static void fake_channel_add_handshakers( &sc->base)); } -static void fake_server_add_handshakers(grpc_exec_ctx *exec_ctx, - grpc_server_security_connector *sc, - grpc_handshake_manager *handshake_mgr) { +static void fake_server_add_handshakers(grpc_exec_ctx* exec_ctx, + grpc_server_security_connector* sc, + grpc_handshake_manager* handshake_mgr) { grpc_handshake_manager_add( handshake_mgr, grpc_security_handshaker_create( @@ -509,12 +507,12 @@ static grpc_security_connector_vtable fake_channel_vtable = { static grpc_security_connector_vtable fake_server_vtable = { fake_server_destroy, fake_server_check_peer, fake_server_cmp}; -grpc_channel_security_connector *grpc_fake_channel_security_connector_create( - grpc_channel_credentials *channel_creds, - grpc_call_credentials *request_metadata_creds, const char *target, - const grpc_channel_args *args) { - grpc_fake_channel_security_connector *c = - (grpc_fake_channel_security_connector *)gpr_zalloc(sizeof(*c)); +grpc_channel_security_connector* grpc_fake_channel_security_connector_create( + grpc_channel_credentials* channel_creds, + grpc_call_credentials* request_metadata_creds, const char* target, + const grpc_channel_args* args) { + grpc_fake_channel_security_connector* c = + (grpc_fake_channel_security_connector*)gpr_zalloc(sizeof(*c)); gpr_ref_init(&c->base.base.refcount, 1); c->base.base.url_scheme = GRPC_FAKE_SECURITY_URL_SCHEME; c->base.base.vtable = &fake_channel_vtable; @@ -525,16 +523,16 @@ grpc_channel_security_connector *grpc_fake_channel_security_connector_create( c->base.cancel_check_call_host = fake_channel_cancel_check_call_host; c->base.add_handshakers = fake_channel_add_handshakers; c->target = gpr_strdup(target); - const char *expected_targets = grpc_fake_transport_get_expected_targets(args); + const char* expected_targets = grpc_fake_transport_get_expected_targets(args); c->expected_targets = gpr_strdup(expected_targets); - c->is_lb_channel = (grpc_lb_targets_info_find_in_args(args) != NULL); + c->is_lb_channel = (grpc_lb_targets_info_find_in_args(args) != nullptr); return &c->base; } -grpc_server_security_connector *grpc_fake_server_security_connector_create( - grpc_server_credentials *server_creds) { - grpc_server_security_connector *c = - (grpc_server_security_connector *)gpr_zalloc( +grpc_server_security_connector* grpc_fake_server_security_connector_create( + grpc_server_credentials* server_creds) { + grpc_server_security_connector* c = + (grpc_server_security_connector*)gpr_zalloc( sizeof(grpc_server_security_connector)); gpr_ref_init(&c->base.refcount, 1); c->base.vtable = &fake_server_vtable; @@ -548,59 +546,59 @@ grpc_server_security_connector *grpc_fake_server_security_connector_create( typedef struct { grpc_channel_security_connector base; - tsi_ssl_client_handshaker_factory *client_handshaker_factory; - char *target_name; - char *overridden_target_name; + tsi_ssl_client_handshaker_factory* client_handshaker_factory; + char* target_name; + char* overridden_target_name; } grpc_ssl_channel_security_connector; typedef struct { grpc_server_security_connector base; - tsi_ssl_server_handshaker_factory *server_handshaker_factory; + tsi_ssl_server_handshaker_factory* server_handshaker_factory; } grpc_ssl_server_security_connector; static bool server_connector_has_cert_config_fetcher( - grpc_ssl_server_security_connector *c) { - GPR_ASSERT(c != NULL); - grpc_ssl_server_credentials *server_creds = - (grpc_ssl_server_credentials *)c->base.server_creds; - GPR_ASSERT(server_creds != NULL); - return server_creds->certificate_config_fetcher.cb != NULL; + grpc_ssl_server_security_connector* c) { + GPR_ASSERT(c != nullptr); + grpc_ssl_server_credentials* server_creds = + (grpc_ssl_server_credentials*)c->base.server_creds; + GPR_ASSERT(server_creds != nullptr); + return server_creds->certificate_config_fetcher.cb != nullptr; } -static void ssl_channel_destroy(grpc_exec_ctx *exec_ctx, - grpc_security_connector *sc) { - grpc_ssl_channel_security_connector *c = - (grpc_ssl_channel_security_connector *)sc; +static void ssl_channel_destroy(grpc_exec_ctx* exec_ctx, + grpc_security_connector* sc) { + grpc_ssl_channel_security_connector* c = + (grpc_ssl_channel_security_connector*)sc; grpc_channel_credentials_unref(exec_ctx, c->base.channel_creds); grpc_call_credentials_unref(exec_ctx, c->base.request_metadata_creds); tsi_ssl_client_handshaker_factory_unref(c->client_handshaker_factory); - c->client_handshaker_factory = NULL; - if (c->target_name != NULL) gpr_free(c->target_name); - if (c->overridden_target_name != NULL) gpr_free(c->overridden_target_name); + c->client_handshaker_factory = nullptr; + if (c->target_name != nullptr) gpr_free(c->target_name); + if (c->overridden_target_name != nullptr) gpr_free(c->overridden_target_name); gpr_free(sc); } -static void ssl_server_destroy(grpc_exec_ctx *exec_ctx, - grpc_security_connector *sc) { - grpc_ssl_server_security_connector *c = - (grpc_ssl_server_security_connector *)sc; +static void ssl_server_destroy(grpc_exec_ctx* exec_ctx, + grpc_security_connector* sc) { + grpc_ssl_server_security_connector* c = + (grpc_ssl_server_security_connector*)sc; grpc_server_credentials_unref(exec_ctx, c->base.server_creds); tsi_ssl_server_handshaker_factory_unref(c->server_handshaker_factory); - c->server_handshaker_factory = NULL; + c->server_handshaker_factory = nullptr; gpr_free(sc); } -static void ssl_channel_add_handshakers(grpc_exec_ctx *exec_ctx, - grpc_channel_security_connector *sc, - grpc_handshake_manager *handshake_mgr) { - grpc_ssl_channel_security_connector *c = - (grpc_ssl_channel_security_connector *)sc; +static void ssl_channel_add_handshakers(grpc_exec_ctx* exec_ctx, + grpc_channel_security_connector* sc, + grpc_handshake_manager* handshake_mgr) { + grpc_ssl_channel_security_connector* c = + (grpc_ssl_channel_security_connector*)sc; // Instantiate TSI handshaker. - tsi_handshaker *tsi_hs = NULL; + tsi_handshaker* tsi_hs = nullptr; tsi_result result = tsi_ssl_client_handshaker_factory_create_handshaker( c->client_handshaker_factory, - c->overridden_target_name != NULL ? c->overridden_target_name - : c->target_name, + c->overridden_target_name != nullptr ? c->overridden_target_name + : c->target_name, &tsi_hs); if (result != TSI_OK) { gpr_log(GPR_ERROR, "Handshaker creation failed with error %s.", @@ -614,11 +612,11 @@ static void ssl_channel_add_handshakers(grpc_exec_ctx *exec_ctx, exec_ctx, tsi_create_adapter_handshaker(tsi_hs), &sc->base)); } -static const char **fill_alpn_protocol_strings(size_t *num_alpn_protocols) { - GPR_ASSERT(num_alpn_protocols != NULL); +static const char** fill_alpn_protocol_strings(size_t* num_alpn_protocols) { + GPR_ASSERT(num_alpn_protocols != nullptr); *num_alpn_protocols = grpc_chttp2_num_alpn_versions(); - const char **alpn_protocol_strings = - (const char **)gpr_malloc(sizeof(const char *) * (*num_alpn_protocols)); + const char** alpn_protocol_strings = + (const char**)gpr_malloc(sizeof(const char*) * (*num_alpn_protocols)); for (size_t i = 0; i < *num_alpn_protocols; i++) { alpn_protocol_strings[i] = grpc_chttp2_get_alpn_version_index(i); } @@ -630,9 +628,9 @@ static const char **fill_alpn_protocol_strings(size_t *num_alpn_protocols) { * fail, the existing factory will not be replaced. Returns true on success (new * factory created). */ static bool try_replace_server_handshaker_factory( - grpc_ssl_server_security_connector *sc, - const grpc_ssl_server_certificate_config *config) { - if (config == NULL) { + grpc_ssl_server_security_connector* sc, + const grpc_ssl_server_certificate_config* config) { + if (config == nullptr) { gpr_log(GPR_ERROR, "Server certificate config callback returned invalid (NULL) " "config."); @@ -641,13 +639,13 @@ static bool try_replace_server_handshaker_factory( gpr_log(GPR_DEBUG, "Using new server certificate config (%p).", config); size_t num_alpn_protocols = 0; - const char **alpn_protocol_strings = + const char** alpn_protocol_strings = fill_alpn_protocol_strings(&num_alpn_protocols); - tsi_ssl_pem_key_cert_pair *cert_pairs = grpc_convert_grpc_to_tsi_cert_pairs( + tsi_ssl_pem_key_cert_pair* cert_pairs = grpc_convert_grpc_to_tsi_cert_pairs( config->pem_key_cert_pairs, config->num_key_cert_pairs); - tsi_ssl_server_handshaker_factory *new_handshaker_factory = NULL; - grpc_ssl_server_credentials *server_creds = - (grpc_ssl_server_credentials *)sc->base.server_creds; + tsi_ssl_server_handshaker_factory* new_handshaker_factory = nullptr; + grpc_ssl_server_credentials* server_creds = + (grpc_ssl_server_credentials*)sc->base.server_creds; tsi_result result = tsi_create_ssl_server_handshaker_factory_ex( cert_pairs, config->num_key_cert_pairs, config->pem_root_certs, get_tsi_client_certificate_request_type( @@ -655,7 +653,7 @@ static bool try_replace_server_handshaker_factory( ssl_cipher_suites(), alpn_protocol_strings, (uint16_t)num_alpn_protocols, &new_handshaker_factory); gpr_free(cert_pairs); - gpr_free((void *)alpn_protocol_strings); + gpr_free((void*)alpn_protocol_strings); if (result != TSI_OK) { gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.", @@ -671,15 +669,15 @@ static bool try_replace_server_handshaker_factory( * Current certificate config will continue to be used if the callback returns * an error. Returns true if new credentials were sucessfully loaded. */ static bool try_fetch_ssl_server_credentials( - grpc_ssl_server_security_connector *sc) { - grpc_ssl_server_certificate_config *certificate_config = NULL; + grpc_ssl_server_security_connector* sc) { + grpc_ssl_server_certificate_config* certificate_config = nullptr; bool status; - GPR_ASSERT(sc != NULL); + GPR_ASSERT(sc != nullptr); if (!server_connector_has_cert_config_fetcher(sc)) return false; - grpc_ssl_server_credentials *server_creds = - (grpc_ssl_server_credentials *)sc->base.server_creds; + grpc_ssl_server_credentials* server_creds = + (grpc_ssl_server_credentials*)sc->base.server_creds; grpc_ssl_certificate_config_reload_status cb_result = server_creds->certificate_config_fetcher.cb( server_creds->certificate_config_fetcher.user_data, @@ -697,20 +695,20 @@ static bool try_fetch_ssl_server_credentials( status = false; } - if (certificate_config != NULL) { + if (certificate_config != nullptr) { grpc_ssl_server_certificate_config_destroy(certificate_config); } return status; } -static void ssl_server_add_handshakers(grpc_exec_ctx *exec_ctx, - grpc_server_security_connector *sc, - grpc_handshake_manager *handshake_mgr) { - grpc_ssl_server_security_connector *c = - (grpc_ssl_server_security_connector *)sc; +static void ssl_server_add_handshakers(grpc_exec_ctx* exec_ctx, + grpc_server_security_connector* sc, + grpc_handshake_manager* handshake_mgr) { + grpc_ssl_server_security_connector* c = + (grpc_ssl_server_security_connector*)sc; // Instantiate TSI handshaker. try_fetch_ssl_server_credentials(c); - tsi_handshaker *tsi_hs = NULL; + tsi_handshaker* tsi_hs = nullptr; tsi_result result = tsi_ssl_server_handshaker_factory_create_handshaker( c->server_handshaker_factory, &tsi_hs); if (result != TSI_OK) { @@ -725,12 +723,12 @@ static void ssl_server_add_handshakers(grpc_exec_ctx *exec_ctx, exec_ctx, tsi_create_adapter_handshaker(tsi_hs), &sc->base)); } -static int ssl_host_matches_name(const tsi_peer *peer, const char *peer_name) { - char *allocated_name = NULL; +static int ssl_host_matches_name(const tsi_peer* peer, const char* peer_name) { + char* allocated_name = nullptr; int r; - if (strchr(peer_name, ':') != NULL) { - char *ignored_port; + if (strchr(peer_name, ':') != nullptr) { + char* ignored_port; gpr_split_host_port(peer_name, &allocated_name, &ignored_port); gpr_free(ignored_port); peer_name = allocated_name; @@ -741,23 +739,23 @@ static int ssl_host_matches_name(const tsi_peer *peer, const char *peer_name) { return r; } -grpc_auth_context *tsi_ssl_peer_to_auth_context(const tsi_peer *peer) { +grpc_auth_context* tsi_ssl_peer_to_auth_context(const tsi_peer* peer) { size_t i; - grpc_auth_context *ctx = NULL; - const char *peer_identity_property_name = NULL; + grpc_auth_context* ctx = nullptr; + const char* peer_identity_property_name = nullptr; /* The caller has checked the certificate type property. */ GPR_ASSERT(peer->property_count >= 1); - ctx = grpc_auth_context_create(NULL); + ctx = grpc_auth_context_create(nullptr); grpc_auth_context_add_cstring_property( ctx, GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME, GRPC_SSL_TRANSPORT_SECURITY_TYPE); for (i = 0; i < peer->property_count; i++) { - const tsi_peer_property *prop = &peer->properties[i]; - if (prop->name == NULL) continue; + const tsi_peer_property* prop = &peer->properties[i]; + if (prop->name == nullptr) continue; if (strcmp(prop->name, TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY) == 0) { /* If there is no subject alt name, have the CN as the identity. */ - if (peer_identity_property_name == NULL) { + if (peer_identity_property_name == nullptr) { peer_identity_property_name = GRPC_X509_CN_PROPERTY_NAME; } grpc_auth_context_add_property(ctx, GRPC_X509_CN_PROPERTY_NAME, @@ -772,20 +770,20 @@ grpc_auth_context *tsi_ssl_peer_to_auth_context(const tsi_peer *peer) { prop->value.data, prop->value.length); } } - if (peer_identity_property_name != NULL) { + if (peer_identity_property_name != nullptr) { GPR_ASSERT(grpc_auth_context_set_peer_identity_property_name( ctx, peer_identity_property_name) == 1); } return ctx; } -static grpc_error *ssl_check_peer(grpc_security_connector *sc, - const char *peer_name, const tsi_peer *peer, - grpc_auth_context **auth_context) { +static grpc_error* ssl_check_peer(grpc_security_connector* sc, + const char* peer_name, const tsi_peer* peer, + grpc_auth_context** auth_context) { /* Check the ALPN. */ - const tsi_peer_property *p = + const tsi_peer_property* p = tsi_peer_get_property_by_name(peer, TSI_SSL_ALPN_SELECTED_PROTOCOL); - if (p == NULL) { + if (p == nullptr) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Cannot check peer: missing selected ALPN property."); } @@ -795,10 +793,10 @@ static grpc_error *ssl_check_peer(grpc_security_connector *sc, } /* Check the peer name if specified. */ - if (peer_name != NULL && !ssl_host_matches_name(peer, peer_name)) { - char *msg; + if (peer_name != nullptr && !ssl_host_matches_name(peer, peer_name)) { + char* msg; gpr_asprintf(&msg, "Peer name %s is not in peer certificate", peer_name); - grpc_error *error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); + grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(msg); gpr_free(msg); return error; } @@ -806,77 +804,78 @@ static grpc_error *ssl_check_peer(grpc_security_connector *sc, return GRPC_ERROR_NONE; } -static void ssl_channel_check_peer(grpc_exec_ctx *exec_ctx, - grpc_security_connector *sc, tsi_peer peer, - grpc_auth_context **auth_context, - grpc_closure *on_peer_checked) { - grpc_ssl_channel_security_connector *c = - (grpc_ssl_channel_security_connector *)sc; - grpc_error *error = ssl_check_peer(sc, c->overridden_target_name != NULL - ? c->overridden_target_name - : c->target_name, +static void ssl_channel_check_peer(grpc_exec_ctx* exec_ctx, + grpc_security_connector* sc, tsi_peer peer, + grpc_auth_context** auth_context, + grpc_closure* on_peer_checked) { + grpc_ssl_channel_security_connector* c = + (grpc_ssl_channel_security_connector*)sc; + grpc_error* error = ssl_check_peer(sc, + c->overridden_target_name != nullptr + ? c->overridden_target_name + : c->target_name, &peer, auth_context); GRPC_CLOSURE_SCHED(exec_ctx, on_peer_checked, error); tsi_peer_destruct(&peer); } -static void ssl_server_check_peer(grpc_exec_ctx *exec_ctx, - grpc_security_connector *sc, tsi_peer peer, - grpc_auth_context **auth_context, - grpc_closure *on_peer_checked) { - grpc_error *error = ssl_check_peer(sc, NULL, &peer, auth_context); +static void ssl_server_check_peer(grpc_exec_ctx* exec_ctx, + grpc_security_connector* sc, tsi_peer peer, + grpc_auth_context** auth_context, + grpc_closure* on_peer_checked) { + grpc_error* error = ssl_check_peer(sc, nullptr, &peer, auth_context); tsi_peer_destruct(&peer); GRPC_CLOSURE_SCHED(exec_ctx, on_peer_checked, error); } -static int ssl_channel_cmp(grpc_security_connector *sc1, - grpc_security_connector *sc2) { - grpc_ssl_channel_security_connector *c1 = - (grpc_ssl_channel_security_connector *)sc1; - grpc_ssl_channel_security_connector *c2 = - (grpc_ssl_channel_security_connector *)sc2; +static int ssl_channel_cmp(grpc_security_connector* sc1, + grpc_security_connector* sc2) { + grpc_ssl_channel_security_connector* c1 = + (grpc_ssl_channel_security_connector*)sc1; + grpc_ssl_channel_security_connector* c2 = + (grpc_ssl_channel_security_connector*)sc2; int c = grpc_channel_security_connector_cmp(&c1->base, &c2->base); if (c != 0) return c; c = strcmp(c1->target_name, c2->target_name); if (c != 0) return c; - return (c1->overridden_target_name == NULL || - c2->overridden_target_name == NULL) + return (c1->overridden_target_name == nullptr || + c2->overridden_target_name == nullptr) ? GPR_ICMP(c1->overridden_target_name, c2->overridden_target_name) : strcmp(c1->overridden_target_name, c2->overridden_target_name); } -static int ssl_server_cmp(grpc_security_connector *sc1, - grpc_security_connector *sc2) { +static int ssl_server_cmp(grpc_security_connector* sc1, + grpc_security_connector* sc2) { return grpc_server_security_connector_cmp( - (grpc_server_security_connector *)sc1, - (grpc_server_security_connector *)sc2); + (grpc_server_security_connector*)sc1, + (grpc_server_security_connector*)sc2); } -static void add_shallow_auth_property_to_peer(tsi_peer *peer, - const grpc_auth_property *prop, - const char *tsi_prop_name) { - tsi_peer_property *tsi_prop = &peer->properties[peer->property_count++]; - tsi_prop->name = (char *)tsi_prop_name; +static void add_shallow_auth_property_to_peer(tsi_peer* peer, + const grpc_auth_property* prop, + const char* tsi_prop_name) { + tsi_peer_property* tsi_prop = &peer->properties[peer->property_count++]; + tsi_prop->name = (char*)tsi_prop_name; tsi_prop->value.data = prop->value; tsi_prop->value.length = prop->value_length; } tsi_peer tsi_shallow_peer_from_ssl_auth_context( - const grpc_auth_context *auth_context) { + const grpc_auth_context* auth_context) { size_t max_num_props = 0; grpc_auth_property_iterator it; - const grpc_auth_property *prop; + const grpc_auth_property* prop; tsi_peer peer; memset(&peer, 0, sizeof(peer)); it = grpc_auth_context_property_iterator(auth_context); - while (grpc_auth_property_iterator_next(&it) != NULL) max_num_props++; + while (grpc_auth_property_iterator_next(&it) != nullptr) max_num_props++; if (max_num_props > 0) { - peer.properties = (tsi_peer_property *)gpr_malloc( - max_num_props * sizeof(tsi_peer_property)); + peer.properties = (tsi_peer_property*)gpr_malloc(max_num_props * + sizeof(tsi_peer_property)); it = grpc_auth_context_property_iterator(auth_context); - while ((prop = grpc_auth_property_iterator_next(&it)) != NULL) { + while ((prop = grpc_auth_property_iterator_next(&it)) != nullptr) { if (strcmp(prop->name, GRPC_X509_SAN_PROPERTY_NAME) == 0) { add_shallow_auth_property_to_peer( &peer, prop, TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY); @@ -892,25 +891,26 @@ tsi_peer tsi_shallow_peer_from_ssl_auth_context( return peer; } -void tsi_shallow_peer_destruct(tsi_peer *peer) { - if (peer->properties != NULL) gpr_free(peer->properties); +void tsi_shallow_peer_destruct(tsi_peer* peer) { + if (peer->properties != nullptr) gpr_free(peer->properties); } -static bool ssl_channel_check_call_host(grpc_exec_ctx *exec_ctx, - grpc_channel_security_connector *sc, - const char *host, - grpc_auth_context *auth_context, - grpc_closure *on_call_host_checked, - grpc_error **error) { - grpc_ssl_channel_security_connector *c = - (grpc_ssl_channel_security_connector *)sc; +static bool ssl_channel_check_call_host(grpc_exec_ctx* exec_ctx, + grpc_channel_security_connector* sc, + const char* host, + grpc_auth_context* auth_context, + grpc_closure* on_call_host_checked, + grpc_error** error) { + grpc_ssl_channel_security_connector* c = + (grpc_ssl_channel_security_connector*)sc; grpc_security_status status = GRPC_SECURITY_ERROR; tsi_peer peer = tsi_shallow_peer_from_ssl_auth_context(auth_context); if (ssl_host_matches_name(&peer, host)) status = GRPC_SECURITY_OK; /* If the target name was overridden, then the original target_name was 'checked' transitively during the previous peer check at the end of the handshake. */ - if (c->overridden_target_name != NULL && strcmp(host, c->target_name) == 0) { + if (c->overridden_target_name != nullptr && + strcmp(host, c->target_name) == 0) { status = GRPC_SECURITY_OK; } if (status != GRPC_SECURITY_OK) { @@ -922,8 +922,8 @@ static bool ssl_channel_check_call_host(grpc_exec_ctx *exec_ctx, } static void ssl_channel_cancel_check_call_host( - grpc_exec_ctx *exec_ctx, grpc_channel_security_connector *sc, - grpc_closure *on_call_host_checked, grpc_error *error) { + grpc_exec_ctx* exec_ctx, grpc_channel_security_connector* sc, + grpc_closure* on_call_host_checked, grpc_error* error) { GRPC_ERROR_UNREF(error); } @@ -938,9 +938,9 @@ static grpc_slice compute_default_pem_root_certs_once(void) { grpc_slice result = grpc_empty_slice(); /* First try to load the roots from the environment. */ - char *default_root_certs_path = + char* default_root_certs_path = gpr_getenv(GRPC_DEFAULT_SSL_ROOTS_FILE_PATH_ENV_VAR); - if (default_root_certs_path != NULL) { + if (default_root_certs_path != nullptr) { GRPC_LOG_IF_ERROR("load_file", grpc_load_file(default_root_certs_path, 1, &result)); gpr_free(default_root_certs_path); @@ -948,11 +948,11 @@ static grpc_slice compute_default_pem_root_certs_once(void) { /* Try overridden roots if needed. */ grpc_ssl_roots_override_result ovrd_res = GRPC_SSL_ROOTS_OVERRIDE_FAIL; - if (GRPC_SLICE_IS_EMPTY(result) && ssl_roots_override_cb != NULL) { - char *pem_root_certs = NULL; + if (GRPC_SLICE_IS_EMPTY(result) && ssl_roots_override_cb != nullptr) { + char* pem_root_certs = nullptr; ovrd_res = ssl_roots_override_cb(&pem_root_certs); if (ovrd_res == GRPC_SSL_ROOTS_OVERRIDE_OK) { - GPR_ASSERT(pem_root_certs != NULL); + GPR_ASSERT(pem_root_certs != nullptr); result = grpc_slice_from_copied_buffer( pem_root_certs, strlen(pem_root_certs) + 1); // NULL terminator. @@ -979,37 +979,37 @@ grpc_slice grpc_get_default_ssl_roots_for_testing(void) { return compute_default_pem_root_certs_once(); } -const char *grpc_get_default_ssl_roots(void) { +const char* grpc_get_default_ssl_roots(void) { /* TODO(jboeuf@google.com): Maybe revisit the approach which consists in loading all the roots once for the lifetime of the process. */ static gpr_once once = GPR_ONCE_INIT; gpr_once_init(&once, init_default_pem_root_certs); return GRPC_SLICE_IS_EMPTY(default_pem_root_certs) - ? NULL - : (const char *)GRPC_SLICE_START_PTR(default_pem_root_certs); + ? nullptr + : (const char*)GRPC_SLICE_START_PTR(default_pem_root_certs); } grpc_security_status grpc_ssl_channel_security_connector_create( - grpc_exec_ctx *exec_ctx, grpc_channel_credentials *channel_creds, - grpc_call_credentials *request_metadata_creds, - const grpc_ssl_config *config, const char *target_name, - const char *overridden_target_name, grpc_channel_security_connector **sc) { + grpc_exec_ctx* exec_ctx, grpc_channel_credentials* channel_creds, + grpc_call_credentials* request_metadata_creds, + const grpc_ssl_config* config, const char* target_name, + const char* overridden_target_name, grpc_channel_security_connector** sc) { size_t num_alpn_protocols = 0; - const char **alpn_protocol_strings = + const char** alpn_protocol_strings = fill_alpn_protocol_strings(&num_alpn_protocols); tsi_result result = TSI_OK; - grpc_ssl_channel_security_connector *c; - const char *pem_root_certs; - char *port; + grpc_ssl_channel_security_connector* c; + const char* pem_root_certs; + char* port; bool has_key_cert_pair; - if (config == NULL || target_name == NULL) { + if (config == nullptr || target_name == nullptr) { gpr_log(GPR_ERROR, "An ssl channel needs a config and a target name."); goto error; } - if (config->pem_root_certs == NULL) { + if (config->pem_root_certs == nullptr) { pem_root_certs = grpc_get_default_ssl_roots(); - if (pem_root_certs == NULL) { + if (pem_root_certs == nullptr) { gpr_log(GPR_ERROR, "Could not get default pem root certs."); goto error; } @@ -1017,7 +1017,7 @@ grpc_security_status grpc_ssl_channel_security_connector_create( pem_root_certs = config->pem_root_certs; } - c = (grpc_ssl_channel_security_connector *)gpr_zalloc( + c = (grpc_ssl_channel_security_connector*)gpr_zalloc( sizeof(grpc_ssl_channel_security_connector)); gpr_ref_init(&c->base.base.refcount, 1); @@ -1031,38 +1031,38 @@ grpc_security_status grpc_ssl_channel_security_connector_create( c->base.add_handshakers = ssl_channel_add_handshakers; gpr_split_host_port(target_name, &c->target_name, &port); gpr_free(port); - if (overridden_target_name != NULL) { + if (overridden_target_name != nullptr) { c->overridden_target_name = gpr_strdup(overridden_target_name); } - has_key_cert_pair = config->pem_key_cert_pair != NULL && - config->pem_key_cert_pair->private_key != NULL && - config->pem_key_cert_pair->cert_chain != NULL; + has_key_cert_pair = config->pem_key_cert_pair != nullptr && + config->pem_key_cert_pair->private_key != nullptr && + config->pem_key_cert_pair->cert_chain != nullptr; result = tsi_create_ssl_client_handshaker_factory( - has_key_cert_pair ? config->pem_key_cert_pair : NULL, pem_root_certs, + has_key_cert_pair ? config->pem_key_cert_pair : nullptr, pem_root_certs, ssl_cipher_suites(), alpn_protocol_strings, (uint16_t)num_alpn_protocols, &c->client_handshaker_factory); if (result != TSI_OK) { gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.", tsi_result_to_string(result)); ssl_channel_destroy(exec_ctx, &c->base.base); - *sc = NULL; + *sc = nullptr; goto error; } *sc = &c->base; - gpr_free((void *)alpn_protocol_strings); + gpr_free((void*)alpn_protocol_strings); return GRPC_SECURITY_OK; error: - gpr_free((void *)alpn_protocol_strings); + gpr_free((void*)alpn_protocol_strings); return GRPC_SECURITY_ERROR; } -static grpc_ssl_server_security_connector * +static grpc_ssl_server_security_connector* grpc_ssl_server_security_connector_initialize( - grpc_server_credentials *server_creds) { - grpc_ssl_server_security_connector *c = - (grpc_ssl_server_security_connector *)gpr_zalloc( + grpc_server_credentials* server_creds) { + grpc_ssl_server_security_connector* c = + (grpc_ssl_server_security_connector*)gpr_zalloc( sizeof(grpc_ssl_server_security_connector)); gpr_ref_init(&c->base.base.refcount, 1); c->base.base.url_scheme = GRPC_SSL_URL_SCHEME; @@ -1073,17 +1073,17 @@ grpc_ssl_server_security_connector_initialize( } grpc_security_status grpc_ssl_server_security_connector_create( - grpc_exec_ctx *exec_ctx, grpc_server_credentials *gsc, - grpc_server_security_connector **sc) { + grpc_exec_ctx* exec_ctx, grpc_server_credentials* gsc, + grpc_server_security_connector** sc) { tsi_result result = TSI_OK; - grpc_ssl_server_credentials *server_credentials = - (grpc_ssl_server_credentials *)gsc; + grpc_ssl_server_credentials* server_credentials = + (grpc_ssl_server_credentials*)gsc; grpc_security_status retval = GRPC_SECURITY_OK; - GPR_ASSERT(server_credentials != NULL); - GPR_ASSERT(sc != NULL); + GPR_ASSERT(server_credentials != nullptr); + GPR_ASSERT(sc != nullptr); - grpc_ssl_server_security_connector *c = + grpc_ssl_server_security_connector* c = grpc_ssl_server_security_connector_initialize(gsc); if (server_connector_has_cert_config_fetcher(c)) { // Load initial credentials from certificate_config_fetcher: @@ -1093,7 +1093,7 @@ grpc_security_status grpc_ssl_server_security_connector_create( } } else { size_t num_alpn_protocols = 0; - const char **alpn_protocol_strings = + const char** alpn_protocol_strings = fill_alpn_protocol_strings(&num_alpn_protocols); result = tsi_create_ssl_server_handshaker_factory_ex( server_credentials->config.pem_key_cert_pairs, @@ -1103,7 +1103,7 @@ grpc_security_status grpc_ssl_server_security_connector_create( server_credentials->config.client_certificate_request), ssl_cipher_suites(), alpn_protocol_strings, (uint16_t)num_alpn_protocols, &c->server_handshaker_factory); - gpr_free((void *)alpn_protocol_strings); + gpr_free((void*)alpn_protocol_strings); if (result != TSI_OK) { gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.", tsi_result_to_string(result)); @@ -1114,8 +1114,8 @@ grpc_security_status grpc_ssl_server_security_connector_create( if (retval == GRPC_SECURITY_OK) { *sc = &c->base; } else { - if (c != NULL) ssl_server_destroy(exec_ctx, &c->base.base); - if (sc != NULL) *sc = NULL; + if (c != nullptr) ssl_server_destroy(exec_ctx, &c->base.base); + if (sc != nullptr) *sc = nullptr; } return retval; } diff --git a/src/core/lib/security/transport/security_connector.h b/src/core/lib/security/transport/security_connector.h index 54a563bb2c9..03daba3a180 100644 --- a/src/core/lib/security/transport/security_connector.h +++ b/src/core/lib/security/transport/security_connector.h @@ -29,13 +29,7 @@ #include "src/core/tsi/ssl_transport_security.h" #include "src/core/tsi/transport_security_interface.h" -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef NDEBUG -extern grpc_tracer_flag grpc_trace_security_connector_refcount; -#endif +extern grpc_core::DebugOnlyTraceFlag grpc_trace_security_connector_refcount; /* --- status enum. --- */ @@ -56,17 +50,17 @@ typedef struct grpc_security_connector grpc_security_connector; #define GRPC_ARG_SECURITY_CONNECTOR "grpc.security_connector" typedef struct { - void (*destroy)(grpc_exec_ctx *exec_ctx, grpc_security_connector *sc); - void (*check_peer)(grpc_exec_ctx *exec_ctx, grpc_security_connector *sc, - tsi_peer peer, grpc_auth_context **auth_context, - grpc_closure *on_peer_checked); - int (*cmp)(grpc_security_connector *sc, grpc_security_connector *other); + void (*destroy)(grpc_exec_ctx* exec_ctx, grpc_security_connector* sc); + void (*check_peer)(grpc_exec_ctx* exec_ctx, grpc_security_connector* sc, + tsi_peer peer, grpc_auth_context** auth_context, + grpc_closure* on_peer_checked); + int (*cmp)(grpc_security_connector* sc, grpc_security_connector* other); } grpc_security_connector_vtable; struct grpc_security_connector { - const grpc_security_connector_vtable *vtable; + const grpc_security_connector_vtable* vtable; gpr_refcount refcount; - const char *url_scheme; + const char* url_scheme; }; /* Refcounting. */ @@ -75,44 +69,44 @@ struct grpc_security_connector { grpc_security_connector_ref((p), __FILE__, __LINE__, (r)) #define GRPC_SECURITY_CONNECTOR_UNREF(exec_ctx, p, r) \ grpc_security_connector_unref((exec_ctx), (p), __FILE__, __LINE__, (r)) -grpc_security_connector *grpc_security_connector_ref( - grpc_security_connector *policy, const char *file, int line, - const char *reason); -void grpc_security_connector_unref(grpc_exec_ctx *exec_ctx, - grpc_security_connector *policy, - const char *file, int line, - const char *reason); +grpc_security_connector* grpc_security_connector_ref( + grpc_security_connector* policy, const char* file, int line, + const char* reason); +void grpc_security_connector_unref(grpc_exec_ctx* exec_ctx, + grpc_security_connector* policy, + const char* file, int line, + const char* reason); #else #define GRPC_SECURITY_CONNECTOR_REF(p, r) grpc_security_connector_ref((p)) #define GRPC_SECURITY_CONNECTOR_UNREF(exec_ctx, p, r) \ grpc_security_connector_unref((exec_ctx), (p)) -grpc_security_connector *grpc_security_connector_ref( - grpc_security_connector *policy); -void grpc_security_connector_unref(grpc_exec_ctx *exec_ctx, - grpc_security_connector *policy); +grpc_security_connector* grpc_security_connector_ref( + grpc_security_connector* policy); +void grpc_security_connector_unref(grpc_exec_ctx* exec_ctx, + grpc_security_connector* policy); #endif /* Check the peer. Callee takes ownership of the peer object. When done, sets *auth_context and invokes on_peer_checked. */ -void grpc_security_connector_check_peer(grpc_exec_ctx *exec_ctx, - grpc_security_connector *sc, +void grpc_security_connector_check_peer(grpc_exec_ctx* exec_ctx, + grpc_security_connector* sc, tsi_peer peer, - grpc_auth_context **auth_context, - grpc_closure *on_peer_checked); + grpc_auth_context** auth_context, + grpc_closure* on_peer_checked); /* Compares two security connectors. */ -int grpc_security_connector_cmp(grpc_security_connector *sc, - grpc_security_connector *other); +int grpc_security_connector_cmp(grpc_security_connector* sc, + grpc_security_connector* other); /* Util to encapsulate the connector in a channel arg. */ -grpc_arg grpc_security_connector_to_arg(grpc_security_connector *sc); +grpc_arg grpc_security_connector_to_arg(grpc_security_connector* sc); /* Util to get the connector from a channel arg. */ -grpc_security_connector *grpc_security_connector_from_arg(const grpc_arg *arg); +grpc_security_connector* grpc_security_connector_from_arg(const grpc_arg* arg); /* Util to find the connector from channel args. */ -grpc_security_connector *grpc_security_connector_find_in_args( - const grpc_channel_args *args); +grpc_security_connector* grpc_security_connector_find_in_args( + const grpc_channel_args* args); /* --- channel_security_connector object. --- @@ -123,46 +117,46 @@ typedef struct grpc_channel_security_connector grpc_channel_security_connector; struct grpc_channel_security_connector { grpc_security_connector base; - grpc_channel_credentials *channel_creds; - grpc_call_credentials *request_metadata_creds; - bool (*check_call_host)(grpc_exec_ctx *exec_ctx, - grpc_channel_security_connector *sc, const char *host, - grpc_auth_context *auth_context, - grpc_closure *on_call_host_checked, - grpc_error **error); - void (*cancel_check_call_host)(grpc_exec_ctx *exec_ctx, - grpc_channel_security_connector *sc, - grpc_closure *on_call_host_checked, - grpc_error *error); - void (*add_handshakers)(grpc_exec_ctx *exec_ctx, - grpc_channel_security_connector *sc, - grpc_handshake_manager *handshake_mgr); + grpc_channel_credentials* channel_creds; + grpc_call_credentials* request_metadata_creds; + bool (*check_call_host)(grpc_exec_ctx* exec_ctx, + grpc_channel_security_connector* sc, const char* host, + grpc_auth_context* auth_context, + grpc_closure* on_call_host_checked, + grpc_error** error); + void (*cancel_check_call_host)(grpc_exec_ctx* exec_ctx, + grpc_channel_security_connector* sc, + grpc_closure* on_call_host_checked, + grpc_error* error); + void (*add_handshakers)(grpc_exec_ctx* exec_ctx, + grpc_channel_security_connector* sc, + grpc_handshake_manager* handshake_mgr); }; /// A helper function for use in grpc_security_connector_cmp() implementations. -int grpc_channel_security_connector_cmp(grpc_channel_security_connector *sc1, - grpc_channel_security_connector *sc2); +int grpc_channel_security_connector_cmp(grpc_channel_security_connector* sc1, + grpc_channel_security_connector* sc2); /// Checks that the host that will be set for a call is acceptable. /// Returns true if completed synchronously, in which case \a error will /// be set to indicate the result. Otherwise, \a on_call_host_checked /// will be invoked when complete. bool grpc_channel_security_connector_check_call_host( - grpc_exec_ctx *exec_ctx, grpc_channel_security_connector *sc, - const char *host, grpc_auth_context *auth_context, - grpc_closure *on_call_host_checked, grpc_error **error); + grpc_exec_ctx* exec_ctx, grpc_channel_security_connector* sc, + const char* host, grpc_auth_context* auth_context, + grpc_closure* on_call_host_checked, grpc_error** error); /// Cancels a pending asychronous call to /// grpc_channel_security_connector_check_call_host() with /// \a on_call_host_checked as its callback. void grpc_channel_security_connector_cancel_check_call_host( - grpc_exec_ctx *exec_ctx, grpc_channel_security_connector *sc, - grpc_closure *on_call_host_checked, grpc_error *error); + grpc_exec_ctx* exec_ctx, grpc_channel_security_connector* sc, + grpc_closure* on_call_host_checked, grpc_error* error); /* Registers handshakers with \a handshake_mgr. */ void grpc_channel_security_connector_add_handshakers( - grpc_exec_ctx *exec_ctx, grpc_channel_security_connector *connector, - grpc_handshake_manager *handshake_mgr); + grpc_exec_ctx* exec_ctx, grpc_channel_security_connector* connector, + grpc_handshake_manager* handshake_mgr); /* --- server_security_connector object. --- @@ -173,39 +167,39 @@ typedef struct grpc_server_security_connector grpc_server_security_connector; struct grpc_server_security_connector { grpc_security_connector base; - grpc_server_credentials *server_creds; - void (*add_handshakers)(grpc_exec_ctx *exec_ctx, - grpc_server_security_connector *sc, - grpc_handshake_manager *handshake_mgr); + grpc_server_credentials* server_creds; + void (*add_handshakers)(grpc_exec_ctx* exec_ctx, + grpc_server_security_connector* sc, + grpc_handshake_manager* handshake_mgr); }; /// A helper function for use in grpc_security_connector_cmp() implementations. -int grpc_server_security_connector_cmp(grpc_server_security_connector *sc1, - grpc_server_security_connector *sc2); +int grpc_server_security_connector_cmp(grpc_server_security_connector* sc1, + grpc_server_security_connector* sc2); void grpc_server_security_connector_add_handshakers( - grpc_exec_ctx *exec_ctx, grpc_server_security_connector *sc, - grpc_handshake_manager *handshake_mgr); + grpc_exec_ctx* exec_ctx, grpc_server_security_connector* sc, + grpc_handshake_manager* handshake_mgr); /* --- Creation security connectors. --- */ /* For TESTING ONLY! Creates a fake connector that emulates real channel security. */ -grpc_channel_security_connector *grpc_fake_channel_security_connector_create( - grpc_channel_credentials *channel_creds, - grpc_call_credentials *request_metadata_creds, const char *target, - const grpc_channel_args *args); +grpc_channel_security_connector* grpc_fake_channel_security_connector_create( + grpc_channel_credentials* channel_creds, + grpc_call_credentials* request_metadata_creds, const char* target, + const grpc_channel_args* args); /* For TESTING ONLY! Creates a fake connector that emulates real server security. */ -grpc_server_security_connector *grpc_fake_server_security_connector_create( - grpc_server_credentials *server_creds); +grpc_server_security_connector* grpc_fake_server_security_connector_create( + grpc_server_credentials* server_creds); /* Config for ssl clients. */ typedef struct { - tsi_ssl_pem_key_cert_pair *pem_key_cert_pair; - char *pem_root_certs; + tsi_ssl_pem_key_cert_pair* pem_key_cert_pair; + char* pem_root_certs; } grpc_ssl_config; /* Creates an SSL channel_security_connector. @@ -222,22 +216,22 @@ typedef struct { specific error code otherwise. */ grpc_security_status grpc_ssl_channel_security_connector_create( - grpc_exec_ctx *exec_ctx, grpc_channel_credentials *channel_creds, - grpc_call_credentials *request_metadata_creds, - const grpc_ssl_config *config, const char *target_name, - const char *overridden_target_name, grpc_channel_security_connector **sc); + grpc_exec_ctx* exec_ctx, grpc_channel_credentials* channel_creds, + grpc_call_credentials* request_metadata_creds, + const grpc_ssl_config* config, const char* target_name, + const char* overridden_target_name, grpc_channel_security_connector** sc); /* Gets the default ssl roots. Returns NULL if not found. */ -const char *grpc_get_default_ssl_roots(void); +const char* grpc_get_default_ssl_roots(void); /* Exposed for TESTING ONLY!. */ grpc_slice grpc_get_default_ssl_roots_for_testing(void); /* Config for ssl servers. */ typedef struct { - tsi_ssl_pem_key_cert_pair *pem_key_cert_pairs; + tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs; size_t num_key_cert_pairs; - char *pem_root_certs; + char* pem_root_certs; grpc_ssl_client_certificate_request_type client_certificate_request; } grpc_ssl_server_config; @@ -248,21 +242,17 @@ typedef struct { specific error code otherwise. */ grpc_security_status grpc_ssl_server_security_connector_create( - grpc_exec_ctx *exec_ctx, grpc_server_credentials *server_credentials, - grpc_server_security_connector **sc); + grpc_exec_ctx* exec_ctx, grpc_server_credentials* server_credentials, + grpc_server_security_connector** sc); /* Util. */ -const tsi_peer_property *tsi_peer_get_property_by_name(const tsi_peer *peer, - const char *name); +const tsi_peer_property* tsi_peer_get_property_by_name(const tsi_peer* peer, + const char* name); /* Exposed for testing only. */ -grpc_auth_context *tsi_ssl_peer_to_auth_context(const tsi_peer *peer); +grpc_auth_context* tsi_ssl_peer_to_auth_context(const tsi_peer* peer); tsi_peer tsi_shallow_peer_from_ssl_auth_context( - const grpc_auth_context *auth_context); -void tsi_shallow_peer_destruct(tsi_peer *peer); - -#ifdef __cplusplus -} -#endif + const grpc_auth_context* auth_context); +void tsi_shallow_peer_destruct(tsi_peer* peer); #endif /* GRPC_CORE_LIB_SECURITY_TRANSPORT_SECURITY_CONNECTOR_H */ diff --git a/src/core/lib/security/transport/security_handshaker.cc b/src/core/lib/security/transport/security_handshaker.cc index 3d196056177..7067b70cb6a 100644 --- a/src/core/lib/security/transport/security_handshaker.cc +++ b/src/core/lib/security/transport/security_handshaker.cc @@ -40,41 +40,60 @@ typedef struct { grpc_handshaker base; // State set at creation time. - tsi_handshaker *handshaker; - grpc_security_connector *connector; + tsi_handshaker* handshaker; + grpc_security_connector* connector; gpr_mu mu; gpr_refcount refs; bool shutdown; // Endpoint and read buffer to destroy after a shutdown. - grpc_endpoint *endpoint_to_destroy; - grpc_slice_buffer *read_buffer_to_destroy; + grpc_endpoint* endpoint_to_destroy; + grpc_slice_buffer* read_buffer_to_destroy; // State saved while performing the handshake. - grpc_handshaker_args *args; - grpc_closure *on_handshake_done; + grpc_handshaker_args* args; + grpc_closure* on_handshake_done; - unsigned char *handshake_buffer; + unsigned char* handshake_buffer; size_t handshake_buffer_size; grpc_slice_buffer outgoing; grpc_closure on_handshake_data_sent_to_peer; grpc_closure on_handshake_data_received_from_peer; grpc_closure on_peer_checked; - grpc_auth_context *auth_context; - tsi_handshaker_result *handshaker_result; + grpc_auth_context* auth_context; + tsi_handshaker_result* handshaker_result; } security_handshaker; -static void security_handshaker_unref(grpc_exec_ctx *exec_ctx, - security_handshaker *h) { +static size_t move_read_buffer_into_handshake_buffer(grpc_exec_ctx* exec_ctx, + security_handshaker* h) { + size_t bytes_in_read_buffer = h->args->read_buffer->length; + if (h->handshake_buffer_size < bytes_in_read_buffer) { + h->handshake_buffer = + (uint8_t*)gpr_realloc(h->handshake_buffer, bytes_in_read_buffer); + h->handshake_buffer_size = bytes_in_read_buffer; + } + size_t offset = 0; + while (h->args->read_buffer->count > 0) { + grpc_slice next_slice = grpc_slice_buffer_take_first(h->args->read_buffer); + memcpy(h->handshake_buffer + offset, GRPC_SLICE_START_PTR(next_slice), + GRPC_SLICE_LENGTH(next_slice)); + offset += GRPC_SLICE_LENGTH(next_slice); + grpc_slice_unref_internal(exec_ctx, next_slice); + } + return bytes_in_read_buffer; +} + +static void security_handshaker_unref(grpc_exec_ctx* exec_ctx, + security_handshaker* h) { if (gpr_unref(&h->refs)) { gpr_mu_destroy(&h->mu); tsi_handshaker_destroy(h->handshaker); tsi_handshaker_result_destroy(h->handshaker_result); - if (h->endpoint_to_destroy != NULL) { + if (h->endpoint_to_destroy != nullptr) { grpc_endpoint_destroy(exec_ctx, h->endpoint_to_destroy); } - if (h->read_buffer_to_destroy != NULL) { + if (h->read_buffer_to_destroy != nullptr) { grpc_slice_buffer_destroy_internal(exec_ctx, h->read_buffer_to_destroy); gpr_free(h->read_buffer_to_destroy); } @@ -88,27 +107,27 @@ static void security_handshaker_unref(grpc_exec_ctx *exec_ctx, // Set args fields to NULL, saving the endpoint and read buffer for // later destruction. -static void cleanup_args_for_failure_locked(grpc_exec_ctx *exec_ctx, - security_handshaker *h) { +static void cleanup_args_for_failure_locked(grpc_exec_ctx* exec_ctx, + security_handshaker* h) { h->endpoint_to_destroy = h->args->endpoint; - h->args->endpoint = NULL; + h->args->endpoint = nullptr; h->read_buffer_to_destroy = h->args->read_buffer; - h->args->read_buffer = NULL; + h->args->read_buffer = nullptr; grpc_channel_args_destroy(exec_ctx, h->args->args); - h->args->args = NULL; + h->args->args = nullptr; } // If the handshake failed or we're shutting down, clean up and invoke the // callback with the error. -static void security_handshake_failed_locked(grpc_exec_ctx *exec_ctx, - security_handshaker *h, - grpc_error *error) { +static void security_handshake_failed_locked(grpc_exec_ctx* exec_ctx, + security_handshaker* h, + grpc_error* error) { if (error == GRPC_ERROR_NONE) { // If we were shut down after the handshake succeeded but before an // endpoint callback was invoked, we need to generate our own error. error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshaker shutdown"); } - const char *msg = grpc_error_string(error); + const char* msg = grpc_error_string(error); gpr_log(GPR_DEBUG, "Security handshake failed: %s", msg); if (!h->shutdown) { @@ -128,16 +147,16 @@ static void security_handshake_failed_locked(grpc_exec_ctx *exec_ctx, GRPC_CLOSURE_SCHED(exec_ctx, h->on_handshake_done, error); } -static void on_peer_checked_inner(grpc_exec_ctx *exec_ctx, - security_handshaker *h, grpc_error *error) { +static void on_peer_checked_inner(grpc_exec_ctx* exec_ctx, + security_handshaker* h, grpc_error* error) { if (error != GRPC_ERROR_NONE || h->shutdown) { security_handshake_failed_locked(exec_ctx, h, GRPC_ERROR_REF(error)); return; } // Create zero-copy frame protector, if implemented. - tsi_zero_copy_grpc_protector *zero_copy_protector = NULL; + tsi_zero_copy_grpc_protector* zero_copy_protector = nullptr; tsi_result result = tsi_handshaker_result_create_zero_copy_grpc_protector( - exec_ctx, h->handshaker_result, NULL, &zero_copy_protector); + exec_ctx, h->handshaker_result, nullptr, &zero_copy_protector); if (result != TSI_OK && result != TSI_UNIMPLEMENTED) { error = grpc_set_tsi_error_result( GRPC_ERROR_CREATE_FROM_STATIC_STRING( @@ -147,10 +166,10 @@ static void on_peer_checked_inner(grpc_exec_ctx *exec_ctx, return; } // Create frame protector if zero-copy frame protector is NULL. - tsi_frame_protector *protector = NULL; - if (zero_copy_protector == NULL) { + tsi_frame_protector* protector = nullptr; + if (zero_copy_protector == nullptr) { result = tsi_handshaker_result_create_frame_protector(h->handshaker_result, - NULL, &protector); + nullptr, &protector); if (result != TSI_OK) { error = grpc_set_tsi_error_result(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Frame protector creation failed"), @@ -160,28 +179,26 @@ static void on_peer_checked_inner(grpc_exec_ctx *exec_ctx, } } // Get unused bytes. - const unsigned char *unused_bytes = NULL; + const unsigned char* unused_bytes = nullptr; size_t unused_bytes_size = 0; result = tsi_handshaker_result_get_unused_bytes( h->handshaker_result, &unused_bytes, &unused_bytes_size); // Create secure endpoint. if (unused_bytes_size > 0) { grpc_slice slice = - grpc_slice_from_copied_buffer((char *)unused_bytes, unused_bytes_size); + grpc_slice_from_copied_buffer((char*)unused_bytes, unused_bytes_size); h->args->endpoint = grpc_secure_endpoint_create( protector, zero_copy_protector, h->args->endpoint, &slice, 1); grpc_slice_unref_internal(exec_ctx, slice); } else { h->args->endpoint = grpc_secure_endpoint_create( - protector, zero_copy_protector, h->args->endpoint, NULL, 0); + protector, zero_copy_protector, h->args->endpoint, nullptr, 0); } tsi_handshaker_result_destroy(h->handshaker_result); - h->handshaker_result = NULL; - // Clear out the read buffer before it gets passed to the transport. - grpc_slice_buffer_reset_and_unref_internal(exec_ctx, h->args->read_buffer); + h->handshaker_result = nullptr; // Add auth context to channel args. grpc_arg auth_context_arg = grpc_auth_context_to_arg(h->auth_context); - grpc_channel_args *tmp_args = h->args->args; + grpc_channel_args* tmp_args = h->args->args; h->args->args = grpc_channel_args_copy_and_add(tmp_args, &auth_context_arg, 1); grpc_channel_args_destroy(exec_ctx, tmp_args); @@ -192,17 +209,17 @@ static void on_peer_checked_inner(grpc_exec_ctx *exec_ctx, h->shutdown = true; } -static void on_peer_checked(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - security_handshaker *h = (security_handshaker *)arg; +static void on_peer_checked(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + security_handshaker* h = (security_handshaker*)arg; gpr_mu_lock(&h->mu); on_peer_checked_inner(exec_ctx, h, error); gpr_mu_unlock(&h->mu); security_handshaker_unref(exec_ctx, h); } -static grpc_error *check_peer_locked(grpc_exec_ctx *exec_ctx, - security_handshaker *h) { +static grpc_error* check_peer_locked(grpc_exec_ctx* exec_ctx, + security_handshaker* h) { tsi_peer peer; tsi_result result = tsi_handshaker_result_extract_peer(h->handshaker_result, &peer); @@ -215,11 +232,11 @@ static grpc_error *check_peer_locked(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static grpc_error *on_handshake_next_done_locked( - grpc_exec_ctx *exec_ctx, security_handshaker *h, tsi_result result, - const unsigned char *bytes_to_send, size_t bytes_to_send_size, - tsi_handshaker_result *handshaker_result) { - grpc_error *error = GRPC_ERROR_NONE; +static grpc_error* on_handshake_next_done_locked( + grpc_exec_ctx* exec_ctx, security_handshaker* h, tsi_result result, + const unsigned char* bytes_to_send, size_t bytes_to_send_size, + tsi_handshaker_result* handshaker_result) { + grpc_error* error = GRPC_ERROR_NONE; // Read more if we need to. if (result == TSI_INCOMPLETE_DATA) { GPR_ASSERT(bytes_to_send_size == 0); @@ -232,19 +249,19 @@ static grpc_error *on_handshake_next_done_locked( GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshake failed"), result); } // Update handshaker result. - if (handshaker_result != NULL) { - GPR_ASSERT(h->handshaker_result == NULL); + if (handshaker_result != nullptr) { + GPR_ASSERT(h->handshaker_result == nullptr); h->handshaker_result = handshaker_result; } if (bytes_to_send_size > 0) { // Send data to peer, if needed. grpc_slice to_send = grpc_slice_from_copied_buffer( - (const char *)bytes_to_send, bytes_to_send_size); + (const char*)bytes_to_send, bytes_to_send_size); grpc_slice_buffer_reset_and_unref_internal(exec_ctx, &h->outgoing); grpc_slice_buffer_add(&h->outgoing, to_send); grpc_endpoint_write(exec_ctx, h->args->endpoint, &h->outgoing, &h->on_handshake_data_sent_to_peer); - } else if (handshaker_result == NULL) { + } else if (handshaker_result == nullptr) { // There is nothing to send, but need to read from peer. grpc_endpoint_read(exec_ctx, h->args->endpoint, h->args->read_buffer, &h->on_handshake_data_received_from_peer); @@ -256,14 +273,14 @@ static grpc_error *on_handshake_next_done_locked( } static void on_handshake_next_done_grpc_wrapper( - tsi_result result, void *user_data, const unsigned char *bytes_to_send, - size_t bytes_to_send_size, tsi_handshaker_result *handshaker_result) { - security_handshaker *h = (security_handshaker *)user_data; + tsi_result result, void* user_data, const unsigned char* bytes_to_send, + size_t bytes_to_send_size, tsi_handshaker_result* handshaker_result) { + security_handshaker* h = (security_handshaker*)user_data; // This callback will be invoked by TSI in a non-grpc thread, so it's // safe to create our own exec_ctx here. grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; gpr_mu_lock(&h->mu); - grpc_error *error = + grpc_error* error = on_handshake_next_done_locked(&exec_ctx, h, result, bytes_to_send, bytes_to_send_size, handshaker_result); if (error != GRPC_ERROR_NONE) { @@ -276,13 +293,13 @@ static void on_handshake_next_done_grpc_wrapper( grpc_exec_ctx_finish(&exec_ctx); } -static grpc_error *do_handshaker_next_locked( - grpc_exec_ctx *exec_ctx, security_handshaker *h, - const unsigned char *bytes_received, size_t bytes_received_size) { +static grpc_error* do_handshaker_next_locked( + grpc_exec_ctx* exec_ctx, security_handshaker* h, + const unsigned char* bytes_received, size_t bytes_received_size) { // Invoke TSI handshaker. - const unsigned char *bytes_to_send = NULL; + const unsigned char* bytes_to_send = nullptr; size_t bytes_to_send_size = 0; - tsi_handshaker_result *handshaker_result = NULL; + tsi_handshaker_result* handshaker_result = nullptr; tsi_result result = tsi_handshaker_next( h->handshaker, bytes_received, bytes_received_size, &bytes_to_send, &bytes_to_send_size, &handshaker_result, @@ -298,36 +315,22 @@ static grpc_error *do_handshaker_next_locked( bytes_to_send_size, handshaker_result); } -static void on_handshake_data_received_from_peer(grpc_exec_ctx *exec_ctx, - void *arg, grpc_error *error) { - security_handshaker *h = (security_handshaker *)arg; +static void on_handshake_data_received_from_peer(grpc_exec_ctx* exec_ctx, + void* arg, grpc_error* error) { + security_handshaker* h = (security_handshaker*)arg; gpr_mu_lock(&h->mu); if (error != GRPC_ERROR_NONE || h->shutdown) { security_handshake_failed_locked( - exec_ctx, h, GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( - "Handshake read failed", &error, 1)); + exec_ctx, h, + GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( + "Handshake read failed", &error, 1)); gpr_mu_unlock(&h->mu); security_handshaker_unref(exec_ctx, h); return; } // Copy all slices received. - size_t i; - size_t bytes_received_size = 0; - for (i = 0; i < h->args->read_buffer->count; i++) { - bytes_received_size += GRPC_SLICE_LENGTH(h->args->read_buffer->slices[i]); - } - if (bytes_received_size > h->handshake_buffer_size) { - h->handshake_buffer = - (uint8_t *)gpr_realloc(h->handshake_buffer, bytes_received_size); - h->handshake_buffer_size = bytes_received_size; - } - size_t offset = 0; - for (i = 0; i < h->args->read_buffer->count; i++) { - size_t slice_size = GPR_SLICE_LENGTH(h->args->read_buffer->slices[i]); - memcpy(h->handshake_buffer + offset, - GRPC_SLICE_START_PTR(h->args->read_buffer->slices[i]), slice_size); - offset += slice_size; - } + size_t bytes_received_size = + move_read_buffer_into_handshake_buffer(exec_ctx, h); // Call TSI handshaker. error = do_handshaker_next_locked(exec_ctx, h, h->handshake_buffer, bytes_received_size); @@ -341,20 +344,21 @@ static void on_handshake_data_received_from_peer(grpc_exec_ctx *exec_ctx, } } -static void on_handshake_data_sent_to_peer(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - security_handshaker *h = (security_handshaker *)arg; +static void on_handshake_data_sent_to_peer(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + security_handshaker* h = (security_handshaker*)arg; gpr_mu_lock(&h->mu); if (error != GRPC_ERROR_NONE || h->shutdown) { security_handshake_failed_locked( - exec_ctx, h, GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( - "Handshake write failed", &error, 1)); + exec_ctx, h, + GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( + "Handshake write failed", &error, 1)); gpr_mu_unlock(&h->mu); security_handshaker_unref(exec_ctx, h); return; } // We may be done. - if (h->handshaker_result == NULL) { + if (h->handshaker_result == nullptr) { grpc_endpoint_read(exec_ctx, h->args->endpoint, h->args->read_buffer, &h->on_handshake_data_received_from_peer); } else { @@ -373,16 +377,16 @@ static void on_handshake_data_sent_to_peer(grpc_exec_ctx *exec_ctx, void *arg, // public handshaker API // -static void security_handshaker_destroy(grpc_exec_ctx *exec_ctx, - grpc_handshaker *handshaker) { - security_handshaker *h = (security_handshaker *)handshaker; +static void security_handshaker_destroy(grpc_exec_ctx* exec_ctx, + grpc_handshaker* handshaker) { + security_handshaker* h = (security_handshaker*)handshaker; security_handshaker_unref(exec_ctx, h); } -static void security_handshaker_shutdown(grpc_exec_ctx *exec_ctx, - grpc_handshaker *handshaker, - grpc_error *why) { - security_handshaker *h = (security_handshaker *)handshaker; +static void security_handshaker_shutdown(grpc_exec_ctx* exec_ctx, + grpc_handshaker* handshaker, + grpc_error* why) { + security_handshaker* h = (security_handshaker*)handshaker; gpr_mu_lock(&h->mu); if (!h->shutdown) { h->shutdown = true; @@ -393,17 +397,20 @@ static void security_handshaker_shutdown(grpc_exec_ctx *exec_ctx, GRPC_ERROR_UNREF(why); } -static void security_handshaker_do_handshake(grpc_exec_ctx *exec_ctx, - grpc_handshaker *handshaker, - grpc_tcp_server_acceptor *acceptor, - grpc_closure *on_handshake_done, - grpc_handshaker_args *args) { - security_handshaker *h = (security_handshaker *)handshaker; +static void security_handshaker_do_handshake(grpc_exec_ctx* exec_ctx, + grpc_handshaker* handshaker, + grpc_tcp_server_acceptor* acceptor, + grpc_closure* on_handshake_done, + grpc_handshaker_args* args) { + security_handshaker* h = (security_handshaker*)handshaker; gpr_mu_lock(&h->mu); h->args = args; h->on_handshake_done = on_handshake_done; gpr_ref(&h->refs); - grpc_error *error = do_handshaker_next_locked(exec_ctx, h, NULL, 0); + size_t bytes_received_size = + move_read_buffer_into_handshake_buffer(exec_ctx, h); + grpc_error* error = do_handshaker_next_locked( + exec_ctx, h, h->handshake_buffer, bytes_received_size); if (error != GRPC_ERROR_NONE) { security_handshake_failed_locked(exec_ctx, h, error); gpr_mu_unlock(&h->mu); @@ -417,18 +424,18 @@ static const grpc_handshaker_vtable security_handshaker_vtable = { security_handshaker_destroy, security_handshaker_shutdown, security_handshaker_do_handshake}; -static grpc_handshaker *security_handshaker_create( - grpc_exec_ctx *exec_ctx, tsi_handshaker *handshaker, - grpc_security_connector *connector) { - security_handshaker *h = - (security_handshaker *)gpr_zalloc(sizeof(security_handshaker)); +static grpc_handshaker* security_handshaker_create( + grpc_exec_ctx* exec_ctx, tsi_handshaker* handshaker, + grpc_security_connector* connector) { + security_handshaker* h = + (security_handshaker*)gpr_zalloc(sizeof(security_handshaker)); grpc_handshaker_init(&security_handshaker_vtable, &h->base); h->handshaker = handshaker; h->connector = GRPC_SECURITY_CONNECTOR_REF(connector, "handshake"); gpr_mu_init(&h->mu); gpr_ref_init(&h->refs, 1); h->handshake_buffer_size = GRPC_INITIAL_HANDSHAKE_BUFFER_SIZE; - h->handshake_buffer = (uint8_t *)gpr_malloc(h->handshake_buffer_size); + h->handshake_buffer = (uint8_t*)gpr_malloc(h->handshake_buffer_size); GRPC_CLOSURE_INIT(&h->on_handshake_data_sent_to_peer, on_handshake_data_sent_to_peer, h, grpc_schedule_on_exec_ctx); @@ -445,22 +452,22 @@ static grpc_handshaker *security_handshaker_create( // fail_handshaker // -static void fail_handshaker_destroy(grpc_exec_ctx *exec_ctx, - grpc_handshaker *handshaker) { +static void fail_handshaker_destroy(grpc_exec_ctx* exec_ctx, + grpc_handshaker* handshaker) { gpr_free(handshaker); } -static void fail_handshaker_shutdown(grpc_exec_ctx *exec_ctx, - grpc_handshaker *handshaker, - grpc_error *why) { +static void fail_handshaker_shutdown(grpc_exec_ctx* exec_ctx, + grpc_handshaker* handshaker, + grpc_error* why) { GRPC_ERROR_UNREF(why); } -static void fail_handshaker_do_handshake(grpc_exec_ctx *exec_ctx, - grpc_handshaker *handshaker, - grpc_tcp_server_acceptor *acceptor, - grpc_closure *on_handshake_done, - grpc_handshaker_args *args) { +static void fail_handshaker_do_handshake(grpc_exec_ctx* exec_ctx, + grpc_handshaker* handshaker, + grpc_tcp_server_acceptor* acceptor, + grpc_closure* on_handshake_done, + grpc_handshaker_args* args) { GRPC_CLOSURE_SCHED(exec_ctx, on_handshake_done, GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Failed to create security handshaker")); @@ -470,8 +477,8 @@ static const grpc_handshaker_vtable fail_handshaker_vtable = { fail_handshaker_destroy, fail_handshaker_shutdown, fail_handshaker_do_handshake}; -static grpc_handshaker *fail_handshaker_create() { - grpc_handshaker *h = (grpc_handshaker *)gpr_malloc(sizeof(*h)); +static grpc_handshaker* fail_handshaker_create() { + grpc_handshaker* h = (grpc_handshaker*)gpr_malloc(sizeof(*h)); grpc_handshaker_init(&fail_handshaker_vtable, h); return h; } @@ -481,27 +488,27 @@ static grpc_handshaker *fail_handshaker_create() { // static void client_handshaker_factory_add_handshakers( - grpc_exec_ctx *exec_ctx, grpc_handshaker_factory *handshaker_factory, - const grpc_channel_args *args, grpc_handshake_manager *handshake_mgr) { - grpc_channel_security_connector *security_connector = - (grpc_channel_security_connector *)grpc_security_connector_find_in_args( + grpc_exec_ctx* exec_ctx, grpc_handshaker_factory* handshaker_factory, + const grpc_channel_args* args, grpc_handshake_manager* handshake_mgr) { + grpc_channel_security_connector* security_connector = + (grpc_channel_security_connector*)grpc_security_connector_find_in_args( args); grpc_channel_security_connector_add_handshakers(exec_ctx, security_connector, handshake_mgr); } static void server_handshaker_factory_add_handshakers( - grpc_exec_ctx *exec_ctx, grpc_handshaker_factory *hf, - const grpc_channel_args *args, grpc_handshake_manager *handshake_mgr) { - grpc_server_security_connector *security_connector = - (grpc_server_security_connector *)grpc_security_connector_find_in_args( + grpc_exec_ctx* exec_ctx, grpc_handshaker_factory* hf, + const grpc_channel_args* args, grpc_handshake_manager* handshake_mgr) { + grpc_server_security_connector* security_connector = + (grpc_server_security_connector*)grpc_security_connector_find_in_args( args); grpc_server_security_connector_add_handshakers(exec_ctx, security_connector, handshake_mgr); } static void handshaker_factory_destroy( - grpc_exec_ctx *exec_ctx, grpc_handshaker_factory *handshaker_factory) {} + grpc_exec_ctx* exec_ctx, grpc_handshaker_factory* handshaker_factory) {} static const grpc_handshaker_factory_vtable client_handshaker_factory_vtable = { client_handshaker_factory_add_handshakers, handshaker_factory_destroy}; @@ -519,12 +526,12 @@ static grpc_handshaker_factory server_handshaker_factory = { // exported functions // -grpc_handshaker *grpc_security_handshaker_create( - grpc_exec_ctx *exec_ctx, tsi_handshaker *handshaker, - grpc_security_connector *connector) { +grpc_handshaker* grpc_security_handshaker_create( + grpc_exec_ctx* exec_ctx, tsi_handshaker* handshaker, + grpc_security_connector* connector) { // If no TSI handshaker was created, return a handshaker that always fails. // Otherwise, return a real security handshaker. - if (handshaker == NULL) { + if (handshaker == nullptr) { return fail_handshaker_create(); } else { return security_handshaker_create(exec_ctx, handshaker, connector); diff --git a/src/core/lib/security/transport/security_handshaker.h b/src/core/lib/security/transport/security_handshaker.h index 178099bb945..6c3a0510cee 100644 --- a/src/core/lib/security/transport/security_handshaker.h +++ b/src/core/lib/security/transport/security_handshaker.h @@ -23,20 +23,12 @@ #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/security/transport/security_connector.h" -#ifdef __cplusplus -extern "C" { -#endif - /// Creates a security handshaker using \a handshaker. -grpc_handshaker *grpc_security_handshaker_create( - grpc_exec_ctx *exec_ctx, tsi_handshaker *handshaker, - grpc_security_connector *connector); +grpc_handshaker* grpc_security_handshaker_create( + grpc_exec_ctx* exec_ctx, tsi_handshaker* handshaker, + grpc_security_connector* connector); /// Registers security handshaker factories. void grpc_security_register_handshaker_factories(); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SECURITY_TRANSPORT_SECURITY_HANDSHAKER_H */ diff --git a/src/core/lib/security/transport/server_auth_filter.cc b/src/core/lib/security/transport/server_auth_filter.cc index f5e02f42fe0..9cf368acd01 100644 --- a/src/core/lib/security/transport/server_auth_filter.cc +++ b/src/core/lib/security/transport/server_auth_filter.cc @@ -33,37 +33,37 @@ typedef enum { } async_state; typedef struct call_data { - grpc_call_combiner *call_combiner; - grpc_call_stack *owning_call; - grpc_transport_stream_op_batch *recv_initial_metadata_batch; - grpc_closure *original_recv_initial_metadata_ready; + grpc_call_combiner* call_combiner; + grpc_call_stack* owning_call; + grpc_transport_stream_op_batch* recv_initial_metadata_batch; + grpc_closure* original_recv_initial_metadata_ready; grpc_closure recv_initial_metadata_ready; grpc_metadata_array md; - const grpc_metadata *consumed_md; + const grpc_metadata* consumed_md; size_t num_consumed_md; - grpc_auth_context *auth_context; + grpc_auth_context* auth_context; grpc_closure cancel_closure; gpr_atm state; // async_state } call_data; typedef struct channel_data { - grpc_auth_context *auth_context; - grpc_server_credentials *creds; + grpc_auth_context* auth_context; + grpc_server_credentials* creds; } channel_data; static grpc_metadata_array metadata_batch_to_md_array( - const grpc_metadata_batch *batch) { - grpc_linked_mdelem *l; + const grpc_metadata_batch* batch) { + grpc_linked_mdelem* l; grpc_metadata_array result; grpc_metadata_array_init(&result); - for (l = batch->list.head; l != NULL; l = l->next) { - grpc_metadata *usr_md = NULL; + for (l = batch->list.head; l != nullptr; l = l->next) { + grpc_metadata* usr_md = nullptr; grpc_mdelem md = l->md; grpc_slice key = GRPC_MDKEY(md); grpc_slice value = GRPC_MDVALUE(md); if (result.count == result.capacity) { result.capacity = GPR_MAX(result.capacity + 8, result.capacity * 2); - result.metadata = (grpc_metadata *)gpr_realloc( + result.metadata = (grpc_metadata*)gpr_realloc( result.metadata, result.capacity * sizeof(grpc_metadata)); } usr_md = &result.metadata[result.count++]; @@ -73,14 +73,14 @@ static grpc_metadata_array metadata_batch_to_md_array( return result; } -static grpc_filtered_mdelem remove_consumed_md(grpc_exec_ctx *exec_ctx, - void *user_data, +static grpc_filtered_mdelem remove_consumed_md(grpc_exec_ctx* exec_ctx, + void* user_data, grpc_mdelem md) { - grpc_call_element *elem = (grpc_call_element *)user_data; - call_data *calld = (call_data *)elem->call_data; + grpc_call_element* elem = (grpc_call_element*)user_data; + call_data* calld = (call_data*)elem->call_data; size_t i; for (i = 0; i < calld->num_consumed_md; i++) { - const grpc_metadata *consumed_md = &calld->consumed_md[i]; + const grpc_metadata* consumed_md = &calld->consumed_md[i]; if (grpc_slice_eq(GRPC_MDKEY(md), consumed_md->key) && grpc_slice_eq(GRPC_MDVALUE(md), consumed_md->value)) return GRPC_FILTERED_REMOVE(); @@ -88,17 +88,17 @@ static grpc_filtered_mdelem remove_consumed_md(grpc_exec_ctx *exec_ctx, return GRPC_FILTERED_MDELEM(md); } -static void on_md_processing_done_inner(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - const grpc_metadata *consumed_md, +static void on_md_processing_done_inner(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + const grpc_metadata* consumed_md, size_t num_consumed_md, - const grpc_metadata *response_md, + const grpc_metadata* response_md, size_t num_response_md, - grpc_error *error) { - call_data *calld = (call_data *)elem->call_data; - grpc_transport_stream_op_batch *batch = calld->recv_initial_metadata_batch; + grpc_error* error) { + call_data* calld = (call_data*)elem->call_data; + grpc_transport_stream_op_batch* batch = calld->recv_initial_metadata_batch; /* TODO(jboeuf): Implement support for response_md. */ - if (response_md != NULL && num_response_md > 0) { + if (response_md != nullptr && num_response_md > 0) { gpr_log(GPR_INFO, "response_md in auth metadata processing not supported for now. " "Ignoring..."); @@ -116,18 +116,18 @@ static void on_md_processing_done_inner(grpc_exec_ctx *exec_ctx, // Called from application code. static void on_md_processing_done( - void *user_data, const grpc_metadata *consumed_md, size_t num_consumed_md, - const grpc_metadata *response_md, size_t num_response_md, - grpc_status_code status, const char *error_details) { - grpc_call_element *elem = (grpc_call_element *)user_data; - call_data *calld = (call_data *)elem->call_data; + void* user_data, const grpc_metadata* consumed_md, size_t num_consumed_md, + const grpc_metadata* response_md, size_t num_response_md, + grpc_status_code status, const char* error_details) { + grpc_call_element* elem = (grpc_call_element*)user_data; + call_data* calld = (call_data*)elem->call_data; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; // If the call was not cancelled while we were in flight, process the result. if (gpr_atm_full_cas(&calld->state, (gpr_atm)STATE_INIT, (gpr_atm)STATE_DONE)) { - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; if (status != GRPC_STATUS_OK) { - if (error_details == NULL) { + if (error_details == nullptr) { error_details = "Authentication metadata processing failed."; } error = grpc_error_set_int( @@ -147,27 +147,27 @@ static void on_md_processing_done( grpc_exec_ctx_finish(&exec_ctx); } -static void cancel_call(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { - grpc_call_element *elem = (grpc_call_element *)arg; - call_data *calld = (call_data *)elem->call_data; +static void cancel_call(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { + grpc_call_element* elem = (grpc_call_element*)arg; + call_data* calld = (call_data*)elem->call_data; // If the result was not already processed, invoke the callback now. if (error != GRPC_ERROR_NONE && gpr_atm_full_cas(&calld->state, (gpr_atm)STATE_INIT, (gpr_atm)STATE_CANCELLED)) { - on_md_processing_done_inner(exec_ctx, elem, NULL, 0, NULL, 0, + on_md_processing_done_inner(exec_ctx, elem, nullptr, 0, nullptr, 0, GRPC_ERROR_REF(error)); } GRPC_CALL_STACK_UNREF(exec_ctx, calld->owning_call, "cancel_call"); } -static void recv_initial_metadata_ready(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_call_element *elem = (grpc_call_element *)arg; - channel_data *chand = (channel_data *)elem->channel_data; - call_data *calld = (call_data *)elem->call_data; - grpc_transport_stream_op_batch *batch = calld->recv_initial_metadata_batch; +static void recv_initial_metadata_ready(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_call_element* elem = (grpc_call_element*)arg; + channel_data* chand = (channel_data*)elem->channel_data; + call_data* calld = (call_data*)elem->call_data; + grpc_transport_stream_op_batch* batch = calld->recv_initial_metadata_batch; if (error == GRPC_ERROR_NONE) { - if (chand->creds != NULL && chand->creds->processor.process != NULL) { + if (chand->creds != nullptr && chand->creds->processor.process != nullptr) { // We're calling out to the application, so we need to make sure // to drop the call combiner early if we get cancelled. GRPC_CALL_STACK_REF(calld->owning_call, "cancel_call"); @@ -189,9 +189,9 @@ static void recv_initial_metadata_ready(grpc_exec_ctx *exec_ctx, void *arg, } static void auth_start_transport_stream_op_batch( - grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_transport_stream_op_batch *batch) { - call_data *calld = (call_data *)elem->call_data; + grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_transport_stream_op_batch* batch) { + call_data* calld = (call_data*)elem->call_data; if (batch->recv_initial_metadata) { // Inject our callback. calld->recv_initial_metadata_batch = batch; @@ -204,11 +204,11 @@ static void auth_start_transport_stream_op_batch( } /* Constructor for call_data */ -static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - const grpc_call_element_args *args) { - call_data *calld = (call_data *)elem->call_data; - channel_data *chand = (channel_data *)elem->channel_data; +static grpc_error* init_call_elem(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + const grpc_call_element_args* args) { + call_data* calld = (call_data*)elem->call_data; + channel_data* chand = (channel_data*)elem->channel_data; calld->call_combiner = args->call_combiner; calld->owning_call = args->call_stack; GRPC_CLOSURE_INIT(&calld->recv_initial_metadata_ready, @@ -216,11 +216,11 @@ static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, grpc_schedule_on_exec_ctx); // Create server security context. Set its auth context from channel // data and save it in the call context. - grpc_server_security_context *server_ctx = + grpc_server_security_context* server_ctx = grpc_server_security_context_create(); server_ctx->auth_context = grpc_auth_context_create(chand->auth_context); calld->auth_context = server_ctx->auth_context; - if (args->context[GRPC_CONTEXT_SECURITY].value != NULL) { + if (args->context[GRPC_CONTEXT_SECURITY].value != nullptr) { args->context[GRPC_CONTEXT_SECURITY].destroy( args->context[GRPC_CONTEXT_SECURITY].value); } @@ -231,31 +231,31 @@ static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, } /* Destructor for call_data */ -static void destroy_call_elem(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - const grpc_call_final_info *final_info, - grpc_closure *ignored) {} +static void destroy_call_elem(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + const grpc_call_final_info* final_info, + grpc_closure* ignored) {} /* Constructor for channel_data */ -static grpc_error *init_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_channel_element_args *args) { +static grpc_error* init_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_channel_element_args* args) { GPR_ASSERT(!args->is_last); - channel_data *chand = (channel_data *)elem->channel_data; - grpc_auth_context *auth_context = + channel_data* chand = (channel_data*)elem->channel_data; + grpc_auth_context* auth_context = grpc_find_auth_context_in_args(args->channel_args); - GPR_ASSERT(auth_context != NULL); + GPR_ASSERT(auth_context != nullptr); chand->auth_context = GRPC_AUTH_CONTEXT_REF(auth_context, "server_auth_filter"); - grpc_server_credentials *creds = + grpc_server_credentials* creds = grpc_find_server_credentials_in_args(args->channel_args); chand->creds = grpc_server_credentials_ref(creds); return GRPC_ERROR_NONE; } /* Destructor for channel data */ -static void destroy_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem) { - channel_data *chand = (channel_data *)elem->channel_data; +static void destroy_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem) { + channel_data* chand = (channel_data*)elem->channel_data; GRPC_AUTH_CONTEXT_UNREF(chand->auth_context, "server_auth_filter"); grpc_server_credentials_unref(exec_ctx, chand->creds); } diff --git a/src/core/lib/security/transport/tsi_error.cc b/src/core/lib/security/transport/tsi_error.cc index 72f9600e846..f71696d35da 100644 --- a/src/core/lib/security/transport/tsi_error.cc +++ b/src/core/lib/security/transport/tsi_error.cc @@ -18,7 +18,7 @@ #include "src/core/lib/security/transport/tsi_error.h" -grpc_error *grpc_set_tsi_error_result(grpc_error *error, tsi_result result) { +grpc_error* grpc_set_tsi_error_result(grpc_error* error, tsi_result result) { return grpc_error_set_int( grpc_error_set_str( error, GRPC_ERROR_STR_TSI_ERROR, diff --git a/src/core/lib/security/transport/tsi_error.h b/src/core/lib/security/transport/tsi_error.h index 4e19daf796f..8fa6c480acd 100644 --- a/src/core/lib/security/transport/tsi_error.h +++ b/src/core/lib/security/transport/tsi_error.h @@ -22,14 +22,6 @@ #include "src/core/lib/iomgr/error.h" #include "src/core/tsi/transport_security_interface.h" -#ifdef __cplusplus -extern "C" { -#endif - -grpc_error *grpc_set_tsi_error_result(grpc_error *error, tsi_result result); - -#ifdef __cplusplus -} -#endif +grpc_error* grpc_set_tsi_error_result(grpc_error* error, tsi_result result); #endif /* GRPC_CORE_LIB_SECURITY_TRANSPORT_TSI_ERROR_H */ diff --git a/src/core/lib/security/util/json_util.cc b/src/core/lib/security/util/json_util.cc index d847addef9a..fef1a1f51d2 100644 --- a/src/core/lib/security/util/json_util.cc +++ b/src/core/lib/security/util/json_util.cc @@ -23,24 +23,24 @@ #include #include -const char *grpc_json_get_string_property(const grpc_json *json, - const char *prop_name) { - grpc_json *child; - for (child = json->child; child != NULL; child = child->next) { +const char* grpc_json_get_string_property(const grpc_json* json, + const char* prop_name) { + grpc_json* child; + for (child = json->child; child != nullptr; child = child->next) { if (strcmp(child->key, prop_name) == 0) break; } - if (child == NULL || child->type != GRPC_JSON_STRING) { + if (child == nullptr || child->type != GRPC_JSON_STRING) { gpr_log(GPR_ERROR, "Invalid or missing %s property.", prop_name); - return NULL; + return nullptr; } return child->value; } -bool grpc_copy_json_string_property(const grpc_json *json, - const char *prop_name, - char **copied_value) { - const char *prop_value = grpc_json_get_string_property(json, prop_name); - if (prop_value == NULL) return false; +bool grpc_copy_json_string_property(const grpc_json* json, + const char* prop_name, + char** copied_value) { + const char* prop_value = grpc_json_get_string_property(json, prop_name); + if (prop_value == nullptr) return false; *copied_value = gpr_strdup(prop_value); return true; } diff --git a/src/core/lib/security/util/json_util.h b/src/core/lib/security/util/json_util.h index cdd8a7198a8..b7e46d40627 100644 --- a/src/core/lib/security/util/json_util.h +++ b/src/core/lib/security/util/json_util.h @@ -28,21 +28,13 @@ #define GRPC_AUTH_JSON_TYPE_SERVICE_ACCOUNT "service_account" #define GRPC_AUTH_JSON_TYPE_AUTHORIZED_USER "authorized_user" -#ifdef __cplusplus -extern "C" { -#endif - // Gets a child property from a json node. -const char *grpc_json_get_string_property(const grpc_json *json, - const char *prop_name); +const char* grpc_json_get_string_property(const grpc_json* json, + const char* prop_name); // Copies the value of the json child property specified by prop_name. // Returns false if the property was not found. -bool grpc_copy_json_string_property(const grpc_json *json, - const char *prop_name, char **copied_value); - -#ifdef __cplusplus -} -#endif +bool grpc_copy_json_string_property(const grpc_json* json, + const char* prop_name, char** copied_value); #endif /* GRPC_CORE_LIB_SECURITY_UTIL_JSON_UTIL_H */ diff --git a/src/core/lib/slice/b64.cc b/src/core/lib/slice/b64.cc index 50264719a4b..fe7a86ef842 100644 --- a/src/core/lib/slice/b64.cc +++ b/src/core/lib/slice/b64.cc @@ -54,11 +54,11 @@ static const char base64_url_safe_chars[] = /* --- base64 functions. --- */ -char *grpc_base64_encode(const void *vdata, size_t data_size, int url_safe, +char* grpc_base64_encode(const void* vdata, size_t data_size, int url_safe, int multiline) { size_t result_projected_size = grpc_base64_estimate_encoded_size(data_size, url_safe, multiline); - char *result = (char *)gpr_malloc(result_projected_size); + char* result = (char*)gpr_malloc(result_projected_size); grpc_base64_encode_core(result, vdata, data_size, url_safe, multiline); return result; } @@ -73,15 +73,15 @@ size_t grpc_base64_estimate_encoded_size(size_t data_size, int url_safe, return result_projected_size; } -void grpc_base64_encode_core(char *result, const void *vdata, size_t data_size, +void grpc_base64_encode_core(char* result, const void* vdata, size_t data_size, int url_safe, int multiline) { - const unsigned char *data = (const unsigned char *)vdata; - const char *base64_chars = + const unsigned char* data = (const unsigned char*)vdata; + const char* base64_chars = url_safe ? base64_url_safe_chars : base64_url_unsafe_chars; const size_t result_projected_size = grpc_base64_estimate_encoded_size(data_size, url_safe, multiline); - char *current = result; + char* current = result; size_t num_blocks = 0; size_t i = 0; @@ -122,27 +122,27 @@ void grpc_base64_encode_core(char *result, const void *vdata, size_t data_size, result[current - result] = '\0'; } -grpc_slice grpc_base64_decode(grpc_exec_ctx *exec_ctx, const char *b64, +grpc_slice grpc_base64_decode(grpc_exec_ctx* exec_ctx, const char* b64, int url_safe) { return grpc_base64_decode_with_len(exec_ctx, b64, strlen(b64), url_safe); } -static void decode_one_char(const unsigned char *codes, unsigned char *result, - size_t *result_offset) { +static void decode_one_char(const unsigned char* codes, unsigned char* result, + size_t* result_offset) { uint32_t packed = ((uint32_t)codes[0] << 2) | ((uint32_t)codes[1] >> 4); result[(*result_offset)++] = (unsigned char)packed; } -static void decode_two_chars(const unsigned char *codes, unsigned char *result, - size_t *result_offset) { +static void decode_two_chars(const unsigned char* codes, unsigned char* result, + size_t* result_offset) { uint32_t packed = ((uint32_t)codes[0] << 10) | ((uint32_t)codes[1] << 4) | ((uint32_t)codes[2] >> 2); result[(*result_offset)++] = (unsigned char)(packed >> 8); result[(*result_offset)++] = (unsigned char)(packed); } -static int decode_group(const unsigned char *codes, size_t num_codes, - unsigned char *result, size_t *result_offset) { +static int decode_group(const unsigned char* codes, size_t num_codes, + unsigned char* result, size_t* result_offset) { GPR_ASSERT(num_codes <= 4); /* Short end groups that may not have padding. */ @@ -185,10 +185,10 @@ static int decode_group(const unsigned char *codes, size_t num_codes, return 1; } -grpc_slice grpc_base64_decode_with_len(grpc_exec_ctx *exec_ctx, const char *b64, +grpc_slice grpc_base64_decode_with_len(grpc_exec_ctx* exec_ctx, const char* b64, size_t b64_len, int url_safe) { grpc_slice result = GRPC_SLICE_MALLOC(b64_len); - unsigned char *current = GRPC_SLICE_START_PTR(result); + unsigned char* current = GRPC_SLICE_START_PTR(result); size_t result_size = 0; unsigned char codes[4]; size_t num_codes = 0; diff --git a/src/core/lib/slice/b64.h b/src/core/lib/slice/b64.h index 9b4dc65dbbb..f86c1d99010 100644 --- a/src/core/lib/slice/b64.h +++ b/src/core/lib/slice/b64.h @@ -21,14 +21,10 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /* Encodes data using base64. It is the caller's responsability to free the returned char * using gpr_free. Returns NULL on NULL input. TODO(makdharma) : change the flags to bool from int */ -char *grpc_base64_encode(const void *data, size_t data_size, int url_safe, +char* grpc_base64_encode(const void* data, size_t data_size, int url_safe, int multiline); /* estimate the upper bound on size of base64 encoded data. The actual size @@ -39,20 +35,16 @@ size_t grpc_base64_estimate_encoded_size(size_t data_size, int url_safe, /* Encodes data using base64 and write it to memory pointed to by result. It is * the caller's responsiblity to allocate enough memory in |result| to fit the * encoded data. */ -void grpc_base64_encode_core(char *result, const void *vdata, size_t data_size, +void grpc_base64_encode_core(char* result, const void* vdata, size_t data_size, int url_safe, int multiline); /* Decodes data according to the base64 specification. Returns an empty slice in case of failure. */ -grpc_slice grpc_base64_decode(grpc_exec_ctx *exec_ctx, const char *b64, +grpc_slice grpc_base64_decode(grpc_exec_ctx* exec_ctx, const char* b64, int url_safe); /* Same as above except that the length is provided by the caller. */ -grpc_slice grpc_base64_decode_with_len(grpc_exec_ctx *exec_ctx, const char *b64, +grpc_slice grpc_base64_decode_with_len(grpc_exec_ctx* exec_ctx, const char* b64, size_t b64_len, int url_safe); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SLICE_B64_H */ diff --git a/src/core/lib/slice/percent_encoding.cc b/src/core/lib/slice/percent_encoding.cc index effc8d7ad6b..894e43b1919 100644 --- a/src/core/lib/slice/percent_encoding.cc +++ b/src/core/lib/slice/percent_encoding.cc @@ -32,19 +32,19 @@ const uint8_t grpc_compatible_percent_encoding_unreserved_bytes[256 / 8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static bool is_unreserved_character(uint8_t c, - const uint8_t *unreserved_bytes) { + const uint8_t* unreserved_bytes) { return ((unreserved_bytes[c / 8] >> (c % 8)) & 1) != 0; } grpc_slice grpc_percent_encode_slice(grpc_slice slice, - const uint8_t *unreserved_bytes) { + const uint8_t* unreserved_bytes) { static const uint8_t hex[] = "0123456789ABCDEF"; // first pass: count the number of bytes needed to output this string size_t output_length = 0; - const uint8_t *slice_start = GRPC_SLICE_START_PTR(slice); - const uint8_t *slice_end = GRPC_SLICE_END_PTR(slice); - const uint8_t *p; + const uint8_t* slice_start = GRPC_SLICE_START_PTR(slice); + const uint8_t* slice_end = GRPC_SLICE_END_PTR(slice); + const uint8_t* p; bool any_reserved_bytes = false; for (p = slice_start; p < slice_end; p++) { bool unres = is_unreserved_character(*p, unreserved_bytes); @@ -57,7 +57,7 @@ grpc_slice grpc_percent_encode_slice(grpc_slice slice, } // second pass: actually encode grpc_slice out = GRPC_SLICE_MALLOC(output_length); - uint8_t *q = GRPC_SLICE_START_PTR(out); + uint8_t* q = GRPC_SLICE_START_PTR(out); for (p = slice_start; p < slice_end; p++) { if (is_unreserved_character(*p, unreserved_bytes)) { *q++ = *p; @@ -71,7 +71,7 @@ grpc_slice grpc_percent_encode_slice(grpc_slice slice, return out; } -static bool valid_hex(const uint8_t *p, const uint8_t *end) { +static bool valid_hex(const uint8_t* p, const uint8_t* end) { if (p >= end) return false; return (*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f') || (*p >= 'A' && *p <= 'F'); @@ -85,10 +85,10 @@ static uint8_t dehex(uint8_t c) { } bool grpc_strict_percent_decode_slice(grpc_slice slice_in, - const uint8_t *unreserved_bytes, - grpc_slice *slice_out) { - const uint8_t *p = GRPC_SLICE_START_PTR(slice_in); - const uint8_t *in_end = GRPC_SLICE_END_PTR(slice_in); + const uint8_t* unreserved_bytes, + grpc_slice* slice_out) { + const uint8_t* p = GRPC_SLICE_START_PTR(slice_in); + const uint8_t* in_end = GRPC_SLICE_END_PTR(slice_in); size_t out_length = 0; bool any_percent_encoded_stuff = false; while (p != in_end) { @@ -111,7 +111,7 @@ bool grpc_strict_percent_decode_slice(grpc_slice slice_in, } p = GRPC_SLICE_START_PTR(slice_in); *slice_out = GRPC_SLICE_MALLOC(out_length); - uint8_t *q = GRPC_SLICE_START_PTR(*slice_out); + uint8_t* q = GRPC_SLICE_START_PTR(*slice_out); while (p != in_end) { if (*p == '%') { *q++ = (uint8_t)(dehex(p[1]) << 4) | (dehex(p[2])); @@ -125,8 +125,8 @@ bool grpc_strict_percent_decode_slice(grpc_slice slice_in, } grpc_slice grpc_permissive_percent_decode_slice(grpc_slice slice_in) { - const uint8_t *p = GRPC_SLICE_START_PTR(slice_in); - const uint8_t *in_end = GRPC_SLICE_END_PTR(slice_in); + const uint8_t* p = GRPC_SLICE_START_PTR(slice_in); + const uint8_t* in_end = GRPC_SLICE_END_PTR(slice_in); size_t out_length = 0; bool any_percent_encoded_stuff = false; while (p != in_end) { @@ -149,7 +149,7 @@ grpc_slice grpc_permissive_percent_decode_slice(grpc_slice slice_in) { } p = GRPC_SLICE_START_PTR(slice_in); grpc_slice out = GRPC_SLICE_MALLOC(out_length); - uint8_t *q = GRPC_SLICE_START_PTR(out); + uint8_t* q = GRPC_SLICE_START_PTR(out); while (p != in_end) { if (*p == '%') { if (!valid_hex(p + 1, in_end) || !valid_hex(p + 2, in_end)) { diff --git a/src/core/lib/slice/percent_encoding.h b/src/core/lib/slice/percent_encoding.h index 14a4deb44b8..a1009ff01f3 100644 --- a/src/core/lib/slice/percent_encoding.h +++ b/src/core/lib/slice/percent_encoding.h @@ -30,10 +30,6 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /* URL percent encoding spec bitfield (usabel as 'unreserved_bytes' in grpc_percent_encode_slice, grpc_strict_percent_decode_slice). Flags [A-Za-z0-9-_.~] as unreserved bytes for the percent encoding routines @@ -49,7 +45,7 @@ extern const uint8_t grpc_compatible_percent_encoding_unreserved_bytes[256 / 8]; unreserved_bytes is a bitfield indicating which bytes are considered unreserved and thus do not need percent encoding */ grpc_slice grpc_percent_encode_slice(grpc_slice slice, - const uint8_t *unreserved_bytes); + const uint8_t* unreserved_bytes); /* Percent-decode a slice, strictly. If the input is legal (contains no unreserved bytes, and legal % encodings), returns true and sets *slice_out to the decoded slice. @@ -57,15 +53,11 @@ grpc_slice grpc_percent_encode_slice(grpc_slice slice, unreserved_bytes is a bitfield indicating which bytes are considered unreserved and thus do not need percent encoding */ bool grpc_strict_percent_decode_slice(grpc_slice slice_in, - const uint8_t *unreserved_bytes, - grpc_slice *slice_out); + const uint8_t* unreserved_bytes, + grpc_slice* slice_out); /* Percent-decode a slice, permissively. If a % triplet can not be decoded, pass it through verbatim. This cannot fail. */ grpc_slice grpc_permissive_percent_decode_slice(grpc_slice slice_in); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SLICE_PERCENT_ENCODING_H */ diff --git a/src/core/lib/slice/slice.cc b/src/core/lib/slice/slice.cc index 0764eda0527..bbaf87ba23d 100644 --- a/src/core/lib/slice/slice.cc +++ b/src/core/lib/slice/slice.cc @@ -26,8 +26,8 @@ #include "src/core/lib/iomgr/exec_ctx.h" -char *grpc_slice_to_c_string(grpc_slice slice) { - char *out = (char *)gpr_malloc(GRPC_SLICE_LENGTH(slice) + 1); +char* grpc_slice_to_c_string(grpc_slice slice) { + char* out = (char*)gpr_malloc(GRPC_SLICE_LENGTH(slice) + 1); memcpy(out, GRPC_SLICE_START_PTR(slice), GRPC_SLICE_LENGTH(slice)); out[GRPC_SLICE_LENGTH(slice)] = 0; return out; @@ -35,7 +35,7 @@ char *grpc_slice_to_c_string(grpc_slice slice) { grpc_slice grpc_empty_slice(void) { grpc_slice out; - out.refcount = NULL; + out.refcount = nullptr; out.data.inlined.length = 0; return out; } @@ -54,7 +54,7 @@ grpc_slice grpc_slice_ref_internal(grpc_slice slice) { return slice; } -void grpc_slice_unref_internal(grpc_exec_ctx *exec_ctx, grpc_slice slice) { +void grpc_slice_unref_internal(grpc_exec_ctx* exec_ctx, grpc_slice slice) { if (slice.refcount) { slice.refcount->vtable->unref(exec_ctx, slice.refcount); } @@ -74,8 +74,8 @@ void grpc_slice_unref(grpc_slice slice) { /* grpc_slice_from_static_string support structure - a refcount that does nothing */ -static void noop_ref(void *unused) {} -static void noop_unref(grpc_exec_ctx *exec_ctx, void *unused) {} +static void noop_ref(void* unused) {} +static void noop_unref(grpc_exec_ctx* exec_ctx, void* unused) {} static const grpc_slice_refcount_vtable noop_refcount_vtable = { noop_ref, noop_unref, grpc_slice_default_eq_impl, @@ -83,15 +83,15 @@ static const grpc_slice_refcount_vtable noop_refcount_vtable = { static grpc_slice_refcount noop_refcount = {&noop_refcount_vtable, &noop_refcount}; -grpc_slice grpc_slice_from_static_buffer(const void *s, size_t len) { +grpc_slice grpc_slice_from_static_buffer(const void* s, size_t len) { grpc_slice slice; slice.refcount = &noop_refcount; - slice.data.refcounted.bytes = (uint8_t *)s; + slice.data.refcounted.bytes = (uint8_t*)s; slice.data.refcounted.length = len; return slice; } -grpc_slice grpc_slice_from_static_string(const char *s) { +grpc_slice grpc_slice_from_static_string(const char* s) { return grpc_slice_from_static_buffer(s, strlen(s)); } @@ -100,17 +100,17 @@ grpc_slice grpc_slice_from_static_string(const char *s) { typedef struct new_slice_refcount { grpc_slice_refcount rc; gpr_refcount refs; - void (*user_destroy)(void *); - void *user_data; + void (*user_destroy)(void*); + void* user_data; } new_slice_refcount; -static void new_slice_ref(void *p) { - new_slice_refcount *r = (new_slice_refcount *)p; +static void new_slice_ref(void* p) { + new_slice_refcount* r = (new_slice_refcount*)p; gpr_ref(&r->refs); } -static void new_slice_unref(grpc_exec_ctx *exec_ctx, void *p) { - new_slice_refcount *r = (new_slice_refcount *)p; +static void new_slice_unref(grpc_exec_ctx* exec_ctx, void* p) { + new_slice_refcount* r = (new_slice_refcount*)p; if (gpr_unref(&r->refs)) { r->user_destroy(r->user_data); gpr_free(r); @@ -121,12 +121,12 @@ static const grpc_slice_refcount_vtable new_slice_vtable = { new_slice_ref, new_slice_unref, grpc_slice_default_eq_impl, grpc_slice_default_hash_impl}; -grpc_slice grpc_slice_new_with_user_data(void *p, size_t len, - void (*destroy)(void *), - void *user_data) { +grpc_slice grpc_slice_new_with_user_data(void* p, size_t len, + void (*destroy)(void*), + void* user_data) { grpc_slice slice; - new_slice_refcount *rc = - (new_slice_refcount *)gpr_malloc(sizeof(new_slice_refcount)); + new_slice_refcount* rc = + (new_slice_refcount*)gpr_malloc(sizeof(new_slice_refcount)); gpr_ref_init(&rc->refs, 1); rc->rc.vtable = &new_slice_vtable; rc->rc.sub_refcount = &rc->rc; @@ -134,12 +134,12 @@ grpc_slice grpc_slice_new_with_user_data(void *p, size_t len, rc->user_data = user_data; slice.refcount = &rc->rc; - slice.data.refcounted.bytes = (uint8_t *)p; + slice.data.refcounted.bytes = (uint8_t*)p; slice.data.refcounted.length = len; return slice; } -grpc_slice grpc_slice_new(void *p, size_t len, void (*destroy)(void *)) { +grpc_slice grpc_slice_new(void* p, size_t len, void (*destroy)(void*)) { /* Pass "p" to *destroy when the slice is no longer needed. */ return grpc_slice_new_with_user_data(p, len, destroy, p); } @@ -149,18 +149,18 @@ grpc_slice grpc_slice_new(void *p, size_t len, void (*destroy)(void *)) { typedef struct new_with_len_slice_refcount { grpc_slice_refcount rc; gpr_refcount refs; - void *user_data; + void* user_data; size_t user_length; - void (*user_destroy)(void *, size_t); + void (*user_destroy)(void*, size_t); } new_with_len_slice_refcount; -static void new_with_len_ref(void *p) { - new_with_len_slice_refcount *r = (new_with_len_slice_refcount *)p; +static void new_with_len_ref(void* p) { + new_with_len_slice_refcount* r = (new_with_len_slice_refcount*)p; gpr_ref(&r->refs); } -static void new_with_len_unref(grpc_exec_ctx *exec_ctx, void *p) { - new_with_len_slice_refcount *r = (new_with_len_slice_refcount *)p; +static void new_with_len_unref(grpc_exec_ctx* exec_ctx, void* p) { + new_with_len_slice_refcount* r = (new_with_len_slice_refcount*)p; if (gpr_unref(&r->refs)) { r->user_destroy(r->user_data, r->user_length); gpr_free(r); @@ -171,10 +171,10 @@ static const grpc_slice_refcount_vtable new_with_len_vtable = { new_with_len_ref, new_with_len_unref, grpc_slice_default_eq_impl, grpc_slice_default_hash_impl}; -grpc_slice grpc_slice_new_with_len(void *p, size_t len, - void (*destroy)(void *, size_t)) { +grpc_slice grpc_slice_new_with_len(void* p, size_t len, + void (*destroy)(void*, size_t)) { grpc_slice slice; - new_with_len_slice_refcount *rc = (new_with_len_slice_refcount *)gpr_malloc( + new_with_len_slice_refcount* rc = (new_with_len_slice_refcount*)gpr_malloc( sizeof(new_with_len_slice_refcount)); gpr_ref_init(&rc->refs, 1); rc->rc.vtable = &new_with_len_vtable; @@ -184,19 +184,19 @@ grpc_slice grpc_slice_new_with_len(void *p, size_t len, rc->user_length = len; slice.refcount = &rc->rc; - slice.data.refcounted.bytes = (uint8_t *)p; + slice.data.refcounted.bytes = (uint8_t*)p; slice.data.refcounted.length = len; return slice; } -grpc_slice grpc_slice_from_copied_buffer(const char *source, size_t length) { +grpc_slice grpc_slice_from_copied_buffer(const char* source, size_t length) { if (length == 0) return grpc_empty_slice(); grpc_slice slice = GRPC_SLICE_MALLOC(length); memcpy(GRPC_SLICE_START_PTR(slice), source, length); return slice; } -grpc_slice grpc_slice_from_copied_string(const char *source) { +grpc_slice grpc_slice_from_copied_string(const char* source) { return grpc_slice_from_copied_buffer(source, strlen(source)); } @@ -205,13 +205,13 @@ typedef struct { gpr_refcount refs; } malloc_refcount; -static void malloc_ref(void *p) { - malloc_refcount *r = (malloc_refcount *)p; +static void malloc_ref(void* p) { + malloc_refcount* r = (malloc_refcount*)p; gpr_ref(&r->refs); } -static void malloc_unref(grpc_exec_ctx *exec_ctx, void *p) { - malloc_refcount *r = (malloc_refcount *)p; +static void malloc_unref(grpc_exec_ctx* exec_ctx, void* p) { + malloc_refcount* r = (malloc_refcount*)p; if (gpr_unref(&r->refs)) { gpr_free(r); } @@ -233,8 +233,8 @@ grpc_slice grpc_slice_malloc_large(size_t length) { refcount is a malloc_refcount bytes is an array of bytes of the requested length Both parts are placed in the same allocation returned from gpr_malloc */ - malloc_refcount *rc = - (malloc_refcount *)gpr_malloc(sizeof(malloc_refcount) + length); + malloc_refcount* rc = + (malloc_refcount*)gpr_malloc(sizeof(malloc_refcount) + length); /* Initial refcount on rc is 1 - and it's up to the caller to release this reference. */ @@ -247,7 +247,7 @@ grpc_slice grpc_slice_malloc_large(size_t length) { /* The slices refcount points back to the allocated block. */ slice.refcount = &rc->base; /* The data bytes are placed immediately after the refcount struct */ - slice.data.refcounted.bytes = (uint8_t *)(rc + 1); + slice.data.refcounted.bytes = (uint8_t*)(rc + 1); /* And the length of the block is set to the requested length */ slice.data.refcounted.length = length; return slice; @@ -260,7 +260,7 @@ grpc_slice grpc_slice_malloc(size_t length) { return grpc_slice_malloc_large(length); } else { /* small slice: just inline the data */ - slice.refcount = NULL; + slice.refcount = nullptr; slice.data.inlined.length = (uint8_t)length; } return slice; @@ -283,7 +283,7 @@ grpc_slice grpc_slice_sub_no_ref(grpc_slice source, size_t begin, size_t end) { } else { /* Enforce preconditions */ GPR_ASSERT(source.data.inlined.length >= end); - subset.refcount = NULL; + subset.refcount = nullptr; subset.data.inlined.length = (uint8_t)(end - begin); memcpy(subset.data.inlined.bytes, source.data.inlined.bytes + begin, end - begin); @@ -295,7 +295,7 @@ grpc_slice grpc_slice_sub(grpc_slice source, size_t begin, size_t end) { grpc_slice subset; if (end - begin <= sizeof(subset.data.inlined.bytes)) { - subset.refcount = NULL; + subset.refcount = nullptr; subset.data.inlined.length = (uint8_t)(end - begin); memcpy(subset.data.inlined.bytes, GRPC_SLICE_START_PTR(source) + begin, end - begin); @@ -307,14 +307,14 @@ grpc_slice grpc_slice_sub(grpc_slice source, size_t begin, size_t end) { return subset; } -grpc_slice grpc_slice_split_tail_maybe_ref(grpc_slice *source, size_t split, +grpc_slice grpc_slice_split_tail_maybe_ref(grpc_slice* source, size_t split, grpc_slice_ref_whom ref_whom) { grpc_slice tail; - if (source->refcount == NULL) { + if (source->refcount == nullptr) { /* inlined data, copy it out */ GPR_ASSERT(source->data.inlined.length >= split); - tail.refcount = NULL; + tail.refcount = nullptr; tail.data.inlined.length = (uint8_t)(source->data.inlined.length - split); memcpy(tail.data.inlined.bytes, source->data.inlined.bytes + split, tail.data.inlined.length); @@ -325,7 +325,7 @@ grpc_slice grpc_slice_split_tail_maybe_ref(grpc_slice *source, size_t split, if (tail_length < sizeof(tail.data.inlined.bytes) && ref_whom != GRPC_SLICE_REF_TAIL) { /* Copy out the bytes - it'll be cheaper than refcounting */ - tail.refcount = NULL; + tail.refcount = nullptr; tail.data.inlined.length = (uint8_t)tail_length; memcpy(tail.data.inlined.bytes, source->data.refcounted.bytes + split, tail_length); @@ -358,17 +358,17 @@ grpc_slice grpc_slice_split_tail_maybe_ref(grpc_slice *source, size_t split, return tail; } -grpc_slice grpc_slice_split_tail(grpc_slice *source, size_t split) { +grpc_slice grpc_slice_split_tail(grpc_slice* source, size_t split) { return grpc_slice_split_tail_maybe_ref(source, split, GRPC_SLICE_REF_BOTH); } -grpc_slice grpc_slice_split_head(grpc_slice *source, size_t split) { +grpc_slice grpc_slice_split_head(grpc_slice* source, size_t split) { grpc_slice head; - if (source->refcount == NULL) { + if (source->refcount == nullptr) { GPR_ASSERT(source->data.inlined.length >= split); - head.refcount = NULL; + head.refcount = nullptr; head.data.inlined.length = (uint8_t)split; memcpy(head.data.inlined.bytes, source->data.inlined.bytes, split); source->data.inlined.length = @@ -378,7 +378,7 @@ grpc_slice grpc_slice_split_head(grpc_slice *source, size_t split) { } else if (split < sizeof(head.data.inlined.bytes)) { GPR_ASSERT(source->data.refcounted.length >= split); - head.refcount = NULL; + head.refcount = nullptr; head.data.inlined.length = (uint8_t)split; memcpy(head.data.inlined.bytes, source->data.refcounted.bytes, split); source->refcount = source->refcount->sub_refcount; @@ -423,7 +423,7 @@ int grpc_slice_cmp(grpc_slice a, grpc_slice b) { GRPC_SLICE_LENGTH(a)); } -int grpc_slice_str_cmp(grpc_slice a, const char *b) { +int grpc_slice_str_cmp(grpc_slice a, const char* b) { size_t b_length = strlen(b); int d = (int)(GRPC_SLICE_LENGTH(a) - b_length); if (d != 0) return d; @@ -431,20 +431,20 @@ int grpc_slice_str_cmp(grpc_slice a, const char *b) { } int grpc_slice_is_equivalent(grpc_slice a, grpc_slice b) { - if (a.refcount == NULL || b.refcount == NULL) { + if (a.refcount == nullptr || b.refcount == nullptr) { return grpc_slice_eq(a, b); } return a.data.refcounted.length == b.data.refcounted.length && a.data.refcounted.bytes == b.data.refcounted.bytes; } -int grpc_slice_buf_start_eq(grpc_slice a, const void *b, size_t len) { +int grpc_slice_buf_start_eq(grpc_slice a, const void* b, size_t len) { if (GRPC_SLICE_LENGTH(a) < len) return 0; return 0 == memcmp(GRPC_SLICE_START_PTR(a), b, len); } int grpc_slice_rchr(grpc_slice s, char c) { - const char *b = (const char *)GRPC_SLICE_START_PTR(s); + const char* b = (const char*)GRPC_SLICE_START_PTR(s); int i; for (i = (int)GRPC_SLICE_LENGTH(s) - 1; i != -1 && b[i] != c; i--) ; @@ -452,16 +452,16 @@ int grpc_slice_rchr(grpc_slice s, char c) { } int grpc_slice_chr(grpc_slice s, char c) { - const char *b = (const char *)GRPC_SLICE_START_PTR(s); - const char *p = (const char *)memchr(b, c, GRPC_SLICE_LENGTH(s)); - return p == NULL ? -1 : (int)(p - b); + const char* b = (const char*)GRPC_SLICE_START_PTR(s); + const char* p = (const char*)memchr(b, c, GRPC_SLICE_LENGTH(s)); + return p == nullptr ? -1 : (int)(p - b); } int grpc_slice_slice(grpc_slice haystack, grpc_slice needle) { size_t haystack_len = GRPC_SLICE_LENGTH(haystack); - const uint8_t *haystack_bytes = GRPC_SLICE_START_PTR(haystack); + const uint8_t* haystack_bytes = GRPC_SLICE_START_PTR(haystack); size_t needle_len = GRPC_SLICE_LENGTH(needle); - const uint8_t *needle_bytes = GRPC_SLICE_START_PTR(needle); + const uint8_t* needle_bytes = GRPC_SLICE_START_PTR(needle); if (haystack_len == 0 || needle_len == 0) return -1; if (haystack_len < needle_len) return -1; @@ -469,8 +469,8 @@ int grpc_slice_slice(grpc_slice haystack, grpc_slice needle) { return grpc_slice_eq(haystack, needle) ? 0 : -1; if (needle_len == 1) return grpc_slice_chr(haystack, (char)*needle_bytes); - const uint8_t *last = haystack_bytes + haystack_len - needle_len; - for (const uint8_t *cur = haystack_bytes; cur != last; ++cur) { + const uint8_t* last = haystack_bytes + haystack_len - needle_len; + for (const uint8_t* cur = haystack_bytes; cur != last; ++cur) { if (0 == memcmp(cur, needle_bytes, needle_len)) { return (int)(cur - haystack_bytes); } diff --git a/src/core/lib/slice/slice_buffer.cc b/src/core/lib/slice/slice_buffer.cc index 63ffc0b00dc..5db54dad91e 100644 --- a/src/core/lib/slice/slice_buffer.cc +++ b/src/core/lib/slice/slice_buffer.cc @@ -30,7 +30,7 @@ /* grow a buffer; requires GRPC_SLICE_BUFFER_INLINE_ELEMENTS > 1 */ #define GROW(x) (3 * (x) / 2) -static void maybe_embiggen(grpc_slice_buffer *sb) { +static void maybe_embiggen(grpc_slice_buffer* sb) { /* How far away from sb->base_slices is sb->slices pointer */ size_t slice_offset = (size_t)(sb->slices - sb->base_slices); size_t slice_count = sb->count + slice_offset; @@ -46,10 +46,10 @@ static void maybe_embiggen(grpc_slice_buffer *sb) { GPR_ASSERT(sb->capacity > slice_count); if (sb->base_slices == sb->inlined) { sb->base_slices = - (grpc_slice *)gpr_malloc(sb->capacity * sizeof(grpc_slice)); + (grpc_slice*)gpr_malloc(sb->capacity * sizeof(grpc_slice)); memcpy(sb->base_slices, sb->inlined, slice_count * sizeof(grpc_slice)); } else { - sb->base_slices = (grpc_slice *)gpr_realloc( + sb->base_slices = (grpc_slice*)gpr_realloc( sb->base_slices, sb->capacity * sizeof(grpc_slice)); } @@ -58,30 +58,30 @@ static void maybe_embiggen(grpc_slice_buffer *sb) { } } -void grpc_slice_buffer_init(grpc_slice_buffer *sb) { +void grpc_slice_buffer_init(grpc_slice_buffer* sb) { sb->count = 0; sb->length = 0; sb->capacity = GRPC_SLICE_BUFFER_INLINE_ELEMENTS; sb->base_slices = sb->slices = sb->inlined; } -void grpc_slice_buffer_destroy_internal(grpc_exec_ctx *exec_ctx, - grpc_slice_buffer *sb) { +void grpc_slice_buffer_destroy_internal(grpc_exec_ctx* exec_ctx, + grpc_slice_buffer* sb) { grpc_slice_buffer_reset_and_unref_internal(exec_ctx, sb); if (sb->base_slices != sb->inlined) { gpr_free(sb->base_slices); } } -void grpc_slice_buffer_destroy(grpc_slice_buffer *sb) { +void grpc_slice_buffer_destroy(grpc_slice_buffer* sb) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_slice_buffer_destroy_internal(&exec_ctx, sb); grpc_exec_ctx_finish(&exec_ctx); } -uint8_t *grpc_slice_buffer_tiny_add(grpc_slice_buffer *sb, size_t n) { - grpc_slice *back; - uint8_t *out; +uint8_t* grpc_slice_buffer_tiny_add(grpc_slice_buffer* sb, size_t n) { + grpc_slice* back; + uint8_t* out; sb->length += n; @@ -98,12 +98,12 @@ add_new: maybe_embiggen(sb); back = &sb->slices[sb->count]; sb->count++; - back->refcount = NULL; + back->refcount = nullptr; back->data.inlined.length = (uint8_t)n; return back->data.inlined.bytes; } -size_t grpc_slice_buffer_add_indexed(grpc_slice_buffer *sb, grpc_slice s) { +size_t grpc_slice_buffer_add_indexed(grpc_slice_buffer* sb, grpc_slice s) { size_t out = sb->count; maybe_embiggen(sb); sb->slices[out] = s; @@ -112,7 +112,7 @@ size_t grpc_slice_buffer_add_indexed(grpc_slice_buffer *sb, grpc_slice s) { return out; } -void grpc_slice_buffer_add(grpc_slice_buffer *sb, grpc_slice s) { +void grpc_slice_buffer_add(grpc_slice_buffer* sb, grpc_slice s) { size_t n = sb->count; /* if both the last slice in the slice buffer and the slice being added are inlined (that is, that they carry their data inside the slice data @@ -120,7 +120,7 @@ void grpc_slice_buffer_add(grpc_slice_buffer *sb, grpc_slice s) { into the back slice, preventing many small slices being passed into writes */ if (!s.refcount && n) { - grpc_slice *back = &sb->slices[n - 1]; + grpc_slice* back = &sb->slices[n - 1]; if (!back->refcount && back->data.inlined.length < GRPC_SLICE_INLINED_SIZE) { if (s.data.inlined.length + back->data.inlined.length <= @@ -137,7 +137,7 @@ void grpc_slice_buffer_add(grpc_slice_buffer *sb, grpc_slice s) { maybe_embiggen(sb); back = &sb->slices[n]; sb->count = n + 1; - back->refcount = NULL; + back->refcount = nullptr; back->data.inlined.length = (uint8_t)(s.data.inlined.length - cp1); memcpy(back->data.inlined.bytes, s.data.inlined.bytes + cp1, s.data.inlined.length - cp1); @@ -149,22 +149,22 @@ void grpc_slice_buffer_add(grpc_slice_buffer *sb, grpc_slice s) { grpc_slice_buffer_add_indexed(sb, s); } -void grpc_slice_buffer_addn(grpc_slice_buffer *sb, grpc_slice *s, size_t n) { +void grpc_slice_buffer_addn(grpc_slice_buffer* sb, grpc_slice* s, size_t n) { size_t i; for (i = 0; i < n; i++) { grpc_slice_buffer_add(sb, s[i]); } } -void grpc_slice_buffer_pop(grpc_slice_buffer *sb) { +void grpc_slice_buffer_pop(grpc_slice_buffer* sb) { if (sb->count != 0) { size_t count = --sb->count; sb->length -= GRPC_SLICE_LENGTH(sb->slices[count]); } } -void grpc_slice_buffer_reset_and_unref_internal(grpc_exec_ctx *exec_ctx, - grpc_slice_buffer *sb) { +void grpc_slice_buffer_reset_and_unref_internal(grpc_exec_ctx* exec_ctx, + grpc_slice_buffer* sb) { size_t i; for (i = 0; i < sb->count; i++) { grpc_slice_unref_internal(exec_ctx, sb->slices[i]); @@ -174,13 +174,13 @@ void grpc_slice_buffer_reset_and_unref_internal(grpc_exec_ctx *exec_ctx, sb->length = 0; } -void grpc_slice_buffer_reset_and_unref(grpc_slice_buffer *sb) { +void grpc_slice_buffer_reset_and_unref(grpc_slice_buffer* sb) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_slice_buffer_reset_and_unref_internal(&exec_ctx, sb); grpc_exec_ctx_finish(&exec_ctx); } -void grpc_slice_buffer_swap(grpc_slice_buffer *a, grpc_slice_buffer *b) { +void grpc_slice_buffer_swap(grpc_slice_buffer* a, grpc_slice_buffer* b) { size_t a_offset = (size_t)(a->slices - a->base_slices); size_t b_offset = (size_t)(b->slices - b->base_slices); @@ -207,7 +207,7 @@ void grpc_slice_buffer_swap(grpc_slice_buffer *a, grpc_slice_buffer *b) { memcpy(a->base_slices, b->inlined, b_count * sizeof(grpc_slice)); } else { /* no inlining: easy swap */ - GPR_SWAP(grpc_slice *, a->base_slices, b->base_slices); + GPR_SWAP(grpc_slice*, a->base_slices, b->base_slices); } /* Update the slices pointers (cannot do a GPR_SWAP on slices fields here). @@ -222,8 +222,8 @@ void grpc_slice_buffer_swap(grpc_slice_buffer *a, grpc_slice_buffer *b) { GPR_SWAP(size_t, a->length, b->length); } -void grpc_slice_buffer_move_into(grpc_slice_buffer *src, - grpc_slice_buffer *dst) { +void grpc_slice_buffer_move_into(grpc_slice_buffer* src, + grpc_slice_buffer* dst) { /* anything to move? */ if (src->count == 0) { return; @@ -239,8 +239,8 @@ void grpc_slice_buffer_move_into(grpc_slice_buffer *src, src->length = 0; } -static void slice_buffer_move_first_maybe_ref(grpc_slice_buffer *src, size_t n, - grpc_slice_buffer *dst, +static void slice_buffer_move_first_maybe_ref(grpc_slice_buffer* src, size_t n, + grpc_slice_buffer* dst, bool incref) { GPR_ASSERT(src->length >= n); if (src->length == n) { @@ -279,20 +279,20 @@ static void slice_buffer_move_first_maybe_ref(grpc_slice_buffer *src, size_t n, GPR_ASSERT(src->count > 0); } -void grpc_slice_buffer_move_first(grpc_slice_buffer *src, size_t n, - grpc_slice_buffer *dst) { +void grpc_slice_buffer_move_first(grpc_slice_buffer* src, size_t n, + grpc_slice_buffer* dst) { slice_buffer_move_first_maybe_ref(src, n, dst, true); } -void grpc_slice_buffer_move_first_no_ref(grpc_slice_buffer *src, size_t n, - grpc_slice_buffer *dst) { +void grpc_slice_buffer_move_first_no_ref(grpc_slice_buffer* src, size_t n, + grpc_slice_buffer* dst) { slice_buffer_move_first_maybe_ref(src, n, dst, false); } -void grpc_slice_buffer_move_first_into_buffer(grpc_exec_ctx *exec_ctx, - grpc_slice_buffer *src, size_t n, - void *dst) { - char *dstp = (char *)dst; +void grpc_slice_buffer_move_first_into_buffer(grpc_exec_ctx* exec_ctx, + grpc_slice_buffer* src, size_t n, + void* dst) { + char* dstp = (char*)dst; GPR_ASSERT(src->length >= n); while (n > 0) { @@ -316,8 +316,8 @@ void grpc_slice_buffer_move_first_into_buffer(grpc_exec_ctx *exec_ctx, } } -void grpc_slice_buffer_trim_end(grpc_slice_buffer *sb, size_t n, - grpc_slice_buffer *garbage) { +void grpc_slice_buffer_trim_end(grpc_slice_buffer* sb, size_t n, + grpc_slice_buffer* garbage) { GPR_ASSERT(n <= sb->length); sb->length -= n; for (;;) { @@ -340,7 +340,7 @@ void grpc_slice_buffer_trim_end(grpc_slice_buffer *sb, size_t n, } } -grpc_slice grpc_slice_buffer_take_first(grpc_slice_buffer *sb) { +grpc_slice grpc_slice_buffer_take_first(grpc_slice_buffer* sb) { grpc_slice slice; GPR_ASSERT(sb->count > 0); slice = sb->slices[0]; @@ -351,7 +351,7 @@ grpc_slice grpc_slice_buffer_take_first(grpc_slice_buffer *sb) { return slice; } -void grpc_slice_buffer_undo_take_first(grpc_slice_buffer *sb, +void grpc_slice_buffer_undo_take_first(grpc_slice_buffer* sb, grpc_slice slice) { sb->slices--; sb->slices[0] = slice; diff --git a/src/core/lib/slice/slice_hash_table.cc b/src/core/lib/slice/slice_hash_table.cc index 6c2c9c201c3..8f8e5a6b34a 100644 --- a/src/core/lib/slice/slice_hash_table.cc +++ b/src/core/lib/slice/slice_hash_table.cc @@ -35,12 +35,12 @@ struct grpc_slice_hash_table { }; static bool is_empty(grpc_slice_hash_table_entry* entry) { - return entry->value == NULL; + return entry->value == nullptr; } static void grpc_slice_hash_table_add(grpc_slice_hash_table* table, grpc_slice key, void* value) { - GPR_ASSERT(value != NULL); + GPR_ASSERT(value != nullptr); const size_t hash = grpc_slice_hash(key); for (size_t offset = 0; offset < table->size; ++offset) { const size_t idx = (hash + offset) % table->size; @@ -77,13 +77,13 @@ grpc_slice_hash_table* grpc_slice_hash_table_create( } grpc_slice_hash_table* grpc_slice_hash_table_ref(grpc_slice_hash_table* table) { - if (table != NULL) gpr_ref(&table->refs); + if (table != nullptr) gpr_ref(&table->refs); return table; } void grpc_slice_hash_table_unref(grpc_exec_ctx* exec_ctx, grpc_slice_hash_table* table) { - if (table != NULL && gpr_unref(&table->refs)) { + if (table != nullptr && gpr_unref(&table->refs)) { for (size_t i = 0; i < table->size; ++i) { grpc_slice_hash_table_entry* entry = &table->entries[i]; if (!is_empty(entry)) { @@ -108,16 +108,16 @@ void* grpc_slice_hash_table_get(const grpc_slice_hash_table* table, return table->entries[idx].value; } } - return NULL; // Not found. + return nullptr; // Not found. } static int pointer_cmp(void* a, void* b) { return GPR_ICMP(a, b); } int grpc_slice_hash_table_cmp(const grpc_slice_hash_table* a, const grpc_slice_hash_table* b) { int (*const value_cmp_fn_a)(void* a, void* b) = - a->value_cmp != NULL ? a->value_cmp : pointer_cmp; + a->value_cmp != nullptr ? a->value_cmp : pointer_cmp; int (*const value_cmp_fn_b)(void* a, void* b) = - b->value_cmp != NULL ? b->value_cmp : pointer_cmp; + b->value_cmp != nullptr ? b->value_cmp : pointer_cmp; // Compare value_fns const int value_fns_cmp = GPR_ICMP((void*)value_cmp_fn_a, (void*)value_cmp_fn_b); diff --git a/src/core/lib/slice/slice_hash_table.h b/src/core/lib/slice/slice_hash_table.h index 41250df7385..85102bd67d7 100644 --- a/src/core/lib/slice/slice_hash_table.h +++ b/src/core/lib/slice/slice_hash_table.h @@ -19,10 +19,6 @@ #include "src/core/lib/transport/metadata.h" -#ifdef __cplusplus -extern "C" { -#endif - /** Hash table implementation. * * This implementation uses open addressing @@ -39,7 +35,7 @@ typedef struct grpc_slice_hash_table grpc_slice_hash_table; typedef struct grpc_slice_hash_table_entry { grpc_slice key; - void *value; /* Must not be NULL. */ + void* value; /* Must not be NULL. */ } grpc_slice_hash_table_entry; /** Creates a new hash table of containing \a entries, which is an array @@ -48,18 +44,18 @@ typedef struct grpc_slice_hash_table_entry { value_cmp will be used to compare values in the context of \a grpc_slice_hash_table_cmp. If NULL, raw pointer (\a GPR_ICMP) comparison will be used. */ -grpc_slice_hash_table *grpc_slice_hash_table_create( - size_t num_entries, grpc_slice_hash_table_entry *entries, - void (*destroy_value)(grpc_exec_ctx *exec_ctx, void *value), - int (*value_cmp)(void *a, void *b)); +grpc_slice_hash_table* grpc_slice_hash_table_create( + size_t num_entries, grpc_slice_hash_table_entry* entries, + void (*destroy_value)(grpc_exec_ctx* exec_ctx, void* value), + int (*value_cmp)(void* a, void* b)); -grpc_slice_hash_table *grpc_slice_hash_table_ref(grpc_slice_hash_table *table); -void grpc_slice_hash_table_unref(grpc_exec_ctx *exec_ctx, - grpc_slice_hash_table *table); +grpc_slice_hash_table* grpc_slice_hash_table_ref(grpc_slice_hash_table* table); +void grpc_slice_hash_table_unref(grpc_exec_ctx* exec_ctx, + grpc_slice_hash_table* table); /** Returns the value from \a table associated with \a key. Returns NULL if \a key is not found. */ -void *grpc_slice_hash_table_get(const grpc_slice_hash_table *table, +void* grpc_slice_hash_table_get(const grpc_slice_hash_table* table, const grpc_slice key); /** Compares \a a vs. \a b. @@ -68,11 +64,7 @@ void *grpc_slice_hash_table_get(const grpc_slice_hash_table *table, * - else, it contains fewer (resp. more) entries, * - else, if strcmp(a_key, b_key) < 1 (resp. > 1), * - else, if value_cmp(a_value, b_value) < 1 (resp. > 1). */ -int grpc_slice_hash_table_cmp(const grpc_slice_hash_table *a, - const grpc_slice_hash_table *b); - -#ifdef __cplusplus -} -#endif +int grpc_slice_hash_table_cmp(const grpc_slice_hash_table* a, + const grpc_slice_hash_table* b); #endif /* GRPC_CORE_LIB_SLICE_SLICE_HASH_TABLE_H */ diff --git a/src/core/lib/slice/slice_intern.cc b/src/core/lib/slice/slice_intern.cc index 1ea9a2aa677..e8949135c08 100644 --- a/src/core/lib/slice/slice_intern.cc +++ b/src/core/lib/slice/slice_intern.cc @@ -43,12 +43,12 @@ typedef struct interned_slice_refcount { size_t length; gpr_atm refcnt; uint32_t hash; - struct interned_slice_refcount *bucket_next; + struct interned_slice_refcount* bucket_next; } interned_slice_refcount; typedef struct slice_shard { gpr_mu mu; - interned_slice_refcount **strs; + interned_slice_refcount** strs; size_t count; size_t capacity; } slice_shard; @@ -69,17 +69,17 @@ static static_metadata_hash_ent static uint32_t max_static_metadata_hash_probe; static uint32_t static_metadata_hash_values[GRPC_STATIC_MDSTR_COUNT]; -static void interned_slice_ref(void *p) { - interned_slice_refcount *s = (interned_slice_refcount *)p; +static void interned_slice_ref(void* p) { + interned_slice_refcount* s = (interned_slice_refcount*)p; GPR_ASSERT(gpr_atm_no_barrier_fetch_add(&s->refcnt, 1) > 0); } -static void interned_slice_destroy(interned_slice_refcount *s) { - slice_shard *shard = &g_shards[SHARD_IDX(s->hash)]; +static void interned_slice_destroy(interned_slice_refcount* s) { + slice_shard* shard = &g_shards[SHARD_IDX(s->hash)]; gpr_mu_lock(&shard->mu); GPR_ASSERT(0 == gpr_atm_no_barrier_load(&s->refcnt)); - interned_slice_refcount **prev_next; - interned_slice_refcount *cur; + interned_slice_refcount** prev_next; + interned_slice_refcount* cur; for (prev_next = &shard->strs[TABLE_IDX(s->hash, shard->capacity)], cur = *prev_next; cur != s; prev_next = &cur->bucket_next, cur = cur->bucket_next) @@ -90,24 +90,24 @@ static void interned_slice_destroy(interned_slice_refcount *s) { gpr_mu_unlock(&shard->mu); } -static void interned_slice_unref(grpc_exec_ctx *exec_ctx, void *p) { - interned_slice_refcount *s = (interned_slice_refcount *)p; +static void interned_slice_unref(grpc_exec_ctx* exec_ctx, void* p) { + interned_slice_refcount* s = (interned_slice_refcount*)p; if (1 == gpr_atm_full_fetch_add(&s->refcnt, -1)) { interned_slice_destroy(s); } } -static void interned_slice_sub_ref(void *p) { - interned_slice_ref(((char *)p) - offsetof(interned_slice_refcount, sub)); +static void interned_slice_sub_ref(void* p) { + interned_slice_ref(((char*)p) - offsetof(interned_slice_refcount, sub)); } -static void interned_slice_sub_unref(grpc_exec_ctx *exec_ctx, void *p) { +static void interned_slice_sub_unref(grpc_exec_ctx* exec_ctx, void* p) { interned_slice_unref(exec_ctx, - ((char *)p) - offsetof(interned_slice_refcount, sub)); + ((char*)p) - offsetof(interned_slice_refcount, sub)); } static uint32_t interned_slice_hash(grpc_slice slice) { - interned_slice_refcount *s = (interned_slice_refcount *)slice.refcount; + interned_slice_refcount* s = (interned_slice_refcount*)slice.refcount; return s->hash; } @@ -122,16 +122,16 @@ static const grpc_slice_refcount_vtable interned_slice_sub_vtable = { interned_slice_sub_ref, interned_slice_sub_unref, grpc_slice_default_eq_impl, grpc_slice_default_hash_impl}; -static void grow_shard(slice_shard *shard) { +static void grow_shard(slice_shard* shard) { size_t capacity = shard->capacity * 2; size_t i; - interned_slice_refcount **strtab; + interned_slice_refcount** strtab; interned_slice_refcount *s, *next; GPR_TIMER_BEGIN("grow_strtab", 0); - strtab = (interned_slice_refcount **)gpr_zalloc( - sizeof(interned_slice_refcount *) * capacity); + strtab = (interned_slice_refcount**)gpr_zalloc( + sizeof(interned_slice_refcount*) * capacity); for (i = 0; i < shard->capacity; i++) { for (s = shard->strs[i]; s; s = next) { @@ -149,10 +149,10 @@ static void grow_shard(slice_shard *shard) { GPR_TIMER_END("grow_strtab", 0); } -static grpc_slice materialize(interned_slice_refcount *s) { +static grpc_slice materialize(interned_slice_refcount* s) { grpc_slice slice; slice.refcount = &s->base; - slice.data.refcounted.bytes = (uint8_t *)(s + 1); + slice.data.refcounted.bytes = (uint8_t*)(s + 1); slice.data.refcounted.length = s->length; return slice; } @@ -171,12 +171,12 @@ int grpc_static_slice_eq(grpc_slice a, grpc_slice b) { } uint32_t grpc_slice_hash(grpc_slice s) { - return s.refcount == NULL ? grpc_slice_default_hash_impl(s) - : s.refcount->vtable->hash(s); + return s.refcount == nullptr ? grpc_slice_default_hash_impl(s) + : s.refcount->vtable->hash(s); } grpc_slice grpc_slice_maybe_static_intern(grpc_slice slice, - bool *returned_slice_is_different) { + bool* returned_slice_is_different) { if (GRPC_IS_STATIC_METADATA_STRING(slice)) { return slice; } @@ -218,8 +218,8 @@ grpc_slice grpc_slice_intern(grpc_slice slice) { } } - interned_slice_refcount *s; - slice_shard *shard = &g_shards[SHARD_IDX(hash)]; + interned_slice_refcount* s; + slice_shard* shard = &g_shards[SHARD_IDX(hash)]; gpr_mu_lock(&shard->mu); @@ -244,8 +244,8 @@ grpc_slice grpc_slice_intern(grpc_slice slice) { /* not found: create a new string */ /* string data goes after the internal_string header */ - s = (interned_slice_refcount *)gpr_malloc(sizeof(*s) + - GRPC_SLICE_LENGTH(slice)); + s = (interned_slice_refcount*)gpr_malloc(sizeof(*s) + + GRPC_SLICE_LENGTH(slice)); gpr_atm_rel_store(&s->refcnt, 1); s->length = GRPC_SLICE_LENGTH(slice); s->hash = hash; @@ -279,12 +279,12 @@ void grpc_slice_intern_init(void) { g_hash_seed = (uint32_t)gpr_now(GPR_CLOCK_REALTIME).tv_nsec; } for (size_t i = 0; i < SHARD_COUNT; i++) { - slice_shard *shard = &g_shards[i]; + slice_shard* shard = &g_shards[i]; gpr_mu_init(&shard->mu); shard->count = 0; shard->capacity = INITIAL_SHARD_CAPACITY; - shard->strs = (interned_slice_refcount **)gpr_zalloc(sizeof(*shard->strs) * - shard->capacity); + shard->strs = (interned_slice_refcount**)gpr_zalloc(sizeof(*shard->strs) * + shard->capacity); } for (size_t i = 0; i < GPR_ARRAY_SIZE(static_metadata_hash); i++) { static_metadata_hash[i].hash = 0; @@ -311,16 +311,16 @@ void grpc_slice_intern_init(void) { void grpc_slice_intern_shutdown(void) { for (size_t i = 0; i < SHARD_COUNT; i++) { - slice_shard *shard = &g_shards[i]; + slice_shard* shard = &g_shards[i]; gpr_mu_destroy(&shard->mu); /* TODO(ctiller): GPR_ASSERT(shard->count == 0); */ if (shard->count != 0) { gpr_log(GPR_DEBUG, "WARNING: %" PRIuPTR " metadata strings were leaked", shard->count); for (size_t j = 0; j < shard->capacity; j++) { - for (interned_slice_refcount *s = shard->strs[j]; s; + for (interned_slice_refcount* s = shard->strs[j]; s; s = s->bucket_next) { - char *text = + char* text = grpc_dump_slice(materialize(s), GPR_DUMP_HEX | GPR_DUMP_ASCII); gpr_log(GPR_DEBUG, "LEAKED: %s", text); gpr_free(text); diff --git a/src/core/lib/slice/slice_internal.h b/src/core/lib/slice/slice_internal.h index fcf70a0e55f..ed0070d375c 100644 --- a/src/core/lib/slice/slice_internal.h +++ b/src/core/lib/slice/slice_internal.h @@ -24,16 +24,15 @@ #include "src/core/lib/iomgr/exec_ctx.h" -#ifdef __cplusplus -extern "C" { -#endif - grpc_slice grpc_slice_ref_internal(grpc_slice slice); -void grpc_slice_unref_internal(grpc_exec_ctx *exec_ctx, grpc_slice slice); -void grpc_slice_buffer_reset_and_unref_internal(grpc_exec_ctx *exec_ctx, - grpc_slice_buffer *sb); -void grpc_slice_buffer_destroy_internal(grpc_exec_ctx *exec_ctx, - grpc_slice_buffer *sb); +void grpc_slice_unref_internal(grpc_exec_ctx* exec_ctx, grpc_slice slice); +void grpc_slice_buffer_reset_and_unref_internal(grpc_exec_ctx* exec_ctx, + grpc_slice_buffer* sb); +void grpc_slice_buffer_partial_unref_internal(grpc_exec_ctx* exec_ctx, + grpc_slice_buffer* sb, + size_t idx); +void grpc_slice_buffer_destroy_internal(grpc_exec_ctx* exec_ctx, + grpc_slice_buffer* sb); /* Check if a slice is interned */ bool grpc_slice_is_interned(grpc_slice slice); @@ -46,12 +45,8 @@ void grpc_test_only_set_slice_hash_seed(uint32_t key); // used for surface boundaries where we might receive an un-interned static // string grpc_slice grpc_slice_maybe_static_intern(grpc_slice slice, - bool *returned_slice_is_different); + bool* returned_slice_is_different); uint32_t grpc_static_slice_hash(grpc_slice s); int grpc_static_slice_eq(grpc_slice a, grpc_slice b); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SLICE_SLICE_INTERNAL_H */ diff --git a/src/core/lib/slice/slice_string_helpers.cc b/src/core/lib/slice/slice_string_helpers.cc index d461c474d2c..5385be9866b 100644 --- a/src/core/lib/slice/slice_string_helpers.cc +++ b/src/core/lib/slice/slice_string_helpers.cc @@ -25,8 +25,8 @@ #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/support/string.h" -char *grpc_dump_slice(grpc_slice s, uint32_t flags) { - return gpr_dump((const char *)GRPC_SLICE_START_PTR(s), GRPC_SLICE_LENGTH(s), +char* grpc_dump_slice(grpc_slice s, uint32_t flags) { + return gpr_dump((const char*)GRPC_SLICE_START_PTR(s), GRPC_SLICE_LENGTH(s), flags); } @@ -35,11 +35,11 @@ char *grpc_dump_slice(grpc_slice s, uint32_t flags) { * str. * * Returns 1 and updates \a begin and \a end. Returns 0 otherwise. */ -static int slice_find_separator_offset(const grpc_slice str, const char *sep, - const size_t read_offset, size_t *begin, - size_t *end) { +static int slice_find_separator_offset(const grpc_slice str, const char* sep, + const size_t read_offset, size_t* begin, + size_t* end) { size_t i; - const uint8_t *str_ptr = GRPC_SLICE_START_PTR(str) + read_offset; + const uint8_t* str_ptr = GRPC_SLICE_START_PTR(str) + read_offset; const size_t str_len = GRPC_SLICE_LENGTH(str) - read_offset; const size_t sep_len = strlen(sep); if (str_len < sep_len) { @@ -56,7 +56,7 @@ static int slice_find_separator_offset(const grpc_slice str, const char *sep, return 0; } -void grpc_slice_split(grpc_slice str, const char *sep, grpc_slice_buffer *dst) { +void grpc_slice_split(grpc_slice str, const char* sep, grpc_slice_buffer* dst) { const size_t sep_len = strlen(sep); size_t begin, end; @@ -74,7 +74,7 @@ void grpc_slice_split(grpc_slice str, const char *sep, grpc_slice_buffer *dst) { } } -bool grpc_parse_slice_to_uint32(grpc_slice str, uint32_t *result) { - return gpr_parse_bytes_to_uint32((const char *)GRPC_SLICE_START_PTR(str), +bool grpc_parse_slice_to_uint32(grpc_slice str, uint32_t* result) { + return gpr_parse_bytes_to_uint32((const char*)GRPC_SLICE_START_PTR(str), GRPC_SLICE_LENGTH(str), result) != 0; } diff --git a/src/core/lib/slice/slice_string_helpers.h b/src/core/lib/slice/slice_string_helpers.h index bcfb33bfb3a..7f51b11b9cf 100644 --- a/src/core/lib/slice/slice_string_helpers.h +++ b/src/core/lib/slice/slice_string_helpers.h @@ -28,21 +28,13 @@ #include "src/core/lib/support/string.h" -#ifdef __cplusplus -extern "C" { -#endif - /* Calls gpr_dump on a slice. */ -char *grpc_dump_slice(grpc_slice slice, uint32_t flags); +char* grpc_dump_slice(grpc_slice slice, uint32_t flags); /** Split \a str by the separator \a sep. Results are stored in \a dst, which * should be a properly initialized instance. */ -void grpc_slice_split(grpc_slice str, const char *sep, grpc_slice_buffer *dst); - -bool grpc_parse_slice_to_uint32(grpc_slice str, uint32_t *result); +void grpc_slice_split(grpc_slice str, const char* sep, grpc_slice_buffer* dst); -#ifdef __cplusplus -} -#endif +bool grpc_parse_slice_to_uint32(grpc_slice str, uint32_t* result); #endif /* GRPC_CORE_LIB_SLICE_SLICE_STRING_HELPERS_H */ diff --git a/src/core/lib/slice/slice_traits.h b/src/core/lib/slice/slice_traits.h index 7fdb6752cb4..4b898bdcd46 100644 --- a/src/core/lib/slice/slice_traits.h +++ b/src/core/lib/slice/slice_traits.h @@ -22,16 +22,8 @@ #include #include -#ifdef __cplusplus -extern "C" { -#endif - bool grpc_slice_is_legal_header(grpc_slice s); bool grpc_slice_is_legal_nonbin_header(grpc_slice s); bool grpc_slice_is_bin_suffixed(grpc_slice s); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SLICE_SLICE_TRAITS_H */ diff --git a/src/node/ext/slice.h b/src/core/lib/support/abstract.h similarity index 50% rename from src/node/ext/slice.h rename to src/core/lib/support/abstract.h index 0a652c57554..5498769a7d9 100644 --- a/src/node/ext/slice.h +++ b/src/core/lib/support/abstract.h @@ -1,6 +1,6 @@ /* * - * Copyright 2016 gRPC authors. + * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,23 +16,14 @@ * */ -#include -#include -#include +#ifndef GRPC_CORE_LIB_SUPPORT_ABSTRACT_H +#define GRPC_CORE_LIB_SUPPORT_ABSTRACT_H -namespace grpc { -namespace node { +// This is needed to support abstract base classes in the c core. Since gRPC +// doesn't have a c++ runtime, it will hit a linker error on delete unless +// we define a virtual operator delete. See this blog for more info: +// https://eli.thegreenplace.net/2015/c-deleting-destructors-and-virtual-operator-delete/ +#define GRPC_ABSTRACT_BASE_CLASS \ + static void operator delete(void* p) { abort(); } -typedef Nan::Persistent> - PersistentValue; - -grpc_slice CreateSliceFromString(const v8::Local source); - -grpc_slice CreateSliceFromBuffer(const v8::Local source); - -v8::Local CopyStringFromSlice(const grpc_slice slice); - -v8::Local CreateBufferFromSlice(const grpc_slice slice); - -} // namespace node -} // namespace grpc +#endif /* GRPC_CORE_LIB_SUPPORT_ABSTRACT_H */ diff --git a/src/core/lib/support/alloc.cc b/src/core/lib/support/alloc.cc index 886d69d64c3..518bdb99f74 100644 --- a/src/core/lib/support/alloc.cc +++ b/src/core/lib/support/alloc.cc @@ -24,10 +24,10 @@ #include #include "src/core/lib/profiling/timers.h" -static void *zalloc_with_calloc(size_t sz) { return calloc(sz, 1); } +static void* zalloc_with_calloc(size_t sz) { return calloc(sz, 1); } -static void *zalloc_with_gpr_malloc(size_t sz) { - void *p = gpr_malloc(sz); +static void* zalloc_with_gpr_malloc(size_t sz) { + void* p = gpr_malloc(sz); memset(p, 0, sz); return p; } @@ -40,18 +40,18 @@ gpr_allocation_functions gpr_get_allocation_functions() { } void gpr_set_allocation_functions(gpr_allocation_functions functions) { - GPR_ASSERT(functions.malloc_fn != NULL); - GPR_ASSERT(functions.realloc_fn != NULL); - GPR_ASSERT(functions.free_fn != NULL); - if (functions.zalloc_fn == NULL) { + GPR_ASSERT(functions.malloc_fn != nullptr); + GPR_ASSERT(functions.realloc_fn != nullptr); + GPR_ASSERT(functions.free_fn != nullptr); + if (functions.zalloc_fn == nullptr) { functions.zalloc_fn = zalloc_with_gpr_malloc; } g_alloc_functions = functions; } -void *gpr_malloc(size_t size) { - void *p; - if (size == 0) return NULL; +void* gpr_malloc(size_t size) { + void* p; + if (size == 0) return nullptr; GPR_TIMER_BEGIN("gpr_malloc", 0); p = g_alloc_functions.malloc_fn(size); if (!p) { @@ -61,9 +61,9 @@ void *gpr_malloc(size_t size) { return p; } -void *gpr_zalloc(size_t size) { - void *p; - if (size == 0) return NULL; +void* gpr_zalloc(size_t size) { + void* p; + if (size == 0) return nullptr; GPR_TIMER_BEGIN("gpr_zalloc", 0); p = g_alloc_functions.zalloc_fn(size); if (!p) { @@ -73,14 +73,14 @@ void *gpr_zalloc(size_t size) { return p; } -void gpr_free(void *p) { +void gpr_free(void* p) { GPR_TIMER_BEGIN("gpr_free", 0); g_alloc_functions.free_fn(p); GPR_TIMER_END("gpr_free", 0); } -void *gpr_realloc(void *p, size_t size) { - if ((size == 0) && (p == NULL)) return NULL; +void* gpr_realloc(void* p, size_t size) { + if ((size == 0) && (p == nullptr)) return nullptr; GPR_TIMER_BEGIN("gpr_realloc", 0); p = g_alloc_functions.realloc_fn(p, size); if (!p) { @@ -90,13 +90,13 @@ void *gpr_realloc(void *p, size_t size) { return p; } -void *gpr_malloc_aligned(size_t size, size_t alignment_log) { +void* gpr_malloc_aligned(size_t size, size_t alignment_log) { size_t alignment = ((size_t)1) << alignment_log; - size_t extra = alignment - 1 + sizeof(void *); - void *p = gpr_malloc(size + extra); - void **ret = (void **)(((uintptr_t)p + extra) & ~(alignment - 1)); + 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; + return (void*)ret; } -void gpr_free_aligned(void *ptr) { gpr_free(((void **)ptr)[-1]); } +void gpr_free_aligned(void* ptr) { gpr_free(((void**)ptr)[-1]); } diff --git a/src/core/lib/support/arena.cc b/src/core/lib/support/arena.cc index 9e0f73ae3d8..5b9dd370d84 100644 --- a/src/core/lib/support/arena.cc +++ b/src/core/lib/support/arena.cc @@ -36,40 +36,40 @@ struct gpr_arena { zone initial_zone; }; -gpr_arena *gpr_arena_create(size_t initial_size) { +gpr_arena* gpr_arena_create(size_t initial_size) { initial_size = ROUND_UP_TO_ALIGNMENT_SIZE(initial_size); - gpr_arena *a = (gpr_arena *)gpr_zalloc(sizeof(gpr_arena) + initial_size); + gpr_arena* a = (gpr_arena*)gpr_zalloc(sizeof(gpr_arena) + initial_size); a->initial_zone.size_end = initial_size; return a; } -size_t gpr_arena_destroy(gpr_arena *arena) { +size_t gpr_arena_destroy(gpr_arena* arena) { gpr_atm size = gpr_atm_no_barrier_load(&arena->size_so_far); - zone *z = (zone *)gpr_atm_no_barrier_load(&arena->initial_zone.next_atm); + zone* z = (zone*)gpr_atm_no_barrier_load(&arena->initial_zone.next_atm); gpr_free(arena); while (z) { - zone *next_z = (zone *)gpr_atm_no_barrier_load(&z->next_atm); + zone* next_z = (zone*)gpr_atm_no_barrier_load(&z->next_atm); gpr_free(z); z = next_z; } return (size_t)size; } -void *gpr_arena_alloc(gpr_arena *arena, size_t size) { +void* gpr_arena_alloc(gpr_arena* arena, size_t size) { size = ROUND_UP_TO_ALIGNMENT_SIZE(size); size_t start = (size_t)gpr_atm_no_barrier_fetch_add(&arena->size_so_far, size); - zone *z = &arena->initial_zone; + zone* z = &arena->initial_zone; while (start > z->size_end) { - zone *next_z = (zone *)gpr_atm_acq_load(&z->next_atm); - if (next_z == NULL) { + zone* next_z = (zone*)gpr_atm_acq_load(&z->next_atm); + if (next_z == nullptr) { size_t next_z_size = (size_t)gpr_atm_no_barrier_load(&arena->size_so_far); - next_z = (zone *)gpr_zalloc(sizeof(zone) + next_z_size); + next_z = (zone*)gpr_zalloc(sizeof(zone) + next_z_size); next_z->size_begin = z->size_end; next_z->size_end = z->size_end + next_z_size; if (!gpr_atm_rel_cas(&z->next_atm, (gpr_atm)NULL, (gpr_atm)next_z)) { gpr_free(next_z); - next_z = (zone *)gpr_atm_acq_load(&z->next_atm); + next_z = (zone*)gpr_atm_acq_load(&z->next_atm); } } z = next_z; @@ -79,5 +79,5 @@ void *gpr_arena_alloc(gpr_arena *arena, size_t size) { } GPR_ASSERT(start >= z->size_begin); GPR_ASSERT(start + size <= z->size_end); - return ((char *)(z + 1)) + start - z->size_begin; + return ((char*)(z + 1)) + start - z->size_begin; } diff --git a/src/core/lib/support/arena.h b/src/core/lib/support/arena.h index 8a50786348c..cfe973a0368 100644 --- a/src/core/lib/support/arena.h +++ b/src/core/lib/support/arena.h @@ -27,21 +27,13 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - typedef struct gpr_arena gpr_arena; // Create an arena, with \a initial_size bytes in the first allocated buffer -gpr_arena *gpr_arena_create(size_t initial_size); +gpr_arena* gpr_arena_create(size_t initial_size); // Allocate \a size bytes from the arena -void *gpr_arena_alloc(gpr_arena *arena, size_t size); +void* gpr_arena_alloc(gpr_arena* arena, size_t size); // Destroy an arena, returning the total number of bytes allocated -size_t gpr_arena_destroy(gpr_arena *arena); - -#ifdef __cplusplus -} -#endif +size_t gpr_arena_destroy(gpr_arena* arena); #endif /* GRPC_CORE_LIB_SUPPORT_ARENA_H */ diff --git a/src/core/lib/support/atm.cc b/src/core/lib/support/atm.cc index 2f37d62f764..15bfe52d64d 100644 --- a/src/core/lib/support/atm.cc +++ b/src/core/lib/support/atm.cc @@ -19,7 +19,7 @@ #include #include -gpr_atm gpr_atm_no_barrier_clamped_add(gpr_atm *value, gpr_atm delta, +gpr_atm gpr_atm_no_barrier_clamped_add(gpr_atm* value, gpr_atm delta, gpr_atm min, gpr_atm max) { gpr_atm current_value; gpr_atm new_value; diff --git a/src/core/lib/support/avl.cc b/src/core/lib/support/avl.cc index 0e28b24c98e..0b67a21f2f8 100644 --- a/src/core/lib/support/avl.cc +++ b/src/core/lib/support/avl.cc @@ -25,23 +25,23 @@ #include #include -gpr_avl gpr_avl_create(const gpr_avl_vtable *vtable) { +gpr_avl gpr_avl_create(const gpr_avl_vtable* vtable) { gpr_avl out; out.vtable = vtable; - out.root = NULL; + out.root = nullptr; return out; } -static gpr_avl_node *ref_node(gpr_avl_node *node) { +static gpr_avl_node* ref_node(gpr_avl_node* node) { if (node) { gpr_ref(&node->refs); } return node; } -static void unref_node(const gpr_avl_vtable *vtable, gpr_avl_node *node, - void *user_data) { - if (node == NULL) { +static void unref_node(const gpr_avl_vtable* vtable, gpr_avl_node* node, + void* user_data) { + if (node == nullptr) { return; } if (gpr_unref(&node->refs)) { @@ -53,18 +53,19 @@ static void unref_node(const gpr_avl_vtable *vtable, gpr_avl_node *node, } } -static long node_height(gpr_avl_node *node) { - return node == NULL ? 0 : node->height; +static long node_height(gpr_avl_node* node) { + return node == nullptr ? 0 : node->height; } #ifndef NDEBUG -static long calculate_height(gpr_avl_node *node) { - return node == NULL ? 0 : 1 + GPR_MAX(calculate_height(node->left), - calculate_height(node->right)); +static long calculate_height(gpr_avl_node* node) { + return node == nullptr ? 0 + : 1 + GPR_MAX(calculate_height(node->left), + calculate_height(node->right)); } -static gpr_avl_node *assert_invariants(gpr_avl_node *n) { - if (n == NULL) return NULL; +static gpr_avl_node* assert_invariants(gpr_avl_node* n) { + if (n == nullptr) return nullptr; assert_invariants(n->left); assert_invariants(n->right); assert(calculate_height(n) == n->height); @@ -72,12 +73,12 @@ static gpr_avl_node *assert_invariants(gpr_avl_node *n) { return n; } #else -static gpr_avl_node *assert_invariants(gpr_avl_node *n) { return n; } +static gpr_avl_node* assert_invariants(gpr_avl_node* n) { return n; } #endif -gpr_avl_node *new_node(void *key, void *value, gpr_avl_node *left, - gpr_avl_node *right) { - gpr_avl_node *node = (gpr_avl_node *)gpr_malloc(sizeof(*node)); +gpr_avl_node* new_node(void* key, void* value, gpr_avl_node* left, + gpr_avl_node* right) { + gpr_avl_node* node = (gpr_avl_node*)gpr_malloc(sizeof(*node)); gpr_ref_init(&node->refs, 1); node->key = key; node->value = value; @@ -87,12 +88,12 @@ gpr_avl_node *new_node(void *key, void *value, gpr_avl_node *left, return node; } -static gpr_avl_node *get(const gpr_avl_vtable *vtable, gpr_avl_node *node, - void *key, void *user_data) { +static gpr_avl_node* get(const gpr_avl_vtable* vtable, gpr_avl_node* node, + void* key, void* user_data) { long cmp; - if (node == NULL) { - return NULL; + if (node == nullptr) { + return nullptr; } cmp = vtable->compare_keys(node->key, key, user_data); @@ -105,24 +106,24 @@ static gpr_avl_node *get(const gpr_avl_vtable *vtable, gpr_avl_node *node, } } -void *gpr_avl_get(gpr_avl avl, void *key, void *user_data) { - gpr_avl_node *node = get(avl.vtable, avl.root, key, user_data); - return node ? node->value : NULL; +void* gpr_avl_get(gpr_avl avl, void* key, void* user_data) { + gpr_avl_node* node = get(avl.vtable, avl.root, key, user_data); + return node ? node->value : nullptr; } -int gpr_avl_maybe_get(gpr_avl avl, void *key, void **value, void *user_data) { - gpr_avl_node *node = get(avl.vtable, avl.root, key, user_data); - if (node != NULL) { +int gpr_avl_maybe_get(gpr_avl avl, void* key, void** value, void* user_data) { + gpr_avl_node* node = get(avl.vtable, avl.root, key, user_data); + if (node != nullptr) { *value = node->value; return 1; } return 0; } -static gpr_avl_node *rotate_left(const gpr_avl_vtable *vtable, void *key, - void *value, gpr_avl_node *left, - gpr_avl_node *right, void *user_data) { - gpr_avl_node *n = new_node(vtable->copy_key(right->key, user_data), +static gpr_avl_node* rotate_left(const gpr_avl_vtable* vtable, void* key, + void* value, gpr_avl_node* left, + gpr_avl_node* right, void* user_data) { + gpr_avl_node* n = new_node(vtable->copy_key(right->key, user_data), vtable->copy_value(right->value, user_data), new_node(key, value, left, ref_node(right->left)), ref_node(right->right)); @@ -130,10 +131,10 @@ static gpr_avl_node *rotate_left(const gpr_avl_vtable *vtable, void *key, return n; } -static gpr_avl_node *rotate_right(const gpr_avl_vtable *vtable, void *key, - void *value, gpr_avl_node *left, - gpr_avl_node *right, void *user_data) { - gpr_avl_node *n = +static gpr_avl_node* rotate_right(const gpr_avl_vtable* vtable, void* key, + void* value, gpr_avl_node* left, + gpr_avl_node* right, void* user_data) { + gpr_avl_node* n = new_node(vtable->copy_key(left->key, user_data), vtable->copy_value(left->value, user_data), ref_node(left->left), new_node(key, value, ref_node(left->right), right)); @@ -141,11 +142,11 @@ static gpr_avl_node *rotate_right(const gpr_avl_vtable *vtable, void *key, return n; } -static gpr_avl_node *rotate_left_right(const gpr_avl_vtable *vtable, void *key, - void *value, gpr_avl_node *left, - gpr_avl_node *right, void *user_data) { +static gpr_avl_node* rotate_left_right(const gpr_avl_vtable* vtable, void* key, + void* value, gpr_avl_node* left, + gpr_avl_node* right, void* user_data) { /* rotate_right(..., rotate_left(left), right) */ - gpr_avl_node *n = + gpr_avl_node* n = new_node(vtable->copy_key(left->right->key, user_data), vtable->copy_value(left->right->value, user_data), new_node(vtable->copy_key(left->key, user_data), @@ -156,11 +157,11 @@ static gpr_avl_node *rotate_left_right(const gpr_avl_vtable *vtable, void *key, return n; } -static gpr_avl_node *rotate_right_left(const gpr_avl_vtable *vtable, void *key, - void *value, gpr_avl_node *left, - gpr_avl_node *right, void *user_data) { +static gpr_avl_node* rotate_right_left(const gpr_avl_vtable* vtable, void* key, + void* value, gpr_avl_node* left, + gpr_avl_node* right, void* user_data) { /* rotate_left(..., left, rotate_right(right)) */ - gpr_avl_node *n = + gpr_avl_node* n = new_node(vtable->copy_key(right->left->key, user_data), vtable->copy_value(right->left->value, user_data), new_node(key, value, left, ref_node(right->left->left)), @@ -171,9 +172,9 @@ static gpr_avl_node *rotate_right_left(const gpr_avl_vtable *vtable, void *key, return n; } -static gpr_avl_node *rebalance(const gpr_avl_vtable *vtable, void *key, - void *value, gpr_avl_node *left, - gpr_avl_node *right, void *user_data) { +static gpr_avl_node* rebalance(const gpr_avl_vtable* vtable, void* key, + void* value, gpr_avl_node* left, + gpr_avl_node* right, void* user_data) { switch (node_height(left) - node_height(right)) { case 2: if (node_height(left->left) - node_height(left->right) == -1) { @@ -196,11 +197,11 @@ static gpr_avl_node *rebalance(const gpr_avl_vtable *vtable, void *key, } } -static gpr_avl_node *add_key(const gpr_avl_vtable *vtable, gpr_avl_node *node, - void *key, void *value, void *user_data) { +static gpr_avl_node* add_key(const gpr_avl_vtable* vtable, gpr_avl_node* node, + void* key, void* value, void* user_data) { long cmp; - if (node == NULL) { - return new_node(key, value, NULL, NULL); + if (node == nullptr) { + return new_node(key, value, nullptr, nullptr); } cmp = vtable->compare_keys(node->key, key, user_data); if (cmp == 0) { @@ -218,49 +219,49 @@ static gpr_avl_node *add_key(const gpr_avl_vtable *vtable, gpr_avl_node *node, } } -gpr_avl gpr_avl_add(gpr_avl avl, void *key, void *value, void *user_data) { - gpr_avl_node *old_root = avl.root; +gpr_avl gpr_avl_add(gpr_avl avl, void* key, void* value, void* user_data) { + gpr_avl_node* old_root = avl.root; avl.root = add_key(avl.vtable, avl.root, key, value, user_data); assert_invariants(avl.root); unref_node(avl.vtable, old_root, user_data); return avl; } -static gpr_avl_node *in_order_head(gpr_avl_node *node) { - while (node->left != NULL) { +static gpr_avl_node* in_order_head(gpr_avl_node* node) { + while (node->left != nullptr) { node = node->left; } return node; } -static gpr_avl_node *in_order_tail(gpr_avl_node *node) { - while (node->right != NULL) { +static gpr_avl_node* in_order_tail(gpr_avl_node* node) { + while (node->right != nullptr) { node = node->right; } return node; } -static gpr_avl_node *remove_key(const gpr_avl_vtable *vtable, - gpr_avl_node *node, void *key, - void *user_data) { +static gpr_avl_node* remove_key(const gpr_avl_vtable* vtable, + gpr_avl_node* node, void* key, + void* user_data) { long cmp; - if (node == NULL) { - return NULL; + if (node == nullptr) { + return nullptr; } cmp = vtable->compare_keys(node->key, key, user_data); if (cmp == 0) { - if (node->left == NULL) { + if (node->left == nullptr) { return ref_node(node->right); - } else if (node->right == NULL) { + } else if (node->right == nullptr) { return ref_node(node->left); } else if (node->left->height < node->right->height) { - gpr_avl_node *h = in_order_head(node->right); + gpr_avl_node* h = in_order_head(node->right); return rebalance( vtable, vtable->copy_key(h->key, user_data), vtable->copy_value(h->value, user_data), ref_node(node->left), remove_key(vtable, node->right, h->key, user_data), user_data); } else { - gpr_avl_node *h = in_order_tail(node->left); + gpr_avl_node* h = in_order_tail(node->left); return rebalance(vtable, vtable->copy_key(h->key, user_data), vtable->copy_value(h->value, user_data), remove_key(vtable, node->left, h->key, user_data), @@ -279,21 +280,21 @@ static gpr_avl_node *remove_key(const gpr_avl_vtable *vtable, } } -gpr_avl gpr_avl_remove(gpr_avl avl, void *key, void *user_data) { - gpr_avl_node *old_root = avl.root; +gpr_avl gpr_avl_remove(gpr_avl avl, void* key, void* user_data) { + gpr_avl_node* old_root = avl.root; avl.root = remove_key(avl.vtable, avl.root, key, user_data); assert_invariants(avl.root); unref_node(avl.vtable, old_root, user_data); return avl; } -gpr_avl gpr_avl_ref(gpr_avl avl, void *user_data) { +gpr_avl gpr_avl_ref(gpr_avl avl, void* user_data) { ref_node(avl.root); return avl; } -void gpr_avl_unref(gpr_avl avl, void *user_data) { +void gpr_avl_unref(gpr_avl avl, void* user_data) { unref_node(avl.vtable, avl.root, user_data); } -int gpr_avl_is_empty(gpr_avl avl) { return avl.root == NULL; } +int gpr_avl_is_empty(gpr_avl avl) { return avl.root == nullptr; } diff --git a/src/core/lib/support/cmdline.cc b/src/core/lib/support/cmdline.cc index 9fb80d44602..da9f10a4963 100644 --- a/src/core/lib/support/cmdline.cc +++ b/src/core/lib/support/cmdline.cc @@ -30,33 +30,33 @@ typedef enum { ARGTYPE_INT, ARGTYPE_BOOL, ARGTYPE_STRING } argtype; typedef struct arg { - const char *name; - const char *help; + const char* name; + const char* help; argtype type; - void *value; - struct arg *next; + void* value; + struct arg* next; } arg; struct gpr_cmdline { - const char *description; - arg *args; - const char *argv0; + const char* description; + arg* args; + const char* argv0; - const char *extra_arg_name; - const char *extra_arg_help; - void (*extra_arg)(void *user_data, const char *arg); - void *extra_arg_user_data; + const char* extra_arg_name; + const char* extra_arg_help; + void (*extra_arg)(void* user_data, const char* arg); + void* extra_arg_user_data; - int (*state)(gpr_cmdline *cl, char *arg); - arg *cur_arg; + int (*state)(gpr_cmdline* cl, char* arg); + arg* cur_arg; int survive_failure; }; -static int normal_state(gpr_cmdline *cl, char *arg); +static int normal_state(gpr_cmdline* cl, char* arg); -gpr_cmdline *gpr_cmdline_create(const char *description) { - gpr_cmdline *cl = (gpr_cmdline *)gpr_zalloc(sizeof(gpr_cmdline)); +gpr_cmdline* gpr_cmdline_create(const char* description) { + gpr_cmdline* cl = (gpr_cmdline*)gpr_zalloc(sizeof(gpr_cmdline)); cl->description = description; cl->state = normal_state; @@ -64,28 +64,28 @@ gpr_cmdline *gpr_cmdline_create(const char *description) { return cl; } -void gpr_cmdline_set_survive_failure(gpr_cmdline *cl) { +void gpr_cmdline_set_survive_failure(gpr_cmdline* cl) { cl->survive_failure = 1; } -void gpr_cmdline_destroy(gpr_cmdline *cl) { +void gpr_cmdline_destroy(gpr_cmdline* cl) { while (cl->args) { - arg *a = cl->args; + arg* a = cl->args; cl->args = a->next; gpr_free(a); } gpr_free(cl); } -static void add_arg(gpr_cmdline *cl, const char *name, const char *help, - argtype type, void *value) { - arg *a; +static void add_arg(gpr_cmdline* cl, const char* name, const char* help, + argtype type, void* value) { + arg* a; for (a = cl->args; a; a = a->next) { GPR_ASSERT(0 != strcmp(a->name, name)); } - a = (arg *)gpr_zalloc(sizeof(arg)); + a = (arg*)gpr_zalloc(sizeof(arg)); a->name = name; a->help = help; a->type = type; @@ -94,24 +94,24 @@ static void add_arg(gpr_cmdline *cl, const char *name, const char *help, cl->args = a; } -void gpr_cmdline_add_int(gpr_cmdline *cl, const char *name, const char *help, - int *value) { +void gpr_cmdline_add_int(gpr_cmdline* cl, const char* name, const char* help, + int* value) { add_arg(cl, name, help, ARGTYPE_INT, value); } -void gpr_cmdline_add_flag(gpr_cmdline *cl, const char *name, const char *help, - int *value) { +void gpr_cmdline_add_flag(gpr_cmdline* cl, const char* name, const char* help, + int* value) { add_arg(cl, name, help, ARGTYPE_BOOL, value); } -void gpr_cmdline_add_string(gpr_cmdline *cl, const char *name, const char *help, - char **value) { +void gpr_cmdline_add_string(gpr_cmdline* cl, const char* name, const char* help, + const char** value) { add_arg(cl, name, help, ARGTYPE_STRING, value); } void gpr_cmdline_on_extra_arg( - gpr_cmdline *cl, const char *name, const char *help, - void (*on_extra_arg)(void *user_data, const char *arg), void *user_data) { + gpr_cmdline* cl, const char* name, const char* help, + void (*on_extra_arg)(void* user_data, const char* arg), void* user_data) { GPR_ASSERT(!cl->extra_arg); GPR_ASSERT(on_extra_arg); @@ -124,8 +124,8 @@ void gpr_cmdline_on_extra_arg( /* recursively descend argument list, adding the last element to s first - so that arguments are added in the order they were added to the list by api calls */ -static void add_args_to_usage(gpr_strvec *s, arg *a) { - char *tmp; +static void add_args_to_usage(gpr_strvec* s, arg* a) { + char* tmp; if (!a) return; add_args_to_usage(s, a->next); @@ -146,11 +146,11 @@ static void add_args_to_usage(gpr_strvec *s, arg *a) { } } -char *gpr_cmdline_usage_string(gpr_cmdline *cl, const char *argv0) { +char* gpr_cmdline_usage_string(gpr_cmdline* cl, const char* argv0) { /* TODO(ctiller): make this prettier */ gpr_strvec s; - char *tmp; - const char *name = strrchr(argv0, '/'); + char* tmp; + const char* name = strrchr(argv0, '/'); if (name) { name++; @@ -169,13 +169,13 @@ char *gpr_cmdline_usage_string(gpr_cmdline *cl, const char *argv0) { } gpr_strvec_add(&s, gpr_strdup("\n")); - tmp = gpr_strvec_flatten(&s, NULL); + tmp = gpr_strvec_flatten(&s, nullptr); gpr_strvec_destroy(&s); return tmp; } -static int print_usage_and_die(gpr_cmdline *cl) { - char *usage = gpr_cmdline_usage_string(cl, cl->argv0); +static int print_usage_and_die(gpr_cmdline* cl) { + char* usage = gpr_cmdline_usage_string(cl, cl->argv0); fprintf(stderr, "%s", usage); gpr_free(usage); if (!cl->survive_failure) { @@ -184,7 +184,7 @@ static int print_usage_and_die(gpr_cmdline *cl) { return 0; } -static int extra_state(gpr_cmdline *cl, char *str) { +static int extra_state(gpr_cmdline* cl, char* str) { if (!cl->extra_arg) { return print_usage_and_die(cl); } @@ -192,8 +192,8 @@ static int extra_state(gpr_cmdline *cl, char *str) { return 1; } -static arg *find_arg(gpr_cmdline *cl, char *name) { - arg *a; +static arg* find_arg(gpr_cmdline* cl, char* name) { + arg* a; for (a = cl->args; a; a = a->next) { if (0 == strcmp(a->name, name)) { @@ -203,15 +203,15 @@ static arg *find_arg(gpr_cmdline *cl, char *name) { if (!a) { fprintf(stderr, "Unknown argument: %s\n", name); - return NULL; + return nullptr; } return a; } -static int value_state(gpr_cmdline *cl, char *str) { +static int value_state(gpr_cmdline* cl, char* str) { long intval; - char *end; + char* end; GPR_ASSERT(cl->cur_arg); @@ -223,13 +223,13 @@ static int value_state(gpr_cmdline *cl, char *str) { cl->cur_arg->name); return print_usage_and_die(cl); } - *(int *)cl->cur_arg->value = (int)intval; + *(int*)cl->cur_arg->value = (int)intval; break; case ARGTYPE_BOOL: if (0 == strcmp(str, "1") || 0 == strcmp(str, "true")) { - *(int *)cl->cur_arg->value = 1; + *(int*)cl->cur_arg->value = 1; } else if (0 == strcmp(str, "0") || 0 == strcmp(str, "false")) { - *(int *)cl->cur_arg->value = 0; + *(int*)cl->cur_arg->value = 0; } else { fprintf(stderr, "expected boolean, got '%s' for %s\n", str, cl->cur_arg->name); @@ -237,7 +237,7 @@ static int value_state(gpr_cmdline *cl, char *str) { } break; case ARGTYPE_STRING: - *(char **)cl->cur_arg->value = str; + *(char**)cl->cur_arg->value = str; break; } @@ -245,10 +245,10 @@ static int value_state(gpr_cmdline *cl, char *str) { return 1; } -static int normal_state(gpr_cmdline *cl, char *str) { - char *eq = NULL; - char *tmp = NULL; - char *arg_name = NULL; +static int normal_state(gpr_cmdline* cl, char* str) { + char* eq = nullptr; + char* tmp = nullptr; + char* arg_name = nullptr; int r = 1; if (0 == strcmp(str, "-help") || 0 == strcmp(str, "--help") || @@ -256,7 +256,7 @@ static int normal_state(gpr_cmdline *cl, char *str) { return print_usage_and_die(cl); } - cl->cur_arg = NULL; + cl->cur_arg = nullptr; if (str[0] == '-') { if (str[1] == '-') { @@ -274,30 +274,30 @@ static int normal_state(gpr_cmdline *cl, char *str) { /* str is of the form '--no-foo' - it's a flag disable */ str += 3; cl->cur_arg = find_arg(cl, str); - if (cl->cur_arg == NULL) { + if (cl->cur_arg == nullptr) { return print_usage_and_die(cl); } if (cl->cur_arg->type != ARGTYPE_BOOL) { fprintf(stderr, "%s is not a flag argument\n", str); return print_usage_and_die(cl); } - *(int *)cl->cur_arg->value = 0; + *(int*)cl->cur_arg->value = 0; return 1; /* early out */ } eq = strchr(str, '='); - if (eq != NULL) { + if (eq != nullptr) { /* copy the string into a temp buffer and extract the name */ - tmp = arg_name = (char *)gpr_malloc((size_t)(eq - str + 1)); + tmp = arg_name = (char*)gpr_malloc((size_t)(eq - str + 1)); memcpy(arg_name, str, (size_t)(eq - str)); arg_name[eq - str] = 0; } else { arg_name = str; } cl->cur_arg = find_arg(cl, arg_name); - if (cl->cur_arg == NULL) { + if (cl->cur_arg == nullptr) { return print_usage_and_die(cl); } - if (eq != NULL) { + if (eq != nullptr) { /* str was of the type --foo=value, parse the value */ r = value_state(cl, eq + 1); } else if (cl->cur_arg->type != ARGTYPE_BOOL) { @@ -305,7 +305,7 @@ static int normal_state(gpr_cmdline *cl, char *str) { cl->state = value_state; } else { /* flag parameter: just set the value */ - *(int *)cl->cur_arg->value = 1; + *(int*)cl->cur_arg->value = 1; } } else { r = extra_state(cl, str); @@ -315,7 +315,7 @@ static int normal_state(gpr_cmdline *cl, char *str) { return r; } -int gpr_cmdline_parse(gpr_cmdline *cl, int argc, char **argv) { +int gpr_cmdline_parse(gpr_cmdline* cl, int argc, char** argv) { int i; GPR_ASSERT(argc >= 1); diff --git a/src/core/lib/support/cpu_linux.cc b/src/core/lib/support/cpu_linux.cc index 22806684421..21b1a71dc92 100644 --- a/src/core/lib/support/cpu_linux.cc +++ b/src/core/lib/support/cpu_linux.cc @@ -36,6 +36,13 @@ static int ncpus = 0; static void init_num_cpus() { +#ifndef GPR_MUSL_LIBC_COMPAT + if (sched_getcpu() < 0) { + gpr_log(GPR_ERROR, "Error determining current CPU: %s\n", strerror(errno)); + ncpus = 1; + return; + } +#endif /* This must be signed. sysconf returns -1 when the number cannot be determined */ ncpus = (int)sysconf(_SC_NPROCESSORS_ONLN); @@ -56,6 +63,9 @@ unsigned gpr_cpu_current_cpu(void) { // sched_getcpu() is undefined on musl return 0; #else + if (gpr_cpu_num_cores() == 1) { + return 0; + } int cpu = sched_getcpu(); if (cpu < 0) { gpr_log(GPR_ERROR, "Error determining current CPU: %s\n", strerror(errno)); diff --git a/src/core/lib/support/cpu_posix.cc b/src/core/lib/support/cpu_posix.cc index 503a96b4c8a..bca14a0c121 100644 --- a/src/core/lib/support/cpu_posix.cc +++ b/src/core/lib/support/cpu_posix.cc @@ -18,21 +18,23 @@ #include -#ifdef GPR_CPU_POSIX +#if defined(GPR_CPU_POSIX) #include +#include #include #include +#include #include #include #include #include -static __thread char magic_thread_local; - static long ncpus = 0; +static pthread_key_t thread_id_key; + static void init_ncpus() { ncpus = sysconf(_SC_NPROCESSORS_ONLN); if (ncpus < 1 || ncpus > INT32_MAX) { @@ -47,12 +49,32 @@ unsigned gpr_cpu_num_cores(void) { return (unsigned)ncpus; } +static void delete_thread_id(void* value) { + if (value) { + gpr_free(value); + } +} + +static void init_thread_id_key(void) { + pthread_key_create(&thread_id_key, delete_thread_id); +} + unsigned gpr_cpu_current_cpu(void) { /* NOTE: there's no way I know to return the actual cpu index portably... most code that's using this is using it to shard across work queues though, so here we use thread identity instead to achieve a similar though not identical effect */ - return (unsigned)GPR_HASH_POINTER(&magic_thread_local, gpr_cpu_num_cores()); + static gpr_once once = GPR_ONCE_INIT; + gpr_once_init(&once, init_thread_id_key); + + unsigned int* thread_id = + static_cast(pthread_getspecific(thread_id_key)); + if (thread_id == nullptr) { + thread_id = static_cast(gpr_malloc(sizeof(unsigned int))); + pthread_setspecific(thread_id_key, thread_id); + } + + return (unsigned)GPR_HASH_POINTER(thread_id, gpr_cpu_num_cores()); } #endif /* GPR_CPU_POSIX */ diff --git a/src/core/lib/support/debug_location.h b/src/core/lib/support/debug_location.h new file mode 100644 index 00000000000..0939da595d2 --- /dev/null +++ b/src/core/lib/support/debug_location.h @@ -0,0 +1,52 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_SUPPORT_DEBUG_LOCATION_H +#define GRPC_CORE_LIB_SUPPORT_DEBUG_LOCATION_H + +namespace grpc_core { + +// Used for tracking file and line where a call is made for debug builds. +// No-op for non-debug builds. +// Callers can use the DEBUG_LOCATION macro in either case. +#ifndef NDEBUG +class DebugLocation { + public: + DebugLocation(const char* file, int line) : file_(file), line_(line) {} + bool Log() const { return true; } + const char* file() const { return file_; } + int line() const { return line_; } + + private: + const char* file_; + const int line_; +}; +#define DEBUG_LOCATION DebugLocation(__FILE__, __LINE__) +#else +class DebugLocation { + public: + bool Log() const { return false; } + const char* file() const { return nullptr; } + int line() const { return -1; } +}; +#define DEBUG_LOCATION DebugLocation() +#endif + +} // namespace grpc_core + +#endif /* GRPC_CORE_LIB_SUPPORT_DEBUG_LOCATION_H */ diff --git a/src/core/lib/support/env.h b/src/core/lib/support/env.h index e2c012a7288..2452fd330d9 100644 --- a/src/core/lib/support/env.h +++ b/src/core/lib/support/env.h @@ -21,29 +21,21 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /* Env utility functions */ /* Gets the environment variable value with the specified name. Returns a newly allocated string. It is the responsability of the caller to gpr_free the return value if not NULL (which means that the environment variable exists). */ -char *gpr_getenv(const char *name); +char* gpr_getenv(const char* name); /* Sets the the environment with the specified name to the specified value. */ -void gpr_setenv(const char *name, const char *value); +void gpr_setenv(const char* name, const char* value); /* This is a version of gpr_getenv that does not produce any output if it has to use an insecure version of the function. It is ONLY to be used to solve the problem in which we need to check an env variable to configure the verbosity level of logging. So DO NOT USE THIS. */ -const char *gpr_getenv_silent(const char *name, char **dst); - -#ifdef __cplusplus -} -#endif +const char* gpr_getenv_silent(const char* name, char** dst); #endif /* GRPC_CORE_LIB_SUPPORT_ENV_H */ diff --git a/src/core/lib/support/env_linux.cc b/src/core/lib/support/env_linux.cc index 4c45a977caa..0af2de9f7e0 100644 --- a/src/core/lib/support/env_linux.cc +++ b/src/core/lib/support/env_linux.cc @@ -38,15 +38,15 @@ #include "src/core/lib/support/string.h" -const char *gpr_getenv_silent(const char *name, char **dst) { - const char *insecure_func_used = NULL; - char *result = NULL; +const char* gpr_getenv_silent(const char* name, char** dst) { + const char* insecure_func_used = nullptr; + char* result = nullptr; #if defined(GPR_BACKWARDS_COMPATIBILITY_MODE) - typedef char *(*getenv_type)(const char *); + typedef char* (*getenv_type)(const char*); static getenv_type getenv_func = NULL; /* Check to see which getenv variant is supported (go from most * to least secure) */ - const char *names[] = {"secure_getenv", "__secure_getenv", "getenv"}; + const char* names[] = {"secure_getenv", "__secure_getenv", "getenv"}; for (size_t i = 0; getenv_func == NULL && i < GPR_ARRAY_SIZE(names); i++) { getenv_func = (getenv_type)dlsym(RTLD_DEFAULT, names[i]); if (getenv_func != NULL && strstr(names[i], "secure") == NULL) { @@ -60,21 +60,21 @@ const char *gpr_getenv_silent(const char *name, char **dst) { result = getenv(name); insecure_func_used = "getenv"; #endif - *dst = result == NULL ? result : gpr_strdup(result); + *dst = result == nullptr ? result : gpr_strdup(result); return insecure_func_used; } -char *gpr_getenv(const char *name) { - char *result = NULL; - const char *insecure_func_used = gpr_getenv_silent(name, &result); - if (insecure_func_used != NULL) { +char* gpr_getenv(const char* name) { + char* result = nullptr; + const char* insecure_func_used = gpr_getenv_silent(name, &result); + if (insecure_func_used != nullptr) { gpr_log(GPR_DEBUG, "Warning: insecure environment read function '%s' used", insecure_func_used); } return result; } -void gpr_setenv(const char *name, const char *value) { +void gpr_setenv(const char* name, const char* value) { int res = setenv(name, value, 1); GPR_ASSERT(res == 0); } diff --git a/src/core/lib/support/env_posix.cc b/src/core/lib/support/env_posix.cc index b88822ca025..7bea31ca550 100644 --- a/src/core/lib/support/env_posix.cc +++ b/src/core/lib/support/env_posix.cc @@ -29,17 +29,17 @@ #include #include "src/core/lib/support/string.h" -const char *gpr_getenv_silent(const char *name, char **dst) { +const char* gpr_getenv_silent(const char* name, char** dst) { *dst = gpr_getenv(name); return NULL; } -char *gpr_getenv(const char *name) { - char *result = getenv(name); +char* gpr_getenv(const char* name) { + char* result = getenv(name); return result == NULL ? result : gpr_strdup(result); } -void gpr_setenv(const char *name, const char *value) { +void gpr_setenv(const char* name, const char* value) { int res = setenv(name, value, 1); GPR_ASSERT(res == 0); } diff --git a/src/core/lib/support/env_windows.cc b/src/core/lib/support/env_windows.cc index c5a25dc201d..cdb1d58ccd9 100644 --- a/src/core/lib/support/env_windows.cc +++ b/src/core/lib/support/env_windows.cc @@ -30,13 +30,13 @@ #include #include -const char *gpr_getenv_silent(const char *name, char **dst) { +const char* gpr_getenv_silent(const char* name, char** dst) { *dst = gpr_getenv(name); return NULL; } -char *gpr_getenv(const char *name) { - char *result = NULL; +char* gpr_getenv(const char* name) { + char* result = NULL; DWORD size; LPTSTR tresult = NULL; LPTSTR tname = gpr_char_to_tchar(name); @@ -60,7 +60,7 @@ char *gpr_getenv(const char *name) { return result; } -void gpr_setenv(const char *name, const char *value) { +void gpr_setenv(const char* name, const char* value) { LPTSTR tname = gpr_char_to_tchar(name); LPTSTR tvalue = gpr_char_to_tchar(value); BOOL res = SetEnvironmentVariable(tname, tvalue); diff --git a/src/core/lib/support/fork.cc b/src/core/lib/support/fork.cc new file mode 100644 index 00000000000..d59ca5584cb --- /dev/null +++ b/src/core/lib/support/fork.cc @@ -0,0 +1,62 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include "src/core/lib/support/fork.h" + +#include + +#include +#include + +#include "src/core/lib/support/env.h" + +/* + * NOTE: FORKING IS NOT GENERALLY SUPPORTED, THIS IS ONLY INTENDED TO WORK + * AROUND VERY SPECIFIC USE CASES. + */ + +static int override_fork_support_enabled = -1; +static int fork_support_enabled; + +void grpc_fork_support_init() { +#ifdef GRPC_ENABLE_FORK_SUPPORT + fork_support_enabled = 1; +#else + fork_support_enabled = 0; + char* env = gpr_getenv("GRPC_ENABLE_FORK_SUPPORT"); + if (env != NULL) { + static const char* truthy[] = {"yes", "Yes", "YES", "true", + "True", "TRUE", "1"}; + for (size_t i = 0; i < GPR_ARRAY_SIZE(truthy); i++) { + if (0 == strcmp(env, truthy[i])) { + fork_support_enabled = 1; + } + } + gpr_free(env); + } +#endif + if (override_fork_support_enabled != -1) { + fork_support_enabled = override_fork_support_enabled; + } +} + +int grpc_fork_support_enabled() { return fork_support_enabled; } + +void grpc_enable_fork_support(int enable) { + override_fork_support_enabled = enable; +} diff --git a/src/core/lib/support/fork.h b/src/core/lib/support/fork.h new file mode 100644 index 00000000000..215d4214a61 --- /dev/null +++ b/src/core/lib/support/fork.h @@ -0,0 +1,35 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_SUPPORT_FORK_H +#define GRPC_CORE_LIB_SUPPORT_FORK_H + +/* + * NOTE: FORKING IS NOT GENERALLY SUPPORTED, THIS IS ONLY INTENDED TO WORK + * AROUND VERY SPECIFIC USE CASES. + */ + +void grpc_fork_support_init(void); + +int grpc_fork_support_enabled(void); + +// Test only: Must be called before grpc_init(), and overrides +// environment variables/compile flags +void grpc_enable_fork_support(int enable); + +#endif /* GRPC_CORE_LIB_SUPPORT_FORK_H */ diff --git a/src/core/lib/support/host_port.cc b/src/core/lib/support/host_port.cc index 3302e574abb..cb8e3d44797 100644 --- a/src/core/lib/support/host_port.cc +++ b/src/core/lib/support/host_port.cc @@ -25,8 +25,8 @@ #include #include "src/core/lib/support/string.h" -int gpr_join_host_port(char **out, const char *host, int port) { - if (host[0] != '[' && strchr(host, ':') != NULL) { +int gpr_join_host_port(char** out, const char* host, int port) { + if (host[0] != '[' && strchr(host, ':') != nullptr) { /* IPv6 literals must be enclosed in brackets. */ return gpr_asprintf(out, "[%s]:%d", host, port); } else { @@ -35,24 +35,24 @@ int gpr_join_host_port(char **out, const char *host, int port) { } } -int gpr_split_host_port(const char *name, char **host, char **port) { - const char *host_start; +int gpr_split_host_port(const char* name, char** host, char** port) { + const char* host_start; size_t host_len; - const char *port_start; + const char* port_start; - *host = NULL; - *port = NULL; + *host = nullptr; + *port = nullptr; if (name[0] == '[') { /* Parse a bracketed host, typically an IPv6 literal. */ - const char *rbracket = strchr(name, ']'); - if (rbracket == NULL) { + const char* rbracket = strchr(name, ']'); + if (rbracket == nullptr) { /* Unmatched [ */ return 0; } if (rbracket[1] == '\0') { /* ] */ - port_start = NULL; + port_start = nullptr; } else if (rbracket[1] == ':') { /* ]: */ port_start = rbracket + 2; @@ -62,14 +62,14 @@ int gpr_split_host_port(const char *name, char **host, char **port) { } host_start = name + 1; host_len = (size_t)(rbracket - host_start); - if (memchr(host_start, ':', host_len) == NULL) { + if (memchr(host_start, ':', host_len) == nullptr) { /* Require all bracketed hosts to contain a colon, because a hostname or IPv4 address should never use brackets. */ return 0; } } else { - const char *colon = strchr(name, ':'); - if (colon != NULL && strchr(colon + 1, ':') == NULL) { + const char* colon = strchr(name, ':'); + if (colon != nullptr && strchr(colon + 1, ':') == nullptr) { /* Exactly 1 colon. Split into host:port. */ host_start = name; host_len = (size_t)(colon - name); @@ -78,16 +78,16 @@ int gpr_split_host_port(const char *name, char **host, char **port) { /* 0 or 2+ colons. Bare hostname or IPv6 litearal. */ host_start = name; host_len = strlen(name); - port_start = NULL; + port_start = nullptr; } } /* Allocate return values. */ - *host = (char *)gpr_malloc(host_len + 1); + *host = (char*)gpr_malloc(host_len + 1); memcpy(*host, host_start, host_len); (*host)[host_len] = '\0'; - if (port_start != NULL) { + if (port_start != nullptr) { *port = gpr_strdup(port_start); } diff --git a/src/core/lib/support/log.cc b/src/core/lib/support/log.cc index 69f92e001c1..2a40745e97d 100644 --- a/src/core/lib/support/log.cc +++ b/src/core/lib/support/log.cc @@ -27,11 +27,11 @@ #include #include -extern "C" void gpr_default_log(gpr_log_func_args *args); +void gpr_default_log(gpr_log_func_args* args); static gpr_atm g_log_func = (gpr_atm)gpr_default_log; static gpr_atm g_min_severity_to_print = GPR_LOG_VERBOSITY_UNSET; -const char *gpr_log_severity_string(gpr_log_severity severity) { +const char* gpr_log_severity_string(gpr_log_severity severity) { switch (severity) { case GPR_LOG_SEVERITY_DEBUG: return "D"; @@ -43,8 +43,8 @@ const char *gpr_log_severity_string(gpr_log_severity severity) { GPR_UNREACHABLE_CODE(return "UNKNOWN"); } -void gpr_log_message(const char *file, int line, gpr_log_severity severity, - const char *message) { +void gpr_log_message(const char* file, int line, gpr_log_severity severity, + const char* message) { if ((gpr_atm)severity < gpr_atm_no_barrier_load(&g_min_severity_to_print)) { return; } @@ -64,11 +64,11 @@ void gpr_set_log_verbosity(gpr_log_severity min_severity_to_print) { } void gpr_log_verbosity_init() { - char *verbosity = NULL; - const char *insecure_getenv = gpr_getenv_silent("GRPC_VERBOSITY", &verbosity); + char* verbosity = nullptr; + const char* insecure_getenv = gpr_getenv_silent("GRPC_VERBOSITY", &verbosity); gpr_atm min_severity_to_print = GPR_LOG_SEVERITY_ERROR; - if (verbosity != NULL) { + if (verbosity != nullptr) { if (gpr_stricmp(verbosity, "DEBUG") == 0) { min_severity_to_print = (gpr_atm)GPR_LOG_SEVERITY_DEBUG; } else if (gpr_stricmp(verbosity, "INFO") == 0) { @@ -83,7 +83,7 @@ void gpr_log_verbosity_init() { gpr_atm_no_barrier_store(&g_min_severity_to_print, min_severity_to_print); } - if (insecure_getenv != NULL) { + if (insecure_getenv != nullptr) { gpr_log(GPR_DEBUG, "Warning: insecure environment read function '%s' used", insecure_getenv); } diff --git a/src/core/lib/support/log_android.cc b/src/core/lib/support/log_android.cc index 9e8529cbac8..0d3ac0fe522 100644 --- a/src/core/lib/support/log_android.cc +++ b/src/core/lib/support/log_android.cc @@ -39,9 +39,9 @@ static android_LogPriority severity_to_log_priority(gpr_log_severity severity) { return ANDROID_LOG_DEFAULT; } -extern "C" void gpr_log(const char *file, int line, gpr_log_severity severity, - const char *format, ...) { - char *message = NULL; +void gpr_log(const char* file, int line, gpr_log_severity severity, + const char* format, ...) { + char* message = NULL; va_list args; va_start(args, format); vasprintf(&message, format, args); @@ -50,10 +50,10 @@ extern "C" void gpr_log(const char *file, int line, gpr_log_severity severity, free(message); } -extern "C" void gpr_default_log(gpr_log_func_args *args) { - const char *final_slash; - const char *display_file; - char *output = NULL; +void gpr_default_log(gpr_log_func_args* args) { + const char* final_slash; + const char* display_file; + char* output = NULL; final_slash = strrchr(args->file, '/'); if (final_slash == NULL) diff --git a/src/core/lib/support/log_linux.cc b/src/core/lib/support/log_linux.cc index 0914acedf4f..6b1f1c71e44 100644 --- a/src/core/lib/support/log_linux.cc +++ b/src/core/lib/support/log_linux.cc @@ -41,9 +41,9 @@ static long gettid(void) { return syscall(__NR_gettid); } -void gpr_log(const char *file, int line, gpr_log_severity severity, - const char *format, ...) { - char *message = NULL; +void gpr_log(const char* file, int line, gpr_log_severity severity, + const char* format, ...) { + char* message = nullptr; va_list args; va_start(args, format); if (vasprintf(&message, format, args) == -1) { @@ -56,10 +56,10 @@ void gpr_log(const char *file, int line, gpr_log_severity severity, free(message); } -extern "C" void gpr_default_log(gpr_log_func_args *args) { - const char *final_slash; - char *prefix; - const char *display_file; +void gpr_default_log(gpr_log_func_args* args) { + const char* final_slash; + char* prefix; + const char* display_file; char time_buffer[64]; time_t timer; gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME); @@ -69,7 +69,7 @@ extern "C" void gpr_default_log(gpr_log_func_args *args) { timer = (time_t)now.tv_sec; final_slash = strrchr(args->file, '/'); - if (final_slash == NULL) + if (final_slash == nullptr) display_file = args->file; else display_file = final_slash + 1; diff --git a/src/core/lib/support/log_posix.cc b/src/core/lib/support/log_posix.cc index 29530c858f3..9fab480a8d4 100644 --- a/src/core/lib/support/log_posix.cc +++ b/src/core/lib/support/log_posix.cc @@ -27,17 +27,16 @@ #include #include #include -#include #include #include static intptr_t gettid(void) { return (intptr_t)pthread_self(); } -void gpr_log(const char *file, int line, gpr_log_severity severity, - const char *format, ...) { +void gpr_log(const char* file, int line, gpr_log_severity severity, + const char* format, ...) { char buf[64]; - char *allocated = NULL; - char *message = NULL; + char* allocated = NULL; + char* message = NULL; int ret; va_list args; va_start(args, format); @@ -48,7 +47,7 @@ void gpr_log(const char *file, int line, gpr_log_severity severity, } else if ((size_t)ret <= sizeof(buf) - 1) { message = buf; } else { - message = allocated = (char *)gpr_malloc((size_t)ret + 1); + message = allocated = (char*)gpr_malloc((size_t)ret + 1); va_start(args, format); vsnprintf(message, (size_t)(ret + 1), format, args); va_end(args); @@ -57,9 +56,9 @@ void gpr_log(const char *file, int line, gpr_log_severity severity, gpr_free(allocated); } -extern "C" void gpr_default_log(gpr_log_func_args *args) { - const char *final_slash; - const char *display_file; +void gpr_default_log(gpr_log_func_args* args) { + const char* final_slash; + const char* display_file; char time_buffer[64]; time_t timer; gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME); @@ -79,7 +78,7 @@ extern "C" void gpr_default_log(gpr_log_func_args *args) { strcpy(time_buffer, "error:strftime"); } - char *prefix; + char* prefix; gpr_asprintf(&prefix, "%s%s.%09d %7tu %s:%d]", gpr_log_severity_string(args->severity), time_buffer, (int)(now.tv_nsec), gettid(), display_file, args->line); diff --git a/src/core/lib/support/log_windows.cc b/src/core/lib/support/log_windows.cc index ee52abea730..0013bf448fd 100644 --- a/src/core/lib/support/log_windows.cc +++ b/src/core/lib/support/log_windows.cc @@ -32,9 +32,9 @@ #include "src/core/lib/support/string.h" #include "src/core/lib/support/string_windows.h" -void gpr_log(const char *file, int line, gpr_log_severity severity, - const char *format, ...) { - char *message = NULL; +void gpr_log(const char* file, int line, gpr_log_severity severity, + const char* format, ...) { + char* message = NULL; va_list args; int ret; @@ -47,7 +47,7 @@ void gpr_log(const char *file, int line, gpr_log_severity severity, } else { /* Allocate a new buffer, with space for the NUL terminator. */ size_t strp_buflen = (size_t)ret + 1; - message = (char *)gpr_malloc(strp_buflen); + message = (char*)gpr_malloc(strp_buflen); /* Print to the buffer. */ va_start(args, format); @@ -65,9 +65,9 @@ void gpr_log(const char *file, int line, gpr_log_severity severity, } /* Simple starter implementation */ -extern "C" void gpr_default_log(gpr_log_func_args *args) { - const char *final_slash; - const char *display_file; +void gpr_default_log(gpr_log_func_args* args) { + const char* final_slash; + const char* display_file; char time_buffer[64]; time_t timer; gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME); diff --git a/src/core/lib/support/manual_constructor.h b/src/core/lib/support/manual_constructor.h index d753cf98a0c..fda7653dbce 100644 --- a/src/core/lib/support/manual_constructor.h +++ b/src/core/lib/support/manual_constructor.h @@ -22,12 +22,147 @@ // manually construct a region of memory with some type #include +#include #include #include #include +#include + namespace grpc_core { +// this contains templated helpers needed to implement the ManualConstructors +// in this file. +namespace manual_ctor_impl { + +// is_one_of returns true it a class, Member, is present in a variadic list of +// classes, List. +template +class is_one_of; + +template +class is_one_of { + public: + static constexpr const bool value = true; +}; + +template +class is_one_of { + public: + static constexpr const bool value = is_one_of::value; +}; + +template +class is_one_of { + public: + static constexpr const bool value = false; +}; + +// max_size_of returns sizeof(Type) for the largest type in the variadic list +// of classes, Types. +template +class max_size_of; + +template +class max_size_of { + public: + static constexpr const size_t value = sizeof(A); +}; + +template +class max_size_of { + public: + static constexpr const size_t value = sizeof(A) > max_size_of::value + ? sizeof(A) + : max_size_of::value; +}; + +// max_size_of returns alignof(Type) for the largest type in the variadic list +// of classes, Types. +template +class max_align_of; + +template +class max_align_of { + public: + static constexpr const size_t value = alignof(A); +}; + +template +class max_align_of { + public: + static constexpr const size_t value = alignof(A) > max_align_of::value + ? alignof(A) + : max_align_of::value; +}; + +} // namespace manual_ctor_impl + +template +class PolymorphicManualConstructor { + public: + // No constructor or destructor because one of the most useful uses of + // this class is as part of a union, and members of a union could not have + // constructors or destructors till C++11. And, anyway, the whole point of + // this class is to bypass constructor and destructor. + + BaseType* get() { return reinterpret_cast(&space_); } + const BaseType* get() const { + return reinterpret_cast(&space_); + } + + BaseType* operator->() { return get(); } + const BaseType* operator->() const { return get(); } + + BaseType& operator*() { return *get(); } + const BaseType& operator*() const { return *get(); } + + template + void Init() { + FinishInit(new (&space_) DerivedType); + } + + // Init() constructs the Type instance using the given arguments + // (which are forwarded to Type's constructor). + // + // Note that Init() with no arguments performs default-initialization, + // not zero-initialization (i.e it behaves the same as "new Type;", not + // "new Type();"), so it will leave non-class types uninitialized. + template + void Init(Ts&&... args) { + FinishInit(new (&space_) DerivedType(std::forward(args)...)); + } + + // Init() that is equivalent to copy and move construction. + // Enables usage like this: + // ManualConstructor> v; + // v.Init({1, 2, 3}); + template + void Init(const DerivedType& x) { + FinishInit(new (&space_) DerivedType(x)); + } + template + void Init(DerivedType&& x) { + FinishInit(new (&space_) DerivedType(std::move(x))); + } + + void Destroy() { get()->~BaseType(); } + + private: + template + void FinishInit(DerivedType* p) { + static_assert( + manual_ctor_impl::is_one_of::value, + "DerivedType must be one of the predeclared DerivedTypes"); + GPR_ASSERT(reinterpret_cast(static_cast(p)) == p); + } + + typename std::aligned_storage< + grpc_core::manual_ctor_impl::max_size_of::value, + grpc_core::manual_ctor_impl::max_align_of::value>::type + space_; +}; + template class ManualConstructor { public: diff --git a/src/core/lib/support/memory.h b/src/core/lib/support/memory.h index 6b336681db2..695418e3e1e 100644 --- a/src/core/lib/support/memory.h +++ b/src/core/lib/support/memory.h @@ -76,7 +76,7 @@ class Allocator { pointer address(reference x) const { return &x; } const_pointer address(const_reference x) const { return &x; } pointer allocate(std::size_t n, - std::allocator::const_pointer hint = 0) { + std::allocator::const_pointer hint = nullptr) { return static_cast(gpr_malloc(n * sizeof(T))); } void deallocate(T* p, std::size_t n) { gpr_free(p); } diff --git a/src/core/lib/support/mpscq.cc b/src/core/lib/support/mpscq.cc index e9f893988df..47e896d2df6 100644 --- a/src/core/lib/support/mpscq.cc +++ b/src/core/lib/support/mpscq.cc @@ -20,60 +20,95 @@ #include -void gpr_mpscq_init(gpr_mpscq *q) { +void gpr_mpscq_init(gpr_mpscq* q) { gpr_atm_no_barrier_store(&q->head, (gpr_atm)&q->stub); q->tail = &q->stub; gpr_atm_no_barrier_store(&q->stub.next, (gpr_atm)NULL); } -void gpr_mpscq_destroy(gpr_mpscq *q) { +void gpr_mpscq_destroy(gpr_mpscq* q) { GPR_ASSERT(gpr_atm_no_barrier_load(&q->head) == (gpr_atm)&q->stub); GPR_ASSERT(q->tail == &q->stub); } -void gpr_mpscq_push(gpr_mpscq *q, gpr_mpscq_node *n) { +bool gpr_mpscq_push(gpr_mpscq* q, gpr_mpscq_node* n) { gpr_atm_no_barrier_store(&n->next, (gpr_atm)NULL); - gpr_mpscq_node *prev = - (gpr_mpscq_node *)gpr_atm_full_xchg(&q->head, (gpr_atm)n); + gpr_mpscq_node* prev = + (gpr_mpscq_node*)gpr_atm_full_xchg(&q->head, (gpr_atm)n); gpr_atm_rel_store(&prev->next, (gpr_atm)n); + return prev == &q->stub; } -gpr_mpscq_node *gpr_mpscq_pop(gpr_mpscq *q) { +gpr_mpscq_node* gpr_mpscq_pop(gpr_mpscq* q) { bool empty; return gpr_mpscq_pop_and_check_end(q, &empty); } -gpr_mpscq_node *gpr_mpscq_pop_and_check_end(gpr_mpscq *q, bool *empty) { - gpr_mpscq_node *tail = q->tail; - gpr_mpscq_node *next = (gpr_mpscq_node *)gpr_atm_acq_load(&tail->next); +gpr_mpscq_node* gpr_mpscq_pop_and_check_end(gpr_mpscq* q, bool* empty) { + gpr_mpscq_node* tail = q->tail; + gpr_mpscq_node* next = (gpr_mpscq_node*)gpr_atm_acq_load(&tail->next); if (tail == &q->stub) { // indicates the list is actually (ephemerally) empty - if (next == NULL) { + if (next == nullptr) { *empty = true; - return NULL; + return nullptr; } q->tail = next; tail = next; - next = (gpr_mpscq_node *)gpr_atm_acq_load(&tail->next); + next = (gpr_mpscq_node*)gpr_atm_acq_load(&tail->next); } - if (next != NULL) { + if (next != nullptr) { *empty = false; q->tail = next; return tail; } - gpr_mpscq_node *head = (gpr_mpscq_node *)gpr_atm_acq_load(&q->head); + gpr_mpscq_node* head = (gpr_mpscq_node*)gpr_atm_acq_load(&q->head); if (tail != head) { *empty = false; // indicates a retry is in order: we're still adding - return NULL; + return nullptr; } gpr_mpscq_push(q, &q->stub); - next = (gpr_mpscq_node *)gpr_atm_acq_load(&tail->next); - if (next != NULL) { + next = (gpr_mpscq_node*)gpr_atm_acq_load(&tail->next); + if (next != nullptr) { q->tail = next; return tail; } // indicates a retry is in order: we're still adding *empty = false; - return NULL; + return nullptr; +} + +void gpr_locked_mpscq_init(gpr_locked_mpscq* q) { + gpr_mpscq_init(&q->queue); + gpr_mu_init(&q->mu); +} + +void gpr_locked_mpscq_destroy(gpr_locked_mpscq* q) { + gpr_mpscq_destroy(&q->queue); + gpr_mu_destroy(&q->mu); +} + +bool gpr_locked_mpscq_push(gpr_locked_mpscq* q, gpr_mpscq_node* n) { + return gpr_mpscq_push(&q->queue, n); +} + +gpr_mpscq_node* gpr_locked_mpscq_try_pop(gpr_locked_mpscq* q) { + if (gpr_mu_trylock(&q->mu)) { + gpr_mpscq_node* n = gpr_mpscq_pop(&q->queue); + gpr_mu_unlock(&q->mu); + return n; + } + return nullptr; +} + +gpr_mpscq_node* gpr_locked_mpscq_pop(gpr_locked_mpscq* q) { + gpr_mu_lock(&q->mu); + bool empty = false; + gpr_mpscq_node* n; + do { + n = gpr_mpscq_pop_and_check_end(&q->queue, &empty); + } while (n == nullptr && !empty); + gpr_mu_unlock(&q->mu); + return n; } diff --git a/src/core/lib/support/mpscq.h b/src/core/lib/support/mpscq.h index ca63a044bb3..648ead1f5b5 100644 --- a/src/core/lib/support/mpscq.h +++ b/src/core/lib/support/mpscq.h @@ -20,42 +20,65 @@ #define GRPC_CORE_LIB_SUPPORT_MPSCQ_H #include +#include #include #include -#ifdef __cplusplus -extern "C" { -#endif - // Multiple-producer single-consumer lock free queue, based upon the // implementation from Dmitry Vyukov here: // http://www.1024cores.net/home/lock-free-algorithms/queues/intrusive-mpsc-node-based-queue // List node (include this in a data structure at the top, and add application // fields after it - to simulate inheritance) -typedef struct gpr_mpscq_node { gpr_atm next; } gpr_mpscq_node; +typedef struct gpr_mpscq_node { + gpr_atm next; +} gpr_mpscq_node; // Actual queue type typedef struct gpr_mpscq { gpr_atm head; // make sure head & tail don't share a cacheline char padding[GPR_CACHELINE_SIZE]; - gpr_mpscq_node *tail; + gpr_mpscq_node* tail; gpr_mpscq_node stub; } gpr_mpscq; -void gpr_mpscq_init(gpr_mpscq *q); -void gpr_mpscq_destroy(gpr_mpscq *q); +void gpr_mpscq_init(gpr_mpscq* q); +void gpr_mpscq_destroy(gpr_mpscq* q); // Push a node -void gpr_mpscq_push(gpr_mpscq *q, gpr_mpscq_node *n); +// Thread safe - can be called from multiple threads concurrently +// Returns true if this was possibly the first node (may return true +// sporadically, will not return false sporadically) +bool gpr_mpscq_push(gpr_mpscq* q, gpr_mpscq_node* n); // Pop a node (returns NULL if no node is ready - which doesn't indicate that // the queue is empty!!) -gpr_mpscq_node *gpr_mpscq_pop(gpr_mpscq *q); +// Thread compatible - can only be called from one thread at a time +gpr_mpscq_node* gpr_mpscq_pop(gpr_mpscq* q); // Pop a node; sets *empty to true if the queue is empty, or false if it is not -gpr_mpscq_node *gpr_mpscq_pop_and_check_end(gpr_mpscq *q, bool *empty); +gpr_mpscq_node* gpr_mpscq_pop_and_check_end(gpr_mpscq* q, bool* empty); + +// An mpscq with a lock: it's safe to pop from multiple threads, but doing +// only one thread will succeed concurrently +typedef struct gpr_locked_mpscq { + gpr_mpscq queue; + gpr_mu mu; +} gpr_locked_mpscq; + +void gpr_locked_mpscq_init(gpr_locked_mpscq* q); +void gpr_locked_mpscq_destroy(gpr_locked_mpscq* q); +// Push a node +// Thread safe - can be called from multiple threads concurrently +// Returns true if this was possibly the first node (may return true +// sporadically, will not return false sporadically) +bool gpr_locked_mpscq_push(gpr_locked_mpscq* q, gpr_mpscq_node* n); + +// Pop a node (returns NULL if no node is ready - which doesn't indicate that +// the queue is empty!!) +// Thread safe - can be called from multiple threads concurrently +gpr_mpscq_node* gpr_locked_mpscq_try_pop(gpr_locked_mpscq* q); -#ifdef __cplusplus -} -#endif +// Pop a node. Returns NULL only if the queue was empty at some point after +// calling this function +gpr_mpscq_node* gpr_locked_mpscq_pop(gpr_locked_mpscq* q); #endif /* GRPC_CORE_LIB_SUPPORT_MPSCQ_H */ diff --git a/src/core/lib/support/murmur_hash.cc b/src/core/lib/support/murmur_hash.cc index f06b970de70..2f0e71a53c9 100644 --- a/src/core/lib/support/murmur_hash.cc +++ b/src/core/lib/support/murmur_hash.cc @@ -29,23 +29,20 @@ (h) *= 0xc2b2ae35; \ (h) ^= (h) >> 16; -uint32_t gpr_murmur_hash3(const void *key, size_t len, uint32_t seed) { - const uint8_t *data = (const uint8_t *)key; - const size_t nblocks = len / 4; - int i; - +uint32_t gpr_murmur_hash3(const void* key, size_t len, uint32_t seed) { uint32_t h1 = seed; uint32_t k1; const uint32_t c1 = 0xcc9e2d51; const uint32_t c2 = 0x1b873593; - const uint32_t *blocks = ((const uint32_t *)key) + nblocks; - const uint8_t *tail = (const uint8_t *)(data + nblocks * 4); + const uint8_t* keyptr = (const uint8_t*)key; + const size_t bsize = sizeof(k1); + const size_t nblocks = len / bsize; /* body */ - for (i = -(int)nblocks; i; i++) { - memcpy(&k1, blocks + i, sizeof(uint32_t)); + for (size_t i = 0; i < nblocks; i++, keyptr += bsize) { + memcpy(&k1, keyptr, bsize); k1 *= c1; k1 = ROTL32(k1, 15); @@ -61,13 +58,13 @@ uint32_t gpr_murmur_hash3(const void *key, size_t len, uint32_t seed) { /* tail */ switch (len & 3) { case 3: - k1 ^= ((uint32_t)tail[2]) << 16; + k1 ^= ((uint32_t)keyptr[2]) << 16; /* fallthrough */ case 2: - k1 ^= ((uint32_t)tail[1]) << 8; + k1 ^= ((uint32_t)keyptr[1]) << 8; /* fallthrough */ case 1: - k1 ^= tail[0]; + k1 ^= keyptr[0]; k1 *= c1; k1 = ROTL32(k1, 15); k1 *= c2; diff --git a/src/core/lib/support/murmur_hash.h b/src/core/lib/support/murmur_hash.h index a4c642e49ff..422770f1035 100644 --- a/src/core/lib/support/murmur_hash.h +++ b/src/core/lib/support/murmur_hash.h @@ -23,15 +23,7 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /* compute the hash of key (length len) */ -uint32_t gpr_murmur_hash3(const void *key, size_t len, uint32_t seed); - -#ifdef __cplusplus -} -#endif +uint32_t gpr_murmur_hash3(const void* key, size_t len, uint32_t seed); #endif /* GRPC_CORE_LIB_SUPPORT_MURMUR_HASH_H */ diff --git a/src/core/lib/support/ref_counted.h b/src/core/lib/support/ref_counted.h new file mode 100644 index 00000000000..4c662f91190 --- /dev/null +++ b/src/core/lib/support/ref_counted.h @@ -0,0 +1,122 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_SUPPORT_REF_COUNTED_H +#define GRPC_CORE_LIB_SUPPORT_REF_COUNTED_H + +#include +#include + +#include "src/core/lib/debug/trace.h" +#include "src/core/lib/support/debug_location.h" +#include "src/core/lib/support/memory.h" + +namespace grpc_core { + +// A base class for reference-counted objects. +// New objects should be created via New() and start with a refcount of 1. +// When the refcount reaches 0, the object will be deleted via Delete(). +class RefCounted { + public: + void Ref() { gpr_ref(&refs_); } + + void Unref() { + if (gpr_unref(&refs_)) { + Delete(this); + } + } + + // Not copyable nor movable. + RefCounted(const RefCounted&) = delete; + RefCounted& operator=(const RefCounted&) = delete; + + protected: + // Allow Delete() to access destructor. + template + friend void Delete(T*); + + RefCounted() { gpr_ref_init(&refs_, 1); } + + virtual ~RefCounted() {} + + private: + gpr_refcount refs_; +}; + +// An alternative version of the RefCounted base class that +// supports tracing. This is intended to be used in cases where the +// object will be handled both by idiomatic C++ code using smart +// pointers and legacy code that is manually calling Ref() and Unref(). +// Once all of our code is converted to idiomatic C++, we may be able to +// eliminate this class. +class RefCountedWithTracing { + public: + void Ref() { gpr_ref(&refs_); } + + void Ref(const DebugLocation& location, const char* reason) { + if (location.Log() && trace_flag_ != nullptr && trace_flag_->enabled()) { + gpr_atm old_refs = gpr_atm_no_barrier_load(&refs_.count); + gpr_log(GPR_DEBUG, "%s:%p %s:%d ref %" PRIdPTR " -> %" PRIdPTR " %s", + trace_flag_->name(), this, location.file(), location.line(), + old_refs, old_refs + 1, reason); + } + Ref(); + } + + void Unref() { + if (gpr_unref(&refs_)) { + Delete(this); + } + } + + void Unref(const DebugLocation& location, const char* reason) { + if (location.Log() && trace_flag_ != nullptr && trace_flag_->enabled()) { + gpr_atm old_refs = gpr_atm_no_barrier_load(&refs_.count); + gpr_log(GPR_DEBUG, "%s:%p %s:%d unref %" PRIdPTR " -> %" PRIdPTR " %s", + trace_flag_->name(), this, location.file(), location.line(), + old_refs, old_refs - 1, reason); + } + Unref(); + } + + // Not copyable nor movable. + RefCountedWithTracing(const RefCountedWithTracing&) = delete; + RefCountedWithTracing& operator=(const RefCountedWithTracing&) = delete; + + protected: + // Allow Delete() to access destructor. + template + friend void Delete(T*); + + RefCountedWithTracing() : RefCountedWithTracing(nullptr) {} + + explicit RefCountedWithTracing(TraceFlag* trace_flag) + : trace_flag_(trace_flag) { + gpr_ref_init(&refs_, 1); + } + + virtual ~RefCountedWithTracing() {} + + private: + TraceFlag* trace_flag_ = nullptr; + gpr_refcount refs_; +}; + +} // namespace grpc_core + +#endif /* GRPC_CORE_LIB_SUPPORT_REF_COUNTED_H */ diff --git a/src/core/lib/support/ref_counted_ptr.h b/src/core/lib/support/ref_counted_ptr.h new file mode 100644 index 00000000000..dc2385e369c --- /dev/null +++ b/src/core/lib/support/ref_counted_ptr.h @@ -0,0 +1,90 @@ +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_SUPPORT_REF_COUNTED_PTR_H +#define GRPC_CORE_LIB_SUPPORT_REF_COUNTED_PTR_H + +#include + +#include "src/core/lib/support/memory.h" + +namespace grpc_core { + +// A smart pointer class for objects that provide Ref() and Unref() methods, +// such as those provided by the RefCounted base class. +template +class RefCountedPtr { + public: + RefCountedPtr() {} + + // If value is non-null, we take ownership of a ref to it. + explicit RefCountedPtr(T* value) { value_ = value; } + + // Move support. + RefCountedPtr(RefCountedPtr&& other) { + value_ = other.value_; + other.value_ = nullptr; + } + RefCountedPtr& operator=(RefCountedPtr&& other) { + if (value_ != nullptr) value_->Unref(); + value_ = other.value_; + other.value_ = nullptr; + return *this; + } + + // Copy support. + RefCountedPtr(const RefCountedPtr& other) { + if (other.value_ != nullptr) other.value_->Ref(); + value_ = other.value_; + } + RefCountedPtr& operator=(const RefCountedPtr& other) { + // Note: Order of reffing and unreffing is important here in case value_ + // and other.value_ are the same object. + if (other.value_ != nullptr) other.value_->Ref(); + if (value_ != nullptr) value_->Unref(); + value_ = other.value_; + return *this; + } + + ~RefCountedPtr() { + if (value_ != nullptr) value_->Unref(); + } + + // If value is non-null, we take ownership of a ref to it. + void reset(T* value = nullptr) { + if (value_ != nullptr) value_->Unref(); + value_ = value; + } + + T* get() const { return value_; } + + T& operator*() const { return *value_; } + T* operator->() const { return value_; } + + private: + T* value_ = nullptr; +}; + +template +inline RefCountedPtr MakeRefCounted(Args&&... args) { + return RefCountedPtr(New(std::forward(args)...)); +} + +} // namespace grpc_core + +#endif /* GRPC_CORE_LIB_SUPPORT_REF_COUNTED_PTR_H */ diff --git a/src/core/lib/support/spinlock.h b/src/core/lib/support/spinlock.h index 47584f62794..8b439642e9d 100644 --- a/src/core/lib/support/spinlock.h +++ b/src/core/lib/support/spinlock.h @@ -23,7 +23,9 @@ /* Simple spinlock. No backoff strategy, gpr_spinlock_lock is almost always a concurrency code smell. */ -typedef struct { gpr_atm atm; } gpr_spinlock; +typedef struct { + gpr_atm atm; +} gpr_spinlock; #ifdef __cplusplus #define GPR_SPINLOCK_INITIALIZER (gpr_spinlock{0}) diff --git a/src/core/lib/support/stack_lockfree.cc b/src/core/lib/support/stack_lockfree.cc deleted file mode 100644 index 0fb64ed0017..00000000000 --- a/src/core/lib/support/stack_lockfree.cc +++ /dev/null @@ -1,137 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include "src/core/lib/support/stack_lockfree.h" - -#include -#include - -#include -#include -#include -#include - -/* The lockfree node structure is a single architecture-level - word that allows for an atomic CAS to set it up. */ -struct lockfree_node_contents { - /* next thing to look at. Actual index for head, next index otherwise */ - uint16_t index; -#ifdef GPR_ARCH_64 - uint16_t pad; - uint32_t aba_ctr; -#else -#ifdef GPR_ARCH_32 - uint16_t aba_ctr; -#else -#error Unsupported bit width architecture -#endif -#endif -}; - -/* Use a union to make sure that these are in the same bits as an atm word */ -typedef union lockfree_node { - gpr_atm atm; - struct lockfree_node_contents contents; -} lockfree_node; - -/* make sure that entries aligned to 8-bytes */ -#define ENTRY_ALIGNMENT_BITS 3 -/* reserve this entry as invalid */ -#define INVALID_ENTRY_INDEX ((1 << 16) - 1) - -struct gpr_stack_lockfree { - lockfree_node *entries; - lockfree_node head; /* An atomic entry describing curr head */ -}; - -gpr_stack_lockfree *gpr_stack_lockfree_create(size_t entries) { - gpr_stack_lockfree *stack; - stack = (gpr_stack_lockfree *)gpr_malloc(sizeof(*stack)); - /* Since we only allocate 16 bits to represent an entry number, - * make sure that we are within the desired range */ - /* Reserve the highest entry number as a dummy */ - GPR_ASSERT(entries < INVALID_ENTRY_INDEX); - stack->entries = (lockfree_node *)gpr_malloc_aligned( - entries * sizeof(stack->entries[0]), ENTRY_ALIGNMENT_BITS); - /* Clear out all entries */ - memset(stack->entries, 0, entries * sizeof(stack->entries[0])); - memset(&stack->head, 0, sizeof(stack->head)); - - GPR_ASSERT(sizeof(stack->entries->atm) == sizeof(stack->entries->contents)); - - /* Point the head at reserved dummy entry */ - stack->head.contents.index = INVALID_ENTRY_INDEX; -/* Fill in the pad and aba_ctr to avoid confusing memcheck tools */ -#ifdef GPR_ARCH_64 - stack->head.contents.pad = 0; -#endif - stack->head.contents.aba_ctr = 0; - return stack; -} - -void gpr_stack_lockfree_destroy(gpr_stack_lockfree *stack) { - gpr_free_aligned(stack->entries); - gpr_free(stack); -} - -int gpr_stack_lockfree_push(gpr_stack_lockfree *stack, int entry) { - lockfree_node head; - lockfree_node newhead; - lockfree_node curent; - lockfree_node newent; - - /* First fill in the entry's index and aba ctr for new head */ - newhead.contents.index = (uint16_t)entry; -#ifdef GPR_ARCH_64 - /* Fill in the pad to avoid confusing memcheck tools */ - newhead.contents.pad = 0; -#endif - - /* Also post-increment the aba_ctr */ - curent.atm = gpr_atm_no_barrier_load(&stack->entries[entry].atm); - newhead.contents.aba_ctr = ++curent.contents.aba_ctr; - gpr_atm_no_barrier_store(&stack->entries[entry].atm, curent.atm); - - do { - /* Atomically get the existing head value for use */ - head.atm = gpr_atm_no_barrier_load(&(stack->head.atm)); - /* Point to it */ - newent.atm = gpr_atm_no_barrier_load(&stack->entries[entry].atm); - newent.contents.index = head.contents.index; - gpr_atm_no_barrier_store(&stack->entries[entry].atm, newent.atm); - } while (!gpr_atm_rel_cas(&(stack->head.atm), head.atm, newhead.atm)); - /* Use rel_cas above to make sure that entry index is set properly */ - return head.contents.index == INVALID_ENTRY_INDEX; -} - -int gpr_stack_lockfree_pop(gpr_stack_lockfree *stack) { - lockfree_node head; - lockfree_node newhead; - - do { - head.atm = gpr_atm_acq_load(&(stack->head.atm)); - if (head.contents.index == INVALID_ENTRY_INDEX) { - return -1; - } - newhead.atm = - gpr_atm_no_barrier_load(&(stack->entries[head.contents.index].atm)); - - } while (!gpr_atm_no_barrier_cas(&(stack->head.atm), head.atm, newhead.atm)); - - return head.contents.index; -} diff --git a/src/core/lib/support/stack_lockfree.h b/src/core/lib/support/stack_lockfree.h deleted file mode 100644 index 706f63fbf69..00000000000 --- a/src/core/lib/support/stack_lockfree.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_SUPPORT_STACK_LOCKFREE_H -#define GRPC_CORE_LIB_SUPPORT_STACK_LOCKFREE_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct gpr_stack_lockfree gpr_stack_lockfree; - -/* This stack must specify the maximum number of entries to track. - The current implementation only allows up to 65534 entries */ -gpr_stack_lockfree *gpr_stack_lockfree_create(size_t entries); -void gpr_stack_lockfree_destroy(gpr_stack_lockfree *stack); - -/* Pass in a valid entry number for the next stack entry */ -/* Returns 1 if this is the first element on the stack, 0 otherwise */ -int gpr_stack_lockfree_push(gpr_stack_lockfree *, int entry); - -/* Returns -1 on empty or the actual entry number */ -int gpr_stack_lockfree_pop(gpr_stack_lockfree *stack); - -#ifdef __cplusplus -} -#endif - -#endif /* GRPC_CORE_LIB_SUPPORT_STACK_LOCKFREE_H */ diff --git a/src/core/lib/support/string.cc b/src/core/lib/support/string.cc index d55863892fc..e31ad72c68f 100644 --- a/src/core/lib/support/string.cc +++ b/src/core/lib/support/string.cc @@ -30,16 +30,16 @@ #include #include -char *gpr_strdup(const char *src) { - char *dst; +char* gpr_strdup(const char* src) { + char* dst; size_t len; if (!src) { - return NULL; + return nullptr; } len = strlen(src) + 1; - dst = (char *)gpr_malloc(len); + dst = (char*)gpr_malloc(len); memcpy(dst, src, len); @@ -49,28 +49,28 @@ char *gpr_strdup(const char *src) { typedef struct { size_t capacity; size_t length; - char *data; + char* data; } dump_out; static dump_out dump_out_create(void) { - dump_out r = {0, 0, NULL}; + dump_out r = {0, 0, nullptr}; return r; } -static void dump_out_append(dump_out *out, char c) { +static void dump_out_append(dump_out* out, char c) { if (out->length == out->capacity) { out->capacity = GPR_MAX(8, 2 * out->capacity); - out->data = (char *)gpr_realloc(out->data, out->capacity); + out->data = (char*)gpr_realloc(out->data, out->capacity); } out->data[out->length++] = c; } -static void hexdump(dump_out *out, const char *buf, size_t len) { - static const char *hex = "0123456789abcdef"; +static void hexdump(dump_out* out, const char* buf, size_t len) { + static const char* hex = "0123456789abcdef"; - const uint8_t *const beg = (const uint8_t *)buf; - const uint8_t *const end = beg + len; - const uint8_t *cur; + const uint8_t* const beg = (const uint8_t*)buf; + const uint8_t* const end = beg + len; + const uint8_t* cur; for (cur = beg; cur != end; ++cur) { if (cur != beg) dump_out_append(out, ' '); @@ -79,24 +79,24 @@ static void hexdump(dump_out *out, const char *buf, size_t len) { } } -static void asciidump(dump_out *out, const char *buf, size_t len) { - const uint8_t *const beg = (const uint8_t *)buf; - const uint8_t *const end = beg + len; - const uint8_t *cur; +static void asciidump(dump_out* out, const char* buf, size_t len) { + const uint8_t* const beg = (const uint8_t*)buf; + const uint8_t* const end = beg + len; + const uint8_t* cur; int out_was_empty = (out->length == 0); if (!out_was_empty) { dump_out_append(out, ' '); dump_out_append(out, '\''); } for (cur = beg; cur != end; ++cur) { - dump_out_append(out, (char)(isprint(*cur) ? *(char *)cur : '.')); + dump_out_append(out, (char)(isprint(*cur) ? *(char*)cur : '.')); } if (!out_was_empty) { dump_out_append(out, '\''); } } -char *gpr_dump(const char *buf, size_t len, uint32_t flags) { +char* gpr_dump(const char* buf, size_t len, uint32_t flags) { dump_out out = dump_out_create(); if (flags & GPR_DUMP_HEX) { hexdump(&out, buf, len); @@ -108,7 +108,7 @@ char *gpr_dump(const char *buf, size_t len, uint32_t flags) { return out.data; } -int gpr_parse_bytes_to_uint32(const char *buf, size_t len, uint32_t *result) { +int gpr_parse_bytes_to_uint32(const char* buf, size_t len, uint32_t* result) { uint32_t out = 0; uint32_t new_val; size_t i; @@ -126,7 +126,7 @@ int gpr_parse_bytes_to_uint32(const char *buf, size_t len, uint32_t *result) { return 1; } -void gpr_reverse_bytes(char *str, int len) { +void gpr_reverse_bytes(char* str, int len) { char *p1, *p2; for (p1 = str, p2 = str + len - 1; p2 > p1; ++p1, --p2) { char temp = *p1; @@ -135,7 +135,7 @@ void gpr_reverse_bytes(char *str, int len) { } } -int gpr_ltoa(long value, char *string) { +int gpr_ltoa(long value, char* string) { long sign; int i = 0; @@ -156,7 +156,7 @@ int gpr_ltoa(long value, char *string) { return i; } -int int64_ttoa(int64_t value, char *string) { +int int64_ttoa(int64_t value, char* string) { int64_t sign; int i = 0; @@ -177,33 +177,33 @@ int int64_ttoa(int64_t value, char *string) { return i; } -int gpr_parse_nonnegative_int(const char *value) { - char *end; +int gpr_parse_nonnegative_int(const char* value) { + char* end; long result = strtol(value, &end, 0); if (*end != '\0' || result < 0 || result > INT_MAX) return -1; return (int)result; } -char *gpr_leftpad(const char *str, char flag, size_t length) { +char* gpr_leftpad(const char* str, char flag, size_t length) { const size_t str_length = strlen(str); const size_t out_length = str_length > length ? str_length : length; - char *out = (char *)gpr_malloc(out_length + 1); + char* out = (char*)gpr_malloc(out_length + 1); memset(out, flag, out_length - str_length); memcpy(out + out_length - str_length, str, str_length); out[out_length] = 0; return out; } -char *gpr_strjoin(const char **strs, size_t nstrs, size_t *final_length) { +char* gpr_strjoin(const char** strs, size_t nstrs, size_t* final_length) { return gpr_strjoin_sep(strs, nstrs, "", final_length); } -char *gpr_strjoin_sep(const char **strs, size_t nstrs, const char *sep, - size_t *final_length) { +char* gpr_strjoin_sep(const char** strs, size_t nstrs, const char* sep, + size_t* final_length) { const size_t sep_len = strlen(sep); size_t out_length = 0; size_t i; - char *out; + char* out; for (i = 0; i < nstrs; i++) { out_length += strlen(strs[i]); } @@ -211,7 +211,7 @@ char *gpr_strjoin_sep(const char **strs, size_t nstrs, const char *sep, if (nstrs > 0) { out_length += sep_len * (nstrs - 1); /* separators */ } - out = (char *)gpr_malloc(out_length); + out = (char*)gpr_malloc(out_length); out_length = 0; for (i = 0; i < nstrs; i++) { const size_t slen = strlen(strs[i]); @@ -223,15 +223,15 @@ char *gpr_strjoin_sep(const char **strs, size_t nstrs, const char *sep, out_length += slen; } out[out_length] = 0; - if (final_length != NULL) { + if (final_length != nullptr) { *final_length = out_length; } return out; } -void gpr_strvec_init(gpr_strvec *sv) { memset(sv, 0, sizeof(*sv)); } +void gpr_strvec_init(gpr_strvec* sv) { memset(sv, 0, sizeof(*sv)); } -void gpr_strvec_destroy(gpr_strvec *sv) { +void gpr_strvec_destroy(gpr_strvec* sv) { size_t i; for (i = 0; i < sv->count; i++) { gpr_free(sv->strs[i]); @@ -239,19 +239,19 @@ void gpr_strvec_destroy(gpr_strvec *sv) { gpr_free(sv->strs); } -void gpr_strvec_add(gpr_strvec *sv, char *str) { +void gpr_strvec_add(gpr_strvec* sv, char* str) { if (sv->count == sv->capacity) { sv->capacity = GPR_MAX(sv->capacity + 8, sv->capacity * 2); - sv->strs = (char **)gpr_realloc(sv->strs, sizeof(char *) * sv->capacity); + sv->strs = (char**)gpr_realloc(sv->strs, sizeof(char*) * sv->capacity); } sv->strs[sv->count++] = str; } -char *gpr_strvec_flatten(gpr_strvec *sv, size_t *final_length) { - return gpr_strjoin((const char **)sv->strs, sv->count, final_length); +char* gpr_strvec_flatten(gpr_strvec* sv, size_t* final_length) { + return gpr_strjoin((const char**)sv->strs, sv->count, final_length); } -int gpr_stricmp(const char *a, const char *b) { +int gpr_stricmp(const char* a, const char* b) { int ca, cb; do { ca = tolower(*a); @@ -262,23 +262,23 @@ int gpr_stricmp(const char *a, const char *b) { return ca - cb; } -static void add_string_to_split(const char *beg, const char *end, char ***strs, - size_t *nstrs, size_t *capstrs) { - char *out = (char *)gpr_malloc((size_t)(end - beg) + 1); +static void add_string_to_split(const char* beg, const char* end, char*** strs, + size_t* nstrs, size_t* capstrs) { + char* out = (char*)gpr_malloc((size_t)(end - beg) + 1); memcpy(out, beg, (size_t)(end - beg)); out[end - beg] = 0; if (*nstrs == *capstrs) { *capstrs = GPR_MAX(8, 2 * *capstrs); - *strs = (char **)gpr_realloc(*strs, sizeof(*strs) * *capstrs); + *strs = (char**)gpr_realloc(*strs, sizeof(*strs) * *capstrs); } (*strs)[*nstrs] = out; ++*nstrs; } -void gpr_string_split(const char *input, const char *sep, char ***strs, - size_t *nstrs) { - const char *next; - *strs = NULL; +void gpr_string_split(const char* input, const char* sep, char*** strs, + size_t* nstrs) { + const char* next; + *strs = nullptr; *nstrs = 0; size_t capstrs = 0; while ((next = strstr(input, sep))) { @@ -288,24 +288,24 @@ void gpr_string_split(const char *input, const char *sep, char ***strs, add_string_to_split(input, input + strlen(input), strs, nstrs, &capstrs); } -void *gpr_memrchr(const void *s, int c, size_t n) { - if (s == NULL) return NULL; - char *b = (char *)s; +void* gpr_memrchr(const void* s, int c, size_t n) { + if (s == nullptr) return nullptr; + char* b = (char*)s; size_t i; for (i = 0; i < n; i++) { if (b[n - i - 1] == c) { return &b[n - i - 1]; } } - return NULL; + return nullptr; } -bool gpr_is_true(const char *s) { +bool gpr_is_true(const char* s) { size_t i; - if (s == NULL) { + if (s == nullptr) { return false; } - static const char *truthy[] = {"yes", "true", "1"}; + static const char* truthy[] = {"yes", "true", "1"}; for (i = 0; i < GPR_ARRAY_SIZE(truthy); i++) { if (0 == gpr_stricmp(s, truthy[i])) { return true; diff --git a/src/core/lib/support/string.h b/src/core/lib/support/string.h index 5a56fa3a0a8..dd37f0b0e19 100644 --- a/src/core/lib/support/string.h +++ b/src/core/lib/support/string.h @@ -24,10 +24,6 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /* String utility functions */ /* Flags for gpr_dump function. */ @@ -36,12 +32,12 @@ extern "C" { /* Converts array buf, of length len, into a C string according to the flags. Result should be freed with gpr_free() */ -char *gpr_dump(const char *buf, size_t len, uint32_t flags); +char* gpr_dump(const char* buf, size_t len, uint32_t flags); /* Parses an array of bytes into an integer (base 10). Returns 1 on success, 0 on failure. */ -int gpr_parse_bytes_to_uint32(const char *data, size_t length, - uint32_t *result); +int gpr_parse_bytes_to_uint32(const char* data, size_t length, + uint32_t* result); /* Minimum buffer size for calling ltoa */ #define GPR_LTOA_MIN_BUFSIZE (3 * sizeof(long)) @@ -49,7 +45,7 @@ int gpr_parse_bytes_to_uint32(const char *data, size_t length, /* Convert a long to a string in base 10; returns the length of the output string (or 0 on failure). output must be at least GPR_LTOA_MIN_BUFSIZE bytes long. */ -int gpr_ltoa(long value, char *output); +int gpr_ltoa(long value, char* output); /* Minimum buffer size for calling int64toa */ #define GPR_INT64TOA_MIN_BUFSIZE (3 * sizeof(int64_t)) @@ -59,58 +55,55 @@ output string (or 0 on failure). output must be at least GPR_INT64TOA_MIN_BUFSIZE bytes long. NOTE: This function ensures sufficient bit width even on Win x64, where long is 32bit is size.*/ -int int64_ttoa(int64_t value, char *output); +int int64_ttoa(int64_t value, char* output); // Parses a non-negative number from a value string. Returns -1 on error. -int gpr_parse_nonnegative_int(const char *value); +int gpr_parse_nonnegative_int(const char* value); /* Reverse a run of bytes */ -void gpr_reverse_bytes(char *str, int len); +void gpr_reverse_bytes(char* str, int len); /* Pad a string with flag characters. The given length specifies the minimum field width. The input string is never truncated. */ -char *gpr_leftpad(const char *str, char flag, size_t length); +char* gpr_leftpad(const char* str, char flag, size_t length); /* Join a set of strings, returning the resulting string. Total combined length (excluding null terminator) is returned in total_length if it is non-null. */ -char *gpr_strjoin(const char **strs, size_t nstrs, size_t *total_length); +char* gpr_strjoin(const char** strs, size_t nstrs, size_t* total_length); /* Join a set of strings using a separator, returning the resulting string. Total combined length (excluding null terminator) is returned in total_length if it is non-null. */ -char *gpr_strjoin_sep(const char **strs, size_t nstrs, const char *sep, - size_t *total_length); +char* gpr_strjoin_sep(const char** strs, size_t nstrs, const char* sep, + size_t* total_length); -void gpr_string_split(const char *input, const char *sep, char ***strs, - size_t *nstrs); +void gpr_string_split(const char* input, const char* sep, char*** strs, + size_t* nstrs); /* A vector of strings... for building up a final string one piece at a time */ typedef struct { - char **strs; + char** strs; size_t count; size_t capacity; } gpr_strvec; /* Initialize/destroy */ -void gpr_strvec_init(gpr_strvec *strs); -void gpr_strvec_destroy(gpr_strvec *strs); +void gpr_strvec_init(gpr_strvec* strs); +void gpr_strvec_destroy(gpr_strvec* strs); /* Add a string to a strvec, takes ownership of the string */ -void gpr_strvec_add(gpr_strvec *strs, char *add); +void gpr_strvec_add(gpr_strvec* strs, char* add); /* Return a joined string with all added substrings, optionally setting total_length as per gpr_strjoin */ -char *gpr_strvec_flatten(gpr_strvec *strs, size_t *total_length); +char* gpr_strvec_flatten(gpr_strvec* strs, size_t* total_length); /** Case insensitive string comparison... return <0 if lower(a)0 if lower(a)>lower(b) */ -int gpr_stricmp(const char *a, const char *b); +int gpr_stricmp(const char* a, const char* b); -void *gpr_memrchr(const void *s, int c, size_t n); +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); -#ifdef __cplusplus -} -#endif +bool gpr_is_true(const char* s); #endif /* GRPC_CORE_LIB_SUPPORT_STRING_H */ diff --git a/src/core/lib/support/string_posix.cc b/src/core/lib/support/string_posix.cc index 92de21a6e1e..8b818e39b9d 100644 --- a/src/core/lib/support/string_posix.cc +++ b/src/core/lib/support/string_posix.cc @@ -27,7 +27,7 @@ #include #include -int gpr_asprintf(char **strp, const char *format, ...) { +int gpr_asprintf(char** strp, const char* format, ...) { va_list args; int ret; char buf[64]; @@ -38,13 +38,13 @@ int gpr_asprintf(char **strp, const char *format, ...) { ret = vsnprintf(buf, sizeof(buf), format, args); va_end(args); if (ret < 0) { - *strp = NULL; + *strp = nullptr; return -1; } /* Allocate a new buffer, with space for the NUL terminator. */ strp_buflen = (size_t)ret + 1; - if ((*strp = (char *)gpr_malloc(strp_buflen)) == NULL) { + if ((*strp = (char*)gpr_malloc(strp_buflen)) == nullptr) { /* This shouldn't happen, because gpr_malloc() calls abort(). */ return -1; } @@ -65,7 +65,7 @@ int gpr_asprintf(char **strp, const char *format, ...) { /* This should never happen. */ gpr_free(*strp); - *strp = NULL; + *strp = nullptr; return -1; } diff --git a/src/core/lib/support/string_util_windows.cc b/src/core/lib/support/string_util_windows.cc index b365512ee38..e2b386be55c 100644 --- a/src/core/lib/support/string_util_windows.cc +++ b/src/core/lib/support/string_util_windows.cc @@ -65,9 +65,9 @@ LPSTR gpr_tchar_to_char(LPCTSTR input) { return (LPSTR)gpr_strdup(input); } LPTSTR gpr_char_to_tchar(LPCTSTR input) { return (LPTSTR)gpr_strdup(input); } #endif -char *gpr_format_message(int messageid) { +char* gpr_format_message(int messageid) { LPTSTR tmessage; - char *message; + char* message; DWORD status = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, diff --git a/src/core/lib/support/string_windows.cc b/src/core/lib/support/string_windows.cc index d37863c0662..ceb78f00543 100644 --- a/src/core/lib/support/string_windows.cc +++ b/src/core/lib/support/string_windows.cc @@ -31,7 +31,7 @@ #include "src/core/lib/support/string.h" -int gpr_asprintf(char **strp, const char *format, ...) { +int gpr_asprintf(char** strp, const char* format, ...) { va_list args; int ret; size_t strp_buflen; @@ -47,7 +47,7 @@ int gpr_asprintf(char **strp, const char *format, ...) { /* Allocate a new buffer, with space for the NUL terminator. */ strp_buflen = (size_t)ret + 1; - if ((*strp = (char *)gpr_malloc(strp_buflen)) == NULL) { + if ((*strp = (char*)gpr_malloc(strp_buflen)) == NULL) { /* This shouldn't happen, because gpr_malloc() calls abort(). */ return -1; } diff --git a/src/core/lib/support/string_windows.h b/src/core/lib/support/string_windows.h index 67716475813..7c7f31e7aaf 100644 --- a/src/core/lib/support/string_windows.h +++ b/src/core/lib/support/string_windows.h @@ -21,10 +21,6 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - #ifdef GPR_WINDOWS /* These allocate new strings using gpr_malloc to convert from and to utf-8. */ @@ -33,8 +29,4 @@ LPSTR gpr_tchar_to_char(LPCTSTR input); #endif /* GPR_WINDOWS */ -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SUPPORT_STRING_WINDOWS_H */ diff --git a/src/core/lib/support/subprocess_posix.cc b/src/core/lib/support/subprocess_posix.cc index af75162ee93..dc046b64997 100644 --- a/src/core/lib/support/subprocess_posix.cc +++ b/src/core/lib/support/subprocess_posix.cc @@ -41,33 +41,33 @@ struct gpr_subprocess { bool joined; }; -const char *gpr_subprocess_binary_extension() { return ""; } +const char* gpr_subprocess_binary_extension() { return ""; } -gpr_subprocess *gpr_subprocess_create(int argc, const char **argv) { - gpr_subprocess *r; +gpr_subprocess* gpr_subprocess_create(int argc, const char** argv) { + gpr_subprocess* r; int pid; - char **exec_args; + char** exec_args; pid = fork(); if (pid == -1) { - return NULL; + return nullptr; } else if (pid == 0) { - exec_args = (char **)gpr_malloc(((size_t)argc + 1) * sizeof(char *)); - memcpy(exec_args, argv, (size_t)argc * sizeof(char *)); - exec_args[argc] = NULL; + exec_args = (char**)gpr_malloc(((size_t)argc + 1) * sizeof(char*)); + memcpy(exec_args, argv, (size_t)argc * sizeof(char*)); + exec_args[argc] = nullptr; execv(exec_args[0], exec_args); /* if we reach here, an error has occurred */ gpr_log(GPR_ERROR, "execv '%s' failed: %s", exec_args[0], strerror(errno)); _exit(1); - return NULL; + return nullptr; } else { - r = (gpr_subprocess *)gpr_zalloc(sizeof(gpr_subprocess)); + r = (gpr_subprocess*)gpr_zalloc(sizeof(gpr_subprocess)); r->pid = pid; return r; } } -void gpr_subprocess_destroy(gpr_subprocess *p) { +void gpr_subprocess_destroy(gpr_subprocess* p) { if (!p->joined) { kill(p->pid, SIGKILL); gpr_subprocess_join(p); @@ -75,7 +75,7 @@ void gpr_subprocess_destroy(gpr_subprocess *p) { gpr_free(p); } -int gpr_subprocess_join(gpr_subprocess *p) { +int gpr_subprocess_join(gpr_subprocess* p) { int status; retry: if (waitpid(p->pid, &status, 0) == -1) { @@ -90,7 +90,7 @@ retry: return status; } -void gpr_subprocess_interrupt(gpr_subprocess *p) { +void gpr_subprocess_interrupt(gpr_subprocess* p) { if (!p->joined) { kill(p->pid, SIGINT); } diff --git a/src/core/lib/support/subprocess_windows.cc b/src/core/lib/support/subprocess_windows.cc index 6769f1d3a4b..dcdafb5a637 100644 --- a/src/core/lib/support/subprocess_windows.cc +++ b/src/core/lib/support/subprocess_windows.cc @@ -36,16 +36,16 @@ struct gpr_subprocess { int interrupted; }; -const char *gpr_subprocess_binary_extension() { return ".exe"; } +const char* gpr_subprocess_binary_extension() { return ".exe"; } -gpr_subprocess *gpr_subprocess_create(int argc, const char **argv) { - gpr_subprocess *r; +gpr_subprocess* gpr_subprocess_create(int argc, const char** argv) { + gpr_subprocess* r; STARTUPINFO si; PROCESS_INFORMATION pi; - char *args = gpr_strjoin_sep(argv, (size_t)argc, " ", NULL); - TCHAR *args_tchar; + char* args = gpr_strjoin_sep(argv, (size_t)argc, " ", NULL); + TCHAR* args_tchar; args_tchar = gpr_char_to_tchar(args); gpr_free(args); @@ -61,13 +61,13 @@ gpr_subprocess *gpr_subprocess_create(int argc, const char **argv) { } gpr_free(args_tchar); - r = (gpr_subprocess *)gpr_malloc(sizeof(gpr_subprocess)); + r = (gpr_subprocess*)gpr_malloc(sizeof(gpr_subprocess)); memset(r, 0, sizeof(*r)); r->pi = pi; return r; } -void gpr_subprocess_destroy(gpr_subprocess *p) { +void gpr_subprocess_destroy(gpr_subprocess* p) { if (p) { if (!p->joined) { gpr_subprocess_interrupt(p); @@ -83,7 +83,7 @@ void gpr_subprocess_destroy(gpr_subprocess *p) { } } -int gpr_subprocess_join(gpr_subprocess *p) { +int gpr_subprocess_join(gpr_subprocess* p) { DWORD dwExitCode; if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) { if (dwExitCode == STILL_ACTIVE) { @@ -110,7 +110,7 @@ getExitCode: } } -void gpr_subprocess_interrupt(gpr_subprocess *p) { +void gpr_subprocess_interrupt(gpr_subprocess* p) { DWORD dwExitCode; if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) { if (dwExitCode == STILL_ACTIVE) { diff --git a/src/core/lib/support/sync.cc b/src/core/lib/support/sync.cc index 994dcb0e149..347ffcd00e2 100644 --- a/src/core/lib/support/sync.cc +++ b/src/core/lib/support/sync.cc @@ -45,47 +45,47 @@ static void event_initialize(void) { } /* Hash ev into an element of sync_array[]. */ -static struct sync_array_s *hash(gpr_event *ev) { +static struct sync_array_s* hash(gpr_event* ev) { return &sync_array[((uintptr_t)ev) % event_sync_partitions]; } -void gpr_event_init(gpr_event *ev) { +void gpr_event_init(gpr_event* ev) { gpr_once_init(&event_once, &event_initialize); ev->state = 0; } -void gpr_event_set(gpr_event *ev, void *value) { - struct sync_array_s *s = hash(ev); +void gpr_event_set(gpr_event* ev, void* value) { + struct sync_array_s* s = hash(ev); gpr_mu_lock(&s->mu); GPR_ASSERT(gpr_atm_acq_load(&ev->state) == 0); gpr_atm_rel_store(&ev->state, (gpr_atm)value); gpr_cv_broadcast(&s->cv); gpr_mu_unlock(&s->mu); - GPR_ASSERT(value != NULL); + GPR_ASSERT(value != nullptr); } -void *gpr_event_get(gpr_event *ev) { - return (void *)gpr_atm_acq_load(&ev->state); +void* gpr_event_get(gpr_event* ev) { + return (void*)gpr_atm_acq_load(&ev->state); } -void *gpr_event_wait(gpr_event *ev, gpr_timespec abs_deadline) { - void *result = (void *)gpr_atm_acq_load(&ev->state); - if (result == NULL) { - struct sync_array_s *s = hash(ev); +void* gpr_event_wait(gpr_event* ev, gpr_timespec abs_deadline) { + void* result = (void*)gpr_atm_acq_load(&ev->state); + if (result == nullptr) { + struct sync_array_s* s = hash(ev); gpr_mu_lock(&s->mu); do { - result = (void *)gpr_atm_acq_load(&ev->state); - } while (result == NULL && !gpr_cv_wait(&s->cv, &s->mu, abs_deadline)); + result = (void*)gpr_atm_acq_load(&ev->state); + } while (result == nullptr && !gpr_cv_wait(&s->cv, &s->mu, abs_deadline)); gpr_mu_unlock(&s->mu); } return result; } -void gpr_ref_init(gpr_refcount *r, int n) { gpr_atm_rel_store(&r->count, n); } +void gpr_ref_init(gpr_refcount* r, int n) { gpr_atm_rel_store(&r->count, n); } -void gpr_ref(gpr_refcount *r) { gpr_atm_no_barrier_fetch_add(&r->count, 1); } +void gpr_ref(gpr_refcount* r) { gpr_atm_no_barrier_fetch_add(&r->count, 1); } -void gpr_ref_non_zero(gpr_refcount *r) { +void gpr_ref_non_zero(gpr_refcount* r) { #ifndef NDEBUG gpr_atm prior = gpr_atm_no_barrier_fetch_add(&r->count, 1); assert(prior > 0); @@ -94,29 +94,29 @@ void gpr_ref_non_zero(gpr_refcount *r) { #endif } -void gpr_refn(gpr_refcount *r, int n) { +void gpr_refn(gpr_refcount* r, int n) { gpr_atm_no_barrier_fetch_add(&r->count, n); } -int gpr_unref(gpr_refcount *r) { +int gpr_unref(gpr_refcount* r) { gpr_atm prior = gpr_atm_full_fetch_add(&r->count, -1); GPR_ASSERT(prior > 0); return prior == 1; } -int gpr_ref_is_unique(gpr_refcount *r) { +int gpr_ref_is_unique(gpr_refcount* r) { return gpr_atm_acq_load(&r->count) == 1; } -void gpr_stats_init(gpr_stats_counter *c, intptr_t n) { +void gpr_stats_init(gpr_stats_counter* c, intptr_t n) { gpr_atm_rel_store(&c->value, n); } -void gpr_stats_inc(gpr_stats_counter *c, intptr_t inc) { +void gpr_stats_inc(gpr_stats_counter* c, intptr_t inc) { gpr_atm_no_barrier_fetch_add(&c->value, inc); } -intptr_t gpr_stats_read(const gpr_stats_counter *c) { +intptr_t gpr_stats_read(const gpr_stats_counter* c) { /* don't need acquire-load, but we have no no-barrier load yet */ return gpr_atm_acq_load(&c->value); } diff --git a/src/core/lib/support/sync_posix.cc b/src/core/lib/support/sync_posix.cc index 62d800b18cc..dfdd233bf43 100644 --- a/src/core/lib/support/sync_posix.cc +++ b/src/core/lib/support/sync_posix.cc @@ -33,7 +33,9 @@ gpr_atm gpr_counter_atm_cas = 0; gpr_atm gpr_counter_atm_add = 0; #endif -void gpr_mu_init(gpr_mu* mu) { GPR_ASSERT(pthread_mutex_init(mu, NULL) == 0); } +void gpr_mu_init(gpr_mu* mu) { + GPR_ASSERT(pthread_mutex_init(mu, nullptr) == 0); +} void gpr_mu_destroy(gpr_mu* mu) { GPR_ASSERT(pthread_mutex_destroy(mu) == 0); } @@ -63,7 +65,9 @@ int gpr_mu_trylock(gpr_mu* mu) { /*----------------------------------------*/ -void gpr_cv_init(gpr_cv* cv) { GPR_ASSERT(pthread_cond_init(cv, NULL) == 0); } +void gpr_cv_init(gpr_cv* cv) { + GPR_ASSERT(pthread_cond_init(cv, nullptr) == 0); +} void gpr_cv_destroy(gpr_cv* cv) { GPR_ASSERT(pthread_cond_destroy(cv) == 0); } diff --git a/src/core/lib/support/sync_windows.cc b/src/core/lib/support/sync_windows.cc index 62fdd40af70..7cd41633d53 100644 --- a/src/core/lib/support/sync_windows.cc +++ b/src/core/lib/support/sync_windows.cc @@ -26,25 +26,25 @@ #include #include -void gpr_mu_init(gpr_mu *mu) { +void gpr_mu_init(gpr_mu* mu) { InitializeCriticalSection(&mu->cs); mu->locked = 0; } -void gpr_mu_destroy(gpr_mu *mu) { DeleteCriticalSection(&mu->cs); } +void gpr_mu_destroy(gpr_mu* mu) { DeleteCriticalSection(&mu->cs); } -void gpr_mu_lock(gpr_mu *mu) { +void gpr_mu_lock(gpr_mu* mu) { EnterCriticalSection(&mu->cs); GPR_ASSERT(!mu->locked); mu->locked = 1; } -void gpr_mu_unlock(gpr_mu *mu) { +void gpr_mu_unlock(gpr_mu* mu) { mu->locked = 0; LeaveCriticalSection(&mu->cs); } -int gpr_mu_trylock(gpr_mu *mu) { +int gpr_mu_trylock(gpr_mu* mu) { int result = TryEnterCriticalSection(&mu->cs); if (result) { if (mu->locked) { /* This thread already holds the lock. */ @@ -58,13 +58,13 @@ int gpr_mu_trylock(gpr_mu *mu) { /*----------------------------------------*/ -void gpr_cv_init(gpr_cv *cv) { InitializeConditionVariable(cv); } +void gpr_cv_init(gpr_cv* cv) { InitializeConditionVariable(cv); } -void gpr_cv_destroy(gpr_cv *cv) { +void gpr_cv_destroy(gpr_cv* cv) { /* Condition variables don't need destruction in Win32. */ } -int gpr_cv_wait(gpr_cv *cv, gpr_mu *mu, gpr_timespec abs_deadline) { +int gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline) { int timeout = 0; DWORD timeout_max_ms; mu->locked = 0; @@ -93,23 +93,23 @@ int gpr_cv_wait(gpr_cv *cv, gpr_mu *mu, gpr_timespec abs_deadline) { return timeout; } -void gpr_cv_signal(gpr_cv *cv) { WakeConditionVariable(cv); } +void gpr_cv_signal(gpr_cv* cv) { WakeConditionVariable(cv); } -void gpr_cv_broadcast(gpr_cv *cv) { WakeAllConditionVariable(cv); } +void gpr_cv_broadcast(gpr_cv* cv) { WakeAllConditionVariable(cv); } /*----------------------------------------*/ -static void *dummy; +static void* dummy; struct run_once_func_arg { void (*init_function)(void); }; -static BOOL CALLBACK run_once_func(gpr_once *once, void *v, void **pv) { - struct run_once_func_arg *arg = (struct run_once_func_arg *)v; +static BOOL CALLBACK run_once_func(gpr_once* once, void* v, void** pv) { + struct run_once_func_arg* arg = (struct run_once_func_arg*)v; (*arg->init_function)(); return 1; } -void gpr_once_init(gpr_once *once, void (*init_function)(void)) { +void gpr_once_init(gpr_once* once, void (*init_function)(void)) { struct run_once_func_arg arg; arg.init_function = init_function; InitOnceExecuteOnce(once, run_once_func, &arg, &dummy); diff --git a/src/core/lib/support/thd_internal.h b/src/core/lib/support/thd_internal.h new file mode 100644 index 00000000000..38bffc847d6 --- /dev/null +++ b/src/core/lib/support/thd_internal.h @@ -0,0 +1,30 @@ +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_SUPPORT_THD_INTERNAL_H +#define GRPC_CORE_LIB_SUPPORT_THD_INTERNAL_H + +#include + +/* Internal interfaces between modules within the gpr support library. */ +void gpr_thd_init(); + +/* Wait for all outstanding threads to finish, up to deadline */ +int gpr_await_threads(gpr_timespec deadline); + +#endif /* GRPC_CORE_LIB_SUPPORT_THD_INTERNAL_H */ diff --git a/src/core/lib/support/thd_posix.cc b/src/core/lib/support/thd_posix.cc index 98afd10df7c..c2a4f4198ff 100644 --- a/src/core/lib/support/thd_posix.cc +++ b/src/core/lib/support/thd_posix.cc @@ -24,36 +24,49 @@ #include #include +#include #include #include #include #include #include +#include "src/core/lib/support/fork.h" + +static gpr_mu g_mu; +static gpr_cv g_cv; +static int g_thread_count; +static int g_awaiting_threads; + struct thd_arg { - void (*body)(void *arg); /* body of a thread */ - void *arg; /* argument to a thread */ + void (*body)(void* arg); /* body of a thread */ + void* arg; /* argument to a thread */ }; +static void inc_thd_count(); +static void dec_thd_count(); + /* Body of every thread started via gpr_thd_new. */ -static void *thread_body(void *v) { - struct thd_arg a = *(struct thd_arg *)v; +static void* thread_body(void* v) { + struct thd_arg a = *(struct thd_arg*)v; free(v); (*a.body)(a.arg); - return NULL; + dec_thd_count(); + return nullptr; } -int gpr_thd_new(gpr_thd_id *t, void (*thd_body)(void *arg), void *arg, - const gpr_thd_options *options) { +int gpr_thd_new(gpr_thd_id* t, void (*thd_body)(void* arg), void* arg, + const gpr_thd_options* options) { int thread_started; pthread_attr_t attr; pthread_t p; /* don't use gpr_malloc as we may cause an infinite recursion with * the profiling code */ - struct thd_arg *a = (struct thd_arg *)malloc(sizeof(*a)); - GPR_ASSERT(a != NULL); + struct thd_arg* a = (struct thd_arg*)malloc(sizeof(*a)); + GPR_ASSERT(a != nullptr); a->body = thd_body; a->arg = arg; + inc_thd_count(); GPR_ASSERT(pthread_attr_init(&attr) == 0); if (gpr_thd_options_is_detached(options)) { @@ -68,6 +81,7 @@ int gpr_thd_new(gpr_thd_id *t, void (*thd_body)(void *arg), void *arg, if (!thread_started) { /* don't use gpr_free, as this was allocated using malloc (see above) */ free(a); + dec_thd_count(); } *t = (gpr_thd_id)p; return thread_started; @@ -75,6 +89,48 @@ int gpr_thd_new(gpr_thd_id *t, void (*thd_body)(void *arg), void *arg, gpr_thd_id gpr_thd_currentid(void) { return (gpr_thd_id)pthread_self(); } -void gpr_thd_join(gpr_thd_id t) { pthread_join((pthread_t)t, NULL); } +void gpr_thd_join(gpr_thd_id t) { pthread_join((pthread_t)t, nullptr); } + +/***************************************** + * Only used when fork support is enabled + */ + +static void inc_thd_count() { + if (grpc_fork_support_enabled()) { + gpr_mu_lock(&g_mu); + g_thread_count++; + gpr_mu_unlock(&g_mu); + } +} + +static void dec_thd_count() { + if (grpc_fork_support_enabled()) { + gpr_mu_lock(&g_mu); + g_thread_count--; + if (g_awaiting_threads && g_thread_count == 0) { + gpr_cv_signal(&g_cv); + } + gpr_mu_unlock(&g_mu); + } +} + +void gpr_thd_init() { + gpr_mu_init(&g_mu); + gpr_cv_init(&g_cv); + g_thread_count = 0; + g_awaiting_threads = 0; +} + +int gpr_await_threads(gpr_timespec deadline) { + gpr_mu_lock(&g_mu); + g_awaiting_threads = 1; + int res = 0; + if (g_thread_count > 0) { + res = gpr_cv_wait(&g_cv, &g_mu, deadline); + } + g_awaiting_threads = 0; + gpr_mu_unlock(&g_mu); + return res == 0; +} #endif /* GPR_POSIX_SYNC */ diff --git a/src/core/lib/support/thd_windows.cc b/src/core/lib/support/thd_windows.cc index 1a82805dd9f..0875c2f03e0 100644 --- a/src/core/lib/support/thd_windows.cc +++ b/src/core/lib/support/thd_windows.cc @@ -36,23 +36,25 @@ #endif struct thd_info { - void (*body)(void *arg); /* body of a thread */ - void *arg; /* argument to a thread */ + void (*body)(void* arg); /* body of a thread */ + void* arg; /* argument to a thread */ HANDLE join_event; /* if joinable, the join event */ int joinable; /* true if not detached */ }; -static thread_local struct thd_info *g_thd_info; +static thread_local struct thd_info* g_thd_info; /* Destroys a thread info */ -static void destroy_thread(struct thd_info *t) { +static void destroy_thread(struct thd_info* t) { if (t->joinable) CloseHandle(t->join_event); gpr_free(t); } +void gpr_thd_init(void) {} + /* Body of every thread started via gpr_thd_new. */ -static DWORD WINAPI thread_body(void *v) { - g_thd_info = (struct thd_info *)v; +static DWORD WINAPI thread_body(void* v) { + g_thd_info = (struct thd_info*)v; g_thd_info->body(g_thd_info->arg); if (g_thd_info->joinable) { BOOL ret = SetEvent(g_thd_info->join_event); @@ -63,10 +65,10 @@ static DWORD WINAPI thread_body(void *v) { return 0; } -int gpr_thd_new(gpr_thd_id *t, void (*thd_body)(void *arg), void *arg, - const gpr_thd_options *options) { +int gpr_thd_new(gpr_thd_id* t, void (*thd_body)(void* arg), void* arg, + const gpr_thd_options* options) { HANDLE handle; - struct thd_info *info = (struct thd_info *)gpr_malloc(sizeof(*info)); + struct thd_info* info = (struct thd_info*)gpr_malloc(sizeof(*info)); info->body = thd_body; info->arg = arg; *t = 0; @@ -93,7 +95,7 @@ int gpr_thd_new(gpr_thd_id *t, void (*thd_body)(void *arg), void *arg, gpr_thd_id gpr_thd_currentid(void) { return (gpr_thd_id)g_thd_info; } void gpr_thd_join(gpr_thd_id t) { - struct thd_info *info = (struct thd_info *)t; + struct thd_info* info = (struct thd_info*)t; DWORD ret = WaitForSingleObject(info->join_event, INFINITE); GPR_ASSERT(ret == WAIT_OBJECT_0); destroy_thread(info); diff --git a/src/core/lib/support/time_posix.cc b/src/core/lib/support/time_posix.cc index 3f8a9094fd6..47a849480f5 100644 --- a/src/core/lib/support/time_posix.cc +++ b/src/core/lib/support/time_posix.cc @@ -81,7 +81,7 @@ static gpr_timespec now_impl(gpr_clock_type clock_type) { } } #else -/* For some reason Apple's OSes haven't implemented clock_gettime. */ + /* For some reason Apple's OSes haven't implemented clock_gettime. */ #include #include @@ -127,9 +127,7 @@ static gpr_timespec now_impl(gpr_clock_type clock) { } #endif -extern "C" { gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type) = now_impl; -} #ifdef GPR_LOW_LEVEL_COUNTERS gpr_atm gpr_now_call_count; @@ -158,7 +156,7 @@ void gpr_sleep_until(gpr_timespec until) { delta = gpr_time_sub(until, now); delta_ts = timespec_from_gpr(delta); - ns_result = nanosleep(&delta_ts, NULL); + ns_result = nanosleep(&delta_ts, nullptr); if (ns_result == 0) { break; } diff --git a/src/core/lib/support/time_precise.cc b/src/core/lib/support/time_precise.cc index 05ef7c59bcc..b7372df1b81 100644 --- a/src/core/lib/support/time_precise.cc +++ b/src/core/lib/support/time_precise.cc @@ -24,7 +24,7 @@ #ifdef GRPC_TIMERS_RDTSC #if defined(__i386__) -static void gpr_get_cycle_counter(int64_t int *clk) { +static void gpr_get_cycle_counter(int64_t int* clk) { int64_t int ret; __asm__ volatile("rdtsc" : "=A"(ret)); *clk = ret; @@ -32,7 +32,7 @@ static void gpr_get_cycle_counter(int64_t int *clk) { // ---------------------------------------------------------------- #elif defined(__x86_64__) || defined(__amd64__) -static void gpr_get_cycle_counter(int64_t *clk) { +static void gpr_get_cycle_counter(int64_t* clk) { uint64_t low, high; __asm__ volatile("rdtsc" : "=a"(low), "=d"(high)); *clk = (int64_t)(high << 32) | (int64_t)low; @@ -56,7 +56,7 @@ void gpr_precise_clock_init(void) { gpr_log(GPR_DEBUG, "... cycles_per_second = %f\n", cycles_per_second); } -void gpr_precise_clock_now(gpr_timespec *clk) { +void gpr_precise_clock_now(gpr_timespec* clk) { int64_t counter; double secs; gpr_get_cycle_counter(&counter); @@ -69,7 +69,7 @@ void gpr_precise_clock_now(gpr_timespec *clk) { #else /* GRPC_TIMERS_RDTSC */ void gpr_precise_clock_init(void) {} -void gpr_precise_clock_now(gpr_timespec *clk) { +void gpr_precise_clock_now(gpr_timespec* clk) { *clk = gpr_now(GPR_CLOCK_REALTIME); clk->clock_type = GPR_CLOCK_PRECISE; } diff --git a/src/core/lib/support/time_precise.h b/src/core/lib/support/time_precise.h index cb15cdf9198..35cd154dbdf 100644 --- a/src/core/lib/support/time_precise.h +++ b/src/core/lib/support/time_precise.h @@ -21,15 +21,7 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - void gpr_precise_clock_init(void); -void gpr_precise_clock_now(gpr_timespec *clk); - -#ifdef __cplusplus -} -#endif +void gpr_precise_clock_now(gpr_timespec* clk); #endif /* GRPC_CORE_LIB_SUPPORT_TIME_PRECISE_H */ diff --git a/src/core/lib/support/time_windows.cc b/src/core/lib/support/time_windows.cc index 08c1b22964a..fb17e5c079f 100644 --- a/src/core/lib/support/time_windows.cc +++ b/src/core/lib/support/time_windows.cc @@ -68,9 +68,7 @@ static gpr_timespec now_impl(gpr_clock_type clock) { return now_tv; } -extern "C" { gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type) = now_impl; -} gpr_timespec gpr_now(gpr_clock_type clock_type) { return gpr_now_impl(clock_type); diff --git a/src/core/lib/support/tls_pthread.cc b/src/core/lib/support/tls_pthread.cc index 9ebee577fe8..ebeef2a8c2d 100644 --- a/src/core/lib/support/tls_pthread.cc +++ b/src/core/lib/support/tls_pthread.cc @@ -22,8 +22,8 @@ #include -intptr_t gpr_tls_set(struct gpr_pthread_thread_local *tls, intptr_t value) { - GPR_ASSERT(0 == pthread_setspecific(tls->key, (void *)value)); +intptr_t gpr_tls_set(struct gpr_pthread_thread_local* tls, intptr_t value) { + GPR_ASSERT(0 == pthread_setspecific(tls->key, (void*)value)); return value; } diff --git a/src/core/lib/support/tmpfile.h b/src/core/lib/support/tmpfile.h index caa1d0f4d2d..c5ceda86751 100644 --- a/src/core/lib/support/tmpfile.h +++ b/src/core/lib/support/tmpfile.h @@ -21,18 +21,10 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /* Creates a temporary file from a prefix. If tmp_filename is not NULL, *tmp_filename is assigned the name of the created file and it is the responsibility of the caller to gpr_free it unless an error occurs in which case it will be set to NULL. */ -FILE *gpr_tmpfile(const char *prefix, char **tmp_filename); - -#ifdef __cplusplus -} -#endif +FILE* gpr_tmpfile(const char* prefix, char** tmp_filename); #endif /* GRPC_CORE_LIB_SUPPORT_TMPFILE_H */ diff --git a/src/core/lib/support/tmpfile_msys.cc b/src/core/lib/support/tmpfile_msys.cc index 614c0a4a188..430e866629f 100644 --- a/src/core/lib/support/tmpfile_msys.cc +++ b/src/core/lib/support/tmpfile_msys.cc @@ -32,8 +32,8 @@ #include "src/core/lib/support/string_windows.h" #include "src/core/lib/support/tmpfile.h" -FILE *gpr_tmpfile(const char *prefix, char **tmp_filename_out) { - FILE *result = NULL; +FILE* gpr_tmpfile(const char* prefix, char** tmp_filename_out) { + FILE* result = NULL; char tmp_filename[MAX_PATH]; UINT success; diff --git a/src/core/lib/support/tmpfile_posix.cc b/src/core/lib/support/tmpfile_posix.cc index 7ad3af0a577..79c5c688742 100644 --- a/src/core/lib/support/tmpfile_posix.cc +++ b/src/core/lib/support/tmpfile_posix.cc @@ -33,15 +33,15 @@ #include "src/core/lib/support/string.h" -FILE *gpr_tmpfile(const char *prefix, char **tmp_filename) { - FILE *result = NULL; - char *filename_template; +FILE* gpr_tmpfile(const char* prefix, char** tmp_filename) { + FILE* result = nullptr; + char* filename_template; int fd; - if (tmp_filename != NULL) *tmp_filename = NULL; + if (tmp_filename != nullptr) *tmp_filename = nullptr; gpr_asprintf(&filename_template, "/tmp/%s_XXXXXX", prefix); - GPR_ASSERT(filename_template != NULL); + GPR_ASSERT(filename_template != nullptr); fd = mkstemp(filename_template); if (fd == -1) { @@ -50,7 +50,7 @@ FILE *gpr_tmpfile(const char *prefix, char **tmp_filename) { goto end; } result = fdopen(fd, "w+"); - if (result == NULL) { + if (result == nullptr) { gpr_log(GPR_ERROR, "Could not open file %s from fd %d (error = %s).", filename_template, fd, strerror(errno)); unlink(filename_template); @@ -59,7 +59,7 @@ FILE *gpr_tmpfile(const char *prefix, char **tmp_filename) { } end: - if (result != NULL && tmp_filename != NULL) { + if (result != nullptr && tmp_filename != nullptr) { *tmp_filename = filename_template; } else { gpr_free(filename_template); diff --git a/src/core/lib/support/tmpfile_windows.cc b/src/core/lib/support/tmpfile_windows.cc index 47b4510a721..2b10bcde437 100644 --- a/src/core/lib/support/tmpfile_windows.cc +++ b/src/core/lib/support/tmpfile_windows.cc @@ -32,8 +32,8 @@ #include "src/core/lib/support/string_windows.h" #include "src/core/lib/support/tmpfile.h" -FILE *gpr_tmpfile(const char *prefix, char **tmp_filename_out) { - FILE *result = NULL; +FILE* gpr_tmpfile(const char* prefix, char** tmp_filename_out) { + FILE* result = NULL; LPTSTR template_string = NULL; TCHAR tmp_path[MAX_PATH]; TCHAR tmp_filename[MAX_PATH]; diff --git a/src/core/lib/support/wrap_memcpy.cc b/src/core/lib/support/wrap_memcpy.cc index c2362bf5b89..9b8608e056c 100644 --- a/src/core/lib/support/wrap_memcpy.cc +++ b/src/core/lib/support/wrap_memcpy.cc @@ -30,11 +30,11 @@ extern "C" { #ifdef __linux__ #if defined(__x86_64__) && !defined(GPR_MUSL_LIBC_COMPAT) __asm__(".symver memcpy,memcpy@GLIBC_2.2.5"); -void *__wrap_memcpy(void *destination, const void *source, size_t num) { +void* __wrap_memcpy(void* destination, const void* source, size_t num) { return memcpy(destination, source, num); } #else /* !__x86_64__ */ -void *__wrap_memcpy(void *destination, const void *source, size_t num) { +void* __wrap_memcpy(void* destination, const void* source, size_t num) { return memmove(destination, source, num); } #endif diff --git a/src/core/lib/surface/alarm.cc b/src/core/lib/surface/alarm.cc index 16a16bfd93b..b1c9f7b1640 100644 --- a/src/core/lib/surface/alarm.cc +++ b/src/core/lib/surface/alarm.cc @@ -27,10 +27,8 @@ #include "src/core/lib/iomgr/timer.h" #include "src/core/lib/surface/completion_queue.h" -#ifndef NDEBUG -grpc_tracer_flag grpc_trace_alarm_refcount = - GRPC_TRACER_INITIALIZER(false, "alarm_refcount"); -#endif +grpc_core::DebugOnlyTraceFlag grpc_trace_alarm_refcount(false, + "alarm_refcount"); struct grpc_alarm { gpr_refcount refs; @@ -38,17 +36,17 @@ struct grpc_alarm { grpc_closure on_alarm; grpc_cq_completion completion; /** completion queue where events about this alarm will be posted */ - grpc_completion_queue *cq; + grpc_completion_queue* cq; /** user supplied tag */ - void *tag; + void* tag; }; -static void alarm_ref(grpc_alarm *alarm) { gpr_ref(&alarm->refs); } +static void alarm_ref(grpc_alarm* alarm) { gpr_ref(&alarm->refs); } -static void alarm_unref(grpc_alarm *alarm) { +static void alarm_unref(grpc_alarm* alarm) { if (gpr_unref(&alarm->refs)) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - if (alarm->cq != NULL) { + if (alarm->cq != nullptr) { GRPC_CQ_INTERNAL_UNREF(&exec_ctx, alarm->cq, "alarm"); } grpc_exec_ctx_finish(&exec_ctx); @@ -57,9 +55,9 @@ static void alarm_unref(grpc_alarm *alarm) { } #ifndef NDEBUG -static void alarm_ref_dbg(grpc_alarm *alarm, const char *reason, - const char *file, int line) { - if (GRPC_TRACER_ON(grpc_trace_alarm_refcount)) { +static void alarm_ref_dbg(grpc_alarm* alarm, const char* reason, + const char* file, int line) { + if (grpc_trace_alarm_refcount.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&alarm->refs.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "Alarm:%p ref %" PRIdPTR " -> %" PRIdPTR " %s", alarm, val, @@ -69,9 +67,9 @@ static void alarm_ref_dbg(grpc_alarm *alarm, const char *reason, alarm_ref(alarm); } -static void alarm_unref_dbg(grpc_alarm *alarm, const char *reason, - const char *file, int line) { - if (GRPC_TRACER_ON(grpc_trace_alarm_refcount)) { +static void alarm_unref_dbg(grpc_alarm* alarm, const char* reason, + const char* file, int line) { + if (grpc_trace_alarm_refcount.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&alarm->refs.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "Alarm:%p Unref %" PRIdPTR " -> %" PRIdPTR " %s", alarm, val, @@ -82,42 +80,42 @@ static void alarm_unref_dbg(grpc_alarm *alarm, const char *reason, } #endif -static void alarm_end_completion(grpc_exec_ctx *exec_ctx, void *arg, - grpc_cq_completion *c) { - grpc_alarm *alarm = (grpc_alarm *)arg; +static void alarm_end_completion(grpc_exec_ctx* exec_ctx, void* arg, + grpc_cq_completion* c) { + grpc_alarm* alarm = (grpc_alarm*)arg; GRPC_ALARM_UNREF(alarm, "dequeue-end-op"); } -static void alarm_cb(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { - grpc_alarm *alarm = (grpc_alarm *)arg; +static void alarm_cb(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { + grpc_alarm* alarm = (grpc_alarm*)arg; /* We are queuing an op on completion queue. This means, the alarm's structure cannot be destroyed until the op is dequeued. Adding an extra ref here and unref'ing when the op is dequeued will achieve this */ GRPC_ALARM_REF(alarm, "queue-end-op"); grpc_cq_end_op(exec_ctx, alarm->cq, alarm->tag, error, alarm_end_completion, - (void *)alarm, &alarm->completion); + (void*)alarm, &alarm->completion); } -grpc_alarm *grpc_alarm_create(void *reserved) { - grpc_alarm *alarm = (grpc_alarm *)gpr_malloc(sizeof(grpc_alarm)); +grpc_alarm* grpc_alarm_create(void* reserved) { + grpc_alarm* alarm = (grpc_alarm*)gpr_malloc(sizeof(grpc_alarm)); #ifndef NDEBUG - if (GRPC_TRACER_ON(grpc_trace_alarm_refcount)) { + if (grpc_trace_alarm_refcount.enabled()) { gpr_log(GPR_DEBUG, "Alarm:%p created (ref: 1)", alarm); } #endif gpr_ref_init(&alarm->refs, 1); grpc_timer_init_unset(&alarm->alarm); - alarm->cq = NULL; + alarm->cq = nullptr; GRPC_CLOSURE_INIT(&alarm->on_alarm, alarm_cb, alarm, grpc_schedule_on_exec_ctx); return alarm; } -void grpc_alarm_set(grpc_alarm *alarm, grpc_completion_queue *cq, - gpr_timespec deadline, void *tag, void *reserved) { +void grpc_alarm_set(grpc_alarm* alarm, grpc_completion_queue* cq, + gpr_timespec deadline, void* tag, void* reserved) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GRPC_CQ_INTERNAL_REF(cq, "alarm"); @@ -130,13 +128,13 @@ void grpc_alarm_set(grpc_alarm *alarm, grpc_completion_queue *cq, grpc_exec_ctx_finish(&exec_ctx); } -void grpc_alarm_cancel(grpc_alarm *alarm, void *reserved) { +void grpc_alarm_cancel(grpc_alarm* alarm, void* reserved) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_timer_cancel(&exec_ctx, &alarm->alarm); grpc_exec_ctx_finish(&exec_ctx); } -void grpc_alarm_destroy(grpc_alarm *alarm, void *reserved) { +void grpc_alarm_destroy(grpc_alarm* alarm, void* reserved) { grpc_alarm_cancel(alarm, reserved); GRPC_ALARM_UNREF(alarm, "alarm_destroy"); } diff --git a/src/core/lib/surface/alarm_internal.h b/src/core/lib/surface/alarm_internal.h index 136b60547fa..99e981234d0 100644 --- a/src/core/lib/surface/alarm_internal.h +++ b/src/core/lib/surface/alarm_internal.h @@ -22,14 +22,10 @@ #include #include "src/core/lib/debug/trace.h" -#ifdef __cplusplus -extern "C" { -#endif +extern grpc_core::DebugOnlyTraceFlag grpc_trace_alarm_refcount; #ifndef NDEBUG -extern grpc_tracer_flag grpc_trace_alarm_refcount; - #define GRPC_ALARM_REF(a, reason) alarm_ref_dbg(a, reason, __FILE__, __LINE__) #define GRPC_ALARM_UNREF(a, reason) \ alarm_unref_dbg(a, reason, __FILE__, __LINE__) @@ -41,8 +37,4 @@ extern grpc_tracer_flag grpc_trace_alarm_refcount; #endif /* defined(NDEBUG) */ -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SURFACE_ALARM_INTERNAL_H */ diff --git a/src/core/lib/surface/api_trace.cc b/src/core/lib/surface/api_trace.cc index 56973303dab..7ab836a9bac 100644 --- a/src/core/lib/surface/api_trace.cc +++ b/src/core/lib/surface/api_trace.cc @@ -19,4 +19,4 @@ #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/debug/trace.h" -grpc_tracer_flag grpc_api_trace = GRPC_TRACER_INITIALIZER(false, "api"); +grpc_core::TraceFlag grpc_api_trace(false, "api"); diff --git a/src/core/lib/surface/api_trace.h b/src/core/lib/surface/api_trace.h index 105abdf629d..a4e11ce1544 100644 --- a/src/core/lib/surface/api_trace.h +++ b/src/core/lib/surface/api_trace.h @@ -22,11 +22,7 @@ #include #include "src/core/lib/debug/trace.h" -#ifdef __cplusplus -extern "C" { -#endif - -extern grpc_tracer_flag grpc_api_trace; +extern grpc_core::TraceFlag grpc_api_trace; /* Provide unwrapping macros because we're in C89 and variadic macros weren't introduced until C99... */ @@ -47,12 +43,8 @@ extern grpc_tracer_flag grpc_api_trace; /* Due to the limitations of C89's preprocessor, the arity of the var-arg list 'nargs' must be specified. */ #define GRPC_API_TRACE(fmt, nargs, args) \ - if (GRPC_TRACER_ON(grpc_api_trace)) { \ + if (grpc_api_trace.enabled()) { \ gpr_log(GPR_INFO, fmt GRPC_API_TRACE_UNWRAP##nargs args); \ } -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SURFACE_API_TRACE_H */ diff --git a/src/core/lib/surface/byte_buffer.cc b/src/core/lib/surface/byte_buffer.cc index 7ed550ef87c..9e0636b4cea 100644 --- a/src/core/lib/surface/byte_buffer.cc +++ b/src/core/lib/surface/byte_buffer.cc @@ -22,18 +22,18 @@ #include "src/core/lib/slice/slice_internal.h" -grpc_byte_buffer *grpc_raw_byte_buffer_create(grpc_slice *slices, +grpc_byte_buffer* grpc_raw_byte_buffer_create(grpc_slice* slices, size_t nslices) { return grpc_raw_compressed_byte_buffer_create(slices, nslices, GRPC_COMPRESS_NONE); } -grpc_byte_buffer *grpc_raw_compressed_byte_buffer_create( - grpc_slice *slices, size_t nslices, +grpc_byte_buffer* grpc_raw_compressed_byte_buffer_create( + grpc_slice* slices, size_t nslices, grpc_compression_algorithm compression) { size_t i; - grpc_byte_buffer *bb = - (grpc_byte_buffer *)gpr_malloc(sizeof(grpc_byte_buffer)); + grpc_byte_buffer* bb = + (grpc_byte_buffer*)gpr_malloc(sizeof(grpc_byte_buffer)); bb->type = GRPC_BB_RAW; bb->data.raw.compression = compression; grpc_slice_buffer_init(&bb->data.raw.slice_buffer); @@ -44,10 +44,10 @@ grpc_byte_buffer *grpc_raw_compressed_byte_buffer_create( return bb; } -grpc_byte_buffer *grpc_raw_byte_buffer_from_reader( - grpc_byte_buffer_reader *reader) { - grpc_byte_buffer *bb = - (grpc_byte_buffer *)gpr_malloc(sizeof(grpc_byte_buffer)); +grpc_byte_buffer* grpc_raw_byte_buffer_from_reader( + grpc_byte_buffer_reader* reader) { + grpc_byte_buffer* bb = + (grpc_byte_buffer*)gpr_malloc(sizeof(grpc_byte_buffer)); grpc_slice slice; bb->type = GRPC_BB_RAW; bb->data.raw.compression = GRPC_COMPRESS_NONE; @@ -59,17 +59,17 @@ grpc_byte_buffer *grpc_raw_byte_buffer_from_reader( return bb; } -grpc_byte_buffer *grpc_byte_buffer_copy(grpc_byte_buffer *bb) { +grpc_byte_buffer* grpc_byte_buffer_copy(grpc_byte_buffer* bb) { switch (bb->type) { case GRPC_BB_RAW: return grpc_raw_compressed_byte_buffer_create( bb->data.raw.slice_buffer.slices, bb->data.raw.slice_buffer.count, bb->data.raw.compression); } - GPR_UNREACHABLE_CODE(return NULL); + GPR_UNREACHABLE_CODE(return nullptr); } -void grpc_byte_buffer_destroy(grpc_byte_buffer *bb) { +void grpc_byte_buffer_destroy(grpc_byte_buffer* bb) { if (!bb) return; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; switch (bb->type) { @@ -81,7 +81,7 @@ void grpc_byte_buffer_destroy(grpc_byte_buffer *bb) { grpc_exec_ctx_finish(&exec_ctx); } -size_t grpc_byte_buffer_length(grpc_byte_buffer *bb) { +size_t grpc_byte_buffer_length(grpc_byte_buffer* bb) { switch (bb->type) { case GRPC_BB_RAW: return bb->data.raw.slice_buffer.length; diff --git a/src/core/lib/surface/byte_buffer_reader.cc b/src/core/lib/surface/byte_buffer_reader.cc index 87bd3239c03..001227a2aa0 100644 --- a/src/core/lib/surface/byte_buffer_reader.cc +++ b/src/core/lib/surface/byte_buffer_reader.cc @@ -29,7 +29,7 @@ #include "src/core/lib/compression/message_compress.h" #include "src/core/lib/slice/slice_internal.h" -static int is_compressed(grpc_byte_buffer *buffer) { +static int is_compressed(grpc_byte_buffer* buffer) { switch (buffer->type) { case GRPC_BB_RAW: if (buffer->data.raw.compression == GRPC_COMPRESS_NONE) { @@ -40,8 +40,8 @@ static int is_compressed(grpc_byte_buffer *buffer) { return 1 /* GPR_TRUE */; } -int grpc_byte_buffer_reader_init(grpc_byte_buffer_reader *reader, - grpc_byte_buffer *buffer) { +int grpc_byte_buffer_reader_init(grpc_byte_buffer_reader* reader, + grpc_byte_buffer* buffer) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_slice_buffer decompressed_slices_buffer; reader->buffer_in = buffer; @@ -76,7 +76,7 @@ int grpc_byte_buffer_reader_init(grpc_byte_buffer_reader *reader, return 1; } -void grpc_byte_buffer_reader_destroy(grpc_byte_buffer_reader *reader) { +void grpc_byte_buffer_reader_destroy(grpc_byte_buffer_reader* reader) { switch (reader->buffer_in->type) { case GRPC_BB_RAW: /* keeping the same if-else structure as in the init function */ @@ -87,11 +87,11 @@ void grpc_byte_buffer_reader_destroy(grpc_byte_buffer_reader *reader) { } } -int grpc_byte_buffer_reader_next(grpc_byte_buffer_reader *reader, - grpc_slice *slice) { +int grpc_byte_buffer_reader_next(grpc_byte_buffer_reader* reader, + grpc_slice* slice) { switch (reader->buffer_in->type) { case GRPC_BB_RAW: { - grpc_slice_buffer *slice_buffer; + grpc_slice_buffer* slice_buffer; slice_buffer = &reader->buffer_out->data.raw.slice_buffer; if (reader->current.index < slice_buffer->count) { *slice = grpc_slice_ref_internal( @@ -105,12 +105,12 @@ int grpc_byte_buffer_reader_next(grpc_byte_buffer_reader *reader, return 0; } -grpc_slice grpc_byte_buffer_reader_readall(grpc_byte_buffer_reader *reader) { +grpc_slice grpc_byte_buffer_reader_readall(grpc_byte_buffer_reader* reader) { grpc_slice in_slice; size_t bytes_read = 0; const size_t input_size = grpc_byte_buffer_length(reader->buffer_out); grpc_slice out_slice = GRPC_SLICE_MALLOC(input_size); - uint8_t *const outbuf = GRPC_SLICE_START_PTR(out_slice); /* just an alias */ + uint8_t* const outbuf = GRPC_SLICE_START_PTR(out_slice); /* just an alias */ grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; while (grpc_byte_buffer_reader_next(reader, &in_slice) != 0) { diff --git a/src/core/lib/surface/call.cc b/src/core/lib/surface/call.cc index 8216aa0ec81..a2eb02bd857 100644 --- a/src/core/lib/surface/call.cc +++ b/src/core/lib/surface/call.cc @@ -86,7 +86,7 @@ typedef enum { typedef struct { bool is_set; - grpc_error *error; + grpc_error* error; } received_status; static gpr_atm pack_received_status(received_status r) { @@ -97,14 +97,14 @@ static received_status unpack_received_status(gpr_atm atm) { if ((atm & 1) == 0) { return {false, GRPC_ERROR_NONE}; } else { - return {true, (grpc_error *)(atm & ~(gpr_atm)1)}; + return {true, (grpc_error*)(atm & ~(gpr_atm)1)}; } } #define MAX_ERRORS_PER_BATCH 4 typedef struct batch_control { - grpc_call *call; + grpc_call* call; /* Share memory for cq_completion and notify_tag as they are never needed simultaneously. Each byte used in this data structure count as six bytes per call, so any savings we can make are worthwhile, @@ -120,7 +120,7 @@ typedef struct batch_control { \a is_closure is true, \a tag indicates a closure to be invoked; otherwise, \a tag indicates the tag to be used in the notification to be sent to the completion queue. */ - void *tag; + void* tag; bool is_closure; } notify_tag; } completion_data; @@ -128,7 +128,7 @@ typedef struct batch_control { grpc_closure finish_batch; gpr_refcount steps_to_complete; - grpc_error *errors[MAX_ERRORS_PER_BATCH]; + grpc_error* errors[MAX_ERRORS_PER_BATCH]; gpr_atm num_errors; grpc_transport_stream_op_batch op; @@ -136,16 +136,16 @@ typedef struct batch_control { typedef struct { gpr_mu child_list_mu; - grpc_call *first_child; + grpc_call* first_child; } parent_call; typedef struct { - grpc_call *parent; + grpc_call* parent; /** siblings: children of the same parent form a list, and this list is protected under parent->mu */ - grpc_call *sibling_next; - grpc_call *sibling_prev; + grpc_call* sibling_next; + grpc_call* sibling_prev; } child_call; #define RECV_NONE ((gpr_atm)0) @@ -153,14 +153,14 @@ typedef struct { struct grpc_call { gpr_refcount ext_ref; - gpr_arena *arena; + gpr_arena* arena; grpc_call_combiner call_combiner; - grpc_completion_queue *cq; + grpc_completion_queue* cq; grpc_polling_entity pollent; - grpc_channel *channel; + grpc_channel* channel; gpr_timespec start_time; /* parent_call* */ gpr_atm parent_call_atm; - child_call *child; + child_call* child; /* client or server call */ bool is_client; @@ -178,7 +178,7 @@ struct grpc_call { gpr_atm any_ops_sent_atm; gpr_atm received_final_op_atm; - batch_control *active_batches[MAX_CONCURRENT_BATCHES]; + batch_control* active_batches[MAX_CONCURRENT_BATCHES]; grpc_transport_stream_op_batch_payload stream_op_payload; /* first idx: is_receiving, second idx: is_trailing */ @@ -186,7 +186,7 @@ struct grpc_call { /* Buffered read metadata waiting to be returned to the application. Element 0 is initial metadata, element 1 is trailing metadata. */ - grpc_metadata_array *buffered_metadata[2]; + grpc_metadata_array* buffered_metadata[2]; grpc_metadata compression_md; @@ -220,8 +220,8 @@ struct grpc_call { grpc_slice_buffer_stream sending_stream; - grpc_byte_stream *receiving_stream; - grpc_byte_buffer **receiving_buffer; + grpc_byte_stream* receiving_stream; + grpc_byte_buffer** receiving_buffer; grpc_slice receiving_slice; grpc_closure receiving_slice_ready; grpc_closure receiving_stream_ready; @@ -232,11 +232,12 @@ struct grpc_call { union { struct { - grpc_status_code *status; - grpc_slice *status_details; + grpc_status_code* status; + grpc_slice* status_details; + const char** error_string; } client; struct { - int *cancelled; + int* cancelled; } server; } final_op; @@ -259,83 +260,82 @@ struct grpc_call { gpr_atm recv_state; }; -grpc_tracer_flag grpc_call_error_trace = - GRPC_TRACER_INITIALIZER(false, "call_error"); -grpc_tracer_flag grpc_compression_trace = - GRPC_TRACER_INITIALIZER(false, "compression"); +grpc_core::TraceFlag grpc_call_error_trace(false, "call_error"); +grpc_core::TraceFlag grpc_compression_trace(false, "compression"); -#define CALL_STACK_FROM_CALL(call) ((grpc_call_stack *)((call) + 1)) -#define CALL_FROM_CALL_STACK(call_stack) (((grpc_call *)(call_stack)) - 1) +#define CALL_STACK_FROM_CALL(call) ((grpc_call_stack*)((call) + 1)) +#define CALL_FROM_CALL_STACK(call_stack) (((grpc_call*)(call_stack)) - 1) #define CALL_ELEM_FROM_CALL(call, idx) \ grpc_call_stack_element(CALL_STACK_FROM_CALL(call), idx) #define CALL_FROM_TOP_ELEM(top_elem) \ CALL_FROM_CALL_STACK(grpc_call_stack_from_top_element(top_elem)) -static void execute_batch(grpc_exec_ctx *exec_ctx, grpc_call *call, - grpc_transport_stream_op_batch *op, - grpc_closure *start_batch_closure); -static void cancel_with_status(grpc_exec_ctx *exec_ctx, grpc_call *c, +static void execute_batch(grpc_exec_ctx* exec_ctx, grpc_call* call, + grpc_transport_stream_op_batch* op, + grpc_closure* start_batch_closure); +static void cancel_with_status(grpc_exec_ctx* exec_ctx, grpc_call* c, status_source source, grpc_status_code status, - const char *description); -static void cancel_with_error(grpc_exec_ctx *exec_ctx, grpc_call *c, - status_source source, grpc_error *error); -static void destroy_call(grpc_exec_ctx *exec_ctx, void *call_stack, - grpc_error *error); -static void receiving_slice_ready(grpc_exec_ctx *exec_ctx, void *bctlp, - grpc_error *error); -static void get_final_status(grpc_exec_ctx *exec_ctx, grpc_call *call, + const char* description); +static void cancel_with_error(grpc_exec_ctx* exec_ctx, grpc_call* c, + status_source source, grpc_error* error); +static void destroy_call(grpc_exec_ctx* exec_ctx, void* call_stack, + grpc_error* error); +static void receiving_slice_ready(grpc_exec_ctx* exec_ctx, void* bctlp, + grpc_error* error); +static void get_final_status(grpc_exec_ctx* exec_ctx, grpc_call* call, void (*set_value)(grpc_status_code code, - void *user_data), - void *set_value_user_data, grpc_slice *details); -static void set_status_value_directly(grpc_status_code status, void *dest); -static void set_status_from_error(grpc_exec_ctx *exec_ctx, grpc_call *call, - status_source source, grpc_error *error); -static void process_data_after_md(grpc_exec_ctx *exec_ctx, batch_control *bctl); -static void post_batch_completion(grpc_exec_ctx *exec_ctx, batch_control *bctl); -static void add_batch_error(grpc_exec_ctx *exec_ctx, batch_control *bctl, - grpc_error *error, bool has_cancelled); - -static void add_init_error(grpc_error **composite, grpc_error *new_err) { + void* user_data), + void* set_value_user_data, grpc_slice* details, + const char** error_string); +static void set_status_value_directly(grpc_status_code status, void* dest); +static void set_status_from_error(grpc_exec_ctx* exec_ctx, grpc_call* call, + status_source source, grpc_error* error); +static void process_data_after_md(grpc_exec_ctx* exec_ctx, batch_control* bctl); +static void post_batch_completion(grpc_exec_ctx* exec_ctx, batch_control* bctl); +static void add_batch_error(grpc_exec_ctx* exec_ctx, batch_control* bctl, + grpc_error* error, bool has_cancelled); + +static void add_init_error(grpc_error** composite, grpc_error* new_err) { if (new_err == GRPC_ERROR_NONE) return; if (*composite == GRPC_ERROR_NONE) *composite = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Call creation failed"); *composite = grpc_error_add_child(*composite, new_err); } -void *grpc_call_arena_alloc(grpc_call *call, size_t size) { +void* grpc_call_arena_alloc(grpc_call* call, size_t size) { return gpr_arena_alloc(call->arena, size); } -static parent_call *get_or_create_parent_call(grpc_call *call) { - parent_call *p = (parent_call *)gpr_atm_acq_load(&call->parent_call_atm); - if (p == NULL) { - p = (parent_call *)gpr_arena_alloc(call->arena, sizeof(*p)); +static parent_call* get_or_create_parent_call(grpc_call* call) { + parent_call* p = (parent_call*)gpr_atm_acq_load(&call->parent_call_atm); + if (p == nullptr) { + p = (parent_call*)gpr_arena_alloc(call->arena, sizeof(*p)); gpr_mu_init(&p->child_list_mu); if (!gpr_atm_rel_cas(&call->parent_call_atm, (gpr_atm)NULL, (gpr_atm)p)) { gpr_mu_destroy(&p->child_list_mu); - p = (parent_call *)gpr_atm_acq_load(&call->parent_call_atm); + p = (parent_call*)gpr_atm_acq_load(&call->parent_call_atm); } } return p; } -static parent_call *get_parent_call(grpc_call *call) { - return (parent_call *)gpr_atm_acq_load(&call->parent_call_atm); +static parent_call* get_parent_call(grpc_call* call) { + return (parent_call*)gpr_atm_acq_load(&call->parent_call_atm); } -grpc_error *grpc_call_create(grpc_exec_ctx *exec_ctx, - const grpc_call_create_args *args, - grpc_call **out_call) { +grpc_error* grpc_call_create(grpc_exec_ctx* exec_ctx, + const grpc_call_create_args* args, + grpc_call** out_call) { size_t i, j; - grpc_error *error = GRPC_ERROR_NONE; - grpc_channel_stack *channel_stack = + grpc_error* error = GRPC_ERROR_NONE; + grpc_channel_stack* channel_stack = grpc_channel_get_channel_stack(args->channel); - grpc_call *call; + grpc_call* call; GPR_TIMER_BEGIN("grpc_call_create", 0); size_t initial_size = grpc_channel_get_call_size_estimate(args->channel); GRPC_STATS_INC_CALL_INITIAL_SIZE(exec_ctx, initial_size); - gpr_arena *arena = gpr_arena_create(initial_size); - call = (grpc_call *)gpr_arena_alloc( + gpr_arena* arena = gpr_arena_create(initial_size); + call = (grpc_call*)gpr_arena_alloc( arena, sizeof(grpc_call) + channel_stack->call_stack_size); gpr_ref_init(&call->ext_ref, 1); call->arena = arena; @@ -346,7 +346,7 @@ grpc_error *grpc_call_create(grpc_exec_ctx *exec_ctx, call->start_time = gpr_now(GPR_CLOCK_MONOTONIC); /* Always support no compression */ GPR_BITSET(&call->encodings_accepted_by_peer, GRPC_COMPRESS_NONE); - call->is_client = args->server_transport_data == NULL; + call->is_client = args->server_transport_data == nullptr; if (call->is_client) { GRPC_STATS_INC_CLIENT_CALLS_CREATED(exec_ctx); } else { @@ -379,16 +379,16 @@ grpc_error *grpc_call_create(grpc_exec_ctx *exec_ctx, bool immediately_cancel = false; - if (args->parent != NULL) { - child_call *cc = call->child = - (child_call *)gpr_arena_alloc(arena, sizeof(child_call)); + if (args->parent != nullptr) { + child_call* cc = call->child = + (child_call*)gpr_arena_alloc(arena, sizeof(child_call)); call->child->parent = args->parent; GRPC_CALL_INTERNAL_REF(args->parent, "child"); GPR_ASSERT(call->is_client); GPR_ASSERT(!args->parent->is_client); - parent_call *pc = get_or_create_parent_call(args->parent); + parent_call* pc = get_or_create_parent_call(args->parent); gpr_mu_lock(&pc->child_list_mu); @@ -407,7 +407,7 @@ grpc_error *grpc_call_create(grpc_exec_ctx *exec_ctx, } grpc_call_context_set(call, GRPC_CONTEXT_TRACING, args->parent->context[GRPC_CONTEXT_TRACING].value, - NULL); + nullptr); } else if (args->propagation_mask & GRPC_PROPAGATE_CENSUS_STATS_CONTEXT) { add_init_error(&error, GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Census context propagation requested " @@ -420,7 +420,7 @@ grpc_error *grpc_call_create(grpc_exec_ctx *exec_ctx, } } - if (pc->first_child == NULL) { + if (pc->first_child == nullptr) { pc->first_child = call; cc->sibling_next = cc->sibling_prev = call; } else { @@ -455,15 +455,15 @@ grpc_error *grpc_call_create(grpc_exec_ctx *exec_ctx, cancel_with_error(exec_ctx, call, STATUS_FROM_API_OVERRIDE, GRPC_ERROR_CANCELLED); } - if (args->cq != NULL) { + if (args->cq != nullptr) { GPR_ASSERT( - args->pollset_set_alternative == NULL && + args->pollset_set_alternative == nullptr && "Only one of 'cq' and 'pollset_set_alternative' should be non-NULL."); GRPC_CQ_INTERNAL_REF(args->cq, "bind"); call->pollent = grpc_polling_entity_create_from_pollset(grpc_cq_pollset(args->cq)); } - if (args->pollset_set_alternative != NULL) { + if (args->pollset_set_alternative != nullptr) { call->pollent = grpc_polling_entity_create_from_pollset_set( args->pollset_set_alternative); } @@ -478,11 +478,11 @@ grpc_error *grpc_call_create(grpc_exec_ctx *exec_ctx, return error; } -void grpc_call_set_completion_queue(grpc_exec_ctx *exec_ctx, grpc_call *call, - grpc_completion_queue *cq) { +void grpc_call_set_completion_queue(grpc_exec_ctx* exec_ctx, grpc_call* call, + grpc_completion_queue* cq) { GPR_ASSERT(cq); - if (grpc_polling_entity_pollset_set(&call->pollent) != NULL) { + if (grpc_polling_entity_pollset_set(&call->pollent) != nullptr) { gpr_log(GPR_ERROR, "A pollset_set is already registered for this call."); abort(); } @@ -495,44 +495,44 @@ void grpc_call_set_completion_queue(grpc_exec_ctx *exec_ctx, grpc_call *call, #ifndef NDEBUG #define REF_REASON reason -#define REF_ARG , const char *reason +#define REF_ARG , const char* reason #else #define REF_REASON "" #define REF_ARG #endif -void grpc_call_internal_ref(grpc_call *c REF_ARG) { +void grpc_call_internal_ref(grpc_call* c REF_ARG) { GRPC_CALL_STACK_REF(CALL_STACK_FROM_CALL(c), REF_REASON); } -void grpc_call_internal_unref(grpc_exec_ctx *exec_ctx, grpc_call *c REF_ARG) { +void grpc_call_internal_unref(grpc_exec_ctx* exec_ctx, grpc_call* c REF_ARG) { GRPC_CALL_STACK_UNREF(exec_ctx, CALL_STACK_FROM_CALL(c), REF_REASON); } -static void release_call(grpc_exec_ctx *exec_ctx, void *call, - grpc_error *error) { - grpc_call *c = (grpc_call *)call; - grpc_channel *channel = c->channel; +static void release_call(grpc_exec_ctx* exec_ctx, void* call, + grpc_error* error) { + grpc_call* c = (grpc_call*)call; + grpc_channel* channel = c->channel; grpc_call_combiner_destroy(&c->call_combiner); - gpr_free((char *)c->peer_string); + gpr_free((char*)c->peer_string); grpc_channel_update_call_size_estimate(channel, gpr_arena_destroy(c->arena)); GRPC_CHANNEL_INTERNAL_UNREF(exec_ctx, channel, "call"); } -static void set_status_value_directly(grpc_status_code status, void *dest); -static void destroy_call(grpc_exec_ctx *exec_ctx, void *call, - grpc_error *error) { +static void set_status_value_directly(grpc_status_code status, void* dest); +static void destroy_call(grpc_exec_ctx* exec_ctx, void* call, + grpc_error* error) { size_t i; int ii; - grpc_call *c = (grpc_call *)call; + grpc_call* c = (grpc_call*)call; GPR_TIMER_BEGIN("destroy_call", 0); for (i = 0; i < 2; i++) { grpc_metadata_batch_destroy( exec_ctx, &c->metadata_batch[1 /* is_receiving */][i /* is_initial */]); } - if (c->receiving_stream != NULL) { + if (c->receiving_stream != nullptr) { grpc_byte_stream_destroy(exec_ctx, c->receiving_stream); } - parent_call *pc = get_parent_call(c); - if (pc != NULL) { + parent_call* pc = get_parent_call(c); + if (pc != nullptr) { gpr_mu_destroy(&pc->child_list_mu); } for (ii = 0; ii < c->send_extra_metadata_count; ii++) { @@ -548,7 +548,8 @@ static void destroy_call(grpc_exec_ctx *exec_ctx, void *call, } get_final_status(exec_ctx, c, set_status_value_directly, - &c->final_info.final_status, NULL); + &c->final_info.final_status, nullptr, + c->final_info.error_string); c->final_info.stats.latency = gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), c->start_time); @@ -563,24 +564,24 @@ static void destroy_call(grpc_exec_ctx *exec_ctx, void *call, GPR_TIMER_END("destroy_call", 0); } -void grpc_call_ref(grpc_call *c) { gpr_ref(&c->ext_ref); } +void grpc_call_ref(grpc_call* c) { gpr_ref(&c->ext_ref); } -void grpc_call_unref(grpc_call *c) { +void grpc_call_unref(grpc_call* c) { if (!gpr_unref(&c->ext_ref)) return; - child_call *cc = c->child; + child_call* cc = c->child; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GPR_TIMER_BEGIN("grpc_call_unref", 0); GRPC_API_TRACE("grpc_call_unref(c=%p)", 1, (c)); if (cc) { - parent_call *pc = get_parent_call(cc->parent); + parent_call* pc = get_parent_call(cc->parent); gpr_mu_lock(&pc->child_list_mu); if (c == pc->first_child) { pc->first_child = cc->sibling_next; if (c == pc->first_child) { - pc->first_child = NULL; + pc->first_child = nullptr; } } cc->sibling_prev->child->sibling_next = cc->sibling_next; @@ -601,14 +602,15 @@ void grpc_call_unref(grpc_call *c) { // effect of scheduling the previously set cancellation closure, if // any, so that it can release any internal references it may be // holding to the call stack. - grpc_call_combiner_set_notify_on_cancel(&exec_ctx, &c->call_combiner, NULL); + grpc_call_combiner_set_notify_on_cancel(&exec_ctx, &c->call_combiner, + nullptr); } GRPC_CALL_INTERNAL_UNREF(&exec_ctx, c, "destroy"); grpc_exec_ctx_finish(&exec_ctx); GPR_TIMER_END("grpc_call_unref", 0); } -grpc_call_error grpc_call_cancel(grpc_call *call, void *reserved) { +grpc_call_error grpc_call_cancel(grpc_call* call, void* reserved) { GRPC_API_TRACE("grpc_call_cancel(call=%p, reserved=%p)", 2, (call, reserved)); GPR_ASSERT(!reserved); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; @@ -620,12 +622,12 @@ grpc_call_error grpc_call_cancel(grpc_call *call, void *reserved) { // This is called via the call combiner to start sending a batch down // the filter stack. -static void execute_batch_in_call_combiner(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *ignored) { - grpc_transport_stream_op_batch *batch = (grpc_transport_stream_op_batch *)arg; - grpc_call *call = (grpc_call *)batch->handler_private.extra_arg; +static void execute_batch_in_call_combiner(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* ignored) { + grpc_transport_stream_op_batch* batch = (grpc_transport_stream_op_batch*)arg; + grpc_call* call = (grpc_call*)batch->handler_private.extra_arg; GPR_TIMER_BEGIN("execute_batch", 0); - grpc_call_element *elem = CALL_ELEM_FROM_CALL(call, 0); + grpc_call_element* elem = CALL_ELEM_FROM_CALL(call, 0); GRPC_CALL_LOG_OP(GPR_INFO, elem, batch); elem->filter->start_transport_stream_op_batch(exec_ctx, elem, batch); GPR_TIMER_END("execute_batch", 0); @@ -633,9 +635,9 @@ static void execute_batch_in_call_combiner(grpc_exec_ctx *exec_ctx, void *arg, // start_batch_closure points to a caller-allocated closure to be used // for entering the call combiner. -static void execute_batch(grpc_exec_ctx *exec_ctx, grpc_call *call, - grpc_transport_stream_op_batch *batch, - grpc_closure *start_batch_closure) { +static void execute_batch(grpc_exec_ctx* exec_ctx, grpc_call* call, + grpc_transport_stream_op_batch* batch, + grpc_closure* start_batch_closure) { batch->handler_private.extra_arg = call; GRPC_CLOSURE_INIT(start_batch_closure, execute_batch_in_call_combiner, batch, grpc_schedule_on_exec_ctx); @@ -643,15 +645,15 @@ static void execute_batch(grpc_exec_ctx *exec_ctx, grpc_call *call, GRPC_ERROR_NONE, "executing batch"); } -char *grpc_call_get_peer(grpc_call *call) { - char *peer_string = (char *)gpr_atm_acq_load(&call->peer_string); - if (peer_string != NULL) return gpr_strdup(peer_string); +char* grpc_call_get_peer(grpc_call* call) { + char* peer_string = (char*)gpr_atm_acq_load(&call->peer_string); + if (peer_string != nullptr) return gpr_strdup(peer_string); peer_string = grpc_channel_get_target(call->channel); - if (peer_string != NULL) return peer_string; + if (peer_string != nullptr) return peer_string; return gpr_strdup("unknown"); } -grpc_call *grpc_call_from_top_element(grpc_call_element *elem) { +grpc_call* grpc_call_from_top_element(grpc_call_element* elem) { return CALL_FROM_TOP_ELEM(elem); } @@ -659,16 +661,16 @@ grpc_call *grpc_call_from_top_element(grpc_call_element *elem) { * CANCELLATION */ -grpc_call_error grpc_call_cancel_with_status(grpc_call *c, +grpc_call_error grpc_call_cancel_with_status(grpc_call* c, grpc_status_code status, - const char *description, - void *reserved) { + const char* description, + void* reserved) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GRPC_API_TRACE( "grpc_call_cancel_with_status(" "c=%p, status=%d, description=%s, reserved=%p)", 4, (c, (int)status, description, reserved)); - GPR_ASSERT(reserved == NULL); + GPR_ASSERT(reserved == nullptr); cancel_with_status(&exec_ctx, c, STATUS_FROM_API_OVERRIDE, status, description); grpc_exec_ctx_finish(&exec_ctx); @@ -676,24 +678,24 @@ grpc_call_error grpc_call_cancel_with_status(grpc_call *c, } typedef struct { - grpc_call *call; + grpc_call* call; grpc_closure start_batch; grpc_closure finish_batch; } cancel_state; // The on_complete callback used when sending a cancel_stream batch down // the filter stack. Yields the call combiner when the batch is done. -static void done_termination(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - cancel_state *state = (cancel_state *)arg; +static void done_termination(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + cancel_state* state = (cancel_state*)arg; GRPC_CALL_COMBINER_STOP(exec_ctx, &state->call->call_combiner, "on_complete for cancel_stream op"); GRPC_CALL_INTERNAL_UNREF(exec_ctx, state->call, "termination"); gpr_free(state); } -static void cancel_with_error(grpc_exec_ctx *exec_ctx, grpc_call *c, - status_source source, grpc_error *error) { +static void cancel_with_error(grpc_exec_ctx* exec_ctx, grpc_call* c, + status_source source, grpc_error* error) { GRPC_CALL_INTERNAL_REF(c, "termination"); // Inform the call combiner of the cancellation, so that it can cancel // any in-flight asynchronous actions that may be holding the call @@ -701,19 +703,19 @@ static void cancel_with_error(grpc_exec_ctx *exec_ctx, grpc_call *c, // down the filter stack in a timely manner. grpc_call_combiner_cancel(exec_ctx, &c->call_combiner, GRPC_ERROR_REF(error)); set_status_from_error(exec_ctx, c, source, GRPC_ERROR_REF(error)); - cancel_state *state = (cancel_state *)gpr_malloc(sizeof(*state)); + cancel_state* state = (cancel_state*)gpr_malloc(sizeof(*state)); state->call = c; GRPC_CLOSURE_INIT(&state->finish_batch, done_termination, state, grpc_schedule_on_exec_ctx); - grpc_transport_stream_op_batch *op = + grpc_transport_stream_op_batch* op = grpc_make_transport_stream_op(&state->finish_batch); op->cancel_stream = true; op->payload->cancel_stream.cancel_error = error; execute_batch(exec_ctx, c, op, &state->start_batch); } -static grpc_error *error_from_status(grpc_status_code status, - const char *description) { +static grpc_error* error_from_status(grpc_status_code status, + const char* description) { // copying 'description' is needed to ensure the grpc_call_cancel_with_status // guarantee that can be short-lived. return grpc_error_set_int( @@ -723,9 +725,9 @@ static grpc_error *error_from_status(grpc_status_code status, GRPC_ERROR_INT_GRPC_STATUS, status); } -static void cancel_with_status(grpc_exec_ctx *exec_ctx, grpc_call *c, +static void cancel_with_status(grpc_exec_ctx* exec_ctx, grpc_call* c, status_source source, grpc_status_code status, - const char *description) { + const char* description) { cancel_with_error(exec_ctx, c, source, error_from_status(status, description)); } @@ -734,37 +736,37 @@ static void cancel_with_status(grpc_exec_ctx *exec_ctx, grpc_call *c, * FINAL STATUS CODE MANIPULATION */ -static bool get_final_status_from(grpc_exec_ctx *exec_ctx, grpc_call *call, - grpc_error *error, bool allow_ok_status, - void (*set_value)(grpc_status_code code, - void *user_data), - void *set_value_user_data, - grpc_slice *details) { +static bool get_final_status_from( + grpc_exec_ctx* exec_ctx, grpc_call* call, grpc_error* error, + bool allow_ok_status, + void (*set_value)(grpc_status_code code, void* user_data), + void* set_value_user_data, grpc_slice* details, const char** error_string) { grpc_status_code code; grpc_slice slice = grpc_empty_slice(); grpc_error_get_status(exec_ctx, error, call->send_deadline, &code, &slice, - NULL); + nullptr, error_string); if (code == GRPC_STATUS_OK && !allow_ok_status) { return false; } set_value(code, set_value_user_data); - if (details != NULL) { + if (details != nullptr) { *details = grpc_slice_ref_internal(slice); } return true; } -static void get_final_status(grpc_exec_ctx *exec_ctx, grpc_call *call, +static void get_final_status(grpc_exec_ctx* exec_ctx, grpc_call* call, void (*set_value)(grpc_status_code code, - void *user_data), - void *set_value_user_data, grpc_slice *details) { + void* user_data), + void* set_value_user_data, grpc_slice* details, + const char** error_string) { int i; received_status status[STATUS_SOURCE_COUNT]; for (i = 0; i < STATUS_SOURCE_COUNT; i++) { status[i] = unpack_received_status(gpr_atm_acq_load(&call->status[i])); } - if (GRPC_TRACER_ON(grpc_call_error_trace)) { + if (grpc_call_error_trace.enabled()) { gpr_log(GPR_DEBUG, "get_final_status %s", call->is_client ? "CLI" : "SVR"); for (i = 0; i < STATUS_SOURCE_COUNT; i++) { if (status[i].is_set) { @@ -782,7 +784,7 @@ static void get_final_status(grpc_exec_ctx *exec_ctx, grpc_call *call, grpc_error_has_clear_grpc_status(status[i].error)) { if (get_final_status_from(exec_ctx, call, status[i].error, allow_ok_status != 0, set_value, - set_value_user_data, details)) { + set_value_user_data, details, error_string)) { return; } } @@ -792,7 +794,7 @@ static void get_final_status(grpc_exec_ctx *exec_ctx, grpc_call *call, if (status[i].is_set) { if (get_final_status_from(exec_ctx, call, status[i].error, allow_ok_status != 0, set_value, - set_value_user_data, details)) { + set_value_user_data, details, error_string)) { return; } } @@ -806,8 +808,8 @@ static void get_final_status(grpc_exec_ctx *exec_ctx, grpc_call *call, } } -static void set_status_from_error(grpc_exec_ctx *exec_ctx, grpc_call *call, - status_source source, grpc_error *error) { +static void set_status_from_error(grpc_exec_ctx* exec_ctx, grpc_call* call, + status_source source, grpc_error* error) { if (!gpr_atm_rel_cas(&call->status[source], pack_received_status({false, GRPC_ERROR_NONE}), pack_received_status({true, error}))) { @@ -820,56 +822,56 @@ static void set_status_from_error(grpc_exec_ctx *exec_ctx, grpc_call *call, */ static void set_incoming_compression_algorithm( - grpc_call *call, grpc_compression_algorithm algo) { + grpc_call* call, grpc_compression_algorithm algo) { GPR_ASSERT(algo < GRPC_COMPRESS_ALGORITHMS_COUNT); call->incoming_compression_algorithm = algo; } static void set_incoming_stream_compression_algorithm( - grpc_call *call, grpc_stream_compression_algorithm algo) { + grpc_call* call, grpc_stream_compression_algorithm algo) { GPR_ASSERT(algo < GRPC_STREAM_COMPRESS_ALGORITHMS_COUNT); call->incoming_stream_compression_algorithm = algo; } grpc_compression_algorithm grpc_call_test_only_get_compression_algorithm( - grpc_call *call) { + grpc_call* call) { grpc_compression_algorithm algorithm; algorithm = call->incoming_compression_algorithm; return algorithm; } static grpc_compression_algorithm compression_algorithm_for_level_locked( - grpc_call *call, grpc_compression_level level) { + grpc_call* call, grpc_compression_level level) { return grpc_compression_algorithm_for_level(level, call->encodings_accepted_by_peer); } static grpc_stream_compression_algorithm stream_compression_algorithm_for_level_locked( - grpc_call *call, grpc_stream_compression_level level) { + grpc_call* call, grpc_stream_compression_level level) { return grpc_stream_compression_algorithm_for_level( level, call->stream_encodings_accepted_by_peer); } -uint32_t grpc_call_test_only_get_message_flags(grpc_call *call) { +uint32_t grpc_call_test_only_get_message_flags(grpc_call* call) { uint32_t flags; flags = call->test_only_last_message_flags; return flags; } -static void destroy_encodings_accepted_by_peer(void *p) { return; } +static void destroy_encodings_accepted_by_peer(void* p) { return; } -static void set_encodings_accepted_by_peer(grpc_exec_ctx *exec_ctx, - grpc_call *call, grpc_mdelem mdel) { +static void set_encodings_accepted_by_peer(grpc_exec_ctx* exec_ctx, + grpc_call* call, grpc_mdelem mdel) { size_t i; grpc_compression_algorithm algorithm; grpc_slice_buffer accept_encoding_parts; grpc_slice accept_encoding_slice; - void *accepted_user_data; + void* accepted_user_data; accepted_user_data = grpc_mdelem_get_user_data(mdel, destroy_encodings_accepted_by_peer); - if (accepted_user_data != NULL) { + if (accepted_user_data != nullptr) { call->encodings_accepted_by_peer = (uint32_t)(((uintptr_t)accepted_user_data) - 1); return; @@ -889,7 +891,7 @@ static void set_encodings_accepted_by_peer(grpc_exec_ctx *exec_ctx, &algorithm)) { GPR_BITSET(&call->encodings_accepted_by_peer, algorithm); } else { - char *accept_encoding_entry_str = + char* accept_encoding_entry_str = grpc_slice_to_c_string(accept_encoding_entry_slice); gpr_log(GPR_ERROR, "Invalid entry in accept encoding metadata: '%s'. Ignoring.", @@ -902,21 +904,21 @@ static void set_encodings_accepted_by_peer(grpc_exec_ctx *exec_ctx, grpc_mdelem_set_user_data( mdel, destroy_encodings_accepted_by_peer, - (void *)(((uintptr_t)call->encodings_accepted_by_peer) + 1)); + (void*)(((uintptr_t)call->encodings_accepted_by_peer) + 1)); } -static void set_stream_encodings_accepted_by_peer(grpc_exec_ctx *exec_ctx, - grpc_call *call, +static void set_stream_encodings_accepted_by_peer(grpc_exec_ctx* exec_ctx, + grpc_call* call, grpc_mdelem mdel) { size_t i; grpc_stream_compression_algorithm algorithm; grpc_slice_buffer accept_encoding_parts; grpc_slice accept_encoding_slice; - void *accepted_user_data; + void* accepted_user_data; accepted_user_data = grpc_mdelem_get_user_data(mdel, destroy_encodings_accepted_by_peer); - if (accepted_user_data != NULL) { + if (accepted_user_data != nullptr) { call->stream_encodings_accepted_by_peer = (uint32_t)(((uintptr_t)accepted_user_data) - 1); return; @@ -935,7 +937,7 @@ static void set_stream_encodings_accepted_by_peer(grpc_exec_ctx *exec_ctx, &algorithm)) { GPR_BITSET(&call->stream_encodings_accepted_by_peer, algorithm); } else { - char *accept_encoding_entry_str = + char* accept_encoding_entry_str = grpc_slice_to_c_string(accept_encoding_entry_slice); gpr_log(GPR_ERROR, "Invalid entry in accept encoding metadata: '%s'. Ignoring.", @@ -948,52 +950,52 @@ static void set_stream_encodings_accepted_by_peer(grpc_exec_ctx *exec_ctx, grpc_mdelem_set_user_data( mdel, destroy_encodings_accepted_by_peer, - (void *)(((uintptr_t)call->stream_encodings_accepted_by_peer) + 1)); + (void*)(((uintptr_t)call->stream_encodings_accepted_by_peer) + 1)); } -uint32_t grpc_call_test_only_get_encodings_accepted_by_peer(grpc_call *call) { +uint32_t grpc_call_test_only_get_encodings_accepted_by_peer(grpc_call* call) { uint32_t encodings_accepted_by_peer; encodings_accepted_by_peer = call->encodings_accepted_by_peer; return encodings_accepted_by_peer; } uint32_t grpc_call_test_only_get_stream_encodings_accepted_by_peer( - grpc_call *call) { + grpc_call* call) { uint32_t stream_encodings_accepted_by_peer; stream_encodings_accepted_by_peer = call->stream_encodings_accepted_by_peer; return stream_encodings_accepted_by_peer; } grpc_stream_compression_algorithm -grpc_call_test_only_get_incoming_stream_encodings(grpc_call *call) { +grpc_call_test_only_get_incoming_stream_encodings(grpc_call* call) { return call->incoming_stream_compression_algorithm; } -static grpc_linked_mdelem *linked_from_md(const grpc_metadata *md) { - return (grpc_linked_mdelem *)&md->internal_data; +static grpc_linked_mdelem* linked_from_md(const grpc_metadata* md) { + return (grpc_linked_mdelem*)&md->internal_data; } -static grpc_metadata *get_md_elem(grpc_metadata *metadata, - grpc_metadata *additional_metadata, int i, +static grpc_metadata* get_md_elem(grpc_metadata* metadata, + grpc_metadata* additional_metadata, int i, int count) { - grpc_metadata *res = + grpc_metadata* res = i < count ? &metadata[i] : &additional_metadata[i - count]; GPR_ASSERT(res); return res; } static int prepare_application_metadata( - grpc_exec_ctx *exec_ctx, grpc_call *call, int count, - grpc_metadata *metadata, int is_trailing, int prepend_extra_metadata, - grpc_metadata *additional_metadata, int additional_metadata_count) { + grpc_exec_ctx* exec_ctx, grpc_call* call, int count, + grpc_metadata* metadata, int is_trailing, int prepend_extra_metadata, + grpc_metadata* additional_metadata, int additional_metadata_count) { int total_count = count + additional_metadata_count; int i; - grpc_metadata_batch *batch = + grpc_metadata_batch* batch = &call->metadata_batch[0 /* is_receiving */][is_trailing]; for (i = 0; i < total_count; i++) { - const grpc_metadata *md = + const grpc_metadata* md = get_md_elem(metadata, additional_metadata, i, count); - grpc_linked_mdelem *l = linked_from_md(md); + grpc_linked_mdelem* l = linked_from_md(md); GPR_ASSERT(sizeof(grpc_linked_mdelem) == sizeof(md->internal_data)); if (!GRPC_LOG_IF_ERROR("validate_metadata", grpc_validate_header_key_is_legal(md->key))) { @@ -1004,13 +1006,13 @@ static int prepare_application_metadata( grpc_validate_header_nonbin_value_is_legal(md->value))) { break; } - l->md = grpc_mdelem_from_grpc_metadata(exec_ctx, (grpc_metadata *)md); + l->md = grpc_mdelem_from_grpc_metadata(exec_ctx, (grpc_metadata*)md); } if (i != total_count) { for (int j = 0; j < i; j++) { - const grpc_metadata *md = + const grpc_metadata* md = get_md_elem(metadata, additional_metadata, j, count); - grpc_linked_mdelem *l = linked_from_md(md); + grpc_linked_mdelem* l = linked_from_md(md); GRPC_MDELEM_UNREF(exec_ctx, l->md); } return 0; @@ -1027,9 +1029,9 @@ static int prepare_application_metadata( } } for (i = 0; i < total_count; i++) { - grpc_metadata *md = get_md_elem(metadata, additional_metadata, i, count); - grpc_linked_mdelem *l = linked_from_md(md); - grpc_error *error = grpc_metadata_batch_link_tail(exec_ctx, batch, l); + grpc_metadata* md = get_md_elem(metadata, additional_metadata, i, count); + grpc_linked_mdelem* l = linked_from_md(md); + grpc_error* error = grpc_metadata_batch_link_tail(exec_ctx, batch, l); if (error != GRPC_ERROR_NONE) { GRPC_MDELEM_UNREF(exec_ctx, l->md); } @@ -1044,23 +1046,23 @@ static int prepare_application_metadata( as metadata cannot store a 0 value (which is used as OK for grpc_status_codes */ #define STATUS_OFFSET 1 -static void destroy_status(void *ignored) {} +static void destroy_status(void* ignored) {} static uint32_t decode_status(grpc_mdelem md) { uint32_t status; - void *user_data; + void* user_data; if (grpc_mdelem_eq(md, GRPC_MDELEM_GRPC_STATUS_0)) return 0; if (grpc_mdelem_eq(md, GRPC_MDELEM_GRPC_STATUS_1)) return 1; if (grpc_mdelem_eq(md, GRPC_MDELEM_GRPC_STATUS_2)) return 2; user_data = grpc_mdelem_get_user_data(md, destroy_status); - if (user_data != NULL) { + if (user_data != nullptr) { status = ((uint32_t)(intptr_t)user_data) - STATUS_OFFSET; } else { if (!grpc_parse_slice_to_uint32(GRPC_MDVALUE(md), &status)) { status = GRPC_STATUS_UNKNOWN; /* could not parse status code */ } grpc_mdelem_set_user_data(md, destroy_status, - (void *)(intptr_t)(status + STATUS_OFFSET)); + (void*)(intptr_t)(status + STATUS_OFFSET)); } return status; } @@ -1069,7 +1071,7 @@ static grpc_compression_algorithm decode_compression(grpc_mdelem md) { grpc_compression_algorithm algorithm = grpc_compression_algorithm_from_slice(GRPC_MDVALUE(md)); if (algorithm == GRPC_COMPRESS_ALGORITHMS_COUNT) { - char *md_c_str = grpc_slice_to_c_string(GRPC_MDVALUE(md)); + char* md_c_str = grpc_slice_to_c_string(GRPC_MDVALUE(md)); gpr_log(GPR_ERROR, "Invalid incoming compression algorithm: '%s'. Interpreting " "incoming data as uncompressed.", @@ -1085,7 +1087,7 @@ static grpc_stream_compression_algorithm decode_stream_compression( grpc_stream_compression_algorithm algorithm = grpc_stream_compression_algorithm_from_slice(GRPC_MDVALUE(md)); if (algorithm == GRPC_STREAM_COMPRESS_ALGORITHMS_COUNT) { - char *md_c_str = grpc_slice_to_c_string(GRPC_MDVALUE(md)); + char* md_c_str = grpc_slice_to_c_string(GRPC_MDVALUE(md)); gpr_log(GPR_ERROR, "Invalid incoming stream compression algorithm: '%s'. Interpreting " "incoming data as uncompressed.", @@ -1096,20 +1098,20 @@ static grpc_stream_compression_algorithm decode_stream_compression( return algorithm; } -static void publish_app_metadata(grpc_call *call, grpc_metadata_batch *b, +static void publish_app_metadata(grpc_call* call, grpc_metadata_batch* b, int is_trailing) { if (b->list.count == 0) return; GPR_TIMER_BEGIN("publish_app_metadata", 0); - grpc_metadata_array *dest; - grpc_metadata *mdusr; + grpc_metadata_array* dest; + grpc_metadata* mdusr; dest = call->buffered_metadata[is_trailing]; if (dest->count + b->list.count > dest->capacity) { dest->capacity = GPR_MAX(dest->capacity + b->list.count, dest->capacity * 3 / 2); - dest->metadata = (grpc_metadata *)gpr_realloc( + dest->metadata = (grpc_metadata*)gpr_realloc( dest->metadata, sizeof(grpc_metadata) * dest->capacity); } - for (grpc_linked_mdelem *l = b->list.head; l != NULL; l = l->next) { + for (grpc_linked_mdelem* l = b->list.head; l != nullptr; l = l->next) { mdusr = &dest->metadata[dest->count++]; /* we pass back borrowed slices that are valid whilst the call is valid */ mdusr->key = GRPC_MDKEY(l->md); @@ -1118,10 +1120,10 @@ static void publish_app_metadata(grpc_call *call, grpc_metadata_batch *b, GPR_TIMER_END("publish_app_metadata", 0); } -static void recv_initial_filter(grpc_exec_ctx *exec_ctx, grpc_call *call, - grpc_metadata_batch *b) { - if (b->idx.named.content_encoding != NULL) { - if (b->idx.named.grpc_encoding != NULL) { +static void recv_initial_filter(grpc_exec_ctx* exec_ctx, grpc_call* call, + grpc_metadata_batch* b) { + if (b->idx.named.content_encoding != nullptr) { + if (b->idx.named.grpc_encoding != nullptr) { gpr_log(GPR_ERROR, "Received both content-encoding and grpc-encoding header. " "Ignoring grpc-encoding."); @@ -1132,21 +1134,21 @@ static void recv_initial_filter(grpc_exec_ctx *exec_ctx, grpc_call *call, call, decode_stream_compression(b->idx.named.content_encoding->md)); GPR_TIMER_END("incoming_stream_compression_algorithm", 0); grpc_metadata_batch_remove(exec_ctx, b, b->idx.named.content_encoding); - } else if (b->idx.named.grpc_encoding != NULL) { + } else if (b->idx.named.grpc_encoding != nullptr) { GPR_TIMER_BEGIN("incoming_compression_algorithm", 0); set_incoming_compression_algorithm( call, decode_compression(b->idx.named.grpc_encoding->md)); GPR_TIMER_END("incoming_compression_algorithm", 0); grpc_metadata_batch_remove(exec_ctx, b, b->idx.named.grpc_encoding); } - if (b->idx.named.grpc_accept_encoding != NULL) { + if (b->idx.named.grpc_accept_encoding != nullptr) { GPR_TIMER_BEGIN("encodings_accepted_by_peer", 0); set_encodings_accepted_by_peer(exec_ctx, call, b->idx.named.grpc_accept_encoding->md); grpc_metadata_batch_remove(exec_ctx, b, b->idx.named.grpc_accept_encoding); GPR_TIMER_END("encodings_accepted_by_peer", 0); } - if (b->idx.named.accept_encoding != NULL) { + if (b->idx.named.accept_encoding != nullptr) { GPR_TIMER_BEGIN("stream_encodings_accepted_by_peer", 0); set_stream_encodings_accepted_by_peer(exec_ctx, call, b->idx.named.accept_encoding->md); @@ -1156,19 +1158,19 @@ static void recv_initial_filter(grpc_exec_ctx *exec_ctx, grpc_call *call, publish_app_metadata(call, b, false); } -static void recv_trailing_filter(grpc_exec_ctx *exec_ctx, void *args, - grpc_metadata_batch *b) { - grpc_call *call = (grpc_call *)args; - if (b->idx.named.grpc_status != NULL) { +static void recv_trailing_filter(grpc_exec_ctx* exec_ctx, void* args, + grpc_metadata_batch* b) { + grpc_call* call = (grpc_call*)args; + if (b->idx.named.grpc_status != nullptr) { uint32_t status_code = decode_status(b->idx.named.grpc_status->md); - grpc_error *error = + grpc_error* error = status_code == GRPC_STATUS_OK ? GRPC_ERROR_NONE : grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Error received from peer"), GRPC_ERROR_INT_GRPC_STATUS, (intptr_t)status_code); - if (b->idx.named.grpc_message != NULL) { + if (b->idx.named.grpc_message != nullptr) { error = grpc_error_set_str( error, GRPC_ERROR_STR_GRPC_MESSAGE, grpc_slice_ref_internal(GRPC_MDVALUE(b->idx.named.grpc_message->md))); @@ -1183,7 +1185,7 @@ static void recv_trailing_filter(grpc_exec_ctx *exec_ctx, void *args, publish_app_metadata(call, b, true); } -grpc_call_stack *grpc_call_get_call_stack(grpc_call *call) { +grpc_call_stack* grpc_call_get_call_stack(grpc_call* call) { return CALL_STACK_FROM_CALL(call); } @@ -1191,12 +1193,12 @@ grpc_call_stack *grpc_call_get_call_stack(grpc_call *call) { * BATCH API IMPLEMENTATION */ -static void set_status_value_directly(grpc_status_code status, void *dest) { - *(grpc_status_code *)dest = status; +static void set_status_value_directly(grpc_status_code status, void* dest) { + *(grpc_status_code*)dest = status; } -static void set_cancelled_value(grpc_status_code status, void *dest) { - *(int *)dest = (status != GRPC_STATUS_OK); +static void set_cancelled_value(grpc_status_code status, void* dest) { + *(int*)dest = (status != GRPC_STATUS_OK); } static bool are_write_flags_valid(uint32_t flags) { @@ -1236,18 +1238,18 @@ static int batch_slot_for_op(grpc_op_type type) { GPR_UNREACHABLE_CODE(return 123456789); } -static batch_control *allocate_batch_control(grpc_call *call, - const grpc_op *ops, +static batch_control* allocate_batch_control(grpc_call* call, + const grpc_op* ops, size_t num_ops) { int slot = batch_slot_for_op(ops[0].op); - batch_control **pslot = &call->active_batches[slot]; - if (*pslot == NULL) { + batch_control** pslot = &call->active_batches[slot]; + if (*pslot == nullptr) { *pslot = - (batch_control *)gpr_arena_alloc(call->arena, sizeof(batch_control)); + (batch_control*)gpr_arena_alloc(call->arena, sizeof(batch_control)); } - batch_control *bctl = *pslot; - if (bctl->call != NULL) { - return NULL; + batch_control* bctl = *pslot; + if (bctl->call != nullptr) { + return nullptr; } memset(bctl, 0, sizeof(*bctl)); bctl->call = call; @@ -1255,40 +1257,40 @@ static batch_control *allocate_batch_control(grpc_call *call, return bctl; } -static void finish_batch_completion(grpc_exec_ctx *exec_ctx, void *user_data, - grpc_cq_completion *storage) { - batch_control *bctl = (batch_control *)user_data; - grpc_call *call = bctl->call; - bctl->call = NULL; +static void finish_batch_completion(grpc_exec_ctx* exec_ctx, void* user_data, + grpc_cq_completion* storage) { + batch_control* bctl = (batch_control*)user_data; + grpc_call* call = bctl->call; + bctl->call = nullptr; GRPC_CALL_INTERNAL_UNREF(exec_ctx, call, "completion"); } -static grpc_error *consolidate_batch_errors(batch_control *bctl) { +static grpc_error* consolidate_batch_errors(batch_control* bctl) { size_t n = (size_t)gpr_atm_acq_load(&bctl->num_errors); if (n == 0) { return GRPC_ERROR_NONE; } else if (n == 1) { /* Skip creating a composite error in the case that only one error was logged */ - grpc_error *e = bctl->errors[0]; - bctl->errors[0] = NULL; + grpc_error* e = bctl->errors[0]; + bctl->errors[0] = nullptr; return e; } else { - grpc_error *error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( + grpc_error* error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Call batch failed", bctl->errors, n); for (size_t i = 0; i < n; i++) { GRPC_ERROR_UNREF(bctl->errors[i]); - bctl->errors[i] = NULL; + bctl->errors[i] = nullptr; } return error; } } -static void post_batch_completion(grpc_exec_ctx *exec_ctx, - batch_control *bctl) { - grpc_call *next_child_call; - grpc_call *call = bctl->call; - grpc_error *error = consolidate_batch_errors(bctl); +static void post_batch_completion(grpc_exec_ctx* exec_ctx, + batch_control* bctl) { + grpc_call* next_child_call; + grpc_call* call = bctl->call; + grpc_error* error = consolidate_batch_errors(bctl); if (bctl->op.send_initial_metadata) { grpc_metadata_batch_destroy( @@ -1304,18 +1306,18 @@ static void post_batch_completion(grpc_exec_ctx *exec_ctx, &call->metadata_batch[0 /* is_receiving */][1 /* is_trailing */]); } if (bctl->op.recv_trailing_metadata) { - grpc_metadata_batch *md = + grpc_metadata_batch* md = &call->metadata_batch[1 /* is_receiving */][1 /* is_trailing */]; recv_trailing_filter(exec_ctx, call, md); /* propagate cancellation to any interested children */ gpr_atm_rel_store(&call->received_final_op_atm, 1); - parent_call *pc = get_parent_call(call); - if (pc != NULL) { - grpc_call *child; + parent_call* pc = get_parent_call(call); + if (pc != nullptr) { + grpc_call* child; gpr_mu_lock(&pc->child_list_mu); child = pc->first_child; - if (child != NULL) { + if (child != nullptr) { do { next_child_call = child->child->sibling_next; if (child->cancellation_is_inherited) { @@ -1333,26 +1335,27 @@ static void post_batch_completion(grpc_exec_ctx *exec_ctx, if (call->is_client) { get_final_status(exec_ctx, call, set_status_value_directly, call->final_op.client.status, - call->final_op.client.status_details); + call->final_op.client.status_details, + call->final_op.client.error_string); } else { get_final_status(exec_ctx, call, set_cancelled_value, - call->final_op.server.cancelled, NULL); + call->final_op.server.cancelled, nullptr, nullptr); } GRPC_ERROR_UNREF(error); error = GRPC_ERROR_NONE; } if (error != GRPC_ERROR_NONE && bctl->op.recv_message && - *call->receiving_buffer != NULL) { + *call->receiving_buffer != nullptr) { grpc_byte_buffer_destroy(*call->receiving_buffer); - *call->receiving_buffer = NULL; + *call->receiving_buffer = nullptr; } if (bctl->completion_data.notify_tag.is_closure) { /* unrefs bctl->error */ - bctl->call = NULL; + bctl->call = nullptr; GRPC_CLOSURE_RUN( - exec_ctx, (grpc_closure *)bctl->completion_data.notify_tag.tag, error); + exec_ctx, (grpc_closure*)bctl->completion_data.notify_tag.tag, error); GRPC_CALL_INTERNAL_UNREF(exec_ctx, call, "completion"); } else { /* unrefs bctl->error */ @@ -1362,23 +1365,23 @@ static void post_batch_completion(grpc_exec_ctx *exec_ctx, } } -static void finish_batch_step(grpc_exec_ctx *exec_ctx, batch_control *bctl) { +static void finish_batch_step(grpc_exec_ctx* exec_ctx, batch_control* bctl) { if (gpr_unref(&bctl->steps_to_complete)) { post_batch_completion(exec_ctx, bctl); } } -static void continue_receiving_slices(grpc_exec_ctx *exec_ctx, - batch_control *bctl) { - grpc_error *error; - grpc_call *call = bctl->call; +static void continue_receiving_slices(grpc_exec_ctx* exec_ctx, + batch_control* bctl) { + grpc_error* error; + grpc_call* call = bctl->call; for (;;) { size_t remaining = call->receiving_stream->length - (*call->receiving_buffer)->data.raw.slice_buffer.length; if (remaining == 0) { call->receiving_message = 0; grpc_byte_stream_destroy(exec_ctx, call->receiving_stream); - call->receiving_stream = NULL; + call->receiving_stream = nullptr; finish_batch_step(exec_ctx, bctl); return; } @@ -1391,9 +1394,9 @@ static void continue_receiving_slices(grpc_exec_ctx *exec_ctx, call->receiving_slice); } else { grpc_byte_stream_destroy(exec_ctx, call->receiving_stream); - call->receiving_stream = NULL; + call->receiving_stream = nullptr; grpc_byte_buffer_destroy(*call->receiving_buffer); - *call->receiving_buffer = NULL; + *call->receiving_buffer = nullptr; call->receiving_message = 0; finish_batch_step(exec_ctx, bctl); return; @@ -1404,11 +1407,11 @@ static void continue_receiving_slices(grpc_exec_ctx *exec_ctx, } } -static void receiving_slice_ready(grpc_exec_ctx *exec_ctx, void *bctlp, - grpc_error *error) { - batch_control *bctl = (batch_control *)bctlp; - grpc_call *call = bctl->call; - grpc_byte_stream *bs = call->receiving_stream; +static void receiving_slice_ready(grpc_exec_ctx* exec_ctx, void* bctlp, + grpc_error* error) { + batch_control* bctl = (batch_control*)bctlp; + grpc_call* call = bctl->call; + grpc_byte_stream* bs = call->receiving_stream; bool release_error = false; if (error == GRPC_ERROR_NONE) { @@ -1426,13 +1429,13 @@ static void receiving_slice_ready(grpc_exec_ctx *exec_ctx, void *bctlp, } if (error != GRPC_ERROR_NONE) { - if (GRPC_TRACER_ON(grpc_trace_operation_failures)) { + if (grpc_trace_operation_failures.enabled()) { GRPC_LOG_IF_ERROR("receiving_slice_ready", GRPC_ERROR_REF(error)); } grpc_byte_stream_destroy(exec_ctx, call->receiving_stream); - call->receiving_stream = NULL; + call->receiving_stream = nullptr; grpc_byte_buffer_destroy(*call->receiving_buffer); - *call->receiving_buffer = NULL; + *call->receiving_buffer = nullptr; call->receiving_message = 0; finish_batch_step(exec_ctx, bctl); if (release_error) { @@ -1441,11 +1444,11 @@ static void receiving_slice_ready(grpc_exec_ctx *exec_ctx, void *bctlp, } } -static void process_data_after_md(grpc_exec_ctx *exec_ctx, - batch_control *bctl) { - grpc_call *call = bctl->call; - if (call->receiving_stream == NULL) { - *call->receiving_buffer = NULL; +static void process_data_after_md(grpc_exec_ctx* exec_ctx, + batch_control* bctl) { + grpc_call* call = bctl->call; + if (call->receiving_stream == nullptr) { + *call->receiving_buffer = nullptr; call->receiving_message = 0; finish_batch_step(exec_ctx, bctl); } else { @@ -1453,9 +1456,9 @@ static void process_data_after_md(grpc_exec_ctx *exec_ctx, if ((call->receiving_stream->flags & GRPC_WRITE_INTERNAL_COMPRESS) && (call->incoming_compression_algorithm > GRPC_COMPRESS_NONE)) { *call->receiving_buffer = grpc_raw_compressed_byte_buffer_create( - NULL, 0, call->incoming_compression_algorithm); + nullptr, 0, call->incoming_compression_algorithm); } else { - *call->receiving_buffer = grpc_raw_byte_buffer_create(NULL, 0); + *call->receiving_buffer = grpc_raw_byte_buffer_create(nullptr, 0); } GRPC_CLOSURE_INIT(&call->receiving_slice_ready, receiving_slice_ready, bctl, grpc_schedule_on_exec_ctx); @@ -1463,14 +1466,14 @@ static void process_data_after_md(grpc_exec_ctx *exec_ctx, } } -static void receiving_stream_ready(grpc_exec_ctx *exec_ctx, void *bctlp, - grpc_error *error) { - batch_control *bctl = (batch_control *)bctlp; - grpc_call *call = bctl->call; +static void receiving_stream_ready(grpc_exec_ctx* exec_ctx, void* bctlp, + grpc_error* error) { + batch_control* bctl = (batch_control*)bctlp; + grpc_call* call = bctl->call; if (error != GRPC_ERROR_NONE) { - if (call->receiving_stream != NULL) { + if (call->receiving_stream != nullptr) { grpc_byte_stream_destroy(exec_ctx, call->receiving_stream); - call->receiving_stream = NULL; + call->receiving_stream = nullptr; } add_batch_error(exec_ctx, bctl, GRPC_ERROR_REF(error), true); cancel_with_error(exec_ctx, call, STATUS_FROM_SURFACE, @@ -1479,7 +1482,7 @@ static void receiving_stream_ready(grpc_exec_ctx *exec_ctx, void *bctlp, /* If recv_state is RECV_NONE, we will save the batch_control * object with rel_cas, and will not use it after the cas. Its corresponding * acq_load is in receiving_initial_metadata_ready() */ - if (error != GRPC_ERROR_NONE || call->receiving_stream == NULL || + if (error != GRPC_ERROR_NONE || call->receiving_stream == nullptr || !gpr_atm_rel_cas(&call->recv_state, RECV_NONE, (gpr_atm)bctlp)) { process_data_after_md(exec_ctx, bctl); } @@ -1488,24 +1491,24 @@ static void receiving_stream_ready(grpc_exec_ctx *exec_ctx, void *bctlp, // The recv_message_ready callback used when sending a batch containing // a recv_message op down the filter stack. Yields the call combiner // before processing the received message. -static void receiving_stream_ready_in_call_combiner(grpc_exec_ctx *exec_ctx, - void *bctlp, - grpc_error *error) { - batch_control *bctl = (batch_control *)bctlp; - grpc_call *call = bctl->call; +static void receiving_stream_ready_in_call_combiner(grpc_exec_ctx* exec_ctx, + void* bctlp, + grpc_error* error) { + batch_control* bctl = (batch_control*)bctlp; + grpc_call* call = bctl->call; GRPC_CALL_COMBINER_STOP(exec_ctx, &call->call_combiner, "recv_message_ready"); receiving_stream_ready(exec_ctx, bctlp, error); } -static void validate_filtered_metadata(grpc_exec_ctx *exec_ctx, - batch_control *bctl) { - grpc_call *call = bctl->call; +static void validate_filtered_metadata(grpc_exec_ctx* exec_ctx, + batch_control* bctl) { + grpc_call* call = bctl->call; /* validate compression algorithms */ if (call->incoming_stream_compression_algorithm != GRPC_STREAM_COMPRESS_NONE) { const grpc_stream_compression_algorithm algo = call->incoming_stream_compression_algorithm; - char *error_msg = NULL; + char* error_msg = nullptr; const grpc_compression_options compression_options = grpc_channel_compression_options(call->channel); if (algo >= GRPC_STREAM_COMPRESS_ALGORITHMS_COUNT) { @@ -1517,7 +1520,7 @@ static void validate_filtered_metadata(grpc_exec_ctx *exec_ctx, } else if (grpc_compression_options_is_stream_compression_algorithm_enabled( &compression_options, algo) == 0) { /* check if algorithm is supported by current channel config */ - const char *algo_name = NULL; + const char* algo_name = nullptr; grpc_stream_compression_algorithm_name(algo, &algo_name); gpr_asprintf(&error_msg, "Stream compression algorithm '%s' is disabled.", algo_name); @@ -1530,8 +1533,8 @@ static void validate_filtered_metadata(grpc_exec_ctx *exec_ctx, GPR_ASSERT(call->stream_encodings_accepted_by_peer != 0); if (!GPR_BITGET(call->stream_encodings_accepted_by_peer, call->incoming_stream_compression_algorithm)) { - if (GRPC_TRACER_ON(grpc_compression_trace)) { - const char *algo_name = NULL; + if (grpc_compression_trace.enabled()) { + const char* algo_name = nullptr; grpc_stream_compression_algorithm_name( call->incoming_stream_compression_algorithm, &algo_name); gpr_log( @@ -1545,7 +1548,7 @@ static void validate_filtered_metadata(grpc_exec_ctx *exec_ctx, } else if (call->incoming_compression_algorithm != GRPC_COMPRESS_NONE) { const grpc_compression_algorithm algo = call->incoming_compression_algorithm; - char *error_msg = NULL; + char* error_msg = nullptr; const grpc_compression_options compression_options = grpc_channel_compression_options(call->channel); /* check if algorithm is known */ @@ -1558,7 +1561,7 @@ static void validate_filtered_metadata(grpc_exec_ctx *exec_ctx, } else if (grpc_compression_options_is_algorithm_enabled( &compression_options, algo) == 0) { /* check if algorithm is supported by current channel config */ - const char *algo_name = NULL; + const char* algo_name = nullptr; grpc_compression_algorithm_name(algo, &algo_name); gpr_asprintf(&error_msg, "Compression algorithm '%s' is disabled.", algo_name); @@ -1573,8 +1576,8 @@ static void validate_filtered_metadata(grpc_exec_ctx *exec_ctx, GPR_ASSERT(call->encodings_accepted_by_peer != 0); if (!GPR_BITGET(call->encodings_accepted_by_peer, call->incoming_compression_algorithm)) { - if (GRPC_TRACER_ON(grpc_compression_trace)) { - const char *algo_name = NULL; + if (grpc_compression_trace.enabled()) { + const char* algo_name = nullptr; grpc_compression_algorithm_name(call->incoming_compression_algorithm, &algo_name); gpr_log(GPR_ERROR, @@ -1587,8 +1590,8 @@ static void validate_filtered_metadata(grpc_exec_ctx *exec_ctx, } } -static void add_batch_error(grpc_exec_ctx *exec_ctx, batch_control *bctl, - grpc_error *error, bool has_cancelled) { +static void add_batch_error(grpc_exec_ctx* exec_ctx, batch_control* bctl, + grpc_error* error, bool has_cancelled) { if (error == GRPC_ERROR_NONE) return; int idx = (int)gpr_atm_full_fetch_add(&bctl->num_errors, 1); if (idx == 0 && !has_cancelled) { @@ -1598,17 +1601,17 @@ static void add_batch_error(grpc_exec_ctx *exec_ctx, batch_control *bctl, bctl->errors[idx] = error; } -static void receiving_initial_metadata_ready(grpc_exec_ctx *exec_ctx, - void *bctlp, grpc_error *error) { - batch_control *bctl = (batch_control *)bctlp; - grpc_call *call = bctl->call; +static void receiving_initial_metadata_ready(grpc_exec_ctx* exec_ctx, + void* bctlp, grpc_error* error) { + batch_control* bctl = (batch_control*)bctlp; + grpc_call* call = bctl->call; GRPC_CALL_COMBINER_STOP(exec_ctx, &call->call_combiner, "recv_initial_metadata_ready"); add_batch_error(exec_ctx, bctl, GRPC_ERROR_REF(error), false); if (error == GRPC_ERROR_NONE) { - grpc_metadata_batch *md = + grpc_metadata_batch* md = &call->metadata_batch[1 /* is_receiving */][0 /* is_trailing */]; recv_initial_filter(exec_ctx, call, md); @@ -1622,7 +1625,7 @@ static void receiving_initial_metadata_ready(grpc_exec_ctx *exec_ctx, } } - grpc_closure *saved_rsr_closure = NULL; + grpc_closure* saved_rsr_closure = nullptr; while (true) { gpr_atm rsr_bctlp = gpr_atm_acq_load(&call->recv_state); /* Should only receive initial metadata once */ @@ -1639,45 +1642,45 @@ static void receiving_initial_metadata_ready(grpc_exec_ctx *exec_ctx, } } else { /* Already received messages */ - saved_rsr_closure = GRPC_CLOSURE_CREATE(receiving_stream_ready, - (batch_control *)rsr_bctlp, - grpc_schedule_on_exec_ctx); + saved_rsr_closure = + GRPC_CLOSURE_CREATE(receiving_stream_ready, (batch_control*)rsr_bctlp, + grpc_schedule_on_exec_ctx); /* No need to modify recv_state */ break; } } - if (saved_rsr_closure != NULL) { + if (saved_rsr_closure != nullptr) { GRPC_CLOSURE_RUN(exec_ctx, saved_rsr_closure, GRPC_ERROR_REF(error)); } finish_batch_step(exec_ctx, bctl); } -static void finish_batch(grpc_exec_ctx *exec_ctx, void *bctlp, - grpc_error *error) { - batch_control *bctl = (batch_control *)bctlp; - grpc_call *call = bctl->call; +static void finish_batch(grpc_exec_ctx* exec_ctx, void* bctlp, + grpc_error* error) { + batch_control* bctl = (batch_control*)bctlp; + grpc_call* call = bctl->call; GRPC_CALL_COMBINER_STOP(exec_ctx, &call->call_combiner, "on_complete"); add_batch_error(exec_ctx, bctl, GRPC_ERROR_REF(error), false); finish_batch_step(exec_ctx, bctl); } -static void free_no_op_completion(grpc_exec_ctx *exec_ctx, void *p, - grpc_cq_completion *completion) { +static void free_no_op_completion(grpc_exec_ctx* exec_ctx, void* p, + grpc_cq_completion* completion) { gpr_free(completion); } -static grpc_call_error call_start_batch(grpc_exec_ctx *exec_ctx, - grpc_call *call, const grpc_op *ops, - size_t nops, void *notify_tag, +static grpc_call_error call_start_batch(grpc_exec_ctx* exec_ctx, + grpc_call* call, const grpc_op* ops, + size_t nops, void* notify_tag, int is_notify_tag_closure) { size_t i; - const grpc_op *op; - batch_control *bctl; + const grpc_op* op; + batch_control* bctl; int num_completion_callbacks_needed = 1; grpc_call_error error = GRPC_CALL_OK; - grpc_transport_stream_op_batch *stream_op; - grpc_transport_stream_op_batch_payload *stream_op_payload; + grpc_transport_stream_op_batch* stream_op; + grpc_transport_stream_op_batch_payload* stream_op_payload; GPR_TIMER_BEGIN("grpc_call_start_batch", 0); GRPC_CALL_LOG_BATCH(GPR_INFO, call, ops, nops, notify_tag); @@ -1687,17 +1690,17 @@ static grpc_call_error call_start_batch(grpc_exec_ctx *exec_ctx, GPR_ASSERT(grpc_cq_begin_op(call->cq, notify_tag)); grpc_cq_end_op( exec_ctx, call->cq, notify_tag, GRPC_ERROR_NONE, - free_no_op_completion, NULL, - (grpc_cq_completion *)gpr_malloc(sizeof(grpc_cq_completion))); + free_no_op_completion, nullptr, + (grpc_cq_completion*)gpr_malloc(sizeof(grpc_cq_completion))); } else { - GRPC_CLOSURE_SCHED(exec_ctx, (grpc_closure *)notify_tag, GRPC_ERROR_NONE); + GRPC_CLOSURE_SCHED(exec_ctx, (grpc_closure*)notify_tag, GRPC_ERROR_NONE); } error = GRPC_CALL_OK; goto done; } bctl = allocate_batch_control(call, ops, nops); - if (bctl == NULL) { + if (bctl == nullptr) { return GRPC_CALL_ERROR_TOO_MANY_OPERATIONS; } bctl->completion_data.notify_tag.tag = notify_tag; @@ -1710,7 +1713,7 @@ static grpc_call_error call_start_batch(grpc_exec_ctx *exec_ctx, /* rewrite batch ops into a transport op */ for (i = 0; i < nops; i++) { op = &ops[i]; - if (op->reserved != NULL) { + if (op->reserved != nullptr) { error = GRPC_CALL_ERROR; goto done_with_error; } @@ -1815,7 +1818,7 @@ static grpc_call_error call_start_batch(grpc_exec_ctx *exec_ctx, error = GRPC_CALL_ERROR_INVALID_FLAGS; goto done_with_error; } - if (op->data.send_message.send_message == NULL) { + if (op->data.send_message.send_message == nullptr) { error = GRPC_CALL_ERROR_INVALID_MESSAGE; goto done_with_error; } @@ -1886,18 +1889,18 @@ static grpc_call_error call_start_batch(grpc_exec_ctx *exec_ctx, call->send_extra_metadata[0].md = grpc_channel_get_reffed_status_elem( exec_ctx, call->channel, op->data.send_status_from_server.status); { - grpc_error *override_error = GRPC_ERROR_NONE; + grpc_error* override_error = GRPC_ERROR_NONE; if (op->data.send_status_from_server.status != GRPC_STATUS_OK) { override_error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Error from server send status"); } - if (op->data.send_status_from_server.status_details != NULL) { + if (op->data.send_status_from_server.status_details != nullptr) { call->send_extra_metadata[1].md = grpc_mdelem_from_slices( exec_ctx, GRPC_MDSTR_GRPC_MESSAGE, grpc_slice_ref_internal( *op->data.send_status_from_server.status_details)); call->send_extra_metadata_count++; - char *msg = grpc_slice_to_c_string( + char* msg = grpc_slice_to_c_string( GRPC_MDVALUE(call->send_extra_metadata[1].md)); override_error = grpc_error_set_str(override_error, GRPC_ERROR_STR_GRPC_MESSAGE, @@ -1910,8 +1913,8 @@ static grpc_call_error call_start_batch(grpc_exec_ctx *exec_ctx, if (!prepare_application_metadata( exec_ctx, call, (int)op->data.send_status_from_server.trailing_metadata_count, - op->data.send_status_from_server.trailing_metadata, 1, 1, NULL, - 0)) { + op->data.send_status_from_server.trailing_metadata, 1, 1, + nullptr, 0)) { for (int n = 0; n < call->send_extra_metadata_count; n++) { GRPC_MDELEM_UNREF(exec_ctx, call->send_extra_metadata[n].md); } @@ -1993,6 +1996,8 @@ static grpc_call_error call_start_batch(grpc_exec_ctx *exec_ctx, call->final_op.client.status = op->data.recv_status_on_client.status; call->final_op.client.status_details = op->data.recv_status_on_client.status_details; + call->final_op.client.error_string = + op->data.recv_status_on_client.error_string; stream_op->recv_trailing_metadata = true; stream_op->collect_stats = true; stream_op_payload->recv_trailing_metadata.recv_trailing_metadata = @@ -2072,8 +2077,8 @@ done_with_error: goto done; } -grpc_call_error grpc_call_start_batch(grpc_call *call, const grpc_op *ops, - size_t nops, void *tag, void *reserved) { +grpc_call_error grpc_call_start_batch(grpc_call* call, const grpc_op* ops, + size_t nops, void* tag, void* reserved) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_call_error err; @@ -2082,7 +2087,7 @@ grpc_call_error grpc_call_start_batch(grpc_call *call, const grpc_op *ops, "reserved=%p)", 5, (call, ops, (unsigned long)nops, tag, reserved)); - if (reserved != NULL) { + if (reserved != nullptr) { err = GRPC_CALL_ERROR; } else { err = call_start_batch(&exec_ctx, call, ops, nops, tag, 0); @@ -2092,16 +2097,16 @@ grpc_call_error grpc_call_start_batch(grpc_call *call, const grpc_op *ops, return err; } -grpc_call_error grpc_call_start_batch_and_execute(grpc_exec_ctx *exec_ctx, - grpc_call *call, - const grpc_op *ops, +grpc_call_error grpc_call_start_batch_and_execute(grpc_exec_ctx* exec_ctx, + grpc_call* call, + const grpc_op* ops, size_t nops, - grpc_closure *closure) { + grpc_closure* closure) { return call_start_batch(exec_ctx, call, ops, nops, closure, 1); } -void grpc_call_context_set(grpc_call *call, grpc_context_index elem, - void *value, void (*destroy)(void *value)) { +void grpc_call_context_set(grpc_call* call, grpc_context_index elem, + void* value, void (*destroy)(void* value)) { if (call->context[elem].destroy) { call->context[elem].destroy(call->context[elem].value); } @@ -2109,20 +2114,20 @@ void grpc_call_context_set(grpc_call *call, grpc_context_index elem, call->context[elem].destroy = destroy; } -void *grpc_call_context_get(grpc_call *call, grpc_context_index elem) { +void* grpc_call_context_get(grpc_call* call, grpc_context_index elem) { return call->context[elem].value; } -uint8_t grpc_call_is_client(grpc_call *call) { return call->is_client; } +uint8_t grpc_call_is_client(grpc_call* call) { return call->is_client; } grpc_compression_algorithm grpc_call_compression_for_level( - grpc_call *call, grpc_compression_level level) { + grpc_call* call, grpc_compression_level level) { grpc_compression_algorithm algo = compression_algorithm_for_level_locked(call, level); return algo; } -const char *grpc_call_error_to_string(grpc_call_error error) { +const char* grpc_call_error_to_string(grpc_call_error error) { switch (error) { case GRPC_CALL_ERROR: return "GRPC_CALL_ERROR"; diff --git a/src/core/lib/surface/call.h b/src/core/lib/surface/call.h index 27c2f5243ca..1d2e266717f 100644 --- a/src/core/lib/surface/call.h +++ b/src/core/lib/surface/call.h @@ -19,10 +19,6 @@ #ifndef GRPC_CORE_LIB_SURFACE_CALL_H #define GRPC_CORE_LIB_SURFACE_CALL_H -#ifdef __cplusplus -extern "C" { -#endif - #include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/channel/context.h" #include "src/core/lib/surface/api_trace.h" @@ -30,23 +26,23 @@ extern "C" { #include #include -typedef void (*grpc_ioreq_completion_func)(grpc_exec_ctx *exec_ctx, - grpc_call *call, int success, - void *user_data); +typedef void (*grpc_ioreq_completion_func)(grpc_exec_ctx* exec_ctx, + grpc_call* call, int success, + void* user_data); typedef struct grpc_call_create_args { - grpc_channel *channel; + grpc_channel* channel; - grpc_call *parent; + grpc_call* parent; uint32_t propagation_mask; - grpc_completion_queue *cq; + grpc_completion_queue* cq; /* if not NULL, it'll be used in lieu of cq */ - grpc_pollset_set *pollset_set_alternative; + grpc_pollset_set* pollset_set_alternative; - const void *server_transport_data; + const void* server_transport_data; - grpc_mdelem *add_initial_metadata; + grpc_mdelem* add_initial_metadata; size_t add_initial_metadata_count; grpc_millis send_deadline; @@ -55,68 +51,63 @@ typedef struct grpc_call_create_args { /* Create a new call based on \a args. Regardless of success or failure, always returns a valid new call into *call */ -grpc_error *grpc_call_create(grpc_exec_ctx *exec_ctx, - const grpc_call_create_args *args, - grpc_call **call); +grpc_error* grpc_call_create(grpc_exec_ctx* exec_ctx, + const grpc_call_create_args* args, + grpc_call** call); -void grpc_call_set_completion_queue(grpc_exec_ctx *exec_ctx, grpc_call *call, - grpc_completion_queue *cq); +void grpc_call_set_completion_queue(grpc_exec_ctx* exec_ctx, grpc_call* call, + grpc_completion_queue* cq); #ifndef NDEBUG -void grpc_call_internal_ref(grpc_call *call, const char *reason); -void grpc_call_internal_unref(grpc_exec_ctx *exec_ctx, grpc_call *call, - const char *reason); +void grpc_call_internal_ref(grpc_call* call, const char* reason); +void grpc_call_internal_unref(grpc_exec_ctx* exec_ctx, grpc_call* call, + const char* reason); #define GRPC_CALL_INTERNAL_REF(call, reason) \ grpc_call_internal_ref(call, reason) #define GRPC_CALL_INTERNAL_UNREF(exec_ctx, call, reason) \ grpc_call_internal_unref(exec_ctx, call, reason) #else -void grpc_call_internal_ref(grpc_call *call); -void grpc_call_internal_unref(grpc_exec_ctx *exec_ctx, grpc_call *call); +void grpc_call_internal_ref(grpc_call* call); +void grpc_call_internal_unref(grpc_exec_ctx* exec_ctx, grpc_call* call); #define GRPC_CALL_INTERNAL_REF(call, reason) grpc_call_internal_ref(call) #define GRPC_CALL_INTERNAL_UNREF(exec_ctx, call, reason) \ grpc_call_internal_unref(exec_ctx, call) #endif -grpc_call_stack *grpc_call_get_call_stack(grpc_call *call); +grpc_call_stack* grpc_call_get_call_stack(grpc_call* call); -grpc_call_error grpc_call_start_batch_and_execute(grpc_exec_ctx *exec_ctx, - grpc_call *call, - const grpc_op *ops, +grpc_call_error grpc_call_start_batch_and_execute(grpc_exec_ctx* exec_ctx, + grpc_call* call, + const grpc_op* ops, size_t nops, - grpc_closure *closure); + grpc_closure* closure); /* Given the top call_element, get the call object. */ -grpc_call *grpc_call_from_top_element(grpc_call_element *surface_element); +grpc_call* grpc_call_from_top_element(grpc_call_element* surface_element); -void grpc_call_log_batch(const char *file, int line, gpr_log_severity severity, - grpc_call *call, const grpc_op *ops, size_t nops, - void *tag); +void grpc_call_log_batch(const char* file, int line, gpr_log_severity severity, + grpc_call* call, const grpc_op* ops, size_t nops, + void* tag); /* Set a context pointer. No thread safety guarantees are made wrt this value. */ /* TODO(#9731): add exec_ctx to destroy */ -void grpc_call_context_set(grpc_call *call, grpc_context_index elem, - void *value, void (*destroy)(void *value)); +void grpc_call_context_set(grpc_call* call, grpc_context_index elem, + void* value, void (*destroy)(void* value)); /* Get a context pointer. */ -void *grpc_call_context_get(grpc_call *call, grpc_context_index elem); +void* grpc_call_context_get(grpc_call* call, grpc_context_index elem); #define GRPC_CALL_LOG_BATCH(sev, call, ops, nops, tag) \ - if (GRPC_TRACER_ON(grpc_api_trace)) \ - grpc_call_log_batch(sev, call, ops, nops, tag) + if (grpc_api_trace.enabled()) grpc_call_log_batch(sev, call, ops, nops, tag) -uint8_t grpc_call_is_client(grpc_call *call); +uint8_t grpc_call_is_client(grpc_call* call); /* Return an appropriate compression algorithm for the requested compression \a * level in the context of \a call. */ grpc_compression_algorithm grpc_call_compression_for_level( - grpc_call *call, grpc_compression_level level); + grpc_call* call, grpc_compression_level level); -extern grpc_tracer_flag grpc_call_error_trace; -extern grpc_tracer_flag grpc_compression_trace; - -#ifdef __cplusplus -} -#endif +extern grpc_core::TraceFlag grpc_call_error_trace; +extern grpc_core::TraceFlag grpc_compression_trace; #endif /* GRPC_CORE_LIB_SURFACE_CALL_H */ diff --git a/src/core/lib/surface/call_log_batch.cc b/src/core/lib/surface/call_log_batch.cc index 5557927b7c0..535a3d32821 100644 --- a/src/core/lib/surface/call_log_batch.cc +++ b/src/core/lib/surface/call_log_batch.cc @@ -25,9 +25,9 @@ #include "src/core/lib/slice/slice_string_helpers.h" #include "src/core/lib/support/string.h" -static void add_metadata(gpr_strvec *b, const grpc_metadata *md, size_t count) { +static void add_metadata(gpr_strvec* b, const grpc_metadata* md, size_t count) { size_t i; - if (md == NULL) { + if (md == nullptr) { gpr_strvec_add(b, gpr_strdup("(nil)")); return; } @@ -41,9 +41,9 @@ static void add_metadata(gpr_strvec *b, const grpc_metadata *md, size_t count) { } } -char *grpc_op_string(const grpc_op *op) { - char *tmp; - char *out; +char* grpc_op_string(const grpc_op* op) { + char* tmp; + char* out; gpr_strvec b; gpr_strvec_init(&b); @@ -66,7 +66,7 @@ char *grpc_op_string(const grpc_op *op) { gpr_asprintf(&tmp, "SEND_STATUS_FROM_SERVER status=%d details=", op->data.send_status_from_server.status); gpr_strvec_add(&b, tmp); - if (op->data.send_status_from_server.status_details != NULL) { + if (op->data.send_status_from_server.status_details != nullptr) { gpr_strvec_add(&b, grpc_dump_slice( *op->data.send_status_from_server.status_details, GPR_DUMP_ASCII)); @@ -99,16 +99,16 @@ char *grpc_op_string(const grpc_op *op) { op->data.recv_close_on_server.cancelled); gpr_strvec_add(&b, tmp); } - out = gpr_strvec_flatten(&b, NULL); + out = gpr_strvec_flatten(&b, nullptr); gpr_strvec_destroy(&b); return out; } -void grpc_call_log_batch(const char *file, int line, gpr_log_severity severity, - grpc_call *call, const grpc_op *ops, size_t nops, - void *tag) { - char *tmp; +void grpc_call_log_batch(const char* file, int line, gpr_log_severity severity, + grpc_call* call, const grpc_op* ops, size_t nops, + void* tag) { + char* tmp; size_t i; for (i = 0; i < nops; i++) { tmp = grpc_op_string(&ops[i]); diff --git a/src/core/lib/surface/call_test_only.h b/src/core/lib/surface/call_test_only.h index a5a01b36791..90444f85b6c 100644 --- a/src/core/lib/surface/call_test_only.h +++ b/src/core/lib/surface/call_test_only.h @@ -21,41 +21,33 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /** Return the compression algorithm from \a call. * * \warning This function should \b only be used in test code. */ grpc_compression_algorithm grpc_call_test_only_get_compression_algorithm( - grpc_call *call); + grpc_call* call); /** Return the message flags from \a call. * * \warning This function should \b only be used in test code. */ -uint32_t grpc_call_test_only_get_message_flags(grpc_call *call); +uint32_t grpc_call_test_only_get_message_flags(grpc_call* call); /** Returns a bitset for the encodings (compression algorithms) supported by \a * call's peer. * * To be indexed by grpc_compression_algorithm enum values. */ -uint32_t grpc_call_test_only_get_encodings_accepted_by_peer(grpc_call *call); +uint32_t grpc_call_test_only_get_encodings_accepted_by_peer(grpc_call* call); /** Returns a bitset for the stream encodings (stream compression algorithms) * supported by \a call's peer. * * To be indexed by grpc_stream_compression_algorithm enum values. */ uint32_t grpc_call_test_only_get_stream_encodings_accepted_by_peer( - grpc_call *call); + grpc_call* call); /** Returns the incoming stream compression algorithm (content-encoding header) * received by a call. */ grpc_stream_compression_algorithm -grpc_call_test_only_get_incoming_stream_encodings(grpc_call *call); - -#ifdef __cplusplus -} -#endif +grpc_call_test_only_get_incoming_stream_encodings(grpc_call* call); #endif /* GRPC_CORE_LIB_SURFACE_CALL_TEST_ONLY_H */ diff --git a/src/core/lib/surface/channel.cc b/src/core/lib/surface/channel.cc index 860dcc82db0..1be734cdb78 100644 --- a/src/core/lib/surface/channel.cc +++ b/src/core/lib/surface/channel.cc @@ -47,7 +47,7 @@ typedef struct registered_call { grpc_mdelem path; grpc_mdelem authority; - struct registered_call *next; + struct registered_call* next; } registered_call; struct grpc_channel { @@ -58,35 +58,35 @@ struct grpc_channel { gpr_atm call_size_estimate; gpr_mu registered_call_mu; - registered_call *registered_calls; + registered_call* registered_calls; - char *target; + char* target; }; -#define CHANNEL_STACK_FROM_CHANNEL(c) ((grpc_channel_stack *)((c) + 1)) +#define CHANNEL_STACK_FROM_CHANNEL(c) ((grpc_channel_stack*)((c) + 1)) #define CHANNEL_FROM_CHANNEL_STACK(channel_stack) \ - (((grpc_channel *)(channel_stack)) - 1) + (((grpc_channel*)(channel_stack)) - 1) #define CHANNEL_FROM_TOP_ELEM(top_elem) \ CHANNEL_FROM_CHANNEL_STACK(grpc_channel_stack_from_top_element(top_elem)) -static void destroy_channel(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error); +static void destroy_channel(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error); -grpc_channel *grpc_channel_create_with_builder( - grpc_exec_ctx *exec_ctx, grpc_channel_stack_builder *builder, +grpc_channel* grpc_channel_create_with_builder( + grpc_exec_ctx* exec_ctx, grpc_channel_stack_builder* builder, grpc_channel_stack_type channel_stack_type) { - char *target = gpr_strdup(grpc_channel_stack_builder_get_target(builder)); - grpc_channel_args *args = grpc_channel_args_copy( + char* target = gpr_strdup(grpc_channel_stack_builder_get_target(builder)); + grpc_channel_args* args = grpc_channel_args_copy( grpc_channel_stack_builder_get_channel_arguments(builder)); - grpc_channel *channel; + grpc_channel* channel; if (channel_stack_type == GRPC_SERVER_CHANNEL) { GRPC_STATS_INC_SERVER_CHANNELS_CREATED(exec_ctx); } else { GRPC_STATS_INC_CLIENT_CHANNELS_CREATED(exec_ctx); } - grpc_error *error = grpc_channel_stack_builder_finish( - exec_ctx, builder, sizeof(grpc_channel), 1, destroy_channel, NULL, - (void **)&channel); + grpc_error* error = grpc_channel_stack_builder_finish( + exec_ctx, builder, sizeof(grpc_channel), 1, destroy_channel, nullptr, + (void**)&channel); if (error != GRPC_ERROR_NONE) { gpr_log(GPR_ERROR, "channel stack builder failed: %s", grpc_error_string(error)); @@ -99,7 +99,7 @@ grpc_channel *grpc_channel_create_with_builder( channel->target = target; channel->is_client = grpc_channel_stack_type_is_client(channel_stack_type); gpr_mu_init(&channel->registered_call_mu); - channel->registered_calls = NULL; + channel->registered_calls = nullptr; gpr_atm_no_barrier_store( &channel->call_size_estimate, @@ -195,24 +195,24 @@ done: return channel; } -grpc_channel *grpc_channel_create(grpc_exec_ctx *exec_ctx, const char *target, - const grpc_channel_args *input_args, +grpc_channel* grpc_channel_create(grpc_exec_ctx* exec_ctx, const char* target, + const grpc_channel_args* input_args, grpc_channel_stack_type channel_stack_type, - grpc_transport *optional_transport) { - grpc_channel_stack_builder *builder = grpc_channel_stack_builder_create(); + grpc_transport* optional_transport) { + grpc_channel_stack_builder* builder = grpc_channel_stack_builder_create(); grpc_channel_stack_builder_set_channel_arguments(exec_ctx, builder, input_args); grpc_channel_stack_builder_set_target(builder, target); grpc_channel_stack_builder_set_transport(builder, optional_transport); if (!grpc_channel_init_create_stack(exec_ctx, builder, channel_stack_type)) { grpc_channel_stack_builder_destroy(exec_ctx, builder); - return NULL; + return nullptr; } return grpc_channel_create_with_builder(exec_ctx, builder, channel_stack_type); } -size_t grpc_channel_get_call_size_estimate(grpc_channel *channel) { +size_t grpc_channel_get_call_size_estimate(grpc_channel* channel) { #define ROUND_UP_SIZE 256 /* We round up our current estimate to the NEXT value of ROUND_UP_SIZE. This ensures: @@ -225,7 +225,7 @@ size_t grpc_channel_get_call_size_estimate(grpc_channel *channel) { ~(size_t)(ROUND_UP_SIZE - 1); } -void grpc_channel_update_call_size_estimate(grpc_channel *channel, +void grpc_channel_update_call_size_estimate(grpc_channel* channel, size_t size) { size_t cur = (size_t)gpr_atm_no_barrier_load(&channel->call_size_estimate); if (cur < size) { @@ -244,30 +244,30 @@ void grpc_channel_update_call_size_estimate(grpc_channel *channel, } } -char *grpc_channel_get_target(grpc_channel *channel) { +char* grpc_channel_get_target(grpc_channel* channel) { GRPC_API_TRACE("grpc_channel_get_target(channel=%p)", 1, (channel)); return gpr_strdup(channel->target); } -void grpc_channel_get_info(grpc_channel *channel, - const grpc_channel_info *channel_info) { +void grpc_channel_get_info(grpc_channel* channel, + const grpc_channel_info* channel_info) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - grpc_channel_element *elem = + grpc_channel_element* elem = grpc_channel_stack_element(CHANNEL_STACK_FROM_CHANNEL(channel), 0); elem->filter->get_channel_info(&exec_ctx, elem, channel_info); grpc_exec_ctx_finish(&exec_ctx); } -static grpc_call *grpc_channel_create_call_internal( - grpc_exec_ctx *exec_ctx, grpc_channel *channel, grpc_call *parent_call, - uint32_t propagation_mask, grpc_completion_queue *cq, - grpc_pollset_set *pollset_set_alternative, grpc_mdelem path_mdelem, +static grpc_call* grpc_channel_create_call_internal( + grpc_exec_ctx* exec_ctx, grpc_channel* channel, grpc_call* parent_call, + uint32_t propagation_mask, grpc_completion_queue* cq, + grpc_pollset_set* pollset_set_alternative, grpc_mdelem path_mdelem, grpc_mdelem authority_mdelem, grpc_millis deadline) { grpc_mdelem send_metadata[2]; size_t num_metadata = 0; GPR_ASSERT(channel->is_client); - GPR_ASSERT(!(cq != NULL && pollset_set_alternative != NULL)); + GPR_ASSERT(!(cq != nullptr && pollset_set_alternative != nullptr)); send_metadata[num_metadata++] = path_mdelem; if (!GRPC_MDISNULL(authority_mdelem)) { @@ -283,54 +283,54 @@ static grpc_call *grpc_channel_create_call_internal( args.propagation_mask = propagation_mask; args.cq = cq; args.pollset_set_alternative = pollset_set_alternative; - args.server_transport_data = NULL; + args.server_transport_data = nullptr; args.add_initial_metadata = send_metadata; args.add_initial_metadata_count = num_metadata; args.send_deadline = deadline; - grpc_call *call; + grpc_call* call; GRPC_LOG_IF_ERROR("call_create", grpc_call_create(exec_ctx, &args, &call)); return call; } -grpc_call *grpc_channel_create_call(grpc_channel *channel, - grpc_call *parent_call, +grpc_call* grpc_channel_create_call(grpc_channel* channel, + grpc_call* parent_call, uint32_t propagation_mask, - grpc_completion_queue *cq, - grpc_slice method, const grpc_slice *host, - gpr_timespec deadline, void *reserved) { + grpc_completion_queue* cq, + grpc_slice method, const grpc_slice* host, + gpr_timespec deadline, void* reserved) { GPR_ASSERT(!reserved); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - grpc_call *call = grpc_channel_create_call_internal( - &exec_ctx, channel, parent_call, propagation_mask, cq, NULL, + grpc_call* call = grpc_channel_create_call_internal( + &exec_ctx, channel, parent_call, propagation_mask, cq, nullptr, grpc_mdelem_from_slices(&exec_ctx, GRPC_MDSTR_PATH, grpc_slice_ref_internal(method)), - host != NULL ? grpc_mdelem_from_slices(&exec_ctx, GRPC_MDSTR_AUTHORITY, - grpc_slice_ref_internal(*host)) - : GRPC_MDNULL, + host != nullptr ? grpc_mdelem_from_slices(&exec_ctx, GRPC_MDSTR_AUTHORITY, + grpc_slice_ref_internal(*host)) + : GRPC_MDNULL, grpc_timespec_to_millis_round_up(deadline)); grpc_exec_ctx_finish(&exec_ctx); return call; } -grpc_call *grpc_channel_create_pollset_set_call( - grpc_exec_ctx *exec_ctx, grpc_channel *channel, grpc_call *parent_call, - uint32_t propagation_mask, grpc_pollset_set *pollset_set, grpc_slice method, - const grpc_slice *host, grpc_millis deadline, void *reserved) { +grpc_call* grpc_channel_create_pollset_set_call( + grpc_exec_ctx* exec_ctx, grpc_channel* channel, grpc_call* parent_call, + uint32_t propagation_mask, grpc_pollset_set* pollset_set, grpc_slice method, + const grpc_slice* host, grpc_millis deadline, void* reserved) { GPR_ASSERT(!reserved); return grpc_channel_create_call_internal( - exec_ctx, channel, parent_call, propagation_mask, NULL, pollset_set, + exec_ctx, channel, parent_call, propagation_mask, nullptr, pollset_set, grpc_mdelem_from_slices(exec_ctx, GRPC_MDSTR_PATH, grpc_slice_ref_internal(method)), - host != NULL ? grpc_mdelem_from_slices(exec_ctx, GRPC_MDSTR_AUTHORITY, - grpc_slice_ref_internal(*host)) - : GRPC_MDNULL, + host != nullptr ? grpc_mdelem_from_slices(exec_ctx, GRPC_MDSTR_AUTHORITY, + grpc_slice_ref_internal(*host)) + : GRPC_MDNULL, deadline); } -void *grpc_channel_register_call(grpc_channel *channel, const char *method, - const char *host, void *reserved) { - registered_call *rc = (registered_call *)gpr_malloc(sizeof(registered_call)); +void* grpc_channel_register_call(grpc_channel* channel, const char* method, + const char* host, void* reserved) { + registered_call* rc = (registered_call*)gpr_malloc(sizeof(registered_call)); GRPC_API_TRACE( "grpc_channel_register_call(channel=%p, method=%s, host=%s, reserved=%p)", 4, (channel, method, host, reserved)); @@ -353,11 +353,11 @@ void *grpc_channel_register_call(grpc_channel *channel, const char *method, return rc; } -grpc_call *grpc_channel_create_registered_call( - grpc_channel *channel, grpc_call *parent_call, uint32_t propagation_mask, - grpc_completion_queue *completion_queue, void *registered_call_handle, - gpr_timespec deadline, void *reserved) { - registered_call *rc = (registered_call *)registered_call_handle; +grpc_call* grpc_channel_create_registered_call( + grpc_channel* channel, grpc_call* parent_call, uint32_t propagation_mask, + grpc_completion_queue* completion_queue, void* registered_call_handle, + gpr_timespec deadline, void* reserved) { + registered_call* rc = (registered_call*)registered_call_handle; GRPC_API_TRACE( "grpc_channel_create_registered_call(" "channel=%p, parent_call=%p, propagation_mask=%x, completion_queue=%p, " @@ -365,14 +365,15 @@ grpc_call *grpc_channel_create_registered_call( "deadline=gpr_timespec { tv_sec: %" PRId64 ", tv_nsec: %d, clock_type: %d }, " "reserved=%p)", - 9, (channel, parent_call, (unsigned)propagation_mask, completion_queue, - registered_call_handle, deadline.tv_sec, deadline.tv_nsec, - (int)deadline.clock_type, reserved)); + 9, + (channel, parent_call, (unsigned)propagation_mask, completion_queue, + registered_call_handle, deadline.tv_sec, deadline.tv_nsec, + (int)deadline.clock_type, reserved)); GPR_ASSERT(!reserved); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - grpc_call *call = grpc_channel_create_call_internal( - &exec_ctx, channel, parent_call, propagation_mask, completion_queue, NULL, - GRPC_MDELEM_REF(rc->path), GRPC_MDELEM_REF(rc->authority), + grpc_call* call = grpc_channel_create_call_internal( + &exec_ctx, channel, parent_call, propagation_mask, completion_queue, + nullptr, GRPC_MDELEM_REF(rc->path), GRPC_MDELEM_REF(rc->authority), grpc_timespec_to_millis_round_up(deadline)); grpc_exec_ctx_finish(&exec_ctx); return call; @@ -380,26 +381,26 @@ grpc_call *grpc_channel_create_registered_call( #ifndef NDEBUG #define REF_REASON reason -#define REF_ARG , const char *reason +#define REF_ARG , const char* reason #else #define REF_REASON "" #define REF_ARG #endif -void grpc_channel_internal_ref(grpc_channel *c REF_ARG) { +void grpc_channel_internal_ref(grpc_channel* c REF_ARG) { GRPC_CHANNEL_STACK_REF(CHANNEL_STACK_FROM_CHANNEL(c), REF_REASON); } -void grpc_channel_internal_unref(grpc_exec_ctx *exec_ctx, - grpc_channel *c REF_ARG) { +void grpc_channel_internal_unref(grpc_exec_ctx* exec_ctx, + grpc_channel* c REF_ARG) { GRPC_CHANNEL_STACK_UNREF(exec_ctx, CHANNEL_STACK_FROM_CHANNEL(c), REF_REASON); } -static void destroy_channel(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_channel *channel = (grpc_channel *)arg; +static void destroy_channel(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_channel* channel = (grpc_channel*)arg; grpc_channel_stack_destroy(exec_ctx, CHANNEL_STACK_FROM_CHANNEL(channel)); while (channel->registered_calls) { - registered_call *rc = channel->registered_calls; + registered_call* rc = channel->registered_calls; channel->registered_calls = rc->next; GRPC_MDELEM_UNREF(exec_ctx, rc->path); GRPC_MDELEM_UNREF(exec_ctx, rc->authority); @@ -411,9 +412,9 @@ static void destroy_channel(grpc_exec_ctx *exec_ctx, void *arg, gpr_free(channel); } -void grpc_channel_destroy(grpc_channel *channel) { - grpc_transport_op *op = grpc_make_transport_op(NULL); - grpc_channel_element *elem; +void grpc_channel_destroy(grpc_channel* channel) { + grpc_transport_op* op = grpc_make_transport_op(nullptr); + grpc_channel_element* elem; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GRPC_API_TRACE("grpc_channel_destroy(channel=%p)", 1, (channel)); op->disconnect_with_error = @@ -426,17 +427,17 @@ void grpc_channel_destroy(grpc_channel *channel) { grpc_exec_ctx_finish(&exec_ctx); } -grpc_channel_stack *grpc_channel_get_channel_stack(grpc_channel *channel) { +grpc_channel_stack* grpc_channel_get_channel_stack(grpc_channel* channel) { return CHANNEL_STACK_FROM_CHANNEL(channel); } grpc_compression_options grpc_channel_compression_options( - const grpc_channel *channel) { + const grpc_channel* channel) { return channel->compression_options; } -grpc_mdelem grpc_channel_get_reffed_status_elem(grpc_exec_ctx *exec_ctx, - grpc_channel *channel, int i) { +grpc_mdelem grpc_channel_get_reffed_status_elem(grpc_exec_ctx* exec_ctx, + grpc_channel* channel, int i) { char tmp[GPR_LTOA_MIN_BUFSIZE]; switch (i) { case 0: diff --git a/src/core/lib/surface/channel.h b/src/core/lib/surface/channel.h index 4d1c7e369fd..a2e53c777d6 100644 --- a/src/core/lib/surface/channel.h +++ b/src/core/lib/surface/channel.h @@ -23,17 +23,13 @@ #include "src/core/lib/channel/channel_stack_builder.h" #include "src/core/lib/surface/channel_stack_type.h" -#ifdef __cplusplus -extern "C" { -#endif - -grpc_channel *grpc_channel_create(grpc_exec_ctx *exec_ctx, const char *target, - const grpc_channel_args *args, +grpc_channel* grpc_channel_create(grpc_exec_ctx* exec_ctx, const char* target, + const grpc_channel_args* args, grpc_channel_stack_type channel_stack_type, - grpc_transport *optional_transport); + grpc_transport* optional_transport); -grpc_channel *grpc_channel_create_with_builder( - grpc_exec_ctx *exec_ctx, grpc_channel_stack_builder *builder, +grpc_channel* grpc_channel_create_with_builder( + grpc_exec_ctx* exec_ctx, grpc_channel_stack_builder* builder, grpc_channel_stack_type channel_stack_type); /** Create a call given a grpc_channel, in order to call \a method. @@ -44,37 +40,37 @@ grpc_channel *grpc_channel_create_with_builder( non-NULL, it must be a server-side call. It will be used to propagate properties from the server call to this new client call, depending on the value of \a propagation_mask (see propagation_bits.h for possible values) */ -grpc_call *grpc_channel_create_pollset_set_call( - grpc_exec_ctx *exec_ctx, grpc_channel *channel, grpc_call *parent_call, - uint32_t propagation_mask, grpc_pollset_set *pollset_set, grpc_slice method, - const grpc_slice *host, grpc_millis deadline, void *reserved); +grpc_call* grpc_channel_create_pollset_set_call( + grpc_exec_ctx* exec_ctx, grpc_channel* channel, grpc_call* parent_call, + uint32_t propagation_mask, grpc_pollset_set* pollset_set, grpc_slice method, + const grpc_slice* host, grpc_millis deadline, void* reserved); /** Get a (borrowed) pointer to this channels underlying channel stack */ -grpc_channel_stack *grpc_channel_get_channel_stack(grpc_channel *channel); +grpc_channel_stack* grpc_channel_get_channel_stack(grpc_channel* channel); /** Get a grpc_mdelem of grpc-status: X where X is the numeric value of status_code. The returned elem is owned by the caller. */ -grpc_mdelem grpc_channel_get_reffed_status_elem(grpc_exec_ctx *exec_ctx, - grpc_channel *channel, +grpc_mdelem grpc_channel_get_reffed_status_elem(grpc_exec_ctx* exec_ctx, + grpc_channel* channel, int status_code); -size_t grpc_channel_get_call_size_estimate(grpc_channel *channel); -void grpc_channel_update_call_size_estimate(grpc_channel *channel, size_t size); +size_t grpc_channel_get_call_size_estimate(grpc_channel* channel); +void grpc_channel_update_call_size_estimate(grpc_channel* channel, size_t size); #ifndef NDEBUG -void grpc_channel_internal_ref(grpc_channel *channel, const char *reason); -void grpc_channel_internal_unref(grpc_exec_ctx *exec_ctx, grpc_channel *channel, - const char *reason); +void grpc_channel_internal_ref(grpc_channel* channel, const char* reason); +void grpc_channel_internal_unref(grpc_exec_ctx* exec_ctx, grpc_channel* channel, + const char* reason); #define GRPC_CHANNEL_INTERNAL_REF(channel, reason) \ grpc_channel_internal_ref(channel, reason) #define GRPC_CHANNEL_INTERNAL_UNREF(exec_ctx, channel, reason) \ grpc_channel_internal_unref(exec_ctx, channel, reason) #else -void grpc_channel_internal_ref(grpc_channel *channel); -void grpc_channel_internal_unref(grpc_exec_ctx *exec_ctx, - grpc_channel *channel); +void grpc_channel_internal_ref(grpc_channel* channel); +void grpc_channel_internal_unref(grpc_exec_ctx* exec_ctx, + grpc_channel* channel); #define GRPC_CHANNEL_INTERNAL_REF(channel, reason) \ grpc_channel_internal_ref(channel) #define GRPC_CHANNEL_INTERNAL_UNREF(exec_ctx, channel, reason) \ @@ -83,10 +79,6 @@ void grpc_channel_internal_unref(grpc_exec_ctx *exec_ctx, /** Return the channel's compression options. */ grpc_compression_options grpc_channel_compression_options( - const grpc_channel *channel); - -#ifdef __cplusplus -} -#endif + const grpc_channel* channel); #endif /* GRPC_CORE_LIB_SURFACE_CHANNEL_H */ diff --git a/src/core/lib/surface/channel_init.cc b/src/core/lib/surface/channel_init.cc index 33f444b89e9..b563537f357 100644 --- a/src/core/lib/surface/channel_init.cc +++ b/src/core/lib/surface/channel_init.cc @@ -23,13 +23,13 @@ typedef struct stage_slot { grpc_channel_init_stage fn; - void *arg; + void* arg; int priority; size_t insertion_order; } stage_slot; typedef struct stage_slots { - stage_slot *slots; + stage_slot* slots; size_t num_slots; size_t cap_slots; } stage_slots; @@ -39,7 +39,7 @@ static bool g_finalized; void grpc_channel_init_init(void) { for (int i = 0; i < GRPC_NUM_CHANNEL_STACK_TYPES; i++) { - g_slots[i].slots = NULL; + g_slots[i].slots = nullptr; g_slots[i].num_slots = 0; g_slots[i].cap_slots = 0; } @@ -49,24 +49,24 @@ void grpc_channel_init_init(void) { void grpc_channel_init_register_stage(grpc_channel_stack_type type, int priority, grpc_channel_init_stage stage, - void *stage_arg) { + void* stage_arg) { GPR_ASSERT(!g_finalized); if (g_slots[type].cap_slots == g_slots[type].num_slots) { g_slots[type].cap_slots = GPR_MAX(8, 3 * g_slots[type].cap_slots / 2); - g_slots[type].slots = (stage_slot *)gpr_realloc( + g_slots[type].slots = (stage_slot*)gpr_realloc( g_slots[type].slots, g_slots[type].cap_slots * sizeof(*g_slots[type].slots)); } - stage_slot *s = &g_slots[type].slots[g_slots[type].num_slots++]; + stage_slot* s = &g_slots[type].slots[g_slots[type].num_slots++]; s->insertion_order = g_slots[type].num_slots; s->priority = priority; s->fn = stage; s->arg = stage_arg; } -static int compare_slots(const void *a, const void *b) { - const stage_slot *sa = (const stage_slot *)a; - const stage_slot *sb = (const stage_slot *)b; +static int compare_slots(const void* a, const void* b) { + const stage_slot* sa = (const stage_slot*)a; + const stage_slot* sb = (const stage_slot*)b; int c = GPR_ICMP(sa->priority, sb->priority); if (c != 0) return c; @@ -85,12 +85,12 @@ void grpc_channel_init_finalize(void) { void grpc_channel_init_shutdown(void) { for (int i = 0; i < GRPC_NUM_CHANNEL_STACK_TYPES; i++) { gpr_free(g_slots[i].slots); - g_slots[i].slots = (stage_slot *)(void *)(uintptr_t)0xdeadbeef; + g_slots[i].slots = (stage_slot*)(void*)(uintptr_t)0xdeadbeef; } } -bool grpc_channel_init_create_stack(grpc_exec_ctx *exec_ctx, - grpc_channel_stack_builder *builder, +bool grpc_channel_init_create_stack(grpc_exec_ctx* exec_ctx, + grpc_channel_stack_builder* builder, grpc_channel_stack_type type) { GPR_ASSERT(g_finalized); @@ -98,7 +98,7 @@ bool grpc_channel_init_create_stack(grpc_exec_ctx *exec_ctx, grpc_channel_stack_type_string(type)); for (size_t i = 0; i < g_slots[type].num_slots; i++) { - const stage_slot *slot = &g_slots[type].slots[i]; + const stage_slot* slot = &g_slots[type].slots[i]; if (!slot->fn(exec_ctx, builder, slot->arg)) { return false; } diff --git a/src/core/lib/surface/channel_init.h b/src/core/lib/surface/channel_init.h index 5f109332ad6..556ecc4147e 100644 --- a/src/core/lib/surface/channel_init.h +++ b/src/core/lib/surface/channel_init.h @@ -25,10 +25,6 @@ #define GRPC_CHANNEL_INIT_BUILTIN_PRIORITY 10000 -#ifdef __cplusplus -extern "C" { -#endif - /// This module provides a way for plugins (and the grpc core library itself) /// to register mutators for channel stacks. /// It also provides a universal entry path to run those mutators to build @@ -36,9 +32,9 @@ extern "C" { /// One stage of mutation: call functions against \a builder to influence the /// finally constructed channel stack -typedef bool (*grpc_channel_init_stage)(grpc_exec_ctx *exec_ctx, - grpc_channel_stack_builder *builder, - void *arg); +typedef bool (*grpc_channel_init_stage)(grpc_exec_ctx* exec_ctx, + grpc_channel_stack_builder* builder, + void* arg); /// Global initialization of the system void grpc_channel_init_init(void); @@ -51,7 +47,7 @@ void grpc_channel_init_init(void); void grpc_channel_init_register_stage(grpc_channel_stack_type type, int priority, grpc_channel_init_stage stage_fn, - void *stage_arg); + void* stage_arg); /// Finalize registration. No more calls to grpc_channel_init_register_stage are /// allowed. @@ -70,12 +66,8 @@ void grpc_channel_init_shutdown(void); /// \a optional_transport is either NULL or a constructed transport object /// Returns a pointer to the base of the memory allocated (the actual channel /// stack object will be prefix_bytes past that pointer) -bool grpc_channel_init_create_stack(grpc_exec_ctx *exec_ctx, - grpc_channel_stack_builder *builder, +bool grpc_channel_init_create_stack(grpc_exec_ctx* exec_ctx, + grpc_channel_stack_builder* builder, grpc_channel_stack_type type); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SURFACE_CHANNEL_INIT_H */ diff --git a/src/core/lib/surface/channel_ping.cc b/src/core/lib/surface/channel_ping.cc index f45b5689588..e8f47f01cf4 100644 --- a/src/core/lib/surface/channel_ping.cc +++ b/src/core/lib/surface/channel_ping.cc @@ -28,32 +28,32 @@ typedef struct { grpc_closure closure; - void *tag; - grpc_completion_queue *cq; + void* tag; + grpc_completion_queue* cq; grpc_cq_completion completion_storage; } ping_result; -static void ping_destroy(grpc_exec_ctx *exec_ctx, void *arg, - grpc_cq_completion *storage) { +static void ping_destroy(grpc_exec_ctx* exec_ctx, void* arg, + grpc_cq_completion* storage) { gpr_free(arg); } -static void ping_done(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { - ping_result *pr = (ping_result *)arg; +static void ping_done(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) { + ping_result* pr = (ping_result*)arg; grpc_cq_end_op(exec_ctx, pr->cq, pr->tag, GRPC_ERROR_REF(error), ping_destroy, pr, &pr->completion_storage); } -void grpc_channel_ping(grpc_channel *channel, grpc_completion_queue *cq, - void *tag, void *reserved) { +void grpc_channel_ping(grpc_channel* channel, grpc_completion_queue* cq, + void* tag, void* reserved) { GRPC_API_TRACE("grpc_channel_ping(channel=%p, cq=%p, tag=%p, reserved=%p)", 4, (channel, cq, tag, reserved)); - grpc_transport_op *op = grpc_make_transport_op(NULL); - ping_result *pr = (ping_result *)gpr_malloc(sizeof(*pr)); - grpc_channel_element *top_elem = + grpc_transport_op* op = grpc_make_transport_op(nullptr); + ping_result* pr = (ping_result*)gpr_malloc(sizeof(*pr)); + grpc_channel_element* top_elem = grpc_channel_stack_element(grpc_channel_get_channel_stack(channel), 0); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - GPR_ASSERT(reserved == NULL); + GPR_ASSERT(reserved == nullptr); pr->tag = tag; pr->cq = cq; GRPC_CLOSURE_INIT(&pr->closure, ping_done, pr, grpc_schedule_on_exec_ctx); diff --git a/src/core/lib/surface/channel_stack_type.cc b/src/core/lib/surface/channel_stack_type.cc index 5f5c8777273..366c4529427 100644 --- a/src/core/lib/surface/channel_stack_type.cc +++ b/src/core/lib/surface/channel_stack_type.cc @@ -38,7 +38,7 @@ bool grpc_channel_stack_type_is_client(grpc_channel_stack_type type) { GPR_UNREACHABLE_CODE(return true;); } -const char *grpc_channel_stack_type_string(grpc_channel_stack_type type) { +const char* grpc_channel_stack_type_string(grpc_channel_stack_type type) { switch (type) { case GRPC_CLIENT_CHANNEL: return "CLIENT_CHANNEL"; diff --git a/src/core/lib/surface/channel_stack_type.h b/src/core/lib/surface/channel_stack_type.h index c77848794cc..52f85a64069 100644 --- a/src/core/lib/surface/channel_stack_type.h +++ b/src/core/lib/surface/channel_stack_type.h @@ -21,10 +21,6 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - typedef enum { // normal top-half client channel with load-balancing, connection management GRPC_CLIENT_CHANNEL, @@ -44,10 +40,6 @@ typedef enum { bool grpc_channel_stack_type_is_client(grpc_channel_stack_type type); -const char *grpc_channel_stack_type_string(grpc_channel_stack_type type); - -#ifdef __cplusplus -} -#endif +const char* grpc_channel_stack_type_string(grpc_channel_stack_type type); #endif /* GRPC_CORE_LIB_SURFACE_CHANNEL_STACK_TYPE_H */ diff --git a/src/core/lib/surface/completion_queue.cc b/src/core/lib/surface/completion_queue.cc index 5009f786e68..98d7e359437 100644 --- a/src/core/lib/surface/completion_queue.cc +++ b/src/core/lib/surface/completion_queue.cc @@ -40,14 +40,9 @@ #include "src/core/lib/surface/call.h" #include "src/core/lib/surface/event_string.h" -grpc_tracer_flag grpc_trace_operation_failures = - GRPC_TRACER_INITIALIZER(false, "op_failure"); -#ifndef NDEBUG -grpc_tracer_flag grpc_trace_pending_tags = - GRPC_TRACER_INITIALIZER(false, "pending_tags"); -grpc_tracer_flag grpc_trace_cq_refcount = - GRPC_TRACER_INITIALIZER(false, "cq_refcount"); -#endif +grpc_core::TraceFlag grpc_trace_operation_failures(false, "op_failure"); +grpc_core::DebugOnlyTraceFlag grpc_trace_pending_tags(false, "pending_tags"); +grpc_core::DebugOnlyTraceFlag grpc_trace_cq_refcount(false, "cq_refcount"); // Specifies a cq thread local cache. // The first event that occurs on a thread @@ -58,63 +53,63 @@ GPR_TLS_DECL(g_cached_event); GPR_TLS_DECL(g_cached_cq); typedef struct { - grpc_pollset_worker **worker; - void *tag; + grpc_pollset_worker** worker; + void* tag; } plucker; typedef struct { bool can_get_pollset; bool can_listen; size_t (*size)(void); - void (*init)(grpc_pollset *pollset, gpr_mu **mu); - grpc_error *(*kick)(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker *specific_worker); - grpc_error *(*work)(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker **worker, grpc_millis deadline); - void (*shutdown)(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_closure *closure); - void (*destroy)(grpc_exec_ctx *exec_ctx, grpc_pollset *pollset); + void (*init)(grpc_pollset* pollset, gpr_mu** mu); + grpc_error* (*kick)(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker* specific_worker); + grpc_error* (*work)(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker** worker, grpc_millis deadline); + void (*shutdown)(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_closure* closure); + void (*destroy)(grpc_exec_ctx* exec_ctx, grpc_pollset* pollset); } cq_poller_vtable; typedef struct non_polling_worker { gpr_cv cv; bool kicked; - struct non_polling_worker *next; - struct non_polling_worker *prev; + struct non_polling_worker* next; + struct non_polling_worker* prev; } non_polling_worker; typedef struct { gpr_mu mu; - non_polling_worker *root; - grpc_closure *shutdown; + non_polling_worker* root; + grpc_closure* shutdown; } non_polling_poller; static size_t non_polling_poller_size(void) { return sizeof(non_polling_poller); } -static void non_polling_poller_init(grpc_pollset *pollset, gpr_mu **mu) { - non_polling_poller *npp = (non_polling_poller *)pollset; +static void non_polling_poller_init(grpc_pollset* pollset, gpr_mu** mu) { + non_polling_poller* npp = (non_polling_poller*)pollset; gpr_mu_init(&npp->mu); *mu = &npp->mu; } -static void non_polling_poller_destroy(grpc_exec_ctx *exec_ctx, - grpc_pollset *pollset) { - non_polling_poller *npp = (non_polling_poller *)pollset; +static void non_polling_poller_destroy(grpc_exec_ctx* exec_ctx, + grpc_pollset* pollset) { + non_polling_poller* npp = (non_polling_poller*)pollset; gpr_mu_destroy(&npp->mu); } -static grpc_error *non_polling_poller_work(grpc_exec_ctx *exec_ctx, - grpc_pollset *pollset, - grpc_pollset_worker **worker, +static grpc_error* non_polling_poller_work(grpc_exec_ctx* exec_ctx, + grpc_pollset* pollset, + grpc_pollset_worker** worker, grpc_millis deadline) { - non_polling_poller *npp = (non_polling_poller *)pollset; + non_polling_poller* npp = (non_polling_poller*)pollset; if (npp->shutdown) return GRPC_ERROR_NONE; non_polling_worker w; gpr_cv_init(&w.cv); - if (worker != NULL) *worker = (grpc_pollset_worker *)&w; - if (npp->root == NULL) { + if (worker != nullptr) *worker = (grpc_pollset_worker*)&w; + if (npp->root == nullptr) { npp->root = w.next = w.prev = &w; } else { w.next = npp->root; @@ -127,29 +122,31 @@ static grpc_error *non_polling_poller_work(grpc_exec_ctx *exec_ctx, while (!npp->shutdown && !w.kicked && !gpr_cv_wait(&w.cv, &npp->mu, deadline_ts)) ; + grpc_exec_ctx_invalidate_now(exec_ctx); if (&w == npp->root) { npp->root = w.next; if (&w == npp->root) { if (npp->shutdown) { GRPC_CLOSURE_SCHED(exec_ctx, npp->shutdown, GRPC_ERROR_NONE); } - npp->root = NULL; + npp->root = nullptr; } } w.next->prev = w.prev; w.prev->next = w.next; gpr_cv_destroy(&w.cv); - if (worker != NULL) *worker = NULL; + if (worker != nullptr) *worker = nullptr; return GRPC_ERROR_NONE; } -static grpc_error *non_polling_poller_kick( - grpc_exec_ctx *exec_ctx, grpc_pollset *pollset, - grpc_pollset_worker *specific_worker) { - non_polling_poller *p = (non_polling_poller *)pollset; - if (specific_worker == NULL) specific_worker = (grpc_pollset_worker *)p->root; - if (specific_worker != NULL) { - non_polling_worker *w = (non_polling_worker *)specific_worker; +static grpc_error* non_polling_poller_kick( + grpc_exec_ctx* exec_ctx, grpc_pollset* pollset, + grpc_pollset_worker* specific_worker) { + non_polling_poller* p = (non_polling_poller*)pollset; + if (specific_worker == nullptr) + specific_worker = (grpc_pollset_worker*)p->root; + if (specific_worker != nullptr) { + non_polling_worker* w = (non_polling_worker*)specific_worker; if (!w->kicked) { w->kicked = true; gpr_cv_signal(&w->cv); @@ -158,16 +155,16 @@ static grpc_error *non_polling_poller_kick( return GRPC_ERROR_NONE; } -static void non_polling_poller_shutdown(grpc_exec_ctx *exec_ctx, - grpc_pollset *pollset, - grpc_closure *closure) { - non_polling_poller *p = (non_polling_poller *)pollset; - GPR_ASSERT(closure != NULL); +static void non_polling_poller_shutdown(grpc_exec_ctx* exec_ctx, + grpc_pollset* pollset, + grpc_closure* closure) { + non_polling_poller* p = (non_polling_poller*)pollset; + GPR_ASSERT(closure != nullptr); p->shutdown = closure; - if (p->root == NULL) { + if (p->root == nullptr) { GRPC_CLOSURE_SCHED(exec_ctx, closure, GRPC_ERROR_NONE); } else { - non_polling_worker *w = p->root; + non_polling_worker* w = p->root; do { gpr_cv_signal(&w->cv); w = w->next; @@ -191,19 +188,19 @@ static const cq_poller_vtable g_poller_vtable_by_poller_type[] = { typedef struct cq_vtable { grpc_cq_completion_type cq_completion_type; size_t data_size; - void (*init)(void *data); - void (*shutdown)(grpc_exec_ctx *exec_ctx, grpc_completion_queue *cq); - void (*destroy)(void *data); - bool (*begin_op)(grpc_completion_queue *cq, void *tag); - void (*end_op)(grpc_exec_ctx *exec_ctx, grpc_completion_queue *cq, void *tag, - grpc_error *error, - void (*done)(grpc_exec_ctx *exec_ctx, void *done_arg, - grpc_cq_completion *storage), - void *done_arg, grpc_cq_completion *storage); - grpc_event (*next)(grpc_completion_queue *cq, gpr_timespec deadline, - void *reserved); - grpc_event (*pluck)(grpc_completion_queue *cq, void *tag, - gpr_timespec deadline, void *reserved); + void (*init)(void* data); + void (*shutdown)(grpc_exec_ctx* exec_ctx, grpc_completion_queue* cq); + void (*destroy)(void* data); + bool (*begin_op)(grpc_completion_queue* cq, void* tag); + void (*end_op)(grpc_exec_ctx* exec_ctx, grpc_completion_queue* cq, void* tag, + grpc_error* error, + void (*done)(grpc_exec_ctx* exec_ctx, void* done_arg, + grpc_cq_completion* storage), + void* done_arg, grpc_cq_completion* storage); + grpc_event (*next)(grpc_completion_queue* cq, gpr_timespec deadline, + void* reserved); + grpc_event (*pluck)(grpc_completion_queue* cq, void* tag, + gpr_timespec deadline, void* reserved); } cq_vtable; /* Queue that holds the cq_completion_events. Internally uses gpr_mpscq queue @@ -240,7 +237,7 @@ typedef struct cq_next_data { typedef struct cq_pluck_data { /** Completed events for completion-queues of type GRPC_CQ_PLUCK */ grpc_cq_completion completed_head; - grpc_cq_completion *completed_tail; + grpc_cq_completion* completed_tail; /** Number of pending events (+1 if we're not shutdown) */ gpr_atm pending_events; @@ -267,13 +264,13 @@ struct grpc_completion_queue { /** Once owning_refs drops to zero, we will destroy the cq */ gpr_refcount owning_refs; - gpr_mu *mu; + gpr_mu* mu; - const cq_vtable *vtable; - const cq_poller_vtable *poller_vtable; + const cq_vtable* vtable; + const cq_poller_vtable* poller_vtable; #ifndef NDEBUG - void **outstanding_tags; + void** outstanding_tags; size_t outstanding_tag_count; size_t outstanding_tag_capacity; #endif @@ -283,102 +280,100 @@ struct grpc_completion_queue { }; /* Forward declarations */ -static void cq_finish_shutdown_next(grpc_exec_ctx *exec_ctx, - grpc_completion_queue *cq); -static void cq_finish_shutdown_pluck(grpc_exec_ctx *exec_ctx, - grpc_completion_queue *cq); -static void cq_shutdown_next(grpc_exec_ctx *exec_ctx, - grpc_completion_queue *cq); -static void cq_shutdown_pluck(grpc_exec_ctx *exec_ctx, - grpc_completion_queue *cq); - -static bool cq_begin_op_for_next(grpc_completion_queue *cq, void *tag); -static bool cq_begin_op_for_pluck(grpc_completion_queue *cq, void *tag); - -static void cq_end_op_for_next(grpc_exec_ctx *exec_ctx, - grpc_completion_queue *cq, void *tag, - grpc_error *error, - void (*done)(grpc_exec_ctx *exec_ctx, - void *done_arg, - grpc_cq_completion *storage), - void *done_arg, grpc_cq_completion *storage); - -static void cq_end_op_for_pluck(grpc_exec_ctx *exec_ctx, - grpc_completion_queue *cq, void *tag, - grpc_error *error, - void (*done)(grpc_exec_ctx *exec_ctx, - void *done_arg, - grpc_cq_completion *storage), - void *done_arg, grpc_cq_completion *storage); - -static grpc_event cq_next(grpc_completion_queue *cq, gpr_timespec deadline, - void *reserved); - -static grpc_event cq_pluck(grpc_completion_queue *cq, void *tag, - gpr_timespec deadline, void *reserved); - -static void cq_init_next(void *data); -static void cq_init_pluck(void *data); -static void cq_destroy_next(void *data); -static void cq_destroy_pluck(void *data); +static void cq_finish_shutdown_next(grpc_exec_ctx* exec_ctx, + grpc_completion_queue* cq); +static void cq_finish_shutdown_pluck(grpc_exec_ctx* exec_ctx, + grpc_completion_queue* cq); +static void cq_shutdown_next(grpc_exec_ctx* exec_ctx, + grpc_completion_queue* cq); +static void cq_shutdown_pluck(grpc_exec_ctx* exec_ctx, + grpc_completion_queue* cq); + +static bool cq_begin_op_for_next(grpc_completion_queue* cq, void* tag); +static bool cq_begin_op_for_pluck(grpc_completion_queue* cq, void* tag); + +static void cq_end_op_for_next(grpc_exec_ctx* exec_ctx, + grpc_completion_queue* cq, void* tag, + grpc_error* error, + void (*done)(grpc_exec_ctx* exec_ctx, + void* done_arg, + grpc_cq_completion* storage), + void* done_arg, grpc_cq_completion* storage); + +static void cq_end_op_for_pluck(grpc_exec_ctx* exec_ctx, + grpc_completion_queue* cq, void* tag, + grpc_error* error, + void (*done)(grpc_exec_ctx* exec_ctx, + void* done_arg, + grpc_cq_completion* storage), + void* done_arg, grpc_cq_completion* storage); + +static grpc_event cq_next(grpc_completion_queue* cq, gpr_timespec deadline, + void* reserved); + +static grpc_event cq_pluck(grpc_completion_queue* cq, void* tag, + gpr_timespec deadline, void* reserved); + +static void cq_init_next(void* data); +static void cq_init_pluck(void* data); +static void cq_destroy_next(void* data); +static void cq_destroy_pluck(void* data); /* Completion queue vtables based on the completion-type */ static const cq_vtable g_cq_vtable[] = { /* GRPC_CQ_NEXT */ {GRPC_CQ_NEXT, sizeof(cq_next_data), cq_init_next, cq_shutdown_next, - cq_destroy_next, cq_begin_op_for_next, cq_end_op_for_next, cq_next, NULL}, + cq_destroy_next, cq_begin_op_for_next, cq_end_op_for_next, cq_next, + nullptr}, /* GRPC_CQ_PLUCK */ {GRPC_CQ_PLUCK, sizeof(cq_pluck_data), cq_init_pluck, cq_shutdown_pluck, - cq_destroy_pluck, cq_begin_op_for_pluck, cq_end_op_for_pluck, NULL, + cq_destroy_pluck, cq_begin_op_for_pluck, cq_end_op_for_pluck, nullptr, cq_pluck}, }; -#define DATA_FROM_CQ(cq) ((void *)(cq + 1)) +#define DATA_FROM_CQ(cq) ((void*)(cq + 1)) #define POLLSET_FROM_CQ(cq) \ - ((grpc_pollset *)(cq->vtable->data_size + (char *)DATA_FROM_CQ(cq))) - -grpc_tracer_flag grpc_cq_pluck_trace = - GRPC_TRACER_INITIALIZER(true, "queue_pluck"); -grpc_tracer_flag grpc_cq_event_timeout_trace = - GRPC_TRACER_INITIALIZER(true, "queue_timeout"); - -#define GRPC_SURFACE_TRACE_RETURNED_EVENT(cq, event) \ - if (GRPC_TRACER_ON(grpc_api_trace) && \ - (GRPC_TRACER_ON(grpc_cq_pluck_trace) || \ - (event)->type != GRPC_QUEUE_TIMEOUT)) { \ - char *_ev = grpc_event_string(event); \ - gpr_log(GPR_INFO, "RETURN_EVENT[%p]: %s", cq, _ev); \ - gpr_free(_ev); \ + ((grpc_pollset*)(cq->vtable->data_size + (char*)DATA_FROM_CQ(cq))) + +grpc_core::TraceFlag grpc_cq_pluck_trace(true, "queue_pluck"); +grpc_core::TraceFlag grpc_cq_event_timeout_trace(true, "queue_timeout"); + +#define GRPC_SURFACE_TRACE_RETURNED_EVENT(cq, event) \ + if (grpc_api_trace.enabled() && (grpc_cq_pluck_trace.enabled() || \ + (event)->type != GRPC_QUEUE_TIMEOUT)) { \ + char* _ev = grpc_event_string(event); \ + gpr_log(GPR_INFO, "RETURN_EVENT[%p]: %s", cq, _ev); \ + gpr_free(_ev); \ } -static void on_pollset_shutdown_done(grpc_exec_ctx *exec_ctx, void *cq, - grpc_error *error); +static void on_pollset_shutdown_done(grpc_exec_ctx* exec_ctx, void* cq, + grpc_error* error); void grpc_cq_global_init() { gpr_tls_init(&g_cached_event); gpr_tls_init(&g_cached_cq); } -void grpc_completion_queue_thread_local_cache_init(grpc_completion_queue *cq) { - if ((grpc_completion_queue *)gpr_tls_get(&g_cached_cq) == nullptr) { +void grpc_completion_queue_thread_local_cache_init(grpc_completion_queue* cq) { + if ((grpc_completion_queue*)gpr_tls_get(&g_cached_cq) == nullptr) { gpr_tls_set(&g_cached_event, (intptr_t)0); gpr_tls_set(&g_cached_cq, (intptr_t)cq); } } -int grpc_completion_queue_thread_local_cache_flush(grpc_completion_queue *cq, - void **tag, int *ok) { - grpc_cq_completion *storage = - (grpc_cq_completion *)gpr_tls_get(&g_cached_event); +int grpc_completion_queue_thread_local_cache_flush(grpc_completion_queue* cq, + void** tag, int* ok) { + grpc_cq_completion* storage = + (grpc_cq_completion*)gpr_tls_get(&g_cached_event); int ret = 0; - if (storage != NULL && - (grpc_completion_queue *)gpr_tls_get(&g_cached_cq) == cq) { + if (storage != nullptr && + (grpc_completion_queue*)gpr_tls_get(&g_cached_cq) == cq) { *tag = storage->tag; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - storage->done(&exec_ctx, storage->done_arg, storage); *ok = (storage->next & (uintptr_t)(1)) == 1; + storage->done(&exec_ctx, storage->done_arg, storage); ret = 1; - cq_next_data *cqd = (cq_next_data *)DATA_FROM_CQ(cq); + cq_next_data* cqd = (cq_next_data*)DATA_FROM_CQ(cq); if (gpr_atm_full_fetch_add(&cqd->pending_events, -1) == 1) { GRPC_CQ_INTERNAL_REF(cq, "shutting_down"); gpr_mu_lock(cq->mu); @@ -394,33 +389,33 @@ int grpc_completion_queue_thread_local_cache_flush(grpc_completion_queue *cq, return ret; } -static void cq_event_queue_init(grpc_cq_event_queue *q) { +static void cq_event_queue_init(grpc_cq_event_queue* q) { gpr_mpscq_init(&q->queue); q->queue_lock = GPR_SPINLOCK_INITIALIZER; gpr_atm_no_barrier_store(&q->num_queue_items, 0); } -static void cq_event_queue_destroy(grpc_cq_event_queue *q) { +static void cq_event_queue_destroy(grpc_cq_event_queue* q) { gpr_mpscq_destroy(&q->queue); } -static bool cq_event_queue_push(grpc_cq_event_queue *q, grpc_cq_completion *c) { - gpr_mpscq_push(&q->queue, (gpr_mpscq_node *)c); +static bool cq_event_queue_push(grpc_cq_event_queue* q, grpc_cq_completion* c) { + gpr_mpscq_push(&q->queue, (gpr_mpscq_node*)c); return gpr_atm_no_barrier_fetch_add(&q->num_queue_items, 1) == 0; } -static grpc_cq_completion *cq_event_queue_pop(grpc_cq_event_queue *q) { - grpc_cq_completion *c = NULL; +static grpc_cq_completion* cq_event_queue_pop(grpc_cq_event_queue* q) { + grpc_cq_completion* c = nullptr; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; if (gpr_spinlock_trylock(&q->queue_lock)) { GRPC_STATS_INC_CQ_EV_QUEUE_TRYLOCK_SUCCESSES(&exec_ctx); bool is_empty = false; - c = (grpc_cq_completion *)gpr_mpscq_pop_and_check_end(&q->queue, &is_empty); + c = (grpc_cq_completion*)gpr_mpscq_pop_and_check_end(&q->queue, &is_empty); gpr_spinlock_unlock(&q->queue_lock); - if (c == NULL && !is_empty) { + if (c == nullptr && !is_empty) { GRPC_STATS_INC_CQ_EV_QUEUE_TRANSIENT_POP_FAILURES(&exec_ctx); } } else { @@ -438,14 +433,14 @@ static grpc_cq_completion *cq_event_queue_pop(grpc_cq_event_queue *q) { /* Note: The counter is not incremented/decremented atomically with push/pop. * The count is only eventually consistent */ -static long cq_event_queue_num_items(grpc_cq_event_queue *q) { +static long cq_event_queue_num_items(grpc_cq_event_queue* q) { return (long)gpr_atm_no_barrier_load(&q->num_queue_items); } -grpc_completion_queue *grpc_completion_queue_create_internal( +grpc_completion_queue* grpc_completion_queue_create_internal( grpc_cq_completion_type completion_type, grpc_cq_polling_type polling_type) { - grpc_completion_queue *cq; + grpc_completion_queue* cq; GPR_TIMER_BEGIN("grpc_completion_queue_create_internal", 0); @@ -454,17 +449,17 @@ grpc_completion_queue *grpc_completion_queue_create_internal( "polling_type=%d)", 2, (completion_type, polling_type)); - const cq_vtable *vtable = &g_cq_vtable[completion_type]; - const cq_poller_vtable *poller_vtable = + const cq_vtable* vtable = &g_cq_vtable[completion_type]; + const cq_poller_vtable* poller_vtable = &g_poller_vtable_by_poller_type[polling_type]; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GRPC_STATS_INC_CQS_CREATED(&exec_ctx); grpc_exec_ctx_finish(&exec_ctx); - cq = (grpc_completion_queue *)gpr_zalloc(sizeof(grpc_completion_queue) + - vtable->data_size + - poller_vtable->size()); + cq = (grpc_completion_queue*)gpr_zalloc(sizeof(grpc_completion_queue) + + vtable->data_size + + poller_vtable->size()); cq->vtable = vtable; cq->poller_vtable = poller_vtable; @@ -483,8 +478,8 @@ grpc_completion_queue *grpc_completion_queue_create_internal( return cq; } -static void cq_init_next(void *ptr) { - cq_next_data *cqd = (cq_next_data *)ptr; +static void cq_init_next(void* ptr) { + cq_next_data* cqd = (cq_next_data*)ptr; /* Initial count is dropped by grpc_completion_queue_shutdown */ gpr_atm_no_barrier_store(&cqd->pending_events, 1); cqd->shutdown_called = false; @@ -492,14 +487,14 @@ static void cq_init_next(void *ptr) { cq_event_queue_init(&cqd->queue); } -static void cq_destroy_next(void *ptr) { - cq_next_data *cqd = (cq_next_data *)ptr; +static void cq_destroy_next(void* ptr) { + cq_next_data* cqd = (cq_next_data*)ptr; GPR_ASSERT(cq_event_queue_num_items(&cqd->queue) == 0); cq_event_queue_destroy(&cqd->queue); } -static void cq_init_pluck(void *ptr) { - cq_pluck_data *cqd = (cq_pluck_data *)ptr; +static void cq_init_pluck(void* ptr) { + cq_pluck_data* cqd = (cq_pluck_data*)ptr; /* Initial count is dropped by grpc_completion_queue_shutdown */ gpr_atm_no_barrier_store(&cqd->pending_events, 1); cqd->completed_tail = &cqd->completed_head; @@ -510,16 +505,16 @@ static void cq_init_pluck(void *ptr) { gpr_atm_no_barrier_store(&cqd->things_queued_ever, 0); } -static void cq_destroy_pluck(void *ptr) { - cq_pluck_data *cqd = (cq_pluck_data *)ptr; +static void cq_destroy_pluck(void* ptr) { + cq_pluck_data* cqd = (cq_pluck_data*)ptr; GPR_ASSERT(cqd->completed_head.next == (uintptr_t)&cqd->completed_head); } -grpc_cq_completion_type grpc_get_cq_completion_type(grpc_completion_queue *cq) { +grpc_cq_completion_type grpc_get_cq_completion_type(grpc_completion_queue* cq) { return cq->vtable->cq_completion_type; } -int grpc_get_cq_poll_num(grpc_completion_queue *cq) { +int grpc_get_cq_poll_num(grpc_completion_queue* cq) { int cur_num_polls; gpr_mu_lock(cq->mu); cur_num_polls = cq->num_polls; @@ -528,38 +523,38 @@ int grpc_get_cq_poll_num(grpc_completion_queue *cq) { } #ifndef NDEBUG -void grpc_cq_internal_ref(grpc_completion_queue *cq, const char *reason, - const char *file, int line) { - if (GRPC_TRACER_ON(grpc_trace_cq_refcount)) { +void grpc_cq_internal_ref(grpc_completion_queue* cq, const char* reason, + const char* file, int line) { + if (grpc_trace_cq_refcount.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&cq->owning_refs.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "CQ:%p ref %" PRIdPTR " -> %" PRIdPTR " %s", cq, val, val + 1, reason); } #else -void grpc_cq_internal_ref(grpc_completion_queue *cq) { +void grpc_cq_internal_ref(grpc_completion_queue* cq) { #endif gpr_ref(&cq->owning_refs); } -static void on_pollset_shutdown_done(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_completion_queue *cq = (grpc_completion_queue *)arg; +static void on_pollset_shutdown_done(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_completion_queue* cq = (grpc_completion_queue*)arg; GRPC_CQ_INTERNAL_UNREF(exec_ctx, cq, "pollset_destroy"); } #ifndef NDEBUG -void grpc_cq_internal_unref(grpc_exec_ctx *exec_ctx, grpc_completion_queue *cq, - const char *reason, const char *file, int line) { - if (GRPC_TRACER_ON(grpc_trace_cq_refcount)) { +void grpc_cq_internal_unref(grpc_exec_ctx* exec_ctx, grpc_completion_queue* cq, + const char* reason, const char* file, int line) { + if (grpc_trace_cq_refcount.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&cq->owning_refs.count); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "CQ:%p unref %" PRIdPTR " -> %" PRIdPTR " %s", cq, val, val - 1, reason); } #else -void grpc_cq_internal_unref(grpc_exec_ctx *exec_ctx, - grpc_completion_queue *cq) { +void grpc_cq_internal_unref(grpc_exec_ctx* exec_ctx, + grpc_completion_queue* cq) { #endif if (gpr_unref(&cq->owning_refs)) { cq->vtable->destroy(DATA_FROM_CQ(cq)); @@ -572,7 +567,7 @@ void grpc_cq_internal_unref(grpc_exec_ctx *exec_ctx, } #ifndef NDEBUG -static void cq_check_tag(grpc_completion_queue *cq, void *tag, bool lock_cq) { +static void cq_check_tag(grpc_completion_queue* cq, void* tag, bool lock_cq) { int found = 0; if (lock_cq) { gpr_mu_lock(cq->mu); @@ -581,7 +576,7 @@ static void cq_check_tag(grpc_completion_queue *cq, void *tag, bool lock_cq) { for (int i = 0; i < (int)cq->outstanding_tag_count; i++) { if (cq->outstanding_tags[i] == tag) { cq->outstanding_tag_count--; - GPR_SWAP(void *, cq->outstanding_tags[i], + GPR_SWAP(void*, cq->outstanding_tags[i], cq->outstanding_tags[cq->outstanding_tag_count]); found = 1; break; @@ -595,12 +590,12 @@ static void cq_check_tag(grpc_completion_queue *cq, void *tag, bool lock_cq) { GPR_ASSERT(found); } #else -static void cq_check_tag(grpc_completion_queue *cq, void *tag, bool lock_cq) {} +static void cq_check_tag(grpc_completion_queue* cq, void* tag, bool lock_cq) {} #endif /* Atomically increments a counter only if the counter is not zero. Returns * true if the increment was successful; false if the counter is zero */ -static bool atm_inc_if_nonzero(gpr_atm *counter) { +static bool atm_inc_if_nonzero(gpr_atm* counter) { while (true) { gpr_atm count = gpr_atm_acq_load(counter); /* If zero, we are done. If not, we must to a CAS (instead of an atomic @@ -616,22 +611,22 @@ static bool atm_inc_if_nonzero(gpr_atm *counter) { return true; } -static bool cq_begin_op_for_next(grpc_completion_queue *cq, void *tag) { - cq_next_data *cqd = (cq_next_data *)DATA_FROM_CQ(cq); +static bool cq_begin_op_for_next(grpc_completion_queue* cq, void* tag) { + cq_next_data* cqd = (cq_next_data*)DATA_FROM_CQ(cq); return atm_inc_if_nonzero(&cqd->pending_events); } -static bool cq_begin_op_for_pluck(grpc_completion_queue *cq, void *tag) { - cq_pluck_data *cqd = (cq_pluck_data *)DATA_FROM_CQ(cq); +static bool cq_begin_op_for_pluck(grpc_completion_queue* cq, void* tag) { + cq_pluck_data* cqd = (cq_pluck_data*)DATA_FROM_CQ(cq); return atm_inc_if_nonzero(&cqd->pending_events); } -bool grpc_cq_begin_op(grpc_completion_queue *cq, void *tag) { +bool grpc_cq_begin_op(grpc_completion_queue* cq, void* tag) { #ifndef NDEBUG gpr_mu_lock(cq->mu); if (cq->outstanding_tag_count == cq->outstanding_tag_capacity) { cq->outstanding_tag_capacity = GPR_MAX(4, 2 * cq->outstanding_tag_capacity); - cq->outstanding_tags = (void **)gpr_realloc( + cq->outstanding_tags = (void**)gpr_realloc( cq->outstanding_tags, sizeof(*cq->outstanding_tags) * cq->outstanding_tag_capacity); } @@ -644,29 +639,27 @@ bool grpc_cq_begin_op(grpc_completion_queue *cq, void *tag) { /* Queue a GRPC_OP_COMPLETED operation to a completion queue (with a * completion * type of GRPC_CQ_NEXT) */ -static void cq_end_op_for_next(grpc_exec_ctx *exec_ctx, - grpc_completion_queue *cq, void *tag, - grpc_error *error, - void (*done)(grpc_exec_ctx *exec_ctx, - void *done_arg, - grpc_cq_completion *storage), - void *done_arg, grpc_cq_completion *storage) { +static void cq_end_op_for_next(grpc_exec_ctx* exec_ctx, + grpc_completion_queue* cq, void* tag, + grpc_error* error, + void (*done)(grpc_exec_ctx* exec_ctx, + void* done_arg, + grpc_cq_completion* storage), + void* done_arg, grpc_cq_completion* storage) { GPR_TIMER_BEGIN("cq_end_op_for_next", 0); - if (GRPC_TRACER_ON(grpc_api_trace) || - (GRPC_TRACER_ON(grpc_trace_operation_failures) && - error != GRPC_ERROR_NONE)) { - const char *errmsg = grpc_error_string(error); + if (grpc_api_trace.enabled() || + (grpc_trace_operation_failures.enabled() && error != GRPC_ERROR_NONE)) { + const char* errmsg = grpc_error_string(error); GRPC_API_TRACE( "cq_end_op_for_next(exec_ctx=%p, cq=%p, tag=%p, error=%s, " "done=%p, done_arg=%p, storage=%p)", 7, (exec_ctx, cq, tag, errmsg, done, done_arg, storage)); - if (GRPC_TRACER_ON(grpc_trace_operation_failures) && - error != GRPC_ERROR_NONE) { + if (grpc_trace_operation_failures.enabled() && error != GRPC_ERROR_NONE) { gpr_log(GPR_ERROR, "Operation failed: tag=%p, error=%s", tag, errmsg); } } - cq_next_data *cqd = (cq_next_data *)DATA_FROM_CQ(cq); + cq_next_data* cqd = (cq_next_data*)DATA_FROM_CQ(cq); int is_success = (error == GRPC_ERROR_NONE); storage->tag = tag; @@ -676,8 +669,8 @@ static void cq_end_op_for_next(grpc_exec_ctx *exec_ctx, cq_check_tag(cq, tag, true); /* Used in debug builds only */ - if ((grpc_completion_queue *)gpr_tls_get(&g_cached_cq) == cq && - (grpc_cq_completion *)gpr_tls_get(&g_cached_event) == nullptr) { + if ((grpc_completion_queue*)gpr_tls_get(&g_cached_cq) == cq && + (grpc_cq_completion*)gpr_tls_get(&g_cached_event) == nullptr) { gpr_tls_set(&g_cached_event, (intptr_t)storage); } else { /* Add the completion to the queue */ @@ -695,12 +688,12 @@ static void cq_end_op_for_next(grpc_exec_ctx *exec_ctx, /* Only kick if this is the first item queued */ if (is_first) { gpr_mu_lock(cq->mu); - grpc_error *kick_error = - cq->poller_vtable->kick(exec_ctx, POLLSET_FROM_CQ(cq), NULL); + grpc_error* kick_error = + cq->poller_vtable->kick(exec_ctx, POLLSET_FROM_CQ(cq), nullptr); gpr_mu_unlock(cq->mu); if (kick_error != GRPC_ERROR_NONE) { - const char *msg = grpc_error_string(kick_error); + const char* msg = grpc_error_string(kick_error); gpr_log(GPR_ERROR, "Kick failed: %s", msg); GRPC_ERROR_UNREF(kick_error); } @@ -730,28 +723,26 @@ static void cq_end_op_for_next(grpc_exec_ctx *exec_ctx, /* Queue a GRPC_OP_COMPLETED operation to a completion queue (with a * completion * type of GRPC_CQ_PLUCK) */ -static void cq_end_op_for_pluck(grpc_exec_ctx *exec_ctx, - grpc_completion_queue *cq, void *tag, - grpc_error *error, - void (*done)(grpc_exec_ctx *exec_ctx, - void *done_arg, - grpc_cq_completion *storage), - void *done_arg, grpc_cq_completion *storage) { - cq_pluck_data *cqd = (cq_pluck_data *)DATA_FROM_CQ(cq); +static void cq_end_op_for_pluck(grpc_exec_ctx* exec_ctx, + grpc_completion_queue* cq, void* tag, + grpc_error* error, + void (*done)(grpc_exec_ctx* exec_ctx, + void* done_arg, + grpc_cq_completion* storage), + void* done_arg, grpc_cq_completion* storage) { + cq_pluck_data* cqd = (cq_pluck_data*)DATA_FROM_CQ(cq); int is_success = (error == GRPC_ERROR_NONE); GPR_TIMER_BEGIN("cq_end_op_for_pluck", 0); - if (GRPC_TRACER_ON(grpc_api_trace) || - (GRPC_TRACER_ON(grpc_trace_operation_failures) && - error != GRPC_ERROR_NONE)) { - const char *errmsg = grpc_error_string(error); + if (grpc_api_trace.enabled() || + (grpc_trace_operation_failures.enabled() && error != GRPC_ERROR_NONE)) { + const char* errmsg = grpc_error_string(error); GRPC_API_TRACE( "cq_end_op_for_pluck(exec_ctx=%p, cq=%p, tag=%p, error=%s, " "done=%p, done_arg=%p, storage=%p)", 7, (exec_ctx, cq, tag, errmsg, done, done_arg, storage)); - if (GRPC_TRACER_ON(grpc_trace_operation_failures) && - error != GRPC_ERROR_NONE) { + if (grpc_trace_operation_failures.enabled() && error != GRPC_ERROR_NONE) { gpr_log(GPR_ERROR, "Operation failed: tag=%p, error=%s", tag, errmsg); } } @@ -774,7 +765,7 @@ static void cq_end_op_for_pluck(grpc_exec_ctx *exec_ctx, cq_finish_shutdown_pluck(exec_ctx, cq); gpr_mu_unlock(cq->mu); } else { - grpc_pollset_worker *pluck_worker = NULL; + grpc_pollset_worker* pluck_worker = nullptr; for (int i = 0; i < cqd->num_pluckers; i++) { if (cqd->pluckers[i].tag == tag) { pluck_worker = *cqd->pluckers[i].worker; @@ -782,13 +773,13 @@ static void cq_end_op_for_pluck(grpc_exec_ctx *exec_ctx, } } - grpc_error *kick_error = + grpc_error* kick_error = cq->poller_vtable->kick(exec_ctx, POLLSET_FROM_CQ(cq), pluck_worker); gpr_mu_unlock(cq->mu); if (kick_error != GRPC_ERROR_NONE) { - const char *msg = grpc_error_string(kick_error); + const char* msg = grpc_error_string(kick_error); gpr_log(GPR_ERROR, "Kick failed: %s", msg); GRPC_ERROR_UNREF(kick_error); @@ -800,28 +791,28 @@ static void cq_end_op_for_pluck(grpc_exec_ctx *exec_ctx, GRPC_ERROR_UNREF(error); } -void grpc_cq_end_op(grpc_exec_ctx *exec_ctx, grpc_completion_queue *cq, - void *tag, grpc_error *error, - void (*done)(grpc_exec_ctx *exec_ctx, void *done_arg, - grpc_cq_completion *storage), - void *done_arg, grpc_cq_completion *storage) { +void grpc_cq_end_op(grpc_exec_ctx* exec_ctx, grpc_completion_queue* cq, + void* tag, grpc_error* error, + void (*done)(grpc_exec_ctx* exec_ctx, void* done_arg, + grpc_cq_completion* storage), + void* done_arg, grpc_cq_completion* storage) { cq->vtable->end_op(exec_ctx, cq, tag, error, done, done_arg, storage); } typedef struct { gpr_atm last_seen_things_queued_ever; - grpc_completion_queue *cq; + grpc_completion_queue* cq; grpc_millis deadline; - grpc_cq_completion *stolen_completion; - void *tag; /* for pluck */ + grpc_cq_completion* stolen_completion; + void* tag; /* for pluck */ bool first_loop; } cq_is_finished_arg; -static bool cq_is_next_finished(grpc_exec_ctx *exec_ctx, void *arg) { - cq_is_finished_arg *a = (cq_is_finished_arg *)arg; - grpc_completion_queue *cq = a->cq; - cq_next_data *cqd = (cq_next_data *)DATA_FROM_CQ(cq); - GPR_ASSERT(a->stolen_completion == NULL); +static bool cq_is_next_finished(grpc_exec_ctx* exec_ctx, void* arg) { + cq_is_finished_arg* a = (cq_is_finished_arg*)arg; + grpc_completion_queue* cq = a->cq; + cq_next_data* cqd = (cq_next_data*)DATA_FROM_CQ(cq); + GPR_ASSERT(a->stolen_completion == nullptr); gpr_atm current_last_seen_things_queued_ever = gpr_atm_no_barrier_load(&cqd->things_queued_ever); @@ -836,7 +827,7 @@ static bool cq_is_next_finished(grpc_exec_ctx *exec_ctx, void *arg) { * is ok and doesn't affect correctness. Might effect the tail latencies a * bit) */ a->stolen_completion = cq_event_queue_pop(&cqd->queue); - if (a->stolen_completion != NULL) { + if (a->stolen_completion != nullptr) { return true; } } @@ -844,32 +835,32 @@ static bool cq_is_next_finished(grpc_exec_ctx *exec_ctx, void *arg) { } #ifndef NDEBUG -static void dump_pending_tags(grpc_completion_queue *cq) { - if (!GRPC_TRACER_ON(grpc_trace_pending_tags)) return; +static void dump_pending_tags(grpc_completion_queue* cq) { + if (!grpc_trace_pending_tags.enabled()) return; gpr_strvec v; gpr_strvec_init(&v); gpr_strvec_add(&v, gpr_strdup("PENDING TAGS:")); gpr_mu_lock(cq->mu); for (size_t i = 0; i < cq->outstanding_tag_count; i++) { - char *s; + char* s; gpr_asprintf(&s, " %p", cq->outstanding_tags[i]); gpr_strvec_add(&v, s); } gpr_mu_unlock(cq->mu); - char *out = gpr_strvec_flatten(&v, NULL); + char* out = gpr_strvec_flatten(&v, nullptr); gpr_strvec_destroy(&v); gpr_log(GPR_DEBUG, "%s", out); gpr_free(out); } #else -static void dump_pending_tags(grpc_completion_queue *cq) {} +static void dump_pending_tags(grpc_completion_queue* cq) {} #endif -static grpc_event cq_next(grpc_completion_queue *cq, gpr_timespec deadline, - void *reserved) { +static grpc_event cq_next(grpc_completion_queue* cq, gpr_timespec deadline, + void* reserved) { grpc_event ret; - cq_next_data *cqd = (cq_next_data *)DATA_FROM_CQ(cq); + cq_next_data* cqd = (cq_next_data*)DATA_FROM_CQ(cq); GPR_TIMER_BEGIN("grpc_completion_queue_next", 0); @@ -879,8 +870,9 @@ static grpc_event cq_next(grpc_completion_queue *cq, gpr_timespec deadline, "deadline=gpr_timespec { tv_sec: %" PRId64 ", tv_nsec: %d, clock_type: %d }, " "reserved=%p)", - 5, (cq, deadline.tv_sec, deadline.tv_nsec, (int)deadline.clock_type, - reserved)); + 5, + (cq, deadline.tv_sec, deadline.tv_nsec, (int)deadline.clock_type, + reserved)); GPR_ASSERT(!reserved); dump_pending_tags(cq); @@ -892,17 +884,17 @@ static grpc_event cq_next(grpc_completion_queue *cq, gpr_timespec deadline, gpr_atm_no_barrier_load(&cqd->things_queued_ever), cq, deadline_millis, - NULL, - NULL, + nullptr, + nullptr, true}; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INITIALIZER(0, cq_is_next_finished, &is_finished_arg); for (;;) { grpc_millis iteration_deadline = deadline_millis; - if (is_finished_arg.stolen_completion != NULL) { - grpc_cq_completion *c = is_finished_arg.stolen_completion; - is_finished_arg.stolen_completion = NULL; + if (is_finished_arg.stolen_completion != nullptr) { + grpc_cq_completion* c = is_finished_arg.stolen_completion; + is_finished_arg.stolen_completion = nullptr; ret.type = GRPC_OP_COMPLETE; ret.success = c->next & 1u; ret.tag = c->tag; @@ -910,9 +902,9 @@ static grpc_event cq_next(grpc_completion_queue *cq, gpr_timespec deadline, break; } - grpc_cq_completion *c = cq_event_queue_pop(&cqd->queue); + grpc_cq_completion* c = cq_event_queue_pop(&cqd->queue); - if (c != NULL) { + if (c != nullptr) { ret.type = GRPC_OP_COMPLETE; ret.success = c->next & 1u; ret.tag = c->tag; @@ -957,12 +949,12 @@ static grpc_event cq_next(grpc_completion_queue *cq, gpr_timespec deadline, /* The main polling work happens in grpc_pollset_work */ gpr_mu_lock(cq->mu); cq->num_polls++; - grpc_error *err = cq->poller_vtable->work(&exec_ctx, POLLSET_FROM_CQ(cq), - NULL, iteration_deadline); + grpc_error* err = cq->poller_vtable->work(&exec_ctx, POLLSET_FROM_CQ(cq), + nullptr, iteration_deadline); gpr_mu_unlock(cq->mu); if (err != GRPC_ERROR_NONE) { - const char *msg = grpc_error_string(err); + const char* msg = grpc_error_string(err); gpr_log(GPR_ERROR, "Completion queue next failed: %s", msg); GRPC_ERROR_UNREF(err); @@ -977,14 +969,14 @@ static grpc_event cq_next(grpc_completion_queue *cq, gpr_timespec deadline, if (cq_event_queue_num_items(&cqd->queue) > 0 && gpr_atm_acq_load(&cqd->pending_events) > 0) { gpr_mu_lock(cq->mu); - cq->poller_vtable->kick(&exec_ctx, POLLSET_FROM_CQ(cq), NULL); + cq->poller_vtable->kick(&exec_ctx, POLLSET_FROM_CQ(cq), nullptr); gpr_mu_unlock(cq->mu); } GRPC_SURFACE_TRACE_RETURNED_EVENT(cq, &ret); GRPC_CQ_INTERNAL_UNREF(&exec_ctx, cq, "next"); grpc_exec_ctx_finish(&exec_ctx); - GPR_ASSERT(is_finished_arg.stolen_completion == NULL); + GPR_ASSERT(is_finished_arg.stolen_completion == nullptr); GPR_TIMER_END("grpc_completion_queue_next", 0); @@ -997,9 +989,9 @@ static grpc_event cq_next(grpc_completion_queue *cq, gpr_timespec deadline, - Must be called only once in completion queue's lifetime - grpc_completion_queue_shutdown() MUST have been called before calling this function */ -static void cq_finish_shutdown_next(grpc_exec_ctx *exec_ctx, - grpc_completion_queue *cq) { - cq_next_data *cqd = (cq_next_data *)DATA_FROM_CQ(cq); +static void cq_finish_shutdown_next(grpc_exec_ctx* exec_ctx, + grpc_completion_queue* cq) { + cq_next_data* cqd = (cq_next_data*)DATA_FROM_CQ(cq); GPR_ASSERT(cqd->shutdown_called); GPR_ASSERT(gpr_atm_no_barrier_load(&cqd->pending_events) == 0); @@ -1008,9 +1000,9 @@ static void cq_finish_shutdown_next(grpc_exec_ctx *exec_ctx, &cq->pollset_shutdown_done); } -static void cq_shutdown_next(grpc_exec_ctx *exec_ctx, - grpc_completion_queue *cq) { - cq_next_data *cqd = (cq_next_data *)DATA_FROM_CQ(cq); +static void cq_shutdown_next(grpc_exec_ctx* exec_ctx, + grpc_completion_queue* cq) { + cq_next_data* cqd = (cq_next_data*)DATA_FROM_CQ(cq); /* Need an extra ref for cq here because: * We call cq_finish_shutdown_next() below, that would call pollset shutdown. @@ -1036,14 +1028,14 @@ static void cq_shutdown_next(grpc_exec_ctx *exec_ctx, GRPC_CQ_INTERNAL_UNREF(exec_ctx, cq, "shutting_down"); } -grpc_event grpc_completion_queue_next(grpc_completion_queue *cq, - gpr_timespec deadline, void *reserved) { +grpc_event grpc_completion_queue_next(grpc_completion_queue* cq, + gpr_timespec deadline, void* reserved) { return cq->vtable->next(cq, deadline, reserved); } -static int add_plucker(grpc_completion_queue *cq, void *tag, - grpc_pollset_worker **worker) { - cq_pluck_data *cqd = (cq_pluck_data *)DATA_FROM_CQ(cq); +static int add_plucker(grpc_completion_queue* cq, void* tag, + grpc_pollset_worker** worker) { + cq_pluck_data* cqd = (cq_pluck_data*)DATA_FROM_CQ(cq); if (cqd->num_pluckers == GRPC_MAX_COMPLETION_QUEUE_PLUCKERS) { return 0; } @@ -1053,9 +1045,9 @@ static int add_plucker(grpc_completion_queue *cq, void *tag, return 1; } -static void del_plucker(grpc_completion_queue *cq, void *tag, - grpc_pollset_worker **worker) { - cq_pluck_data *cqd = (cq_pluck_data *)DATA_FROM_CQ(cq); +static void del_plucker(grpc_completion_queue* cq, void* tag, + grpc_pollset_worker** worker) { + cq_pluck_data* cqd = (cq_pluck_data*)DATA_FROM_CQ(cq); for (int i = 0; i < cqd->num_pluckers; i++) { if (cqd->pluckers[i].tag == tag && cqd->pluckers[i].worker == worker) { cqd->num_pluckers--; @@ -1066,21 +1058,21 @@ static void del_plucker(grpc_completion_queue *cq, void *tag, GPR_UNREACHABLE_CODE(return ); } -static bool cq_is_pluck_finished(grpc_exec_ctx *exec_ctx, void *arg) { - cq_is_finished_arg *a = (cq_is_finished_arg *)arg; - grpc_completion_queue *cq = a->cq; - cq_pluck_data *cqd = (cq_pluck_data *)DATA_FROM_CQ(cq); +static bool cq_is_pluck_finished(grpc_exec_ctx* exec_ctx, void* arg) { + cq_is_finished_arg* a = (cq_is_finished_arg*)arg; + grpc_completion_queue* cq = a->cq; + cq_pluck_data* cqd = (cq_pluck_data*)DATA_FROM_CQ(cq); - GPR_ASSERT(a->stolen_completion == NULL); + GPR_ASSERT(a->stolen_completion == nullptr); gpr_atm current_last_seen_things_queued_ever = gpr_atm_no_barrier_load(&cqd->things_queued_ever); if (current_last_seen_things_queued_ever != a->last_seen_things_queued_ever) { gpr_mu_lock(cq->mu); a->last_seen_things_queued_ever = gpr_atm_no_barrier_load(&cqd->things_queued_ever); - grpc_cq_completion *c; - grpc_cq_completion *prev = &cqd->completed_head; - while ((c = (grpc_cq_completion *)(prev->next & ~(uintptr_t)1)) != + grpc_cq_completion* c; + grpc_cq_completion* prev = &cqd->completed_head; + while ((c = (grpc_cq_completion*)(prev->next & ~(uintptr_t)1)) != &cqd->completed_head) { if (c->tag == a->tag) { prev->next = (prev->next & (uintptr_t)1) | (c->next & ~(uintptr_t)1); @@ -1098,25 +1090,26 @@ static bool cq_is_pluck_finished(grpc_exec_ctx *exec_ctx, void *arg) { return !a->first_loop && a->deadline < grpc_exec_ctx_now(exec_ctx); } -static grpc_event cq_pluck(grpc_completion_queue *cq, void *tag, - gpr_timespec deadline, void *reserved) { +static grpc_event cq_pluck(grpc_completion_queue* cq, void* tag, + gpr_timespec deadline, void* reserved) { grpc_event ret; - grpc_cq_completion *c; - grpc_cq_completion *prev; - grpc_pollset_worker *worker = NULL; - cq_pluck_data *cqd = (cq_pluck_data *)DATA_FROM_CQ(cq); + grpc_cq_completion* c; + grpc_cq_completion* prev; + grpc_pollset_worker* worker = nullptr; + cq_pluck_data* cqd = (cq_pluck_data*)DATA_FROM_CQ(cq); GPR_TIMER_BEGIN("grpc_completion_queue_pluck", 0); - if (GRPC_TRACER_ON(grpc_cq_pluck_trace)) { + if (grpc_cq_pluck_trace.enabled()) { GRPC_API_TRACE( "grpc_completion_queue_pluck(" "cq=%p, tag=%p, " "deadline=gpr_timespec { tv_sec: %" PRId64 ", tv_nsec: %d, clock_type: %d }, " "reserved=%p)", - 6, (cq, tag, deadline.tv_sec, deadline.tv_nsec, - (int)deadline.clock_type, reserved)); + 6, + (cq, tag, deadline.tv_sec, deadline.tv_nsec, (int)deadline.clock_type, + reserved)); } GPR_ASSERT(!reserved); @@ -1129,16 +1122,16 @@ static grpc_event cq_pluck(grpc_completion_queue *cq, void *tag, gpr_atm_no_barrier_load(&cqd->things_queued_ever), cq, deadline_millis, - NULL, + nullptr, tag, true}; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INITIALIZER(0, cq_is_pluck_finished, &is_finished_arg); for (;;) { - if (is_finished_arg.stolen_completion != NULL) { + if (is_finished_arg.stolen_completion != nullptr) { gpr_mu_unlock(cq->mu); c = is_finished_arg.stolen_completion; - is_finished_arg.stolen_completion = NULL; + is_finished_arg.stolen_completion = nullptr; ret.type = GRPC_OP_COMPLETE; ret.success = c->next & 1u; ret.tag = c->tag; @@ -1146,7 +1139,7 @@ static grpc_event cq_pluck(grpc_completion_queue *cq, void *tag, break; } prev = &cqd->completed_head; - while ((c = (grpc_cq_completion *)(prev->next & ~(uintptr_t)1)) != + while ((c = (grpc_cq_completion*)(prev->next & ~(uintptr_t)1)) != &cqd->completed_head) { if (c->tag == tag) { prev->next = (prev->next & (uintptr_t)1) | (c->next & ~(uintptr_t)1); @@ -1190,12 +1183,12 @@ static grpc_event cq_pluck(grpc_completion_queue *cq, void *tag, break; } cq->num_polls++; - grpc_error *err = cq->poller_vtable->work(&exec_ctx, POLLSET_FROM_CQ(cq), + grpc_error* err = cq->poller_vtable->work(&exec_ctx, POLLSET_FROM_CQ(cq), &worker, deadline_millis); if (err != GRPC_ERROR_NONE) { del_plucker(cq, tag, &worker); gpr_mu_unlock(cq->mu); - const char *msg = grpc_error_string(err); + const char* msg = grpc_error_string(err); gpr_log(GPR_ERROR, "Completion queue pluck failed: %s", msg); GRPC_ERROR_UNREF(err); @@ -1211,21 +1204,21 @@ done: GRPC_SURFACE_TRACE_RETURNED_EVENT(cq, &ret); GRPC_CQ_INTERNAL_UNREF(&exec_ctx, cq, "pluck"); grpc_exec_ctx_finish(&exec_ctx); - GPR_ASSERT(is_finished_arg.stolen_completion == NULL); + GPR_ASSERT(is_finished_arg.stolen_completion == nullptr); GPR_TIMER_END("grpc_completion_queue_pluck", 0); return ret; } -grpc_event grpc_completion_queue_pluck(grpc_completion_queue *cq, void *tag, - gpr_timespec deadline, void *reserved) { +grpc_event grpc_completion_queue_pluck(grpc_completion_queue* cq, void* tag, + gpr_timespec deadline, void* reserved) { return cq->vtable->pluck(cq, tag, deadline, reserved); } -static void cq_finish_shutdown_pluck(grpc_exec_ctx *exec_ctx, - grpc_completion_queue *cq) { - cq_pluck_data *cqd = (cq_pluck_data *)DATA_FROM_CQ(cq); +static void cq_finish_shutdown_pluck(grpc_exec_ctx* exec_ctx, + grpc_completion_queue* cq) { + cq_pluck_data* cqd = (cq_pluck_data*)DATA_FROM_CQ(cq); GPR_ASSERT(cqd->shutdown_called); GPR_ASSERT(!gpr_atm_no_barrier_load(&cqd->shutdown)); @@ -1237,9 +1230,9 @@ static void cq_finish_shutdown_pluck(grpc_exec_ctx *exec_ctx, /* NOTE: This function is almost exactly identical to cq_shutdown_next() but * merging them is a bit tricky and probably not worth it */ -static void cq_shutdown_pluck(grpc_exec_ctx *exec_ctx, - grpc_completion_queue *cq) { - cq_pluck_data *cqd = (cq_pluck_data *)DATA_FROM_CQ(cq); +static void cq_shutdown_pluck(grpc_exec_ctx* exec_ctx, + grpc_completion_queue* cq) { + cq_pluck_data* cqd = (cq_pluck_data*)DATA_FROM_CQ(cq); /* Need an extra ref for cq here because: * We call cq_finish_shutdown_pluck() below, that would call pollset shutdown. @@ -1264,7 +1257,7 @@ static void cq_shutdown_pluck(grpc_exec_ctx *exec_ctx, /* Shutdown simply drops a ref that we reserved at creation time; if we drop to zero here, then enter shutdown mode and wake up any waiters */ -void grpc_completion_queue_shutdown(grpc_completion_queue *cq) { +void grpc_completion_queue_shutdown(grpc_completion_queue* cq) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GPR_TIMER_BEGIN("grpc_completion_queue_shutdown", 0); GRPC_API_TRACE("grpc_completion_queue_shutdown(cq=%p)", 1, (cq)); @@ -1273,7 +1266,7 @@ void grpc_completion_queue_shutdown(grpc_completion_queue *cq) { GPR_TIMER_END("grpc_completion_queue_shutdown", 0); } -void grpc_completion_queue_destroy(grpc_completion_queue *cq) { +void grpc_completion_queue_destroy(grpc_completion_queue* cq) { GRPC_API_TRACE("grpc_completion_queue_destroy(cq=%p)", 1, (cq)); GPR_TIMER_BEGIN("grpc_completion_queue_destroy", 0); grpc_completion_queue_shutdown(cq); @@ -1284,10 +1277,10 @@ void grpc_completion_queue_destroy(grpc_completion_queue *cq) { GPR_TIMER_END("grpc_completion_queue_destroy", 0); } -grpc_pollset *grpc_cq_pollset(grpc_completion_queue *cq) { - return cq->poller_vtable->can_get_pollset ? POLLSET_FROM_CQ(cq) : NULL; +grpc_pollset* grpc_cq_pollset(grpc_completion_queue* cq) { + return cq->poller_vtable->can_get_pollset ? POLLSET_FROM_CQ(cq) : nullptr; } -bool grpc_cq_can_listen(grpc_completion_queue *cq) { +bool grpc_cq_can_listen(grpc_completion_queue* cq) { return cq->poller_vtable->can_listen; } diff --git a/src/core/lib/surface/completion_queue.h b/src/core/lib/surface/completion_queue.h index c02bc5da071..13d3e5807df 100644 --- a/src/core/lib/surface/completion_queue.h +++ b/src/core/lib/surface/completion_queue.h @@ -27,45 +27,38 @@ /* These trace flags default to 1. The corresponding lines are only traced if grpc_api_trace is also truthy */ -extern grpc_tracer_flag grpc_cq_pluck_trace; -extern grpc_tracer_flag grpc_cq_event_timeout_trace; -extern grpc_tracer_flag grpc_trace_operation_failures; - -#ifndef NDEBUG -extern grpc_tracer_flag grpc_trace_pending_tags; -extern grpc_tracer_flag grpc_trace_cq_refcount; -#endif - -#ifdef __cplusplus -extern "C" { -#endif +extern grpc_core::TraceFlag grpc_cq_pluck_trace; +extern grpc_core::TraceFlag grpc_cq_event_timeout_trace; +extern grpc_core::TraceFlag grpc_trace_operation_failures; +extern grpc_core::DebugOnlyTraceFlag grpc_trace_pending_tags; +extern grpc_core::DebugOnlyTraceFlag grpc_trace_cq_refcount; typedef struct grpc_cq_completion { gpr_mpscq_node node; /** user supplied tag */ - void *tag; + void* tag; /** done callback - called when this queue element is no longer needed by the completion queue */ - void (*done)(grpc_exec_ctx *exec_ctx, void *done_arg, - struct grpc_cq_completion *c); - void *done_arg; + void (*done)(grpc_exec_ctx* exec_ctx, void* done_arg, + struct grpc_cq_completion* c); + void* done_arg; /** next pointer; low bit is used to indicate success or not */ uintptr_t next; } grpc_cq_completion; #ifndef NDEBUG -void grpc_cq_internal_ref(grpc_completion_queue *cc, const char *reason, - const char *file, int line); -void grpc_cq_internal_unref(grpc_exec_ctx *exec_ctx, grpc_completion_queue *cc, - const char *reason, const char *file, int line); +void grpc_cq_internal_ref(grpc_completion_queue* cc, const char* reason, + const char* file, int line); +void grpc_cq_internal_unref(grpc_exec_ctx* exec_ctx, grpc_completion_queue* cc, + const char* reason, const char* file, int line); #define GRPC_CQ_INTERNAL_REF(cc, reason) \ grpc_cq_internal_ref(cc, reason, __FILE__, __LINE__) #define GRPC_CQ_INTERNAL_UNREF(ec, cc, reason) \ grpc_cq_internal_unref(ec, cc, reason, __FILE__, __LINE__) #else -void grpc_cq_internal_ref(grpc_completion_queue *cc); -void grpc_cq_internal_unref(grpc_exec_ctx *exec_ctx, grpc_completion_queue *cc); +void grpc_cq_internal_ref(grpc_completion_queue* cc); +void grpc_cq_internal_unref(grpc_exec_ctx* exec_ctx, grpc_completion_queue* cc); #define GRPC_CQ_INTERNAL_REF(cc, reason) grpc_cq_internal_ref(cc) #define GRPC_CQ_INTERNAL_UNREF(ec, cc, reason) grpc_cq_internal_unref(ec, cc) #endif @@ -77,29 +70,25 @@ void grpc_cq_global_init(); shutdown until a corrensponding grpc_cq_end_* call is made. \a tag is currently used only in debug builds. Return true on success, and false if completion_queue has been shutdown. */ -bool grpc_cq_begin_op(grpc_completion_queue *cc, void *tag); +bool grpc_cq_begin_op(grpc_completion_queue* cc, void* tag); /* Queue a GRPC_OP_COMPLETED operation; tag must correspond to the tag passed to grpc_cq_begin_op */ -void grpc_cq_end_op(grpc_exec_ctx *exec_ctx, grpc_completion_queue *cc, - void *tag, grpc_error *error, - void (*done)(grpc_exec_ctx *exec_ctx, void *done_arg, - grpc_cq_completion *storage), - void *done_arg, grpc_cq_completion *storage); +void grpc_cq_end_op(grpc_exec_ctx* exec_ctx, grpc_completion_queue* cc, + void* tag, grpc_error* error, + void (*done)(grpc_exec_ctx* exec_ctx, void* done_arg, + grpc_cq_completion* storage), + void* done_arg, grpc_cq_completion* storage); -grpc_pollset *grpc_cq_pollset(grpc_completion_queue *cc); +grpc_pollset* grpc_cq_pollset(grpc_completion_queue* cc); -bool grpc_cq_can_listen(grpc_completion_queue *cc); +bool grpc_cq_can_listen(grpc_completion_queue* cc); -grpc_cq_completion_type grpc_get_cq_completion_type(grpc_completion_queue *cc); +grpc_cq_completion_type grpc_get_cq_completion_type(grpc_completion_queue* cc); -int grpc_get_cq_poll_num(grpc_completion_queue *cc); +int grpc_get_cq_poll_num(grpc_completion_queue* cc); -grpc_completion_queue *grpc_completion_queue_create_internal( +grpc_completion_queue* grpc_completion_queue_create_internal( grpc_cq_completion_type completion_type, grpc_cq_polling_type polling_type); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SURFACE_COMPLETION_QUEUE_H */ diff --git a/src/core/lib/surface/completion_queue_factory.cc b/src/core/lib/surface/completion_queue_factory.cc index aeecff53063..d0bb065c8f6 100644 --- a/src/core/lib/surface/completion_queue_factory.cc +++ b/src/core/lib/surface/completion_queue_factory.cc @@ -35,7 +35,7 @@ static grpc_completion_queue* default_create( static grpc_completion_queue_factory_vtable default_vtable = {default_create}; static const grpc_completion_queue_factory g_default_cq_factory = { - "Default Factory", NULL, &default_vtable}; + "Default Factory", nullptr, &default_vtable}; /* * == Completion queue factory APIs diff --git a/src/core/lib/surface/completion_queue_factory.h b/src/core/lib/surface/completion_queue_factory.h index af8f3d60c38..89be8f8216a 100644 --- a/src/core/lib/surface/completion_queue_factory.h +++ b/src/core/lib/surface/completion_queue_factory.h @@ -22,10 +22,6 @@ #include #include "src/core/lib/surface/completion_queue.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_completion_queue_factory_vtable { grpc_completion_queue* (*create)(const grpc_completion_queue_factory*, const grpc_completion_queue_attributes*); @@ -37,8 +33,4 @@ struct grpc_completion_queue_factory { grpc_completion_queue_factory_vtable* vtable; }; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SURFACE_COMPLETION_QUEUE_FACTORY_H */ diff --git a/src/core/lib/surface/event_string.cc b/src/core/lib/surface/event_string.cc index f236272e2ad..5168edc9b50 100644 --- a/src/core/lib/surface/event_string.cc +++ b/src/core/lib/surface/event_string.cc @@ -24,25 +24,25 @@ #include #include "src/core/lib/support/string.h" -static void addhdr(gpr_strvec *buf, grpc_event *ev) { - char *tmp; +static void addhdr(gpr_strvec* buf, grpc_event* ev) { + char* tmp; gpr_asprintf(&tmp, "tag:%p", ev->tag); gpr_strvec_add(buf, tmp); } -static const char *errstr(int success) { return success ? "OK" : "ERROR"; } +static const char* errstr(int success) { return success ? "OK" : "ERROR"; } -static void adderr(gpr_strvec *buf, int success) { - char *tmp; +static void adderr(gpr_strvec* buf, int success) { + char* tmp; gpr_asprintf(&tmp, " %s", errstr(success)); gpr_strvec_add(buf, tmp); } -char *grpc_event_string(grpc_event *ev) { - char *out; +char* grpc_event_string(grpc_event* ev) { + char* out; gpr_strvec buf; - if (ev == NULL) return gpr_strdup("null"); + if (ev == nullptr) return gpr_strdup("null"); gpr_strvec_init(&buf); @@ -60,7 +60,7 @@ char *grpc_event_string(grpc_event *ev) { break; } - out = gpr_strvec_flatten(&buf, NULL); + out = gpr_strvec_flatten(&buf, nullptr); gpr_strvec_destroy(&buf); return out; } diff --git a/src/core/lib/surface/event_string.h b/src/core/lib/surface/event_string.h index 2d53cf0facf..cbf96da6c5d 100644 --- a/src/core/lib/surface/event_string.h +++ b/src/core/lib/surface/event_string.h @@ -21,15 +21,7 @@ #include -#ifdef __cplusplus -extern "C" { -#endif - /* Returns a string describing an event. Must be later freed with gpr_free() */ -char *grpc_event_string(grpc_event *ev); - -#ifdef __cplusplus -} -#endif +char* grpc_event_string(grpc_event* ev); #endif /* GRPC_CORE_LIB_SURFACE_EVENT_STRING_H */ diff --git a/src/core/lib/surface/init.cc b/src/core/lib/surface/init.cc index 058e88f8048..8ee1383fb8b 100644 --- a/src/core/lib/surface/init.cc +++ b/src/core/lib/surface/init.cc @@ -21,6 +21,7 @@ #include #include +#include #include #include #include @@ -39,6 +40,8 @@ #include "src/core/lib/iomgr/timer_manager.h" #include "src/core/lib/profiling/timers.h" #include "src/core/lib/slice/slice_internal.h" +#include "src/core/lib/support/fork.h" +#include "src/core/lib/support/thd_internal.h" #include "src/core/lib/surface/alarm_internal.h" #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/call.h" @@ -62,39 +65,41 @@ static int g_initializations; static void do_basic_init(void) { gpr_log_verbosity_init(); + grpc_fork_support_init(); gpr_mu_init(&g_init_mu); grpc_register_built_in_plugins(); grpc_cq_global_init(); g_initializations = 0; + grpc_fork_handlers_auto_register(); } -static bool append_filter(grpc_exec_ctx *exec_ctx, - grpc_channel_stack_builder *builder, void *arg) { +static bool append_filter(grpc_exec_ctx* exec_ctx, + grpc_channel_stack_builder* builder, void* arg) { return grpc_channel_stack_builder_append_filter( - builder, (const grpc_channel_filter *)arg, NULL, NULL); + builder, (const grpc_channel_filter*)arg, nullptr, nullptr); } -static bool prepend_filter(grpc_exec_ctx *exec_ctx, - grpc_channel_stack_builder *builder, void *arg) { +static bool prepend_filter(grpc_exec_ctx* exec_ctx, + grpc_channel_stack_builder* builder, void* arg) { return grpc_channel_stack_builder_prepend_filter( - builder, (const grpc_channel_filter *)arg, NULL, NULL); + builder, (const grpc_channel_filter*)arg, nullptr, nullptr); } static void register_builtin_channel_init() { grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, - grpc_add_connected_filter, NULL); + grpc_add_connected_filter, nullptr); grpc_channel_init_register_stage(GRPC_CLIENT_DIRECT_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, - grpc_add_connected_filter, NULL); + grpc_add_connected_filter, nullptr); grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, - grpc_add_connected_filter, NULL); + grpc_add_connected_filter, nullptr); grpc_channel_init_register_stage(GRPC_CLIENT_LAME_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, - append_filter, (void *)&grpc_lame_filter); + append_filter, (void*)&grpc_lame_filter); grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL, INT_MAX, prepend_filter, - (void *)&grpc_server_top_filter); + (void*)&grpc_server_top_filter); } typedef struct grpc_plugin { @@ -107,7 +112,7 @@ static int g_number_of_plugins = 0; void grpc_register_plugin(void (*init)(void), void (*destroy)(void)) { GRPC_API_TRACE("grpc_register_plugin(init=%p, destroy=%p)", 2, - ((void *)(intptr_t)init, (void *)(intptr_t)destroy)); + ((void*)(intptr_t)init, (void*)(intptr_t)destroy)); GPR_ASSERT(g_number_of_plugins != MAX_PLUGINS); g_all_of_the_plugins[g_number_of_plugins].init = init; g_all_of_the_plugins[g_number_of_plugins].destroy = destroy; @@ -122,41 +127,18 @@ void grpc_init(void) { gpr_mu_lock(&g_init_mu); if (++g_initializations == 1) { gpr_time_init(); + gpr_thd_init(); grpc_stats_init(); grpc_slice_intern_init(); grpc_mdctx_global_init(); grpc_channel_init_init(); - grpc_register_tracer(&grpc_api_trace); - grpc_register_tracer(&grpc_trace_channel); - grpc_register_tracer(&grpc_connectivity_state_trace); - grpc_register_tracer(&grpc_trace_channel_stack_builder); - grpc_register_tracer(&grpc_http1_trace); - grpc_register_tracer(&grpc_cq_pluck_trace); // default on - grpc_register_tracer(&grpc_call_combiner_trace); - grpc_register_tracer(&grpc_combiner_trace); - grpc_register_tracer(&grpc_server_channel_trace); - grpc_register_tracer(&grpc_bdp_estimator_trace); - grpc_register_tracer(&grpc_cq_event_timeout_trace); // default on - grpc_register_tracer(&grpc_trace_operation_failures); - grpc_register_tracer(&grpc_resource_quota_trace); - grpc_register_tracer(&grpc_call_error_trace); -#ifndef NDEBUG - grpc_register_tracer(&grpc_trace_pending_tags); - grpc_register_tracer(&grpc_trace_alarm_refcount); - grpc_register_tracer(&grpc_trace_cq_refcount); - grpc_register_tracer(&grpc_trace_closure); - grpc_register_tracer(&grpc_trace_error_refcount); - grpc_register_tracer(&grpc_trace_stream_refcount); - grpc_register_tracer(&grpc_trace_fd_refcount); - grpc_register_tracer(&grpc_trace_metadata); -#endif grpc_security_pre_init(); grpc_iomgr_init(&exec_ctx); gpr_timers_global_init(); grpc_handshaker_factory_registry_init(); grpc_security_init(); for (i = 0; i < g_number_of_plugins; i++) { - if (g_all_of_the_plugins[i].init != NULL) { + if (g_all_of_the_plugins[i].init != nullptr) { g_all_of_the_plugins[i].init(); } } @@ -178,13 +160,13 @@ void grpc_shutdown(void) { int i; GRPC_API_TRACE("grpc_shutdown(void)", 0, ()); grpc_exec_ctx exec_ctx = - GRPC_EXEC_CTX_INITIALIZER(0, grpc_never_ready_to_finish, NULL); + GRPC_EXEC_CTX_INITIALIZER(0, grpc_never_ready_to_finish, nullptr); gpr_mu_lock(&g_init_mu); if (--g_initializations == 0) { grpc_executor_shutdown(&exec_ctx); grpc_timer_manager_set_threading(false); // shutdown timer_manager thread for (i = g_number_of_plugins; i >= 0; i--) { - if (g_all_of_the_plugins[i].destroy != NULL) { + if (g_all_of_the_plugins[i].destroy != nullptr) { g_all_of_the_plugins[i].destroy(); } } diff --git a/src/core/lib/surface/init.h b/src/core/lib/surface/init.h index d429026327f..9353208332f 100644 --- a/src/core/lib/surface/init.h +++ b/src/core/lib/surface/init.h @@ -19,17 +19,9 @@ #ifndef GRPC_CORE_LIB_SURFACE_INIT_H #define GRPC_CORE_LIB_SURFACE_INIT_H -#ifdef __cplusplus -extern "C" { -#endif - void grpc_register_security_filters(void); void grpc_security_pre_init(void); void grpc_security_init(void); int grpc_is_initialized(void); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SURFACE_INIT_H */ diff --git a/src/core/lib/surface/init_secure.cc b/src/core/lib/surface/init_secure.cc index 8fbde3d1b4a..3eee570fc26 100644 --- a/src/core/lib/surface/init_secure.cc +++ b/src/core/lib/surface/init_secure.cc @@ -24,6 +24,7 @@ #include #include "src/core/lib/debug/trace.h" +#include "src/core/lib/security/context/security_context.h" #include "src/core/lib/security/credentials/credentials.h" #include "src/core/lib/security/credentials/plugin/plugin_credentials.h" #include "src/core/lib/security/transport/auth_filters.h" @@ -33,28 +34,17 @@ #include "src/core/lib/surface/channel_init.h" #include "src/core/tsi/transport_security_interface.h" -#ifndef NDEBUG -#include "src/core/lib/security/context/security_context.h" -#endif - -void grpc_security_pre_init(void) { - grpc_register_tracer(&grpc_trace_secure_endpoint); - grpc_register_tracer(&tsi_tracing_enabled); -#ifndef NDEBUG - grpc_register_tracer(&grpc_trace_auth_context_refcount); - grpc_register_tracer(&grpc_trace_security_connector_refcount); -#endif -} +void grpc_security_pre_init(void) {} static bool maybe_prepend_client_auth_filter( - grpc_exec_ctx *exec_ctx, grpc_channel_stack_builder *builder, void *arg) { - const grpc_channel_args *args = + grpc_exec_ctx* exec_ctx, grpc_channel_stack_builder* builder, void* arg) { + const grpc_channel_args* args = grpc_channel_stack_builder_get_channel_arguments(builder); if (args) { for (size_t i = 0; i < args->num_args; i++) { if (0 == strcmp(GRPC_ARG_SECURITY_CONNECTOR, args->args[i].key)) { return grpc_channel_stack_builder_prepend_filter( - builder, &grpc_client_auth_filter, NULL, NULL); + builder, &grpc_client_auth_filter, nullptr, nullptr); } } } @@ -62,14 +52,14 @@ static bool maybe_prepend_client_auth_filter( } static bool maybe_prepend_server_auth_filter( - grpc_exec_ctx *exec_ctx, grpc_channel_stack_builder *builder, void *arg) { - const grpc_channel_args *args = + grpc_exec_ctx* exec_ctx, grpc_channel_stack_builder* builder, void* arg) { + const grpc_channel_args* args = grpc_channel_stack_builder_get_channel_arguments(builder); if (args) { for (size_t i = 0; i < args->num_args; i++) { if (0 == strcmp(GRPC_SERVER_CREDENTIALS_ARG, args->args[i].key)) { return grpc_channel_stack_builder_prepend_filter( - builder, &grpc_server_auth_filter, NULL, NULL); + builder, &grpc_server_auth_filter, nullptr, nullptr); } } } @@ -78,14 +68,11 @@ static bool maybe_prepend_server_auth_filter( void grpc_register_security_filters(void) { grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL, INT_MAX, - maybe_prepend_client_auth_filter, NULL); + maybe_prepend_client_auth_filter, nullptr); grpc_channel_init_register_stage(GRPC_CLIENT_DIRECT_CHANNEL, INT_MAX, - maybe_prepend_client_auth_filter, NULL); + maybe_prepend_client_auth_filter, nullptr); grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL, INT_MAX, - maybe_prepend_server_auth_filter, NULL); + maybe_prepend_server_auth_filter, nullptr); } -void grpc_security_init() { - grpc_security_register_handshaker_factories(); - grpc_register_tracer(&grpc_plugin_credentials_trace); -} +void grpc_security_init() { grpc_security_register_handshaker_factories(); } diff --git a/src/core/lib/surface/lame_client.cc b/src/core/lib/surface/lame_client.cc index 88e26cbeb70..c32c9af50e5 100644 --- a/src/core/lib/surface/lame_client.cc +++ b/src/core/lib/surface/lame_client.cc @@ -25,7 +25,6 @@ #include "src/core/lib/support/atomic.h" -extern "C" { #include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/support/string.h" #include "src/core/lib/surface/api_trace.h" @@ -33,14 +32,13 @@ extern "C" { #include "src/core/lib/surface/channel.h" #include "src/core/lib/surface/lame_client.h" #include "src/core/lib/transport/static_metadata.h" -} namespace grpc_core { namespace { struct CallData { - grpc_call_combiner *call_combiner; + grpc_call_combiner* call_combiner; grpc_linked_mdelem status; grpc_linked_mdelem details; grpc_core::atomic filled_metadata; @@ -48,19 +46,19 @@ struct CallData { struct ChannelData { grpc_status_code error_code; - const char *error_message; + const char* error_message; }; -static void fill_metadata(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_metadata_batch *mdb) { - CallData *calld = reinterpret_cast(elem->call_data); +static void fill_metadata(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_metadata_batch* mdb) { + CallData* calld = reinterpret_cast(elem->call_data); bool expected = false; if (!calld->filled_metadata.compare_exchange_strong( expected, true, grpc_core::memory_order_relaxed, grpc_core::memory_order_relaxed)) { return; } - ChannelData *chand = reinterpret_cast(elem->channel_data); + ChannelData* chand = reinterpret_cast(elem->channel_data); char tmp[GPR_LTOA_MIN_BUFSIZE]; gpr_ltoa(chand->error_code, tmp); calld->status.md = grpc_mdelem_from_slices( @@ -68,7 +66,7 @@ static void fill_metadata(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, calld->details.md = grpc_mdelem_from_slices( exec_ctx, GRPC_MDSTR_GRPC_MESSAGE, grpc_slice_from_copied_string(chand->error_message)); - calld->status.prev = calld->details.next = NULL; + calld->status.prev = calld->details.next = nullptr; calld->status.next = &calld->details; calld->details.prev = &calld->status; mdb->list.head = &calld->status; @@ -78,9 +76,9 @@ static void fill_metadata(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, } static void lame_start_transport_stream_op_batch( - grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_transport_stream_op_batch *op) { - CallData *calld = reinterpret_cast(elem->call_data); + grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_transport_stream_op_batch* op) { + CallData* calld = reinterpret_cast(elem->call_data); if (op->recv_initial_metadata) { fill_metadata(exec_ctx, elem, op->payload->recv_initial_metadata.recv_initial_metadata); @@ -93,60 +91,60 @@ static void lame_start_transport_stream_op_batch( calld->call_combiner); } -static void lame_get_channel_info(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - const grpc_channel_info *channel_info) {} +static void lame_get_channel_info(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + const grpc_channel_info* channel_info) {} -static void lame_start_transport_op(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_transport_op *op) { +static void lame_start_transport_op(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_transport_op* op) { if (op->on_connectivity_state_change) { GPR_ASSERT(*op->connectivity_state != GRPC_CHANNEL_SHUTDOWN); *op->connectivity_state = GRPC_CHANNEL_SHUTDOWN; GRPC_CLOSURE_SCHED(exec_ctx, op->on_connectivity_state_change, GRPC_ERROR_NONE); } - if (op->send_ping != NULL) { + if (op->send_ping != nullptr) { GRPC_CLOSURE_SCHED( exec_ctx, op->send_ping, GRPC_ERROR_CREATE_FROM_STATIC_STRING("lame client channel")); } GRPC_ERROR_UNREF(op->disconnect_with_error); - if (op->on_consumed != NULL) { + if (op->on_consumed != nullptr) { GRPC_CLOSURE_SCHED(exec_ctx, op->on_consumed, GRPC_ERROR_NONE); } } -static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - const grpc_call_element_args *args) { - CallData *calld = reinterpret_cast(elem->call_data); +static grpc_error* init_call_elem(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + const grpc_call_element_args* args) { + CallData* calld = reinterpret_cast(elem->call_data); calld->call_combiner = args->call_combiner; return GRPC_ERROR_NONE; } -static void destroy_call_elem(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - const grpc_call_final_info *final_info, - grpc_closure *then_schedule_closure) { +static void destroy_call_elem(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + const grpc_call_final_info* final_info, + grpc_closure* then_schedule_closure) { GRPC_CLOSURE_SCHED(exec_ctx, then_schedule_closure, GRPC_ERROR_NONE); } -static grpc_error *init_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_channel_element_args *args) { +static grpc_error* init_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_channel_element_args* args) { GPR_ASSERT(args->is_first); GPR_ASSERT(args->is_last); return GRPC_ERROR_NONE; } -static void destroy_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem) {} +static void destroy_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem) {} } // namespace } // namespace grpc_core -extern "C" const grpc_channel_filter grpc_lame_filter = { +const grpc_channel_filter grpc_lame_filter = { grpc_core::lame_start_transport_stream_op_batch, grpc_core::lame_start_transport_op, sizeof(grpc_core::CallData), @@ -160,22 +158,22 @@ extern "C" const grpc_channel_filter grpc_lame_filter = { "lame-client", }; -#define CHANNEL_STACK_FROM_CHANNEL(c) ((grpc_channel_stack *)((c) + 1)) +#define CHANNEL_STACK_FROM_CHANNEL(c) ((grpc_channel_stack*)((c) + 1)) -grpc_channel *grpc_lame_client_channel_create(const char *target, +grpc_channel* grpc_lame_client_channel_create(const char* target, grpc_status_code error_code, - const char *error_message) { + const char* error_message) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - grpc_channel_element *elem; - grpc_channel *channel = grpc_channel_create(&exec_ctx, target, NULL, - GRPC_CLIENT_LAME_CHANNEL, NULL); + grpc_channel_element* elem; + grpc_channel* channel = grpc_channel_create( + &exec_ctx, target, nullptr, GRPC_CLIENT_LAME_CHANNEL, nullptr); elem = grpc_channel_stack_element(grpc_channel_get_channel_stack(channel), 0); GRPC_API_TRACE( "grpc_lame_client_channel_create(target=%s, error_code=%d, " "error_message=%s)", 3, (target, (int)error_code, error_message)); GPR_ASSERT(elem->filter == &grpc_lame_filter); - auto chand = reinterpret_cast(elem->channel_data); + auto chand = reinterpret_cast(elem->channel_data); chand->error_code = error_code; chand->error_message = error_message; grpc_exec_ctx_finish(&exec_ctx); diff --git a/src/core/lib/surface/lame_client.h b/src/core/lib/surface/lame_client.h index 2f6f9cd046e..3ce353f101f 100644 --- a/src/core/lib/surface/lame_client.h +++ b/src/core/lib/surface/lame_client.h @@ -21,14 +21,6 @@ #include "src/core/lib/channel/channel_stack.h" -#ifdef __cplusplus -extern "C" { -#endif - extern const grpc_channel_filter grpc_lame_filter; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_SURFACE_LAME_CLIENT_H */ diff --git a/src/core/lib/surface/server.cc b/src/core/lib/surface/server.cc index dd09cb91de4..0f8a057f315 100644 --- a/src/core/lib/surface/server.cc +++ b/src/core/lib/surface/server.cc @@ -33,7 +33,8 @@ #include "src/core/lib/iomgr/executor.h" #include "src/core/lib/iomgr/iomgr.h" #include "src/core/lib/slice/slice_internal.h" -#include "src/core/lib/support/stack_lockfree.h" +#include "src/core/lib/support/mpscq.h" +#include "src/core/lib/support/spinlock.h" #include "src/core/lib/support/string.h" #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/call.h" @@ -44,12 +45,12 @@ #include "src/core/lib/transport/static_metadata.h" typedef struct listener { - void *arg; - void (*start)(grpc_exec_ctx *exec_ctx, grpc_server *server, void *arg, - grpc_pollset **pollsets, size_t pollset_count); - void (*destroy)(grpc_exec_ctx *exec_ctx, grpc_server *server, void *arg, - grpc_closure *closure); - struct listener *next; + void* arg; + void (*start)(grpc_exec_ctx* exec_ctx, grpc_server* server, void* arg, + grpc_pollset** pollsets, size_t pollset_count); + void (*destroy)(grpc_exec_ctx* exec_ctx, grpc_server* server, void* arg, + grpc_closure* closure); + struct listener* next; grpc_closure destroy_done; } listener; @@ -59,32 +60,32 @@ typedef struct registered_method registered_method; typedef enum { BATCH_CALL, REGISTERED_CALL } requested_call_type; -grpc_tracer_flag grpc_server_channel_trace = - GRPC_TRACER_INITIALIZER(false, "server_channel"); +grpc_core::TraceFlag grpc_server_channel_trace(false, "server_channel"); typedef struct requested_call { + gpr_mpscq_node request_link; /* must be first */ requested_call_type type; size_t cq_idx; - void *tag; - grpc_server *server; - grpc_completion_queue *cq_bound_to_call; - grpc_call **call; + void* tag; + grpc_server* server; + grpc_completion_queue* cq_bound_to_call; + grpc_call** call; grpc_cq_completion completion; - grpc_metadata_array *initial_metadata; + grpc_metadata_array* initial_metadata; union { struct { - grpc_call_details *details; + grpc_call_details* details; } batch; struct { - registered_method *method; - gpr_timespec *deadline; - grpc_byte_buffer **optional_payload; + registered_method* method; + gpr_timespec* deadline; + grpc_byte_buffer** optional_payload; } registered; } data; } requested_call; typedef struct channel_registered_method { - registered_method *server_registered_method; + registered_method* server_registered_method; uint32_t flags; bool has_host; grpc_slice method; @@ -92,14 +93,14 @@ typedef struct channel_registered_method { } channel_registered_method; struct channel_data { - grpc_server *server; + grpc_server* server; grpc_connectivity_state connectivity_state; - grpc_channel *channel; + grpc_channel* channel; size_t cq_idx; /* linked list of all channels on a server */ - channel_data *next; - channel_data *prev; - channel_registered_method *registered_methods; + channel_data* next; + channel_data* prev; + channel_registered_method* registered_methods; uint32_t registered_method_slots; uint32_t registered_method_max_probes; grpc_closure finish_destroy_channel_closure; @@ -107,8 +108,8 @@ struct channel_data { }; typedef struct shutdown_tag { - void *tag; - grpc_completion_queue *cq; + void* tag; + grpc_completion_queue* cq; grpc_cq_completion completion; } shutdown_tag; @@ -126,12 +127,9 @@ typedef enum { typedef struct request_matcher request_matcher; struct call_data { - grpc_call *call; + grpc_call* call; - /** protects state */ - gpr_mu mu_state; - /** the current state of a call - see call_state */ - call_state state; + gpr_atm state; bool path_set; bool host_set; @@ -139,52 +137,52 @@ struct call_data { grpc_slice host; grpc_millis deadline; - grpc_completion_queue *cq_new; + grpc_completion_queue* cq_new; - grpc_metadata_batch *recv_initial_metadata; + grpc_metadata_batch* recv_initial_metadata; uint32_t recv_initial_metadata_flags; grpc_metadata_array initial_metadata; - request_matcher *matcher; - grpc_byte_buffer *payload; + request_matcher* matcher; + grpc_byte_buffer* payload; grpc_closure got_initial_metadata; grpc_closure server_on_recv_initial_metadata; grpc_closure kill_zombie_closure; - grpc_closure *on_done_recv_initial_metadata; + grpc_closure* on_done_recv_initial_metadata; grpc_closure publish; - call_data *pending_next; + call_data* pending_next; }; struct request_matcher { - grpc_server *server; - call_data *pending_head; - call_data *pending_tail; - gpr_stack_lockfree **requests_per_cq; + grpc_server* server; + call_data* pending_head; + call_data* pending_tail; + gpr_locked_mpscq* requests_per_cq; }; struct registered_method { - char *method; - char *host; + char* method; + char* host; grpc_server_register_method_payload_handling payload_handling; uint32_t flags; /* one request matcher per method */ request_matcher matcher; - registered_method *next; + registered_method* next; }; typedef struct { - grpc_channel **channels; + grpc_channel** channels; size_t num_channels; } channel_broadcaster; struct grpc_server { - grpc_channel_args *channel_args; + grpc_channel_args* channel_args; - grpc_completion_queue **cqs; - grpc_pollset **pollsets; + grpc_completion_queue** cqs; + grpc_pollset** pollsets; size_t cq_count; size_t pollset_count; bool started; @@ -204,23 +202,18 @@ struct grpc_server { bool starting; gpr_cv starting_cv; - registered_method *registered_methods; + registered_method* registered_methods; /** one request matcher for unregistered methods */ request_matcher unregistered_request_matcher; - /** free list of available requested_calls_per_cq indices */ - gpr_stack_lockfree **request_freelist_per_cq; - /** requested call backing data */ - requested_call **requested_calls_per_cq; - int max_requested_calls_per_cq; gpr_atm shutdown_flag; uint8_t shutdown_published; size_t num_shutdown_tags; - shutdown_tag *shutdown_tags; + shutdown_tag* shutdown_tags; channel_data root_channel_data; - listener *listeners; + listener* listeners; int listeners_destroyed; gpr_refcount internal_refcount; @@ -229,30 +222,30 @@ struct grpc_server { }; #define SERVER_FROM_CALL_ELEM(elem) \ - (((channel_data *)(elem)->channel_data)->server) + (((channel_data*)(elem)->channel_data)->server) -static void publish_new_rpc(grpc_exec_ctx *exec_ctx, void *calld, - grpc_error *error); -static void fail_call(grpc_exec_ctx *exec_ctx, grpc_server *server, - size_t cq_idx, requested_call *rc, grpc_error *error); +static void publish_new_rpc(grpc_exec_ctx* exec_ctx, void* calld, + grpc_error* error); +static void fail_call(grpc_exec_ctx* exec_ctx, grpc_server* server, + size_t cq_idx, requested_call* rc, grpc_error* error); /* Before calling maybe_finish_shutdown, we must hold mu_global and not hold mu_call */ -static void maybe_finish_shutdown(grpc_exec_ctx *exec_ctx, grpc_server *server); +static void maybe_finish_shutdown(grpc_exec_ctx* exec_ctx, grpc_server* server); /* * channel broadcaster */ /* assumes server locked */ -static void channel_broadcaster_init(grpc_server *s, channel_broadcaster *cb) { - channel_data *c; +static void channel_broadcaster_init(grpc_server* s, channel_broadcaster* cb) { + channel_data* c; size_t count = 0; for (c = s->root_channel_data.next; c != &s->root_channel_data; c = c->next) { count++; } cb->num_channels = count; cb->channels = - (grpc_channel **)gpr_malloc(sizeof(*cb->channels) * cb->num_channels); + (grpc_channel**)gpr_malloc(sizeof(*cb->channels) * cb->num_channels); count = 0; for (c = s->root_channel_data.next; c != &s->root_channel_data; c = c->next) { cb->channels[count++] = c->channel; @@ -265,21 +258,21 @@ struct shutdown_cleanup_args { grpc_slice slice; }; -static void shutdown_cleanup(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - struct shutdown_cleanup_args *a = (struct shutdown_cleanup_args *)arg; +static void shutdown_cleanup(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + struct shutdown_cleanup_args* a = (struct shutdown_cleanup_args*)arg; grpc_slice_unref_internal(exec_ctx, a->slice); gpr_free(a); } -static void send_shutdown(grpc_exec_ctx *exec_ctx, grpc_channel *channel, - bool send_goaway, grpc_error *send_disconnect) { - struct shutdown_cleanup_args *sc = - (struct shutdown_cleanup_args *)gpr_malloc(sizeof(*sc)); +static void send_shutdown(grpc_exec_ctx* exec_ctx, grpc_channel* channel, + bool send_goaway, grpc_error* send_disconnect) { + struct shutdown_cleanup_args* sc = + (struct shutdown_cleanup_args*)gpr_malloc(sizeof(*sc)); GRPC_CLOSURE_INIT(&sc->closure, shutdown_cleanup, sc, grpc_schedule_on_exec_ctx); - grpc_transport_op *op = grpc_make_transport_op(&sc->closure); - grpc_channel_element *elem; + grpc_transport_op* op = grpc_make_transport_op(&sc->closure); + grpc_channel_element* elem; op->goaway_error = send_goaway ? grpc_error_set_int( @@ -294,10 +287,10 @@ static void send_shutdown(grpc_exec_ctx *exec_ctx, grpc_channel *channel, elem->filter->start_transport_op(exec_ctx, elem, op); } -static void channel_broadcaster_shutdown(grpc_exec_ctx *exec_ctx, - channel_broadcaster *cb, +static void channel_broadcaster_shutdown(grpc_exec_ctx* exec_ctx, + channel_broadcaster* cb, bool send_goaway, - grpc_error *force_disconnect) { + grpc_error* force_disconnect) { size_t i; for (i = 0; i < cb->num_channels; i++) { @@ -313,38 +306,35 @@ static void channel_broadcaster_shutdown(grpc_exec_ctx *exec_ctx, * request_matcher */ -static void request_matcher_init(request_matcher *rm, size_t entries, - grpc_server *server) { +static void request_matcher_init(request_matcher* rm, grpc_server* server) { memset(rm, 0, sizeof(*rm)); rm->server = server; - rm->requests_per_cq = (gpr_stack_lockfree **)gpr_malloc( + rm->requests_per_cq = (gpr_locked_mpscq*)gpr_malloc( sizeof(*rm->requests_per_cq) * server->cq_count); for (size_t i = 0; i < server->cq_count; i++) { - rm->requests_per_cq[i] = gpr_stack_lockfree_create(entries); + gpr_locked_mpscq_init(&rm->requests_per_cq[i]); } } -static void request_matcher_destroy(request_matcher *rm) { +static void request_matcher_destroy(request_matcher* rm) { for (size_t i = 0; i < rm->server->cq_count; i++) { - GPR_ASSERT(gpr_stack_lockfree_pop(rm->requests_per_cq[i]) == -1); - gpr_stack_lockfree_destroy(rm->requests_per_cq[i]); + GPR_ASSERT(gpr_locked_mpscq_pop(&rm->requests_per_cq[i]) == nullptr); + gpr_locked_mpscq_destroy(&rm->requests_per_cq[i]); } gpr_free(rm->requests_per_cq); } -static void kill_zombie(grpc_exec_ctx *exec_ctx, void *elem, - grpc_error *error) { - grpc_call_unref(grpc_call_from_top_element((grpc_call_element *)elem)); +static void kill_zombie(grpc_exec_ctx* exec_ctx, void* elem, + grpc_error* error) { + grpc_call_unref(grpc_call_from_top_element((grpc_call_element*)elem)); } -static void request_matcher_zombify_all_pending_calls(grpc_exec_ctx *exec_ctx, - request_matcher *rm) { +static void request_matcher_zombify_all_pending_calls(grpc_exec_ctx* exec_ctx, + request_matcher* rm) { while (rm->pending_head) { - call_data *calld = rm->pending_head; + call_data* calld = rm->pending_head; rm->pending_head = calld->pending_next; - gpr_mu_lock(&calld->mu_state); - calld->state = ZOMBIED; - gpr_mu_unlock(&calld->mu_state); + gpr_atm_no_barrier_store(&calld->state, ZOMBIED); GRPC_CLOSURE_INIT( &calld->kill_zombie_closure, kill_zombie, grpc_call_stack_element(grpc_call_get_call_stack(calld->call), 0), @@ -353,17 +343,15 @@ static void request_matcher_zombify_all_pending_calls(grpc_exec_ctx *exec_ctx, } } -static void request_matcher_kill_requests(grpc_exec_ctx *exec_ctx, - grpc_server *server, - request_matcher *rm, - grpc_error *error) { - int request_id; +static void request_matcher_kill_requests(grpc_exec_ctx* exec_ctx, + grpc_server* server, + request_matcher* rm, + grpc_error* error) { + requested_call* rc; for (size_t i = 0; i < server->cq_count; i++) { - while ((request_id = gpr_stack_lockfree_pop(rm->requests_per_cq[i])) != - -1) { - fail_call(exec_ctx, server, i, - &server->requested_calls_per_cq[i][request_id], - GRPC_ERROR_REF(error)); + while ((rc = (requested_call*)gpr_locked_mpscq_pop( + &rm->requests_per_cq[i])) != nullptr) { + fail_call(exec_ctx, server, i, rc, GRPC_ERROR_REF(error)); } } GRPC_ERROR_UNREF(error); @@ -373,18 +361,18 @@ static void request_matcher_kill_requests(grpc_exec_ctx *exec_ctx, * server proper */ -static void server_ref(grpc_server *server) { +static void server_ref(grpc_server* server) { gpr_ref(&server->internal_refcount); } -static void server_delete(grpc_exec_ctx *exec_ctx, grpc_server *server) { - registered_method *rm; +static void server_delete(grpc_exec_ctx* exec_ctx, grpc_server* server) { + registered_method* rm; size_t i; grpc_channel_args_destroy(exec_ctx, server->channel_args); gpr_mu_destroy(&server->mu_global); gpr_mu_destroy(&server->mu_call); gpr_cv_destroy(&server->starting_cv); - while ((rm = server->registered_methods) != NULL) { + while ((rm = server->registered_methods) != nullptr) { server->registered_methods = rm->next; if (server->started) { request_matcher_destroy(&rm->matcher); @@ -398,60 +386,54 @@ static void server_delete(grpc_exec_ctx *exec_ctx, grpc_server *server) { } for (i = 0; i < server->cq_count; i++) { GRPC_CQ_INTERNAL_UNREF(exec_ctx, server->cqs[i], "server"); - if (server->started) { - gpr_stack_lockfree_destroy(server->request_freelist_per_cq[i]); - gpr_free(server->requested_calls_per_cq[i]); - } } - gpr_free(server->request_freelist_per_cq); - gpr_free(server->requested_calls_per_cq); gpr_free(server->cqs); gpr_free(server->pollsets); gpr_free(server->shutdown_tags); gpr_free(server); } -static void server_unref(grpc_exec_ctx *exec_ctx, grpc_server *server) { +static void server_unref(grpc_exec_ctx* exec_ctx, grpc_server* server) { if (gpr_unref(&server->internal_refcount)) { server_delete(exec_ctx, server); } } -static int is_channel_orphaned(channel_data *chand) { +static int is_channel_orphaned(channel_data* chand) { return chand->next == chand; } -static void orphan_channel(channel_data *chand) { +static void orphan_channel(channel_data* chand) { chand->next->prev = chand->prev; chand->prev->next = chand->next; chand->next = chand->prev = chand; } -static void finish_destroy_channel(grpc_exec_ctx *exec_ctx, void *cd, - grpc_error *error) { - channel_data *chand = (channel_data *)cd; - grpc_server *server = chand->server; +static void finish_destroy_channel(grpc_exec_ctx* exec_ctx, void* cd, + grpc_error* error) { + channel_data* chand = (channel_data*)cd; + grpc_server* server = chand->server; GRPC_CHANNEL_INTERNAL_UNREF(exec_ctx, chand->channel, "server"); server_unref(exec_ctx, server); } -static void destroy_channel(grpc_exec_ctx *exec_ctx, channel_data *chand, - grpc_error *error) { +static void destroy_channel(grpc_exec_ctx* exec_ctx, channel_data* chand, + grpc_error* error) { if (is_channel_orphaned(chand)) return; - GPR_ASSERT(chand->server != NULL); + GPR_ASSERT(chand->server != nullptr); orphan_channel(chand); server_ref(chand->server); maybe_finish_shutdown(exec_ctx, chand->server); GRPC_CLOSURE_INIT(&chand->finish_destroy_channel_closure, finish_destroy_channel, chand, grpc_schedule_on_exec_ctx); - if (GRPC_TRACER_ON(grpc_server_channel_trace) && error != GRPC_ERROR_NONE) { - const char *msg = grpc_error_string(error); + if (grpc_server_channel_trace.enabled() && error != GRPC_ERROR_NONE) { + const char* msg = grpc_error_string(error); gpr_log(GPR_INFO, "Disconnected client: %s", msg); } GRPC_ERROR_UNREF(error); - grpc_transport_op *op = + grpc_transport_op* op = grpc_make_transport_op(&chand->finish_destroy_channel_closure); op->set_accept_stream = true; grpc_channel_next_op(exec_ctx, @@ -460,29 +442,15 @@ static void destroy_channel(grpc_exec_ctx *exec_ctx, channel_data *chand, op); } -static void done_request_event(grpc_exec_ctx *exec_ctx, void *req, - grpc_cq_completion *c) { - requested_call *rc = (requested_call *)req; - grpc_server *server = rc->server; - - if (rc >= server->requested_calls_per_cq[rc->cq_idx] && - rc < server->requested_calls_per_cq[rc->cq_idx] + - server->max_requested_calls_per_cq) { - GPR_ASSERT(rc - server->requested_calls_per_cq[rc->cq_idx] <= INT_MAX); - gpr_stack_lockfree_push( - server->request_freelist_per_cq[rc->cq_idx], - (int)(rc - server->requested_calls_per_cq[rc->cq_idx])); - } else { - gpr_free(req); - } - - server_unref(exec_ctx, server); +static void done_request_event(grpc_exec_ctx* exec_ctx, void* req, + grpc_cq_completion* c) { + gpr_free(req); } -static void publish_call(grpc_exec_ctx *exec_ctx, grpc_server *server, - call_data *calld, size_t cq_idx, requested_call *rc) { +static void publish_call(grpc_exec_ctx* exec_ctx, grpc_server* server, + call_data* calld, size_t cq_idx, requested_call* rc) { grpc_call_set_completion_queue(exec_ctx, calld->call, rc->cq_bound_to_call); - grpc_call *call = calld->call; + grpc_call* call = calld->call; *rc->call = call; calld->cq_new = server->cqs[cq_idx]; GPR_SWAP(grpc_metadata_array, *rc->initial_metadata, calld->initial_metadata); @@ -501,33 +469,27 @@ static void publish_call(grpc_exec_ctx *exec_ctx, grpc_server *server, grpc_millis_to_timespec(calld->deadline, GPR_CLOCK_MONOTONIC); if (rc->data.registered.optional_payload) { *rc->data.registered.optional_payload = calld->payload; - calld->payload = NULL; + calld->payload = nullptr; } break; default: GPR_UNREACHABLE_CODE(return ); } - grpc_call_element *elem = - grpc_call_stack_element(grpc_call_get_call_stack(call), 0); - channel_data *chand = (channel_data *)elem->channel_data; - server_ref(chand->server); grpc_cq_end_op(exec_ctx, calld->cq_new, rc->tag, GRPC_ERROR_NONE, done_request_event, rc, &rc->completion); } -static void publish_new_rpc(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - grpc_call_element *call_elem = (grpc_call_element *)arg; - call_data *calld = (call_data *)call_elem->call_data; - channel_data *chand = (channel_data *)call_elem->channel_data; - request_matcher *rm = calld->matcher; - grpc_server *server = rm->server; +static void publish_new_rpc(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + grpc_call_element* call_elem = (grpc_call_element*)arg; + call_data* calld = (call_data*)call_elem->call_data; + channel_data* chand = (channel_data*)call_elem->channel_data; + request_matcher* rm = calld->matcher; + grpc_server* server = rm->server; if (error != GRPC_ERROR_NONE || gpr_atm_acq_load(&server->shutdown_flag)) { - gpr_mu_lock(&calld->mu_state); - calld->state = ZOMBIED; - gpr_mu_unlock(&calld->mu_state); + gpr_atm_no_barrier_store(&calld->state, ZOMBIED); GRPC_CLOSURE_INIT( &calld->kill_zombie_closure, kill_zombie, grpc_call_stack_element(grpc_call_get_call_stack(calld->call), 0), @@ -539,16 +501,14 @@ static void publish_new_rpc(grpc_exec_ctx *exec_ctx, void *arg, for (size_t i = 0; i < server->cq_count; i++) { size_t cq_idx = (chand->cq_idx + i) % server->cq_count; - int request_id = gpr_stack_lockfree_pop(rm->requests_per_cq[cq_idx]); - if (request_id == -1) { + requested_call* rc = + (requested_call*)gpr_locked_mpscq_try_pop(&rm->requests_per_cq[cq_idx]); + if (rc == nullptr) { continue; } else { GRPC_STATS_INC_SERVER_CQS_CHECKED(exec_ctx, i); - gpr_mu_lock(&calld->mu_state); - calld->state = ACTIVATED; - gpr_mu_unlock(&calld->mu_state); - publish_call(exec_ctx, server, calld, cq_idx, - &server->requested_calls_per_cq[cq_idx][request_id]); + gpr_atm_no_barrier_store(&calld->state, ACTIVATED); + publish_call(exec_ctx, server, calld, cq_idx, rc); return; /* early out */ } } @@ -556,29 +516,45 @@ static void publish_new_rpc(grpc_exec_ctx *exec_ctx, void *arg, /* no cq to take the request found: queue it on the slow list */ GRPC_STATS_INC_SERVER_SLOWPATH_REQUESTS_QUEUED(exec_ctx); gpr_mu_lock(&server->mu_call); - gpr_mu_lock(&calld->mu_state); - calld->state = PENDING; - gpr_mu_unlock(&calld->mu_state); - if (rm->pending_head == NULL) { + + // We need to ensure that all the queues are empty. We do this under + // the server mu_call lock to ensure that if something is added to + // an empty request queue, it will block until the call is actually + // added to the pending list. + for (size_t i = 0; i < server->cq_count; i++) { + size_t cq_idx = (chand->cq_idx + i) % server->cq_count; + requested_call* rc = + (requested_call*)gpr_locked_mpscq_pop(&rm->requests_per_cq[cq_idx]); + if (rc == nullptr) { + continue; + } else { + gpr_mu_unlock(&server->mu_call); + GRPC_STATS_INC_SERVER_CQS_CHECKED(exec_ctx, i + server->cq_count); + gpr_atm_no_barrier_store(&calld->state, ACTIVATED); + publish_call(exec_ctx, server, calld, cq_idx, rc); + return; /* early out */ + } + } + + gpr_atm_no_barrier_store(&calld->state, PENDING); + if (rm->pending_head == nullptr) { rm->pending_tail = rm->pending_head = calld; } else { rm->pending_tail->pending_next = calld; rm->pending_tail = calld; } - calld->pending_next = NULL; + calld->pending_next = nullptr; gpr_mu_unlock(&server->mu_call); } static void finish_start_new_rpc( - grpc_exec_ctx *exec_ctx, grpc_server *server, grpc_call_element *elem, - request_matcher *rm, + grpc_exec_ctx* exec_ctx, grpc_server* server, grpc_call_element* elem, + request_matcher* rm, grpc_server_register_method_payload_handling payload_handling) { - call_data *calld = (call_data *)elem->call_data; + call_data* calld = (call_data*)elem->call_data; if (gpr_atm_acq_load(&server->shutdown_flag)) { - gpr_mu_lock(&calld->mu_state); - calld->state = ZOMBIED; - gpr_mu_unlock(&calld->mu_state); + gpr_atm_no_barrier_store(&calld->state, ZOMBIED); GRPC_CLOSURE_INIT(&calld->kill_zombie_closure, kill_zombie, elem, grpc_schedule_on_exec_ctx); GRPC_CLOSURE_SCHED(exec_ctx, &calld->kill_zombie_closure, GRPC_ERROR_NONE); @@ -605,13 +581,13 @@ static void finish_start_new_rpc( } } -static void start_new_rpc(grpc_exec_ctx *exec_ctx, grpc_call_element *elem) { - channel_data *chand = (channel_data *)elem->channel_data; - call_data *calld = (call_data *)elem->call_data; - grpc_server *server = chand->server; +static void start_new_rpc(grpc_exec_ctx* exec_ctx, grpc_call_element* elem) { + channel_data* chand = (channel_data*)elem->channel_data; + call_data* calld = (call_data*)elem->call_data; + grpc_server* server = chand->server; uint32_t i; uint32_t hash; - channel_registered_method *rm; + channel_registered_method* rm; if (chand->registered_methods && calld->path_set && calld->host_set) { /* TODO(ctiller): unify these two searches */ @@ -659,8 +635,8 @@ static void start_new_rpc(grpc_exec_ctx *exec_ctx, grpc_call_element *elem) { GRPC_SRM_PAYLOAD_NONE); } -static int num_listeners(grpc_server *server) { - listener *l; +static int num_listeners(grpc_server* server) { + listener* l; int n = 0; for (l = server->listeners; l; l = l->next) { n++; @@ -668,13 +644,13 @@ static int num_listeners(grpc_server *server) { return n; } -static void done_shutdown_event(grpc_exec_ctx *exec_ctx, void *server, - grpc_cq_completion *completion) { - server_unref(exec_ctx, (grpc_server *)server); +static void done_shutdown_event(grpc_exec_ctx* exec_ctx, void* server, + grpc_cq_completion* completion) { + server_unref(exec_ctx, (grpc_server*)server); } -static int num_channels(grpc_server *server) { - channel_data *chand; +static int num_channels(grpc_server* server) { + channel_data* chand; int n = 0; for (chand = server->root_channel_data.next; chand != &server->root_channel_data; chand = chand->next) { @@ -683,15 +659,15 @@ static int num_channels(grpc_server *server) { return n; } -static void kill_pending_work_locked(grpc_exec_ctx *exec_ctx, - grpc_server *server, grpc_error *error) { +static void kill_pending_work_locked(grpc_exec_ctx* exec_ctx, + grpc_server* server, grpc_error* error) { if (server->started) { request_matcher_kill_requests(exec_ctx, server, &server->unregistered_request_matcher, GRPC_ERROR_REF(error)); request_matcher_zombify_all_pending_calls( exec_ctx, &server->unregistered_request_matcher); - for (registered_method *rm = server->registered_methods; rm; + for (registered_method* rm = server->registered_methods; rm; rm = rm->next) { request_matcher_kill_requests(exec_ctx, server, &rm->matcher, GRPC_ERROR_REF(error)); @@ -701,8 +677,8 @@ static void kill_pending_work_locked(grpc_exec_ctx *exec_ctx, GRPC_ERROR_UNREF(error); } -static void maybe_finish_shutdown(grpc_exec_ctx *exec_ctx, - grpc_server *server) { +static void maybe_finish_shutdown(grpc_exec_ctx* exec_ctx, + grpc_server* server) { size_t i; if (!gpr_atm_acq_load(&server->shutdown_flag) || server->shutdown_published) { return; @@ -737,15 +713,15 @@ static void maybe_finish_shutdown(grpc_exec_ctx *exec_ctx, } } -static void server_on_recv_initial_metadata(grpc_exec_ctx *exec_ctx, void *ptr, - grpc_error *error) { - grpc_call_element *elem = (grpc_call_element *)ptr; - call_data *calld = (call_data *)elem->call_data; +static void server_on_recv_initial_metadata(grpc_exec_ctx* exec_ctx, void* ptr, + grpc_error* error) { + grpc_call_element* elem = (grpc_call_element*)ptr; + call_data* calld = (call_data*)elem->call_data; grpc_millis op_deadline; if (error == GRPC_ERROR_NONE) { - GPR_ASSERT(calld->recv_initial_metadata->idx.named.path != NULL); - GPR_ASSERT(calld->recv_initial_metadata->idx.named.authority != NULL); + GPR_ASSERT(calld->recv_initial_metadata->idx.named.path != nullptr); + GPR_ASSERT(calld->recv_initial_metadata->idx.named.authority != nullptr); calld->path = grpc_slice_ref_internal( GRPC_MDVALUE(calld->recv_initial_metadata->idx.named.path->md)); calld->host = grpc_slice_ref_internal( @@ -767,7 +743,7 @@ static void server_on_recv_initial_metadata(grpc_exec_ctx *exec_ctx, void *ptr, if (calld->host_set && calld->path_set) { /* do nothing */ } else { - grpc_error *src_error = error; + grpc_error* src_error = error; error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "Missing :authority or :path", &error, 1); GRPC_ERROR_UNREF(src_error); @@ -776,12 +752,12 @@ static void server_on_recv_initial_metadata(grpc_exec_ctx *exec_ctx, void *ptr, GRPC_CLOSURE_RUN(exec_ctx, calld->on_done_recv_initial_metadata, error); } -static void server_mutate_op(grpc_call_element *elem, - grpc_transport_stream_op_batch *op) { - call_data *calld = (call_data *)elem->call_data; +static void server_mutate_op(grpc_call_element* elem, + grpc_transport_stream_op_batch* op) { + call_data* calld = (call_data*)elem->call_data; if (op->recv_initial_metadata) { - GPR_ASSERT(op->payload->recv_initial_metadata.recv_flags == NULL); + GPR_ASSERT(op->payload->recv_initial_metadata.recv_flags == nullptr); calld->recv_initial_metadata = op->payload->recv_initial_metadata.recv_initial_metadata; calld->on_done_recv_initial_metadata = @@ -794,58 +770,51 @@ static void server_mutate_op(grpc_call_element *elem, } static void server_start_transport_stream_op_batch( - grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - grpc_transport_stream_op_batch *op) { + grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + grpc_transport_stream_op_batch* op) { server_mutate_op(elem, op); grpc_call_next_op(exec_ctx, elem, op); } -static void got_initial_metadata(grpc_exec_ctx *exec_ctx, void *ptr, - grpc_error *error) { - grpc_call_element *elem = (grpc_call_element *)ptr; - call_data *calld = (call_data *)elem->call_data; +static void got_initial_metadata(grpc_exec_ctx* exec_ctx, void* ptr, + grpc_error* error) { + grpc_call_element* elem = (grpc_call_element*)ptr; + call_data* calld = (call_data*)elem->call_data; if (error == GRPC_ERROR_NONE) { start_new_rpc(exec_ctx, elem); } else { - gpr_mu_lock(&calld->mu_state); - if (calld->state == NOT_STARTED) { - calld->state = ZOMBIED; - gpr_mu_unlock(&calld->mu_state); + if (gpr_atm_full_cas(&calld->state, NOT_STARTED, ZOMBIED)) { GRPC_CLOSURE_INIT(&calld->kill_zombie_closure, kill_zombie, elem, grpc_schedule_on_exec_ctx); GRPC_CLOSURE_SCHED(exec_ctx, &calld->kill_zombie_closure, GRPC_ERROR_NONE); - } else if (calld->state == PENDING) { - calld->state = ZOMBIED; - gpr_mu_unlock(&calld->mu_state); + } else if (gpr_atm_full_cas(&calld->state, PENDING, ZOMBIED)) { /* zombied call will be destroyed when it's removed from the pending queue... later */ - } else { - gpr_mu_unlock(&calld->mu_state); } } } -static void accept_stream(grpc_exec_ctx *exec_ctx, void *cd, - grpc_transport *transport, - const void *transport_server_data) { - channel_data *chand = (channel_data *)cd; +static void accept_stream(grpc_exec_ctx* exec_ctx, void* cd, + grpc_transport* transport, + const void* transport_server_data) { + channel_data* chand = (channel_data*)cd; /* create a call */ grpc_call_create_args args; memset(&args, 0, sizeof(args)); args.channel = chand->channel; args.server_transport_data = transport_server_data; args.send_deadline = GRPC_MILLIS_INF_FUTURE; - grpc_call *call; - grpc_error *error = grpc_call_create(exec_ctx, &args, &call); - grpc_call_element *elem = + grpc_call* call; + grpc_error* error = grpc_call_create(exec_ctx, &args, &call); + grpc_call_element* elem = grpc_call_stack_element(grpc_call_get_call_stack(call), 0); if (error != GRPC_ERROR_NONE) { got_initial_metadata(exec_ctx, elem, error); GRPC_ERROR_UNREF(error); return; } - call_data *calld = (call_data *)elem->call_data; + call_data* calld = (call_data*)elem->call_data; grpc_op op; memset(&op, 0, sizeof(op)); op.op = GRPC_OP_RECV_INITIAL_METADATA; @@ -857,13 +826,13 @@ static void accept_stream(grpc_exec_ctx *exec_ctx, void *cd, &calld->got_initial_metadata); } -static void channel_connectivity_changed(grpc_exec_ctx *exec_ctx, void *cd, - grpc_error *error) { - channel_data *chand = (channel_data *)cd; - grpc_server *server = chand->server; +static void channel_connectivity_changed(grpc_exec_ctx* exec_ctx, void* cd, + grpc_error* error) { + channel_data* chand = (channel_data*)cd; + grpc_server* server = chand->server; if (chand->connectivity_state != GRPC_CHANNEL_SHUTDOWN) { - grpc_transport_op *op = grpc_make_transport_op(NULL); - op->on_connectivity_state_change = &chand->channel_connectivity_changed, + grpc_transport_op* op = grpc_make_transport_op(nullptr); + op->on_connectivity_state_change = &chand->channel_connectivity_changed; op->connectivity_state = &chand->connectivity_state; grpc_channel_next_op(exec_ctx, grpc_channel_stack_element( @@ -877,15 +846,14 @@ static void channel_connectivity_changed(grpc_exec_ctx *exec_ctx, void *cd, } } -static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - const grpc_call_element_args *args) { - call_data *calld = (call_data *)elem->call_data; - channel_data *chand = (channel_data *)elem->channel_data; +static grpc_error* init_call_elem(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + const grpc_call_element_args* args) { + call_data* calld = (call_data*)elem->call_data; + channel_data* chand = (channel_data*)elem->channel_data; memset(calld, 0, sizeof(call_data)); calld->deadline = GRPC_MILLIS_INF_FUTURE; calld->call = grpc_call_from_top_element(elem); - gpr_mu_init(&calld->mu_state); GRPC_CLOSURE_INIT(&calld->server_on_recv_initial_metadata, server_on_recv_initial_metadata, elem, @@ -895,11 +863,11 @@ static grpc_error *init_call_elem(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static void destroy_call_elem(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - const grpc_call_final_info *final_info, - grpc_closure *ignored) { - channel_data *chand = (channel_data *)elem->channel_data; - call_data *calld = (call_data *)elem->call_data; +static void destroy_call_elem(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + const grpc_call_final_info* final_info, + grpc_closure* ignored) { + channel_data* chand = (channel_data*)elem->channel_data; + call_data* calld = (call_data*)elem->call_data; GPR_ASSERT(calld->state != PENDING); @@ -912,21 +880,19 @@ static void destroy_call_elem(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, grpc_metadata_array_destroy(&calld->initial_metadata); grpc_byte_buffer_destroy(calld->payload); - gpr_mu_destroy(&calld->mu_state); - server_unref(exec_ctx, chand->server); } -static grpc_error *init_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_channel_element_args *args) { - channel_data *chand = (channel_data *)elem->channel_data; +static grpc_error* init_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_channel_element_args* args) { + channel_data* chand = (channel_data*)elem->channel_data; GPR_ASSERT(args->is_first); GPR_ASSERT(!args->is_last); - chand->server = NULL; - chand->channel = NULL; + chand->server = nullptr; + chand->channel = nullptr; chand->next = chand->prev = chand; - chand->registered_methods = NULL; + chand->registered_methods = nullptr; chand->connectivity_state = GRPC_CHANNEL_IDLE; GRPC_CLOSURE_INIT(&chand->channel_connectivity_changed, channel_connectivity_changed, chand, @@ -934,10 +900,10 @@ static grpc_error *init_channel_elem(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static void destroy_channel_elem(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem) { +static void destroy_channel_elem(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem) { size_t i; - channel_data *chand = (channel_data *)elem->channel_data; + channel_data* chand = (channel_data*)elem->channel_data; if (chand->registered_methods) { for (i = 0; i < chand->registered_method_slots; i++) { grpc_slice_unref_internal(exec_ctx, chand->registered_methods[i].method); @@ -972,9 +938,9 @@ const grpc_channel_filter grpc_server_top_filter = { "server", }; -static void register_completion_queue(grpc_server *server, - grpc_completion_queue *cq, - void *reserved) { +static void register_completion_queue(grpc_server* server, + grpc_completion_queue* cq, + void* reserved) { size_t i, n; GPR_ASSERT(!reserved); for (i = 0; i < server->cq_count; i++) { @@ -983,14 +949,14 @@ static void register_completion_queue(grpc_server *server, GRPC_CQ_INTERNAL_REF(cq, "server"); n = server->cq_count++; - server->cqs = (grpc_completion_queue **)gpr_realloc( - server->cqs, server->cq_count * sizeof(grpc_completion_queue *)); + server->cqs = (grpc_completion_queue**)gpr_realloc( + server->cqs, server->cq_count * sizeof(grpc_completion_queue*)); server->cqs[n] = cq; } -void grpc_server_register_completion_queue(grpc_server *server, - grpc_completion_queue *cq, - void *reserved) { +void grpc_server_register_completion_queue(grpc_server* server, + grpc_completion_queue* cq, + void* reserved) { GRPC_API_TRACE( "grpc_server_register_completion_queue(server=%p, cq=%p, reserved=%p)", 3, (server, cq, reserved)); @@ -1006,10 +972,10 @@ void grpc_server_register_completion_queue(grpc_server *server, register_completion_queue(server, cq, reserved); } -grpc_server *grpc_server_create(const grpc_channel_args *args, void *reserved) { +grpc_server* grpc_server_create(const grpc_channel_args* args, void* reserved) { GRPC_API_TRACE("grpc_server_create(%p, %p)", 2, (args, reserved)); - grpc_server *server = (grpc_server *)gpr_zalloc(sizeof(grpc_server)); + grpc_server* server = (grpc_server*)gpr_zalloc(sizeof(grpc_server)); gpr_mu_init(&server->mu_global); gpr_mu_init(&server->mu_call); @@ -1020,25 +986,23 @@ grpc_server *grpc_server_create(const grpc_channel_args *args, void *reserved) { server->root_channel_data.next = server->root_channel_data.prev = &server->root_channel_data; - /* TODO(ctiller): expose a channel_arg for this */ - server->max_requested_calls_per_cq = 32768; server->channel_args = grpc_channel_args_copy(args); return server; } -static int streq(const char *a, const char *b) { - if (a == NULL && b == NULL) return 1; - if (a == NULL) return 0; - if (b == NULL) return 0; +static int streq(const char* a, const char* b) { + if (a == nullptr && b == nullptr) return 1; + if (a == nullptr) return 0; + if (b == nullptr) return 0; return 0 == strcmp(a, b); } -void *grpc_server_register_method( - grpc_server *server, const char *method, const char *host, +void* grpc_server_register_method( + grpc_server* server, const char* method, const char* host, grpc_server_register_method_payload_handling payload_handling, uint32_t flags) { - registered_method *m; + registered_method* m; GRPC_API_TRACE( "grpc_server_register_method(server=%p, method=%s, host=%s, " "flags=0x%08x)", @@ -1046,21 +1010,21 @@ void *grpc_server_register_method( if (!method) { gpr_log(GPR_ERROR, "grpc_server_register_method method string cannot be NULL"); - return NULL; + return nullptr; } for (m = server->registered_methods; m; m = m->next) { if (streq(m->method, method) && streq(m->host, host)) { gpr_log(GPR_ERROR, "duplicate registration for %s@%s", method, host ? host : "*"); - return NULL; + return nullptr; } } if ((flags & ~GRPC_INITIAL_METADATA_USED_MASK) != 0) { gpr_log(GPR_ERROR, "grpc_server_register_method invalid flags 0x%08x", flags); - return NULL; + return nullptr; } - m = (registered_method *)gpr_zalloc(sizeof(registered_method)); + m = (registered_method*)gpr_zalloc(sizeof(registered_method)); m->method = gpr_strdup(method); m->host = gpr_strdup(host); m->next = server->registered_methods; @@ -1070,10 +1034,10 @@ void *grpc_server_register_method( return m; } -static void start_listeners(grpc_exec_ctx *exec_ctx, void *s, - grpc_error *error) { - grpc_server *server = (grpc_server *)s; - for (listener *l = server->listeners; l; l = l->next) { +static void start_listeners(grpc_exec_ctx* exec_ctx, void* s, + grpc_error* error) { + grpc_server* server = (grpc_server*)s; + for (listener* l = server->listeners; l; l = l->next) { l->start(exec_ctx, server, l->arg, server->pollsets, server->pollset_count); } @@ -1085,7 +1049,7 @@ static void start_listeners(grpc_exec_ctx *exec_ctx, void *s, server_unref(exec_ctx, server); } -void grpc_server_start(grpc_server *server) { +void grpc_server_start(grpc_server* server) { size_t i; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; @@ -1094,30 +1058,16 @@ void grpc_server_start(grpc_server *server) { server->started = true; server->pollset_count = 0; server->pollsets = - (grpc_pollset **)gpr_malloc(sizeof(grpc_pollset *) * server->cq_count); - server->request_freelist_per_cq = (gpr_stack_lockfree **)gpr_malloc( - sizeof(*server->request_freelist_per_cq) * server->cq_count); - server->requested_calls_per_cq = (requested_call **)gpr_malloc( - sizeof(*server->requested_calls_per_cq) * server->cq_count); + (grpc_pollset**)gpr_malloc(sizeof(grpc_pollset*) * server->cq_count); for (i = 0; i < server->cq_count; i++) { if (grpc_cq_can_listen(server->cqs[i])) { server->pollsets[server->pollset_count++] = grpc_cq_pollset(server->cqs[i]); } - server->request_freelist_per_cq[i] = - gpr_stack_lockfree_create((size_t)server->max_requested_calls_per_cq); - for (int j = 0; j < server->max_requested_calls_per_cq; j++) { - gpr_stack_lockfree_push(server->request_freelist_per_cq[i], j); - } - server->requested_calls_per_cq[i] = (requested_call *)gpr_malloc( - (size_t)server->max_requested_calls_per_cq * - sizeof(*server->requested_calls_per_cq[i])); } - request_matcher_init(&server->unregistered_request_matcher, - (size_t)server->max_requested_calls_per_cq, server); - for (registered_method *rm = server->registered_methods; rm; rm = rm->next) { - request_matcher_init(&rm->matcher, - (size_t)server->max_requested_calls_per_cq, server); + request_matcher_init(&server->unregistered_request_matcher, server); + for (registered_method* rm = server->registered_methods; rm; rm = rm->next) { + request_matcher_init(&rm->matcher, server); } server_ref(server); @@ -1131,31 +1081,31 @@ void grpc_server_start(grpc_server *server) { grpc_exec_ctx_finish(&exec_ctx); } -void grpc_server_get_pollsets(grpc_server *server, grpc_pollset ***pollsets, - size_t *pollset_count) { +void grpc_server_get_pollsets(grpc_server* server, grpc_pollset*** pollsets, + size_t* pollset_count) { *pollset_count = server->pollset_count; *pollsets = server->pollsets; } -void grpc_server_setup_transport(grpc_exec_ctx *exec_ctx, grpc_server *s, - grpc_transport *transport, - grpc_pollset *accepting_pollset, - const grpc_channel_args *args) { +void grpc_server_setup_transport(grpc_exec_ctx* exec_ctx, grpc_server* s, + grpc_transport* transport, + grpc_pollset* accepting_pollset, + const grpc_channel_args* args) { size_t num_registered_methods; size_t alloc; - registered_method *rm; - channel_registered_method *crm; - grpc_channel *channel; - channel_data *chand; + registered_method* rm; + channel_registered_method* crm; + grpc_channel* channel; + channel_data* chand; uint32_t hash; size_t slots; uint32_t probes; uint32_t max_probes = 0; - grpc_transport_op *op = NULL; + grpc_transport_op* op = nullptr; - channel = - grpc_channel_create(exec_ctx, NULL, args, GRPC_SERVER_CHANNEL, transport); - chand = (channel_data *)grpc_channel_stack_element( + channel = grpc_channel_create(exec_ctx, nullptr, args, GRPC_SERVER_CHANNEL, + transport); + chand = (channel_data*)grpc_channel_stack_element( grpc_channel_get_channel_stack(channel), 0) ->channel_data; chand->server = s; @@ -1181,12 +1131,12 @@ void grpc_server_setup_transport(grpc_exec_ctx *exec_ctx, grpc_server *s, if (num_registered_methods > 0) { slots = 2 * num_registered_methods; alloc = sizeof(channel_registered_method) * slots; - chand->registered_methods = (channel_registered_method *)gpr_zalloc(alloc); + chand->registered_methods = (channel_registered_method*)gpr_zalloc(alloc); for (rm = s->registered_methods; rm; rm = rm->next) { grpc_slice host; bool has_host; grpc_slice method; - if (rm->host != NULL) { + if (rm->host != nullptr) { host = grpc_slice_intern(grpc_slice_from_static_string(rm->host)); has_host = true; } else { @@ -1196,7 +1146,7 @@ void grpc_server_setup_transport(grpc_exec_ctx *exec_ctx, grpc_server *s, hash = GRPC_MDSTR_KV_HASH(has_host ? grpc_slice_hash(host) : 0, grpc_slice_hash(method)); for (probes = 0; chand->registered_methods[(hash + probes) % slots] - .server_registered_method != NULL; + .server_registered_method != nullptr; probes++) ; if (probes > max_probes) max_probes = probes; @@ -1221,7 +1171,7 @@ void grpc_server_setup_transport(grpc_exec_ctx *exec_ctx, grpc_server *s, gpr_mu_unlock(&s->mu_global); GRPC_CHANNEL_INTERNAL_REF(channel, "connectivity"); - op = grpc_make_transport_op(NULL); + op = grpc_make_transport_op(nullptr); op->set_accept_stream = true; op->set_accept_stream_fn = accept_stream; op->set_accept_stream_user_data = chand; @@ -1234,25 +1184,25 @@ void grpc_server_setup_transport(grpc_exec_ctx *exec_ctx, grpc_server *s, grpc_transport_perform_op(exec_ctx, transport, op); } -void done_published_shutdown(grpc_exec_ctx *exec_ctx, void *done_arg, - grpc_cq_completion *storage) { +void done_published_shutdown(grpc_exec_ctx* exec_ctx, void* done_arg, + grpc_cq_completion* storage) { (void)done_arg; gpr_free(storage); } -static void listener_destroy_done(grpc_exec_ctx *exec_ctx, void *s, - grpc_error *error) { - grpc_server *server = (grpc_server *)s; +static void listener_destroy_done(grpc_exec_ctx* exec_ctx, void* s, + grpc_error* error) { + grpc_server* server = (grpc_server*)s; gpr_mu_lock(&server->mu_global); server->listeners_destroyed++; maybe_finish_shutdown(exec_ctx, server); gpr_mu_unlock(&server->mu_global); } -void grpc_server_shutdown_and_notify(grpc_server *server, - grpc_completion_queue *cq, void *tag) { - listener *l; - shutdown_tag *sdt; +void grpc_server_shutdown_and_notify(grpc_server* server, + grpc_completion_queue* cq, void* tag) { + listener* l; + shutdown_tag* sdt; channel_broadcaster broadcaster; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; @@ -1269,13 +1219,13 @@ void grpc_server_shutdown_and_notify(grpc_server *server, /* stay locked, and gather up some stuff to do */ GPR_ASSERT(grpc_cq_begin_op(cq, tag)); if (server->shutdown_published) { - grpc_cq_end_op( - &exec_ctx, cq, tag, GRPC_ERROR_NONE, done_published_shutdown, NULL, - (grpc_cq_completion *)gpr_malloc(sizeof(grpc_cq_completion))); + grpc_cq_end_op(&exec_ctx, cq, tag, GRPC_ERROR_NONE, done_published_shutdown, + nullptr, + (grpc_cq_completion*)gpr_malloc(sizeof(grpc_cq_completion))); gpr_mu_unlock(&server->mu_global); goto done; } - server->shutdown_tags = (shutdown_tag *)gpr_realloc( + server->shutdown_tags = (shutdown_tag*)gpr_realloc( server->shutdown_tags, sizeof(shutdown_tag) * (server->num_shutdown_tags + 1)); sdt = &server->shutdown_tags[server->num_shutdown_tags++]; @@ -1316,7 +1266,7 @@ done: grpc_exec_ctx_finish(&exec_ctx); } -void grpc_server_cancel_all_calls(grpc_server *server) { +void grpc_server_cancel_all_calls(grpc_server* server) { channel_broadcaster broadcaster; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; @@ -1332,8 +1282,8 @@ void grpc_server_cancel_all_calls(grpc_server *server) { grpc_exec_ctx_finish(&exec_ctx); } -void grpc_server_destroy(grpc_server *server) { - listener *l; +void grpc_server_destroy(grpc_server* server) { + listener* l; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GRPC_API_TRACE("grpc_server_destroy(server=%p)", 1, (server)); @@ -1355,12 +1305,12 @@ void grpc_server_destroy(grpc_server *server) { } void grpc_server_add_listener( - grpc_exec_ctx *exec_ctx, grpc_server *server, void *arg, - void (*start)(grpc_exec_ctx *exec_ctx, grpc_server *server, void *arg, - grpc_pollset **pollsets, size_t pollset_count), - void (*destroy)(grpc_exec_ctx *exec_ctx, grpc_server *server, void *arg, - grpc_closure *on_done)) { - listener *l = (listener *)gpr_malloc(sizeof(listener)); + grpc_exec_ctx* exec_ctx, grpc_server* server, void* arg, + void (*start)(grpc_exec_ctx* exec_ctx, grpc_server* server, void* arg, + grpc_pollset** pollsets, size_t pollset_count), + void (*destroy)(grpc_exec_ctx* exec_ctx, grpc_server* server, void* arg, + grpc_closure* on_done)) { + listener* l = (listener*)gpr_malloc(sizeof(listener)); l->arg = arg; l->start = start; l->destroy = destroy; @@ -1368,26 +1318,16 @@ void grpc_server_add_listener( server->listeners = l; } -static grpc_call_error queue_call_request(grpc_exec_ctx *exec_ctx, - grpc_server *server, size_t cq_idx, - requested_call *rc) { - call_data *calld = NULL; - request_matcher *rm = NULL; - int request_id; +static grpc_call_error queue_call_request(grpc_exec_ctx* exec_ctx, + grpc_server* server, size_t cq_idx, + requested_call* rc) { + call_data* calld = nullptr; + request_matcher* rm = nullptr; if (gpr_atm_acq_load(&server->shutdown_flag)) { fail_call(exec_ctx, server, cq_idx, rc, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Server Shutdown")); return GRPC_CALL_OK; } - request_id = gpr_stack_lockfree_pop(server->request_freelist_per_cq[cq_idx]); - if (request_id == -1) { - /* out of request ids: just fail this one */ - fail_call(exec_ctx, server, cq_idx, rc, - grpc_error_set_int( - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Out of request ids"), - GRPC_ERROR_INT_LIMIT, server->max_requested_calls_per_cq)); - return GRPC_CALL_OK; - } switch (rc->type) { case BATCH_CALL: rm = &server->unregistered_request_matcher; @@ -1396,20 +1336,17 @@ static grpc_call_error queue_call_request(grpc_exec_ctx *exec_ctx, rm = &rc->data.registered.method->matcher; break; } - server->requested_calls_per_cq[cq_idx][request_id] = *rc; - gpr_free(rc); - if (gpr_stack_lockfree_push(rm->requests_per_cq[cq_idx], request_id)) { + if (gpr_locked_mpscq_push(&rm->requests_per_cq[cq_idx], &rc->request_link)) { /* this was the first queued request: we need to lock and start matching calls */ gpr_mu_lock(&server->mu_call); - while ((calld = rm->pending_head) != NULL) { - request_id = gpr_stack_lockfree_pop(rm->requests_per_cq[cq_idx]); - if (request_id == -1) break; + while ((calld = rm->pending_head) != nullptr) { + rc = (requested_call*)gpr_locked_mpscq_pop(&rm->requests_per_cq[cq_idx]); + if (rc == nullptr) break; rm->pending_head = calld->pending_next; gpr_mu_unlock(&server->mu_call); - gpr_mu_lock(&calld->mu_state); - if (calld->state == ZOMBIED) { - gpr_mu_unlock(&calld->mu_state); + if (!gpr_atm_full_cas(&calld->state, PENDING, ACTIVATED)) { + // Zombied Call GRPC_CLOSURE_INIT( &calld->kill_zombie_closure, kill_zombie, grpc_call_stack_element(grpc_call_get_call_stack(calld->call), 0), @@ -1417,11 +1354,7 @@ static grpc_call_error queue_call_request(grpc_exec_ctx *exec_ctx, GRPC_CLOSURE_SCHED(exec_ctx, &calld->kill_zombie_closure, GRPC_ERROR_NONE); } else { - GPR_ASSERT(calld->state == PENDING); - calld->state = ACTIVATED; - gpr_mu_unlock(&calld->mu_state); - publish_call(exec_ctx, server, calld, cq_idx, - &server->requested_calls_per_cq[cq_idx][request_id]); + publish_call(exec_ctx, server, calld, cq_idx, rc); } gpr_mu_lock(&server->mu_call); } @@ -1431,20 +1364,21 @@ static grpc_call_error queue_call_request(grpc_exec_ctx *exec_ctx, } grpc_call_error grpc_server_request_call( - grpc_server *server, grpc_call **call, grpc_call_details *details, - grpc_metadata_array *initial_metadata, - grpc_completion_queue *cq_bound_to_call, - grpc_completion_queue *cq_for_notification, void *tag) { + grpc_server* server, grpc_call** call, grpc_call_details* details, + grpc_metadata_array* initial_metadata, + grpc_completion_queue* cq_bound_to_call, + grpc_completion_queue* cq_for_notification, void* tag) { grpc_call_error error; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - requested_call *rc = (requested_call *)gpr_malloc(sizeof(*rc)); + requested_call* rc = (requested_call*)gpr_malloc(sizeof(*rc)); GRPC_STATS_INC_SERVER_REQUESTED_CALLS(&exec_ctx); GRPC_API_TRACE( "grpc_server_request_call(" "server=%p, call=%p, details=%p, initial_metadata=%p, " "cq_bound_to_call=%p, cq_for_notification=%p, tag=%p)", - 7, (server, call, details, initial_metadata, cq_bound_to_call, - cq_for_notification, tag)); + 7, + (server, call, details, initial_metadata, cq_bound_to_call, + cq_for_notification, tag)); size_t cq_idx; for (cq_idx = 0; cq_idx < server->cq_count; cq_idx++) { if (server->cqs[cq_idx] == cq_for_notification) { @@ -1461,7 +1395,7 @@ grpc_call_error grpc_server_request_call( error = GRPC_CALL_ERROR_COMPLETION_QUEUE_SHUTDOWN; goto done; } - details->reserved = NULL; + details->reserved = nullptr; rc->cq_idx = cq_idx; rc->type = BATCH_CALL; rc->server = server; @@ -1477,22 +1411,23 @@ done: } grpc_call_error grpc_server_request_registered_call( - grpc_server *server, void *rmp, grpc_call **call, gpr_timespec *deadline, - grpc_metadata_array *initial_metadata, grpc_byte_buffer **optional_payload, - grpc_completion_queue *cq_bound_to_call, - grpc_completion_queue *cq_for_notification, void *tag) { + grpc_server* server, void* rmp, grpc_call** call, gpr_timespec* deadline, + grpc_metadata_array* initial_metadata, grpc_byte_buffer** optional_payload, + grpc_completion_queue* cq_bound_to_call, + grpc_completion_queue* cq_for_notification, void* tag) { grpc_call_error error; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - requested_call *rc = (requested_call *)gpr_malloc(sizeof(*rc)); - registered_method *rm = (registered_method *)rmp; + requested_call* rc = (requested_call*)gpr_malloc(sizeof(*rc)); + registered_method* rm = (registered_method*)rmp; GRPC_STATS_INC_SERVER_REQUESTED_CALLS(&exec_ctx); GRPC_API_TRACE( "grpc_server_request_registered_call(" "server=%p, rmp=%p, call=%p, deadline=%p, initial_metadata=%p, " "optional_payload=%p, cq_bound_to_call=%p, cq_for_notification=%p, " "tag=%p)", - 9, (server, rmp, call, deadline, initial_metadata, optional_payload, - cq_bound_to_call, cq_for_notification, tag)); + 9, + (server, rmp, call, deadline, initial_metadata, optional_payload, + cq_bound_to_call, cq_for_notification, tag)); size_t cq_idx; for (cq_idx = 0; cq_idx < server->cq_count; cq_idx++) { @@ -1505,7 +1440,7 @@ grpc_call_error grpc_server_request_registered_call( error = GRPC_CALL_ERROR_NOT_SERVER_COMPLETION_QUEUE; goto done; } - if ((optional_payload == NULL) != + if ((optional_payload == nullptr) != (rm->payload_handling == GRPC_SRM_PAYLOAD_NONE)) { gpr_free(rc); error = GRPC_CALL_ERROR_PAYLOAD_TYPE_MISMATCH; @@ -1532,22 +1467,21 @@ done: return error; } -static void fail_call(grpc_exec_ctx *exec_ctx, grpc_server *server, - size_t cq_idx, requested_call *rc, grpc_error *error) { - *rc->call = NULL; +static void fail_call(grpc_exec_ctx* exec_ctx, grpc_server* server, + size_t cq_idx, requested_call* rc, grpc_error* error) { + *rc->call = nullptr; rc->initial_metadata->count = 0; GPR_ASSERT(error != GRPC_ERROR_NONE); - server_ref(server); grpc_cq_end_op(exec_ctx, server->cqs[cq_idx], rc->tag, error, done_request_event, rc, &rc->completion); } -const grpc_channel_args *grpc_server_get_channel_args(grpc_server *server) { +const grpc_channel_args* grpc_server_get_channel_args(grpc_server* server) { return server->channel_args; } -int grpc_server_has_open_connections(grpc_server *server) { +int grpc_server_has_open_connections(grpc_server* server) { int r; gpr_mu_lock(&server->mu_global); r = server->root_channel_data.next != &server->root_channel_data; diff --git a/src/core/lib/surface/server.h b/src/core/lib/surface/server.h index 375eab4a048..d7ec025d954 100644 --- a/src/core/lib/surface/server.h +++ b/src/core/lib/surface/server.h @@ -24,42 +24,34 @@ #include "src/core/lib/debug/trace.h" #include "src/core/lib/transport/transport.h" -#ifdef __cplusplus -extern "C" { -#endif - extern const grpc_channel_filter grpc_server_top_filter; /** Lightweight tracing of server channel state */ -extern grpc_tracer_flag grpc_server_channel_trace; +extern grpc_core::TraceFlag grpc_server_channel_trace; /* Add a listener to the server: when the server starts, it will call start, and when it shuts down, it will call destroy */ void grpc_server_add_listener( - grpc_exec_ctx *exec_ctx, grpc_server *server, void *listener, - void (*start)(grpc_exec_ctx *exec_ctx, grpc_server *server, void *arg, - grpc_pollset **pollsets, size_t npollsets), - void (*destroy)(grpc_exec_ctx *exec_ctx, grpc_server *server, void *arg, - grpc_closure *on_done)); + grpc_exec_ctx* exec_ctx, grpc_server* server, void* listener, + void (*start)(grpc_exec_ctx* exec_ctx, grpc_server* server, void* arg, + grpc_pollset** pollsets, size_t npollsets), + void (*destroy)(grpc_exec_ctx* exec_ctx, grpc_server* server, void* arg, + grpc_closure* on_done)); /* Setup a transport - creates a channel stack, binds the transport to the server */ -void grpc_server_setup_transport(grpc_exec_ctx *exec_ctx, grpc_server *server, - grpc_transport *transport, - grpc_pollset *accepting_pollset, - const grpc_channel_args *args); +void grpc_server_setup_transport(grpc_exec_ctx* exec_ctx, grpc_server* server, + grpc_transport* transport, + grpc_pollset* accepting_pollset, + const grpc_channel_args* args); -const grpc_channel_args *grpc_server_get_channel_args(grpc_server *server); +const grpc_channel_args* grpc_server_get_channel_args(grpc_server* server); -int grpc_server_has_open_connections(grpc_server *server); +int grpc_server_has_open_connections(grpc_server* server); /* Do not call this before grpc_server_start. Returns the pollsets and the * number of pollsets via 'pollsets' and 'pollset_count'. */ -void grpc_server_get_pollsets(grpc_server *server, grpc_pollset ***pollsets, - size_t *pollset_count); - -#ifdef __cplusplus -} -#endif +void grpc_server_get_pollsets(grpc_server* server, grpc_pollset*** pollsets, + size_t* pollset_count); #endif /* GRPC_CORE_LIB_SURFACE_SERVER_H */ diff --git a/src/core/lib/surface/validate_metadata.cc b/src/core/lib/surface/validate_metadata.cc index 81d07fae442..fc94ea7dbeb 100644 --- a/src/core/lib/surface/validate_metadata.cc +++ b/src/core/lib/surface/validate_metadata.cc @@ -28,17 +28,17 @@ #include "src/core/lib/slice/slice_string_helpers.h" #include "src/core/lib/surface/validate_metadata.h" -static grpc_error *conforms_to(grpc_slice slice, const uint8_t *legal_bits, - const char *err_desc) { - const uint8_t *p = GRPC_SLICE_START_PTR(slice); - const uint8_t *e = GRPC_SLICE_END_PTR(slice); +static grpc_error* conforms_to(grpc_slice slice, const uint8_t* legal_bits, + const char* err_desc) { + const uint8_t* p = GRPC_SLICE_START_PTR(slice); + const uint8_t* e = GRPC_SLICE_END_PTR(slice); for (; p != e; p++) { int idx = *p; int byte = idx / 8; int bit = idx % 8; if ((legal_bits[byte] & (1 << bit)) == 0) { - char *dump = grpc_dump_slice(slice, GPR_DUMP_HEX | GPR_DUMP_ASCII); - grpc_error *error = grpc_error_set_str( + char* dump = grpc_dump_slice(slice, GPR_DUMP_HEX | GPR_DUMP_ASCII); + grpc_error* error = grpc_error_set_str( grpc_error_set_int(GRPC_ERROR_CREATE_FROM_COPIED_STRING(err_desc), GRPC_ERROR_INT_OFFSET, p - GRPC_SLICE_START_PTR(slice)), @@ -50,13 +50,13 @@ static grpc_error *conforms_to(grpc_slice slice, const uint8_t *legal_bits, return GRPC_ERROR_NONE; } -static int error2int(grpc_error *error) { +static int error2int(grpc_error* error) { int r = (error == GRPC_ERROR_NONE); GRPC_ERROR_UNREF(error); return r; } -grpc_error *grpc_validate_header_key_is_legal(grpc_slice slice) { +grpc_error* grpc_validate_header_key_is_legal(grpc_slice slice) { static const uint8_t legal_header_bits[256 / 8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xff, 0x03, 0x00, 0x00, 0x00, 0x80, 0xfe, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -76,7 +76,7 @@ int grpc_header_key_is_legal(grpc_slice slice) { return error2int(grpc_validate_header_key_is_legal(slice)); } -grpc_error *grpc_validate_header_nonbin_value_is_legal(grpc_slice slice) { +grpc_error* grpc_validate_header_nonbin_value_is_legal(grpc_slice slice) { static const uint8_t legal_header_bits[256 / 8] = { 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, diff --git a/src/core/lib/surface/validate_metadata.h b/src/core/lib/surface/validate_metadata.h index afc8be6dfda..ff074b00b2c 100644 --- a/src/core/lib/surface/validate_metadata.h +++ b/src/core/lib/surface/validate_metadata.h @@ -22,15 +22,7 @@ #include #include "src/core/lib/iomgr/error.h" -#ifdef __cplusplus -extern "C" { -#endif - -grpc_error *grpc_validate_header_key_is_legal(grpc_slice slice); -grpc_error *grpc_validate_header_nonbin_value_is_legal(grpc_slice slice); - -#ifdef __cplusplus -} -#endif +grpc_error* grpc_validate_header_key_is_legal(grpc_slice slice); +grpc_error* grpc_validate_header_nonbin_value_is_legal(grpc_slice slice); #endif /* GRPC_CORE_LIB_SURFACE_VALIDATE_METADATA_H */ diff --git a/src/core/lib/surface/version.cc b/src/core/lib/surface/version.cc index 6cb8e7e1a0d..7d36c6c9e1d 100644 --- a/src/core/lib/surface/version.cc +++ b/src/core/lib/surface/version.cc @@ -21,6 +21,6 @@ #include -const char *grpc_version_string(void) { return "5.0.0-dev"; } +const char* grpc_version_string(void) { return "5.0.0-dev"; } -const char *grpc_g_stands_for(void) { return "generous"; } +const char* grpc_g_stands_for(void) { return "glossy"; } diff --git a/src/core/lib/transport/bdp_estimator.cc b/src/core/lib/transport/bdp_estimator.cc index f1597014b17..bb0e583045a 100644 --- a/src/core/lib/transport/bdp_estimator.cc +++ b/src/core/lib/transport/bdp_estimator.cc @@ -23,12 +23,11 @@ #include -grpc_tracer_flag grpc_bdp_estimator_trace = - GRPC_TRACER_INITIALIZER(false, "bdp_estimator"); +grpc_core::TraceFlag grpc_bdp_estimator_trace(false, "bdp_estimator"); namespace grpc_core { -BdpEstimator::BdpEstimator(const char *name) +BdpEstimator::BdpEstimator(const char* name) : ping_state_(PingState::UNSCHEDULED), accumulator_(0), estimate_(65536), @@ -38,15 +37,16 @@ BdpEstimator::BdpEstimator(const char *name) bw_est_(0), name_(name) {} -grpc_millis BdpEstimator::CompletePing(grpc_exec_ctx *exec_ctx) { +grpc_millis BdpEstimator::CompletePing(grpc_exec_ctx* exec_ctx) { gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC); gpr_timespec dt_ts = gpr_time_sub(now, ping_start_time_); double dt = (double)dt_ts.tv_sec + 1e-9 * (double)dt_ts.tv_nsec; double bw = dt > 0 ? ((double)accumulator_ / dt) : 0; int start_inter_ping_delay = inter_ping_delay_; - if (GRPC_TRACER_ON(grpc_bdp_estimator_trace)) { - gpr_log(GPR_DEBUG, "bdp[%s]:complete acc=%" PRId64 " est=%" PRId64 - " dt=%lf bw=%lfMbs bw_est=%lfMbs", + if (grpc_bdp_estimator_trace.enabled()) { + gpr_log(GPR_DEBUG, + "bdp[%s]:complete acc=%" PRId64 " est=%" PRId64 + " dt=%lf bw=%lfMbs bw_est=%lfMbs", name_, accumulator_, estimate_, dt, bw / 125000.0, bw_est_ / 125000.0); } @@ -54,7 +54,7 @@ grpc_millis BdpEstimator::CompletePing(grpc_exec_ctx *exec_ctx) { if (accumulator_ > 2 * estimate_ / 3 && bw > bw_est_) { estimate_ = GPR_MAX(accumulator_, estimate_ * 2); bw_est_ = bw; - if (GRPC_TRACER_ON(grpc_bdp_estimator_trace)) { + if (grpc_bdp_estimator_trace.enabled()) { gpr_log(GPR_DEBUG, "bdp[%s]: estimate increased to %" PRId64, name_, estimate_); } @@ -71,7 +71,7 @@ grpc_millis BdpEstimator::CompletePing(grpc_exec_ctx *exec_ctx) { } if (start_inter_ping_delay != inter_ping_delay_) { stable_estimate_count_ = 0; - if (GRPC_TRACER_ON(grpc_bdp_estimator_trace)) { + if (grpc_bdp_estimator_trace.enabled()) { gpr_log(GPR_DEBUG, "bdp[%s]:update_inter_time to %dms", name_, inter_ping_delay_); } diff --git a/src/core/lib/transport/bdp_estimator.h b/src/core/lib/transport/bdp_estimator.h index 750da395997..df3a86c5f17 100644 --- a/src/core/lib/transport/bdp_estimator.h +++ b/src/core/lib/transport/bdp_estimator.h @@ -31,13 +31,13 @@ #include "src/core/lib/debug/trace.h" #include "src/core/lib/iomgr/exec_ctx.h" -extern grpc_tracer_flag grpc_bdp_estimator_trace; +extern grpc_core::TraceFlag grpc_bdp_estimator_trace; namespace grpc_core { class BdpEstimator { public: - explicit BdpEstimator(const char *name); + explicit BdpEstimator(const char* name); ~BdpEstimator() {} int64_t EstimateBdp() const { return estimate_; } @@ -49,7 +49,7 @@ class BdpEstimator { // grpc_bdp_estimator_add_incoming_bytes once a ping has been scheduled by a // transport (but not necessarily started) void SchedulePing() { - if (GRPC_TRACER_ON(grpc_bdp_estimator_trace)) { + if (grpc_bdp_estimator_trace.enabled()) { gpr_log(GPR_DEBUG, "bdp[%s]:sched acc=%" PRId64 " est=%" PRId64, name_, accumulator_, estimate_); } @@ -62,7 +62,7 @@ class BdpEstimator { // once // the ping is on the wire void StartPing() { - if (GRPC_TRACER_ON(grpc_bdp_estimator_trace)) { + if (grpc_bdp_estimator_trace.enabled()) { gpr_log(GPR_DEBUG, "bdp[%s]:start acc=%" PRId64 " est=%" PRId64, name_, accumulator_, estimate_); } @@ -73,7 +73,7 @@ class BdpEstimator { } // Completes a previously started ping, returns when to schedule the next one - grpc_millis CompletePing(grpc_exec_ctx *exec_ctx); + grpc_millis CompletePing(grpc_exec_ctx* exec_ctx); private: enum class PingState { UNSCHEDULED, SCHEDULED, STARTED }; @@ -86,7 +86,7 @@ class BdpEstimator { int inter_ping_delay_; int stable_estimate_count_; double bw_est_; - const char *name_; + const char* name_; }; } // namespace grpc_core diff --git a/src/core/lib/transport/byte_stream.cc b/src/core/lib/transport/byte_stream.cc index 08f61629a92..b8720250e77 100644 --- a/src/core/lib/transport/byte_stream.cc +++ b/src/core/lib/transport/byte_stream.cc @@ -25,45 +25,45 @@ #include "src/core/lib/slice/slice_internal.h" -bool grpc_byte_stream_next(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream, size_t max_size_hint, - grpc_closure *on_complete) { +bool grpc_byte_stream_next(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream, size_t max_size_hint, + grpc_closure* on_complete) { return byte_stream->vtable->next(exec_ctx, byte_stream, max_size_hint, on_complete); } -grpc_error *grpc_byte_stream_pull(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream, - grpc_slice *slice) { +grpc_error* grpc_byte_stream_pull(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream, + grpc_slice* slice) { return byte_stream->vtable->pull(exec_ctx, byte_stream, slice); } -void grpc_byte_stream_shutdown(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream, - grpc_error *error) { +void grpc_byte_stream_shutdown(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream, + grpc_error* error) { byte_stream->vtable->shutdown(exec_ctx, byte_stream, error); } -void grpc_byte_stream_destroy(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream) { +void grpc_byte_stream_destroy(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream) { byte_stream->vtable->destroy(exec_ctx, byte_stream); } // grpc_slice_buffer_stream -static bool slice_buffer_stream_next(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream, +static bool slice_buffer_stream_next(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream, size_t max_size_hint, - grpc_closure *on_complete) { - grpc_slice_buffer_stream *stream = (grpc_slice_buffer_stream *)byte_stream; + grpc_closure* on_complete) { + grpc_slice_buffer_stream* stream = (grpc_slice_buffer_stream*)byte_stream; GPR_ASSERT(stream->cursor < stream->backing_buffer->count); return true; } -static grpc_error *slice_buffer_stream_pull(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream, - grpc_slice *slice) { - grpc_slice_buffer_stream *stream = (grpc_slice_buffer_stream *)byte_stream; +static grpc_error* slice_buffer_stream_pull(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream, + grpc_slice* slice) { + grpc_slice_buffer_stream* stream = (grpc_slice_buffer_stream*)byte_stream; if (stream->shutdown_error != GRPC_ERROR_NONE) { return GRPC_ERROR_REF(stream->shutdown_error); } @@ -74,17 +74,17 @@ static grpc_error *slice_buffer_stream_pull(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static void slice_buffer_stream_shutdown(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream, - grpc_error *error) { - grpc_slice_buffer_stream *stream = (grpc_slice_buffer_stream *)byte_stream; +static void slice_buffer_stream_shutdown(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream, + grpc_error* error) { + grpc_slice_buffer_stream* stream = (grpc_slice_buffer_stream*)byte_stream; GRPC_ERROR_UNREF(stream->shutdown_error); stream->shutdown_error = error; } -static void slice_buffer_stream_destroy(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream) { - grpc_slice_buffer_stream *stream = (grpc_slice_buffer_stream *)byte_stream; +static void slice_buffer_stream_destroy(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream) { + grpc_slice_buffer_stream* stream = (grpc_slice_buffer_stream*)byte_stream; grpc_slice_buffer_reset_and_unref_internal(exec_ctx, stream->backing_buffer); GRPC_ERROR_UNREF(stream->shutdown_error); } @@ -93,8 +93,8 @@ static const grpc_byte_stream_vtable slice_buffer_stream_vtable = { slice_buffer_stream_next, slice_buffer_stream_pull, slice_buffer_stream_shutdown, slice_buffer_stream_destroy}; -void grpc_slice_buffer_stream_init(grpc_slice_buffer_stream *stream, - grpc_slice_buffer *slice_buffer, +void grpc_slice_buffer_stream_init(grpc_slice_buffer_stream* stream, + grpc_slice_buffer* slice_buffer, uint32_t flags) { GPR_ASSERT(slice_buffer->length <= UINT32_MAX); stream->base.length = (uint32_t)slice_buffer->length; @@ -107,33 +107,33 @@ void grpc_slice_buffer_stream_init(grpc_slice_buffer_stream *stream, // grpc_caching_byte_stream -void grpc_byte_stream_cache_init(grpc_byte_stream_cache *cache, - grpc_byte_stream *underlying_stream) { +void grpc_byte_stream_cache_init(grpc_byte_stream_cache* cache, + grpc_byte_stream* underlying_stream) { cache->underlying_stream = underlying_stream; grpc_slice_buffer_init(&cache->cache_buffer); } -void grpc_byte_stream_cache_destroy(grpc_exec_ctx *exec_ctx, - grpc_byte_stream_cache *cache) { +void grpc_byte_stream_cache_destroy(grpc_exec_ctx* exec_ctx, + grpc_byte_stream_cache* cache) { grpc_byte_stream_destroy(exec_ctx, cache->underlying_stream); grpc_slice_buffer_destroy_internal(exec_ctx, &cache->cache_buffer); } -static bool caching_byte_stream_next(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream, +static bool caching_byte_stream_next(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream, size_t max_size_hint, - grpc_closure *on_complete) { - grpc_caching_byte_stream *stream = (grpc_caching_byte_stream *)byte_stream; + grpc_closure* on_complete) { + grpc_caching_byte_stream* stream = (grpc_caching_byte_stream*)byte_stream; if (stream->shutdown_error != GRPC_ERROR_NONE) return true; if (stream->cursor < stream->cache->cache_buffer.count) return true; return grpc_byte_stream_next(exec_ctx, stream->cache->underlying_stream, max_size_hint, on_complete); } -static grpc_error *caching_byte_stream_pull(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream, - grpc_slice *slice) { - grpc_caching_byte_stream *stream = (grpc_caching_byte_stream *)byte_stream; +static grpc_error* caching_byte_stream_pull(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream, + grpc_slice* slice) { + grpc_caching_byte_stream* stream = (grpc_caching_byte_stream*)byte_stream; if (stream->shutdown_error != GRPC_ERROR_NONE) { return GRPC_ERROR_REF(stream->shutdown_error); } @@ -143,7 +143,7 @@ static grpc_error *caching_byte_stream_pull(grpc_exec_ctx *exec_ctx, ++stream->cursor; return GRPC_ERROR_NONE; } - grpc_error *error = + grpc_error* error = grpc_byte_stream_pull(exec_ctx, stream->cache->underlying_stream, slice); if (error == GRPC_ERROR_NONE) { ++stream->cursor; @@ -153,18 +153,18 @@ static grpc_error *caching_byte_stream_pull(grpc_exec_ctx *exec_ctx, return error; } -static void caching_byte_stream_shutdown(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream, - grpc_error *error) { - grpc_caching_byte_stream *stream = (grpc_caching_byte_stream *)byte_stream; +static void caching_byte_stream_shutdown(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream, + grpc_error* error) { + grpc_caching_byte_stream* stream = (grpc_caching_byte_stream*)byte_stream; GRPC_ERROR_UNREF(stream->shutdown_error); stream->shutdown_error = GRPC_ERROR_REF(error); grpc_byte_stream_shutdown(exec_ctx, stream->cache->underlying_stream, error); } -static void caching_byte_stream_destroy(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream) { - grpc_caching_byte_stream *stream = (grpc_caching_byte_stream *)byte_stream; +static void caching_byte_stream_destroy(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream) { + grpc_caching_byte_stream* stream = (grpc_caching_byte_stream*)byte_stream; GRPC_ERROR_UNREF(stream->shutdown_error); } @@ -172,8 +172,8 @@ static const grpc_byte_stream_vtable caching_byte_stream_vtable = { caching_byte_stream_next, caching_byte_stream_pull, caching_byte_stream_shutdown, caching_byte_stream_destroy}; -void grpc_caching_byte_stream_init(grpc_caching_byte_stream *stream, - grpc_byte_stream_cache *cache) { +void grpc_caching_byte_stream_init(grpc_caching_byte_stream* stream, + grpc_byte_stream_cache* cache) { memset(stream, 0, sizeof(*stream)); stream->base.length = cache->underlying_stream->length; stream->base.flags = cache->underlying_stream->flags; @@ -182,6 +182,6 @@ void grpc_caching_byte_stream_init(grpc_caching_byte_stream *stream, stream->shutdown_error = GRPC_ERROR_NONE; } -void grpc_caching_byte_stream_reset(grpc_caching_byte_stream *stream) { +void grpc_caching_byte_stream_reset(grpc_caching_byte_stream* stream) { stream->cursor = 0; } diff --git a/src/core/lib/transport/byte_stream.h b/src/core/lib/transport/byte_stream.h index c1d8ee543f5..6bca154cb57 100644 --- a/src/core/lib/transport/byte_stream.h +++ b/src/core/lib/transport/byte_stream.h @@ -28,26 +28,22 @@ /** Mask of all valid internal flags. */ #define GRPC_WRITE_INTERNAL_USED_MASK (GRPC_WRITE_INTERNAL_COMPRESS) -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_byte_stream grpc_byte_stream; typedef struct { - bool (*next)(grpc_exec_ctx *exec_ctx, grpc_byte_stream *byte_stream, - size_t max_size_hint, grpc_closure *on_complete); - grpc_error *(*pull)(grpc_exec_ctx *exec_ctx, grpc_byte_stream *byte_stream, - grpc_slice *slice); - void (*shutdown)(grpc_exec_ctx *exec_ctx, grpc_byte_stream *byte_stream, - grpc_error *error); - void (*destroy)(grpc_exec_ctx *exec_ctx, grpc_byte_stream *byte_stream); + bool (*next)(grpc_exec_ctx* exec_ctx, grpc_byte_stream* byte_stream, + size_t max_size_hint, grpc_closure* on_complete); + grpc_error* (*pull)(grpc_exec_ctx* exec_ctx, grpc_byte_stream* byte_stream, + grpc_slice* slice); + void (*shutdown)(grpc_exec_ctx* exec_ctx, grpc_byte_stream* byte_stream, + grpc_error* error); + void (*destroy)(grpc_exec_ctx* exec_ctx, grpc_byte_stream* byte_stream); } grpc_byte_stream_vtable; struct grpc_byte_stream { uint32_t length; uint32_t flags; - const grpc_byte_stream_vtable *vtable; + const grpc_byte_stream_vtable* vtable; }; // Returns true if the bytes are available immediately (in which case @@ -56,18 +52,18 @@ struct grpc_byte_stream { // // max_size_hint can be set as a hint as to the maximum number // of bytes that would be acceptable to read. -bool grpc_byte_stream_next(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream, size_t max_size_hint, - grpc_closure *on_complete); +bool grpc_byte_stream_next(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream, size_t max_size_hint, + grpc_closure* on_complete); // Returns the next slice in the byte stream when it is ready (indicated by // either grpc_byte_stream_next returning true or on_complete passed to // grpc_byte_stream_next is called). // // Once a slice is returned into *slice, it is owned by the caller. -grpc_error *grpc_byte_stream_pull(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream, - grpc_slice *slice); +grpc_error* grpc_byte_stream_pull(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream, + grpc_slice* slice); // Shuts down the byte stream. // @@ -76,12 +72,12 @@ grpc_error *grpc_byte_stream_pull(grpc_exec_ctx *exec_ctx, // // The next call to grpc_byte_stream_pull() (if any) will return the error // passed to grpc_byte_stream_shutdown(). -void grpc_byte_stream_shutdown(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream, - grpc_error *error); +void grpc_byte_stream_shutdown(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream, + grpc_error* error); -void grpc_byte_stream_destroy(grpc_exec_ctx *exec_ctx, - grpc_byte_stream *byte_stream); +void grpc_byte_stream_destroy(grpc_exec_ctx* exec_ctx, + grpc_byte_stream* byte_stream); // grpc_slice_buffer_stream // @@ -91,13 +87,13 @@ void grpc_byte_stream_destroy(grpc_exec_ctx *exec_ctx, typedef struct grpc_slice_buffer_stream { grpc_byte_stream base; - grpc_slice_buffer *backing_buffer; + grpc_slice_buffer* backing_buffer; size_t cursor; - grpc_error *shutdown_error; + grpc_error* shutdown_error; } grpc_slice_buffer_stream; -void grpc_slice_buffer_stream_init(grpc_slice_buffer_stream *stream, - grpc_slice_buffer *slice_buffer, +void grpc_slice_buffer_stream_init(grpc_slice_buffer_stream* stream, + grpc_slice_buffer* slice_buffer, uint32_t flags); // grpc_caching_byte_stream @@ -114,33 +110,29 @@ void grpc_slice_buffer_stream_init(grpc_slice_buffer_stream *stream, // grpc_byte_stream_cache at the same time. typedef struct { - grpc_byte_stream *underlying_stream; + grpc_byte_stream* underlying_stream; grpc_slice_buffer cache_buffer; } grpc_byte_stream_cache; // Takes ownership of underlying_stream. -void grpc_byte_stream_cache_init(grpc_byte_stream_cache *cache, - grpc_byte_stream *underlying_stream); +void grpc_byte_stream_cache_init(grpc_byte_stream_cache* cache, + grpc_byte_stream* underlying_stream); // Must not be called while still in use by a grpc_caching_byte_stream. -void grpc_byte_stream_cache_destroy(grpc_exec_ctx *exec_ctx, - grpc_byte_stream_cache *cache); +void grpc_byte_stream_cache_destroy(grpc_exec_ctx* exec_ctx, + grpc_byte_stream_cache* cache); typedef struct { grpc_byte_stream base; - grpc_byte_stream_cache *cache; + grpc_byte_stream_cache* cache; size_t cursor; - grpc_error *shutdown_error; + grpc_error* shutdown_error; } grpc_caching_byte_stream; -void grpc_caching_byte_stream_init(grpc_caching_byte_stream *stream, - grpc_byte_stream_cache *cache); +void grpc_caching_byte_stream_init(grpc_caching_byte_stream* stream, + grpc_byte_stream_cache* cache); // Resets the byte stream to the start of the underlying stream. -void grpc_caching_byte_stream_reset(grpc_caching_byte_stream *stream); - -#ifdef __cplusplus -} -#endif +void grpc_caching_byte_stream_reset(grpc_caching_byte_stream* stream); #endif /* GRPC_CORE_LIB_TRANSPORT_BYTE_STREAM_H */ diff --git a/src/core/lib/transport/connectivity_state.cc b/src/core/lib/transport/connectivity_state.cc index 652c26cf0a5..e7e5dbd1f15 100644 --- a/src/core/lib/transport/connectivity_state.cc +++ b/src/core/lib/transport/connectivity_state.cc @@ -24,10 +24,9 @@ #include #include -grpc_tracer_flag grpc_connectivity_state_trace = - GRPC_TRACER_INITIALIZER(false, "connectivity_state"); +grpc_core::TraceFlag grpc_connectivity_state_trace(false, "connectivity_state"); -const char *grpc_connectivity_state_name(grpc_connectivity_state state) { +const char* grpc_connectivity_state_name(grpc_connectivity_state state) { switch (state) { case GRPC_CHANNEL_IDLE: return "IDLE"; @@ -43,19 +42,19 @@ const char *grpc_connectivity_state_name(grpc_connectivity_state state) { GPR_UNREACHABLE_CODE(return "UNKNOWN"); } -void grpc_connectivity_state_init(grpc_connectivity_state_tracker *tracker, +void grpc_connectivity_state_init(grpc_connectivity_state_tracker* tracker, grpc_connectivity_state init_state, - const char *name) { + const char* name) { gpr_atm_no_barrier_store(&tracker->current_state_atm, init_state); tracker->current_error = GRPC_ERROR_NONE; - tracker->watchers = NULL; + tracker->watchers = nullptr; tracker->name = gpr_strdup(name); } -void grpc_connectivity_state_destroy(grpc_exec_ctx *exec_ctx, - grpc_connectivity_state_tracker *tracker) { - grpc_error *error; - grpc_connectivity_state_watcher *w; +void grpc_connectivity_state_destroy(grpc_exec_ctx* exec_ctx, + grpc_connectivity_state_tracker* tracker) { + grpc_error* error; + grpc_connectivity_state_watcher* w; while ((w = tracker->watchers)) { tracker->watchers = w->next; @@ -74,11 +73,11 @@ void grpc_connectivity_state_destroy(grpc_exec_ctx *exec_ctx, } grpc_connectivity_state grpc_connectivity_state_check( - grpc_connectivity_state_tracker *tracker) { + grpc_connectivity_state_tracker* tracker) { grpc_connectivity_state cur = (grpc_connectivity_state)gpr_atm_no_barrier_load( &tracker->current_state_atm); - if (GRPC_TRACER_ON(grpc_connectivity_state_trace)) { + if (grpc_connectivity_state_trace.enabled()) { gpr_log(GPR_DEBUG, "CONWATCH: %p %s: get %s", tracker, tracker->name, grpc_connectivity_state_name(cur)); } @@ -86,33 +85,33 @@ grpc_connectivity_state grpc_connectivity_state_check( } grpc_connectivity_state grpc_connectivity_state_get( - grpc_connectivity_state_tracker *tracker, grpc_error **error) { + grpc_connectivity_state_tracker* tracker, grpc_error** error) { grpc_connectivity_state cur = (grpc_connectivity_state)gpr_atm_no_barrier_load( &tracker->current_state_atm); - if (GRPC_TRACER_ON(grpc_connectivity_state_trace)) { + if (grpc_connectivity_state_trace.enabled()) { gpr_log(GPR_DEBUG, "CONWATCH: %p %s: get %s", tracker, tracker->name, grpc_connectivity_state_name(cur)); } - if (error != NULL) { + if (error != nullptr) { *error = GRPC_ERROR_REF(tracker->current_error); } return cur; } bool grpc_connectivity_state_has_watchers( - grpc_connectivity_state_tracker *connectivity_state) { - return connectivity_state->watchers != NULL; + grpc_connectivity_state_tracker* connectivity_state) { + return connectivity_state->watchers != nullptr; } bool grpc_connectivity_state_notify_on_state_change( - grpc_exec_ctx *exec_ctx, grpc_connectivity_state_tracker *tracker, - grpc_connectivity_state *current, grpc_closure *notify) { + grpc_exec_ctx* exec_ctx, grpc_connectivity_state_tracker* tracker, + grpc_connectivity_state* current, grpc_closure* notify) { grpc_connectivity_state cur = (grpc_connectivity_state)gpr_atm_no_barrier_load( &tracker->current_state_atm); - if (GRPC_TRACER_ON(grpc_connectivity_state_trace)) { - if (current == NULL) { + if (grpc_connectivity_state_trace.enabled()) { + if (current == nullptr) { gpr_log(GPR_DEBUG, "CONWATCH: %p %s: unsubscribe notify=%p", tracker, tracker->name, notify); } else { @@ -121,17 +120,17 @@ bool grpc_connectivity_state_notify_on_state_change( grpc_connectivity_state_name(cur), notify); } } - if (current == NULL) { - grpc_connectivity_state_watcher *w = tracker->watchers; - if (w != NULL && w->notify == notify) { + if (current == nullptr) { + grpc_connectivity_state_watcher* w = tracker->watchers; + if (w != nullptr && w->notify == notify) { GRPC_CLOSURE_SCHED(exec_ctx, notify, GRPC_ERROR_CANCELLED); tracker->watchers = w->next; gpr_free(w); return false; } - while (w != NULL) { - grpc_connectivity_state_watcher *rm_candidate = w->next; - if (rm_candidate != NULL && rm_candidate->notify == notify) { + while (w != nullptr) { + grpc_connectivity_state_watcher* rm_candidate = w->next; + if (rm_candidate != nullptr && rm_candidate->notify == notify) { GRPC_CLOSURE_SCHED(exec_ctx, notify, GRPC_ERROR_CANCELLED); w->next = w->next->next; gpr_free(rm_candidate); @@ -146,8 +145,8 @@ bool grpc_connectivity_state_notify_on_state_change( GRPC_CLOSURE_SCHED(exec_ctx, notify, GRPC_ERROR_REF(tracker->current_error)); } else { - grpc_connectivity_state_watcher *w = - (grpc_connectivity_state_watcher *)gpr_malloc(sizeof(*w)); + grpc_connectivity_state_watcher* w = + (grpc_connectivity_state_watcher*)gpr_malloc(sizeof(*w)); w->current = current; w->notify = notify; w->next = tracker->watchers; @@ -157,16 +156,16 @@ bool grpc_connectivity_state_notify_on_state_change( } } -void grpc_connectivity_state_set(grpc_exec_ctx *exec_ctx, - grpc_connectivity_state_tracker *tracker, +void grpc_connectivity_state_set(grpc_exec_ctx* exec_ctx, + grpc_connectivity_state_tracker* tracker, grpc_connectivity_state state, - grpc_error *error, const char *reason) { + grpc_error* error, const char* reason) { grpc_connectivity_state cur = (grpc_connectivity_state)gpr_atm_no_barrier_load( &tracker->current_state_atm); - grpc_connectivity_state_watcher *w; - if (GRPC_TRACER_ON(grpc_connectivity_state_trace)) { - const char *error_string = grpc_error_string(error); + grpc_connectivity_state_watcher* w; + if (grpc_connectivity_state_trace.enabled()) { + const char* error_string = grpc_error_string(error); gpr_log(GPR_DEBUG, "SET: %p %s: %s --> %s [%s] error=%p %s", tracker, tracker->name, grpc_connectivity_state_name(cur), grpc_connectivity_state_name(state), reason, error, error_string); @@ -189,10 +188,10 @@ void grpc_connectivity_state_set(grpc_exec_ctx *exec_ctx, } GPR_ASSERT(cur != GRPC_CHANNEL_SHUTDOWN); gpr_atm_no_barrier_store(&tracker->current_state_atm, state); - while ((w = tracker->watchers) != NULL) { + while ((w = tracker->watchers) != nullptr) { *w->current = state; tracker->watchers = w->next; - if (GRPC_TRACER_ON(grpc_connectivity_state_trace)) { + if (grpc_connectivity_state_trace.enabled()) { gpr_log(GPR_DEBUG, "NOTIFY: %p %s: %p", tracker, tracker->name, w->notify); } diff --git a/src/core/lib/transport/connectivity_state.h b/src/core/lib/transport/connectivity_state.h index c0ba1881484..653637ebea6 100644 --- a/src/core/lib/transport/connectivity_state.h +++ b/src/core/lib/transport/connectivity_state.h @@ -23,73 +23,65 @@ #include "src/core/lib/debug/trace.h" #include "src/core/lib/iomgr/exec_ctx.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_connectivity_state_watcher { /** we keep watchers in a linked list */ - struct grpc_connectivity_state_watcher *next; + struct grpc_connectivity_state_watcher* next; /** closure to notify on change */ - grpc_closure *notify; + grpc_closure* notify; /** the current state as believed by the watcher */ - grpc_connectivity_state *current; + grpc_connectivity_state* current; } grpc_connectivity_state_watcher; typedef struct { /** current grpc_connectivity_state */ gpr_atm current_state_atm; /** error associated with state */ - grpc_error *current_error; + grpc_error* current_error; /** all our watchers */ - grpc_connectivity_state_watcher *watchers; + grpc_connectivity_state_watcher* watchers; /** a name to help debugging */ - char *name; + char* name; } grpc_connectivity_state_tracker; -extern grpc_tracer_flag grpc_connectivity_state_trace; +extern grpc_core::TraceFlag grpc_connectivity_state_trace; /** enum --> string conversion */ -const char *grpc_connectivity_state_name(grpc_connectivity_state state); +const char* grpc_connectivity_state_name(grpc_connectivity_state state); -void grpc_connectivity_state_init(grpc_connectivity_state_tracker *tracker, +void grpc_connectivity_state_init(grpc_connectivity_state_tracker* tracker, grpc_connectivity_state init_state, - const char *name); -void grpc_connectivity_state_destroy(grpc_exec_ctx *exec_ctx, - grpc_connectivity_state_tracker *tracker); + const char* name); +void grpc_connectivity_state_destroy(grpc_exec_ctx* exec_ctx, + grpc_connectivity_state_tracker* tracker); /** Set connectivity state; not thread safe; access must be serialized with an * external lock */ -void grpc_connectivity_state_set(grpc_exec_ctx *exec_ctx, - grpc_connectivity_state_tracker *tracker, +void grpc_connectivity_state_set(grpc_exec_ctx* exec_ctx, + grpc_connectivity_state_tracker* tracker, grpc_connectivity_state state, - grpc_error *associated_error, - const char *reason); + grpc_error* associated_error, + const char* reason); /** Return true if this connectivity state has watchers. Access must be serialized with an external lock. */ bool grpc_connectivity_state_has_watchers( - grpc_connectivity_state_tracker *tracker); + grpc_connectivity_state_tracker* tracker); /** Return the last seen connectivity state. No need to synchronize access. */ grpc_connectivity_state grpc_connectivity_state_check( - grpc_connectivity_state_tracker *tracker); + grpc_connectivity_state_tracker* tracker); /** Return the last seen connectivity state, and the associated error. Access must be serialized with an external lock. */ grpc_connectivity_state grpc_connectivity_state_get( - grpc_connectivity_state_tracker *tracker, grpc_error **error); + grpc_connectivity_state_tracker* tracker, grpc_error** error); /** Return 1 if the channel should start connecting, 0 otherwise. If current==NULL cancel notify if it is already queued (success==0 in that case). Access must be serialized with an external lock. */ bool grpc_connectivity_state_notify_on_state_change( - grpc_exec_ctx *exec_ctx, grpc_connectivity_state_tracker *tracker, - grpc_connectivity_state *current, grpc_closure *notify); - -#ifdef __cplusplus -} -#endif + grpc_exec_ctx* exec_ctx, grpc_connectivity_state_tracker* tracker, + grpc_connectivity_state* current, grpc_closure* notify); #endif /* GRPC_CORE_LIB_TRANSPORT_CONNECTIVITY_STATE_H */ diff --git a/src/core/lib/transport/error_utils.cc b/src/core/lib/transport/error_utils.cc index 2e3b61b7abc..69c8ae6de36 100644 --- a/src/core/lib/transport/error_utils.cc +++ b/src/core/lib/transport/error_utils.cc @@ -18,36 +18,37 @@ #include "src/core/lib/transport/error_utils.h" +#include #include "src/core/lib/iomgr/error_internal.h" #include "src/core/lib/transport/status_conversion.h" -static grpc_error *recursively_find_error_with_field(grpc_error *error, +static grpc_error* recursively_find_error_with_field(grpc_error* error, grpc_error_ints which) { // If the error itself has a status code, return it. - if (grpc_error_get_int(error, which, NULL)) { + if (grpc_error_get_int(error, which, nullptr)) { return error; } - if (grpc_error_is_special(error)) return NULL; + if (grpc_error_is_special(error)) return nullptr; // Otherwise, search through its children. uint8_t slot = error->first_err; while (slot != UINT8_MAX) { - grpc_linked_error *lerr = (grpc_linked_error *)(error->arena + slot); - grpc_error *result = recursively_find_error_with_field(lerr->err, which); + grpc_linked_error* lerr = (grpc_linked_error*)(error->arena + slot); + grpc_error* result = recursively_find_error_with_field(lerr->err, which); if (result) return result; slot = lerr->next; } - return NULL; + return nullptr; } -void grpc_error_get_status(grpc_exec_ctx *exec_ctx, grpc_error *error, - grpc_millis deadline, grpc_status_code *code, - grpc_slice *slice, - grpc_http2_error_code *http_error) { +void grpc_error_get_status(grpc_exec_ctx* exec_ctx, grpc_error* error, + grpc_millis deadline, grpc_status_code* code, + grpc_slice* slice, grpc_http2_error_code* http_error, + const char** error_string) { // 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 = + grpc_error* found_error = recursively_find_error_with_field(error, GRPC_ERROR_INT_GRPC_STATUS); - if (found_error == NULL) { + if (found_error == nullptr) { /// If no grpc-status exists, retry through the tree to find a http2 error /// code found_error = @@ -56,7 +57,7 @@ void grpc_error_get_status(grpc_exec_ctx *exec_ctx, grpc_error *error, // If we found an error with a status code above, use that; otherwise, // fall back to using the parent error. - if (found_error == NULL) found_error = error; + if (found_error == nullptr) found_error = error; grpc_status_code status = GRPC_STATUS_UNKNOWN; intptr_t integer; @@ -67,9 +68,13 @@ void grpc_error_get_status(grpc_exec_ctx *exec_ctx, grpc_error *error, status = grpc_http2_error_to_grpc_status( exec_ctx, (grpc_http2_error_code)integer, deadline); } - if (code != NULL) *code = status; + if (code != nullptr) *code = status; - if (http_error != NULL) { + if (error_string != NULL && status != GRPC_STATUS_OK) { + *error_string = gpr_strdup(grpc_error_string(error)); + } + + if (http_error != nullptr) { if (grpc_error_get_int(found_error, GRPC_ERROR_INT_HTTP2_ERROR, &integer)) { *http_error = (grpc_http2_error_code)integer; } else if (grpc_error_get_int(found_error, GRPC_ERROR_INT_GRPC_STATUS, @@ -83,24 +88,22 @@ void grpc_error_get_status(grpc_exec_ctx *exec_ctx, grpc_error *error, // If the error has a status message, use it. Otherwise, fall back to // the error description. - if (slice != NULL) { + if (slice != nullptr) { if (!grpc_error_get_str(found_error, GRPC_ERROR_STR_GRPC_MESSAGE, slice)) { if (!grpc_error_get_str(found_error, GRPC_ERROR_STR_DESCRIPTION, slice)) { *slice = grpc_slice_from_static_string("unknown error"); } } } - - if (found_error == NULL) found_error = error; } -bool grpc_error_has_clear_grpc_status(grpc_error *error) { - if (grpc_error_get_int(error, GRPC_ERROR_INT_GRPC_STATUS, NULL)) { +bool grpc_error_has_clear_grpc_status(grpc_error* error) { + if (grpc_error_get_int(error, GRPC_ERROR_INT_GRPC_STATUS, nullptr)) { return true; } uint8_t slot = error->first_err; while (slot != UINT8_MAX) { - grpc_linked_error *lerr = (grpc_linked_error *)(error->arena + slot); + grpc_linked_error* lerr = (grpc_linked_error*)(error->arena + slot); if (grpc_error_has_clear_grpc_status(lerr->err)) { return true; } diff --git a/src/core/lib/transport/error_utils.h b/src/core/lib/transport/error_utils.h index b4f9df4bf1a..8b006ae9921 100644 --- a/src/core/lib/transport/error_utils.h +++ b/src/core/lib/transport/error_utils.h @@ -23,29 +23,23 @@ #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/transport/http2_errors.h" -#ifdef __cplusplus -extern "C" { -#endif - /// A utility function to get the status code and message to be returned /// to the application. If not set in the top-level message, looks /// through child errors until it finds the first one with these attributes. -/// All attributes are pulled from the same child error. If any of the -/// attributes (code, msg, http_status) are unneeded, they can be passed as +/// All attributes are pulled from the same child error. error_string will +/// be populated with the entire error string. If any of the attributes (code, +/// msg, http_status, error_string) are unneeded, they can be passed as /// NULL. -void grpc_error_get_status(grpc_exec_ctx *exec_ctx, grpc_error *error, - grpc_millis deadline, grpc_status_code *code, - grpc_slice *slice, - grpc_http2_error_code *http_status); +void grpc_error_get_status(grpc_exec_ctx* exec_ctx, grpc_error* error, + grpc_millis deadline, grpc_status_code* code, + grpc_slice* slice, + grpc_http2_error_code* http_status, + const char** error_string); /// A utility function to check whether there is a clear status code that /// doesn't need to be guessed in \a error. This means that \a error or some /// child has GRPC_ERROR_INT_GRPC_STATUS set, or that it is GRPC_ERROR_NONE or /// GRPC_ERROR_CANCELLED -bool grpc_error_has_clear_grpc_status(grpc_error *error); - -#ifdef __cplusplus -} -#endif +bool grpc_error_has_clear_grpc_status(grpc_error* error); #endif /* GRPC_CORE_LIB_TRANSPORT_ERROR_UTILS_H */ diff --git a/src/core/lib/transport/metadata.cc b/src/core/lib/transport/metadata.cc index 2392f26c0b1..0f30c7533db 100644 --- a/src/core/lib/transport/metadata.cc +++ b/src/core/lib/transport/metadata.cc @@ -48,9 +48,9 @@ * used to determine which kind of element a pointer refers to. */ +grpc_core::DebugOnlyTraceFlag grpc_trace_metadata(false, "metadata"); + #ifndef NDEBUG -grpc_tracer_flag grpc_trace_metadata = - GRPC_TRACER_INITIALIZER(false, "metadata"); #define DEBUG_ARGS , const char *file, int line #define FWD_DEBUG_ARGS , file, line #define REF_MD_LOCKED(shard, s) ref_md_locked((shard), (s), __FILE__, __LINE__) @@ -67,7 +67,7 @@ grpc_tracer_flag grpc_trace_metadata = #define TABLE_IDX(hash, capacity) (((hash) >> (LOG2_SHARD_COUNT)) % (capacity)) #define SHARD_IDX(hash) ((hash) & ((1 << (LOG2_SHARD_COUNT)) - 1)) -typedef void (*destroy_user_data_func)(void *user_data); +typedef void (*destroy_user_data_func)(void* user_data); /* Shadow structure for grpc_mdelem_data for interned elements */ typedef struct interned_metadata { @@ -82,7 +82,7 @@ typedef struct interned_metadata { gpr_atm destroy_user_data; gpr_atm user_data; - struct interned_metadata *bucket_next; + struct interned_metadata* bucket_next; } interned_metadata; /* Shadow structure for grpc_mdelem_data for allocated elements */ @@ -97,7 +97,7 @@ typedef struct allocated_metadata { typedef struct mdtab_shard { gpr_mu mu; - interned_metadata **elems; + interned_metadata** elems; size_t count; size_t capacity; /** Estimate of the number of unreferenced mdelems in the hash table. @@ -108,24 +108,24 @@ typedef struct mdtab_shard { static mdtab_shard g_shards[SHARD_COUNT]; -static void gc_mdtab(grpc_exec_ctx *exec_ctx, mdtab_shard *shard); +static void gc_mdtab(grpc_exec_ctx* exec_ctx, mdtab_shard* shard); void grpc_mdctx_global_init(void) { /* initialize shards */ for (size_t i = 0; i < SHARD_COUNT; i++) { - mdtab_shard *shard = &g_shards[i]; + mdtab_shard* shard = &g_shards[i]; gpr_mu_init(&shard->mu); shard->count = 0; gpr_atm_no_barrier_store(&shard->free_estimate, 0); shard->capacity = INITIAL_SHARD_CAPACITY; - shard->elems = (interned_metadata **)gpr_zalloc(sizeof(*shard->elems) * - shard->capacity); + shard->elems = (interned_metadata**)gpr_zalloc(sizeof(*shard->elems) * + shard->capacity); } } -void grpc_mdctx_global_shutdown(grpc_exec_ctx *exec_ctx) { +void grpc_mdctx_global_shutdown(grpc_exec_ctx* exec_ctx) { for (size_t i = 0; i < SHARD_COUNT; i++) { - mdtab_shard *shard = &g_shards[i]; + mdtab_shard* shard = &g_shards[i]; gpr_mu_destroy(&shard->mu); gc_mdtab(exec_ctx, shard); /* TODO(ctiller): GPR_ASSERT(shard->count == 0); */ @@ -146,14 +146,14 @@ static int is_mdelem_static(grpc_mdelem e) { &grpc_static_mdelem_table[GRPC_STATIC_MDELEM_COUNT]; } -static void ref_md_locked(mdtab_shard *shard, - interned_metadata *md DEBUG_ARGS) { +static void ref_md_locked(mdtab_shard* shard, + interned_metadata* md DEBUG_ARGS) { #ifndef NDEBUG - if (GRPC_TRACER_ON(grpc_trace_metadata)) { - char *key_str = grpc_slice_to_c_string(md->key); - char *value_str = grpc_slice_to_c_string(md->value); + if (grpc_trace_metadata.enabled()) { + char* key_str = grpc_slice_to_c_string(md->key); + char* value_str = grpc_slice_to_c_string(md->value); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, - "ELM REF:%p:%" PRIdPTR "->%" PRIdPTR ": '%s' = '%s'", (void *)md, + "ELM REF:%p:%" PRIdPTR "->%" PRIdPTR ": '%s' = '%s'", (void*)md, gpr_atm_no_barrier_load(&md->refcnt), gpr_atm_no_barrier_load(&md->refcnt) + 1, key_str, value_str); gpr_free(key_str); @@ -165,9 +165,9 @@ static void ref_md_locked(mdtab_shard *shard, } } -static void gc_mdtab(grpc_exec_ctx *exec_ctx, mdtab_shard *shard) { +static void gc_mdtab(grpc_exec_ctx* exec_ctx, mdtab_shard* shard) { size_t i; - interned_metadata **prev_next; + interned_metadata** prev_next; interned_metadata *md, *next; gpr_atm num_freed = 0; @@ -175,7 +175,7 @@ static void gc_mdtab(grpc_exec_ctx *exec_ctx, mdtab_shard *shard) { for (i = 0; i < shard->capacity; i++) { prev_next = &shard->elems[i]; for (md = shard->elems[i]; md; md = next) { - void *user_data = (void *)gpr_atm_no_barrier_load(&md->user_data); + void* user_data = (void*)gpr_atm_no_barrier_load(&md->user_data); next = md->bucket_next; if (gpr_atm_acq_load(&md->refcnt) == 0) { grpc_slice_unref_internal(exec_ctx, md->key); @@ -197,17 +197,17 @@ static void gc_mdtab(grpc_exec_ctx *exec_ctx, mdtab_shard *shard) { GPR_TIMER_END("gc_mdtab", 0); } -static void grow_mdtab(mdtab_shard *shard) { +static void grow_mdtab(mdtab_shard* shard) { size_t capacity = shard->capacity * 2; size_t i; - interned_metadata **mdtab; + interned_metadata** mdtab; interned_metadata *md, *next; uint32_t hash; GPR_TIMER_BEGIN("grow_mdtab", 0); mdtab = - (interned_metadata **)gpr_zalloc(sizeof(interned_metadata *) * capacity); + (interned_metadata**)gpr_zalloc(sizeof(interned_metadata*) * capacity); for (i = 0; i < shard->capacity; i++) { for (md = shard->elems[i]; md; md = next) { @@ -228,7 +228,7 @@ static void grow_mdtab(mdtab_shard *shard) { GPR_TIMER_END("grow_mdtab", 0); } -static void rehash_mdtab(grpc_exec_ctx *exec_ctx, mdtab_shard *shard) { +static void rehash_mdtab(grpc_exec_ctx* exec_ctx, mdtab_shard* shard) { if (gpr_atm_no_barrier_load(&shard->free_estimate) > (gpr_atm)(shard->capacity / 4)) { gc_mdtab(exec_ctx, shard); @@ -238,25 +238,25 @@ static void rehash_mdtab(grpc_exec_ctx *exec_ctx, mdtab_shard *shard) { } grpc_mdelem grpc_mdelem_create( - grpc_exec_ctx *exec_ctx, grpc_slice key, grpc_slice value, - grpc_mdelem_data *compatible_external_backing_store) { + grpc_exec_ctx* exec_ctx, grpc_slice key, grpc_slice value, + grpc_mdelem_data* compatible_external_backing_store) { if (!grpc_slice_is_interned(key) || !grpc_slice_is_interned(value)) { - if (compatible_external_backing_store != NULL) { + if (compatible_external_backing_store != nullptr) { return GRPC_MAKE_MDELEM(compatible_external_backing_store, GRPC_MDELEM_STORAGE_EXTERNAL); } - allocated_metadata *allocated = - (allocated_metadata *)gpr_malloc(sizeof(*allocated)); + allocated_metadata* allocated = + (allocated_metadata*)gpr_malloc(sizeof(*allocated)); allocated->key = grpc_slice_ref_internal(key); allocated->value = grpc_slice_ref_internal(value); gpr_atm_rel_store(&allocated->refcnt, 1); #ifndef NDEBUG - if (GRPC_TRACER_ON(grpc_trace_metadata)) { - char *key_str = grpc_slice_to_c_string(allocated->key); - char *value_str = grpc_slice_to_c_string(allocated->value); + if (grpc_trace_metadata.enabled()) { + char* key_str = grpc_slice_to_c_string(allocated->key); + char* value_str = grpc_slice_to_c_string(allocated->value); gpr_log(GPR_DEBUG, "ELM ALLOC:%p:%" PRIdPTR ": '%s' = '%s'", - (void *)allocated, gpr_atm_no_barrier_load(&allocated->refcnt), + (void*)allocated, gpr_atm_no_barrier_load(&allocated->refcnt), key_str, value_str); gpr_free(key_str); gpr_free(value_str); @@ -276,8 +276,8 @@ grpc_mdelem grpc_mdelem_create( uint32_t hash = GRPC_MDSTR_KV_HASH(grpc_slice_hash(key), grpc_slice_hash(value)); - interned_metadata *md; - mdtab_shard *shard = &g_shards[SHARD_IDX(hash)]; + interned_metadata* md; + mdtab_shard* shard = &g_shards[SHARD_IDX(hash)]; size_t idx; GPR_TIMER_BEGIN("grpc_mdelem_from_metadata_strings", 0); @@ -296,7 +296,7 @@ grpc_mdelem grpc_mdelem_create( } /* not found: create a new pair */ - md = (interned_metadata *)gpr_malloc(sizeof(interned_metadata)); + md = (interned_metadata*)gpr_malloc(sizeof(interned_metadata)); gpr_atm_rel_store(&md->refcnt, 1); md->key = grpc_slice_ref_internal(key); md->value = grpc_slice_ref_internal(value); @@ -306,10 +306,10 @@ grpc_mdelem grpc_mdelem_create( shard->elems[idx] = md; gpr_mu_init(&md->mu_user_data); #ifndef NDEBUG - if (GRPC_TRACER_ON(grpc_trace_metadata)) { - char *key_str = grpc_slice_to_c_string(md->key); - char *value_str = grpc_slice_to_c_string(md->value); - gpr_log(GPR_DEBUG, "ELM NEW:%p:%" PRIdPTR ": '%s' = '%s'", (void *)md, + if (grpc_trace_metadata.enabled()) { + char* key_str = grpc_slice_to_c_string(md->key); + char* value_str = grpc_slice_to_c_string(md->value); + gpr_log(GPR_DEBUG, "ELM NEW:%p:%" PRIdPTR ": '%s' = '%s'", (void*)md, gpr_atm_no_barrier_load(&md->refcnt), key_str, value_str); gpr_free(key_str); gpr_free(value_str); @@ -328,23 +328,23 @@ grpc_mdelem grpc_mdelem_create( return GRPC_MAKE_MDELEM(md, GRPC_MDELEM_STORAGE_INTERNED); } -grpc_mdelem grpc_mdelem_from_slices(grpc_exec_ctx *exec_ctx, grpc_slice key, +grpc_mdelem grpc_mdelem_from_slices(grpc_exec_ctx* exec_ctx, grpc_slice key, grpc_slice value) { - grpc_mdelem out = grpc_mdelem_create(exec_ctx, key, value, NULL); + grpc_mdelem out = grpc_mdelem_create(exec_ctx, key, value, nullptr); grpc_slice_unref_internal(exec_ctx, key); grpc_slice_unref_internal(exec_ctx, value); return out; } -grpc_mdelem grpc_mdelem_from_grpc_metadata(grpc_exec_ctx *exec_ctx, - grpc_metadata *metadata) { +grpc_mdelem grpc_mdelem_from_grpc_metadata(grpc_exec_ctx* exec_ctx, + grpc_metadata* metadata) { bool changed = false; grpc_slice key_slice = grpc_slice_maybe_static_intern(metadata->key, &changed); grpc_slice value_slice = grpc_slice_maybe_static_intern(metadata->value, &changed); return grpc_mdelem_create(exec_ctx, key_slice, value_slice, - changed ? NULL : (grpc_mdelem_data *)metadata); + changed ? nullptr : (grpc_mdelem_data*)metadata); } static size_t get_base64_encoded_size(size_t raw_length) { @@ -371,14 +371,14 @@ grpc_mdelem grpc_mdelem_ref(grpc_mdelem gmd DEBUG_ARGS) { case GRPC_MDELEM_STORAGE_STATIC: break; case GRPC_MDELEM_STORAGE_INTERNED: { - interned_metadata *md = (interned_metadata *)GRPC_MDELEM_DATA(gmd); + interned_metadata* md = (interned_metadata*)GRPC_MDELEM_DATA(gmd); #ifndef NDEBUG - if (GRPC_TRACER_ON(grpc_trace_metadata)) { - char *key_str = grpc_slice_to_c_string(md->key); - char *value_str = grpc_slice_to_c_string(md->value); + if (grpc_trace_metadata.enabled()) { + char* key_str = grpc_slice_to_c_string(md->key); + char* value_str = grpc_slice_to_c_string(md->value); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "ELM REF:%p:%" PRIdPTR "->%" PRIdPTR ": '%s' = '%s'", - (void *)md, gpr_atm_no_barrier_load(&md->refcnt), + (void*)md, gpr_atm_no_barrier_load(&md->refcnt), gpr_atm_no_barrier_load(&md->refcnt) + 1, key_str, value_str); gpr_free(key_str); gpr_free(value_str); @@ -393,14 +393,14 @@ grpc_mdelem grpc_mdelem_ref(grpc_mdelem gmd DEBUG_ARGS) { break; } case GRPC_MDELEM_STORAGE_ALLOCATED: { - allocated_metadata *md = (allocated_metadata *)GRPC_MDELEM_DATA(gmd); + allocated_metadata* md = (allocated_metadata*)GRPC_MDELEM_DATA(gmd); #ifndef NDEBUG - if (GRPC_TRACER_ON(grpc_trace_metadata)) { - char *key_str = grpc_slice_to_c_string(md->key); - char *value_str = grpc_slice_to_c_string(md->value); + if (grpc_trace_metadata.enabled()) { + char* key_str = grpc_slice_to_c_string(md->key); + char* value_str = grpc_slice_to_c_string(md->value); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "ELM REF:%p:%" PRIdPTR "->%" PRIdPTR ": '%s' = '%s'", - (void *)md, gpr_atm_no_barrier_load(&md->refcnt), + (void*)md, gpr_atm_no_barrier_load(&md->refcnt), gpr_atm_no_barrier_load(&md->refcnt) + 1, key_str, value_str); gpr_free(key_str); gpr_free(value_str); @@ -417,20 +417,20 @@ grpc_mdelem grpc_mdelem_ref(grpc_mdelem gmd DEBUG_ARGS) { return gmd; } -void grpc_mdelem_unref(grpc_exec_ctx *exec_ctx, grpc_mdelem gmd DEBUG_ARGS) { +void grpc_mdelem_unref(grpc_exec_ctx* exec_ctx, grpc_mdelem gmd DEBUG_ARGS) { switch (GRPC_MDELEM_STORAGE(gmd)) { case GRPC_MDELEM_STORAGE_EXTERNAL: case GRPC_MDELEM_STORAGE_STATIC: break; case GRPC_MDELEM_STORAGE_INTERNED: { - interned_metadata *md = (interned_metadata *)GRPC_MDELEM_DATA(gmd); + interned_metadata* md = (interned_metadata*)GRPC_MDELEM_DATA(gmd); #ifndef NDEBUG - if (GRPC_TRACER_ON(grpc_trace_metadata)) { - char *key_str = grpc_slice_to_c_string(md->key); - char *value_str = grpc_slice_to_c_string(md->value); + if (grpc_trace_metadata.enabled()) { + char* key_str = grpc_slice_to_c_string(md->key); + char* value_str = grpc_slice_to_c_string(md->value); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "ELM UNREF:%p:%" PRIdPTR "->%" PRIdPTR ": '%s' = '%s'", - (void *)md, gpr_atm_no_barrier_load(&md->refcnt), + (void*)md, gpr_atm_no_barrier_load(&md->refcnt), gpr_atm_no_barrier_load(&md->refcnt) - 1, key_str, value_str); gpr_free(key_str); gpr_free(value_str); @@ -443,20 +443,20 @@ void grpc_mdelem_unref(grpc_exec_ctx *exec_ctx, grpc_mdelem gmd DEBUG_ARGS) { if (1 == prev_refcount) { /* once the refcount hits zero, some other thread can come along and free md at any time: it's unsafe from this point on to access it */ - mdtab_shard *shard = &g_shards[SHARD_IDX(hash)]; + mdtab_shard* shard = &g_shards[SHARD_IDX(hash)]; gpr_atm_no_barrier_fetch_add(&shard->free_estimate, 1); } break; } case GRPC_MDELEM_STORAGE_ALLOCATED: { - allocated_metadata *md = (allocated_metadata *)GRPC_MDELEM_DATA(gmd); + allocated_metadata* md = (allocated_metadata*)GRPC_MDELEM_DATA(gmd); #ifndef NDEBUG - if (GRPC_TRACER_ON(grpc_trace_metadata)) { - char *key_str = grpc_slice_to_c_string(md->key); - char *value_str = grpc_slice_to_c_string(md->value); + if (grpc_trace_metadata.enabled()) { + char* key_str = grpc_slice_to_c_string(md->key); + char* value_str = grpc_slice_to_c_string(md->value); gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "ELM UNREF:%p:%" PRIdPTR "->%" PRIdPTR ": '%s' = '%s'", - (void *)md, gpr_atm_no_barrier_load(&md->refcnt), + (void*)md, gpr_atm_no_barrier_load(&md->refcnt), gpr_atm_no_barrier_load(&md->refcnt) - 1, key_str, value_str); gpr_free(key_str); gpr_free(value_str); @@ -474,51 +474,51 @@ void grpc_mdelem_unref(grpc_exec_ctx *exec_ctx, grpc_mdelem gmd DEBUG_ARGS) { } } -void *grpc_mdelem_get_user_data(grpc_mdelem md, void (*destroy_func)(void *)) { +void* grpc_mdelem_get_user_data(grpc_mdelem md, void (*destroy_func)(void*)) { switch (GRPC_MDELEM_STORAGE(md)) { case GRPC_MDELEM_STORAGE_EXTERNAL: case GRPC_MDELEM_STORAGE_ALLOCATED: - return NULL; + return nullptr; case GRPC_MDELEM_STORAGE_STATIC: - return (void *)grpc_static_mdelem_user_data[GRPC_MDELEM_DATA(md) - - grpc_static_mdelem_table]; + return (void*)grpc_static_mdelem_user_data[GRPC_MDELEM_DATA(md) - + grpc_static_mdelem_table]; case GRPC_MDELEM_STORAGE_INTERNED: { - interned_metadata *im = (interned_metadata *)GRPC_MDELEM_DATA(md); - void *result; + interned_metadata* im = (interned_metadata*)GRPC_MDELEM_DATA(md); + void* result; if (gpr_atm_acq_load(&im->destroy_user_data) == (gpr_atm)destroy_func) { - return (void *)gpr_atm_no_barrier_load(&im->user_data); + return (void*)gpr_atm_no_barrier_load(&im->user_data); } else { - return NULL; + return nullptr; } return result; } } - GPR_UNREACHABLE_CODE(return NULL); + GPR_UNREACHABLE_CODE(return nullptr); } -void *grpc_mdelem_set_user_data(grpc_mdelem md, void (*destroy_func)(void *), - void *user_data) { +void* grpc_mdelem_set_user_data(grpc_mdelem md, void (*destroy_func)(void*), + void* user_data) { switch (GRPC_MDELEM_STORAGE(md)) { case GRPC_MDELEM_STORAGE_EXTERNAL: case GRPC_MDELEM_STORAGE_ALLOCATED: destroy_func(user_data); - return NULL; + return nullptr; case GRPC_MDELEM_STORAGE_STATIC: destroy_func(user_data); - return (void *)grpc_static_mdelem_user_data[GRPC_MDELEM_DATA(md) - - grpc_static_mdelem_table]; + return (void*)grpc_static_mdelem_user_data[GRPC_MDELEM_DATA(md) - + grpc_static_mdelem_table]; case GRPC_MDELEM_STORAGE_INTERNED: { - interned_metadata *im = (interned_metadata *)GRPC_MDELEM_DATA(md); + interned_metadata* im = (interned_metadata*)GRPC_MDELEM_DATA(md); GPR_ASSERT(!is_mdelem_static(md)); - GPR_ASSERT((user_data == NULL) == (destroy_func == NULL)); + GPR_ASSERT((user_data == nullptr) == (destroy_func == nullptr)); gpr_mu_lock(&im->mu_user_data); if (gpr_atm_no_barrier_load(&im->destroy_user_data)) { /* user data can only be set once */ gpr_mu_unlock(&im->mu_user_data); - if (destroy_func != NULL) { + if (destroy_func != nullptr) { destroy_func(user_data); } - return (void *)gpr_atm_no_barrier_load(&im->user_data); + return (void*)gpr_atm_no_barrier_load(&im->user_data); } gpr_atm_no_barrier_store(&im->user_data, (gpr_atm)user_data); gpr_atm_rel_store(&im->destroy_user_data, (gpr_atm)destroy_func); @@ -526,7 +526,7 @@ void *grpc_mdelem_set_user_data(grpc_mdelem md, void (*destroy_func)(void *), return user_data; } } - GPR_UNREACHABLE_CODE(return NULL); + GPR_UNREACHABLE_CODE(return nullptr); } bool grpc_mdelem_eq(grpc_mdelem a, grpc_mdelem b) { diff --git a/src/core/lib/transport/metadata.h b/src/core/lib/transport/metadata.h index 3f1032ab8ad..8d4868d0316 100644 --- a/src/core/lib/transport/metadata.h +++ b/src/core/lib/transport/metadata.h @@ -25,13 +25,7 @@ #include "src/core/lib/iomgr/exec_ctx.h" -#ifndef NDEBUG -extern grpc_tracer_flag grpc_trace_metadata; -#endif - -#ifdef __cplusplus -extern "C" { -#endif +extern grpc_core::DebugOnlyTraceFlag grpc_trace_metadata; /* This file provides a mechanism for tracking metadata through the grpc stack. It's not intended for consumption outside of the library. @@ -98,8 +92,7 @@ struct grpc_mdelem { uintptr_t payload; }; -#define GRPC_MDELEM_DATA(md) \ - ((grpc_mdelem_data *)((md).payload & ~(uintptr_t)3)) +#define GRPC_MDELEM_DATA(md) ((grpc_mdelem_data*)((md).payload & ~(uintptr_t)3)) #define GRPC_MDELEM_STORAGE(md) \ ((grpc_mdelem_data_storage)((md).payload & (uintptr_t)3)) #ifdef __cplusplus @@ -114,21 +107,21 @@ struct grpc_mdelem { (uintptr_t)GRPC_MDELEM_STORAGE_INTERNED_BIT)) /* Unrefs the slices. */ -grpc_mdelem grpc_mdelem_from_slices(grpc_exec_ctx *exec_ctx, grpc_slice key, +grpc_mdelem grpc_mdelem_from_slices(grpc_exec_ctx* exec_ctx, grpc_slice key, grpc_slice value); /* Cheaply convert a grpc_metadata to a grpc_mdelem; may use the grpc_metadata object as backing storage (so lifetimes should align) */ -grpc_mdelem grpc_mdelem_from_grpc_metadata(grpc_exec_ctx *exec_ctx, - grpc_metadata *metadata); +grpc_mdelem grpc_mdelem_from_grpc_metadata(grpc_exec_ctx* exec_ctx, + grpc_metadata* metadata); /* Does not unref the slices; if a new non-interned mdelem is needed, allocates one if compatible_external_backing_store is NULL, or uses compatible_external_backing_store if it is non-NULL (in which case it's the users responsibility to ensure that it outlives usage) */ grpc_mdelem grpc_mdelem_create( - grpc_exec_ctx *exec_ctx, grpc_slice key, grpc_slice value, - grpc_mdelem_data *compatible_external_backing_store); + grpc_exec_ctx* exec_ctx, grpc_slice key, grpc_slice value, + grpc_mdelem_data* compatible_external_backing_store); bool grpc_mdelem_eq(grpc_mdelem a, grpc_mdelem b); @@ -137,23 +130,22 @@ size_t grpc_mdelem_get_size_in_hpack_table(grpc_mdelem elem, /* Mutator and accessor for grpc_mdelem user data. The destructor function is used as a type tag and is checked during user_data fetch. */ -void *grpc_mdelem_get_user_data(grpc_mdelem md, - void (*if_destroy_func)(void *)); -void *grpc_mdelem_set_user_data(grpc_mdelem md, void (*destroy_func)(void *), - void *user_data); +void* grpc_mdelem_get_user_data(grpc_mdelem md, void (*if_destroy_func)(void*)); +void* grpc_mdelem_set_user_data(grpc_mdelem md, void (*destroy_func)(void*), + void* user_data); #ifndef NDEBUG #define GRPC_MDELEM_REF(s) grpc_mdelem_ref((s), __FILE__, __LINE__) #define GRPC_MDELEM_UNREF(exec_ctx, s) \ grpc_mdelem_unref((exec_ctx), (s), __FILE__, __LINE__) -grpc_mdelem grpc_mdelem_ref(grpc_mdelem md, const char *file, int line); -void grpc_mdelem_unref(grpc_exec_ctx *exec_ctx, grpc_mdelem md, - const char *file, int line); +grpc_mdelem grpc_mdelem_ref(grpc_mdelem md, const char* file, int line); +void grpc_mdelem_unref(grpc_exec_ctx* exec_ctx, grpc_mdelem md, + const char* file, int line); #else #define GRPC_MDELEM_REF(s) grpc_mdelem_ref((s)) #define GRPC_MDELEM_UNREF(exec_ctx, s) grpc_mdelem_unref((exec_ctx), (s)) grpc_mdelem grpc_mdelem_ref(grpc_mdelem md); -void grpc_mdelem_unref(grpc_exec_ctx *exec_ctx, grpc_mdelem md); +void grpc_mdelem_unref(grpc_exec_ctx* exec_ctx, grpc_mdelem md); #endif #define GRPC_MDKEY(md) (GRPC_MDELEM_DATA(md)->key) @@ -170,10 +162,6 @@ void grpc_mdelem_unref(grpc_exec_ctx *exec_ctx, grpc_mdelem md); #define GRPC_MDSTR_KV_HASH(k_hash, v_hash) (GPR_ROTL((k_hash), 2) ^ (v_hash)) void grpc_mdctx_global_init(void); -void grpc_mdctx_global_shutdown(grpc_exec_ctx *exec_ctx); - -#ifdef __cplusplus -} -#endif +void grpc_mdctx_global_shutdown(grpc_exec_ctx* exec_ctx); #endif /* GRPC_CORE_LIB_TRANSPORT_METADATA_H */ diff --git a/src/core/lib/transport/metadata_batch.cc b/src/core/lib/transport/metadata_batch.cc index 2df9c9189cf..5817765aa39 100644 --- a/src/core/lib/transport/metadata_batch.cc +++ b/src/core/lib/transport/metadata_batch.cc @@ -28,21 +28,21 @@ #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/slice/slice_string_helpers.h" -static void assert_valid_list(grpc_mdelem_list *list) { +static void assert_valid_list(grpc_mdelem_list* list) { #ifndef NDEBUG - grpc_linked_mdelem *l; + grpc_linked_mdelem* l; - GPR_ASSERT((list->head == NULL) == (list->tail == NULL)); + GPR_ASSERT((list->head == nullptr) == (list->tail == nullptr)); if (!list->head) return; - GPR_ASSERT(list->head->prev == NULL); - GPR_ASSERT(list->tail->next == NULL); - GPR_ASSERT((list->head == list->tail) == (list->head->next == NULL)); + GPR_ASSERT(list->head->prev == nullptr); + GPR_ASSERT(list->tail->next == nullptr); + GPR_ASSERT((list->head == list->tail) == (list->head->next == nullptr)); size_t verified_count = 0; for (l = list->head; l; l = l->next) { GPR_ASSERT(!GRPC_MDISNULL(l->md)); - GPR_ASSERT((l->prev == NULL) == (l == list->head)); - GPR_ASSERT((l->next == NULL) == (l == list->tail)); + GPR_ASSERT((l->prev == nullptr) == (l == list->head)); + GPR_ASSERT((l->next == nullptr) == (l == list->tail)); if (l->next) GPR_ASSERT(l->next->prev == l); if (l->prev) GPR_ASSERT(l->prev->next == l); verified_count++; @@ -51,10 +51,10 @@ static void assert_valid_list(grpc_mdelem_list *list) { #endif /* NDEBUG */ } -static void assert_valid_callouts(grpc_exec_ctx *exec_ctx, - grpc_metadata_batch *batch) { +static void assert_valid_callouts(grpc_exec_ctx* exec_ctx, + grpc_metadata_batch* batch) { #ifndef NDEBUG - for (grpc_linked_mdelem *l = batch->list.head; l != NULL; l = l->next) { + for (grpc_linked_mdelem* l = batch->list.head; l != nullptr; l = l->next) { grpc_slice key_interned = grpc_slice_intern(GRPC_MDKEY(l->md)); grpc_metadata_batch_callouts_index callout_idx = GRPC_BATCH_INDEX_OF(key_interned); @@ -67,44 +67,44 @@ static void assert_valid_callouts(grpc_exec_ctx *exec_ctx, } #ifndef NDEBUG -void grpc_metadata_batch_assert_ok(grpc_metadata_batch *batch) { +void grpc_metadata_batch_assert_ok(grpc_metadata_batch* batch) { assert_valid_list(&batch->list); } #endif /* NDEBUG */ -void grpc_metadata_batch_init(grpc_metadata_batch *batch) { +void grpc_metadata_batch_init(grpc_metadata_batch* batch) { memset(batch, 0, sizeof(*batch)); batch->deadline = GRPC_MILLIS_INF_FUTURE; } -void grpc_metadata_batch_destroy(grpc_exec_ctx *exec_ctx, - grpc_metadata_batch *batch) { - grpc_linked_mdelem *l; +void grpc_metadata_batch_destroy(grpc_exec_ctx* exec_ctx, + grpc_metadata_batch* batch) { + grpc_linked_mdelem* l; for (l = batch->list.head; l; l = l->next) { GRPC_MDELEM_UNREF(exec_ctx, l->md); } } -grpc_error *grpc_attach_md_to_error(grpc_error *src, grpc_mdelem md) { - grpc_error *out = grpc_error_set_str( +grpc_error* grpc_attach_md_to_error(grpc_error* src, grpc_mdelem md) { + grpc_error* out = grpc_error_set_str( grpc_error_set_str(src, GRPC_ERROR_STR_KEY, grpc_slice_ref_internal(GRPC_MDKEY(md))), GRPC_ERROR_STR_VALUE, grpc_slice_ref_internal(GRPC_MDVALUE(md))); return out; } -static grpc_error *maybe_link_callout(grpc_metadata_batch *batch, - grpc_linked_mdelem *storage) +static grpc_error* maybe_link_callout(grpc_metadata_batch* batch, + grpc_linked_mdelem* storage) GRPC_MUST_USE_RESULT; -static grpc_error *maybe_link_callout(grpc_metadata_batch *batch, - grpc_linked_mdelem *storage) { +static grpc_error* maybe_link_callout(grpc_metadata_batch* batch, + grpc_linked_mdelem* storage) { grpc_metadata_batch_callouts_index idx = GRPC_BATCH_INDEX_OF(GRPC_MDKEY(storage->md)); if (idx == GRPC_BATCH_CALLOUTS_COUNT) { return GRPC_ERROR_NONE; } - if (batch->idx.array[idx] == NULL) { + if (batch->idx.array[idx] == nullptr) { if (grpc_static_callout_is_default[idx]) ++batch->list.default_count; batch->idx.array[idx] = storage; return GRPC_ERROR_NONE; @@ -114,33 +114,33 @@ static grpc_error *maybe_link_callout(grpc_metadata_batch *batch, storage->md); } -static void maybe_unlink_callout(grpc_metadata_batch *batch, - grpc_linked_mdelem *storage) { +static void maybe_unlink_callout(grpc_metadata_batch* batch, + grpc_linked_mdelem* storage) { grpc_metadata_batch_callouts_index idx = GRPC_BATCH_INDEX_OF(GRPC_MDKEY(storage->md)); if (idx == GRPC_BATCH_CALLOUTS_COUNT) { return; } if (grpc_static_callout_is_default[idx]) --batch->list.default_count; - GPR_ASSERT(batch->idx.array[idx] != NULL); - batch->idx.array[idx] = NULL; + GPR_ASSERT(batch->idx.array[idx] != nullptr); + batch->idx.array[idx] = nullptr; } -grpc_error *grpc_metadata_batch_add_head(grpc_exec_ctx *exec_ctx, - grpc_metadata_batch *batch, - grpc_linked_mdelem *storage, +grpc_error* grpc_metadata_batch_add_head(grpc_exec_ctx* exec_ctx, + grpc_metadata_batch* batch, + grpc_linked_mdelem* storage, grpc_mdelem elem_to_add) { GPR_ASSERT(!GRPC_MDISNULL(elem_to_add)); storage->md = elem_to_add; return grpc_metadata_batch_link_head(exec_ctx, batch, storage); } -static void link_head(grpc_mdelem_list *list, grpc_linked_mdelem *storage) { +static void link_head(grpc_mdelem_list* list, grpc_linked_mdelem* storage) { assert_valid_list(list); GPR_ASSERT(!GRPC_MDISNULL(storage->md)); - storage->prev = NULL; + storage->prev = nullptr; storage->next = list->head; - if (list->head != NULL) { + if (list->head != nullptr) { list->head->prev = storage; } else { list->tail = storage; @@ -150,11 +150,11 @@ static void link_head(grpc_mdelem_list *list, grpc_linked_mdelem *storage) { assert_valid_list(list); } -grpc_error *grpc_metadata_batch_link_head(grpc_exec_ctx *exec_ctx, - grpc_metadata_batch *batch, - grpc_linked_mdelem *storage) { +grpc_error* grpc_metadata_batch_link_head(grpc_exec_ctx* exec_ctx, + grpc_metadata_batch* batch, + grpc_linked_mdelem* storage) { assert_valid_callouts(exec_ctx, batch); - grpc_error *err = maybe_link_callout(batch, storage); + grpc_error* err = maybe_link_callout(batch, storage); if (err != GRPC_ERROR_NONE) { assert_valid_callouts(exec_ctx, batch); return err; @@ -164,22 +164,22 @@ grpc_error *grpc_metadata_batch_link_head(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -grpc_error *grpc_metadata_batch_add_tail(grpc_exec_ctx *exec_ctx, - grpc_metadata_batch *batch, - grpc_linked_mdelem *storage, +grpc_error* grpc_metadata_batch_add_tail(grpc_exec_ctx* exec_ctx, + grpc_metadata_batch* batch, + grpc_linked_mdelem* storage, grpc_mdelem elem_to_add) { GPR_ASSERT(!GRPC_MDISNULL(elem_to_add)); storage->md = elem_to_add; return grpc_metadata_batch_link_tail(exec_ctx, batch, storage); } -static void link_tail(grpc_mdelem_list *list, grpc_linked_mdelem *storage) { +static void link_tail(grpc_mdelem_list* list, grpc_linked_mdelem* storage) { assert_valid_list(list); GPR_ASSERT(!GRPC_MDISNULL(storage->md)); storage->prev = list->tail; - storage->next = NULL; - storage->reserved = NULL; - if (list->tail != NULL) { + storage->next = nullptr; + storage->reserved = nullptr; + if (list->tail != nullptr) { list->tail->next = storage; } else { list->head = storage; @@ -189,11 +189,11 @@ static void link_tail(grpc_mdelem_list *list, grpc_linked_mdelem *storage) { assert_valid_list(list); } -grpc_error *grpc_metadata_batch_link_tail(grpc_exec_ctx *exec_ctx, - grpc_metadata_batch *batch, - grpc_linked_mdelem *storage) { +grpc_error* grpc_metadata_batch_link_tail(grpc_exec_ctx* exec_ctx, + grpc_metadata_batch* batch, + grpc_linked_mdelem* storage) { assert_valid_callouts(exec_ctx, batch); - grpc_error *err = maybe_link_callout(batch, storage); + grpc_error* err = maybe_link_callout(batch, storage); if (err != GRPC_ERROR_NONE) { assert_valid_callouts(exec_ctx, batch); return err; @@ -203,15 +203,15 @@ grpc_error *grpc_metadata_batch_link_tail(grpc_exec_ctx *exec_ctx, return GRPC_ERROR_NONE; } -static void unlink_storage(grpc_mdelem_list *list, - grpc_linked_mdelem *storage) { +static void unlink_storage(grpc_mdelem_list* list, + grpc_linked_mdelem* storage) { assert_valid_list(list); - if (storage->prev != NULL) { + if (storage->prev != nullptr) { storage->prev->next = storage->next; } else { list->head = storage->next; } - if (storage->next != NULL) { + if (storage->next != nullptr) { storage->next->prev = storage->prev; } else { list->tail = storage->prev; @@ -220,9 +220,9 @@ static void unlink_storage(grpc_mdelem_list *list, assert_valid_list(list); } -void grpc_metadata_batch_remove(grpc_exec_ctx *exec_ctx, - grpc_metadata_batch *batch, - grpc_linked_mdelem *storage) { +void grpc_metadata_batch_remove(grpc_exec_ctx* exec_ctx, + grpc_metadata_batch* batch, + grpc_linked_mdelem* storage) { assert_valid_callouts(exec_ctx, batch); maybe_unlink_callout(batch, storage); unlink_storage(&batch->list, storage); @@ -230,8 +230,8 @@ void grpc_metadata_batch_remove(grpc_exec_ctx *exec_ctx, assert_valid_callouts(exec_ctx, batch); } -void grpc_metadata_batch_set_value(grpc_exec_ctx *exec_ctx, - grpc_linked_mdelem *storage, +void grpc_metadata_batch_set_value(grpc_exec_ctx* exec_ctx, + grpc_linked_mdelem* storage, grpc_slice value) { grpc_mdelem old_mdelem = storage->md; grpc_mdelem new_mdelem = grpc_mdelem_from_slices( @@ -240,12 +240,12 @@ void grpc_metadata_batch_set_value(grpc_exec_ctx *exec_ctx, GRPC_MDELEM_UNREF(exec_ctx, old_mdelem); } -grpc_error *grpc_metadata_batch_substitute(grpc_exec_ctx *exec_ctx, - grpc_metadata_batch *batch, - grpc_linked_mdelem *storage, +grpc_error* grpc_metadata_batch_substitute(grpc_exec_ctx* exec_ctx, + grpc_metadata_batch* batch, + grpc_linked_mdelem* storage, grpc_mdelem new_mdelem) { assert_valid_callouts(exec_ctx, batch); - grpc_error *error = GRPC_ERROR_NONE; + grpc_error* error = GRPC_ERROR_NONE; grpc_mdelem old_mdelem = storage->md; if (!grpc_slice_eq(GRPC_MDKEY(new_mdelem), GRPC_MDKEY(old_mdelem))) { maybe_unlink_callout(batch, storage); @@ -263,27 +263,28 @@ grpc_error *grpc_metadata_batch_substitute(grpc_exec_ctx *exec_ctx, return error; } -void grpc_metadata_batch_clear(grpc_exec_ctx *exec_ctx, - grpc_metadata_batch *batch) { +void grpc_metadata_batch_clear(grpc_exec_ctx* exec_ctx, + grpc_metadata_batch* batch) { grpc_metadata_batch_destroy(exec_ctx, batch); grpc_metadata_batch_init(batch); } -bool grpc_metadata_batch_is_empty(grpc_metadata_batch *batch) { - return batch->list.head == NULL && batch->deadline == GRPC_MILLIS_INF_FUTURE; +bool grpc_metadata_batch_is_empty(grpc_metadata_batch* batch) { + return batch->list.head == nullptr && + batch->deadline == GRPC_MILLIS_INF_FUTURE; } -size_t grpc_metadata_batch_size(grpc_metadata_batch *batch) { +size_t grpc_metadata_batch_size(grpc_metadata_batch* batch) { size_t size = 0; - for (grpc_linked_mdelem *elem = batch->list.head; elem != NULL; + for (grpc_linked_mdelem* elem = batch->list.head; elem != nullptr; elem = elem->next) { size += GRPC_MDELEM_LENGTH(elem->md); } return size; } -static void add_error(grpc_error **composite, grpc_error *error, - const char *composite_error_string) { +static void add_error(grpc_error** composite, grpc_error* error, + const char* composite_error_string) { if (error == GRPC_ERROR_NONE) return; if (*composite == GRPC_ERROR_NONE) { *composite = GRPC_ERROR_CREATE_FROM_COPIED_STRING(composite_error_string); @@ -291,15 +292,15 @@ static void add_error(grpc_error **composite, grpc_error *error, *composite = grpc_error_add_child(*composite, error); } -grpc_error *grpc_metadata_batch_filter(grpc_exec_ctx *exec_ctx, - grpc_metadata_batch *batch, +grpc_error* grpc_metadata_batch_filter(grpc_exec_ctx* exec_ctx, + grpc_metadata_batch* batch, grpc_metadata_batch_filter_func func, - void *user_data, - const char *composite_error_string) { - grpc_linked_mdelem *l = batch->list.head; - grpc_error *error = GRPC_ERROR_NONE; + void* user_data, + const char* composite_error_string) { + grpc_linked_mdelem* l = batch->list.head; + grpc_error* error = GRPC_ERROR_NONE; while (l) { - grpc_linked_mdelem *next = l->next; + grpc_linked_mdelem* next = l->next; grpc_filtered_mdelem new_mdelem = func(exec_ctx, user_data, l->md); add_error(&error, new_mdelem.error, composite_error_string); if (GRPC_MDISNULL(new_mdelem.md)) { diff --git a/src/core/lib/transport/metadata_batch.h b/src/core/lib/transport/metadata_batch.h index a2b4b92385b..adfb2d80694 100644 --- a/src/core/lib/transport/metadata_batch.h +++ b/src/core/lib/transport/metadata_batch.h @@ -28,22 +28,18 @@ #include "src/core/lib/transport/metadata.h" #include "src/core/lib/transport/static_metadata.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_linked_mdelem { grpc_mdelem md; - struct grpc_linked_mdelem *next; - struct grpc_linked_mdelem *prev; - void *reserved; + struct grpc_linked_mdelem* next; + struct grpc_linked_mdelem* prev; + void* reserved; } grpc_linked_mdelem; typedef struct grpc_mdelem_list { size_t count; size_t default_count; // Number of default keys. - grpc_linked_mdelem *head; - grpc_linked_mdelem *tail; + grpc_linked_mdelem* head; + grpc_linked_mdelem* tail; } grpc_mdelem_list; typedef struct grpc_metadata_batch { @@ -56,29 +52,29 @@ typedef struct grpc_metadata_batch { grpc_millis deadline; } grpc_metadata_batch; -void grpc_metadata_batch_init(grpc_metadata_batch *batch); -void grpc_metadata_batch_destroy(grpc_exec_ctx *exec_ctx, - grpc_metadata_batch *batch); -void grpc_metadata_batch_clear(grpc_exec_ctx *exec_ctx, - grpc_metadata_batch *batch); -bool grpc_metadata_batch_is_empty(grpc_metadata_batch *batch); +void grpc_metadata_batch_init(grpc_metadata_batch* batch); +void grpc_metadata_batch_destroy(grpc_exec_ctx* exec_ctx, + grpc_metadata_batch* batch); +void grpc_metadata_batch_clear(grpc_exec_ctx* exec_ctx, + grpc_metadata_batch* batch); +bool grpc_metadata_batch_is_empty(grpc_metadata_batch* batch); /* Returns the transport size of the batch. */ -size_t grpc_metadata_batch_size(grpc_metadata_batch *batch); +size_t grpc_metadata_batch_size(grpc_metadata_batch* batch); /** Remove \a storage from the batch, unreffing the mdelem contained */ -void grpc_metadata_batch_remove(grpc_exec_ctx *exec_ctx, - grpc_metadata_batch *batch, - grpc_linked_mdelem *storage); +void grpc_metadata_batch_remove(grpc_exec_ctx* exec_ctx, + grpc_metadata_batch* batch, + grpc_linked_mdelem* storage); /** Substitute a new mdelem for an old value */ -grpc_error *grpc_metadata_batch_substitute(grpc_exec_ctx *exec_ctx, - grpc_metadata_batch *batch, - grpc_linked_mdelem *storage, +grpc_error* grpc_metadata_batch_substitute(grpc_exec_ctx* exec_ctx, + grpc_metadata_batch* batch, + grpc_linked_mdelem* storage, grpc_mdelem new_value); -void grpc_metadata_batch_set_value(grpc_exec_ctx *exec_ctx, - grpc_linked_mdelem *storage, +void grpc_metadata_batch_set_value(grpc_exec_ctx* exec_ctx, + grpc_linked_mdelem* storage, grpc_slice value); /** Add \a storage to the beginning of \a batch. storage->md is @@ -86,17 +82,17 @@ void grpc_metadata_batch_set_value(grpc_exec_ctx *exec_ctx, \a storage is owned by the caller and must survive for the lifetime of batch. This usually means it should be around for the lifetime of the call. */ -grpc_error *grpc_metadata_batch_link_head( - grpc_exec_ctx *exec_ctx, grpc_metadata_batch *batch, - grpc_linked_mdelem *storage) GRPC_MUST_USE_RESULT; +grpc_error* grpc_metadata_batch_link_head( + grpc_exec_ctx* exec_ctx, grpc_metadata_batch* batch, + grpc_linked_mdelem* storage) GRPC_MUST_USE_RESULT; /** Add \a storage to the end of \a batch. storage->md is assumed to be valid. \a storage is owned by the caller and must survive for the lifetime of batch. This usually means it should be around for the lifetime of the call. */ -grpc_error *grpc_metadata_batch_link_tail( - grpc_exec_ctx *exec_ctx, grpc_metadata_batch *batch, - grpc_linked_mdelem *storage) GRPC_MUST_USE_RESULT; +grpc_error* grpc_metadata_batch_link_tail( + grpc_exec_ctx* exec_ctx, grpc_metadata_batch* batch, + grpc_linked_mdelem* storage) GRPC_MUST_USE_RESULT; /** Add \a elem_to_add as the first element in \a batch, using \a storage as backing storage for the linked list element. @@ -104,23 +100,23 @@ grpc_error *grpc_metadata_batch_link_tail( lifetime of batch. This usually means it should be around for the lifetime of the call. Takes ownership of \a elem_to_add */ -grpc_error *grpc_metadata_batch_add_head( - grpc_exec_ctx *exec_ctx, grpc_metadata_batch *batch, - grpc_linked_mdelem *storage, grpc_mdelem elem_to_add) GRPC_MUST_USE_RESULT; +grpc_error* grpc_metadata_batch_add_head( + grpc_exec_ctx* exec_ctx, grpc_metadata_batch* batch, + grpc_linked_mdelem* storage, grpc_mdelem elem_to_add) GRPC_MUST_USE_RESULT; /** Add \a elem_to_add as the last element in \a batch, using \a storage as backing storage for the linked list element. \a storage is owned by the caller and must survive for the lifetime of batch. This usually means it should be around for the lifetime of the call. Takes ownership of \a elem_to_add */ -grpc_error *grpc_metadata_batch_add_tail( - grpc_exec_ctx *exec_ctx, grpc_metadata_batch *batch, - grpc_linked_mdelem *storage, grpc_mdelem elem_to_add) GRPC_MUST_USE_RESULT; +grpc_error* grpc_metadata_batch_add_tail( + grpc_exec_ctx* exec_ctx, grpc_metadata_batch* batch, + grpc_linked_mdelem* storage, grpc_mdelem elem_to_add) GRPC_MUST_USE_RESULT; -grpc_error *grpc_attach_md_to_error(grpc_error *src, grpc_mdelem md); +grpc_error* grpc_attach_md_to_error(grpc_error* src, grpc_mdelem md); typedef struct { - grpc_error *error; + grpc_error* error; grpc_mdelem md; } grpc_filtered_mdelem; @@ -132,22 +128,18 @@ typedef struct { { GRPC_ERROR_NONE, GRPC_MDNULL } typedef grpc_filtered_mdelem (*grpc_metadata_batch_filter_func)( - grpc_exec_ctx *exec_ctx, void *user_data, grpc_mdelem elem); -grpc_error *grpc_metadata_batch_filter( - grpc_exec_ctx *exec_ctx, grpc_metadata_batch *batch, - grpc_metadata_batch_filter_func func, void *user_data, - const char *composite_error_string) GRPC_MUST_USE_RESULT; + grpc_exec_ctx* exec_ctx, void* user_data, grpc_mdelem elem); +grpc_error* grpc_metadata_batch_filter( + grpc_exec_ctx* exec_ctx, grpc_metadata_batch* batch, + grpc_metadata_batch_filter_func func, void* user_data, + const char* composite_error_string) GRPC_MUST_USE_RESULT; #ifndef NDEBUG -void grpc_metadata_batch_assert_ok(grpc_metadata_batch *comd); +void grpc_metadata_batch_assert_ok(grpc_metadata_batch* comd); #else #define grpc_metadata_batch_assert_ok(comd) \ do { \ } while (0) #endif -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_TRANSPORT_METADATA_BATCH_H */ diff --git a/src/core/lib/transport/pid_controller.cc b/src/core/lib/transport/pid_controller.cc index 9f7750d6935..e31cc85f762 100644 --- a/src/core/lib/transport/pid_controller.cc +++ b/src/core/lib/transport/pid_controller.cc @@ -21,7 +21,7 @@ namespace grpc_core { -PidController::PidController(const Args &args) +PidController::PidController(const Args& args) : last_control_value_(args.initial_control_value()), args_(args) {} double PidController::Update(double error, double dt) { diff --git a/src/core/lib/transport/service_config.cc b/src/core/lib/transport/service_config.cc index 070a13a2b46..adcec8c4448 100644 --- a/src/core/lib/transport/service_config.cc +++ b/src/core/lib/transport/service_config.cc @@ -64,11 +64,11 @@ grpc_service_config* grpc_service_config_create(const char* json_string) { service_config->json_string = gpr_strdup(json_string); service_config->json_tree = grpc_json_parse_string(service_config->json_string); - if (service_config->json_tree == NULL) { + if (service_config->json_tree == nullptr) { gpr_log(GPR_INFO, "failed to parse JSON for service config"); gpr_free(service_config->json_string); gpr_free(service_config); - return NULL; + return nullptr; } return service_config; } @@ -83,9 +83,9 @@ void grpc_service_config_parse_global_params( const grpc_service_config* service_config, void (*process_json)(const grpc_json* json, void* arg), void* arg) { const grpc_json* json = service_config->json_tree; - if (json->type != GRPC_JSON_OBJECT || json->key != NULL) return; - for (grpc_json* field = json->child; field != NULL; field = field->next) { - if (field->key == NULL) return; + if (json->type != GRPC_JSON_OBJECT || json->key != nullptr) return; + for (grpc_json* field = json->child; field != nullptr; field = field->next) { + if (field->key == nullptr) return; if (strcmp(field->key, "methodConfig") == 0) continue; process_json(field, arg); } @@ -94,13 +94,13 @@ void grpc_service_config_parse_global_params( const char* grpc_service_config_get_lb_policy_name( const grpc_service_config* service_config) { const grpc_json* json = service_config->json_tree; - if (json->type != GRPC_JSON_OBJECT || json->key != NULL) return NULL; - const char* lb_policy_name = NULL; - for (grpc_json* field = json->child; field != NULL; field = field->next) { - if (field->key == NULL) return NULL; + if (json->type != GRPC_JSON_OBJECT || json->key != nullptr) return nullptr; + const char* lb_policy_name = nullptr; + for (grpc_json* field = json->child; field != nullptr; field = field->next) { + if (field->key == nullptr) return nullptr; if (strcmp(field->key, "loadBalancingPolicy") == 0) { - if (lb_policy_name != NULL) return NULL; // Duplicate. - if (field->type != GRPC_JSON_STRING) return NULL; + if (lb_policy_name != nullptr) return nullptr; // Duplicate. + if (field->type != GRPC_JSON_STRING) return nullptr; lb_policy_name = field->value; } } @@ -110,8 +110,14 @@ const char* grpc_service_config_get_lb_policy_name( // Returns the number of names specified in the method config \a json. static size_t count_names_in_method_config_json(grpc_json* json) { size_t num_names = 0; - for (grpc_json* field = json->child; field != NULL; field = field->next) { - if (field->key != NULL && strcmp(field->key, "name") == 0) ++num_names; + for (grpc_json* field = json->child; field != nullptr; field = field->next) { + if (field->key != nullptr && strcmp(field->key, "name") == 0) { + if (field->type != GRPC_JSON_ARRAY) return -1; + for (grpc_json* name = field->child; name != nullptr; name = name->next) { + if (name->type != GRPC_JSON_OBJECT) return -1; + ++num_names; + } + } } return num_names; } @@ -119,26 +125,26 @@ static size_t count_names_in_method_config_json(grpc_json* json) { // Returns a path string for the JSON name object specified by \a json. // Returns NULL on error. Caller takes ownership of result. static char* parse_json_method_name(grpc_json* json) { - if (json->type != GRPC_JSON_OBJECT) return NULL; - const char* service_name = NULL; - const char* method_name = NULL; - for (grpc_json* child = json->child; child != NULL; child = child->next) { - if (child->key == NULL) return NULL; - if (child->type != GRPC_JSON_STRING) return NULL; + if (json->type != GRPC_JSON_OBJECT) return nullptr; + const char* service_name = nullptr; + const char* method_name = nullptr; + for (grpc_json* child = json->child; child != nullptr; child = child->next) { + if (child->key == nullptr) return nullptr; + if (child->type != GRPC_JSON_STRING) return nullptr; if (strcmp(child->key, "service") == 0) { - if (service_name != NULL) return NULL; // Duplicate. - if (child->value == NULL) return NULL; + if (service_name != nullptr) return nullptr; // Duplicate. + if (child->value == nullptr) return nullptr; service_name = child->value; } else if (strcmp(child->key, "method") == 0) { - if (method_name != NULL) return NULL; // Duplicate. - if (child->value == NULL) return NULL; + if (method_name != nullptr) return nullptr; // Duplicate. + if (child->value == nullptr) return nullptr; method_name = child->value; } } - if (service_name == NULL) return NULL; // Required field. + if (service_name == nullptr) return nullptr; // Required field. char* path; gpr_asprintf(&path, "/%s/%s", service_name, - method_name == NULL ? "*" : method_name); + method_name == nullptr ? "*" : method_name); return path; } @@ -148,20 +154,23 @@ static char* parse_json_method_name(grpc_json* json) { static bool parse_json_method_config( grpc_exec_ctx* exec_ctx, grpc_json* json, void* (*create_value)(const grpc_json* method_config_json), + void* (*ref_value)(void* value), + void (*unref_value)(grpc_exec_ctx* exec_ctx, void* value), grpc_slice_hash_table_entry* entries, size_t* idx) { // Construct value. void* method_config = create_value(json); - if (method_config == NULL) return false; + if (method_config == nullptr) return false; // Construct list of paths. bool success = false; gpr_strvec paths; gpr_strvec_init(&paths); - for (grpc_json* child = json->child; child != NULL; child = child->next) { - if (child->key == NULL) continue; + for (grpc_json* child = json->child; child != nullptr; child = child->next) { + if (child->key == nullptr) continue; if (strcmp(child->key, "name") == 0) { if (child->type != GRPC_JSON_ARRAY) goto done; - for (grpc_json* name = child->child; name != NULL; name = name->next) { + for (grpc_json* name = child->child; name != nullptr; name = name->next) { char* path = parse_json_method_name(name); + if (path == nullptr) goto done; gpr_strvec_add(&paths, path); } } @@ -170,11 +179,12 @@ static bool parse_json_method_config( // Add entry for each path. for (size_t i = 0; i < paths.count; ++i) { entries[*idx].key = grpc_slice_from_copied_string(paths.strs[i]); - entries[*idx].value = method_config; + entries[*idx].value = ref_value(method_config); ++*idx; } success = true; done: + unref_value(exec_ctx, method_config); gpr_strvec_destroy(&paths); return success; } @@ -182,41 +192,49 @@ done: grpc_slice_hash_table* grpc_service_config_create_method_config_table( grpc_exec_ctx* exec_ctx, const grpc_service_config* service_config, void* (*create_value)(const grpc_json* method_config_json), - void (*destroy_value)(grpc_exec_ctx* exec_ctx, void* value)) { + void* (*ref_value)(void* value), + void (*unref_value)(grpc_exec_ctx* exec_ctx, void* value)) { const grpc_json* json = service_config->json_tree; // Traverse parsed JSON tree. - if (json->type != GRPC_JSON_OBJECT || json->key != NULL) return NULL; + if (json->type != GRPC_JSON_OBJECT || json->key != nullptr) return nullptr; size_t num_entries = 0; - grpc_slice_hash_table_entry* entries = NULL; - for (grpc_json* field = json->child; field != NULL; field = field->next) { - if (field->key == NULL) return NULL; + grpc_slice_hash_table_entry* entries = nullptr; + for (grpc_json* field = json->child; field != nullptr; field = field->next) { + if (field->key == nullptr) return nullptr; if (strcmp(field->key, "methodConfig") == 0) { - if (entries != NULL) return NULL; // Duplicate. - if (field->type != GRPC_JSON_ARRAY) return NULL; + if (entries != nullptr) return nullptr; // Duplicate. + if (field->type != GRPC_JSON_ARRAY) return nullptr; // Find number of entries. - for (grpc_json* method = field->child; method != NULL; + for (grpc_json* method = field->child; method != nullptr; method = method->next) { - num_entries += count_names_in_method_config_json(method); + size_t count = count_names_in_method_config_json(method); + if (count <= 0) return nullptr; + num_entries += count; } // Populate method config table entries. entries = (grpc_slice_hash_table_entry*)gpr_malloc( num_entries * sizeof(grpc_slice_hash_table_entry)); size_t idx = 0; - for (grpc_json* method = field->child; method != NULL; + for (grpc_json* method = field->child; method != nullptr; method = method->next) { - if (!parse_json_method_config(exec_ctx, method, create_value, entries, - &idx)) { - return NULL; + if (!parse_json_method_config(exec_ctx, method, create_value, ref_value, + unref_value, entries, &idx)) { + for (size_t i = 0; i < idx; ++i) { + grpc_slice_unref_internal(exec_ctx, entries[i].key); + unref_value(exec_ctx, entries[i].value); + } + gpr_free(entries); + return nullptr; } } GPR_ASSERT(idx == num_entries); } } // Instantiate method config table. - grpc_slice_hash_table* method_config_table = NULL; - if (entries != NULL) { - method_config_table = - grpc_slice_hash_table_create(num_entries, entries, destroy_value, NULL); + grpc_slice_hash_table* method_config_table = nullptr; + if (entries != nullptr) { + method_config_table = grpc_slice_hash_table_create(num_entries, entries, + unref_value, nullptr); gpr_free(entries); } return method_config_table; @@ -228,7 +246,7 @@ void* grpc_method_config_table_get(grpc_exec_ctx* exec_ctx, void* value = grpc_slice_hash_table_get(table, path); // If we didn't find a match for the path, try looking for a wildcard // entry (i.e., change "/service/method" to "/service/*"). - if (value == NULL) { + if (value == nullptr) { char* path_str = grpc_slice_to_c_string(path); const char* sep = strrchr(path_str, '/') + 1; const size_t len = (size_t)(sep - path_str); diff --git a/src/core/lib/transport/service_config.h b/src/core/lib/transport/service_config.h index 9c430936274..75a290bfd80 100644 --- a/src/core/lib/transport/service_config.h +++ b/src/core/lib/transport/service_config.h @@ -22,10 +22,6 @@ #include "src/core/lib/json/json.h" #include "src/core/lib/slice/slice_hash_table.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_service_config grpc_service_config; grpc_service_config* grpc_service_config_create(const char* json_string); @@ -46,12 +42,13 @@ const char* grpc_service_config_get_lb_policy_name( /// Creates a method config table based on the data in \a json. /// The table's keys are request paths. The table's value type is /// returned by \a create_value(), based on data parsed from the JSON tree. -/// \a destroy_value is used to clean up values. +/// \a ref_value() and \a unref_value() are used to ref and unref values. /// Returns NULL on error. grpc_slice_hash_table* grpc_service_config_create_method_config_table( grpc_exec_ctx* exec_ctx, const grpc_service_config* service_config, void* (*create_value)(const grpc_json* method_config_json), - void (*destroy_value)(grpc_exec_ctx* exec_ctx, void* value)); + void* (*ref_value)(void* value), + void (*unref_value)(grpc_exec_ctx* exec_ctx, void* value)); /// A helper function for looking up values in the table returned by /// \a grpc_service_config_create_method_config_table(). @@ -63,8 +60,4 @@ void* grpc_method_config_table_get(grpc_exec_ctx* exec_ctx, const grpc_slice_hash_table* table, grpc_slice path); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_TRANSPORT_SERVICE_CONFIG_H */ diff --git a/src/core/lib/transport/static_metadata.cc b/src/core/lib/transport/static_metadata.cc index 472cf888eab..844724cbeb5 100644 --- a/src/core/lib/transport/static_metadata.cc +++ b/src/core/lib/transport/static_metadata.cc @@ -103,8 +103,8 @@ static uint8_t g_bytes[] = { 105, 100, 101, 110, 116, 105, 116, 121, 44, 100, 101, 102, 108, 97, 116, 101, 44, 103, 122, 105, 112}; -static void static_ref(void *unused) {} -static void static_unref(grpc_exec_ctx *exec_ctx, void *unused) {} +static void static_ref(void* unused) {} +static void static_unref(grpc_exec_ctx* exec_ctx, void* unused) {} static const grpc_slice_refcount_vtable static_sub_vtable = { static_ref, static_unref, grpc_slice_default_eq_impl, grpc_slice_default_hash_impl}; diff --git a/src/core/lib/transport/static_metadata.h b/src/core/lib/transport/static_metadata.h index 299410f22c4..ce3a11b0095 100644 --- a/src/core/lib/transport/static_metadata.h +++ b/src/core/lib/transport/static_metadata.h @@ -27,10 +27,6 @@ #ifndef GRPC_CORE_LIB_TRANSPORT_STATIC_METADATA_H #define GRPC_CORE_LIB_TRANSPORT_STATIC_METADATA_H -#ifdef __cplusplus -extern "C" { -#endif - #include "src/core/lib/transport/metadata.h" #define GRPC_STATIC_MDSTR_COUNT 100 @@ -541,30 +537,30 @@ typedef enum { } grpc_metadata_batch_callouts_index; typedef union { - struct grpc_linked_mdelem *array[GRPC_BATCH_CALLOUTS_COUNT]; + struct grpc_linked_mdelem* array[GRPC_BATCH_CALLOUTS_COUNT]; struct { - struct grpc_linked_mdelem *path; - struct grpc_linked_mdelem *method; - struct grpc_linked_mdelem *status; - struct grpc_linked_mdelem *authority; - struct grpc_linked_mdelem *scheme; - struct grpc_linked_mdelem *te; - struct grpc_linked_mdelem *grpc_message; - struct grpc_linked_mdelem *grpc_status; - struct grpc_linked_mdelem *grpc_payload_bin; - struct grpc_linked_mdelem *grpc_encoding; - struct grpc_linked_mdelem *grpc_accept_encoding; - struct grpc_linked_mdelem *grpc_server_stats_bin; - struct grpc_linked_mdelem *grpc_tags_bin; - struct grpc_linked_mdelem *grpc_trace_bin; - struct grpc_linked_mdelem *content_type; - struct grpc_linked_mdelem *content_encoding; - struct grpc_linked_mdelem *accept_encoding; - struct grpc_linked_mdelem *grpc_internal_encoding_request; - struct grpc_linked_mdelem *grpc_internal_stream_encoding_request; - struct grpc_linked_mdelem *user_agent; - struct grpc_linked_mdelem *host; - struct grpc_linked_mdelem *lb_token; + struct grpc_linked_mdelem* path; + struct grpc_linked_mdelem* method; + struct grpc_linked_mdelem* status; + struct grpc_linked_mdelem* authority; + struct grpc_linked_mdelem* scheme; + struct grpc_linked_mdelem* te; + struct grpc_linked_mdelem* grpc_message; + struct grpc_linked_mdelem* grpc_status; + struct grpc_linked_mdelem* grpc_payload_bin; + struct grpc_linked_mdelem* grpc_encoding; + struct grpc_linked_mdelem* grpc_accept_encoding; + struct grpc_linked_mdelem* grpc_server_stats_bin; + struct grpc_linked_mdelem* grpc_tags_bin; + struct grpc_linked_mdelem* grpc_trace_bin; + struct grpc_linked_mdelem* content_type; + struct grpc_linked_mdelem* content_encoding; + struct grpc_linked_mdelem* accept_encoding; + struct grpc_linked_mdelem* grpc_internal_encoding_request; + struct grpc_linked_mdelem* grpc_internal_stream_encoding_request; + struct grpc_linked_mdelem* user_agent; + struct grpc_linked_mdelem* host; + struct grpc_linked_mdelem* lb_token; } named; } grpc_metadata_batch_callouts; @@ -588,7 +584,5 @@ extern const uint8_t grpc_static_accept_stream_encoding_metadata[4]; (GRPC_MAKE_MDELEM(&grpc_static_mdelem_table \ [grpc_static_accept_stream_encoding_metadata[(algs)]], \ GRPC_MDELEM_STORAGE_STATIC)) -#ifdef __cplusplus -} -#endif + #endif /* GRPC_CORE_LIB_TRANSPORT_STATIC_METADATA_H */ diff --git a/src/core/lib/transport/status_conversion.cc b/src/core/lib/transport/status_conversion.cc index 891c4427d7c..a0a5f1ba4bf 100644 --- a/src/core/lib/transport/status_conversion.cc +++ b/src/core/lib/transport/status_conversion.cc @@ -37,7 +37,7 @@ grpc_http2_error_code grpc_status_to_http2_error(grpc_status_code status) { } } -grpc_status_code grpc_http2_error_to_grpc_status(grpc_exec_ctx *exec_ctx, +grpc_status_code grpc_http2_error_to_grpc_status(grpc_exec_ctx* exec_ctx, grpc_http2_error_code error, grpc_millis deadline) { switch (error) { diff --git a/src/core/lib/transport/status_conversion.h b/src/core/lib/transport/status_conversion.h index 8ef91aecfea..3637b828019 100644 --- a/src/core/lib/transport/status_conversion.h +++ b/src/core/lib/transport/status_conversion.h @@ -23,13 +23,9 @@ #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/transport/http2_errors.h" -#ifdef __cplusplus -extern "C" { -#endif - /* Conversion of grpc status codes to http2 error codes (for RST_STREAM) */ grpc_http2_error_code grpc_status_to_http2_error(grpc_status_code status); -grpc_status_code grpc_http2_error_to_grpc_status(grpc_exec_ctx *exec_ctx, +grpc_status_code grpc_http2_error_to_grpc_status(grpc_exec_ctx* exec_ctx, grpc_http2_error_code error, grpc_millis deadline); @@ -37,8 +33,4 @@ grpc_status_code grpc_http2_error_to_grpc_status(grpc_exec_ctx *exec_ctx, grpc_status_code grpc_http2_status_to_grpc_status(int status); int grpc_status_to_http2_status(grpc_status_code status); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_TRANSPORT_STATUS_CONVERSION_H */ diff --git a/src/core/lib/transport/timeout_encoding.cc b/src/core/lib/transport/timeout_encoding.cc index 23a9ef308f6..86db6c83443 100644 --- a/src/core/lib/transport/timeout_encoding.cc +++ b/src/core/lib/transport/timeout_encoding.cc @@ -41,15 +41,15 @@ static int64_t round_up_to_three_sig_figs(int64_t x) { } /* encode our minimum viable timeout value */ -static void enc_tiny(char *buffer) { memcpy(buffer, "1n", 3); } +static void enc_tiny(char* buffer) { memcpy(buffer, "1n", 3); } -static void enc_ext(char *buffer, int64_t value, char ext) { +static void enc_ext(char* buffer, int64_t value, char ext) { int n = int64_ttoa(value, buffer); buffer[n] = ext; buffer[n + 1] = 0; } -static void enc_seconds(char *buffer, int64_t sec) { +static void enc_seconds(char* buffer, int64_t sec) { if (sec % 3600 == 0) { enc_ext(buffer, sec / 3600, 'H'); } else if (sec % 60 == 0) { @@ -59,7 +59,7 @@ static void enc_seconds(char *buffer, int64_t sec) { } } -static void enc_millis(char *buffer, int64_t x) { +static void enc_millis(char* buffer, int64_t x) { x = round_up_to_three_sig_figs(x); if (x < GPR_MS_PER_SEC) { enc_ext(buffer, x, 'm'); @@ -72,7 +72,7 @@ static void enc_millis(char *buffer, int64_t x) { } } -void grpc_http2_encode_timeout(grpc_millis timeout, char *buffer) { +void grpc_http2_encode_timeout(grpc_millis timeout, char* buffer) { if (timeout <= 0) { enc_tiny(buffer); } else if (timeout < 1000 * GPR_MS_PER_SEC) { @@ -83,15 +83,15 @@ void grpc_http2_encode_timeout(grpc_millis timeout, char *buffer) { } } -static int is_all_whitespace(const char *p, const char *end) { +static int is_all_whitespace(const char* p, const char* end) { while (p != end && *p == ' ') p++; return p == end; } -int grpc_http2_decode_timeout(grpc_slice text, grpc_millis *timeout) { +int grpc_http2_decode_timeout(grpc_slice text, grpc_millis* timeout) { grpc_millis x = 0; - const uint8_t *p = GRPC_SLICE_START_PTR(text); - const uint8_t *end = GRPC_SLICE_END_PTR(text); + const uint8_t* p = GRPC_SLICE_START_PTR(text); + const uint8_t* end = GRPC_SLICE_END_PTR(text); int have_digit = 0; /* skip whitespace */ for (; p != end && *p == ' '; p++) @@ -138,5 +138,5 @@ int grpc_http2_decode_timeout(grpc_slice text, grpc_millis *timeout) { return 0; } p++; - return is_all_whitespace((const char *)p, (const char *)end); + return is_all_whitespace((const char*)p, (const char*)end); } diff --git a/src/core/lib/transport/timeout_encoding.h b/src/core/lib/transport/timeout_encoding.h index 91cdf0f728e..8611f49b009 100644 --- a/src/core/lib/transport/timeout_encoding.h +++ b/src/core/lib/transport/timeout_encoding.h @@ -27,17 +27,9 @@ #define GRPC_HTTP2_TIMEOUT_ENCODE_MIN_BUFSIZE (GPR_LTOA_MIN_BUFSIZE + 1) -#ifdef __cplusplus -extern "C" { -#endif - /* Encode/decode timeouts to the GRPC over HTTP/2 format; encoding may round up arbitrarily */ -void grpc_http2_encode_timeout(grpc_millis timeout, char *buffer); -int grpc_http2_decode_timeout(grpc_slice text, grpc_millis *timeout); - -#ifdef __cplusplus -} -#endif +void grpc_http2_encode_timeout(grpc_millis timeout, char* buffer); +int grpc_http2_decode_timeout(grpc_slice text, grpc_millis* timeout); #endif /* GRPC_CORE_LIB_TRANSPORT_TIMEOUT_ENCODING_H */ diff --git a/src/core/lib/transport/transport.cc b/src/core/lib/transport/transport.cc index ab4f938e7b4..5bda1541a6d 100644 --- a/src/core/lib/transport/transport.cc +++ b/src/core/lib/transport/transport.cc @@ -31,37 +31,35 @@ #include "src/core/lib/support/string.h" #include "src/core/lib/transport/transport_impl.h" -#ifndef NDEBUG -grpc_tracer_flag grpc_trace_stream_refcount = - GRPC_TRACER_INITIALIZER(false, "stream_refcount"); -#endif +grpc_core::DebugOnlyTraceFlag grpc_trace_stream_refcount(false, + "stream_refcount"); #ifndef NDEBUG -void grpc_stream_ref(grpc_stream_refcount *refcount, const char *reason) { - if (GRPC_TRACER_ON(grpc_trace_stream_refcount)) { +void grpc_stream_ref(grpc_stream_refcount* refcount, const char* reason) { + if (grpc_trace_stream_refcount.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&refcount->refs.count); gpr_log(GPR_DEBUG, "%s %p:%p REF %" PRIdPTR "->%" PRIdPTR " %s", refcount->object_type, refcount, refcount->destroy.cb_arg, val, val + 1, reason); } #else -void grpc_stream_ref(grpc_stream_refcount *refcount) { +void grpc_stream_ref(grpc_stream_refcount* refcount) { #endif gpr_ref_non_zero(&refcount->refs); } #ifndef NDEBUG -void grpc_stream_unref(grpc_exec_ctx *exec_ctx, grpc_stream_refcount *refcount, - const char *reason) { - if (GRPC_TRACER_ON(grpc_trace_stream_refcount)) { +void grpc_stream_unref(grpc_exec_ctx* exec_ctx, grpc_stream_refcount* refcount, + const char* reason) { + if (grpc_trace_stream_refcount.enabled()) { gpr_atm val = gpr_atm_no_barrier_load(&refcount->refs.count); gpr_log(GPR_DEBUG, "%s %p:%p UNREF %" PRIdPTR "->%" PRIdPTR " %s", refcount->object_type, refcount, refcount->destroy.cb_arg, val, val - 1, reason); } #else -void grpc_stream_unref(grpc_exec_ctx *exec_ctx, - grpc_stream_refcount *refcount) { +void grpc_stream_unref(grpc_exec_ctx* exec_ctx, + grpc_stream_refcount* refcount) { #endif if (gpr_unref(&refcount->refs)) { if (exec_ctx->flags & GRPC_EXEC_CTX_FLAG_THREAD_RESOURCE_LOOP) { @@ -79,11 +77,11 @@ void grpc_stream_unref(grpc_exec_ctx *exec_ctx, } } -#define STREAM_REF_FROM_SLICE_REF(p) \ - ((grpc_stream_refcount *)(((uint8_t *)p) - \ - offsetof(grpc_stream_refcount, slice_refcount))) +#define STREAM_REF_FROM_SLICE_REF(p) \ + ((grpc_stream_refcount*)(((uint8_t*)p) - \ + offsetof(grpc_stream_refcount, slice_refcount))) -static void slice_stream_ref(void *p) { +static void slice_stream_ref(void* p) { #ifndef NDEBUG grpc_stream_ref(STREAM_REF_FROM_SLICE_REF(p), "slice"); #else @@ -91,7 +89,7 @@ static void slice_stream_ref(void *p) { #endif } -static void slice_stream_unref(grpc_exec_ctx *exec_ctx, void *p) { +static void slice_stream_unref(grpc_exec_ctx* exec_ctx, void* p) { #ifndef NDEBUG grpc_stream_unref(exec_ctx, STREAM_REF_FROM_SLICE_REF(p), "slice"); #else @@ -99,12 +97,12 @@ static void slice_stream_unref(grpc_exec_ctx *exec_ctx, void *p) { #endif } -grpc_slice grpc_slice_from_stream_owned_buffer(grpc_stream_refcount *refcount, - void *buffer, size_t length) { +grpc_slice grpc_slice_from_stream_owned_buffer(grpc_stream_refcount* refcount, + void* buffer, size_t length) { slice_stream_ref(&refcount->slice_refcount); grpc_slice res; - res.refcount = &refcount->slice_refcount, - res.data.refcounted.bytes = (uint8_t *)buffer; + res.refcount = &refcount->slice_refcount; + res.data.refcounted.bytes = (uint8_t*)buffer; res.data.refcounted.length = length; return res; } @@ -117,13 +115,13 @@ static const grpc_slice_refcount_vtable stream_ref_slice_vtable = { }; #ifndef NDEBUG -void grpc_stream_ref_init(grpc_stream_refcount *refcount, int initial_refs, - grpc_iomgr_cb_func cb, void *cb_arg, - const char *object_type) { +void grpc_stream_ref_init(grpc_stream_refcount* refcount, int initial_refs, + grpc_iomgr_cb_func cb, void* cb_arg, + const char* object_type) { refcount->object_type = object_type; #else -void grpc_stream_ref_init(grpc_stream_refcount *refcount, int initial_refs, - grpc_iomgr_cb_func cb, void *cb_arg) { +void grpc_stream_ref_init(grpc_stream_refcount* refcount, int initial_refs, + grpc_iomgr_cb_func cb, void* cb_arg) { #endif gpr_ref_init(&refcount->refs, initial_refs); GRPC_CLOSURE_INIT(&refcount->destroy, cb, cb_arg, grpc_schedule_on_exec_ctx); @@ -131,62 +129,63 @@ void grpc_stream_ref_init(grpc_stream_refcount *refcount, int initial_refs, refcount->slice_refcount.sub_refcount = &refcount->slice_refcount; } -static void move64(uint64_t *from, uint64_t *to) { +static void move64(uint64_t* from, uint64_t* to) { *to += *from; *from = 0; } -void grpc_transport_move_one_way_stats(grpc_transport_one_way_stats *from, - grpc_transport_one_way_stats *to) { +void grpc_transport_move_one_way_stats(grpc_transport_one_way_stats* from, + grpc_transport_one_way_stats* to) { move64(&from->framing_bytes, &to->framing_bytes); move64(&from->data_bytes, &to->data_bytes); move64(&from->header_bytes, &to->header_bytes); } -void grpc_transport_move_stats(grpc_transport_stream_stats *from, - grpc_transport_stream_stats *to) { +void grpc_transport_move_stats(grpc_transport_stream_stats* from, + grpc_transport_stream_stats* to) { grpc_transport_move_one_way_stats(&from->incoming, &to->incoming); grpc_transport_move_one_way_stats(&from->outgoing, &to->outgoing); } -size_t grpc_transport_stream_size(grpc_transport *transport) { +size_t grpc_transport_stream_size(grpc_transport* transport) { return transport->vtable->sizeof_stream; } -void grpc_transport_destroy(grpc_exec_ctx *exec_ctx, - grpc_transport *transport) { +void grpc_transport_destroy(grpc_exec_ctx* exec_ctx, + grpc_transport* transport) { transport->vtable->destroy(exec_ctx, transport); } -int grpc_transport_init_stream(grpc_exec_ctx *exec_ctx, - grpc_transport *transport, grpc_stream *stream, - grpc_stream_refcount *refcount, - const void *server_data, gpr_arena *arena) { +int grpc_transport_init_stream(grpc_exec_ctx* exec_ctx, + grpc_transport* transport, grpc_stream* stream, + grpc_stream_refcount* refcount, + const void* server_data, gpr_arena* arena) { return transport->vtable->init_stream(exec_ctx, transport, stream, refcount, server_data, arena); } -void grpc_transport_perform_stream_op(grpc_exec_ctx *exec_ctx, - grpc_transport *transport, - grpc_stream *stream, - grpc_transport_stream_op_batch *op) { +void grpc_transport_perform_stream_op(grpc_exec_ctx* exec_ctx, + grpc_transport* transport, + grpc_stream* stream, + grpc_transport_stream_op_batch* op) { transport->vtable->perform_stream_op(exec_ctx, transport, stream, op); } -void grpc_transport_perform_op(grpc_exec_ctx *exec_ctx, - grpc_transport *transport, - grpc_transport_op *op) { +void grpc_transport_perform_op(grpc_exec_ctx* exec_ctx, + grpc_transport* transport, + grpc_transport_op* op) { transport->vtable->perform_op(exec_ctx, transport, op); } -void grpc_transport_set_pops(grpc_exec_ctx *exec_ctx, grpc_transport *transport, - grpc_stream *stream, - grpc_polling_entity *pollent) { - grpc_pollset *pollset; - grpc_pollset_set *pollset_set; - if ((pollset = grpc_polling_entity_pollset(pollent)) != NULL) { +void grpc_transport_set_pops(grpc_exec_ctx* exec_ctx, grpc_transport* transport, + grpc_stream* stream, + grpc_polling_entity* pollent) { + grpc_pollset* pollset; + grpc_pollset_set* pollset_set; + if ((pollset = grpc_polling_entity_pollset(pollent)) != nullptr) { transport->vtable->set_pollset(exec_ctx, transport, stream, pollset); - } else if ((pollset_set = grpc_polling_entity_pollset_set(pollent)) != NULL) { + } else if ((pollset_set = grpc_polling_entity_pollset_set(pollent)) != + nullptr) { transport->vtable->set_pollset_set(exec_ctx, transport, stream, pollset_set); } else { @@ -194,16 +193,16 @@ void grpc_transport_set_pops(grpc_exec_ctx *exec_ctx, grpc_transport *transport, } } -void grpc_transport_destroy_stream(grpc_exec_ctx *exec_ctx, - grpc_transport *transport, - grpc_stream *stream, - grpc_closure *then_schedule_closure) { +void grpc_transport_destroy_stream(grpc_exec_ctx* exec_ctx, + grpc_transport* transport, + grpc_stream* stream, + grpc_closure* then_schedule_closure) { transport->vtable->destroy_stream(exec_ctx, transport, stream, then_schedule_closure); } -grpc_endpoint *grpc_transport_get_endpoint(grpc_exec_ctx *exec_ctx, - grpc_transport *transport) { +grpc_endpoint* grpc_transport_get_endpoint(grpc_exec_ctx* exec_ctx, + grpc_transport* transport) { return transport->vtable->get_endpoint(exec_ctx, transport); } @@ -215,8 +214,8 @@ grpc_endpoint *grpc_transport_get_endpoint(grpc_exec_ctx *exec_ctx, // though it lives in lib, it handles transport stream ops sure // it's grpc_transport_stream_op_batch_finish_with_failure void grpc_transport_stream_op_batch_finish_with_failure( - grpc_exec_ctx *exec_ctx, grpc_transport_stream_op_batch *batch, - grpc_error *error, grpc_call_combiner *call_combiner) { + grpc_exec_ctx* exec_ctx, grpc_transport_stream_op_batch* batch, + grpc_error* error, grpc_call_combiner* call_combiner) { if (batch->send_message) { grpc_byte_stream_destroy(exec_ctx, batch->payload->send_message.send_message); @@ -241,19 +240,19 @@ void grpc_transport_stream_op_batch_finish_with_failure( typedef struct { grpc_closure outer_on_complete; - grpc_closure *inner_on_complete; + grpc_closure* inner_on_complete; grpc_transport_op op; } made_transport_op; -static void destroy_made_transport_op(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - made_transport_op *op = (made_transport_op *)arg; +static void destroy_made_transport_op(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + made_transport_op* op = (made_transport_op*)arg; GRPC_CLOSURE_SCHED(exec_ctx, op->inner_on_complete, GRPC_ERROR_REF(error)); gpr_free(op); } -grpc_transport_op *grpc_make_transport_op(grpc_closure *on_complete) { - made_transport_op *op = (made_transport_op *)gpr_malloc(sizeof(*op)); +grpc_transport_op* grpc_make_transport_op(grpc_closure* on_complete) { + made_transport_op* op = (made_transport_op*)gpr_malloc(sizeof(*op)); GRPC_CLOSURE_INIT(&op->outer_on_complete, destroy_made_transport_op, op, grpc_schedule_on_exec_ctx); op->inner_on_complete = on_complete; @@ -264,23 +263,23 @@ grpc_transport_op *grpc_make_transport_op(grpc_closure *on_complete) { typedef struct { grpc_closure outer_on_complete; - grpc_closure *inner_on_complete; + grpc_closure* inner_on_complete; grpc_transport_stream_op_batch op; grpc_transport_stream_op_batch_payload payload; } made_transport_stream_op; -static void destroy_made_transport_stream_op(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - made_transport_stream_op *op = (made_transport_stream_op *)arg; - grpc_closure *c = op->inner_on_complete; +static void destroy_made_transport_stream_op(grpc_exec_ctx* exec_ctx, void* arg, + grpc_error* error) { + made_transport_stream_op* op = (made_transport_stream_op*)arg; + grpc_closure* c = op->inner_on_complete; gpr_free(op); GRPC_CLOSURE_RUN(exec_ctx, c, GRPC_ERROR_REF(error)); } -grpc_transport_stream_op_batch *grpc_make_transport_stream_op( - grpc_closure *on_complete) { - made_transport_stream_op *op = - (made_transport_stream_op *)gpr_zalloc(sizeof(*op)); +grpc_transport_stream_op_batch* grpc_make_transport_stream_op( + grpc_closure* on_complete) { + made_transport_stream_op* op = + (made_transport_stream_op*)gpr_zalloc(sizeof(*op)); op->op.payload = &op->payload; GRPC_CLOSURE_INIT(&op->outer_on_complete, destroy_made_transport_stream_op, op, grpc_schedule_on_exec_ctx); diff --git a/src/core/lib/transport/transport.h b/src/core/lib/transport/transport.h index fbf5dcb8b59..b3cf04c22da 100644 --- a/src/core/lib/transport/transport.h +++ b/src/core/lib/transport/transport.h @@ -31,10 +31,6 @@ #include "src/core/lib/transport/byte_stream.h" #include "src/core/lib/transport/metadata_batch.h" -#ifdef __cplusplus -extern "C" { -#endif - /* forward declarations */ typedef struct grpc_transport grpc_transport; @@ -43,41 +39,39 @@ typedef struct grpc_transport grpc_transport; for a stream. */ typedef struct grpc_stream grpc_stream; -#ifndef NDEBUG -extern grpc_tracer_flag grpc_trace_stream_refcount; -#endif +extern grpc_core::DebugOnlyTraceFlag grpc_trace_stream_refcount; typedef struct grpc_stream_refcount { gpr_refcount refs; grpc_closure destroy; #ifndef NDEBUG - const char *object_type; + const char* object_type; #endif grpc_slice_refcount slice_refcount; } grpc_stream_refcount; #ifndef NDEBUG -void grpc_stream_ref_init(grpc_stream_refcount *refcount, int initial_refs, - grpc_iomgr_cb_func cb, void *cb_arg, - const char *object_type); -void grpc_stream_ref(grpc_stream_refcount *refcount, const char *reason); -void grpc_stream_unref(grpc_exec_ctx *exec_ctx, grpc_stream_refcount *refcount, - const char *reason); +void grpc_stream_ref_init(grpc_stream_refcount* refcount, int initial_refs, + grpc_iomgr_cb_func cb, void* cb_arg, + const char* object_type); +void grpc_stream_ref(grpc_stream_refcount* refcount, const char* reason); +void grpc_stream_unref(grpc_exec_ctx* exec_ctx, grpc_stream_refcount* refcount, + const char* reason); #define GRPC_STREAM_REF_INIT(rc, ir, cb, cb_arg, objtype) \ grpc_stream_ref_init(rc, ir, cb, cb_arg, objtype) #else -void grpc_stream_ref_init(grpc_stream_refcount *refcount, int initial_refs, - grpc_iomgr_cb_func cb, void *cb_arg); -void grpc_stream_ref(grpc_stream_refcount *refcount); -void grpc_stream_unref(grpc_exec_ctx *exec_ctx, grpc_stream_refcount *refcount); +void grpc_stream_ref_init(grpc_stream_refcount* refcount, int initial_refs, + grpc_iomgr_cb_func cb, void* cb_arg); +void grpc_stream_ref(grpc_stream_refcount* refcount); +void grpc_stream_unref(grpc_exec_ctx* exec_ctx, grpc_stream_refcount* refcount); #define GRPC_STREAM_REF_INIT(rc, ir, cb, cb_arg, objtype) \ grpc_stream_ref_init(rc, ir, cb, cb_arg) #endif /* Wrap a buffer that is owned by some stream object into a slice that shares the same refcount */ -grpc_slice grpc_slice_from_stream_owned_buffer(grpc_stream_refcount *refcount, - void *buffer, size_t length); +grpc_slice grpc_slice_from_stream_owned_buffer(grpc_stream_refcount* refcount, + void* buffer, size_t length); typedef struct { uint64_t framing_bytes; @@ -90,14 +84,14 @@ typedef struct grpc_transport_stream_stats { grpc_transport_one_way_stats outgoing; } grpc_transport_stream_stats; -void grpc_transport_move_one_way_stats(grpc_transport_one_way_stats *from, - grpc_transport_one_way_stats *to); +void grpc_transport_move_one_way_stats(grpc_transport_one_way_stats* from, + grpc_transport_one_way_stats* to); -void grpc_transport_move_stats(grpc_transport_stream_stats *from, - grpc_transport_stream_stats *to); +void grpc_transport_move_stats(grpc_transport_stream_stats* from, + grpc_transport_stream_stats* to); typedef struct { - void *extra_arg; + void* extra_arg; grpc_closure closure; } grpc_handler_private_op_data; @@ -110,10 +104,10 @@ typedef struct grpc_transport_stream_op_batch { /** Should be enqueued when all requested operations (excluding recv_message and recv_initial_metadata which have their own closures) in a given batch have been completed. */ - grpc_closure *on_complete; + grpc_closure* on_complete; /** Values for the stream op (fields set are determined by flags above) */ - grpc_transport_stream_op_batch_payload *payload; + grpc_transport_stream_op_batch_payload* payload; /** Send initial metadata to the peer, from the provided metadata batch. */ bool send_initial_metadata : 1; @@ -149,17 +143,17 @@ typedef struct grpc_transport_stream_op_batch { struct grpc_transport_stream_op_batch_payload { struct { - grpc_metadata_batch *send_initial_metadata; + grpc_metadata_batch* send_initial_metadata; /** Iff send_initial_metadata != NULL, flags associated with send_initial_metadata: a bitfield of GRPC_INITIAL_METADATA_xxx */ uint32_t send_initial_metadata_flags; // If non-NULL, will be set by the transport to the peer string // (a char*, which the caller takes ownership of). - gpr_atm *peer_string; + gpr_atm* peer_string; } send_initial_metadata; struct { - grpc_metadata_batch *send_trailing_metadata; + grpc_metadata_batch* send_trailing_metadata; } send_trailing_metadata; struct { @@ -168,21 +162,21 @@ struct grpc_transport_stream_op_batch_payload { // grpc_byte_stream_destroy() on this. // The batch's on_complete will not be called until after the byte // stream is destroyed. - grpc_byte_stream *send_message; + grpc_byte_stream* send_message; } send_message; struct { - grpc_metadata_batch *recv_initial_metadata; - uint32_t *recv_flags; + grpc_metadata_batch* recv_initial_metadata; + uint32_t* recv_flags; /** Should be enqueued when initial metadata is ready to be processed. */ - grpc_closure *recv_initial_metadata_ready; + grpc_closure* recv_initial_metadata_ready; // If not NULL, will be set to true if trailing metadata is // immediately available. This may be a signal that we received a // Trailers-Only response. - bool *trailing_metadata_available; + bool* trailing_metadata_available; // If non-NULL, will be set by the transport to the peer string // (a char*, which the caller takes ownership of). - gpr_atm *peer_string; + gpr_atm* peer_string; } recv_initial_metadata; struct { @@ -190,17 +184,17 @@ struct grpc_transport_stream_op_batch_payload { // containing a received message. // The caller is responsible for calling grpc_byte_stream_destroy() // on this byte stream. - grpc_byte_stream **recv_message; + grpc_byte_stream** recv_message; /** Should be enqueued when one message is ready to be processed. */ - grpc_closure *recv_message_ready; + grpc_closure* recv_message_ready; } recv_message; struct { - grpc_metadata_batch *recv_trailing_metadata; + grpc_metadata_batch* recv_trailing_metadata; } recv_trailing_metadata; struct { - grpc_transport_stream_stats *collect_stats; + grpc_transport_stream_stats* collect_stats; } collect_stats; /** Forcefully close this stream. @@ -216,43 +210,43 @@ struct grpc_transport_stream_op_batch_payload { struct { // Error contract: the transport that gets this op must cause cancel_error // to be unref'ed after processing it - grpc_error *cancel_error; + grpc_error* cancel_error; } cancel_stream; /* Indexes correspond to grpc_context_index enum values */ - grpc_call_context_element *context; + grpc_call_context_element* context; }; /** Transport op: a set of operations to perform on a transport as a whole */ typedef struct grpc_transport_op { /** Called when processing of this op is done. */ - grpc_closure *on_consumed; + grpc_closure* on_consumed; /** connectivity monitoring - set connectivity_state to NULL to unsubscribe */ - grpc_closure *on_connectivity_state_change; - grpc_connectivity_state *connectivity_state; + grpc_closure* on_connectivity_state_change; + grpc_connectivity_state* connectivity_state; /** should the transport be disconnected * Error contract: the transport that gets this op must cause * disconnect_with_error to be unref'ed after processing it */ - grpc_error *disconnect_with_error; + grpc_error* disconnect_with_error; /** what should the goaway contain? * Error contract: the transport that gets this op must cause * goaway_error to be unref'ed after processing it */ - grpc_error *goaway_error; + grpc_error* goaway_error; /** set the callback for accepting new streams; this is a permanent callback, unlike the other one-shot closures. If true, the callback is set to set_accept_stream_fn, with its user_data argument set to set_accept_stream_user_data */ bool set_accept_stream; - void (*set_accept_stream_fn)(grpc_exec_ctx *exec_ctx, void *user_data, - grpc_transport *transport, - const void *server_data); - void *set_accept_stream_user_data; + void (*set_accept_stream_fn)(grpc_exec_ctx* exec_ctx, void* user_data, + grpc_transport* transport, + const void* server_data); + void* set_accept_stream_user_data; /** add this transport to a pollset */ - grpc_pollset *bind_pollset; + grpc_pollset* bind_pollset; /** add this transport to a pollset_set */ - grpc_pollset_set *bind_pollset_set; + grpc_pollset_set* bind_pollset_set; /** send a ping, call this back if not NULL */ - grpc_closure *send_ping; + grpc_closure* send_ping; /*************************************************************************** * remaining fields are initialized and used at the discretion of the @@ -263,7 +257,7 @@ typedef struct grpc_transport_op { /* Returns the amount of memory required to store a grpc_stream for this transport */ -size_t grpc_transport_stream_size(grpc_transport *transport); +size_t grpc_transport_stream_size(grpc_transport* transport); /* Initialize transport data for a stream. @@ -275,13 +269,13 @@ size_t grpc_transport_stream_size(grpc_transport *transport); stream - a pointer to uninitialized memory to initialize server_data - either NULL for a client initiated stream, or a pointer supplied from the accept_stream callback function */ -int grpc_transport_init_stream(grpc_exec_ctx *exec_ctx, - grpc_transport *transport, grpc_stream *stream, - grpc_stream_refcount *refcount, - const void *server_data, gpr_arena *arena); +int grpc_transport_init_stream(grpc_exec_ctx* exec_ctx, + grpc_transport* transport, grpc_stream* stream, + grpc_stream_refcount* refcount, + const void* server_data, gpr_arena* arena); -void grpc_transport_set_pops(grpc_exec_ctx *exec_ctx, grpc_transport *transport, - grpc_stream *stream, grpc_polling_entity *pollent); +void grpc_transport_set_pops(grpc_exec_ctx* exec_ctx, grpc_transport* transport, + grpc_stream* stream, grpc_polling_entity* pollent); /* Destroy transport data for a stream. @@ -293,17 +287,17 @@ void grpc_transport_set_pops(grpc_exec_ctx *exec_ctx, grpc_transport *transport, transport - the transport on which to create this stream stream - the grpc_stream to destroy (memory is still owned by the caller, but any child memory must be cleaned up) */ -void grpc_transport_destroy_stream(grpc_exec_ctx *exec_ctx, - grpc_transport *transport, - grpc_stream *stream, - grpc_closure *then_schedule_closure); +void grpc_transport_destroy_stream(grpc_exec_ctx* exec_ctx, + grpc_transport* transport, + grpc_stream* stream, + grpc_closure* then_schedule_closure); void grpc_transport_stream_op_batch_finish_with_failure( - grpc_exec_ctx *exec_ctx, grpc_transport_stream_op_batch *op, - grpc_error *error, grpc_call_combiner *call_combiner); + grpc_exec_ctx* exec_ctx, grpc_transport_stream_op_batch* op, + grpc_error* error, grpc_call_combiner* call_combiner); -char *grpc_transport_stream_op_batch_string(grpc_transport_stream_op_batch *op); -char *grpc_transport_op_string(grpc_transport_op *op); +char* grpc_transport_stream_op_batch_string(grpc_transport_stream_op_batch* op); +char* grpc_transport_op_string(grpc_transport_op* op); /* Send a batch of operations on a transport @@ -315,45 +309,38 @@ char *grpc_transport_op_string(grpc_transport_op *op); non-NULL and previously initialized by the same transport. op - a grpc_transport_stream_op_batch specifying the op to perform */ -void grpc_transport_perform_stream_op(grpc_exec_ctx *exec_ctx, - grpc_transport *transport, - grpc_stream *stream, - grpc_transport_stream_op_batch *op); +void grpc_transport_perform_stream_op(grpc_exec_ctx* exec_ctx, + grpc_transport* transport, + grpc_stream* stream, + grpc_transport_stream_op_batch* op); -void grpc_transport_perform_op(grpc_exec_ctx *exec_ctx, - grpc_transport *transport, - grpc_transport_op *op); +void grpc_transport_perform_op(grpc_exec_ctx* exec_ctx, + grpc_transport* transport, + grpc_transport_op* op); /* Send a ping on a transport Calls cb with user data when a response is received. */ -void grpc_transport_ping(grpc_transport *transport, grpc_closure *cb); +void grpc_transport_ping(grpc_transport* transport, grpc_closure* cb); /* Advise peer of pending connection termination. */ -void grpc_transport_goaway(grpc_transport *transport, grpc_status_code status, +void grpc_transport_goaway(grpc_transport* transport, grpc_status_code status, grpc_slice debug_data); -/* Close a transport. Aborts all open streams. */ -void grpc_transport_close(grpc_transport *transport); - /* Destroy the transport */ -void grpc_transport_destroy(grpc_exec_ctx *exec_ctx, grpc_transport *transport); +void grpc_transport_destroy(grpc_exec_ctx* exec_ctx, grpc_transport* transport); /* Get the endpoint used by \a transport */ -grpc_endpoint *grpc_transport_get_endpoint(grpc_exec_ctx *exec_ctx, - grpc_transport *transport); +grpc_endpoint* grpc_transport_get_endpoint(grpc_exec_ctx* exec_ctx, + grpc_transport* transport); /* Allocate a grpc_transport_op, and preconfigure the on_consumed closure to \a on_consumed and then delete the returned transport op */ -grpc_transport_op *grpc_make_transport_op(grpc_closure *on_consumed); +grpc_transport_op* grpc_make_transport_op(grpc_closure* on_consumed); /* Allocate a grpc_transport_stream_op_batch, and preconfigure the on_consumed closure to \a on_consumed and then delete the returned transport op */ -grpc_transport_stream_op_batch *grpc_make_transport_stream_op( - grpc_closure *on_consumed); - -#ifdef __cplusplus -} -#endif +grpc_transport_stream_op_batch* grpc_make_transport_stream_op( + grpc_closure* on_consumed); #endif /* GRPC_CORE_LIB_TRANSPORT_TRANSPORT_H */ diff --git a/src/core/lib/transport/transport_impl.h b/src/core/lib/transport/transport_impl.h index 445fb41ab16..46be61427e5 100644 --- a/src/core/lib/transport/transport_impl.h +++ b/src/core/lib/transport/transport_impl.h @@ -21,60 +21,52 @@ #include "src/core/lib/transport/transport.h" -#ifdef __cplusplus -extern "C" { -#endif - typedef struct grpc_transport_vtable { /* Memory required for a single stream element - this is allocated by upper layers and initialized by the transport */ size_t sizeof_stream; /* = sizeof(transport stream) */ /* name of this transport implementation */ - const char *name; + const char* name; /* implementation of grpc_transport_init_stream */ - int (*init_stream)(grpc_exec_ctx *exec_ctx, grpc_transport *self, - grpc_stream *stream, grpc_stream_refcount *refcount, - const void *server_data, gpr_arena *arena); + int (*init_stream)(grpc_exec_ctx* exec_ctx, grpc_transport* self, + grpc_stream* stream, grpc_stream_refcount* refcount, + const void* server_data, gpr_arena* arena); /* implementation of grpc_transport_set_pollset */ - void (*set_pollset)(grpc_exec_ctx *exec_ctx, grpc_transport *self, - grpc_stream *stream, grpc_pollset *pollset); + void (*set_pollset)(grpc_exec_ctx* exec_ctx, grpc_transport* self, + grpc_stream* stream, grpc_pollset* pollset); /* implementation of grpc_transport_set_pollset */ - void (*set_pollset_set)(grpc_exec_ctx *exec_ctx, grpc_transport *self, - grpc_stream *stream, grpc_pollset_set *pollset_set); + void (*set_pollset_set)(grpc_exec_ctx* exec_ctx, grpc_transport* self, + grpc_stream* stream, grpc_pollset_set* pollset_set); /* implementation of grpc_transport_perform_stream_op */ - void (*perform_stream_op)(grpc_exec_ctx *exec_ctx, grpc_transport *self, - grpc_stream *stream, - grpc_transport_stream_op_batch *op); + void (*perform_stream_op)(grpc_exec_ctx* exec_ctx, grpc_transport* self, + grpc_stream* stream, + grpc_transport_stream_op_batch* op); /* implementation of grpc_transport_perform_op */ - void (*perform_op)(grpc_exec_ctx *exec_ctx, grpc_transport *self, - grpc_transport_op *op); + void (*perform_op)(grpc_exec_ctx* exec_ctx, grpc_transport* self, + grpc_transport_op* op); /* implementation of grpc_transport_destroy_stream */ - void (*destroy_stream)(grpc_exec_ctx *exec_ctx, grpc_transport *self, - grpc_stream *stream, - grpc_closure *then_schedule_closure); + void (*destroy_stream)(grpc_exec_ctx* exec_ctx, grpc_transport* self, + grpc_stream* stream, + grpc_closure* then_schedule_closure); /* implementation of grpc_transport_destroy */ - void (*destroy)(grpc_exec_ctx *exec_ctx, grpc_transport *self); + void (*destroy)(grpc_exec_ctx* exec_ctx, grpc_transport* self); /* implementation of grpc_transport_get_endpoint */ - grpc_endpoint *(*get_endpoint)(grpc_exec_ctx *exec_ctx, grpc_transport *self); + grpc_endpoint* (*get_endpoint)(grpc_exec_ctx* exec_ctx, grpc_transport* self); } grpc_transport_vtable; /* an instance of a grpc transport */ struct grpc_transport { /* pointer to a vtable defining operations on this transport */ - const grpc_transport_vtable *vtable; + const grpc_transport_vtable* vtable; }; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_LIB_TRANSPORT_TRANSPORT_IMPL_H */ diff --git a/src/core/lib/transport/transport_op_string.cc b/src/core/lib/transport/transport_op_string.cc index cc11b0cc49e..e69ab025707 100644 --- a/src/core/lib/transport/transport_op_string.cc +++ b/src/core/lib/transport/transport_op_string.cc @@ -35,7 +35,7 @@ /* These routines are here to facilitate debugging - they produce string representations of various transport data structures */ -static void put_metadata(gpr_strvec *b, grpc_mdelem md) { +static void put_metadata(gpr_strvec* b, grpc_mdelem md) { gpr_strvec_add(b, gpr_strdup("key=")); gpr_strvec_add( b, grpc_dump_slice(GRPC_MDKEY(md), GPR_DUMP_HEX | GPR_DUMP_ASCII)); @@ -45,23 +45,23 @@ static void put_metadata(gpr_strvec *b, grpc_mdelem md) { b, grpc_dump_slice(GRPC_MDVALUE(md), GPR_DUMP_HEX | GPR_DUMP_ASCII)); } -static void put_metadata_list(gpr_strvec *b, grpc_metadata_batch md) { - grpc_linked_mdelem *m; - for (m = md.list.head; m != NULL; m = m->next) { +static void put_metadata_list(gpr_strvec* b, grpc_metadata_batch md) { + grpc_linked_mdelem* m; + for (m = md.list.head; m != nullptr; m = m->next) { if (m != md.list.head) gpr_strvec_add(b, gpr_strdup(", ")); put_metadata(b, m->md); } if (md.deadline != GRPC_MILLIS_INF_FUTURE) { - char *tmp; + char* tmp; gpr_asprintf(&tmp, " deadline=%" PRIdPTR, md.deadline); gpr_strvec_add(b, tmp); } } -char *grpc_transport_stream_op_batch_string( - grpc_transport_stream_op_batch *op) { - char *tmp; - char *out; +char* grpc_transport_stream_op_batch_string( + grpc_transport_stream_op_batch* op) { + char* tmp; + char* out; gpr_strvec b; gpr_strvec_init(&b); @@ -107,7 +107,7 @@ char *grpc_transport_stream_op_batch_string( if (op->cancel_stream) { gpr_strvec_add(&b, gpr_strdup(" ")); - const char *msg = + const char* msg = grpc_error_string(op->payload->cancel_stream.cancel_error); gpr_asprintf(&tmp, "CANCEL:%s", msg); @@ -121,24 +121,24 @@ char *grpc_transport_stream_op_batch_string( gpr_strvec_add(&b, tmp); } - out = gpr_strvec_flatten(&b, NULL); + out = gpr_strvec_flatten(&b, nullptr); gpr_strvec_destroy(&b); return out; } -char *grpc_transport_op_string(grpc_transport_op *op) { - char *tmp; - char *out; +char* grpc_transport_op_string(grpc_transport_op* op) { + char* tmp; + char* out; bool first = true; gpr_strvec b; gpr_strvec_init(&b); - if (op->on_connectivity_state_change != NULL) { + if (op->on_connectivity_state_change != nullptr) { if (!first) gpr_strvec_add(&b, gpr_strdup(" ")); first = false; - if (op->connectivity_state != NULL) { + if (op->connectivity_state != nullptr) { gpr_asprintf(&tmp, "ON_CONNECTIVITY_STATE_CHANGE:p=%p:from=%s", op->on_connectivity_state_change, grpc_connectivity_state_name(*op->connectivity_state)); @@ -153,7 +153,7 @@ char *grpc_transport_op_string(grpc_transport_op *op) { if (op->disconnect_with_error != GRPC_ERROR_NONE) { if (!first) gpr_strvec_add(&b, gpr_strdup(" ")); first = false; - const char *err = grpc_error_string(op->disconnect_with_error); + const char* err = grpc_error_string(op->disconnect_with_error); gpr_asprintf(&tmp, "DISCONNECT:%s", err); gpr_strvec_add(&b, tmp); } @@ -161,7 +161,7 @@ char *grpc_transport_op_string(grpc_transport_op *op) { if (op->goaway_error) { if (!first) gpr_strvec_add(&b, gpr_strdup(" ")); first = false; - const char *msg = grpc_error_string(op->goaway_error); + const char* msg = grpc_error_string(op->goaway_error); gpr_asprintf(&tmp, "SEND_GOAWAY:%s", msg); gpr_strvec_add(&b, tmp); @@ -175,34 +175,34 @@ char *grpc_transport_op_string(grpc_transport_op *op) { gpr_strvec_add(&b, tmp); } - if (op->bind_pollset != NULL) { + if (op->bind_pollset != nullptr) { if (!first) gpr_strvec_add(&b, gpr_strdup(" ")); first = false; gpr_strvec_add(&b, gpr_strdup("BIND_POLLSET")); } - if (op->bind_pollset_set != NULL) { + if (op->bind_pollset_set != nullptr) { if (!first) gpr_strvec_add(&b, gpr_strdup(" ")); first = false; gpr_strvec_add(&b, gpr_strdup("BIND_POLLSET_SET")); } - if (op->send_ping != NULL) { + if (op->send_ping != nullptr) { if (!first) gpr_strvec_add(&b, gpr_strdup(" ")); - first = false; + // first = false; gpr_strvec_add(&b, gpr_strdup("SEND_PING")); } - out = gpr_strvec_flatten(&b, NULL); + out = gpr_strvec_flatten(&b, nullptr); gpr_strvec_destroy(&b); return out; } -void grpc_call_log_op(const char *file, int line, gpr_log_severity severity, - grpc_call_element *elem, - grpc_transport_stream_op_batch *op) { - char *str = grpc_transport_stream_op_batch_string(op); +void grpc_call_log_op(const char* file, int line, gpr_log_severity severity, + grpc_call_element* elem, + grpc_transport_stream_op_batch* op) { + char* str = grpc_transport_stream_op_batch_string(op); gpr_log(file, line, severity, "OP[%s:%p]: %s", elem->filter->name, elem, str); gpr_free(str); } diff --git a/src/core/plugin_registry/grpc_cronet_plugin_registry.cc b/src/core/plugin_registry/grpc_cronet_plugin_registry.cc index e0422f67503..101e29c4819 100644 --- a/src/core/plugin_registry/grpc_cronet_plugin_registry.cc +++ b/src/core/plugin_registry/grpc_cronet_plugin_registry.cc @@ -18,18 +18,18 @@ #include -extern "C" void grpc_http_filters_init(void); -extern "C" void grpc_http_filters_shutdown(void); -extern "C" void grpc_chttp2_plugin_init(void); -extern "C" void grpc_chttp2_plugin_shutdown(void); -extern "C" void grpc_deadline_filter_init(void); -extern "C" void grpc_deadline_filter_shutdown(void); -extern "C" void grpc_client_channel_init(void); -extern "C" void grpc_client_channel_shutdown(void); -extern "C" void grpc_tsi_gts_init(void); -extern "C" void grpc_tsi_gts_shutdown(void); -extern "C" void grpc_server_load_reporting_plugin_init(void); -extern "C" void grpc_server_load_reporting_plugin_shutdown(void); +void grpc_http_filters_init(void); +void grpc_http_filters_shutdown(void); +void grpc_chttp2_plugin_init(void); +void grpc_chttp2_plugin_shutdown(void); +void grpc_deadline_filter_init(void); +void grpc_deadline_filter_shutdown(void); +void grpc_client_channel_init(void); +void grpc_client_channel_shutdown(void); +void grpc_tsi_gts_init(void); +void grpc_tsi_gts_shutdown(void); +void grpc_server_load_reporting_plugin_init(void); +void grpc_server_load_reporting_plugin_shutdown(void); void grpc_register_built_in_plugins(void) { grpc_register_plugin(grpc_http_filters_init, diff --git a/src/core/plugin_registry/grpc_plugin_registry.cc b/src/core/plugin_registry/grpc_plugin_registry.cc index 339c9bb3670..89be3517857 100644 --- a/src/core/plugin_registry/grpc_plugin_registry.cc +++ b/src/core/plugin_registry/grpc_plugin_registry.cc @@ -18,40 +18,40 @@ #include -extern "C" void grpc_http_filters_init(void); -extern "C" void grpc_http_filters_shutdown(void); -extern "C" void grpc_chttp2_plugin_init(void); -extern "C" void grpc_chttp2_plugin_shutdown(void); -extern "C" void grpc_tsi_gts_init(void); -extern "C" void grpc_tsi_gts_shutdown(void); -extern "C" void grpc_deadline_filter_init(void); -extern "C" void grpc_deadline_filter_shutdown(void); -extern "C" void grpc_client_channel_init(void); -extern "C" void grpc_client_channel_shutdown(void); -extern "C" void grpc_inproc_plugin_init(void); -extern "C" void grpc_inproc_plugin_shutdown(void); -extern "C" void grpc_resolver_fake_init(void); -extern "C" void grpc_resolver_fake_shutdown(void); -extern "C" void grpc_lb_policy_grpclb_init(void); -extern "C" void grpc_lb_policy_grpclb_shutdown(void); -extern "C" void grpc_lb_policy_pick_first_init(void); -extern "C" void grpc_lb_policy_pick_first_shutdown(void); -extern "C" void grpc_lb_policy_round_robin_init(void); -extern "C" void grpc_lb_policy_round_robin_shutdown(void); -extern "C" void grpc_resolver_dns_ares_init(void); -extern "C" void grpc_resolver_dns_ares_shutdown(void); -extern "C" void grpc_resolver_dns_native_init(void); -extern "C" void grpc_resolver_dns_native_shutdown(void); -extern "C" void grpc_resolver_sockaddr_init(void); -extern "C" void grpc_resolver_sockaddr_shutdown(void); -extern "C" void grpc_server_load_reporting_plugin_init(void); -extern "C" void grpc_server_load_reporting_plugin_shutdown(void); -extern "C" void grpc_max_age_filter_init(void); -extern "C" void grpc_max_age_filter_shutdown(void); -extern "C" void grpc_message_size_filter_init(void); -extern "C" void grpc_message_size_filter_shutdown(void); -extern "C" void grpc_workaround_cronet_compression_filter_init(void); -extern "C" void grpc_workaround_cronet_compression_filter_shutdown(void); +void grpc_http_filters_init(void); +void grpc_http_filters_shutdown(void); +void grpc_chttp2_plugin_init(void); +void grpc_chttp2_plugin_shutdown(void); +void grpc_tsi_gts_init(void); +void grpc_tsi_gts_shutdown(void); +void grpc_deadline_filter_init(void); +void grpc_deadline_filter_shutdown(void); +void grpc_client_channel_init(void); +void grpc_client_channel_shutdown(void); +void grpc_inproc_plugin_init(void); +void grpc_inproc_plugin_shutdown(void); +void grpc_resolver_fake_init(void); +void grpc_resolver_fake_shutdown(void); +void grpc_lb_policy_grpclb_init(void); +void grpc_lb_policy_grpclb_shutdown(void); +void grpc_lb_policy_pick_first_init(void); +void grpc_lb_policy_pick_first_shutdown(void); +void grpc_lb_policy_round_robin_init(void); +void grpc_lb_policy_round_robin_shutdown(void); +void grpc_resolver_dns_ares_init(void); +void grpc_resolver_dns_ares_shutdown(void); +void grpc_resolver_dns_native_init(void); +void grpc_resolver_dns_native_shutdown(void); +void grpc_resolver_sockaddr_init(void); +void grpc_resolver_sockaddr_shutdown(void); +void grpc_server_load_reporting_plugin_init(void); +void grpc_server_load_reporting_plugin_shutdown(void); +void grpc_max_age_filter_init(void); +void grpc_max_age_filter_shutdown(void); +void grpc_message_size_filter_init(void); +void grpc_message_size_filter_shutdown(void); +void grpc_workaround_cronet_compression_filter_init(void); +void grpc_workaround_cronet_compression_filter_shutdown(void); void grpc_register_built_in_plugins(void) { grpc_register_plugin(grpc_http_filters_init, diff --git a/src/core/plugin_registry/grpc_unsecure_plugin_registry.cc b/src/core/plugin_registry/grpc_unsecure_plugin_registry.cc index c9fc17d34d3..d73f946241e 100644 --- a/src/core/plugin_registry/grpc_unsecure_plugin_registry.cc +++ b/src/core/plugin_registry/grpc_unsecure_plugin_registry.cc @@ -18,38 +18,38 @@ #include -extern "C" void grpc_http_filters_init(void); -extern "C" void grpc_http_filters_shutdown(void); -extern "C" void grpc_chttp2_plugin_init(void); -extern "C" void grpc_chttp2_plugin_shutdown(void); -extern "C" void grpc_deadline_filter_init(void); -extern "C" void grpc_deadline_filter_shutdown(void); -extern "C" void grpc_client_channel_init(void); -extern "C" void grpc_client_channel_shutdown(void); -extern "C" void grpc_inproc_plugin_init(void); -extern "C" void grpc_inproc_plugin_shutdown(void); -extern "C" void grpc_resolver_dns_ares_init(void); -extern "C" void grpc_resolver_dns_ares_shutdown(void); -extern "C" void grpc_resolver_dns_native_init(void); -extern "C" void grpc_resolver_dns_native_shutdown(void); -extern "C" void grpc_resolver_sockaddr_init(void); -extern "C" void grpc_resolver_sockaddr_shutdown(void); -extern "C" void grpc_resolver_fake_init(void); -extern "C" void grpc_resolver_fake_shutdown(void); -extern "C" void grpc_server_load_reporting_plugin_init(void); -extern "C" void grpc_server_load_reporting_plugin_shutdown(void); -extern "C" void grpc_lb_policy_grpclb_init(void); -extern "C" void grpc_lb_policy_grpclb_shutdown(void); -extern "C" void grpc_lb_policy_pick_first_init(void); -extern "C" void grpc_lb_policy_pick_first_shutdown(void); -extern "C" void grpc_lb_policy_round_robin_init(void); -extern "C" void grpc_lb_policy_round_robin_shutdown(void); -extern "C" void grpc_max_age_filter_init(void); -extern "C" void grpc_max_age_filter_shutdown(void); -extern "C" void grpc_message_size_filter_init(void); -extern "C" void grpc_message_size_filter_shutdown(void); -extern "C" void grpc_workaround_cronet_compression_filter_init(void); -extern "C" void grpc_workaround_cronet_compression_filter_shutdown(void); +void grpc_http_filters_init(void); +void grpc_http_filters_shutdown(void); +void grpc_chttp2_plugin_init(void); +void grpc_chttp2_plugin_shutdown(void); +void grpc_deadline_filter_init(void); +void grpc_deadline_filter_shutdown(void); +void grpc_client_channel_init(void); +void grpc_client_channel_shutdown(void); +void grpc_inproc_plugin_init(void); +void grpc_inproc_plugin_shutdown(void); +void grpc_resolver_dns_ares_init(void); +void grpc_resolver_dns_ares_shutdown(void); +void grpc_resolver_dns_native_init(void); +void grpc_resolver_dns_native_shutdown(void); +void grpc_resolver_sockaddr_init(void); +void grpc_resolver_sockaddr_shutdown(void); +void grpc_resolver_fake_init(void); +void grpc_resolver_fake_shutdown(void); +void grpc_server_load_reporting_plugin_init(void); +void grpc_server_load_reporting_plugin_shutdown(void); +void grpc_lb_policy_grpclb_init(void); +void grpc_lb_policy_grpclb_shutdown(void); +void grpc_lb_policy_pick_first_init(void); +void grpc_lb_policy_pick_first_shutdown(void); +void grpc_lb_policy_round_robin_init(void); +void grpc_lb_policy_round_robin_shutdown(void); +void grpc_max_age_filter_init(void); +void grpc_max_age_filter_shutdown(void); +void grpc_message_size_filter_init(void); +void grpc_message_size_filter_shutdown(void); +void grpc_workaround_cronet_compression_filter_init(void); +void grpc_workaround_cronet_compression_filter_shutdown(void); void grpc_register_built_in_plugins(void) { grpc_register_plugin(grpc_http_filters_init, diff --git a/src/core/tsi/fake_transport_security.cc b/src/core/tsi/fake_transport_security.cc index 349dcf5cb8f..f2f365fc0fe 100644 --- a/src/core/tsi/fake_transport_security.cc +++ b/src/core/tsi/fake_transport_security.cc @@ -41,7 +41,7 @@ where the size field value is the size of the size field plus the size of the data encoded in little endian on 4 bytes. */ typedef struct { - unsigned char *data; + unsigned char* data; size_t size; size_t allocated_size; size_t offset; @@ -63,7 +63,7 @@ typedef struct { int needs_incoming_message; tsi_fake_frame incoming_frame; tsi_fake_frame outgoing_frame; - unsigned char *outgoing_bytes_buffer; + unsigned char* outgoing_bytes_buffer; size_t outgoing_bytes_buffer_size; tsi_result result; } tsi_fake_handshaker; @@ -85,10 +85,10 @@ typedef struct { /* --- Utils. ---*/ -static const char *tsi_fake_handshake_message_strings[] = { +static const char* tsi_fake_handshake_message_strings[] = { "CLIENT_INIT", "SERVER_INIT", "CLIENT_FINISHED", "SERVER_FINISHED"}; -static const char *tsi_fake_handshake_message_to_string(int msg) { +static const char* tsi_fake_handshake_message_to_string(int msg) { if (msg < 0 || msg >= TSI_FAKE_HANDSHAKE_MESSAGE_MAX) { gpr_log(GPR_ERROR, "Invalid message %d", msg); return "UNKNOWN"; @@ -97,7 +97,7 @@ static const char *tsi_fake_handshake_message_to_string(int msg) { } static tsi_result tsi_fake_handshake_message_from_string( - const char *msg_string, tsi_fake_handshake_message *msg) { + const char* msg_string, tsi_fake_handshake_message* msg) { for (int i = 0; i < TSI_FAKE_HANDSHAKE_MESSAGE_MAX; i++) { if (strncmp(msg_string, tsi_fake_handshake_message_strings[i], strlen(tsi_fake_handshake_message_strings[i])) == 0) { @@ -109,22 +109,22 @@ static tsi_result tsi_fake_handshake_message_from_string( return TSI_DATA_CORRUPTED; } -static uint32_t load32_little_endian(const unsigned char *buf) { +static uint32_t load32_little_endian(const unsigned char* buf) { return ((uint32_t)(buf[0]) | (uint32_t)(buf[1] << 8) | (uint32_t)(buf[2] << 16) | (uint32_t)(buf[3] << 24)); } -static void store32_little_endian(uint32_t value, unsigned char *buf) { +static void store32_little_endian(uint32_t value, unsigned char* buf) { buf[3] = (unsigned char)((value >> 24) & 0xFF); buf[2] = (unsigned char)((value >> 16) & 0xFF); buf[1] = (unsigned char)((value >> 8) & 0xFF); buf[0] = (unsigned char)((value)&0xFF); } -static uint32_t read_frame_size(const grpc_slice_buffer *sb) { - GPR_ASSERT(sb != NULL && sb->length >= TSI_FAKE_FRAME_HEADER_SIZE); +static uint32_t read_frame_size(const grpc_slice_buffer* sb) { + GPR_ASSERT(sb != nullptr && sb->length >= TSI_FAKE_FRAME_HEADER_SIZE); uint8_t frame_size_buffer[TSI_FAKE_FRAME_HEADER_SIZE]; - uint8_t *buf = frame_size_buffer; + uint8_t* buf = frame_size_buffer; /* Copies the first 4 bytes to a temporary buffer. */ size_t remaining = TSI_FAKE_FRAME_HEADER_SIZE; for (size_t i = 0; i < sb->count; i++) { @@ -143,7 +143,7 @@ static uint32_t read_frame_size(const grpc_slice_buffer *sb) { return load32_little_endian(frame_size_buffer); } -static void tsi_fake_frame_reset(tsi_fake_frame *frame, int needs_draining) { +static void tsi_fake_frame_reset(tsi_fake_frame* frame, int needs_draining) { frame->offset = 0; frame->needs_draining = needs_draining; if (!needs_draining) frame->size = 0; @@ -151,13 +151,13 @@ static void tsi_fake_frame_reset(tsi_fake_frame *frame, int needs_draining) { /* Checks if the frame's allocated size is at least frame->size, and reallocs * more memory if necessary. */ -static void tsi_fake_frame_ensure_size(tsi_fake_frame *frame) { - if (frame->data == NULL) { +static void tsi_fake_frame_ensure_size(tsi_fake_frame* frame) { + if (frame->data == nullptr) { frame->allocated_size = frame->size; - frame->data = (unsigned char *)gpr_malloc(frame->allocated_size); + frame->data = (unsigned char*)gpr_malloc(frame->allocated_size); } else if (frame->size > frame->allocated_size) { - unsigned char *new_data = - (unsigned char *)gpr_realloc(frame->data, frame->size); + unsigned char* new_data = + (unsigned char*)gpr_realloc(frame->data, frame->size); frame->data = new_data; frame->allocated_size = frame->size; } @@ -166,17 +166,17 @@ static void tsi_fake_frame_ensure_size(tsi_fake_frame *frame) { /* Decodes the serialized fake frame contained in incoming_bytes, and fills * frame with the contents of the decoded frame. * This method should not be called if frame->needs_framing is not 0. */ -static tsi_result tsi_fake_frame_decode(const unsigned char *incoming_bytes, - size_t *incoming_bytes_size, - tsi_fake_frame *frame) { +static tsi_result tsi_fake_frame_decode(const unsigned char* incoming_bytes, + size_t* incoming_bytes_size, + tsi_fake_frame* frame) { size_t available_size = *incoming_bytes_size; size_t to_read_size = 0; - const unsigned char *bytes_cursor = incoming_bytes; + const unsigned char* bytes_cursor = incoming_bytes; if (frame->needs_draining) return TSI_INTERNAL_ERROR; - if (frame->data == NULL) { + if (frame->data == nullptr) { frame->allocated_size = TSI_FAKE_FRAME_INITIAL_ALLOCATED_SIZE; - frame->data = (unsigned char *)gpr_malloc(frame->allocated_size); + frame->data = (unsigned char*)gpr_malloc(frame->allocated_size); } if (frame->offset < TSI_FAKE_FRAME_HEADER_SIZE) { @@ -215,9 +215,9 @@ static tsi_result tsi_fake_frame_decode(const unsigned char *incoming_bytes, /* Encodes a fake frame into its wire format and places the result in * outgoing_bytes. outgoing_bytes_size indicates the size of the encoded frame. * This method should not be called if frame->needs_framing is 0. */ -static tsi_result tsi_fake_frame_encode(unsigned char *outgoing_bytes, - size_t *outgoing_bytes_size, - tsi_fake_frame *frame) { +static tsi_result tsi_fake_frame_encode(unsigned char* outgoing_bytes, + size_t* outgoing_bytes_size, + tsi_fake_frame* frame) { size_t to_write_size = frame->size - frame->offset; if (!frame->needs_draining) return TSI_INTERNAL_ERROR; if (*outgoing_bytes_size < to_write_size) { @@ -233,8 +233,8 @@ static tsi_result tsi_fake_frame_encode(unsigned char *outgoing_bytes, /* Sets the payload of a fake frame to contain the given data blob, where * data_size indicates the size of data. */ -static tsi_result tsi_fake_frame_set_data(unsigned char *data, size_t data_size, - tsi_fake_frame *frame) { +static tsi_result tsi_fake_frame_set_data(unsigned char* data, size_t data_size, + tsi_fake_frame* frame) { frame->offset = 0; frame->size = data_size + TSI_FAKE_FRAME_HEADER_SIZE; tsi_fake_frame_ensure_size(frame); @@ -245,24 +245,24 @@ static tsi_result tsi_fake_frame_set_data(unsigned char *data, size_t data_size, } /* Destroys the contents of a fake frame. */ -static void tsi_fake_frame_destruct(tsi_fake_frame *frame) { - if (frame->data != NULL) gpr_free(frame->data); +static void tsi_fake_frame_destruct(tsi_fake_frame* frame) { + if (frame->data != nullptr) gpr_free(frame->data); } /* --- tsi_frame_protector methods implementation. ---*/ -static tsi_result fake_protector_protect(tsi_frame_protector *self, - const unsigned char *unprotected_bytes, - size_t *unprotected_bytes_size, - unsigned char *protected_output_frames, - size_t *protected_output_frames_size) { +static tsi_result fake_protector_protect(tsi_frame_protector* self, + const unsigned char* unprotected_bytes, + size_t* unprotected_bytes_size, + unsigned char* protected_output_frames, + size_t* protected_output_frames_size) { tsi_result result = TSI_OK; - tsi_fake_frame_protector *impl = (tsi_fake_frame_protector *)self; + tsi_fake_frame_protector* impl = (tsi_fake_frame_protector*)self; unsigned char frame_header[TSI_FAKE_FRAME_HEADER_SIZE]; - tsi_fake_frame *frame = &impl->protect_frame; + tsi_fake_frame* frame = &impl->protect_frame; size_t saved_output_size = *protected_output_frames_size; size_t drained_size = 0; - size_t *num_bytes_written = protected_output_frames_size; + size_t* num_bytes_written = protected_output_frames_size; *num_bytes_written = 0; /* Try to drain first. */ @@ -313,11 +313,11 @@ static tsi_result fake_protector_protect(tsi_frame_protector *self, } static tsi_result fake_protector_protect_flush( - tsi_frame_protector *self, unsigned char *protected_output_frames, - size_t *protected_output_frames_size, size_t *still_pending_size) { + tsi_frame_protector* self, unsigned char* protected_output_frames, + size_t* protected_output_frames_size, size_t* still_pending_size) { tsi_result result = TSI_OK; - tsi_fake_frame_protector *impl = (tsi_fake_frame_protector *)self; - tsi_fake_frame *frame = &impl->protect_frame; + tsi_fake_frame_protector* impl = (tsi_fake_frame_protector*)self; + tsi_fake_frame* frame = &impl->protect_frame; if (!frame->needs_draining) { /* Create a short frame. */ frame->size = frame->offset; @@ -334,15 +334,15 @@ static tsi_result fake_protector_protect_flush( } static tsi_result fake_protector_unprotect( - tsi_frame_protector *self, const unsigned char *protected_frames_bytes, - size_t *protected_frames_bytes_size, unsigned char *unprotected_bytes, - size_t *unprotected_bytes_size) { + tsi_frame_protector* self, const unsigned char* protected_frames_bytes, + size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes, + size_t* unprotected_bytes_size) { tsi_result result = TSI_OK; - tsi_fake_frame_protector *impl = (tsi_fake_frame_protector *)self; - tsi_fake_frame *frame = &impl->unprotect_frame; + tsi_fake_frame_protector* impl = (tsi_fake_frame_protector*)self; + tsi_fake_frame* frame = &impl->unprotect_frame; size_t saved_output_size = *unprotected_bytes_size; size_t drained_size = 0; - size_t *num_bytes_written = unprotected_bytes_size; + size_t* num_bytes_written = unprotected_bytes_size; *num_bytes_written = 0; /* Try to drain first. */ @@ -382,29 +382,32 @@ static tsi_result fake_protector_unprotect( return result; } -static void fake_protector_destroy(tsi_frame_protector *self) { - tsi_fake_frame_protector *impl = (tsi_fake_frame_protector *)self; +static void fake_protector_destroy(tsi_frame_protector* self) { + tsi_fake_frame_protector* impl = (tsi_fake_frame_protector*)self; tsi_fake_frame_destruct(&impl->protect_frame); tsi_fake_frame_destruct(&impl->unprotect_frame); gpr_free(self); } static const tsi_frame_protector_vtable frame_protector_vtable = { - fake_protector_protect, fake_protector_protect_flush, - fake_protector_unprotect, fake_protector_destroy, + fake_protector_protect, + fake_protector_protect_flush, + fake_protector_unprotect, + fake_protector_destroy, }; /* --- tsi_zero_copy_grpc_protector methods implementation. ---*/ static tsi_result fake_zero_copy_grpc_protector_protect( - grpc_exec_ctx *exec_ctx, tsi_zero_copy_grpc_protector *self, - grpc_slice_buffer *unprotected_slices, - grpc_slice_buffer *protected_slices) { - if (self == NULL || unprotected_slices == NULL || protected_slices == NULL) { + grpc_exec_ctx* exec_ctx, tsi_zero_copy_grpc_protector* self, + grpc_slice_buffer* unprotected_slices, + grpc_slice_buffer* protected_slices) { + if (self == nullptr || unprotected_slices == nullptr || + protected_slices == nullptr) { return TSI_INVALID_ARGUMENT; } - tsi_fake_zero_copy_grpc_protector *impl = - (tsi_fake_zero_copy_grpc_protector *)self; + tsi_fake_zero_copy_grpc_protector* impl = + (tsi_fake_zero_copy_grpc_protector*)self; /* Protects each frame. */ while (unprotected_slices->length > 0) { size_t frame_length = @@ -421,14 +424,15 @@ static tsi_result fake_zero_copy_grpc_protector_protect( } static tsi_result fake_zero_copy_grpc_protector_unprotect( - grpc_exec_ctx *exec_ctx, tsi_zero_copy_grpc_protector *self, - grpc_slice_buffer *protected_slices, - grpc_slice_buffer *unprotected_slices) { - if (self == NULL || unprotected_slices == NULL || protected_slices == NULL) { + grpc_exec_ctx* exec_ctx, tsi_zero_copy_grpc_protector* self, + grpc_slice_buffer* protected_slices, + grpc_slice_buffer* unprotected_slices) { + if (self == nullptr || unprotected_slices == nullptr || + protected_slices == nullptr) { return TSI_INVALID_ARGUMENT; } - tsi_fake_zero_copy_grpc_protector *impl = - (tsi_fake_zero_copy_grpc_protector *)self; + tsi_fake_zero_copy_grpc_protector* impl = + (tsi_fake_zero_copy_grpc_protector*)self; grpc_slice_buffer_move_into(protected_slices, &impl->protected_sb); /* Unprotect each frame, if we get a full frame. */ while (impl->protected_sb.length >= TSI_FAKE_FRAME_HEADER_SIZE) { @@ -456,10 +460,10 @@ static tsi_result fake_zero_copy_grpc_protector_unprotect( } static void fake_zero_copy_grpc_protector_destroy( - grpc_exec_ctx *exec_ctx, tsi_zero_copy_grpc_protector *self) { - if (self == NULL) return; - tsi_fake_zero_copy_grpc_protector *impl = - (tsi_fake_zero_copy_grpc_protector *)self; + grpc_exec_ctx* exec_ctx, tsi_zero_copy_grpc_protector* self) { + if (self == nullptr) return; + tsi_fake_zero_copy_grpc_protector* impl = + (tsi_fake_zero_copy_grpc_protector*)self; grpc_slice_buffer_destroy_internal(exec_ctx, &impl->header_sb); grpc_slice_buffer_destroy_internal(exec_ctx, &impl->protected_sb); gpr_free(impl); @@ -476,12 +480,12 @@ static const tsi_zero_copy_grpc_protector_vtable typedef struct { tsi_handshaker_result base; - unsigned char *unused_bytes; + unsigned char* unused_bytes; size_t unused_bytes_size; } fake_handshaker_result; static tsi_result fake_handshaker_result_extract_peer( - const tsi_handshaker_result *self, tsi_peer *peer) { + const tsi_handshaker_result* self, tsi_peer* peer) { /* Construct a tsi_peer with 1 property: certificate type. */ tsi_result result = tsi_construct_peer(1, peer); if (result != TSI_OK) return result; @@ -493,32 +497,32 @@ static tsi_result fake_handshaker_result_extract_peer( } static tsi_result fake_handshaker_result_create_zero_copy_grpc_protector( - void *exec_ctx, const tsi_handshaker_result *self, - size_t *max_output_protected_frame_size, - tsi_zero_copy_grpc_protector **protector) { + void* exec_ctx, const tsi_handshaker_result* self, + size_t* max_output_protected_frame_size, + tsi_zero_copy_grpc_protector** protector) { *protector = tsi_create_fake_zero_copy_grpc_protector(max_output_protected_frame_size); return TSI_OK; } static tsi_result fake_handshaker_result_create_frame_protector( - const tsi_handshaker_result *self, size_t *max_output_protected_frame_size, - tsi_frame_protector **protector) { + const tsi_handshaker_result* self, size_t* max_output_protected_frame_size, + tsi_frame_protector** protector) { *protector = tsi_create_fake_frame_protector(max_output_protected_frame_size); return TSI_OK; } static tsi_result fake_handshaker_result_get_unused_bytes( - const tsi_handshaker_result *self, const unsigned char **bytes, - size_t *bytes_size) { - fake_handshaker_result *result = (fake_handshaker_result *)self; + const tsi_handshaker_result* self, const unsigned char** bytes, + size_t* bytes_size) { + fake_handshaker_result* result = (fake_handshaker_result*)self; *bytes_size = result->unused_bytes_size; *bytes = result->unused_bytes; return TSI_OK; } -static void fake_handshaker_result_destroy(tsi_handshaker_result *self) { - fake_handshaker_result *result = (fake_handshaker_result *)self; +static void fake_handshaker_result_destroy(tsi_handshaker_result* self) { + fake_handshaker_result* result = (fake_handshaker_result*)self; gpr_free(result->unused_bytes); gpr_free(self); } @@ -532,17 +536,17 @@ static const tsi_handshaker_result_vtable handshaker_result_vtable = { }; static tsi_result fake_handshaker_result_create( - const unsigned char *unused_bytes, size_t unused_bytes_size, - tsi_handshaker_result **handshaker_result) { - if ((unused_bytes_size > 0 && unused_bytes == NULL) || - handshaker_result == NULL) { + const unsigned char* unused_bytes, size_t unused_bytes_size, + tsi_handshaker_result** handshaker_result) { + if ((unused_bytes_size > 0 && unused_bytes == nullptr) || + handshaker_result == nullptr) { return TSI_INVALID_ARGUMENT; } - fake_handshaker_result *result = - (fake_handshaker_result *)gpr_zalloc(sizeof(*result)); + fake_handshaker_result* result = + (fake_handshaker_result*)gpr_zalloc(sizeof(*result)); result->base.vtable = &handshaker_result_vtable; if (unused_bytes_size > 0) { - result->unused_bytes = (unsigned char *)gpr_malloc(unused_bytes_size); + result->unused_bytes = (unsigned char*)gpr_malloc(unused_bytes_size); memcpy(result->unused_bytes, unused_bytes, unused_bytes_size); } result->unused_bytes_size = unused_bytes_size; @@ -553,8 +557,8 @@ static tsi_result fake_handshaker_result_create( /* --- tsi_handshaker methods implementation. ---*/ static tsi_result fake_handshaker_get_bytes_to_send_to_peer( - tsi_handshaker *self, unsigned char *bytes, size_t *bytes_size) { - tsi_fake_handshaker *impl = (tsi_fake_handshaker *)self; + tsi_handshaker* self, unsigned char* bytes, size_t* bytes_size) { + tsi_fake_handshaker* impl = (tsi_fake_handshaker*)self; tsi_result result = TSI_OK; if (impl->needs_incoming_message || impl->result == TSI_OK) { *bytes_size = 0; @@ -563,15 +567,15 @@ static tsi_result fake_handshaker_get_bytes_to_send_to_peer( if (!impl->outgoing_frame.needs_draining) { tsi_fake_handshake_message next_message_to_send = (tsi_fake_handshake_message)(impl->next_message_to_send + 2); - const char *msg_string = + const char* msg_string = tsi_fake_handshake_message_to_string(impl->next_message_to_send); - result = tsi_fake_frame_set_data((unsigned char *)msg_string, + result = tsi_fake_frame_set_data((unsigned char*)msg_string, strlen(msg_string), &impl->outgoing_frame); if (result != TSI_OK) return result; if (next_message_to_send > TSI_FAKE_HANDSHAKE_MESSAGE_MAX) { next_message_to_send = TSI_FAKE_HANDSHAKE_MESSAGE_MAX; } - if (GRPC_TRACER_ON(tsi_tracing_enabled)) { + if (tsi_tracing_enabled.enabled()) { gpr_log(GPR_INFO, "%s prepared %s.", impl->is_client ? "Client" : "Server", tsi_fake_handshake_message_to_string(impl->next_message_to_send)); @@ -583,7 +587,7 @@ static tsi_result fake_handshaker_get_bytes_to_send_to_peer( if (!impl->is_client && impl->next_message_to_send == TSI_FAKE_HANDSHAKE_MESSAGE_MAX) { /* We're done. */ - if (GRPC_TRACER_ON(tsi_tracing_enabled)) { + if (tsi_tracing_enabled.enabled()) { gpr_log(GPR_INFO, "Server is done."); } impl->result = TSI_OK; @@ -594,9 +598,9 @@ static tsi_result fake_handshaker_get_bytes_to_send_to_peer( } static tsi_result fake_handshaker_process_bytes_from_peer( - tsi_handshaker *self, const unsigned char *bytes, size_t *bytes_size) { + tsi_handshaker* self, const unsigned char* bytes, size_t* bytes_size) { tsi_result result = TSI_OK; - tsi_fake_handshaker *impl = (tsi_fake_handshaker *)self; + tsi_fake_handshaker* impl = (tsi_fake_handshaker*)self; tsi_fake_handshake_message expected_msg = (tsi_fake_handshake_message)(impl->next_message_to_send - 1); tsi_fake_handshake_message received_msg; @@ -610,7 +614,7 @@ static tsi_result fake_handshaker_process_bytes_from_peer( /* We now have a complete frame. */ result = tsi_fake_handshake_message_from_string( - (const char *)impl->incoming_frame.data + TSI_FAKE_FRAME_HEADER_SIZE, + (const char*)impl->incoming_frame.data + TSI_FAKE_FRAME_HEADER_SIZE, &received_msg); if (result != TSI_OK) { impl->result = result; @@ -621,7 +625,7 @@ static tsi_result fake_handshaker_process_bytes_from_peer( tsi_fake_handshake_message_to_string(received_msg), tsi_fake_handshake_message_to_string(expected_msg)); } - if (GRPC_TRACER_ON(tsi_tracing_enabled)) { + if (tsi_tracing_enabled.enabled()) { gpr_log(GPR_INFO, "%s received %s.", impl->is_client ? "Client" : "Server", tsi_fake_handshake_message_to_string(received_msg)); } @@ -629,7 +633,7 @@ static tsi_result fake_handshaker_process_bytes_from_peer( impl->needs_incoming_message = 0; if (impl->next_message_to_send == TSI_FAKE_HANDSHAKE_MESSAGE_MAX) { /* We're done. */ - if (GRPC_TRACER_ON(tsi_tracing_enabled)) { + if (tsi_tracing_enabled.enabled()) { gpr_log(GPR_INFO, "%s is done.", impl->is_client ? "Client" : "Server"); } impl->result = TSI_OK; @@ -637,13 +641,13 @@ static tsi_result fake_handshaker_process_bytes_from_peer( return TSI_OK; } -static tsi_result fake_handshaker_get_result(tsi_handshaker *self) { - tsi_fake_handshaker *impl = (tsi_fake_handshaker *)self; +static tsi_result fake_handshaker_get_result(tsi_handshaker* self) { + tsi_fake_handshaker* impl = (tsi_fake_handshaker*)self; return impl->result; } -static void fake_handshaker_destroy(tsi_handshaker *self) { - tsi_fake_handshaker *impl = (tsi_fake_handshaker *)self; +static void fake_handshaker_destroy(tsi_handshaker* self) { + tsi_fake_handshaker* impl = (tsi_fake_handshaker*)self; tsi_fake_frame_destruct(&impl->incoming_frame); tsi_fake_frame_destruct(&impl->outgoing_frame); gpr_free(impl->outgoing_bytes_buffer); @@ -651,17 +655,17 @@ static void fake_handshaker_destroy(tsi_handshaker *self) { } static tsi_result fake_handshaker_next( - tsi_handshaker *self, const unsigned char *received_bytes, - size_t received_bytes_size, const unsigned char **bytes_to_send, - size_t *bytes_to_send_size, tsi_handshaker_result **handshaker_result, - tsi_handshaker_on_next_done_cb cb, void *user_data) { + tsi_handshaker* self, const unsigned char* received_bytes, + size_t received_bytes_size, const unsigned char** bytes_to_send, + size_t* bytes_to_send_size, tsi_handshaker_result** handshaker_result, + tsi_handshaker_on_next_done_cb cb, void* user_data) { /* Sanity check the arguments. */ - if ((received_bytes_size > 0 && received_bytes == NULL) || - bytes_to_send == NULL || bytes_to_send_size == NULL || - handshaker_result == NULL) { + if ((received_bytes_size > 0 && received_bytes == nullptr) || + bytes_to_send == nullptr || bytes_to_send_size == nullptr || + handshaker_result == nullptr) { return TSI_INVALID_ARGUMENT; } - tsi_fake_handshaker *handshaker = (tsi_fake_handshaker *)self; + tsi_fake_handshaker* handshaker = (tsi_fake_handshaker*)self; tsi_result result = TSI_OK; /* Decode and process a handshake frame from the peer. */ @@ -683,8 +687,8 @@ static tsi_result fake_handshaker_next( if (result == TSI_INCOMPLETE_DATA) { handshaker->outgoing_bytes_buffer_size *= 2; handshaker->outgoing_bytes_buffer = - (unsigned char *)gpr_realloc(handshaker->outgoing_bytes_buffer, - handshaker->outgoing_bytes_buffer_size); + (unsigned char*)gpr_realloc(handshaker->outgoing_bytes_buffer, + handshaker->outgoing_bytes_buffer_size); } } while (result == TSI_INCOMPLETE_DATA); if (result != TSI_OK) return result; @@ -693,10 +697,10 @@ static tsi_result fake_handshaker_next( /* Check if the handshake was completed. */ if (fake_handshaker_get_result(self) == TSI_HANDSHAKE_IN_PROGRESS) { - *handshaker_result = NULL; + *handshaker_result = nullptr; } else { /* Calculate the unused bytes. */ - const unsigned char *unused_bytes = NULL; + const unsigned char* unused_bytes = nullptr; size_t unused_bytes_size = received_bytes_size - consumed_bytes_size; if (unused_bytes_size > 0) { unused_bytes = received_bytes + consumed_bytes_size; @@ -715,24 +719,24 @@ static tsi_result fake_handshaker_next( } static const tsi_handshaker_vtable handshaker_vtable = { - NULL, /* get_bytes_to_send_to_peer -- deprecated */ - NULL, /* process_bytes_from_peer -- deprecated */ - NULL, /* get_result -- deprecated */ - NULL, /* extract_peer -- deprecated */ - NULL, /* create_frame_protector -- deprecated */ + nullptr, /* get_bytes_to_send_to_peer -- deprecated */ + nullptr, /* process_bytes_from_peer -- deprecated */ + nullptr, /* get_result -- deprecated */ + nullptr, /* extract_peer -- deprecated */ + nullptr, /* create_frame_protector -- deprecated */ fake_handshaker_destroy, fake_handshaker_next, }; -tsi_handshaker *tsi_create_fake_handshaker(int is_client) { - tsi_fake_handshaker *impl = (tsi_fake_handshaker *)gpr_zalloc(sizeof(*impl)); +tsi_handshaker* tsi_create_fake_handshaker(int is_client) { + tsi_fake_handshaker* impl = (tsi_fake_handshaker*)gpr_zalloc(sizeof(*impl)); impl->base.vtable = &handshaker_vtable; impl->is_client = is_client; impl->result = TSI_HANDSHAKE_IN_PROGRESS; impl->outgoing_bytes_buffer_size = TSI_FAKE_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE; impl->outgoing_bytes_buffer = - (unsigned char *)gpr_malloc(impl->outgoing_bytes_buffer_size); + (unsigned char*)gpr_malloc(impl->outgoing_bytes_buffer_size); if (is_client) { impl->needs_incoming_message = 0; impl->next_message_to_send = TSI_FAKE_CLIENT_INIT; @@ -743,24 +747,24 @@ tsi_handshaker *tsi_create_fake_handshaker(int is_client) { return &impl->base; } -tsi_frame_protector *tsi_create_fake_frame_protector( - size_t *max_protected_frame_size) { - tsi_fake_frame_protector *impl = - (tsi_fake_frame_protector *)gpr_zalloc(sizeof(*impl)); - impl->max_frame_size = (max_protected_frame_size == NULL) +tsi_frame_protector* tsi_create_fake_frame_protector( + size_t* max_protected_frame_size) { + tsi_fake_frame_protector* impl = + (tsi_fake_frame_protector*)gpr_zalloc(sizeof(*impl)); + impl->max_frame_size = (max_protected_frame_size == nullptr) ? TSI_FAKE_DEFAULT_FRAME_SIZE : *max_protected_frame_size; impl->base.vtable = &frame_protector_vtable; return &impl->base; } -tsi_zero_copy_grpc_protector *tsi_create_fake_zero_copy_grpc_protector( - size_t *max_protected_frame_size) { - tsi_fake_zero_copy_grpc_protector *impl = - (tsi_fake_zero_copy_grpc_protector *)gpr_zalloc(sizeof(*impl)); +tsi_zero_copy_grpc_protector* tsi_create_fake_zero_copy_grpc_protector( + size_t* max_protected_frame_size) { + tsi_fake_zero_copy_grpc_protector* impl = + (tsi_fake_zero_copy_grpc_protector*)gpr_zalloc(sizeof(*impl)); grpc_slice_buffer_init(&impl->header_sb); grpc_slice_buffer_init(&impl->protected_sb); - impl->max_frame_size = (max_protected_frame_size == NULL) + impl->max_frame_size = (max_protected_frame_size == nullptr) ? TSI_FAKE_DEFAULT_FRAME_SIZE : *max_protected_frame_size; impl->parsed_frame_size = 0; diff --git a/src/core/tsi/fake_transport_security.h b/src/core/tsi/fake_transport_security.h index 6159708a849..3848e7c6bf7 100644 --- a/src/core/tsi/fake_transport_security.h +++ b/src/core/tsi/fake_transport_security.h @@ -21,10 +21,6 @@ #include "src/core/tsi/transport_security_interface.h" -#ifdef __cplusplus -extern "C" { -#endif - /* Value for the TSI_CERTIFICATE_TYPE_PEER_PROPERTY property for FAKE certs. */ #define TSI_FAKE_CERTIFICATE_TYPE "FAKE" @@ -33,19 +29,15 @@ extern "C" { No cryptography is performed in these objects. They just simulate handshake messages going back and forth for the handshaker and do some framing on cleartext data for the protector. */ -tsi_handshaker *tsi_create_fake_handshaker(int is_client); +tsi_handshaker* tsi_create_fake_handshaker(int is_client); /* Creates a protector directly without going through the handshake phase. */ -tsi_frame_protector *tsi_create_fake_frame_protector( - size_t *max_protected_frame_size); +tsi_frame_protector* tsi_create_fake_frame_protector( + size_t* max_protected_frame_size); /* Creates a zero-copy protector directly without going through the handshake * phase. */ -tsi_zero_copy_grpc_protector *tsi_create_fake_zero_copy_grpc_protector( - size_t *max_protected_frame_size); - -#ifdef __cplusplus -} -#endif +tsi_zero_copy_grpc_protector* tsi_create_fake_zero_copy_grpc_protector( + size_t* max_protected_frame_size); #endif /* GRPC_CORE_TSI_FAKE_TRANSPORT_SECURITY_H */ diff --git a/src/core/tsi/gts_transport_security.cc b/src/core/tsi/gts_transport_security.cc index d37f3bf8f64..2b099773c48 100644 --- a/src/core/tsi/gts_transport_security.cc +++ b/src/core/tsi/gts_transport_security.cc @@ -22,16 +22,16 @@ static gts_shared_resource g_gts_resource; -gts_shared_resource *gts_get_shared_resource(void) { return &g_gts_resource; } +gts_shared_resource* gts_get_shared_resource(void) { return &g_gts_resource; } -extern "C" void grpc_tsi_gts_init() { +void grpc_tsi_gts_init() { memset(&g_gts_resource, 0, sizeof(gts_shared_resource)); gpr_mu_init(&g_gts_resource.mu); } -extern "C" void grpc_tsi_gts_shutdown() { +void grpc_tsi_gts_shutdown() { gpr_mu_destroy(&g_gts_resource.mu); - if (g_gts_resource.cq == NULL) { + if (g_gts_resource.cq == nullptr) { return; } grpc_completion_queue_destroy(g_gts_resource.cq); diff --git a/src/core/tsi/gts_transport_security.h b/src/core/tsi/gts_transport_security.h index 9590038ed00..23b2b66fb3c 100644 --- a/src/core/tsi/gts_transport_security.h +++ b/src/core/tsi/gts_transport_security.h @@ -23,23 +23,15 @@ #include #include -#ifdef __cplusplus -extern "C" { -#endif - typedef struct gts_shared_resource { gpr_thd_id thread_id; - grpc_channel *channel; - grpc_completion_queue *cq; + grpc_channel* channel; + grpc_completion_queue* cq; gpr_mu mu; } gts_shared_resource; /* This method returns the address of gts_shared_resource object shared by all * TSI handshakes. */ -gts_shared_resource *gts_get_shared_resource(void); - -#ifdef __cplusplus -} -#endif +gts_shared_resource* gts_get_shared_resource(void); #endif /* GRPC_CORE_TSI_GTS_TRANSPORT_SECURITY_H */ diff --git a/src/core/tsi/ssl_transport_security.cc b/src/core/tsi/ssl_transport_security.cc index b1c69e9c7b2..f35caef6402 100644 --- a/src/core/tsi/ssl_transport_security.cc +++ b/src/core/tsi/ssl_transport_security.cc @@ -70,14 +70,14 @@ extern "C" { /* --- Structure definitions. ---*/ struct tsi_ssl_handshaker_factory { - const tsi_ssl_handshaker_factory_vtable *vtable; + const tsi_ssl_handshaker_factory_vtable* vtable; gpr_refcount refcount; }; struct tsi_ssl_client_handshaker_factory { tsi_ssl_handshaker_factory base; - SSL_CTX *ssl_context; - unsigned char *alpn_protocol_list; + SSL_CTX* ssl_context; + unsigned char* alpn_protocol_list; size_t alpn_protocol_list_length; }; @@ -86,28 +86,28 @@ struct tsi_ssl_server_handshaker_factory { The tsi_peer array contains the subject names of the server certificates associated with the contexts at the same index. */ tsi_ssl_handshaker_factory base; - SSL_CTX **ssl_contexts; - tsi_peer *ssl_context_x509_subject_names; + SSL_CTX** ssl_contexts; + tsi_peer* ssl_context_x509_subject_names; size_t ssl_context_count; - unsigned char *alpn_protocol_list; + unsigned char* alpn_protocol_list; size_t alpn_protocol_list_length; }; typedef struct { tsi_handshaker base; - SSL *ssl; - BIO *into_ssl; - BIO *from_ssl; + SSL* ssl; + BIO* into_ssl; + BIO* from_ssl; tsi_result result; - tsi_ssl_handshaker_factory *factory_ref; + tsi_ssl_handshaker_factory* factory_ref; } tsi_ssl_handshaker; typedef struct { tsi_frame_protector base; - SSL *ssl; - BIO *into_ssl; - BIO *from_ssl; - unsigned char *buffer; + SSL* ssl; + BIO* into_ssl; + BIO* from_ssl; + unsigned char* buffer; size_t buffer_size; size_t buffer_offset; } tsi_ssl_frame_protector; @@ -115,9 +115,9 @@ typedef struct { /* --- Library Initialization. ---*/ static gpr_once init_openssl_once = GPR_ONCE_INIT; -static gpr_mu *openssl_mutexes = NULL; +static gpr_mu* openssl_mutexes = nullptr; -static void openssl_locking_cb(int mode, int type, const char *file, int line) { +static void openssl_locking_cb(int mode, int type, const char* file, int line) { if (mode & CRYPTO_LOCK) { gpr_mu_lock(&openssl_mutexes[type]); } else { @@ -137,7 +137,7 @@ static void init_openssl(void) { OpenSSL_add_all_algorithms(); num_locks = CRYPTO_num_locks(); GPR_ASSERT(num_locks > 0); - openssl_mutexes = (gpr_mu *)gpr_malloc((size_t)num_locks * sizeof(gpr_mu)); + openssl_mutexes = (gpr_mu*)gpr_malloc((size_t)num_locks * sizeof(gpr_mu)); for (i = 0; i < CRYPTO_num_locks(); i++) { gpr_mu_init(&openssl_mutexes[i]); } @@ -147,7 +147,7 @@ static void init_openssl(void) { /* --- Ssl utils. ---*/ -static const char *ssl_error_string(int error) { +static const char* ssl_error_string(int error) { switch (error) { case SSL_ERROR_NONE: return "SSL_ERROR_NONE"; @@ -173,16 +173,16 @@ static const char *ssl_error_string(int error) { } /* TODO(jboeuf): Remove when we are past the debugging phase with this code. */ -static void ssl_log_where_info(const SSL *ssl, int where, int flag, - const char *msg) { - if ((where & flag) && GRPC_TRACER_ON(tsi_tracing_enabled)) { +static void ssl_log_where_info(const SSL* ssl, int where, int flag, + const char* msg) { + if ((where & flag) && tsi_tracing_enabled.enabled()) { gpr_log(GPR_INFO, "%20.20s - %30.30s - %5.10s", msg, SSL_state_string_long(ssl), SSL_state_string(ssl)); } } /* Used for debugging. TODO(jboeuf): Remove when code is mature enough. */ -static void ssl_info_callback(const SSL *ssl, int where, int ret) { +static void ssl_info_callback(const SSL* ssl, int where, int ret) { if (ret == 0) { gpr_log(GPR_ERROR, "ssl_info_callback: error occured.\n"); return; @@ -195,7 +195,7 @@ static void ssl_info_callback(const SSL *ssl, int where, int ret) { /* Returns 1 if name looks like an IP address, 0 otherwise. This is a very rough heuristic, and only handles IPv6 in hexadecimal form. */ -static int looks_like_ip_address(const char *name) { +static int looks_like_ip_address(const char* name) { size_t i; size_t dot_count = 0; size_t num_size = 0; @@ -220,14 +220,14 @@ static int looks_like_ip_address(const char *name) { } /* Gets the subject CN from an X509 cert. */ -static tsi_result ssl_get_x509_common_name(X509 *cert, unsigned char **utf8, - size_t *utf8_size) { +static tsi_result ssl_get_x509_common_name(X509* cert, unsigned char** utf8, + size_t* utf8_size) { int common_name_index = -1; - X509_NAME_ENTRY *common_name_entry = NULL; - ASN1_STRING *common_name_asn1 = NULL; - X509_NAME *subject_name = X509_get_subject_name(cert); + X509_NAME_ENTRY* common_name_entry = nullptr; + ASN1_STRING* common_name_asn1 = nullptr; + X509_NAME* subject_name = X509_get_subject_name(cert); int utf8_returned_size = 0; - if (subject_name == NULL) { + if (subject_name == nullptr) { gpr_log(GPR_ERROR, "Could not get subject name from certificate."); return TSI_NOT_FOUND; } @@ -239,12 +239,12 @@ static tsi_result ssl_get_x509_common_name(X509 *cert, unsigned char **utf8, return TSI_NOT_FOUND; } common_name_entry = X509_NAME_get_entry(subject_name, common_name_index); - if (common_name_entry == NULL) { + if (common_name_entry == nullptr) { gpr_log(GPR_ERROR, "Could not get common name entry from certificate."); return TSI_INTERNAL_ERROR; } common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry); - if (common_name_asn1 == NULL) { + if (common_name_asn1 == nullptr) { gpr_log(GPR_ERROR, "Could not get common name entry asn1 from certificate."); return TSI_INTERNAL_ERROR; @@ -260,14 +260,14 @@ static tsi_result ssl_get_x509_common_name(X509 *cert, unsigned char **utf8, /* Gets the subject CN of an X509 cert as a tsi_peer_property. */ static tsi_result peer_property_from_x509_common_name( - X509 *cert, tsi_peer_property *property) { - unsigned char *common_name; + X509* cert, tsi_peer_property* property) { + unsigned char* common_name; size_t common_name_size; tsi_result result = ssl_get_x509_common_name(cert, &common_name, &common_name_size); if (result != TSI_OK) { if (result == TSI_NOT_FOUND) { - common_name = NULL; + common_name = nullptr; common_name_size = 0; } else { return result; @@ -275,35 +275,34 @@ static tsi_result peer_property_from_x509_common_name( } result = tsi_construct_string_peer_property( TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY, - common_name == NULL ? "" : (const char *)common_name, common_name_size, + common_name == nullptr ? "" : (const char*)common_name, common_name_size, property); OPENSSL_free(common_name); return result; } /* Gets the X509 cert in PEM format as a tsi_peer_property. */ -static tsi_result add_pem_certificate(X509 *cert, tsi_peer_property *property) { - BIO *bio = BIO_new(BIO_s_mem()); +static tsi_result add_pem_certificate(X509* cert, tsi_peer_property* property) { + BIO* bio = BIO_new(BIO_s_mem()); if (!PEM_write_bio_X509(bio, cert)) { BIO_free(bio); return TSI_INTERNAL_ERROR; } - char *contents; + char* contents; long len = BIO_get_mem_data(bio, &contents); if (len <= 0) { BIO_free(bio); return TSI_INTERNAL_ERROR; } tsi_result result = tsi_construct_string_peer_property( - TSI_X509_PEM_CERT_PROPERTY, (const char *)contents, (size_t)len, - property); + TSI_X509_PEM_CERT_PROPERTY, (const char*)contents, (size_t)len, property); BIO_free(bio); return result; } /* Gets the subject SANs from an X509 cert as a tsi_peer_property. */ static tsi_result add_subject_alt_names_properties_to_peer( - tsi_peer *peer, GENERAL_NAMES *subject_alt_names, + tsi_peer* peer, GENERAL_NAMES* subject_alt_names, size_t subject_alt_name_count) { size_t i; tsi_result result = TSI_OK; @@ -312,11 +311,11 @@ static tsi_result add_subject_alt_names_properties_to_peer( peer->property_count -= subject_alt_name_count; for (i = 0; i < subject_alt_name_count; i++) { - GENERAL_NAME *subject_alt_name = + GENERAL_NAME* subject_alt_name = sk_GENERAL_NAME_value(subject_alt_names, TSI_SIZE_AS_SIZE(i)); /* Filter out the non-dns entries names. */ if (subject_alt_name->type == GEN_DNS) { - unsigned char *name = NULL; + unsigned char* name = nullptr; int name_size; name_size = ASN1_STRING_to_UTF8(&name, subject_alt_name->d.dNSName); if (name_size < 0) { @@ -325,7 +324,7 @@ static tsi_result add_subject_alt_names_properties_to_peer( break; } result = tsi_construct_string_peer_property( - TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY, (const char *)name, + TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY, (const char*)name, (size_t)name_size, &peer->properties[peer->property_count++]); OPENSSL_free(name); } else if (subject_alt_name->type == GEN_IPADD) { @@ -341,9 +340,9 @@ static tsi_result add_subject_alt_names_properties_to_peer( result = TSI_INTERNAL_ERROR; break; } - const char *name = inet_ntop(af, subject_alt_name->d.iPAddress->data, + const char* name = inet_ntop(af, subject_alt_name->d.iPAddress->data, ntop_buf, INET6_ADDRSTRLEN); - if (name == NULL) { + if (name == nullptr) { gpr_log(GPR_ERROR, "Could not get IP string from asn1 octet."); result = TSI_INTERNAL_ERROR; break; @@ -359,12 +358,12 @@ static tsi_result add_subject_alt_names_properties_to_peer( } /* Gets information about the peer's X509 cert as a tsi_peer object. */ -static tsi_result peer_from_x509(X509 *cert, int include_certificate_type, - tsi_peer *peer) { +static tsi_result peer_from_x509(X509* cert, int include_certificate_type, + tsi_peer* peer) { /* TODO(jboeuf): Maybe add more properties. */ - GENERAL_NAMES *subject_alt_names = - (GENERAL_NAMES *)X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0); - int subject_alt_name_count = (subject_alt_names != NULL) + GENERAL_NAMES* subject_alt_names = (GENERAL_NAMES*)X509_get_ext_d2i( + cert, NID_subject_alt_name, nullptr, nullptr); + int subject_alt_name_count = (subject_alt_names != nullptr) ? (int)sk_GENERAL_NAME_num(subject_alt_names) : 0; size_t property_count; @@ -397,7 +396,7 @@ static tsi_result peer_from_x509(X509 *cert, int include_certificate_type, } } while (0); - if (subject_alt_names != NULL) { + if (subject_alt_names != nullptr) { sk_GENERAL_NAME_pop_free(subject_alt_names, GENERAL_NAME_free); } if (result != TSI_OK) tsi_peer_destruct(peer); @@ -415,8 +414,8 @@ static void log_ssl_error_stack(void) { } /* Performs an SSL_read and handle errors. */ -static tsi_result do_ssl_read(SSL *ssl, unsigned char *unprotected_bytes, - size_t *unprotected_bytes_size) { +static tsi_result do_ssl_read(SSL* ssl, unsigned char* unprotected_bytes, + size_t* unprotected_bytes_size) { int read_from_ssl; GPR_ASSERT(*unprotected_bytes_size <= INT_MAX); read_from_ssl = @@ -448,7 +447,7 @@ static tsi_result do_ssl_read(SSL *ssl, unsigned char *unprotected_bytes, } /* Performs an SSL_write and handle errors. */ -static tsi_result do_ssl_write(SSL *ssl, unsigned char *unprotected_bytes, +static tsi_result do_ssl_write(SSL* ssl, unsigned char* unprotected_bytes, size_t unprotected_bytes_size) { int ssl_write_result; GPR_ASSERT(unprotected_bytes_size <= INT_MAX); @@ -470,19 +469,19 @@ static tsi_result do_ssl_write(SSL *ssl, unsigned char *unprotected_bytes, } /* Loads an in-memory PEM certificate chain into the SSL context. */ -static tsi_result ssl_ctx_use_certificate_chain(SSL_CTX *context, - const char *pem_cert_chain, +static tsi_result ssl_ctx_use_certificate_chain(SSL_CTX* context, + const char* pem_cert_chain, size_t pem_cert_chain_size) { tsi_result result = TSI_OK; - X509 *certificate = NULL; - BIO *pem; + X509* certificate = nullptr; + BIO* pem; GPR_ASSERT(pem_cert_chain_size <= INT_MAX); - pem = BIO_new_mem_buf((void *)pem_cert_chain, (int)pem_cert_chain_size); - if (pem == NULL) return TSI_OUT_OF_RESOURCES; + pem = BIO_new_mem_buf((void*)pem_cert_chain, (int)pem_cert_chain_size); + if (pem == nullptr) return TSI_OUT_OF_RESOURCES; do { - certificate = PEM_read_bio_X509_AUX(pem, NULL, NULL, (void *)""); - if (certificate == NULL) { + certificate = PEM_read_bio_X509_AUX(pem, nullptr, nullptr, (void*)""); + if (certificate == nullptr) { result = TSI_INVALID_ARGUMENT; break; } @@ -491,9 +490,9 @@ static tsi_result ssl_ctx_use_certificate_chain(SSL_CTX *context, break; } while (1) { - X509 *certificate_authority = - PEM_read_bio_X509(pem, NULL, NULL, (void *)""); - if (certificate_authority == NULL) { + X509* certificate_authority = + PEM_read_bio_X509(pem, nullptr, nullptr, (void*)""); + if (certificate_authority == nullptr) { ERR_clear_error(); break; /* Done reading. */ } @@ -508,23 +507,23 @@ static tsi_result ssl_ctx_use_certificate_chain(SSL_CTX *context, } } while (0); - if (certificate != NULL) X509_free(certificate); + if (certificate != nullptr) X509_free(certificate); BIO_free(pem); return result; } /* Loads an in-memory PEM private key into the SSL context. */ -static tsi_result ssl_ctx_use_private_key(SSL_CTX *context, const char *pem_key, +static tsi_result ssl_ctx_use_private_key(SSL_CTX* context, const char* pem_key, size_t pem_key_size) { tsi_result result = TSI_OK; - EVP_PKEY *private_key = NULL; - BIO *pem; + EVP_PKEY* private_key = nullptr; + BIO* pem; GPR_ASSERT(pem_key_size <= INT_MAX); - pem = BIO_new_mem_buf((void *)pem_key, (int)pem_key_size); - if (pem == NULL) return TSI_OUT_OF_RESOURCES; + pem = BIO_new_mem_buf((void*)pem_key, (int)pem_key_size); + if (pem == nullptr) return TSI_OUT_OF_RESOURCES; do { - private_key = PEM_read_bio_PrivateKey(pem, NULL, NULL, (void *)""); - if (private_key == NULL) { + private_key = PEM_read_bio_PrivateKey(pem, nullptr, nullptr, (void*)""); + if (private_key == nullptr) { result = TSI_INVALID_ARGUMENT; break; } @@ -533,54 +532,54 @@ static tsi_result ssl_ctx_use_private_key(SSL_CTX *context, const char *pem_key, break; } } while (0); - if (private_key != NULL) EVP_PKEY_free(private_key); + if (private_key != nullptr) EVP_PKEY_free(private_key); BIO_free(pem); return result; } /* Loads in-memory PEM verification certs into the SSL context and optionally returns the verification cert names (root_names can be NULL). */ -static tsi_result ssl_ctx_load_verification_certs(SSL_CTX *context, - const char *pem_roots, +static tsi_result ssl_ctx_load_verification_certs(SSL_CTX* context, + const char* pem_roots, size_t pem_roots_size, STACK_OF(X509_NAME) * *root_names) { tsi_result result = TSI_OK; size_t num_roots = 0; - X509 *root = NULL; - X509_NAME *root_name = NULL; - BIO *pem; - X509_STORE *root_store; + X509* root = nullptr; + X509_NAME* root_name = nullptr; + BIO* pem; + X509_STORE* root_store; GPR_ASSERT(pem_roots_size <= INT_MAX); - pem = BIO_new_mem_buf((void *)pem_roots, (int)pem_roots_size); + pem = BIO_new_mem_buf((void*)pem_roots, (int)pem_roots_size); root_store = SSL_CTX_get_cert_store(context); - if (root_store == NULL) return TSI_INVALID_ARGUMENT; - if (pem == NULL) return TSI_OUT_OF_RESOURCES; - if (root_names != NULL) { + if (root_store == nullptr) return TSI_INVALID_ARGUMENT; + if (pem == nullptr) return TSI_OUT_OF_RESOURCES; + if (root_names != nullptr) { *root_names = sk_X509_NAME_new_null(); - if (*root_names == NULL) return TSI_OUT_OF_RESOURCES; + if (*root_names == nullptr) return TSI_OUT_OF_RESOURCES; } while (1) { - root = PEM_read_bio_X509_AUX(pem, NULL, NULL, (void *)""); - if (root == NULL) { + root = PEM_read_bio_X509_AUX(pem, nullptr, nullptr, (void*)""); + if (root == nullptr) { ERR_clear_error(); break; /* We're at the end of stream. */ } - if (root_names != NULL) { + if (root_names != nullptr) { root_name = X509_get_subject_name(root); - if (root_name == NULL) { + if (root_name == nullptr) { gpr_log(GPR_ERROR, "Could not get name from root certificate."); result = TSI_INVALID_ARGUMENT; break; } root_name = X509_NAME_dup(root_name); - if (root_name == NULL) { + if (root_name == nullptr) { result = TSI_OUT_OF_RESOURCES; break; } sk_X509_NAME_push(*root_names, root_name); - root_name = NULL; + root_name = nullptr; } if (!X509_STORE_add_cert(root_store, root)) { gpr_log(GPR_ERROR, "Could not add root certificate to ssl context."); @@ -597,11 +596,11 @@ static tsi_result ssl_ctx_load_verification_certs(SSL_CTX *context, } if (result != TSI_OK) { - if (root != NULL) X509_free(root); - if (root_names != NULL) { + if (root != nullptr) X509_free(root); + if (root_names != nullptr) { sk_X509_NAME_pop_free(*root_names, X509_NAME_free); - *root_names = NULL; - if (root_name != NULL) X509_NAME_free(root_name); + *root_names = nullptr; + if (root_name != nullptr) X509_NAME_free(root_name); } } BIO_free(pem); @@ -611,11 +610,11 @@ static tsi_result ssl_ctx_load_verification_certs(SSL_CTX *context, /* Populates the SSL context with a private key and a cert chain, and sets the cipher list and the ephemeral ECDH key. */ static tsi_result populate_ssl_context( - SSL_CTX *context, const tsi_ssl_pem_key_cert_pair *key_cert_pair, - const char *cipher_list) { + SSL_CTX* context, const tsi_ssl_pem_key_cert_pair* key_cert_pair, + const char* cipher_list) { tsi_result result = TSI_OK; - if (key_cert_pair != NULL) { - if (key_cert_pair->cert_chain != NULL) { + if (key_cert_pair != nullptr) { + if (key_cert_pair->cert_chain != nullptr) { result = ssl_ctx_use_certificate_chain(context, key_cert_pair->cert_chain, strlen(key_cert_pair->cert_chain)); if (result != TSI_OK) { @@ -623,7 +622,7 @@ static tsi_result populate_ssl_context( return result; } } - if (key_cert_pair->private_key != NULL) { + if (key_cert_pair->private_key != nullptr) { result = ssl_ctx_use_private_key(context, key_cert_pair->private_key, strlen(key_cert_pair->private_key)); if (result != TSI_OK || !SSL_CTX_check_private_key(context)) { @@ -632,12 +631,13 @@ static tsi_result populate_ssl_context( } } } - if ((cipher_list != NULL) && !SSL_CTX_set_cipher_list(context, cipher_list)) { + if ((cipher_list != nullptr) && + !SSL_CTX_set_cipher_list(context, cipher_list)) { gpr_log(GPR_ERROR, "Invalid cipher list: %s.", cipher_list); return TSI_INVALID_ARGUMENT; } { - EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); + EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); if (!SSL_CTX_set_tmp_ecdh(context, ecdh)) { gpr_log(GPR_ERROR, "Could not set ephemeral ECDH key."); EC_KEY_free(ecdh); @@ -650,45 +650,46 @@ static tsi_result populate_ssl_context( } /* Extracts the CN and the SANs from an X509 cert as a peer object. */ -static tsi_result extract_x509_subject_names_from_pem_cert(const char *pem_cert, - tsi_peer *peer) { +static tsi_result extract_x509_subject_names_from_pem_cert(const char* pem_cert, + tsi_peer* peer) { tsi_result result = TSI_OK; - X509 *cert = NULL; - BIO *pem; - pem = BIO_new_mem_buf((void *)pem_cert, (int)strlen(pem_cert)); - if (pem == NULL) return TSI_OUT_OF_RESOURCES; + X509* cert = nullptr; + BIO* pem; + pem = BIO_new_mem_buf((void*)pem_cert, (int)strlen(pem_cert)); + if (pem == nullptr) return TSI_OUT_OF_RESOURCES; - cert = PEM_read_bio_X509(pem, NULL, NULL, (void *)""); - if (cert == NULL) { + cert = PEM_read_bio_X509(pem, nullptr, nullptr, (void*)""); + if (cert == nullptr) { gpr_log(GPR_ERROR, "Invalid certificate"); result = TSI_INVALID_ARGUMENT; } else { result = peer_from_x509(cert, 0, peer); } - if (cert != NULL) X509_free(cert); + if (cert != nullptr) X509_free(cert); BIO_free(pem); return result; } /* Builds the alpn protocol name list according to rfc 7301. */ static tsi_result build_alpn_protocol_name_list( - const char **alpn_protocols, uint16_t num_alpn_protocols, - unsigned char **protocol_name_list, size_t *protocol_name_list_length) { + const char** alpn_protocols, uint16_t num_alpn_protocols, + unsigned char** protocol_name_list, size_t* protocol_name_list_length) { uint16_t i; - unsigned char *current; - *protocol_name_list = NULL; + unsigned char* current; + *protocol_name_list = nullptr; *protocol_name_list_length = 0; if (num_alpn_protocols == 0) return TSI_INVALID_ARGUMENT; for (i = 0; i < num_alpn_protocols; i++) { - size_t length = alpn_protocols[i] == NULL ? 0 : strlen(alpn_protocols[i]); + size_t length = + alpn_protocols[i] == nullptr ? 0 : strlen(alpn_protocols[i]); if (length == 0 || length > 255) { gpr_log(GPR_ERROR, "Invalid protocol name length: %d.", (int)length); return TSI_INVALID_ARGUMENT; } *protocol_name_list_length += length + 1; } - *protocol_name_list = (unsigned char *)gpr_malloc(*protocol_name_list_length); - if (*protocol_name_list == NULL) return TSI_OUT_OF_RESOURCES; + *protocol_name_list = (unsigned char*)gpr_malloc(*protocol_name_list_length); + if (*protocol_name_list == nullptr) return TSI_OUT_OF_RESOURCES; current = *protocol_name_list; for (i = 0; i < num_alpn_protocols; i++) { size_t length = strlen(alpn_protocols[i]); @@ -709,18 +710,18 @@ static tsi_result build_alpn_protocol_name_list( // the server's certificate, but we need to pull it anyway, in case a higher // layer wants to look at it. In this case the verification may fail, but // we don't really care. -static int NullVerifyCallback(int preverify_ok, X509_STORE_CTX *ctx) { +static int NullVerifyCallback(int preverify_ok, X509_STORE_CTX* ctx) { return 1; } /* --- tsi_frame_protector methods implementation. ---*/ -static tsi_result ssl_protector_protect(tsi_frame_protector *self, - const unsigned char *unprotected_bytes, - size_t *unprotected_bytes_size, - unsigned char *protected_output_frames, - size_t *protected_output_frames_size) { - tsi_ssl_frame_protector *impl = (tsi_ssl_frame_protector *)self; +static tsi_result ssl_protector_protect(tsi_frame_protector* self, + const unsigned char* unprotected_bytes, + size_t* unprotected_bytes_size, + unsigned char* protected_output_frames, + size_t* protected_output_frames_size) { + tsi_ssl_frame_protector* impl = (tsi_ssl_frame_protector*)self; int read_from_ssl; size_t available; tsi_result result = TSI_OK; @@ -771,10 +772,10 @@ static tsi_result ssl_protector_protect(tsi_frame_protector *self, } static tsi_result ssl_protector_protect_flush( - tsi_frame_protector *self, unsigned char *protected_output_frames, - size_t *protected_output_frames_size, size_t *still_pending_size) { + tsi_frame_protector* self, unsigned char* protected_output_frames, + size_t* protected_output_frames_size, size_t* still_pending_size) { tsi_result result = TSI_OK; - tsi_ssl_frame_protector *impl = (tsi_ssl_frame_protector *)self; + tsi_ssl_frame_protector* impl = (tsi_ssl_frame_protector*)self; int read_from_ssl = 0; int pending; @@ -804,14 +805,14 @@ static tsi_result ssl_protector_protect_flush( } static tsi_result ssl_protector_unprotect( - tsi_frame_protector *self, const unsigned char *protected_frames_bytes, - size_t *protected_frames_bytes_size, unsigned char *unprotected_bytes, - size_t *unprotected_bytes_size) { + tsi_frame_protector* self, const unsigned char* protected_frames_bytes, + size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes, + size_t* unprotected_bytes_size) { tsi_result result = TSI_OK; int written_into_ssl = 0; size_t output_bytes_size = *unprotected_bytes_size; size_t output_bytes_offset = 0; - tsi_ssl_frame_protector *impl = (tsi_ssl_frame_protector *)self; + tsi_ssl_frame_protector* impl = (tsi_ssl_frame_protector*)self; /* First, try to read remaining data from ssl. */ result = do_ssl_read(impl->ssl, unprotected_bytes, unprotected_bytes_size); @@ -845,25 +846,27 @@ static tsi_result ssl_protector_unprotect( return result; } -static void ssl_protector_destroy(tsi_frame_protector *self) { - tsi_ssl_frame_protector *impl = (tsi_ssl_frame_protector *)self; - if (impl->buffer != NULL) gpr_free(impl->buffer); - if (impl->ssl != NULL) SSL_free(impl->ssl); +static void ssl_protector_destroy(tsi_frame_protector* self) { + tsi_ssl_frame_protector* impl = (tsi_ssl_frame_protector*)self; + if (impl->buffer != nullptr) gpr_free(impl->buffer); + if (impl->ssl != nullptr) SSL_free(impl->ssl); gpr_free(self); } static const tsi_frame_protector_vtable frame_protector_vtable = { - ssl_protector_protect, ssl_protector_protect_flush, ssl_protector_unprotect, + ssl_protector_protect, + ssl_protector_protect_flush, + ssl_protector_unprotect, ssl_protector_destroy, }; /* --- tsi_server_handshaker_factory methods implementation. --- */ static void tsi_ssl_handshaker_factory_destroy( - tsi_ssl_handshaker_factory *self) { - if (self == NULL) return; + tsi_ssl_handshaker_factory* self) { + if (self == nullptr) return; - if (self->vtable != NULL && self->vtable->destroy != NULL) { + if (self->vtable != nullptr && self->vtable->destroy != nullptr) { self->vtable->destroy(self); } /* Note, we don't free(self) here because this object is always directly @@ -871,28 +874,28 @@ static void tsi_ssl_handshaker_factory_destroy( * any memory, it should be free'd here. */ } -static tsi_ssl_handshaker_factory *tsi_ssl_handshaker_factory_ref( - tsi_ssl_handshaker_factory *self) { - if (self == NULL) return NULL; +static tsi_ssl_handshaker_factory* tsi_ssl_handshaker_factory_ref( + tsi_ssl_handshaker_factory* self) { + if (self == nullptr) return nullptr; gpr_refn(&self->refcount, 1); return self; } -static void tsi_ssl_handshaker_factory_unref(tsi_ssl_handshaker_factory *self) { - if (self == NULL) return; +static void tsi_ssl_handshaker_factory_unref(tsi_ssl_handshaker_factory* self) { + if (self == nullptr) return; if (gpr_unref(&self->refcount)) { tsi_ssl_handshaker_factory_destroy(self); } } -static tsi_ssl_handshaker_factory_vtable handshaker_factory_vtable = {NULL}; +static tsi_ssl_handshaker_factory_vtable handshaker_factory_vtable = {nullptr}; /* Initializes a tsi_ssl_handshaker_factory object. Caller is responsible for * allocating memory for the factory. */ static void tsi_ssl_handshaker_factory_init( - tsi_ssl_handshaker_factory *factory) { - GPR_ASSERT(factory != NULL); + tsi_ssl_handshaker_factory* factory) { + GPR_ASSERT(factory != nullptr); factory->vtable = &handshaker_factory_vtable; gpr_ref_init(&factory->refcount, 1); @@ -900,12 +903,12 @@ static void tsi_ssl_handshaker_factory_init( /* --- tsi_handshaker methods implementation. ---*/ -static tsi_result ssl_handshaker_get_bytes_to_send_to_peer(tsi_handshaker *self, - unsigned char *bytes, - size_t *bytes_size) { - tsi_ssl_handshaker *impl = (tsi_ssl_handshaker *)self; +static tsi_result ssl_handshaker_get_bytes_to_send_to_peer(tsi_handshaker* self, + unsigned char* bytes, + size_t* bytes_size) { + tsi_ssl_handshaker* impl = (tsi_ssl_handshaker*)self; int bytes_read_from_ssl = 0; - if (bytes == NULL || bytes_size == NULL || *bytes_size == 0 || + if (bytes == nullptr || bytes_size == nullptr || *bytes_size == 0 || *bytes_size > INT_MAX) { return TSI_INVALID_ARGUMENT; } @@ -924,8 +927,8 @@ static tsi_result ssl_handshaker_get_bytes_to_send_to_peer(tsi_handshaker *self, return BIO_pending(impl->from_ssl) == 0 ? TSI_OK : TSI_INCOMPLETE_DATA; } -static tsi_result ssl_handshaker_get_result(tsi_handshaker *self) { - tsi_ssl_handshaker *impl = (tsi_ssl_handshaker *)self; +static tsi_result ssl_handshaker_get_result(tsi_handshaker* self) { + tsi_ssl_handshaker* impl = (tsi_ssl_handshaker*)self; if ((impl->result == TSI_HANDSHAKE_IN_PROGRESS) && SSL_is_init_finished(impl->ssl)) { impl->result = TSI_OK; @@ -934,10 +937,10 @@ static tsi_result ssl_handshaker_get_result(tsi_handshaker *self) { } static tsi_result ssl_handshaker_process_bytes_from_peer( - tsi_handshaker *self, const unsigned char *bytes, size_t *bytes_size) { - tsi_ssl_handshaker *impl = (tsi_ssl_handshaker *)self; + tsi_handshaker* self, const unsigned char* bytes, size_t* bytes_size) { + tsi_ssl_handshaker* impl = (tsi_ssl_handshaker*)self; int bytes_written_into_ssl_size = 0; - if (bytes == NULL || bytes_size == 0 || *bytes_size > INT_MAX) { + if (bytes == nullptr || bytes_size == nullptr || *bytes_size > INT_MAX) { return TSI_INVALID_ARGUMENT; } GPR_ASSERT(*bytes_size <= INT_MAX); @@ -979,14 +982,14 @@ static tsi_result ssl_handshaker_process_bytes_from_peer( } } -static tsi_result ssl_handshaker_extract_peer(tsi_handshaker *self, - tsi_peer *peer) { +static tsi_result ssl_handshaker_extract_peer(tsi_handshaker* self, + tsi_peer* peer) { tsi_result result = TSI_OK; - const unsigned char *alpn_selected = NULL; + const unsigned char* alpn_selected = nullptr; unsigned int alpn_selected_len; - tsi_ssl_handshaker *impl = (tsi_ssl_handshaker *)self; - X509 *peer_cert = SSL_get_peer_certificate(impl->ssl); - if (peer_cert != NULL) { + tsi_ssl_handshaker* impl = (tsi_ssl_handshaker*)self; + X509* peer_cert = SSL_get_peer_certificate(impl->ssl); + if (peer_cert != nullptr) { result = peer_from_x509(peer_cert, 1, peer); X509_free(peer_cert); if (result != TSI_OK) return result; @@ -994,26 +997,26 @@ static tsi_result ssl_handshaker_extract_peer(tsi_handshaker *self, #if TSI_OPENSSL_ALPN_SUPPORT SSL_get0_alpn_selected(impl->ssl, &alpn_selected, &alpn_selected_len); #endif /* TSI_OPENSSL_ALPN_SUPPORT */ - if (alpn_selected == NULL) { + if (alpn_selected == nullptr) { /* Try npn. */ SSL_get0_next_proto_negotiated(impl->ssl, &alpn_selected, &alpn_selected_len); } - if (alpn_selected != NULL) { + if (alpn_selected != nullptr) { size_t i; - tsi_peer_property *new_properties = (tsi_peer_property *)gpr_zalloc( + tsi_peer_property* new_properties = (tsi_peer_property*)gpr_zalloc( sizeof(*new_properties) * (peer->property_count + 1)); for (i = 0; i < peer->property_count; i++) { new_properties[i] = peer->properties[i]; } result = tsi_construct_string_peer_property( - TSI_SSL_ALPN_SELECTED_PROTOCOL, (const char *)alpn_selected, + TSI_SSL_ALPN_SELECTED_PROTOCOL, (const char*)alpn_selected, alpn_selected_len, &new_properties[peer->property_count]); if (result != TSI_OK) { gpr_free(new_properties); return result; } - if (peer->properties != NULL) gpr_free(peer->properties); + if (peer->properties != nullptr) gpr_free(peer->properties); peer->property_count++; peer->properties = new_properties; } @@ -1021,15 +1024,15 @@ static tsi_result ssl_handshaker_extract_peer(tsi_handshaker *self, } static tsi_result ssl_handshaker_create_frame_protector( - tsi_handshaker *self, size_t *max_output_protected_frame_size, - tsi_frame_protector **protector) { + tsi_handshaker* self, size_t* max_output_protected_frame_size, + tsi_frame_protector** protector) { size_t actual_max_output_protected_frame_size = TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND; - tsi_ssl_handshaker *impl = (tsi_ssl_handshaker *)self; - tsi_ssl_frame_protector *protector_impl = - (tsi_ssl_frame_protector *)gpr_zalloc(sizeof(*protector_impl)); + tsi_ssl_handshaker* impl = (tsi_ssl_handshaker*)self; + tsi_ssl_frame_protector* protector_impl = + (tsi_ssl_frame_protector*)gpr_zalloc(sizeof(*protector_impl)); - if (max_output_protected_frame_size != NULL) { + if (max_output_protected_frame_size != nullptr) { if (*max_output_protected_frame_size > TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND) { *max_output_protected_frame_size = @@ -1044,8 +1047,8 @@ static tsi_result ssl_handshaker_create_frame_protector( protector_impl->buffer_size = actual_max_output_protected_frame_size - TSI_SSL_MAX_PROTECTION_OVERHEAD; protector_impl->buffer = - (unsigned char *)gpr_malloc(protector_impl->buffer_size); - if (protector_impl->buffer == NULL) { + (unsigned char*)gpr_malloc(protector_impl->buffer_size); + if (protector_impl->buffer == nullptr) { gpr_log(GPR_ERROR, "Could not allocated buffer for tsi_ssl_frame_protector."); gpr_free(protector_impl); @@ -1055,7 +1058,7 @@ static tsi_result ssl_handshaker_create_frame_protector( /* Transfer ownership of ssl to the frame protector. It is OK as the caller * cannot call anything else but destroy on the handshaker after this call. */ protector_impl->ssl = impl->ssl; - impl->ssl = NULL; + impl->ssl = nullptr; protector_impl->into_ssl = impl->into_ssl; protector_impl->from_ssl = impl->from_ssl; @@ -1064,8 +1067,8 @@ static tsi_result ssl_handshaker_create_frame_protector( return TSI_OK; } -static void ssl_handshaker_destroy(tsi_handshaker *self) { - tsi_ssl_handshaker *impl = (tsi_ssl_handshaker *)self; +static void ssl_handshaker_destroy(tsi_handshaker* self) { + tsi_ssl_handshaker* impl = (tsi_ssl_handshaker*)self; SSL_free(impl->ssl); /* The BIO objects are owned by ssl */ tsi_ssl_handshaker_factory_unref(impl->factory_ref); gpr_free(impl); @@ -1078,43 +1081,43 @@ static const tsi_handshaker_vtable handshaker_vtable = { ssl_handshaker_extract_peer, ssl_handshaker_create_frame_protector, ssl_handshaker_destroy, - NULL, + nullptr, }; /* --- tsi_ssl_handshaker_factory common methods. --- */ -static tsi_result create_tsi_ssl_handshaker(SSL_CTX *ctx, int is_client, - const char *server_name_indication, - tsi_ssl_handshaker_factory *factory, - tsi_handshaker **handshaker) { - SSL *ssl = SSL_new(ctx); - BIO *into_ssl = NULL; - BIO *from_ssl = NULL; - tsi_ssl_handshaker *impl = NULL; - *handshaker = NULL; - if (ctx == NULL) { +static tsi_result create_tsi_ssl_handshaker(SSL_CTX* ctx, int is_client, + const char* server_name_indication, + tsi_ssl_handshaker_factory* factory, + tsi_handshaker** handshaker) { + SSL* ssl = SSL_new(ctx); + BIO* into_ssl = nullptr; + BIO* from_ssl = nullptr; + tsi_ssl_handshaker* impl = nullptr; + *handshaker = nullptr; + if (ctx == nullptr) { gpr_log(GPR_ERROR, "SSL Context is null. Should never happen."); return TSI_INTERNAL_ERROR; } - if (ssl == NULL) { + if (ssl == nullptr) { return TSI_OUT_OF_RESOURCES; } SSL_set_info_callback(ssl, ssl_info_callback); into_ssl = BIO_new(BIO_s_mem()); from_ssl = BIO_new(BIO_s_mem()); - if (into_ssl == NULL || from_ssl == NULL) { + if (into_ssl == nullptr || from_ssl == nullptr) { gpr_log(GPR_ERROR, "BIO_new failed."); SSL_free(ssl); - if (into_ssl != NULL) BIO_free(into_ssl); - if (from_ssl != NULL) BIO_free(into_ssl); + if (into_ssl != nullptr) BIO_free(into_ssl); + if (from_ssl != nullptr) BIO_free(into_ssl); return TSI_OUT_OF_RESOURCES; } SSL_set_bio(ssl, into_ssl, from_ssl); if (is_client) { int ssl_result; SSL_set_connect_state(ssl); - if (server_name_indication != NULL) { + if (server_name_indication != nullptr) { if (!SSL_set_tlsext_host_name(ssl, server_name_indication)) { gpr_log(GPR_ERROR, "Invalid server name indication %s.", server_name_indication); @@ -1135,7 +1138,7 @@ static tsi_result create_tsi_ssl_handshaker(SSL_CTX *ctx, int is_client, SSL_set_accept_state(ssl); } - impl = (tsi_ssl_handshaker *)gpr_zalloc(sizeof(*impl)); + impl = (tsi_ssl_handshaker*)gpr_zalloc(sizeof(*impl)); impl->ssl = ssl; impl->into_ssl = into_ssl; impl->from_ssl = from_ssl; @@ -1147,16 +1150,16 @@ static tsi_result create_tsi_ssl_handshaker(SSL_CTX *ctx, int is_client, return TSI_OK; } -static int select_protocol_list(const unsigned char **out, - unsigned char *outlen, - const unsigned char *client_list, +static int select_protocol_list(const unsigned char** out, + unsigned char* outlen, + const unsigned char* client_list, size_t client_list_len, - const unsigned char *server_list, + const unsigned char* server_list, size_t server_list_len) { - const unsigned char *client_current = client_list; + const unsigned char* client_current = client_list; while ((unsigned int)(client_current - client_list) < client_list_len) { unsigned char client_current_len = *(client_current++); - const unsigned char *server_current = server_list; + const unsigned char* server_current = server_list; while ((server_current >= server_list) && (uintptr_t)(server_current - server_list) < server_list_len) { unsigned char server_current_len = *(server_current++); @@ -1176,36 +1179,36 @@ static int select_protocol_list(const unsigned char **out, /* --- tsi_ssl_client_handshaker_factory methods implementation. --- */ tsi_result tsi_ssl_client_handshaker_factory_create_handshaker( - tsi_ssl_client_handshaker_factory *self, const char *server_name_indication, - tsi_handshaker **handshaker) { + tsi_ssl_client_handshaker_factory* self, const char* server_name_indication, + tsi_handshaker** handshaker) { return create_tsi_ssl_handshaker(self->ssl_context, 1, server_name_indication, &self->base, handshaker); } void tsi_ssl_client_handshaker_factory_unref( - tsi_ssl_client_handshaker_factory *self) { - if (self == NULL) return; + tsi_ssl_client_handshaker_factory* self) { + if (self == nullptr) return; tsi_ssl_handshaker_factory_unref(&self->base); } static void tsi_ssl_client_handshaker_factory_destroy( - tsi_ssl_handshaker_factory *factory) { - if (factory == NULL) return; - tsi_ssl_client_handshaker_factory *self = - (tsi_ssl_client_handshaker_factory *)factory; - if (self->ssl_context != NULL) SSL_CTX_free(self->ssl_context); - if (self->alpn_protocol_list != NULL) gpr_free(self->alpn_protocol_list); + tsi_ssl_handshaker_factory* factory) { + if (factory == nullptr) return; + tsi_ssl_client_handshaker_factory* self = + (tsi_ssl_client_handshaker_factory*)factory; + if (self->ssl_context != nullptr) SSL_CTX_free(self->ssl_context); + if (self->alpn_protocol_list != nullptr) gpr_free(self->alpn_protocol_list); gpr_free(self); } -static int client_handshaker_factory_npn_callback(SSL *ssl, unsigned char **out, - unsigned char *outlen, - const unsigned char *in, +static int client_handshaker_factory_npn_callback(SSL* ssl, unsigned char** out, + unsigned char* outlen, + const unsigned char* in, unsigned int inlen, - void *arg) { - tsi_ssl_client_handshaker_factory *factory = - (tsi_ssl_client_handshaker_factory *)arg; - return select_protocol_list((const unsigned char **)out, outlen, + void* arg) { + tsi_ssl_client_handshaker_factory* factory = + (tsi_ssl_client_handshaker_factory*)arg; + return select_protocol_list((const unsigned char**)out, outlen, factory->alpn_protocol_list, factory->alpn_protocol_list_length, in, inlen); } @@ -1213,44 +1216,44 @@ static int client_handshaker_factory_npn_callback(SSL *ssl, unsigned char **out, /* --- tsi_ssl_server_handshaker_factory methods implementation. --- */ tsi_result tsi_ssl_server_handshaker_factory_create_handshaker( - tsi_ssl_server_handshaker_factory *self, tsi_handshaker **handshaker) { + tsi_ssl_server_handshaker_factory* self, tsi_handshaker** handshaker) { if (self->ssl_context_count == 0) return TSI_INVALID_ARGUMENT; /* Create the handshaker with the first context. We will switch if needed because of SNI in ssl_server_handshaker_factory_servername_callback. */ - return create_tsi_ssl_handshaker(self->ssl_contexts[0], 0, NULL, &self->base, - handshaker); + return create_tsi_ssl_handshaker(self->ssl_contexts[0], 0, nullptr, + &self->base, handshaker); } void tsi_ssl_server_handshaker_factory_unref( - tsi_ssl_server_handshaker_factory *self) { - if (self == NULL) return; + tsi_ssl_server_handshaker_factory* self) { + if (self == nullptr) return; tsi_ssl_handshaker_factory_unref(&self->base); } static void tsi_ssl_server_handshaker_factory_destroy( - tsi_ssl_handshaker_factory *factory) { - if (factory == NULL) return; - tsi_ssl_server_handshaker_factory *self = - (tsi_ssl_server_handshaker_factory *)factory; + tsi_ssl_handshaker_factory* factory) { + if (factory == nullptr) return; + tsi_ssl_server_handshaker_factory* self = + (tsi_ssl_server_handshaker_factory*)factory; size_t i; for (i = 0; i < self->ssl_context_count; i++) { - if (self->ssl_contexts[i] != NULL) { + if (self->ssl_contexts[i] != nullptr) { SSL_CTX_free(self->ssl_contexts[i]); tsi_peer_destruct(&self->ssl_context_x509_subject_names[i]); } } - if (self->ssl_contexts != NULL) gpr_free(self->ssl_contexts); - if (self->ssl_context_x509_subject_names != NULL) { + if (self->ssl_contexts != nullptr) gpr_free(self->ssl_contexts); + if (self->ssl_context_x509_subject_names != nullptr) { gpr_free(self->ssl_context_x509_subject_names); } - if (self->alpn_protocol_list != NULL) gpr_free(self->alpn_protocol_list); + if (self->alpn_protocol_list != nullptr) gpr_free(self->alpn_protocol_list); gpr_free(self); } -static int does_entry_match_name(const char *entry, size_t entry_length, - const char *name) { - const char *dot; - const char *name_subdomain = NULL; +static int does_entry_match_name(const char* entry, size_t entry_length, + const char* name) { + const char* dot; + const char* name_subdomain = nullptr; size_t name_length = strlen(name); size_t name_subdomain_length; if (entry_length == 0) return 0; @@ -1276,7 +1279,7 @@ static int does_entry_match_name(const char *entry, size_t entry_length, return 0; } name_subdomain = strchr(name, '.'); - if (name_subdomain == NULL) return 0; + if (name_subdomain == nullptr) return 0; name_subdomain_length = strlen(name_subdomain); if (name_subdomain_length < 2) return 0; name_subdomain++; /* Starts after the dot. */ @@ -1284,7 +1287,7 @@ static int does_entry_match_name(const char *entry, size_t entry_length, entry += 2; /* Remove *. */ entry_length -= 2; dot = strchr(name_subdomain, '.'); - if ((dot == NULL) || (dot == &name_subdomain[name_subdomain_length - 1])) { + if ((dot == nullptr) || (dot == &name_subdomain[name_subdomain_length - 1])) { gpr_log(GPR_ERROR, "Invalid toplevel subdomain: %s", name_subdomain); return 0; } @@ -1295,13 +1298,13 @@ static int does_entry_match_name(const char *entry, size_t entry_length, strncmp(entry, name_subdomain, entry_length) == 0); } -static int ssl_server_handshaker_factory_servername_callback(SSL *ssl, int *ap, - void *arg) { - tsi_ssl_server_handshaker_factory *impl = - (tsi_ssl_server_handshaker_factory *)arg; +static int ssl_server_handshaker_factory_servername_callback(SSL* ssl, int* ap, + void* arg) { + tsi_ssl_server_handshaker_factory* impl = + (tsi_ssl_server_handshaker_factory*)arg; size_t i = 0; - const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); - if (servername == NULL || strlen(servername) == 0) { + const char* servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); + if (servername == nullptr || strlen(servername) == 0) { return SSL_TLSEXT_ERR_NOACK; } @@ -1318,10 +1321,10 @@ static int ssl_server_handshaker_factory_servername_callback(SSL *ssl, int *ap, #if TSI_OPENSSL_ALPN_SUPPORT static int server_handshaker_factory_alpn_callback( - SSL *ssl, const unsigned char **out, unsigned char *outlen, - const unsigned char *in, unsigned int inlen, void *arg) { - tsi_ssl_server_handshaker_factory *factory = - (tsi_ssl_server_handshaker_factory *)arg; + SSL* ssl, const unsigned char** out, unsigned char* outlen, + const unsigned char* in, unsigned int inlen, void* arg) { + tsi_ssl_server_handshaker_factory* factory = + (tsi_ssl_server_handshaker_factory*)arg; return select_protocol_list(out, outlen, in, inlen, factory->alpn_protocol_list, factory->alpn_protocol_list_length); @@ -1329,9 +1332,9 @@ static int server_handshaker_factory_alpn_callback( #endif /* TSI_OPENSSL_ALPN_SUPPORT */ static int server_handshaker_factory_npn_advertised_callback( - SSL *ssl, const unsigned char **out, unsigned int *outlen, void *arg) { - tsi_ssl_server_handshaker_factory *factory = - (tsi_ssl_server_handshaker_factory *)arg; + SSL* ssl, const unsigned char** out, unsigned int* outlen, void* arg) { + tsi_ssl_server_handshaker_factory* factory = + (tsi_ssl_server_handshaker_factory*)arg; *out = factory->alpn_protocol_list; GPR_ASSERT(factory->alpn_protocol_list_length <= UINT_MAX); *outlen = (unsigned int)factory->alpn_protocol_list_length; @@ -1344,27 +1347,27 @@ static tsi_ssl_handshaker_factory_vtable client_handshaker_factory_vtable = { tsi_ssl_client_handshaker_factory_destroy}; tsi_result tsi_create_ssl_client_handshaker_factory( - const tsi_ssl_pem_key_cert_pair *pem_key_cert_pair, - const char *pem_root_certs, const char *cipher_suites, - const char **alpn_protocols, uint16_t num_alpn_protocols, - tsi_ssl_client_handshaker_factory **factory) { - SSL_CTX *ssl_context = NULL; - tsi_ssl_client_handshaker_factory *impl = NULL; + const tsi_ssl_pem_key_cert_pair* pem_key_cert_pair, + const char* pem_root_certs, const char* cipher_suites, + const char** alpn_protocols, uint16_t num_alpn_protocols, + tsi_ssl_client_handshaker_factory** factory) { + SSL_CTX* ssl_context = nullptr; + tsi_ssl_client_handshaker_factory* impl = nullptr; tsi_result result = TSI_OK; gpr_once_init(&init_openssl_once, init_openssl); - if (factory == NULL) return TSI_INVALID_ARGUMENT; - *factory = NULL; - if (pem_root_certs == NULL) return TSI_INVALID_ARGUMENT; + if (factory == nullptr) return TSI_INVALID_ARGUMENT; + *factory = nullptr; + if (pem_root_certs == nullptr) return TSI_INVALID_ARGUMENT; ssl_context = SSL_CTX_new(TLSv1_2_method()); - if (ssl_context == NULL) { + if (ssl_context == nullptr) { gpr_log(GPR_ERROR, "Could not create ssl context."); return TSI_INVALID_ARGUMENT; } - impl = (tsi_ssl_client_handshaker_factory *)gpr_zalloc(sizeof(*impl)); + impl = (tsi_ssl_client_handshaker_factory*)gpr_zalloc(sizeof(*impl)); tsi_ssl_handshaker_factory_init(&impl->base); impl->base.vtable = &client_handshaker_factory_vtable; @@ -1375,7 +1378,7 @@ tsi_result tsi_create_ssl_client_handshaker_factory( populate_ssl_context(ssl_context, pem_key_cert_pair, cipher_suites); if (result != TSI_OK) break; result = ssl_ctx_load_verification_certs(ssl_context, pem_root_certs, - strlen(pem_root_certs), NULL); + strlen(pem_root_certs), nullptr); if (result != TSI_OK) { gpr_log(GPR_ERROR, "Cannot load server root certificates."); break; @@ -1408,7 +1411,7 @@ tsi_result tsi_create_ssl_client_handshaker_factory( tsi_ssl_handshaker_factory_unref(&impl->base); return result; } - SSL_CTX_set_verify(ssl_context, SSL_VERIFY_PEER, NULL); + SSL_CTX_set_verify(ssl_context, SSL_VERIFY_PEER, nullptr); /* TODO(jboeuf): Add revocation verification. */ *factory = impl; @@ -1419,11 +1422,11 @@ static tsi_ssl_handshaker_factory_vtable server_handshaker_factory_vtable = { tsi_ssl_server_handshaker_factory_destroy}; tsi_result tsi_create_ssl_server_handshaker_factory( - const tsi_ssl_pem_key_cert_pair *pem_key_cert_pairs, - size_t num_key_cert_pairs, const char *pem_client_root_certs, - int force_client_auth, const char *cipher_suites, - const char **alpn_protocols, uint16_t num_alpn_protocols, - tsi_ssl_server_handshaker_factory **factory) { + const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs, + size_t num_key_cert_pairs, const char* pem_client_root_certs, + int force_client_auth, const char* cipher_suites, + const char** alpn_protocols, uint16_t num_alpn_protocols, + tsi_ssl_server_handshaker_factory** factory) { return tsi_create_ssl_server_handshaker_factory_ex( pem_key_cert_pairs, num_key_cert_pairs, pem_client_root_certs, force_client_auth ? TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY @@ -1432,33 +1435,33 @@ tsi_result tsi_create_ssl_server_handshaker_factory( } tsi_result tsi_create_ssl_server_handshaker_factory_ex( - const tsi_ssl_pem_key_cert_pair *pem_key_cert_pairs, - size_t num_key_cert_pairs, const char *pem_client_root_certs, + const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs, + size_t num_key_cert_pairs, const char* pem_client_root_certs, tsi_client_certificate_request_type client_certificate_request, - const char *cipher_suites, const char **alpn_protocols, - uint16_t num_alpn_protocols, tsi_ssl_server_handshaker_factory **factory) { - tsi_ssl_server_handshaker_factory *impl = NULL; + const char* cipher_suites, const char** alpn_protocols, + uint16_t num_alpn_protocols, tsi_ssl_server_handshaker_factory** factory) { + tsi_ssl_server_handshaker_factory* impl = nullptr; tsi_result result = TSI_OK; size_t i = 0; gpr_once_init(&init_openssl_once, init_openssl); - if (factory == NULL) return TSI_INVALID_ARGUMENT; - *factory = NULL; - if (num_key_cert_pairs == 0 || pem_key_cert_pairs == NULL) { + if (factory == nullptr) return TSI_INVALID_ARGUMENT; + *factory = nullptr; + if (num_key_cert_pairs == 0 || pem_key_cert_pairs == nullptr) { return TSI_INVALID_ARGUMENT; } - impl = (tsi_ssl_server_handshaker_factory *)gpr_zalloc(sizeof(*impl)); + impl = (tsi_ssl_server_handshaker_factory*)gpr_zalloc(sizeof(*impl)); tsi_ssl_handshaker_factory_init(&impl->base); impl->base.vtable = &server_handshaker_factory_vtable; impl->ssl_contexts = - (SSL_CTX **)gpr_zalloc(num_key_cert_pairs * sizeof(SSL_CTX *)); + (SSL_CTX**)gpr_zalloc(num_key_cert_pairs * sizeof(SSL_CTX*)); impl->ssl_context_x509_subject_names = - (tsi_peer *)gpr_zalloc(num_key_cert_pairs * sizeof(tsi_peer)); - if (impl->ssl_contexts == NULL || - impl->ssl_context_x509_subject_names == NULL) { + (tsi_peer*)gpr_zalloc(num_key_cert_pairs * sizeof(tsi_peer)); + if (impl->ssl_contexts == nullptr || + impl->ssl_context_x509_subject_names == nullptr) { tsi_ssl_handshaker_factory_unref(&impl->base); return TSI_OUT_OF_RESOURCES; } @@ -1477,7 +1480,7 @@ tsi_result tsi_create_ssl_server_handshaker_factory_ex( for (i = 0; i < num_key_cert_pairs; i++) { do { impl->ssl_contexts[i] = SSL_CTX_new(TLSv1_2_method()); - if (impl->ssl_contexts[i] == NULL) { + if (impl->ssl_contexts[i] == nullptr) { gpr_log(GPR_ERROR, "Could not create ssl context."); result = TSI_OUT_OF_RESOURCES; break; @@ -1486,8 +1489,8 @@ tsi_result tsi_create_ssl_server_handshaker_factory_ex( &pem_key_cert_pairs[i], cipher_suites); if (result != TSI_OK) break; - if (pem_client_root_certs != NULL) { - STACK_OF(X509_NAME) *root_names = NULL; + if (pem_client_root_certs != nullptr) { + STACK_OF(X509_NAME)* root_names = nullptr; result = ssl_ctx_load_verification_certs( impl->ssl_contexts[i], pem_client_root_certs, strlen(pem_client_root_certs), &root_names); @@ -1498,14 +1501,14 @@ tsi_result tsi_create_ssl_server_handshaker_factory_ex( SSL_CTX_set_client_CA_list(impl->ssl_contexts[i], root_names); switch (client_certificate_request) { case TSI_DONT_REQUEST_CLIENT_CERTIFICATE: - SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_NONE, NULL); + SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_NONE, nullptr); break; case TSI_REQUEST_CLIENT_CERTIFICATE_BUT_DONT_VERIFY: SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_PEER, NullVerifyCallback); break; case TSI_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY: - SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_PEER, NULL); + SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_PEER, nullptr); break; case TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY: SSL_CTX_set_verify( @@ -1516,7 +1519,7 @@ tsi_result tsi_create_ssl_server_handshaker_factory_ex( case TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY: SSL_CTX_set_verify( impl->ssl_contexts[i], - SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL); + SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr); break; } /* TODO(jboeuf): Add revocation verification. */ @@ -1552,16 +1555,16 @@ tsi_result tsi_create_ssl_server_handshaker_factory_ex( /* --- tsi_ssl utils. --- */ -int tsi_ssl_peer_matches_name(const tsi_peer *peer, const char *name) { +int tsi_ssl_peer_matches_name(const tsi_peer* peer, const char* name) { size_t i = 0; size_t san_count = 0; - const tsi_peer_property *cn_property = NULL; + const tsi_peer_property* cn_property = nullptr; int like_ip = looks_like_ip_address(name); /* Check the SAN first. */ for (i = 0; i < peer->property_count; i++) { - const tsi_peer_property *property = &peer->properties[i]; - if (property->name == NULL) continue; + const tsi_peer_property* property = &peer->properties[i]; + if (property->name == nullptr) continue; if (strcmp(property->name, TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY) == 0) { san_count++; @@ -1583,7 +1586,7 @@ int tsi_ssl_peer_matches_name(const tsi_peer *peer, const char *name) { } /* If there's no SAN, try the CN, but only if its not like an IP Address */ - if (san_count == 0 && cn_property != NULL && !like_ip) { + if (san_count == 0 && cn_property != nullptr && !like_ip) { if (does_entry_match_name(cn_property->value.data, cn_property->value.length, name)) { return 1; @@ -1594,13 +1597,13 @@ int tsi_ssl_peer_matches_name(const tsi_peer *peer, const char *name) { } /* --- Testing support. --- */ -const tsi_ssl_handshaker_factory_vtable *tsi_ssl_handshaker_factory_swap_vtable( - tsi_ssl_handshaker_factory *factory, - tsi_ssl_handshaker_factory_vtable *new_vtable) { - GPR_ASSERT(factory != NULL); - GPR_ASSERT(factory->vtable != NULL); +const tsi_ssl_handshaker_factory_vtable* tsi_ssl_handshaker_factory_swap_vtable( + tsi_ssl_handshaker_factory* factory, + tsi_ssl_handshaker_factory_vtable* new_vtable) { + GPR_ASSERT(factory != nullptr); + GPR_ASSERT(factory->vtable != nullptr); - const tsi_ssl_handshaker_factory_vtable *orig_vtable = factory->vtable; + const tsi_ssl_handshaker_factory_vtable* orig_vtable = factory->vtable; factory->vtable = new_vtable; return orig_vtable; } diff --git a/src/core/tsi/ssl_transport_security.h b/src/core/tsi/ssl_transport_security.h index 3abfdf5ed87..bf211e110a2 100644 --- a/src/core/tsi/ssl_transport_security.h +++ b/src/core/tsi/ssl_transport_security.h @@ -21,10 +21,6 @@ #include "src/core/tsi/transport_security_interface.h" -#ifdef __cplusplus -extern "C" { -#endif - /* Value for the TSI_CERTIFICATE_TYPE_PEER_PROPERTY property for X509 certs. */ #define TSI_X509_CERTIFICATE_TYPE "X509" @@ -49,11 +45,11 @@ typedef struct tsi_ssl_client_handshaker_factory typedef struct { /* private_key is the NULL-terminated string containing the PEM encoding of the client's private key. */ - const char *private_key; + const char* private_key; /* cert_chain is the NULL-terminated string containing the PEM encoding of the client's certificate chain. */ - const char *cert_chain; + const char* cert_chain; } tsi_ssl_pem_key_cert_pair; /* Creates a client handshaker factory. @@ -78,10 +74,10 @@ typedef struct { - This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case where a parameter is invalid. */ tsi_result tsi_create_ssl_client_handshaker_factory( - const tsi_ssl_pem_key_cert_pair *pem_key_cert_pair, - const char *pem_root_certs, const char *cipher_suites, - const char **alpn_protocols, uint16_t num_alpn_protocols, - tsi_ssl_client_handshaker_factory **factory); + const tsi_ssl_pem_key_cert_pair* pem_key_cert_pair, + const char* pem_root_certs, const char* cipher_suites, + const char** alpn_protocols, uint16_t num_alpn_protocols, + tsi_ssl_client_handshaker_factory** factory); /* Creates a client handshaker. - self is the factory from which the handshaker will be created. @@ -93,13 +89,13 @@ tsi_result tsi_create_ssl_client_handshaker_factory( - This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case where a parameter is invalid. */ tsi_result tsi_ssl_client_handshaker_factory_create_handshaker( - tsi_ssl_client_handshaker_factory *self, const char *server_name_indication, - tsi_handshaker **handshaker); + tsi_ssl_client_handshaker_factory* self, const char* server_name_indication, + tsi_handshaker** handshaker); /* Decrements reference count of the handshaker factory. Handshaker factory will * be destroyed once no references exist. */ void tsi_ssl_client_handshaker_factory_unref( - tsi_ssl_client_handshaker_factory *factory); + tsi_ssl_client_handshaker_factory* factory); /* --- tsi_ssl_server_handshaker_factory object --- @@ -130,11 +126,11 @@ typedef struct tsi_ssl_server_handshaker_factory - This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case where a parameter is invalid. */ tsi_result tsi_create_ssl_server_handshaker_factory( - const tsi_ssl_pem_key_cert_pair *pem_key_cert_pairs, - size_t num_key_cert_pairs, const char *pem_client_root_certs, - int force_client_auth, const char *cipher_suites, - const char **alpn_protocols, uint16_t num_alpn_protocols, - tsi_ssl_server_handshaker_factory **factory); + const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs, + size_t num_key_cert_pairs, const char* pem_client_root_certs, + int force_client_auth, const char* cipher_suites, + const char** alpn_protocols, uint16_t num_alpn_protocols, + tsi_ssl_server_handshaker_factory** factory); /* Same as tsi_create_ssl_server_handshaker_factory method except uses tsi_client_certificate_request_type to support more ways to handle client @@ -143,11 +139,11 @@ tsi_result tsi_create_ssl_server_handshaker_factory( authenticate with an SSL cert. Note that this option is ignored if pem_client_root_certs is NULL or pem_client_roots_certs_size is 0 */ tsi_result tsi_create_ssl_server_handshaker_factory_ex( - const tsi_ssl_pem_key_cert_pair *pem_key_cert_pairs, - size_t num_key_cert_pairs, const char *pem_client_root_certs, + const tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs, + size_t num_key_cert_pairs, const char* pem_client_root_certs, tsi_client_certificate_request_type client_certificate_request, - const char *cipher_suites, const char **alpn_protocols, - uint16_t num_alpn_protocols, tsi_ssl_server_handshaker_factory **factory); + const char* cipher_suites, const char** alpn_protocols, + uint16_t num_alpn_protocols, tsi_ssl_server_handshaker_factory** factory); /* Creates a server handshaker. - self is the factory from which the handshaker will be created. @@ -156,19 +152,19 @@ tsi_result tsi_create_ssl_server_handshaker_factory_ex( - This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case where a parameter is invalid. */ tsi_result tsi_ssl_server_handshaker_factory_create_handshaker( - tsi_ssl_server_handshaker_factory *self, tsi_handshaker **handshaker); + tsi_ssl_server_handshaker_factory* self, tsi_handshaker** handshaker); /* Decrements reference count of the handshaker factory. Handshaker factory will * be destroyed once no references exist. */ void tsi_ssl_server_handshaker_factory_unref( - tsi_ssl_server_handshaker_factory *self); + tsi_ssl_server_handshaker_factory* self); /* Util that checks that an ssl peer matches a specific name. Still TODO(jboeuf): - handle mixed case. - handle %encoded chars. - handle public suffix wildchar more strictly (e.g. *.co.uk) */ -int tsi_ssl_peer_matches_name(const tsi_peer *peer, const char *name); +int tsi_ssl_peer_matches_name(const tsi_peer* peer, const char* name); /* --- Testing support. --- @@ -180,7 +176,7 @@ typedef struct tsi_ssl_handshaker_factory tsi_ssl_handshaker_factory; /* Function pointer to handshaker_factory destructor. */ typedef void (*tsi_ssl_handshaker_factory_destructor)( - tsi_ssl_handshaker_factory *factory); + tsi_ssl_handshaker_factory* factory); /* Virtual table for tsi_ssl_handshaker_factory. */ typedef struct { @@ -189,12 +185,8 @@ typedef struct { /* Set destructor of handshaker_factory to new_destructor, returns previous destructor. */ -const tsi_ssl_handshaker_factory_vtable *tsi_ssl_handshaker_factory_swap_vtable( - tsi_ssl_handshaker_factory *factory, - tsi_ssl_handshaker_factory_vtable *new_vtable); - -#ifdef __cplusplus -} -#endif +const tsi_ssl_handshaker_factory_vtable* tsi_ssl_handshaker_factory_swap_vtable( + tsi_ssl_handshaker_factory* factory, + tsi_ssl_handshaker_factory_vtable* new_vtable); #endif /* GRPC_CORE_TSI_SSL_TRANSPORT_SECURITY_H */ diff --git a/src/core/tsi/ssl_types.h b/src/core/tsi/ssl_types.h index e0e967034b2..3788643355c 100644 --- a/src/core/tsi/ssl_types.h +++ b/src/core/tsi/ssl_types.h @@ -19,10 +19,6 @@ #ifndef GRPC_CORE_TSI_SSL_TYPES_H #define GRPC_CORE_TSI_SSL_TYPES_H -#ifdef __cplusplus -extern "C" { -#endif - /* A collection of macros to cast between various integer types that are * used differently between BoringSSL and OpenSSL: * TSI_INT_AS_SIZE(x): convert 'int x' to a length parameter for an OpenSSL @@ -41,8 +37,4 @@ extern "C" { #define TSI_SIZE_AS_SIZE(x) ((int)(x)) #endif -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_TSI_SSL_TYPES_H */ diff --git a/src/core/tsi/transport_security.cc b/src/core/tsi/transport_security.cc index 21bd8eba78e..5abd2f0f689 100644 --- a/src/core/tsi/transport_security.cc +++ b/src/core/tsi/transport_security.cc @@ -26,11 +26,11 @@ /* --- Tracing. --- */ -grpc_tracer_flag tsi_tracing_enabled = GRPC_TRACER_INITIALIZER(false, "tsi"); +grpc_core::TraceFlag tsi_tracing_enabled(false, "tsi"); /* --- tsi_result common implementation. --- */ -const char *tsi_result_to_string(tsi_result result) { +const char* tsi_result_to_string(tsi_result result) { switch (result) { case TSI_OK: return "TSI_OK"; @@ -69,52 +69,56 @@ const char *tsi_result_to_string(tsi_result result) { Calls specific implementation after state/input validation. */ -tsi_result tsi_frame_protector_protect(tsi_frame_protector *self, - const unsigned char *unprotected_bytes, - size_t *unprotected_bytes_size, - unsigned char *protected_output_frames, - size_t *protected_output_frames_size) { - if (self == NULL || self->vtable == NULL || unprotected_bytes == NULL || - unprotected_bytes_size == NULL || protected_output_frames == NULL || - protected_output_frames_size == NULL) { +tsi_result tsi_frame_protector_protect(tsi_frame_protector* self, + const unsigned char* unprotected_bytes, + size_t* unprotected_bytes_size, + unsigned char* protected_output_frames, + size_t* protected_output_frames_size) { + if (self == nullptr || self->vtable == nullptr || + unprotected_bytes == nullptr || unprotected_bytes_size == nullptr || + protected_output_frames == nullptr || + protected_output_frames_size == nullptr) { return TSI_INVALID_ARGUMENT; } - if (self->vtable->protect == NULL) return TSI_UNIMPLEMENTED; + if (self->vtable->protect == nullptr) return TSI_UNIMPLEMENTED; return self->vtable->protect(self, unprotected_bytes, unprotected_bytes_size, protected_output_frames, protected_output_frames_size); } tsi_result tsi_frame_protector_protect_flush( - tsi_frame_protector *self, unsigned char *protected_output_frames, - size_t *protected_output_frames_size, size_t *still_pending_size) { - if (self == NULL || self->vtable == NULL || protected_output_frames == NULL || - protected_output_frames_size == NULL || still_pending_size == NULL) { + tsi_frame_protector* self, unsigned char* protected_output_frames, + size_t* protected_output_frames_size, size_t* still_pending_size) { + if (self == nullptr || self->vtable == nullptr || + protected_output_frames == nullptr || + protected_output_frames_size == nullptr || + still_pending_size == nullptr) { return TSI_INVALID_ARGUMENT; } - if (self->vtable->protect_flush == NULL) return TSI_UNIMPLEMENTED; + if (self->vtable->protect_flush == nullptr) return TSI_UNIMPLEMENTED; return self->vtable->protect_flush(self, protected_output_frames, protected_output_frames_size, still_pending_size); } tsi_result tsi_frame_protector_unprotect( - tsi_frame_protector *self, const unsigned char *protected_frames_bytes, - size_t *protected_frames_bytes_size, unsigned char *unprotected_bytes, - size_t *unprotected_bytes_size) { - if (self == NULL || self->vtable == NULL || protected_frames_bytes == NULL || - protected_frames_bytes_size == NULL || unprotected_bytes == NULL || - unprotected_bytes_size == NULL) { + tsi_frame_protector* self, const unsigned char* protected_frames_bytes, + size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes, + size_t* unprotected_bytes_size) { + if (self == nullptr || self->vtable == nullptr || + protected_frames_bytes == nullptr || + protected_frames_bytes_size == nullptr || unprotected_bytes == nullptr || + unprotected_bytes_size == nullptr) { return TSI_INVALID_ARGUMENT; } - if (self->vtable->unprotect == NULL) return TSI_UNIMPLEMENTED; + if (self->vtable->unprotect == nullptr) return TSI_UNIMPLEMENTED; return self->vtable->unprotect(self, protected_frames_bytes, protected_frames_bytes_size, unprotected_bytes, unprotected_bytes_size); } -void tsi_frame_protector_destroy(tsi_frame_protector *self) { - if (self == NULL) return; +void tsi_frame_protector_destroy(tsi_frame_protector* self) { + if (self == nullptr) return; self->vtable->destroy(self); } @@ -122,39 +126,41 @@ void tsi_frame_protector_destroy(tsi_frame_protector *self) { Calls specific implementation after state/input validation. */ -tsi_result tsi_handshaker_get_bytes_to_send_to_peer(tsi_handshaker *self, - unsigned char *bytes, - size_t *bytes_size) { - if (self == NULL || self->vtable == NULL || bytes == NULL || - bytes_size == NULL) { +tsi_result tsi_handshaker_get_bytes_to_send_to_peer(tsi_handshaker* self, + unsigned char* bytes, + size_t* bytes_size) { + if (self == nullptr || self->vtable == nullptr || bytes == nullptr || + bytes_size == nullptr) { return TSI_INVALID_ARGUMENT; } if (self->frame_protector_created) return TSI_FAILED_PRECONDITION; - if (self->vtable->get_bytes_to_send_to_peer == NULL) return TSI_UNIMPLEMENTED; + if (self->vtable->get_bytes_to_send_to_peer == nullptr) + return TSI_UNIMPLEMENTED; return self->vtable->get_bytes_to_send_to_peer(self, bytes, bytes_size); } -tsi_result tsi_handshaker_process_bytes_from_peer(tsi_handshaker *self, - const unsigned char *bytes, - size_t *bytes_size) { - if (self == NULL || self->vtable == NULL || bytes == NULL || - bytes_size == NULL) { +tsi_result tsi_handshaker_process_bytes_from_peer(tsi_handshaker* self, + const unsigned char* bytes, + size_t* bytes_size) { + if (self == nullptr || self->vtable == nullptr || bytes == nullptr || + bytes_size == nullptr) { return TSI_INVALID_ARGUMENT; } if (self->frame_protector_created) return TSI_FAILED_PRECONDITION; - if (self->vtable->process_bytes_from_peer == NULL) return TSI_UNIMPLEMENTED; + if (self->vtable->process_bytes_from_peer == nullptr) + return TSI_UNIMPLEMENTED; return self->vtable->process_bytes_from_peer(self, bytes, bytes_size); } -tsi_result tsi_handshaker_get_result(tsi_handshaker *self) { - if (self == NULL || self->vtable == NULL) return TSI_INVALID_ARGUMENT; +tsi_result tsi_handshaker_get_result(tsi_handshaker* self) { + if (self == nullptr || self->vtable == nullptr) return TSI_INVALID_ARGUMENT; if (self->frame_protector_created) return TSI_FAILED_PRECONDITION; - if (self->vtable->get_result == NULL) return TSI_UNIMPLEMENTED; + if (self->vtable->get_result == nullptr) return TSI_UNIMPLEMENTED; return self->vtable->get_result(self); } -tsi_result tsi_handshaker_extract_peer(tsi_handshaker *self, tsi_peer *peer) { - if (self == NULL || self->vtable == NULL || peer == NULL) { +tsi_result tsi_handshaker_extract_peer(tsi_handshaker* self, tsi_peer* peer) { + if (self == nullptr || self->vtable == nullptr || peer == nullptr) { return TSI_INVALID_ARGUMENT; } memset(peer, 0, sizeof(tsi_peer)); @@ -162,20 +168,20 @@ tsi_result tsi_handshaker_extract_peer(tsi_handshaker *self, tsi_peer *peer) { if (tsi_handshaker_get_result(self) != TSI_OK) { return TSI_FAILED_PRECONDITION; } - if (self->vtable->extract_peer == NULL) return TSI_UNIMPLEMENTED; + if (self->vtable->extract_peer == nullptr) return TSI_UNIMPLEMENTED; return self->vtable->extract_peer(self, peer); } tsi_result tsi_handshaker_create_frame_protector( - tsi_handshaker *self, size_t *max_protected_frame_size, - tsi_frame_protector **protector) { + tsi_handshaker* self, size_t* max_protected_frame_size, + tsi_frame_protector** protector) { tsi_result result; - if (self == NULL || self->vtable == NULL || protector == NULL) { + if (self == nullptr || self->vtable == nullptr || protector == nullptr) { return TSI_INVALID_ARGUMENT; } if (self->frame_protector_created) return TSI_FAILED_PRECONDITION; if (tsi_handshaker_get_result(self) != TSI_OK) return TSI_FAILED_PRECONDITION; - if (self->vtable->create_frame_protector == NULL) return TSI_UNIMPLEMENTED; + if (self->vtable->create_frame_protector == nullptr) return TSI_UNIMPLEMENTED; result = self->vtable->create_frame_protector(self, max_protected_frame_size, protector); if (result == TSI_OK) { @@ -185,59 +191,59 @@ tsi_result tsi_handshaker_create_frame_protector( } tsi_result tsi_handshaker_next( - tsi_handshaker *self, const unsigned char *received_bytes, - size_t received_bytes_size, const unsigned char **bytes_to_send, - size_t *bytes_to_send_size, tsi_handshaker_result **handshaker_result, - tsi_handshaker_on_next_done_cb cb, void *user_data) { - if (self == NULL || self->vtable == NULL) return TSI_INVALID_ARGUMENT; + tsi_handshaker* self, const unsigned char* received_bytes, + size_t received_bytes_size, const unsigned char** bytes_to_send, + size_t* bytes_to_send_size, tsi_handshaker_result** handshaker_result, + tsi_handshaker_on_next_done_cb cb, void* user_data) { + if (self == nullptr || self->vtable == nullptr) return TSI_INVALID_ARGUMENT; if (self->handshaker_result_created) return TSI_FAILED_PRECONDITION; - if (self->vtable->next == NULL) return TSI_UNIMPLEMENTED; + if (self->vtable->next == nullptr) return TSI_UNIMPLEMENTED; return self->vtable->next(self, received_bytes, received_bytes_size, bytes_to_send, bytes_to_send_size, handshaker_result, cb, user_data); } -void tsi_handshaker_destroy(tsi_handshaker *self) { - if (self == NULL) return; +void tsi_handshaker_destroy(tsi_handshaker* self) { + if (self == nullptr) return; self->vtable->destroy(self); } /* --- tsi_handshaker_result implementation. --- */ -tsi_result tsi_handshaker_result_extract_peer(const tsi_handshaker_result *self, - tsi_peer *peer) { - if (self == NULL || self->vtable == NULL || peer == NULL) { +tsi_result tsi_handshaker_result_extract_peer(const tsi_handshaker_result* self, + tsi_peer* peer) { + if (self == nullptr || self->vtable == nullptr || peer == nullptr) { return TSI_INVALID_ARGUMENT; } memset(peer, 0, sizeof(tsi_peer)); - if (self->vtable->extract_peer == NULL) return TSI_UNIMPLEMENTED; + if (self->vtable->extract_peer == nullptr) return TSI_UNIMPLEMENTED; return self->vtable->extract_peer(self, peer); } tsi_result tsi_handshaker_result_create_frame_protector( - const tsi_handshaker_result *self, size_t *max_protected_frame_size, - tsi_frame_protector **protector) { - if (self == NULL || self->vtable == NULL || protector == NULL) { + const tsi_handshaker_result* self, size_t* max_protected_frame_size, + tsi_frame_protector** protector) { + if (self == nullptr || self->vtable == nullptr || protector == nullptr) { return TSI_INVALID_ARGUMENT; } - if (self->vtable->create_frame_protector == NULL) return TSI_UNIMPLEMENTED; + if (self->vtable->create_frame_protector == nullptr) return TSI_UNIMPLEMENTED; return self->vtable->create_frame_protector(self, max_protected_frame_size, protector); } tsi_result tsi_handshaker_result_get_unused_bytes( - const tsi_handshaker_result *self, const unsigned char **bytes, - size_t *bytes_size) { - if (self == NULL || self->vtable == NULL || bytes == NULL || - bytes_size == NULL) { + const tsi_handshaker_result* self, const unsigned char** bytes, + size_t* bytes_size) { + if (self == nullptr || self->vtable == nullptr || bytes == nullptr || + bytes_size == nullptr) { return TSI_INVALID_ARGUMENT; } - if (self->vtable->get_unused_bytes == NULL) return TSI_UNIMPLEMENTED; + if (self->vtable->get_unused_bytes == nullptr) return TSI_UNIMPLEMENTED; return self->vtable->get_unused_bytes(self, bytes, bytes_size); } -void tsi_handshaker_result_destroy(tsi_handshaker_result *self) { - if (self == NULL) return; +void tsi_handshaker_result_destroy(tsi_handshaker_result* self) { + if (self == nullptr) return; self->vtable->destroy(self); } @@ -249,7 +255,7 @@ tsi_peer_property tsi_init_peer_property(void) { return property; } -static void tsi_peer_destroy_list_property(tsi_peer_property *children, +static void tsi_peer_destroy_list_property(tsi_peer_property* children, size_t child_count) { size_t i; for (i = 0; i < child_count; i++) { @@ -258,46 +264,46 @@ static void tsi_peer_destroy_list_property(tsi_peer_property *children, gpr_free(children); } -void tsi_peer_property_destruct(tsi_peer_property *property) { - if (property->name != NULL) { +void tsi_peer_property_destruct(tsi_peer_property* property) { + if (property->name != nullptr) { gpr_free(property->name); } - if (property->value.data != NULL) { + if (property->value.data != nullptr) { gpr_free(property->value.data); } *property = tsi_init_peer_property(); /* Reset everything to 0. */ } -void tsi_peer_destruct(tsi_peer *self) { - if (self == NULL) return; - if (self->properties != NULL) { +void tsi_peer_destruct(tsi_peer* self) { + if (self == nullptr) return; + if (self->properties != nullptr) { tsi_peer_destroy_list_property(self->properties, self->property_count); - self->properties = NULL; + self->properties = nullptr; } self->property_count = 0; } tsi_result tsi_construct_allocated_string_peer_property( - const char *name, size_t value_length, tsi_peer_property *property) { + const char* name, size_t value_length, tsi_peer_property* property) { *property = tsi_init_peer_property(); - if (name != NULL) property->name = gpr_strdup(name); + if (name != nullptr) property->name = gpr_strdup(name); if (value_length > 0) { - property->value.data = (char *)gpr_zalloc(value_length); + property->value.data = (char*)gpr_zalloc(value_length); property->value.length = value_length; } return TSI_OK; } tsi_result tsi_construct_string_peer_property_from_cstring( - const char *name, const char *value, tsi_peer_property *property) { + const char* name, const char* value, tsi_peer_property* property) { return tsi_construct_string_peer_property(name, value, strlen(value), property); } -tsi_result tsi_construct_string_peer_property(const char *name, - const char *value, +tsi_result tsi_construct_string_peer_property(const char* name, + const char* value, size_t value_length, - tsi_peer_property *property) { + tsi_peer_property* property) { tsi_result result = tsi_construct_allocated_string_peer_property( name, value_length, property); if (result != TSI_OK) return result; @@ -307,10 +313,10 @@ tsi_result tsi_construct_string_peer_property(const char *name, return TSI_OK; } -tsi_result tsi_construct_peer(size_t property_count, tsi_peer *peer) { +tsi_result tsi_construct_peer(size_t property_count, tsi_peer* peer) { memset(peer, 0, sizeof(tsi_peer)); if (property_count > 0) { - peer->properties = (tsi_peer_property *)gpr_zalloc( + peer->properties = (tsi_peer_property*)gpr_zalloc( property_count * sizeof(tsi_peer_property)); peer->property_count = property_count; } diff --git a/src/core/tsi/transport_security.h b/src/core/tsi/transport_security.h index 3bba38149c8..bf3a776b112 100644 --- a/src/core/tsi/transport_security.h +++ b/src/core/tsi/transport_security.h @@ -24,61 +24,57 @@ #include "src/core/lib/debug/trace.h" #include "src/core/tsi/transport_security_interface.h" -#ifdef __cplusplus -extern "C" { -#endif - -extern grpc_tracer_flag tsi_tracing_enabled; +extern grpc_core::TraceFlag tsi_tracing_enabled; /* Base for tsi_frame_protector implementations. See transport_security_interface.h for documentation. */ typedef struct { - tsi_result (*protect)(tsi_frame_protector *self, - const unsigned char *unprotected_bytes, - size_t *unprotected_bytes_size, - unsigned char *protected_output_frames, - size_t *protected_output_frames_size); - tsi_result (*protect_flush)(tsi_frame_protector *self, - unsigned char *protected_output_frames, - size_t *protected_output_frames_size, - size_t *still_pending_size); - tsi_result (*unprotect)(tsi_frame_protector *self, - const unsigned char *protected_frames_bytes, - size_t *protected_frames_bytes_size, - unsigned char *unprotected_bytes, - size_t *unprotected_bytes_size); - void (*destroy)(tsi_frame_protector *self); + tsi_result (*protect)(tsi_frame_protector* self, + const unsigned char* unprotected_bytes, + size_t* unprotected_bytes_size, + unsigned char* protected_output_frames, + size_t* protected_output_frames_size); + tsi_result (*protect_flush)(tsi_frame_protector* self, + unsigned char* protected_output_frames, + size_t* protected_output_frames_size, + size_t* still_pending_size); + tsi_result (*unprotect)(tsi_frame_protector* self, + const unsigned char* protected_frames_bytes, + size_t* protected_frames_bytes_size, + unsigned char* unprotected_bytes, + size_t* unprotected_bytes_size); + void (*destroy)(tsi_frame_protector* self); } tsi_frame_protector_vtable; struct tsi_frame_protector { - const tsi_frame_protector_vtable *vtable; + const tsi_frame_protector_vtable* vtable; }; /* Base for tsi_handshaker implementations. See transport_security_interface.h for documentation. */ typedef struct { - tsi_result (*get_bytes_to_send_to_peer)(tsi_handshaker *self, - unsigned char *bytes, - size_t *bytes_size); - tsi_result (*process_bytes_from_peer)(tsi_handshaker *self, - const unsigned char *bytes, - size_t *bytes_size); - tsi_result (*get_result)(tsi_handshaker *self); - tsi_result (*extract_peer)(tsi_handshaker *self, tsi_peer *peer); - tsi_result (*create_frame_protector)(tsi_handshaker *self, - size_t *max_protected_frame_size, - tsi_frame_protector **protector); - void (*destroy)(tsi_handshaker *self); - tsi_result (*next)(tsi_handshaker *self, const unsigned char *received_bytes, + tsi_result (*get_bytes_to_send_to_peer)(tsi_handshaker* self, + unsigned char* bytes, + size_t* bytes_size); + tsi_result (*process_bytes_from_peer)(tsi_handshaker* self, + const unsigned char* bytes, + size_t* bytes_size); + tsi_result (*get_result)(tsi_handshaker* self); + tsi_result (*extract_peer)(tsi_handshaker* self, tsi_peer* peer); + tsi_result (*create_frame_protector)(tsi_handshaker* self, + size_t* max_protected_frame_size, + tsi_frame_protector** protector); + void (*destroy)(tsi_handshaker* self); + tsi_result (*next)(tsi_handshaker* self, const unsigned char* received_bytes, size_t received_bytes_size, - const unsigned char **bytes_to_send, - size_t *bytes_to_send_size, - tsi_handshaker_result **handshaker_result, - tsi_handshaker_on_next_done_cb cb, void *user_data); + const unsigned char** bytes_to_send, + size_t* bytes_to_send_size, + tsi_handshaker_result** handshaker_result, + tsi_handshaker_on_next_done_cb cb, void* user_data); } tsi_handshaker_vtable; struct tsi_handshaker { - const tsi_handshaker_vtable *vtable; + const tsi_handshaker_vtable* vtable; bool frame_protector_created; bool handshaker_result_created; }; @@ -92,42 +88,38 @@ struct tsi_handshaker { needs to compile in other applications, where grpc_exec_ctx is not defined. */ typedef struct { - tsi_result (*extract_peer)(const tsi_handshaker_result *self, tsi_peer *peer); + tsi_result (*extract_peer)(const tsi_handshaker_result* self, tsi_peer* peer); tsi_result (*create_zero_copy_grpc_protector)( - void *exec_ctx, const tsi_handshaker_result *self, - size_t *max_output_protected_frame_size, - tsi_zero_copy_grpc_protector **protector); - tsi_result (*create_frame_protector)(const tsi_handshaker_result *self, - size_t *max_output_protected_frame_size, - tsi_frame_protector **protector); - tsi_result (*get_unused_bytes)(const tsi_handshaker_result *self, - const unsigned char **bytes, - size_t *bytes_size); - void (*destroy)(tsi_handshaker_result *self); + void* exec_ctx, const tsi_handshaker_result* self, + size_t* max_output_protected_frame_size, + tsi_zero_copy_grpc_protector** protector); + tsi_result (*create_frame_protector)(const tsi_handshaker_result* self, + size_t* max_output_protected_frame_size, + tsi_frame_protector** protector); + tsi_result (*get_unused_bytes)(const tsi_handshaker_result* self, + const unsigned char** bytes, + size_t* bytes_size); + void (*destroy)(tsi_handshaker_result* self); } tsi_handshaker_result_vtable; struct tsi_handshaker_result { - const tsi_handshaker_result_vtable *vtable; + const tsi_handshaker_result_vtable* vtable; }; /* Peer and property construction/destruction functions. */ -tsi_result tsi_construct_peer(size_t property_count, tsi_peer *peer); +tsi_result tsi_construct_peer(size_t property_count, tsi_peer* peer); tsi_peer_property tsi_init_peer_property(void); -void tsi_peer_property_destruct(tsi_peer_property *property); -tsi_result tsi_construct_string_peer_property(const char *name, - const char *value, +void tsi_peer_property_destruct(tsi_peer_property* property); +tsi_result tsi_construct_string_peer_property(const char* name, + const char* value, size_t value_length, - tsi_peer_property *property); + tsi_peer_property* property); tsi_result tsi_construct_allocated_string_peer_property( - const char *name, size_t value_length, tsi_peer_property *property); + const char* name, size_t value_length, tsi_peer_property* property); tsi_result tsi_construct_string_peer_property_from_cstring( - const char *name, const char *value, tsi_peer_property *property); + const char* name, const char* value, tsi_peer_property* property); /* Utils. */ -char *tsi_strdup(const char *src); /* Sadly, no strdup in C89. */ - -#ifdef __cplusplus -} -#endif +char* tsi_strdup(const char* src); /* Sadly, no strdup in C89. */ #endif /* GRPC_CORE_TSI_TRANSPORT_SECURITY_H */ diff --git a/src/core/tsi/transport_security_adapter.cc b/src/core/tsi/transport_security_adapter.cc index e399e42758d..56dec554949 100644 --- a/src/core/tsi/transport_security_adapter.cc +++ b/src/core/tsi/transport_security_adapter.cc @@ -30,36 +30,36 @@ typedef struct { tsi_handshaker_result base; - tsi_handshaker *wrapped; - unsigned char *unused_bytes; + tsi_handshaker* wrapped; + unsigned char* unused_bytes; size_t unused_bytes_size; } tsi_adapter_handshaker_result; -static tsi_result adapter_result_extract_peer(const tsi_handshaker_result *self, - tsi_peer *peer) { - tsi_adapter_handshaker_result *impl = (tsi_adapter_handshaker_result *)self; +static tsi_result adapter_result_extract_peer(const tsi_handshaker_result* self, + tsi_peer* peer) { + tsi_adapter_handshaker_result* impl = (tsi_adapter_handshaker_result*)self; return tsi_handshaker_extract_peer(impl->wrapped, peer); } static tsi_result adapter_result_create_frame_protector( - const tsi_handshaker_result *self, size_t *max_output_protected_frame_size, - tsi_frame_protector **protector) { - tsi_adapter_handshaker_result *impl = (tsi_adapter_handshaker_result *)self; + const tsi_handshaker_result* self, size_t* max_output_protected_frame_size, + tsi_frame_protector** protector) { + tsi_adapter_handshaker_result* impl = (tsi_adapter_handshaker_result*)self; return tsi_handshaker_create_frame_protector( impl->wrapped, max_output_protected_frame_size, protector); } static tsi_result adapter_result_get_unused_bytes( - const tsi_handshaker_result *self, const unsigned char **bytes, - size_t *byte_size) { - tsi_adapter_handshaker_result *impl = (tsi_adapter_handshaker_result *)self; + const tsi_handshaker_result* self, const unsigned char** bytes, + size_t* byte_size) { + tsi_adapter_handshaker_result* impl = (tsi_adapter_handshaker_result*)self; *bytes = impl->unused_bytes; *byte_size = impl->unused_bytes_size; return TSI_OK; } -static void adapter_result_destroy(tsi_handshaker_result *self) { - tsi_adapter_handshaker_result *impl = (tsi_adapter_handshaker_result *)self; +static void adapter_result_destroy(tsi_handshaker_result* self) { + tsi_adapter_handshaker_result* impl = (tsi_adapter_handshaker_result*)self; tsi_handshaker_destroy(impl->wrapped); gpr_free(impl->unused_bytes); gpr_free(self); @@ -67,7 +67,7 @@ static void adapter_result_destroy(tsi_handshaker_result *self) { static const tsi_handshaker_result_vtable result_vtable = { adapter_result_extract_peer, - NULL, /* create_zero_copy_grpc_protector */ + nullptr, /* create_zero_copy_grpc_protector */ adapter_result_create_frame_protector, adapter_result_get_unused_bytes, adapter_result_destroy, @@ -75,21 +75,22 @@ static const tsi_handshaker_result_vtable result_vtable = { /* Ownership of wrapped tsi_handshaker is transferred to the result object. */ static tsi_result tsi_adapter_create_handshaker_result( - tsi_handshaker *wrapped, const unsigned char *unused_bytes, - size_t unused_bytes_size, tsi_handshaker_result **handshaker_result) { - if (wrapped == NULL || (unused_bytes_size > 0 && unused_bytes == NULL)) { + tsi_handshaker* wrapped, const unsigned char* unused_bytes, + size_t unused_bytes_size, tsi_handshaker_result** handshaker_result) { + if (wrapped == nullptr || + (unused_bytes_size > 0 && unused_bytes == nullptr)) { return TSI_INVALID_ARGUMENT; } - tsi_adapter_handshaker_result *impl = - (tsi_adapter_handshaker_result *)gpr_zalloc(sizeof(*impl)); + tsi_adapter_handshaker_result* impl = + (tsi_adapter_handshaker_result*)gpr_zalloc(sizeof(*impl)); impl->base.vtable = &result_vtable; impl->wrapped = wrapped; impl->unused_bytes_size = unused_bytes_size; if (unused_bytes_size > 0) { - impl->unused_bytes = (unsigned char *)gpr_malloc(unused_bytes_size); + impl->unused_bytes = (unsigned char*)gpr_malloc(unused_bytes_size); memcpy(impl->unused_bytes, unused_bytes, unused_bytes_size); } else { - impl->unused_bytes = NULL; + impl->unused_bytes = nullptr; } *handshaker_result = &impl->base; return TSI_OK; @@ -99,63 +100,63 @@ static tsi_result tsi_adapter_create_handshaker_result( typedef struct { tsi_handshaker base; - tsi_handshaker *wrapped; - unsigned char *adapter_buffer; + tsi_handshaker* wrapped; + unsigned char* adapter_buffer; size_t adapter_buffer_size; } tsi_adapter_handshaker; -static tsi_result adapter_get_bytes_to_send_to_peer(tsi_handshaker *self, - unsigned char *bytes, - size_t *bytes_size) { +static tsi_result adapter_get_bytes_to_send_to_peer(tsi_handshaker* self, + unsigned char* bytes, + size_t* bytes_size) { return tsi_handshaker_get_bytes_to_send_to_peer( tsi_adapter_handshaker_get_wrapped(self), bytes, bytes_size); } -static tsi_result adapter_process_bytes_from_peer(tsi_handshaker *self, - const unsigned char *bytes, - size_t *bytes_size) { +static tsi_result adapter_process_bytes_from_peer(tsi_handshaker* self, + const unsigned char* bytes, + size_t* bytes_size) { return tsi_handshaker_process_bytes_from_peer( tsi_adapter_handshaker_get_wrapped(self), bytes, bytes_size); } -static tsi_result adapter_get_result(tsi_handshaker *self) { +static tsi_result adapter_get_result(tsi_handshaker* self) { return tsi_handshaker_get_result(tsi_adapter_handshaker_get_wrapped(self)); } -static tsi_result adapter_extract_peer(tsi_handshaker *self, tsi_peer *peer) { +static tsi_result adapter_extract_peer(tsi_handshaker* self, tsi_peer* peer) { return tsi_handshaker_extract_peer(tsi_adapter_handshaker_get_wrapped(self), peer); } static tsi_result adapter_create_frame_protector( - tsi_handshaker *self, size_t *max_protected_frame_size, - tsi_frame_protector **protector) { + tsi_handshaker* self, size_t* max_protected_frame_size, + tsi_frame_protector** protector) { return tsi_handshaker_create_frame_protector( tsi_adapter_handshaker_get_wrapped(self), max_protected_frame_size, protector); } -static void adapter_destroy(tsi_handshaker *self) { - tsi_adapter_handshaker *impl = (tsi_adapter_handshaker *)self; +static void adapter_destroy(tsi_handshaker* self) { + tsi_adapter_handshaker* impl = (tsi_adapter_handshaker*)self; tsi_handshaker_destroy(impl->wrapped); gpr_free(impl->adapter_buffer); gpr_free(self); } static tsi_result adapter_next( - tsi_handshaker *self, const unsigned char *received_bytes, - size_t received_bytes_size, const unsigned char **bytes_to_send, - size_t *bytes_to_send_size, tsi_handshaker_result **handshaker_result, - tsi_handshaker_on_next_done_cb cb, void *user_data) { + tsi_handshaker* self, const unsigned char* received_bytes, + size_t received_bytes_size, const unsigned char** bytes_to_send, + size_t* bytes_to_send_size, tsi_handshaker_result** handshaker_result, + tsi_handshaker_on_next_done_cb cb, void* user_data) { /* Input sanity check. */ - if ((received_bytes_size > 0 && received_bytes == NULL) || - bytes_to_send == NULL || bytes_to_send_size == NULL || - handshaker_result == NULL) { + if ((received_bytes_size > 0 && received_bytes == nullptr) || + bytes_to_send == nullptr || bytes_to_send_size == nullptr || + handshaker_result == nullptr) { return TSI_INVALID_ARGUMENT; } /* If there are received bytes, process them first. */ - tsi_adapter_handshaker *impl = (tsi_adapter_handshaker *)self; + tsi_adapter_handshaker* impl = (tsi_adapter_handshaker*)self; tsi_result status = TSI_OK; size_t bytes_consumed = received_bytes_size; if (received_bytes_size > 0) { @@ -173,7 +174,7 @@ static tsi_result adapter_next( offset += to_send_size; if (status == TSI_INCOMPLETE_DATA) { impl->adapter_buffer_size *= 2; - impl->adapter_buffer = (unsigned char *)gpr_realloc( + impl->adapter_buffer = (unsigned char*)gpr_realloc( impl->adapter_buffer, impl->adapter_buffer_size); } } while (status == TSI_INCOMPLETE_DATA); @@ -183,16 +184,16 @@ static tsi_result adapter_next( /* If handshake completes, create tsi_handshaker_result. */ if (tsi_handshaker_is_in_progress(impl->wrapped)) { - *handshaker_result = NULL; + *handshaker_result = nullptr; } else { size_t unused_bytes_size = received_bytes_size - bytes_consumed; - const unsigned char *unused_bytes = - unused_bytes_size == 0 ? NULL : received_bytes + bytes_consumed; + const unsigned char* unused_bytes = + unused_bytes_size == 0 ? nullptr : received_bytes + bytes_consumed; status = tsi_adapter_create_handshaker_result( impl->wrapped, unused_bytes, unused_bytes_size, handshaker_result); if (status == TSI_OK) { impl->base.handshaker_result_created = true; - impl->wrapped = NULL; + impl->wrapped = nullptr; } } return status; @@ -208,19 +209,19 @@ static const tsi_handshaker_vtable handshaker_vtable = { adapter_next, }; -tsi_handshaker *tsi_create_adapter_handshaker(tsi_handshaker *wrapped) { - GPR_ASSERT(wrapped != NULL); - tsi_adapter_handshaker *impl = - (tsi_adapter_handshaker *)gpr_zalloc(sizeof(*impl)); +tsi_handshaker* tsi_create_adapter_handshaker(tsi_handshaker* wrapped) { + GPR_ASSERT(wrapped != nullptr); + tsi_adapter_handshaker* impl = + (tsi_adapter_handshaker*)gpr_zalloc(sizeof(*impl)); impl->base.vtable = &handshaker_vtable; impl->wrapped = wrapped; impl->adapter_buffer_size = TSI_ADAPTER_INITIAL_BUFFER_SIZE; - impl->adapter_buffer = (unsigned char *)gpr_malloc(impl->adapter_buffer_size); + impl->adapter_buffer = (unsigned char*)gpr_malloc(impl->adapter_buffer_size); return &impl->base; } -tsi_handshaker *tsi_adapter_handshaker_get_wrapped(tsi_handshaker *adapter) { - if (adapter == NULL) return NULL; - tsi_adapter_handshaker *impl = (tsi_adapter_handshaker *)adapter; +tsi_handshaker* tsi_adapter_handshaker_get_wrapped(tsi_handshaker* adapter) { + if (adapter == nullptr) return nullptr; + tsi_adapter_handshaker* impl = (tsi_adapter_handshaker*)adapter; return impl->wrapped; } diff --git a/src/core/tsi/transport_security_adapter.h b/src/core/tsi/transport_security_adapter.h index 02f33d4c1c2..9818fceb865 100644 --- a/src/core/tsi/transport_security_adapter.h +++ b/src/core/tsi/transport_security_adapter.h @@ -21,10 +21,6 @@ #include "src/core/tsi/transport_security_interface.h" -#ifdef __cplusplus -extern "C" { -#endif - /* Create a tsi handshaker that takes an implementation of old interface and converts into an implementation of new interface. In the old interface, there are get_bytes_to_send_to_peer, process_bytes_from_peer, get_result, @@ -33,15 +29,11 @@ extern "C" { this tsi adapter handshaker is temporary. It will be removed once TSI has been fully migrated to the new interface. Ownership of input tsi_handshaker is transferred to this new adapter. */ -tsi_handshaker *tsi_create_adapter_handshaker(tsi_handshaker *wrapped); +tsi_handshaker* tsi_create_adapter_handshaker(tsi_handshaker* wrapped); /* Given a tsi adapter handshaker, return the original wrapped handshaker. The adapter still owns the wrapped handshaker which should not be destroyed by the caller. */ -tsi_handshaker *tsi_adapter_handshaker_get_wrapped(tsi_handshaker *adapter); - -#ifdef __cplusplus -} -#endif +tsi_handshaker* tsi_adapter_handshaker_get_wrapped(tsi_handshaker* adapter); #endif /* GRPC_CORE_TSI_TRANSPORT_SECURITY_ADAPTER_H */ diff --git a/src/core/tsi/transport_security_grpc.cc b/src/core/tsi/transport_security_grpc.cc index affd995230e..875d3672182 100644 --- a/src/core/tsi/transport_security_grpc.cc +++ b/src/core/tsi/transport_security_grpc.cc @@ -20,14 +20,14 @@ /* This method creates a tsi_zero_copy_grpc_protector object. */ tsi_result tsi_handshaker_result_create_zero_copy_grpc_protector( - grpc_exec_ctx *exec_ctx, const tsi_handshaker_result *self, - size_t *max_output_protected_frame_size, - tsi_zero_copy_grpc_protector **protector) { - if (exec_ctx == NULL || self == NULL || self->vtable == NULL || - protector == NULL) { + grpc_exec_ctx* exec_ctx, const tsi_handshaker_result* self, + size_t* max_output_protected_frame_size, + tsi_zero_copy_grpc_protector** protector) { + if (exec_ctx == nullptr || self == nullptr || self->vtable == nullptr || + protector == nullptr) { return TSI_INVALID_ARGUMENT; } - if (self->vtable->create_zero_copy_grpc_protector == NULL) { + if (self->vtable->create_zero_copy_grpc_protector == nullptr) { return TSI_UNIMPLEMENTED; } return self->vtable->create_zero_copy_grpc_protector( @@ -39,33 +39,33 @@ tsi_result tsi_handshaker_result_create_zero_copy_grpc_protector( Calls specific implementation after state/input validation. */ tsi_result tsi_zero_copy_grpc_protector_protect( - grpc_exec_ctx *exec_ctx, tsi_zero_copy_grpc_protector *self, - grpc_slice_buffer *unprotected_slices, - grpc_slice_buffer *protected_slices) { - if (exec_ctx == NULL || self == NULL || self->vtable == NULL || - unprotected_slices == NULL || protected_slices == NULL) { + grpc_exec_ctx* exec_ctx, tsi_zero_copy_grpc_protector* self, + grpc_slice_buffer* unprotected_slices, + grpc_slice_buffer* protected_slices) { + if (exec_ctx == nullptr || self == nullptr || self->vtable == nullptr || + unprotected_slices == nullptr || protected_slices == nullptr) { return TSI_INVALID_ARGUMENT; } - if (self->vtable->protect == NULL) return TSI_UNIMPLEMENTED; + if (self->vtable->protect == nullptr) return TSI_UNIMPLEMENTED; return self->vtable->protect(exec_ctx, self, unprotected_slices, protected_slices); } tsi_result tsi_zero_copy_grpc_protector_unprotect( - grpc_exec_ctx *exec_ctx, tsi_zero_copy_grpc_protector *self, - grpc_slice_buffer *protected_slices, - grpc_slice_buffer *unprotected_slices) { - if (exec_ctx == NULL || self == NULL || self->vtable == NULL || - protected_slices == NULL || unprotected_slices == NULL) { + grpc_exec_ctx* exec_ctx, tsi_zero_copy_grpc_protector* self, + grpc_slice_buffer* protected_slices, + grpc_slice_buffer* unprotected_slices) { + if (exec_ctx == nullptr || self == nullptr || self->vtable == nullptr || + protected_slices == nullptr || unprotected_slices == nullptr) { return TSI_INVALID_ARGUMENT; } - if (self->vtable->unprotect == NULL) return TSI_UNIMPLEMENTED; + if (self->vtable->unprotect == nullptr) return TSI_UNIMPLEMENTED; return self->vtable->unprotect(exec_ctx, self, protected_slices, unprotected_slices); } -void tsi_zero_copy_grpc_protector_destroy(grpc_exec_ctx *exec_ctx, - tsi_zero_copy_grpc_protector *self) { - if (self == NULL) return; +void tsi_zero_copy_grpc_protector_destroy(grpc_exec_ctx* exec_ctx, + tsi_zero_copy_grpc_protector* self) { + if (self == nullptr) return; self->vtable->destroy(exec_ctx, self); } diff --git a/src/core/tsi/transport_security_grpc.h b/src/core/tsi/transport_security_grpc.h index ca6755c12fa..9fccfd79dd7 100644 --- a/src/core/tsi/transport_security_grpc.h +++ b/src/core/tsi/transport_security_grpc.h @@ -22,17 +22,13 @@ #include #include "src/core/tsi/transport_security.h" -#ifdef __cplusplus -extern "C" { -#endif - /* This method creates a tsi_zero_copy_grpc_protector object. It return TSI_OK assuming there is no fatal error. The caller is responsible for destroying the protector. */ tsi_result tsi_handshaker_result_create_zero_copy_grpc_protector( - grpc_exec_ctx *exec_ctx, const tsi_handshaker_result *self, - size_t *max_output_protected_frame_size, - tsi_zero_copy_grpc_protector **protector); + grpc_exec_ctx* exec_ctx, const tsi_handshaker_result* self, + size_t* max_output_protected_frame_size, + tsi_zero_copy_grpc_protector** protector); /* -- tsi_zero_copy_grpc_protector object -- */ @@ -43,8 +39,8 @@ tsi_result tsi_handshaker_result_create_zero_copy_grpc_protector( - This method returns TSI_OK in case of success or a specific error code in case of failure. */ tsi_result tsi_zero_copy_grpc_protector_protect( - grpc_exec_ctx *exec_ctx, tsi_zero_copy_grpc_protector *self, - grpc_slice_buffer *unprotected_slices, grpc_slice_buffer *protected_slices); + grpc_exec_ctx* exec_ctx, tsi_zero_copy_grpc_protector* self, + grpc_slice_buffer* unprotected_slices, grpc_slice_buffer* protected_slices); /* Outputs unprotected bytes. - protected_slices is the bytes of protected frames. @@ -53,32 +49,28 @@ tsi_result tsi_zero_copy_grpc_protector_protect( there is not enough data to output in which case unprotected_slices has 0 bytes. */ tsi_result tsi_zero_copy_grpc_protector_unprotect( - grpc_exec_ctx *exec_ctx, tsi_zero_copy_grpc_protector *self, - grpc_slice_buffer *protected_slices, grpc_slice_buffer *unprotected_slices); + grpc_exec_ctx* exec_ctx, tsi_zero_copy_grpc_protector* self, + grpc_slice_buffer* protected_slices, grpc_slice_buffer* unprotected_slices); /* Destroys the tsi_zero_copy_grpc_protector object. */ -void tsi_zero_copy_grpc_protector_destroy(grpc_exec_ctx *exec_ctx, - tsi_zero_copy_grpc_protector *self); +void tsi_zero_copy_grpc_protector_destroy(grpc_exec_ctx* exec_ctx, + tsi_zero_copy_grpc_protector* self); /* Base for tsi_zero_copy_grpc_protector implementations. */ typedef struct { - tsi_result (*protect)(grpc_exec_ctx *exec_ctx, - tsi_zero_copy_grpc_protector *self, - grpc_slice_buffer *unprotected_slices, - grpc_slice_buffer *protected_slices); - tsi_result (*unprotect)(grpc_exec_ctx *exec_ctx, - tsi_zero_copy_grpc_protector *self, - grpc_slice_buffer *protected_slices, - grpc_slice_buffer *unprotected_slices); - void (*destroy)(grpc_exec_ctx *exec_ctx, tsi_zero_copy_grpc_protector *self); + tsi_result (*protect)(grpc_exec_ctx* exec_ctx, + tsi_zero_copy_grpc_protector* self, + grpc_slice_buffer* unprotected_slices, + grpc_slice_buffer* protected_slices); + tsi_result (*unprotect)(grpc_exec_ctx* exec_ctx, + tsi_zero_copy_grpc_protector* self, + grpc_slice_buffer* protected_slices, + grpc_slice_buffer* unprotected_slices); + void (*destroy)(grpc_exec_ctx* exec_ctx, tsi_zero_copy_grpc_protector* self); } tsi_zero_copy_grpc_protector_vtable; struct tsi_zero_copy_grpc_protector { - const tsi_zero_copy_grpc_protector_vtable *vtable; + const tsi_zero_copy_grpc_protector_vtable* vtable; }; -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_TSI_TRANSPORT_SECURITY_GRPC_H */ diff --git a/src/core/tsi/transport_security_interface.h b/src/core/tsi/transport_security_interface.h index 80c426bbdbe..e9255984638 100644 --- a/src/core/tsi/transport_security_interface.h +++ b/src/core/tsi/transport_security_interface.h @@ -24,10 +24,6 @@ #include "src/core/lib/debug/trace.h" -#ifdef __cplusplus -extern "C" { -#endif - /* --- tsi result --- */ typedef enum { @@ -56,11 +52,11 @@ typedef enum { TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY, } tsi_client_certificate_request_type; -const char *tsi_result_to_string(tsi_result result); +const char* tsi_result_to_string(tsi_result result); /* --- tsi tracing --- */ -extern grpc_tracer_flag tsi_tracing_enabled; +extern grpc_core::TraceFlag tsi_tracing_enabled; /* -- tsi_zero_copy_grpc_protector object -- @@ -131,11 +127,11 @@ typedef struct tsi_frame_protector tsi_frame_protector; if (result != TSI_OK) HandleError(result); ------------------------------------------------------------------------ */ -tsi_result tsi_frame_protector_protect(tsi_frame_protector *self, - const unsigned char *unprotected_bytes, - size_t *unprotected_bytes_size, - unsigned char *protected_output_frames, - size_t *protected_output_frames_size); +tsi_result tsi_frame_protector_protect(tsi_frame_protector* self, + const unsigned char* unprotected_bytes, + size_t* unprotected_bytes_size, + unsigned char* protected_output_frames, + size_t* protected_output_frames_size); /* Indicates that we need to flush the bytes buffered in the protector and get the resulting frame. @@ -146,8 +142,8 @@ tsi_result tsi_frame_protector_protect(tsi_frame_protector *self, - still_pending_bytes is an output parameter indicating the number of bytes that still need to be flushed from the protector.*/ tsi_result tsi_frame_protector_protect_flush( - tsi_frame_protector *self, unsigned char *protected_output_frames, - size_t *protected_output_frames_size, size_t *still_pending_size); + tsi_frame_protector* self, unsigned char* protected_output_frames, + size_t* protected_output_frames_size, size_t* still_pending_size); /* Outputs unprotected bytes. - protected_frames_bytes is an input only parameter and points to the @@ -172,12 +168,12 @@ tsi_result tsi_frame_protector_protect_flush( needs to be read before new protected data can be processed in which case protected_frames_size will be set to 0. */ tsi_result tsi_frame_protector_unprotect( - tsi_frame_protector *self, const unsigned char *protected_frames_bytes, - size_t *protected_frames_bytes_size, unsigned char *unprotected_bytes, - size_t *unprotected_bytes_size); + tsi_frame_protector* self, const unsigned char* protected_frames_bytes, + size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes, + size_t* unprotected_bytes_size); /* Destroys the tsi_frame_protector object. */ -void tsi_frame_protector_destroy(tsi_frame_protector *self); +void tsi_frame_protector_destroy(tsi_frame_protector* self); /* --- tsi_peer objects --- @@ -189,20 +185,20 @@ void tsi_frame_protector_destroy(tsi_frame_protector *self); /* Property values may contain NULL characters just like C++ strings. The length field gives the length of the string. */ typedef struct tsi_peer_property { - char *name; + char* name; struct { - char *data; + char* data; size_t length; } value; } tsi_peer_property; typedef struct { - tsi_peer_property *properties; + tsi_peer_property* properties; size_t property_count; } tsi_peer; /* Destructs the tsi_peer object. */ -void tsi_peer_destruct(tsi_peer *self); +void tsi_peer_destruct(tsi_peer* self); /* --- tsi_handshaker_result object --- @@ -215,27 +211,27 @@ typedef struct tsi_handshaker_result tsi_handshaker_result; /* This method extracts tsi peer. It returns TSI_OK assuming there is no fatal error. The caller is responsible for destructing the peer. */ -tsi_result tsi_handshaker_result_extract_peer(const tsi_handshaker_result *self, - tsi_peer *peer); +tsi_result tsi_handshaker_result_extract_peer(const tsi_handshaker_result* self, + tsi_peer* peer); /* This method creates a tsi_frame_protector object. It returns TSI_OK assuming there is no fatal error. The caller is responsible for destroying the protector. */ tsi_result tsi_handshaker_result_create_frame_protector( - const tsi_handshaker_result *self, size_t *max_output_protected_frame_size, - tsi_frame_protector **protector); + const tsi_handshaker_result* self, size_t* max_output_protected_frame_size, + tsi_frame_protector** protector); /* This method returns the unused bytes from the handshake. It returns TSI_OK assuming there is no fatal error. Ownership of the bytes is retained by the handshaker result. As a consequence, the caller must not free the bytes. */ tsi_result tsi_handshaker_result_get_unused_bytes( - const tsi_handshaker_result *self, const unsigned char **bytes, - size_t *byte_size); + const tsi_handshaker_result* self, const unsigned char** bytes, + size_t* byte_size); /* This method releases the tsi_handshaker_handshaker object. After this method is called, no other method can be called on the object. */ -void tsi_handshaker_result_destroy(tsi_handshaker_result *self); +void tsi_handshaker_result_destroy(tsi_handshaker_result* self); /* --- tsi_handshaker objects ---- @@ -346,9 +342,9 @@ typedef struct tsi_handshaker tsi_handshaker; needs to be called again to get all the bytes to send to the peer (there was more data to write than the specified bytes_size). In case of a fatal error in the handshake, another specific error code is returned. */ -tsi_result tsi_handshaker_get_bytes_to_send_to_peer(tsi_handshaker *self, - unsigned char *bytes, - size_t *bytes_size); +tsi_result tsi_handshaker_get_bytes_to_send_to_peer(tsi_handshaker* self, + unsigned char* bytes, + size_t* bytes_size); /* TO BE DEPRECATED SOON. Use tsi_handshaker_next instead. Processes bytes received from the peer. @@ -360,9 +356,9 @@ tsi_result tsi_handshaker_get_bytes_to_send_to_peer(tsi_handshaker *self, needs to be called again to complete the data needed for processing. In case of a fatal error in the handshake, another specific error code is returned. */ -tsi_result tsi_handshaker_process_bytes_from_peer(tsi_handshaker *self, - const unsigned char *bytes, - size_t *bytes_size); +tsi_result tsi_handshaker_process_bytes_from_peer(tsi_handshaker* self, + const unsigned char* bytes, + size_t* bytes_size); /* TO BE DEPRECATED SOON. Gets the result of the handshaker. @@ -370,7 +366,7 @@ tsi_result tsi_handshaker_process_bytes_from_peer(tsi_handshaker *self, errors. Returns TSI_HANDSHAKE_IN_PROGRESS if the handshaker is not done yet but no error has been encountered so far. Otherwise the handshaker failed with the returned error. */ -tsi_result tsi_handshaker_get_result(tsi_handshaker *self); +tsi_result tsi_handshaker_get_result(tsi_handshaker* self); /* TO BE DEPRECATED SOON. Returns 1 if the handshake is in progress, 0 otherwise. */ @@ -382,7 +378,7 @@ tsi_result tsi_handshaker_get_result(tsi_handshaker *self); tsi_handshaker_is_in_progress returns 1, it returns TSI_OK otherwise assuming the handshaker is not in a fatal error state. The caller is responsible for destructing the peer. */ -tsi_result tsi_handshaker_extract_peer(tsi_handshaker *self, tsi_peer *peer); +tsi_result tsi_handshaker_extract_peer(tsi_handshaker* self, tsi_peer* peer); /* TO BE DEPRECATED SOON. Use tsi_handshaker_result_create_frame_protector instead. @@ -403,8 +399,8 @@ tsi_result tsi_handshaker_extract_peer(tsi_handshaker *self, tsi_peer *peer); the handshaker is not in a fatal error state. The caller is responsible for destroying the protector. */ tsi_result tsi_handshaker_create_frame_protector( - tsi_handshaker *self, size_t *max_output_protected_frame_size, - tsi_frame_protector **protector); + tsi_handshaker* self, size_t* max_output_protected_frame_size, + tsi_frame_protector** protector); /* Callback function definition for tsi_handshaker_next. - status indicates the status of the next operation. @@ -414,8 +410,8 @@ tsi_result tsi_handshaker_create_frame_protector( - handshaker_result is the result of handshake when the handshake completes, is NULL otherwise. */ typedef void (*tsi_handshaker_on_next_done_cb)( - tsi_result status, void *user_data, const unsigned char *bytes_to_send, - size_t bytes_to_send_size, tsi_handshaker_result *handshaker_result); + tsi_result status, void* user_data, const unsigned char* bytes_to_send, + size_t bytes_to_send_size, tsi_handshaker_result* handshaker_result); /* Conduct a next step of the handshake. - received_bytes is the buffer containing the data received from the peer. @@ -437,14 +433,14 @@ typedef void (*tsi_handshaker_on_next_done_cb)( the caller should not free bytes_to_send, as the buffer is owned by the tsi_handshaker object. */ tsi_result tsi_handshaker_next( - tsi_handshaker *self, const unsigned char *received_bytes, - size_t received_bytes_size, const unsigned char **bytes_to_send, - size_t *bytes_to_send_size, tsi_handshaker_result **handshaker_result, - tsi_handshaker_on_next_done_cb cb, void *user_data); + tsi_handshaker* self, const unsigned char* received_bytes, + size_t received_bytes_size, const unsigned char** bytes_to_send, + size_t* bytes_to_send_size, tsi_handshaker_result** handshaker_result, + tsi_handshaker_on_next_done_cb cb, void* user_data); /* This method releases the tsi_handshaker object. After this method is called, no other method can be called on the object. */ -void tsi_handshaker_destroy(tsi_handshaker *self); +void tsi_handshaker_destroy(tsi_handshaker* self); /* This method initializes the necessary shared objects used for tsi implementation. */ @@ -453,8 +449,4 @@ void tsi_init(); /* This method destroys the shared objects created by tsi_init. */ void tsi_destroy(); -#ifdef __cplusplus -} -#endif - #endif /* GRPC_CORE_TSI_TRANSPORT_SECURITY_INTERFACE_H */ diff --git a/src/cpp/client/channel_cc.cc b/src/cpp/client/channel_cc.cc index 9df531066e2..08420817c87 100644 --- a/src/cpp/client/channel_cc.cc +++ b/src/cpp/client/channel_cc.cc @@ -61,11 +61,11 @@ namespace { grpc::string GetChannelInfoField(grpc_channel* channel, grpc_channel_info* channel_info, char*** channel_info_field) { - char* value = NULL; + char* value = nullptr; memset(channel_info, 0, sizeof(*channel_info)); *channel_info_field = &value; grpc_channel_get_info(channel, channel_info); - if (value == NULL) return ""; + if (value == nullptr) return ""; grpc::string result = value; gpr_free(value); return result; @@ -89,14 +89,14 @@ internal::Call Channel::CreateCall(const internal::RpcMethod& method, ClientContext* context, CompletionQueue* cq) { const bool kRegistered = method.channel_tag() && context->authority().empty(); - grpc_call* c_call = NULL; + grpc_call* c_call = nullptr; if (kRegistered) { c_call = grpc_channel_create_registered_call( c_channel_, context->propagate_from_call_, context->propagation_options_.c_bitmask(), cq->cq(), method.channel_tag(), context->raw_deadline(), nullptr); } else { - const char* host_str = NULL; + const char* host_str = nullptr; if (!context->authority().empty()) { host_str = context->authority_.c_str(); } else if (!host_.empty()) { @@ -134,7 +134,7 @@ void Channel::PerformOpsOnCall(internal::CallOpSetInterface* ops, void* Channel::RegisterMethod(const char* method) { return grpc_channel_register_call( - c_channel_, method, host_.empty() ? NULL : host_.c_str(), nullptr); + c_channel_, method, host_.empty() ? nullptr : host_.c_str(), nullptr); } grpc_connectivity_state Channel::GetState(bool try_to_connect) { @@ -171,10 +171,10 @@ bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed, gpr_timespec deadline) { CompletionQueue cq; bool ok = false; - void* tag = NULL; - NotifyOnStateChangeImpl(last_observed, deadline, &cq, NULL); + void* tag = nullptr; + NotifyOnStateChangeImpl(last_observed, deadline, &cq, nullptr); cq.Next(&tag, &ok); - GPR_ASSERT(tag == NULL); + GPR_ASSERT(tag == nullptr); return ok; } diff --git a/src/cpp/client/client_context.cc b/src/cpp/client/client_context.cc index 40e95f3c05d..dafa8081e99 100644 --- a/src/cpp/client/client_context.cc +++ b/src/cpp/client/client_context.cc @@ -127,7 +127,7 @@ grpc::string ClientContext::peer() const { void ClientContext::SetGlobalCallbacks(GlobalCallbacks* client_callbacks) { GPR_ASSERT(g_client_callbacks == &g_default_client_callbacks); - GPR_ASSERT(client_callbacks != NULL); + GPR_ASSERT(client_callbacks != nullptr); GPR_ASSERT(client_callbacks != &g_default_client_callbacks); g_client_callbacks = client_callbacks; } diff --git a/src/cpp/client/create_channel.cc b/src/cpp/client/create_channel.cc index de67281dd45..93233153d08 100644 --- a/src/cpp/client/create_channel.cc +++ b/src/cpp/client/create_channel.cc @@ -39,11 +39,11 @@ std::shared_ptr CreateCustomChannel( const std::shared_ptr& creds, const ChannelArguments& args) { GrpcLibraryCodegen init_lib; // We need to call init in case of a bad creds. - return creds - ? creds->CreateChannel(target, args) - : CreateChannelInternal("", grpc_lame_client_channel_create( - NULL, GRPC_STATUS_INVALID_ARGUMENT, - "Invalid credentials.")); + return creds ? creds->CreateChannel(target, args) + : CreateChannelInternal( + "", grpc_lame_client_channel_create( + nullptr, GRPC_STATUS_INVALID_ARGUMENT, + "Invalid credentials.")); } } // namespace grpc diff --git a/src/cpp/client/generic_stub.cc b/src/cpp/client/generic_stub.cc index fc18ce90935..4b4b8dd427b 100644 --- a/src/cpp/client/generic_stub.cc +++ b/src/cpp/client/generic_stub.cc @@ -28,8 +28,9 @@ std::unique_ptr CallInternal( const grpc::string& method, CompletionQueue* cq, bool start, void* tag) { return std::unique_ptr( internal::ClientAsyncReaderWriterFactory::Create( - channel, cq, internal::RpcMethod(method.c_str(), - internal::RpcMethod::BIDI_STREAMING), + channel, cq, + internal::RpcMethod(method.c_str(), + internal::RpcMethod::BIDI_STREAMING), context, start, tag)); } diff --git a/src/cpp/client/secure_credentials.cc b/src/cpp/client/secure_credentials.cc index 13bbc3075df..4fb128d98b1 100644 --- a/src/cpp/client/secure_credentials.cc +++ b/src/cpp/client/secure_credentials.cc @@ -56,14 +56,16 @@ bool SecureCallCredentials::ApplyToCall(grpc_call* call) { namespace { std::shared_ptr WrapChannelCredentials( grpc_channel_credentials* creds) { - return creds == nullptr ? nullptr : std::shared_ptr( - new SecureChannelCredentials(creds)); + return creds == nullptr ? nullptr + : std::shared_ptr( + new SecureChannelCredentials(creds)); } std::shared_ptr WrapCallCredentials( grpc_call_credentials* creds) { - return creds == nullptr ? nullptr : std::shared_ptr( - new SecureCallCredentials(creds)); + return creds == nullptr ? nullptr + : std::shared_ptr( + new SecureCallCredentials(creds)); } } // namespace diff --git a/src/cpp/common/channel_arguments.cc b/src/cpp/common/channel_arguments.cc index f89f5f1f03d..cae9ef953ad 100644 --- a/src/cpp/common/channel_arguments.cc +++ b/src/cpp/common/channel_arguments.cc @@ -23,11 +23,10 @@ #include #include #include -extern "C" { #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/iomgr/socket_mutator.h" -} + namespace grpc { ChannelArguments::ChannelArguments() { diff --git a/src/cpp/common/channel_filter.cc b/src/cpp/common/channel_filter.cc index ea44cff832c..274079f8dd1 100644 --- a/src/cpp/common/channel_filter.cc +++ b/src/cpp/common/channel_filter.cc @@ -18,9 +18,7 @@ #include -extern "C" { #include "src/core/lib/channel/channel_stack.h" -} #include "src/cpp/common/channel_filter.h" #include @@ -29,10 +27,10 @@ namespace grpc { // MetadataBatch -grpc_linked_mdelem *MetadataBatch::AddMetadata(grpc_exec_ctx *exec_ctx, - const string &key, - const string &value) { - grpc_linked_mdelem *storage = new grpc_linked_mdelem; +grpc_linked_mdelem* MetadataBatch::AddMetadata(grpc_exec_ctx* exec_ctx, + const string& key, + const string& value) { + grpc_linked_mdelem* storage = new grpc_linked_mdelem; memset(storage, 0, sizeof(grpc_linked_mdelem)); storage->md = grpc_mdelem_from_slices(exec_ctx, SliceFromCopiedString(key), SliceFromCopiedString(value)); @@ -43,28 +41,28 @@ grpc_linked_mdelem *MetadataBatch::AddMetadata(grpc_exec_ctx *exec_ctx, // ChannelData -void ChannelData::StartTransportOp(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - TransportOp *op) { +void ChannelData::StartTransportOp(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + TransportOp* op) { grpc_channel_next_op(exec_ctx, elem, op->op()); } -void ChannelData::GetInfo(grpc_exec_ctx *exec_ctx, grpc_channel_element *elem, - const grpc_channel_info *channel_info) { +void ChannelData::GetInfo(grpc_exec_ctx* exec_ctx, grpc_channel_element* elem, + const grpc_channel_info* channel_info) { grpc_channel_next_get_info(exec_ctx, elem, channel_info); } // CallData -void CallData::StartTransportStreamOpBatch(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - TransportStreamOpBatch *op) { +void CallData::StartTransportStreamOpBatch(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + TransportStreamOpBatch* op) { grpc_call_next_op(exec_ctx, elem, op->op()); } -void CallData::SetPollsetOrPollsetSet(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_polling_entity *pollent) { +void CallData::SetPollsetOrPollsetSet(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_polling_entity* pollent) { grpc_call_stack_ignore_set_pollset_or_pollset_set(exec_ctx, elem, pollent); } @@ -73,15 +71,15 @@ void CallData::SetPollsetOrPollsetSet(grpc_exec_ctx *exec_ctx, namespace internal { // Note: Implicitly initialized to nullptr due to static lifetime. -std::vector *channel_filters; +std::vector* channel_filters; namespace { -bool MaybeAddFilter(grpc_exec_ctx *exec_ctx, - grpc_channel_stack_builder *builder, void *arg) { - const FilterRecord &filter = *(FilterRecord *)arg; +bool MaybeAddFilter(grpc_exec_ctx* exec_ctx, + grpc_channel_stack_builder* builder, void* arg) { + const FilterRecord& filter = *(FilterRecord*)arg; if (filter.include_filter) { - const grpc_channel_args *args = + const grpc_channel_args* args = grpc_channel_stack_builder_get_channel_arguments(builder); if (!filter.include_filter(*args)) return true; } @@ -93,9 +91,9 @@ bool MaybeAddFilter(grpc_exec_ctx *exec_ctx, void ChannelFilterPluginInit() { for (size_t i = 0; i < channel_filters->size(); ++i) { - FilterRecord &filter = (*channel_filters)[i]; + FilterRecord& filter = (*channel_filters)[i]; grpc_channel_init_register_stage(filter.stack_type, filter.priority, - MaybeAddFilter, (void *)&filter); + MaybeAddFilter, (void*)&filter); } } diff --git a/src/cpp/common/channel_filter.h b/src/cpp/common/channel_filter.h index c1aeb3f7245..9fe9cf0aea4 100644 --- a/src/cpp/common/channel_filter.h +++ b/src/cpp/common/channel_filter.h @@ -26,11 +26,9 @@ #include #include -extern "C" { #include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/surface/channel_init.h" #include "src/core/lib/transport/metadata_batch.h" -} /// An interface to define filters. /// @@ -49,23 +47,23 @@ class MetadataBatch { /// Borrows a pointer to \a batch, but does NOT take ownership. /// The caller must ensure that \a batch continues to exist for as /// long as the MetadataBatch object does. - explicit MetadataBatch(grpc_metadata_batch *batch) : batch_(batch) {} + explicit MetadataBatch(grpc_metadata_batch* batch) : batch_(batch) {} - grpc_metadata_batch *batch() const { return batch_; } + grpc_metadata_batch* batch() const { return batch_; } /// Adds metadata and returns the newly allocated storage. /// The caller takes ownership of the result, which must exist for the /// lifetime of the gRPC call. - grpc_linked_mdelem *AddMetadata(grpc_exec_ctx *exec_ctx, const string &key, - const string &value); + grpc_linked_mdelem* AddMetadata(grpc_exec_ctx* exec_ctx, const string& key, + const string& value); class const_iterator : public std::iterator { public: - const grpc_mdelem &operator*() const { return elem_->md; } + const grpc_mdelem& operator*() const { return elem_->md; } const grpc_mdelem operator->() const { return elem_->md; } - const_iterator &operator++() { + const_iterator& operator++() { elem_ = elem_->next; return *this; } @@ -74,7 +72,7 @@ class MetadataBatch { operator++(); return tmp; } - const_iterator &operator--() { + const_iterator& operator--() { elem_ = elem_->prev; return *this; } @@ -84,25 +82,25 @@ class MetadataBatch { return tmp; } - bool operator==(const const_iterator &other) const { + bool operator==(const const_iterator& other) const { return elem_ == other.elem_; } - bool operator!=(const const_iterator &other) const { + bool operator!=(const const_iterator& other) const { return elem_ != other.elem_; } private: friend class MetadataBatch; - explicit const_iterator(grpc_linked_mdelem *elem) : elem_(elem) {} + explicit const_iterator(grpc_linked_mdelem* elem) : elem_(elem) {} - grpc_linked_mdelem *elem_; + grpc_linked_mdelem* elem_; }; const_iterator begin() const { return const_iterator(batch_->list.head); } const_iterator end() const { return const_iterator(nullptr); } private: - grpc_metadata_batch *batch_; // Not owned. + grpc_metadata_batch* batch_; // Not owned. }; /// A C++ wrapper for the \c grpc_transport_op struct. @@ -111,12 +109,12 @@ class TransportOp { /// Borrows a pointer to \a op, but does NOT take ownership. /// The caller must ensure that \a op continues to exist for as /// long as the TransportOp object does. - explicit TransportOp(grpc_transport_op *op) : op_(op) {} + explicit TransportOp(grpc_transport_op* op) : op_(op) {} - grpc_transport_op *op() const { return op_; } + grpc_transport_op* op() const { return op_; } // TODO(roth): Add a C++ wrapper for grpc_error? - grpc_error *disconnect_with_error() const { + grpc_error* disconnect_with_error() const { return op_->disconnect_with_error; } bool send_goaway() const { return op_->goaway_error != GRPC_ERROR_NONE; } @@ -124,7 +122,7 @@ class TransportOp { // TODO(roth): Add methods for additional fields as needed. private: - grpc_transport_op *op_; // Not owned. + grpc_transport_op* op_; // Not owned. }; /// A C++ wrapper for the \c grpc_transport_stream_op_batch struct. @@ -133,7 +131,7 @@ class TransportStreamOpBatch { /// Borrows a pointer to \a op, but does NOT take ownership. /// The caller must ensure that \a op continues to exist for as /// long as the TransportStreamOpBatch object does. - explicit TransportStreamOpBatch(grpc_transport_stream_op_batch *op) + explicit TransportStreamOpBatch(grpc_transport_stream_op_batch* op) : op_(op), send_initial_metadata_( op->send_initial_metadata @@ -152,64 +150,63 @@ class TransportStreamOpBatch { ? op->payload->recv_trailing_metadata.recv_trailing_metadata : nullptr) {} - grpc_transport_stream_op_batch *op() const { return op_; } + grpc_transport_stream_op_batch* op() const { return op_; } - grpc_closure *on_complete() const { return op_->on_complete; } - void set_on_complete(grpc_closure *closure) { op_->on_complete = closure; } + grpc_closure* on_complete() const { return op_->on_complete; } + void set_on_complete(grpc_closure* closure) { op_->on_complete = closure; } - MetadataBatch *send_initial_metadata() { + MetadataBatch* send_initial_metadata() { return op_->send_initial_metadata ? &send_initial_metadata_ : nullptr; } - MetadataBatch *send_trailing_metadata() { + MetadataBatch* send_trailing_metadata() { return op_->send_trailing_metadata ? &send_trailing_metadata_ : nullptr; } - MetadataBatch *recv_initial_metadata() { + MetadataBatch* recv_initial_metadata() { return op_->recv_initial_metadata ? &recv_initial_metadata_ : nullptr; } - MetadataBatch *recv_trailing_metadata() { + MetadataBatch* recv_trailing_metadata() { return op_->recv_trailing_metadata ? &recv_trailing_metadata_ : nullptr; } - uint32_t *send_initial_metadata_flags() const { - return op_->send_initial_metadata - ? &op_->payload->send_initial_metadata - .send_initial_metadata_flags - : nullptr; + uint32_t* send_initial_metadata_flags() const { + return op_->send_initial_metadata ? &op_->payload->send_initial_metadata + .send_initial_metadata_flags + : nullptr; } - grpc_closure *recv_initial_metadata_ready() const { + grpc_closure* recv_initial_metadata_ready() const { return op_->recv_initial_metadata ? op_->payload->recv_initial_metadata.recv_initial_metadata_ready : nullptr; } - void set_recv_initial_metadata_ready(grpc_closure *closure) { + void set_recv_initial_metadata_ready(grpc_closure* closure) { op_->payload->recv_initial_metadata.recv_initial_metadata_ready = closure; } - grpc_byte_stream *send_message() const { + grpc_byte_stream* send_message() const { return op_->send_message ? op_->payload->send_message.send_message : nullptr; } - void set_send_message(grpc_byte_stream *send_message) { + void set_send_message(grpc_byte_stream* send_message) { op_->send_message = true; op_->payload->send_message.send_message = send_message; } - grpc_byte_stream **recv_message() const { + grpc_byte_stream** recv_message() const { return op_->recv_message ? op_->payload->recv_message.recv_message : nullptr; } - void set_recv_message(grpc_byte_stream **recv_message) { + void set_recv_message(grpc_byte_stream** recv_message) { op_->recv_message = true; op_->payload->recv_message.recv_message = recv_message; } - census_context *get_census_context() const { - return (census_context *)op_->payload->context[GRPC_CONTEXT_TRACING].value; + census_context* get_census_context() const { + return (census_context*)op_->payload->context[GRPC_CONTEXT_TRACING].value; } private: - grpc_transport_stream_op_batch *op_; // Not owned. + grpc_transport_stream_op_batch* op_; // Not owned. MetadataBatch send_initial_metadata_; MetadataBatch send_trailing_metadata_; MetadataBatch recv_initial_metadata_; @@ -225,19 +222,19 @@ class ChannelData { // TODO(roth): Come up with a more C++-like API for the channel element. /// Initializes the channel data. - virtual grpc_error *Init(grpc_exec_ctx *exec_ctx, grpc_channel_element *elem, - grpc_channel_element_args *args) { + virtual grpc_error* Init(grpc_exec_ctx* exec_ctx, grpc_channel_element* elem, + grpc_channel_element_args* args) { return GRPC_ERROR_NONE; } // Called before destruction. - virtual void Destroy(grpc_exec_ctx *exec_ctx, grpc_channel_element *elem) {} + virtual void Destroy(grpc_exec_ctx* exec_ctx, grpc_channel_element* elem) {} - virtual void StartTransportOp(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, TransportOp *op); + virtual void StartTransportOp(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, TransportOp* op); - virtual void GetInfo(grpc_exec_ctx *exec_ctx, grpc_channel_element *elem, - const grpc_channel_info *channel_info); + virtual void GetInfo(grpc_exec_ctx* exec_ctx, grpc_channel_element* elem, + const grpc_channel_info* channel_info); }; /// Represents call data. @@ -249,25 +246,25 @@ class CallData { // TODO(roth): Come up with a more C++-like API for the call element. /// Initializes the call data. - virtual grpc_error *Init(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - const grpc_call_element_args *args) { + virtual grpc_error* Init(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + const grpc_call_element_args* args) { return GRPC_ERROR_NONE; } // Called before destruction. - virtual void Destroy(grpc_exec_ctx *exec_ctx, grpc_call_element *elem, - const grpc_call_final_info *final_info, - grpc_closure *then_call_closure) {} + virtual void Destroy(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, + const grpc_call_final_info* final_info, + grpc_closure* then_call_closure) {} /// Starts a new stream operation. - virtual void StartTransportStreamOpBatch(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - TransportStreamOpBatch *op); + virtual void StartTransportStreamOpBatch(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + TransportStreamOpBatch* op); /// Sets a pollset or pollset set. - virtual void SetPollsetOrPollsetSet(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_polling_entity *pollent); + virtual void SetPollsetOrPollsetSet(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_polling_entity* pollent); }; namespace internal { @@ -280,70 +277,70 @@ class ChannelFilter final { public: static const size_t channel_data_size = sizeof(ChannelDataType); - static grpc_error *InitChannelElement(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_channel_element_args *args) { + static grpc_error* InitChannelElement(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_channel_element_args* args) { // Construct the object in the already-allocated memory. - ChannelDataType *channel_data = new (elem->channel_data) ChannelDataType(); + ChannelDataType* channel_data = new (elem->channel_data) ChannelDataType(); return channel_data->Init(exec_ctx, elem, args); } - static void DestroyChannelElement(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem) { - ChannelDataType *channel_data = - reinterpret_cast(elem->channel_data); + static void DestroyChannelElement(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem) { + ChannelDataType* channel_data = + reinterpret_cast(elem->channel_data); channel_data->Destroy(exec_ctx, elem); channel_data->~ChannelDataType(); } - static void StartTransportOp(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - grpc_transport_op *op) { - ChannelDataType *channel_data = - reinterpret_cast(elem->channel_data); + static void StartTransportOp(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + grpc_transport_op* op) { + ChannelDataType* channel_data = + reinterpret_cast(elem->channel_data); TransportOp op_wrapper(op); channel_data->StartTransportOp(exec_ctx, elem, &op_wrapper); } - static void GetChannelInfo(grpc_exec_ctx *exec_ctx, - grpc_channel_element *elem, - const grpc_channel_info *channel_info) { - ChannelDataType *channel_data = - reinterpret_cast(elem->channel_data); + static void GetChannelInfo(grpc_exec_ctx* exec_ctx, + grpc_channel_element* elem, + const grpc_channel_info* channel_info) { + ChannelDataType* channel_data = + reinterpret_cast(elem->channel_data); channel_data->GetInfo(exec_ctx, elem, channel_info); } static const size_t call_data_size = sizeof(CallDataType); - static grpc_error *InitCallElement(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - const grpc_call_element_args *args) { + static grpc_error* InitCallElement(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + const grpc_call_element_args* args) { // Construct the object in the already-allocated memory. - CallDataType *call_data = new (elem->call_data) CallDataType(); + CallDataType* call_data = new (elem->call_data) CallDataType(); return call_data->Init(exec_ctx, elem, args); } - static void DestroyCallElement(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - const grpc_call_final_info *final_info, - grpc_closure *then_call_closure) { - CallDataType *call_data = reinterpret_cast(elem->call_data); + static void DestroyCallElement(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + const grpc_call_final_info* final_info, + grpc_closure* then_call_closure) { + CallDataType* call_data = reinterpret_cast(elem->call_data); call_data->Destroy(exec_ctx, elem, final_info, then_call_closure); call_data->~CallDataType(); } - static void StartTransportStreamOpBatch(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_transport_stream_op_batch *op) { - CallDataType *call_data = reinterpret_cast(elem->call_data); + static void StartTransportStreamOpBatch(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_transport_stream_op_batch* op) { + CallDataType* call_data = reinterpret_cast(elem->call_data); TransportStreamOpBatch op_wrapper(op); call_data->StartTransportStreamOpBatch(exec_ctx, elem, &op_wrapper); } - static void SetPollsetOrPollsetSet(grpc_exec_ctx *exec_ctx, - grpc_call_element *elem, - grpc_polling_entity *pollent) { - CallDataType *call_data = reinterpret_cast(elem->call_data); + static void SetPollsetOrPollsetSet(grpc_exec_ctx* exec_ctx, + grpc_call_element* elem, + grpc_polling_entity* pollent) { + CallDataType* call_data = reinterpret_cast(elem->call_data); call_data->SetPollsetOrPollsetSet(exec_ctx, elem, pollent); } }; @@ -351,10 +348,10 @@ class ChannelFilter final { struct FilterRecord { grpc_channel_stack_type stack_type; int priority; - std::function include_filter; + std::function include_filter; grpc_channel_filter filter; }; -extern std::vector *channel_filters; +extern std::vector* channel_filters; void ChannelFilterPluginInit(); void ChannelFilterPluginShutdown(); @@ -368,8 +365,8 @@ void ChannelFilterPluginShutdown(); /// value is nullptr, the filter will be added unconditionally. template void RegisterChannelFilter( - const char *name, grpc_channel_stack_type stack_type, int priority, - std::function include_filter) { + const char* name, grpc_channel_stack_type stack_type, int priority, + std::function include_filter) { // If we haven't been called before, initialize channel_filters and // call grpc_register_plugin(). if (internal::channel_filters == nullptr) { diff --git a/src/cpp/common/core_codegen.cc b/src/cpp/common/core_codegen.cc index 6ea5f1d3c76..936d6996b26 100644 --- a/src/cpp/common/core_codegen.cc +++ b/src/cpp/common/core_codegen.cc @@ -33,9 +33,7 @@ #include "src/core/lib/profiling/timers.h" -extern "C" { struct grpc_byte_buffer; -} namespace grpc { @@ -76,6 +74,9 @@ void* CoreCodegen::gpr_malloc(size_t size) { return ::gpr_malloc(size); } void CoreCodegen::gpr_free(void* p) { return ::gpr_free(p); } +void CoreCodegen::grpc_init() { ::grpc_init(); } +void CoreCodegen::grpc_shutdown() { ::grpc_shutdown(); } + void CoreCodegen::gpr_mu_init(gpr_mu* mu) { ::gpr_mu_init(mu); }; void CoreCodegen::gpr_mu_destroy(gpr_mu* mu) { ::gpr_mu_destroy(mu); } void CoreCodegen::gpr_mu_lock(gpr_mu* mu) { ::gpr_mu_lock(mu); } @@ -156,6 +157,10 @@ grpc_slice CoreCodegen::grpc_slice_split_head(grpc_slice* s, size_t split) { return ::grpc_slice_split_head(s, split); } +grpc_slice CoreCodegen::grpc_slice_sub(grpc_slice s, size_t begin, size_t end) { + return ::grpc_slice_sub(s, begin, end); +} + grpc_slice CoreCodegen::grpc_slice_from_static_buffer(const void* buffer, size_t length) { return ::grpc_slice_from_static_buffer(buffer, length); diff --git a/src/cpp/common/version_cc.cc b/src/cpp/common/version_cc.cc index 8049cbe0c90..7f01a66dcf0 100644 --- a/src/cpp/common/version_cc.cc +++ b/src/cpp/common/version_cc.cc @@ -22,5 +22,5 @@ #include namespace grpc { -grpc::string Version() { return "1.8.0-dev"; } -} +grpc::string Version() { return "1.9.0-dev"; } +} // namespace grpc diff --git a/src/cpp/ext/proto_server_reflection.cc b/src/cpp/ext/proto_server_reflection.cc index ac08ce5c76c..e6122115fe0 100644 --- a/src/cpp/ext/proto_server_reflection.cc +++ b/src/cpp/ext/proto_server_reflection.cc @@ -25,14 +25,14 @@ using grpc::Status; using grpc::StatusCode; -using grpc::reflection::v1alpha::ServerReflectionRequest; +using grpc::reflection::v1alpha::ErrorResponse; +using grpc::reflection::v1alpha::ExtensionNumberResponse; using grpc::reflection::v1alpha::ExtensionRequest; -using grpc::reflection::v1alpha::ServerReflectionResponse; +using grpc::reflection::v1alpha::FileDescriptorResponse; using grpc::reflection::v1alpha::ListServiceResponse; +using grpc::reflection::v1alpha::ServerReflectionRequest; +using grpc::reflection::v1alpha::ServerReflectionResponse; using grpc::reflection::v1alpha::ServiceResponse; -using grpc::reflection::v1alpha::ExtensionNumberResponse; -using grpc::reflection::v1alpha::ErrorResponse; -using grpc::reflection::v1alpha::FileDescriptorResponse; namespace grpc { diff --git a/src/cpp/server/channel_argument_option.cc b/src/cpp/server/channel_argument_option.cc index 0d3a0dc25b5..dcad2531d58 100644 --- a/src/cpp/server/channel_argument_option.cc +++ b/src/cpp/server/channel_argument_option.cc @@ -21,17 +21,17 @@ namespace grpc { std::unique_ptr MakeChannelArgumentOption( - const grpc::string &name, const grpc::string &value) { + const grpc::string& name, const grpc::string& value) { class StringOption final : public ServerBuilderOption { public: - StringOption(const grpc::string &name, const grpc::string &value) + StringOption(const grpc::string& name, const grpc::string& value) : name_(name), value_(value) {} - virtual void UpdateArguments(ChannelArguments *args) override { + virtual void UpdateArguments(ChannelArguments* args) override { args->SetString(name_, value_); } virtual void UpdatePlugins( - std::vector> *plugins) override {} + std::vector>* plugins) override {} private: const grpc::string name_; @@ -41,17 +41,17 @@ std::unique_ptr MakeChannelArgumentOption( } std::unique_ptr MakeChannelArgumentOption( - const grpc::string &name, int value) { + const grpc::string& name, int value) { class IntOption final : public ServerBuilderOption { public: - IntOption(const grpc::string &name, int value) + IntOption(const grpc::string& name, int value) : name_(name), value_(value) {} - virtual void UpdateArguments(ChannelArguments *args) override { + virtual void UpdateArguments(ChannelArguments* args) override { args->SetInt(name_, value_); } virtual void UpdatePlugins( - std::vector> *plugins) override {} + std::vector>* plugins) override {} private: const grpc::string name_; diff --git a/src/cpp/server/health/health_check_service.cc b/src/cpp/server/health/health_check_service.cc index 14c83e73c93..a34b533bb22 100644 --- a/src/cpp/server/health/health_check_service.cc +++ b/src/cpp/server/health/health_check_service.cc @@ -21,7 +21,7 @@ namespace grpc { namespace { bool g_grpc_default_health_check_service_enabled = false; -} // namesapce +} // namespace bool DefaultHealthCheckServiceEnabled() { return g_grpc_default_health_check_service_enabled; diff --git a/src/cpp/server/server_cc.cc b/src/cpp/server/server_cc.cc index 6480482774e..4f8f4e06fcc 100644 --- a/src/cpp/server/server_cc.cc +++ b/src/cpp/server/server_cc.cc @@ -76,7 +76,7 @@ class Server::UnimplementedAsyncRequest final public: UnimplementedAsyncRequest(Server* server, ServerCompletionQueue* cq) : GenericAsyncRequest(server, &server_context_, &generic_stream_, cq, cq, - NULL, false), + nullptr, false), server_(server), cq_(cq) {} diff --git a/src/cpp/server/server_context.cc b/src/cpp/server/server_context.cc index f2cb6363f5c..f0cbbdb86dd 100644 --- a/src/cpp/server/server_context.cc +++ b/src/cpp/server/server_context.cc @@ -90,7 +90,7 @@ void ServerContext::CompletionOp::FillOps(grpc_call* call, grpc_op* ops, ops->op = GRPC_OP_RECV_CLOSE_ON_SERVER; ops->data.recv_close_on_server.cancelled = &cancelled_; ops->flags = 0; - ops->reserved = NULL; + ops->reserved = nullptr; *nops = 1; } @@ -171,7 +171,7 @@ void ServerContext::AddTrailingMetadata(const grpc::string& key, void ServerContext::TryCancel() const { grpc_call_error err = grpc_call_cancel_with_status( - call_, GRPC_STATUS_CANCELLED, "Cancelled on the server side", NULL); + call_, GRPC_STATUS_CANCELLED, "Cancelled on the server side", nullptr); if (err != GRPC_CALL_OK) { gpr_log(GPR_ERROR, "TryCancel failed with: %d", err); } @@ -190,13 +190,13 @@ bool ServerContext::IsCancelled() const { void ServerContext::set_compression_algorithm( grpc_compression_algorithm algorithm) { - const char* algorithm_name = NULL; + const char* algorithm_name = nullptr; if (!grpc_compression_algorithm_name(algorithm, &algorithm_name)) { gpr_log(GPR_ERROR, "Name for compression algorithm '%d' unknown.", algorithm); abort(); } - GPR_ASSERT(algorithm_name != NULL); + GPR_ASSERT(algorithm_name != nullptr); AddInitialMetadata(GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY, algorithm_name); } diff --git a/src/cpp/server/server_posix.cc b/src/cpp/server/server_posix.cc index a3c58f777bd..d3ef5cb650e 100644 --- a/src/cpp/server/server_posix.cc +++ b/src/cpp/server/server_posix.cc @@ -25,7 +25,7 @@ namespace grpc { #ifdef GPR_SUPPORT_CHANNELS_FROM_FD void AddInsecureChannelFromFd(Server* server, int fd) { - grpc_server_add_insecure_channel_from_fd(server->c_server(), NULL, fd); + grpc_server_add_insecure_channel_from_fd(server->c_server(), nullptr, fd); } #endif // GPR_SUPPORT_CHANNELS_FROM_FD diff --git a/src/cpp/util/core_stats.h b/src/cpp/util/core_stats.h index 00e38bf2660..6366d7d06e7 100644 --- a/src/cpp/util/core_stats.h +++ b/src/cpp/util/core_stats.h @@ -21,9 +21,7 @@ #include "src/proto/grpc/core/stats.pb.h" -extern "C" { #include "src/core/lib/debug/stats.h" -} namespace grpc { diff --git a/src/cpp/util/time_cc.cc b/src/cpp/util/time_cc.cc index 1c658b0c15d..3b6e0759290 100644 --- a/src/cpp/util/time_cc.cc +++ b/src/cpp/util/time_cc.cc @@ -21,10 +21,10 @@ #include using std::chrono::duration_cast; +using std::chrono::high_resolution_clock; using std::chrono::nanoseconds; using std::chrono::seconds; using std::chrono::system_clock; -using std::chrono::high_resolution_clock; namespace grpc { diff --git a/src/csharp/Grpc.Core.Tests/CallCancellationTest.cs b/src/csharp/Grpc.Core.Tests/CallCancellationTest.cs new file mode 100644 index 00000000000..e040f52380a --- /dev/null +++ b/src/csharp/Grpc.Core.Tests/CallCancellationTest.cs @@ -0,0 +1,182 @@ +#region Copyright notice and license + +// Copyright 2015 gRPC authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#endregion + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Grpc.Core; +using Grpc.Core.Internal; +using Grpc.Core.Profiling; +using Grpc.Core.Utils; +using NUnit.Framework; + +namespace Grpc.Core.Tests +{ + public class CallCancellationTest + { + const string Host = "127.0.0.1"; + + MockServiceHelper helper; + Server server; + Channel channel; + + [SetUp] + public void Init() + { + helper = new MockServiceHelper(Host); + server = helper.GetServer(); + server.Start(); + channel = helper.GetChannel(); + } + + [TearDown] + public void Cleanup() + { + channel.ShutdownAsync().Wait(); + server.ShutdownAsync().Wait(); + } + + [Test] + public async Task ClientStreamingCall_CancelAfterBegin() + { + var barrier = new TaskCompletionSource(); + + helper.ClientStreamingHandler = new ClientStreamingServerMethod(async (requestStream, context) => + { + barrier.SetResult(null); + await requestStream.ToListAsync(); + return ""; + }); + + var cts = new CancellationTokenSource(); + var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(cancellationToken: cts.Token))); + + await barrier.Task; // make sure the handler has started. + cts.Cancel(); + + try + { + // cannot use Assert.ThrowsAsync because it uses Task.Wait and would deadlock. + await call.ResponseAsync; + Assert.Fail(); + } + catch (RpcException ex) + { + Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); + } + } + + [Test] + public async Task ClientStreamingCall_ServerSideReadAfterCancelNotificationReturnsNull() + { + var handlerStartedBarrier = new TaskCompletionSource(); + var cancelNotificationReceivedBarrier = new TaskCompletionSource(); + var successTcs = new TaskCompletionSource(); + + helper.ClientStreamingHandler = new ClientStreamingServerMethod(async (requestStream, context) => + { + handlerStartedBarrier.SetResult(null); + + // wait for cancellation to be delivered. + context.CancellationToken.Register(() => cancelNotificationReceivedBarrier.SetResult(null)); + await cancelNotificationReceivedBarrier.Task; + + var moveNextResult = await requestStream.MoveNext(); + successTcs.SetResult(!moveNextResult ? "SUCCESS" : "FAIL"); + return ""; + }); + + var cts = new CancellationTokenSource(); + var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(cancellationToken: cts.Token))); + + await handlerStartedBarrier.Task; + cts.Cancel(); + + try + { + await call.ResponseAsync; + Assert.Fail(); + } + catch (RpcException ex) + { + Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); + } + Assert.AreEqual("SUCCESS", await successTcs.Task); + } + + [Test] + public async Task ClientStreamingCall_CancelServerSideRead() + { + helper.ClientStreamingHandler = new ClientStreamingServerMethod(async (requestStream, context) => + { + var cts = new CancellationTokenSource(); + var moveNextTask = requestStream.MoveNext(cts.Token); + cts.Cancel(); + await moveNextTask; + return ""; + }); + + var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall()); + try + { + // cannot use Assert.ThrowsAsync because it uses Task.Wait and would deadlock. + await call.ResponseAsync; + Assert.Fail(); + } + catch (RpcException ex) + { + Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); + } + } + + [Test] + public async Task ServerStreamingCall_CancelClientSideRead() + { + helper.ServerStreamingHandler = new ServerStreamingServerMethod(async (request, responseStream, context) => + { + await responseStream.WriteAsync("abc"); + while (!context.CancellationToken.IsCancellationRequested) + { + await Task.Delay(10); + } + }); + + var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), ""); + await call.ResponseStream.MoveNext(); + Assert.AreEqual("abc", call.ResponseStream.Current); + + var cts = new CancellationTokenSource(); + var moveNextTask = call.ResponseStream.MoveNext(cts.Token); + cts.Cancel(); + + try + { + // cannot use Assert.ThrowsAsync because it uses Task.Wait and would deadlock. + await moveNextTask; + Assert.Fail(); + } + catch (RpcException ex) + { + Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); + } + } + } +} diff --git a/src/csharp/Grpc.Core.Tests/ClientServerTest.cs b/src/csharp/Grpc.Core.Tests/ClientServerTest.cs index 72d9035a6ff..90dd365b07e 100644 --- a/src/csharp/Grpc.Core.Tests/ClientServerTest.cs +++ b/src/csharp/Grpc.Core.Tests/ClientServerTest.cs @@ -272,74 +272,6 @@ namespace Grpc.Core.Tests Assert.AreEqual("xyz-value", call.GetTrailers()[0].Value); } - [Test] - public async Task ClientStreamingCall_CancelAfterBegin() - { - var barrier = new TaskCompletionSource(); - - helper.ClientStreamingHandler = new ClientStreamingServerMethod(async (requestStream, context) => - { - barrier.SetResult(null); - await requestStream.ToListAsync(); - return ""; - }); - - var cts = new CancellationTokenSource(); - var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(cancellationToken: cts.Token))); - - await barrier.Task; // make sure the handler has started. - cts.Cancel(); - - try - { - // cannot use Assert.ThrowsAsync because it uses Task.Wait and would deadlock. - await call.ResponseAsync; - Assert.Fail(); - } - catch (RpcException ex) - { - Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); - } - } - - [Test] - public async Task ClientStreamingCall_ServerSideReadAfterCancelNotificationReturnsNull() - { - var handlerStartedBarrier = new TaskCompletionSource(); - var cancelNotificationReceivedBarrier = new TaskCompletionSource(); - var successTcs = new TaskCompletionSource(); - - helper.ClientStreamingHandler = new ClientStreamingServerMethod(async (requestStream, context) => - { - handlerStartedBarrier.SetResult(null); - - // wait for cancellation to be delivered. - context.CancellationToken.Register(() => cancelNotificationReceivedBarrier.SetResult(null)); - await cancelNotificationReceivedBarrier.Task; - - var moveNextResult = await requestStream.MoveNext(); - successTcs.SetResult(!moveNextResult ? "SUCCESS" : "FAIL"); - return ""; - }); - - var cts = new CancellationTokenSource(); - var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(cancellationToken: cts.Token))); - - await handlerStartedBarrier.Task; - cts.Cancel(); - - try - { - await call.ResponseAsync; - Assert.Fail(); - } - catch (RpcException ex) - { - Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); - } - Assert.AreEqual("SUCCESS", await successTcs.Task); - } - [Test] public async Task AsyncUnaryCall_EchoMetadata() { diff --git a/src/csharp/Grpc.Core.Tests/Internal/AsyncCallServerTest.cs b/src/csharp/Grpc.Core.Tests/Internal/AsyncCallServerTest.cs index 9488ce29e9d..e7d89399789 100644 --- a/src/csharp/Grpc.Core.Tests/Internal/AsyncCallServerTest.cs +++ b/src/csharp/Grpc.Core.Tests/Internal/AsyncCallServerTest.cs @@ -64,7 +64,7 @@ namespace Grpc.Core.Internal.Tests public void CancelNotificationAfterStartDisposes() { var finishedTask = asyncCallServer.ServerSideCallAsync(); - fakeCall.ReceivedCloseOnServerHandler(true, cancelled: true); + fakeCall.ReceivedCloseOnServerCallback.OnReceivedCloseOnServer(true, cancelled: true); AssertFinished(asyncCallServer, fakeCall, finishedTask); } @@ -76,8 +76,8 @@ namespace Grpc.Core.Internal.Tests var moveNextTask = requestStream.MoveNext(); - fakeCall.ReceivedCloseOnServerHandler(true, cancelled: true); - fakeCall.ReceivedMessageHandler(true, null); + fakeCall.ReceivedCloseOnServerCallback.OnReceivedCloseOnServer(true, cancelled: true); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(true, null); Assert.IsFalse(moveNextTask.Result); AssertFinished(asyncCallServer, fakeCall, finishedTask); @@ -89,7 +89,7 @@ namespace Grpc.Core.Internal.Tests var finishedTask = asyncCallServer.ServerSideCallAsync(); var requestStream = new ServerRequestStream(asyncCallServer); - fakeCall.ReceivedCloseOnServerHandler(true, cancelled: true); + fakeCall.ReceivedCloseOnServerCallback.OnReceivedCloseOnServer(true, cancelled: true); // Check that starting a read after cancel notification has been processed is legal. var moveNextTask = requestStream.MoveNext(); @@ -107,10 +107,10 @@ namespace Grpc.Core.Internal.Tests // if a read completion's success==false, the request stream will silently finish // and we rely on C core cancelling the call. var moveNextTask = requestStream.MoveNext(); - fakeCall.ReceivedMessageHandler(false, null); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(false, null); Assert.IsFalse(moveNextTask.Result); - fakeCall.ReceivedCloseOnServerHandler(true, cancelled: true); + fakeCall.ReceivedCloseOnServerCallback.OnReceivedCloseOnServer(true, cancelled: true); AssertFinished(asyncCallServer, fakeCall, finishedTask); } @@ -120,7 +120,7 @@ namespace Grpc.Core.Internal.Tests var finishedTask = asyncCallServer.ServerSideCallAsync(); var responseStream = new ServerResponseStream(asyncCallServer); - fakeCall.ReceivedCloseOnServerHandler(true, cancelled: true); + fakeCall.ReceivedCloseOnServerCallback.OnReceivedCloseOnServer(true, cancelled: true); // TODO(jtattermusch): should we throw a different exception type instead? Assert.Throws(typeof(InvalidOperationException), () => responseStream.WriteAsync("request1")); @@ -134,10 +134,10 @@ namespace Grpc.Core.Internal.Tests var responseStream = new ServerResponseStream(asyncCallServer); var writeTask = responseStream.WriteAsync("request1"); - fakeCall.SendCompletionHandler(false); + fakeCall.SendCompletionCallback.OnSendCompletion(false); Assert.ThrowsAsync(typeof(IOException), async () => await writeTask); - fakeCall.ReceivedCloseOnServerHandler(true, cancelled: true); + fakeCall.ReceivedCloseOnServerCallback.OnReceivedCloseOnServer(true, cancelled: true); AssertFinished(asyncCallServer, fakeCall, finishedTask); } @@ -150,13 +150,13 @@ namespace Grpc.Core.Internal.Tests var writeTask = responseStream.WriteAsync("request1"); var writeStatusTask = asyncCallServer.SendStatusFromServerAsync(Status.DefaultSuccess, new Metadata(), null); - fakeCall.SendCompletionHandler(true); - fakeCall.SendStatusFromServerHandler(true); + fakeCall.SendCompletionCallback.OnSendCompletion(true); + fakeCall.SendStatusFromServerCallback.OnSendStatusFromServerCompletion(true); Assert.DoesNotThrowAsync(async () => await writeTask); Assert.DoesNotThrowAsync(async () => await writeStatusTask); - fakeCall.ReceivedCloseOnServerHandler(true, cancelled: true); + fakeCall.ReceivedCloseOnServerCallback.OnReceivedCloseOnServer(true, cancelled: true); AssertFinished(asyncCallServer, fakeCall, finishedTask); } @@ -170,8 +170,8 @@ namespace Grpc.Core.Internal.Tests asyncCallServer.SendStatusFromServerAsync(Status.DefaultSuccess, new Metadata(), null); Assert.ThrowsAsync(typeof(InvalidOperationException), async () => await responseStream.WriteAsync("request1")); - fakeCall.SendStatusFromServerHandler(true); - fakeCall.ReceivedCloseOnServerHandler(true, cancelled: true); + fakeCall.SendStatusFromServerCallback.OnSendStatusFromServerCompletion(true); + fakeCall.ReceivedCloseOnServerCallback.OnReceivedCloseOnServer(true, cancelled: true); AssertFinished(asyncCallServer, fakeCall, finishedTask); } diff --git a/src/csharp/Grpc.Core.Tests/Internal/AsyncCallTest.cs b/src/csharp/Grpc.Core.Tests/Internal/AsyncCallTest.cs index b2b49f3a48d..9aab54d2d08 100644 --- a/src/csharp/Grpc.Core.Tests/Internal/AsyncCallTest.cs +++ b/src/csharp/Grpc.Core.Tests/Internal/AsyncCallTest.cs @@ -73,7 +73,7 @@ namespace Grpc.Core.Internal.Tests public void AsyncUnary_Success() { var resultTask = asyncCall.UnaryCallAsync("request1"); - fakeCall.UnaryResponseClientHandler(true, + fakeCall.UnaryResponseClientCallback.OnUnaryResponseClient(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()), CreateResponsePayload(), new Metadata()); @@ -85,7 +85,7 @@ namespace Grpc.Core.Internal.Tests public void AsyncUnary_NonSuccessStatusCode() { var resultTask = asyncCall.UnaryCallAsync("request1"); - fakeCall.UnaryResponseClientHandler(true, + fakeCall.UnaryResponseClientCallback.OnUnaryResponseClient(true, CreateClientSideStatus(StatusCode.InvalidArgument), null, new Metadata()); @@ -97,7 +97,7 @@ namespace Grpc.Core.Internal.Tests public void AsyncUnary_NullResponsePayload() { var resultTask = asyncCall.UnaryCallAsync("request1"); - fakeCall.UnaryResponseClientHandler(true, + fakeCall.UnaryResponseClientCallback.OnUnaryResponseClient(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()), null, new Metadata()); @@ -118,7 +118,7 @@ namespace Grpc.Core.Internal.Tests public void ClientStreaming_NoRequest_Success() { var resultTask = asyncCall.ClientStreamingCallAsync(); - fakeCall.UnaryResponseClientHandler(true, + fakeCall.UnaryResponseClientCallback.OnUnaryResponseClient(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()), CreateResponsePayload(), new Metadata()); @@ -130,7 +130,7 @@ namespace Grpc.Core.Internal.Tests public void ClientStreaming_NoRequest_NonSuccessStatusCode() { var resultTask = asyncCall.ClientStreamingCallAsync(); - fakeCall.UnaryResponseClientHandler(true, + fakeCall.UnaryResponseClientCallback.OnUnaryResponseClient(true, CreateClientSideStatus(StatusCode.InvalidArgument), null, new Metadata()); @@ -145,18 +145,18 @@ namespace Grpc.Core.Internal.Tests var requestStream = new ClientRequestStream(asyncCall); var writeTask = requestStream.WriteAsync("request1"); - fakeCall.SendCompletionHandler(true); + fakeCall.SendCompletionCallback.OnSendCompletion(true); writeTask.Wait(); var writeTask2 = requestStream.WriteAsync("request2"); - fakeCall.SendCompletionHandler(true); + fakeCall.SendCompletionCallback.OnSendCompletion(true); writeTask2.Wait(); var completeTask = requestStream.CompleteAsync(); - fakeCall.SendCompletionHandler(true); + fakeCall.SendCompletionCallback.OnSendCompletion(true); completeTask.Wait(); - fakeCall.UnaryResponseClientHandler(true, + fakeCall.UnaryResponseClientCallback.OnUnaryResponseClient(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()), CreateResponsePayload(), new Metadata()); @@ -171,12 +171,12 @@ namespace Grpc.Core.Internal.Tests var requestStream = new ClientRequestStream(asyncCall); var writeTask = requestStream.WriteAsync("request1"); - fakeCall.SendCompletionHandler(false); + fakeCall.SendCompletionCallback.OnSendCompletion(false); // The write will wait for call to finish to receive the status code. Assert.IsFalse(writeTask.IsCompleted); - fakeCall.UnaryResponseClientHandler(true, + fakeCall.UnaryResponseClientCallback.OnUnaryResponseClient(true, CreateClientSideStatus(StatusCode.Internal), null, new Metadata()); @@ -195,12 +195,12 @@ namespace Grpc.Core.Internal.Tests var writeTask = requestStream.WriteAsync("request1"); - fakeCall.UnaryResponseClientHandler(true, + fakeCall.UnaryResponseClientCallback.OnUnaryResponseClient(true, CreateClientSideStatus(StatusCode.Internal), null, new Metadata()); - fakeCall.SendCompletionHandler(false); + fakeCall.SendCompletionCallback.OnSendCompletion(false); var ex = Assert.ThrowsAsync(async () => await writeTask); Assert.AreEqual(StatusCode.Internal, ex.Status.StatusCode); @@ -215,13 +215,13 @@ namespace Grpc.Core.Internal.Tests var requestStream = new ClientRequestStream(asyncCall); var writeTask = requestStream.WriteAsync("request1"); - fakeCall.SendCompletionHandler(false); + fakeCall.SendCompletionCallback.OnSendCompletion(false); // Until the delayed write completion has been triggered, // we still act as if there was an active write. Assert.Throws(typeof(InvalidOperationException), () => requestStream.WriteAsync("request2")); - fakeCall.UnaryResponseClientHandler(true, + fakeCall.UnaryResponseClientCallback.OnUnaryResponseClient(true, CreateClientSideStatus(StatusCode.Internal), null, new Metadata()); @@ -242,7 +242,7 @@ namespace Grpc.Core.Internal.Tests var resultTask = asyncCall.ClientStreamingCallAsync(); var requestStream = new ClientRequestStream(asyncCall); - fakeCall.UnaryResponseClientHandler(true, + fakeCall.UnaryResponseClientCallback.OnUnaryResponseClient(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()), CreateResponsePayload(), new Metadata()); @@ -260,7 +260,7 @@ namespace Grpc.Core.Internal.Tests var resultTask = asyncCall.ClientStreamingCallAsync(); var requestStream = new ClientRequestStream(asyncCall); - fakeCall.UnaryResponseClientHandler(true, + fakeCall.UnaryResponseClientCallback.OnUnaryResponseClient(true, new ClientSideStatus(new Status(StatusCode.OutOfRange, ""), new Metadata()), CreateResponsePayload(), new Metadata()); @@ -282,9 +282,9 @@ namespace Grpc.Core.Internal.Tests Assert.Throws(typeof(InvalidOperationException), () => requestStream.WriteAsync("request1")); - fakeCall.SendCompletionHandler(true); + fakeCall.SendCompletionCallback.OnSendCompletion(true); - fakeCall.UnaryResponseClientHandler(true, + fakeCall.UnaryResponseClientCallback.OnUnaryResponseClient(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()), CreateResponsePayload(), new Metadata()); @@ -298,7 +298,7 @@ namespace Grpc.Core.Internal.Tests var resultTask = asyncCall.ClientStreamingCallAsync(); var requestStream = new ClientRequestStream(asyncCall); - fakeCall.UnaryResponseClientHandler(true, + fakeCall.UnaryResponseClientCallback.OnUnaryResponseClient(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()), CreateResponsePayload(), new Metadata()); @@ -319,7 +319,7 @@ namespace Grpc.Core.Internal.Tests var writeTask = requestStream.WriteAsync("request1"); Assert.ThrowsAsync(typeof(TaskCanceledException), async () => await writeTask); - fakeCall.UnaryResponseClientHandler(true, + fakeCall.UnaryResponseClientCallback.OnUnaryResponseClient(true, CreateClientSideStatus(StatusCode.Cancelled), null, new Metadata()); @@ -342,11 +342,11 @@ namespace Grpc.Core.Internal.Tests var responseStream = new ClientResponseStream(asyncCall); var readTask = responseStream.MoveNext(); - fakeCall.ReceivedResponseHeadersHandler(true, new Metadata()); + fakeCall.ReceivedResponseHeadersCallback.OnReceivedResponseHeaders(true, new Metadata()); Assert.AreEqual(0, asyncCall.ResponseHeadersAsync.Result.Count); - fakeCall.ReceivedMessageHandler(true, null); - fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata())); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(true, null); + fakeCall.ReceivedStatusOnClientCallback.OnReceivedStatusOnClient(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata())); AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask); } @@ -359,8 +359,8 @@ namespace Grpc.Core.Internal.Tests var readTask = responseStream.MoveNext(); // try alternative order of completions - fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata())); - fakeCall.ReceivedMessageHandler(true, null); + fakeCall.ReceivedStatusOnClientCallback.OnReceivedStatusOnClient(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata())); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(true, null); AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask); } @@ -372,8 +372,8 @@ namespace Grpc.Core.Internal.Tests var responseStream = new ClientResponseStream(asyncCall); var readTask = responseStream.MoveNext(); - fakeCall.ReceivedMessageHandler(false, null); // after a failed read, we rely on C core to deliver appropriate status code. - fakeCall.ReceivedStatusOnClientHandler(true, CreateClientSideStatus(StatusCode.Internal)); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(false, null); // after a failed read, we rely on C core to deliver appropriate status code. + fakeCall.ReceivedStatusOnClientCallback.OnReceivedStatusOnClient(true, CreateClientSideStatus(StatusCode.Internal)); AssertStreamingResponseError(asyncCall, fakeCall, readTask, StatusCode.Internal); } @@ -385,18 +385,18 @@ namespace Grpc.Core.Internal.Tests var responseStream = new ClientResponseStream(asyncCall); var readTask1 = responseStream.MoveNext(); - fakeCall.ReceivedMessageHandler(true, CreateResponsePayload()); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(true, CreateResponsePayload()); Assert.IsTrue(readTask1.Result); Assert.AreEqual("response1", responseStream.Current); var readTask2 = responseStream.MoveNext(); - fakeCall.ReceivedMessageHandler(true, CreateResponsePayload()); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(true, CreateResponsePayload()); Assert.IsTrue(readTask2.Result); Assert.AreEqual("response1", responseStream.Current); var readTask3 = responseStream.MoveNext(); - fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata())); - fakeCall.ReceivedMessageHandler(true, null); + fakeCall.ReceivedStatusOnClientCallback.OnReceivedStatusOnClient(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata())); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(true, null); AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask3); } @@ -409,12 +409,12 @@ namespace Grpc.Core.Internal.Tests var responseStream = new ClientResponseStream(asyncCall); var writeTask1 = requestStream.CompleteAsync(); - fakeCall.SendCompletionHandler(true); + fakeCall.SendCompletionCallback.OnSendCompletion(true); Assert.DoesNotThrowAsync(async () => await writeTask1); var readTask = responseStream.MoveNext(); - fakeCall.ReceivedMessageHandler(true, null); - fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata())); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(true, null); + fakeCall.ReceivedStatusOnClientCallback.OnReceivedStatusOnClient(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata())); AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask); } @@ -427,8 +427,8 @@ namespace Grpc.Core.Internal.Tests var responseStream = new ClientResponseStream(asyncCall); var readTask = responseStream.MoveNext(); - fakeCall.ReceivedMessageHandler(true, null); - fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata())); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(true, null); + fakeCall.ReceivedStatusOnClientCallback.OnReceivedStatusOnClient(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata())); AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask); @@ -445,8 +445,8 @@ namespace Grpc.Core.Internal.Tests var responseStream = new ClientResponseStream(asyncCall); var readTask = responseStream.MoveNext(); - fakeCall.ReceivedMessageHandler(true, null); - fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata())); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(true, null); + fakeCall.ReceivedStatusOnClientCallback.OnReceivedStatusOnClient(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata())); AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask); @@ -461,14 +461,14 @@ namespace Grpc.Core.Internal.Tests var responseStream = new ClientResponseStream(asyncCall); var writeTask = requestStream.WriteAsync("request1"); - fakeCall.SendCompletionHandler(false); + fakeCall.SendCompletionCallback.OnSendCompletion(false); // The write will wait for call to finish to receive the status code. Assert.IsFalse(writeTask.IsCompleted); var readTask = responseStream.MoveNext(); - fakeCall.ReceivedMessageHandler(true, null); - fakeCall.ReceivedStatusOnClientHandler(true, CreateClientSideStatus(StatusCode.PermissionDenied)); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(true, null); + fakeCall.ReceivedStatusOnClientCallback.OnReceivedStatusOnClient(true, CreateClientSideStatus(StatusCode.PermissionDenied)); var ex = Assert.ThrowsAsync(async () => await writeTask); Assert.AreEqual(StatusCode.PermissionDenied, ex.Status.StatusCode); @@ -486,9 +486,9 @@ namespace Grpc.Core.Internal.Tests var writeTask = requestStream.WriteAsync("request1"); var readTask = responseStream.MoveNext(); - fakeCall.ReceivedMessageHandler(true, null); - fakeCall.ReceivedStatusOnClientHandler(true, CreateClientSideStatus(StatusCode.PermissionDenied)); - fakeCall.SendCompletionHandler(false); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(true, null); + fakeCall.ReceivedStatusOnClientCallback.OnReceivedStatusOnClient(true, CreateClientSideStatus(StatusCode.PermissionDenied)); + fakeCall.SendCompletionCallback.OnSendCompletion(false); var ex = Assert.ThrowsAsync(async () => await writeTask); Assert.AreEqual(StatusCode.PermissionDenied, ex.Status.StatusCode); @@ -510,8 +510,8 @@ namespace Grpc.Core.Internal.Tests Assert.ThrowsAsync(typeof(TaskCanceledException), async () => await writeTask); var readTask = responseStream.MoveNext(); - fakeCall.ReceivedMessageHandler(true, null); - fakeCall.ReceivedStatusOnClientHandler(true, CreateClientSideStatus(StatusCode.Cancelled)); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(true, null); + fakeCall.ReceivedStatusOnClientCallback.OnReceivedStatusOnClient(true, CreateClientSideStatus(StatusCode.Cancelled)); AssertStreamingResponseError(asyncCall, fakeCall, readTask, StatusCode.Cancelled); } @@ -526,13 +526,13 @@ namespace Grpc.Core.Internal.Tests Assert.IsTrue(fakeCall.IsCancelled); var readTask1 = responseStream.MoveNext(); - fakeCall.ReceivedMessageHandler(true, CreateResponsePayload()); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(true, CreateResponsePayload()); Assert.IsTrue(readTask1.Result); Assert.AreEqual("response1", responseStream.Current); var readTask2 = responseStream.MoveNext(); - fakeCall.ReceivedMessageHandler(true, null); - fakeCall.ReceivedStatusOnClientHandler(true, CreateClientSideStatus(StatusCode.Cancelled)); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(true, null); + fakeCall.ReceivedStatusOnClientCallback.OnReceivedStatusOnClient(true, CreateClientSideStatus(StatusCode.Cancelled)); AssertStreamingResponseError(asyncCall, fakeCall, readTask2, StatusCode.Cancelled); } @@ -547,13 +547,13 @@ namespace Grpc.Core.Internal.Tests asyncCall.Cancel(); Assert.IsTrue(fakeCall.IsCancelled); - fakeCall.ReceivedMessageHandler(true, CreateResponsePayload()); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(true, CreateResponsePayload()); Assert.IsTrue(readTask1.Result); Assert.AreEqual("response1", responseStream.Current); var readTask2 = responseStream.MoveNext(); - fakeCall.ReceivedMessageHandler(true, null); - fakeCall.ReceivedStatusOnClientHandler(true, CreateClientSideStatus(StatusCode.Cancelled)); + fakeCall.ReceivedMessageCallback.OnReceivedMessage(true, null); + fakeCall.ReceivedStatusOnClientCallback.OnReceivedStatusOnClient(true, CreateClientSideStatus(StatusCode.Cancelled)); AssertStreamingResponseError(asyncCall, fakeCall, readTask2, StatusCode.Cancelled); } diff --git a/src/csharp/Grpc.Core.Tests/Internal/CompletionQueueSafeHandleTest.cs b/src/csharp/Grpc.Core.Tests/Internal/CompletionQueueSafeHandleTest.cs index 1d9475a8b8a..775c950c8ce 100644 --- a/src/csharp/Grpc.Core.Tests/Internal/CompletionQueueSafeHandleTest.cs +++ b/src/csharp/Grpc.Core.Tests/Internal/CompletionQueueSafeHandleTest.cs @@ -40,7 +40,7 @@ namespace Grpc.Core.Internal.Tests public void CreateAsyncAndShutdown() { var env = GrpcEnvironment.AddRef(); - var cq = CompletionQueueSafeHandle.CreateAsync(new CompletionRegistry(env)); + var cq = CompletionQueueSafeHandle.CreateAsync(new CompletionRegistry(env, () => BatchContextSafeHandle.Create())); cq.Shutdown(); var ev = cq.Next(); cq.Dispose(); diff --git a/src/csharp/Grpc.Core.Tests/Internal/DefaultObjectPoolTest.cs b/src/csharp/Grpc.Core.Tests/Internal/DefaultObjectPoolTest.cs new file mode 100644 index 00000000000..b6bb0a9eaeb --- /dev/null +++ b/src/csharp/Grpc.Core.Tests/Internal/DefaultObjectPoolTest.cs @@ -0,0 +1,79 @@ +#region Copyright notice and license + +// Copyright 2017 gRPC authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#endregion + +using System; +using Grpc.Core; +using Grpc.Core.Internal; +using Grpc.Core.Utils; +using NUnit.Framework; + +namespace Grpc.Core.Internal.Tests +{ + public class DefaultObjectPoolTest + { + [Test] + [TestCase(10, 2)] + [TestCase(10, 1)] + [TestCase(0, 2)] + [TestCase(2, 0)] + public void ObjectIsReused(int sharedCapacity, int threadLocalCapacity) + { + var pool = new DefaultObjectPool(() => new TestPooledObject(), sharedCapacity, threadLocalCapacity); + var origLeased = pool.Lease(); + pool.Return(origLeased); + Assert.AreSame(origLeased, pool.Lease()); + Assert.AreNotSame(origLeased, pool.Lease()); + } + + [Test] + public void ZeroCapacities() + { + var pool = new DefaultObjectPool(() => new TestPooledObject(), 0, 0); + var origLeased = pool.Lease(); + pool.Return(origLeased); + Assert.AreNotSame(origLeased, pool.Lease()); + } + + [Test] + public void DisposeCleansSharedPool() + { + var pool = new DefaultObjectPool(() => new TestPooledObject(), 10, 0); + var origLeased = pool.Lease(); + pool.Return(origLeased); + pool.Dispose(); + Assert.AreNotSame(origLeased, pool.Lease()); + } + + [Test] + public void Constructor() + { + Assert.Throws(() => new DefaultObjectPool(null, 10, 2)); + Assert.Throws(() => new DefaultObjectPool(() => new TestPooledObject(), -1, 10)); + Assert.Throws(() => new DefaultObjectPool(() => new TestPooledObject(), 10, -1)); + } + + class TestPooledObject : IDisposable + { + + public void Dispose() + { + + } + } + } +} diff --git a/src/csharp/Grpc.Core.Tests/Internal/FakeNativeCall.cs b/src/csharp/Grpc.Core.Tests/Internal/FakeNativeCall.cs index c3a27167f9f..581ac3384be 100644 --- a/src/csharp/Grpc.Core.Tests/Internal/FakeNativeCall.cs +++ b/src/csharp/Grpc.Core.Tests/Internal/FakeNativeCall.cs @@ -31,43 +31,43 @@ namespace Grpc.Core.Internal.Tests /// internal class FakeNativeCall : INativeCall { - public UnaryResponseClientHandler UnaryResponseClientHandler + public IUnaryResponseClientCallback UnaryResponseClientCallback { get; set; } - public ReceivedStatusOnClientHandler ReceivedStatusOnClientHandler + public IReceivedStatusOnClientCallback ReceivedStatusOnClientCallback { get; set; } - public ReceivedMessageHandler ReceivedMessageHandler + public IReceivedMessageCallback ReceivedMessageCallback { get; set; } - public ReceivedResponseHeadersHandler ReceivedResponseHeadersHandler + public IReceivedResponseHeadersCallback ReceivedResponseHeadersCallback { get; set; } - public SendCompletionHandler SendCompletionHandler + public ISendCompletionCallback SendCompletionCallback { get; set; } - public SendCompletionHandler SendStatusFromServerHandler + public ISendStatusFromServerCompletionCallback SendStatusFromServerCallback { get; set; } - public ReceivedCloseOnServerHandler ReceivedCloseOnServerHandler + public IReceivedCloseOnServerCallback ReceivedCloseOnServerCallback { get; set; @@ -100,9 +100,9 @@ namespace Grpc.Core.Internal.Tests return "PEER"; } - public void StartUnary(UnaryResponseClientHandler callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) + public void StartUnary(IUnaryResponseClientCallback callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { - UnaryResponseClientHandler = callback; + UnaryResponseClientCallback = callback; } public void StartUnary(BatchContextSafeHandle ctx, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) @@ -110,55 +110,55 @@ namespace Grpc.Core.Internal.Tests throw new NotImplementedException(); } - public void StartClientStreaming(UnaryResponseClientHandler callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags) + public void StartClientStreaming(IUnaryResponseClientCallback callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { - UnaryResponseClientHandler = callback; + UnaryResponseClientCallback = callback; } - public void StartServerStreaming(ReceivedStatusOnClientHandler callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) + public void StartServerStreaming(IReceivedStatusOnClientCallback callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { - ReceivedStatusOnClientHandler = callback; + ReceivedStatusOnClientCallback = callback; } - public void StartDuplexStreaming(ReceivedStatusOnClientHandler callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags) + public void StartDuplexStreaming(IReceivedStatusOnClientCallback callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { - ReceivedStatusOnClientHandler = callback; + ReceivedStatusOnClientCallback = callback; } - public void StartReceiveMessage(ReceivedMessageHandler callback) + public void StartReceiveMessage(IReceivedMessageCallback callback) { - ReceivedMessageHandler = callback; + ReceivedMessageCallback = callback; } - public void StartReceiveInitialMetadata(ReceivedResponseHeadersHandler callback) + public void StartReceiveInitialMetadata(IReceivedResponseHeadersCallback callback) { - ReceivedResponseHeadersHandler = callback; + ReceivedResponseHeadersCallback = callback; } - public void StartSendInitialMetadata(SendCompletionHandler callback, MetadataArraySafeHandle metadataArray) + public void StartSendInitialMetadata(ISendCompletionCallback callback, MetadataArraySafeHandle metadataArray) { - SendCompletionHandler = callback; + SendCompletionCallback = callback; } - public void StartSendMessage(SendCompletionHandler callback, byte[] payload, WriteFlags writeFlags, bool sendEmptyInitialMetadata) + public void StartSendMessage(ISendCompletionCallback callback, byte[] payload, WriteFlags writeFlags, bool sendEmptyInitialMetadata) { - SendCompletionHandler = callback; + SendCompletionCallback = callback; } - public void StartSendCloseFromClient(SendCompletionHandler callback) + public void StartSendCloseFromClient(ISendCompletionCallback callback) { - SendCompletionHandler = callback; + SendCompletionCallback = callback; } - public void StartSendStatusFromServer(SendCompletionHandler callback, Status status, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata, + public void StartSendStatusFromServer(ISendStatusFromServerCompletionCallback callback, Status status, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata, byte[] optionalPayload, WriteFlags writeFlags) { - SendStatusFromServerHandler = callback; + SendStatusFromServerCallback = callback; } - public void StartServerSide(ReceivedCloseOnServerHandler callback) + public void StartServerSide(IReceivedCloseOnServerCallback callback) { - ReceivedCloseOnServerHandler = callback; + ReceivedCloseOnServerCallback = callback; } public void Dispose() diff --git a/src/csharp/Grpc.Core.Tests/PInvokeTest.cs b/src/csharp/Grpc.Core.Tests/PInvokeTest.cs index 7529c44c4e6..43f816bb1c6 100644 --- a/src/csharp/Grpc.Core.Tests/PInvokeTest.cs +++ b/src/csharp/Grpc.Core.Tests/PInvokeTest.cs @@ -63,7 +63,7 @@ namespace Grpc.Core.Tests [Ignore("Prevent running on Jenkins")] public void NativeCallbackBenchmark() { - OpCompletionDelegate handler = Handler; + NativeCallbackTestDelegate handler = Handler; counter = 0; BenchmarkUtil.RunBenchmark( @@ -91,7 +91,7 @@ namespace Grpc.Core.Tests 10000, 10000, () => { - Native.grpcsharp_test_callback(new OpCompletionDelegate(Handler)); + Native.grpcsharp_test_callback(new NativeCallbackTestDelegate(Handler)); }); Assert.AreNotEqual(0, counter); } diff --git a/src/csharp/Grpc.Core/Channel.cs b/src/csharp/Grpc.Core/Channel.cs index 18039206628..f9925a8a766 100644 --- a/src/csharp/Grpc.Core/Channel.cs +++ b/src/csharp/Grpc.Core/Channel.cs @@ -127,6 +127,20 @@ namespace Grpc.Core } } + // cached handler for watch connectivity state + static readonly BatchCompletionDelegate WatchConnectivityStateHandler = (success, ctx, state) => + { + var tcs = (TaskCompletionSource) state; + if (success) + { + tcs.SetResult(null); + } + else + { + tcs.SetCanceled(); + } + }; + /// /// Returned tasks completes once channel state has become different from /// given lastObservedState. @@ -138,18 +152,8 @@ namespace Grpc.Core "Shutdown is a terminal state. No further state changes can occur."); var tcs = new TaskCompletionSource(); var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture; - var handler = new BatchCompletionDelegate((success, ctx) => - { - if (success) - { - tcs.SetResult(null); - } - else - { - tcs.SetCanceled(); - } - }); - handle.WatchConnectivityState(lastObservedState, deadlineTimespec, completionQueue, handler); + // pass "tcs" as "state" for WatchConnectivityStateHandler. + handle.WatchConnectivityState(lastObservedState, deadlineTimespec, completionQueue, WatchConnectivityStateHandler, tcs); return tcs.Task; } diff --git a/src/csharp/Grpc.Core/GrpcEnvironment.cs b/src/csharp/Grpc.Core/GrpcEnvironment.cs index 80031cb7efe..2b1b5e32d74 100644 --- a/src/csharp/Grpc.Core/GrpcEnvironment.cs +++ b/src/csharp/Grpc.Core/GrpcEnvironment.cs @@ -33,6 +33,8 @@ namespace Grpc.Core public class GrpcEnvironment { const int MinDefaultThreadPoolSize = 4; + const int DefaultBatchContextPoolSharedCapacity = 10000; + const int DefaultBatchContextPoolThreadLocalCapacity = 64; static object staticLock = new object(); static GrpcEnvironment instance; @@ -40,11 +42,14 @@ namespace Grpc.Core static int? customThreadPoolSize; static int? customCompletionQueueCount; static bool inlineHandlers; + static int batchContextPoolSharedCapacity = DefaultBatchContextPoolSharedCapacity; + static int batchContextPoolThreadLocalCapacity = DefaultBatchContextPoolThreadLocalCapacity; static readonly HashSet registeredChannels = new HashSet(); static readonly HashSet registeredServers = new HashSet(); static ILogger logger = new LogLevelFilterLogger(new ConsoleLogger(), LogLevel.Off, true); + readonly IObjectPool batchContextPool; readonly GrpcThreadPool threadPool; readonly DebugStats debugStats = new DebugStats(); readonly AtomicCounter cqPickerCounter = new AtomicCounter(); @@ -186,7 +191,7 @@ namespace Grpc.Core /// /// Sets the number of threads in the gRPC thread pool that polls for internal RPC events. - /// Can be only invoke before the GrpcEnviroment is started and cannot be changed afterwards. + /// Can be only invoked before the GrpcEnviroment is started and cannot be changed afterwards. /// Setting thread pool size is an advanced setting and you should only use it if you know what you are doing. /// Most users should rely on the default value provided by gRPC library. /// Note: this method is part of an experimental API that can change or be removed without any prior notice. @@ -203,7 +208,7 @@ namespace Grpc.Core /// /// Sets the number of completion queues in the gRPC thread pool that polls for internal RPC events. - /// Can be only invoke before the GrpcEnviroment is started and cannot be changed afterwards. + /// Can be only invoked before the GrpcEnviroment is started and cannot be changed afterwards. /// Setting the number of completions queues is an advanced setting and you should only use it if you know what you are doing. /// Most users should rely on the default value provided by gRPC library. /// Note: this method is part of an experimental API that can change or be removed without any prior notice. @@ -237,6 +242,26 @@ namespace Grpc.Core } } + /// + /// Sets the parameters for a pool that caches batch context instances. Reusing batch context instances + /// instead of creating a new one for every C core operation helps reducing the GC pressure. + /// Can be only invoked before the GrpcEnviroment is started and cannot be changed afterwards. + /// This is an advanced setting and you should only use it if you know what you are doing. + /// Most users should rely on the default value provided by gRPC library. + /// Note: this method is part of an experimental API that can change or be removed without any prior notice. + /// + public static void SetBatchContextPoolParams(int sharedCapacity, int threadLocalCapacity) + { + lock (staticLock) + { + GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized"); + GrpcPreconditions.CheckArgument(sharedCapacity >= 0, "Shared capacity needs to be a non-negative number"); + GrpcPreconditions.CheckArgument(threadLocalCapacity >= 0, "Thread local capacity needs to be a non-negative number"); + batchContextPoolSharedCapacity = sharedCapacity; + batchContextPoolThreadLocalCapacity = threadLocalCapacity; + } + } + /// /// Occurs when GrpcEnvironment is about the start the shutdown logic. /// If GrpcEnvironment is later initialized and shutdown, the event will be fired again (unless unregistered first). @@ -249,6 +274,7 @@ namespace Grpc.Core private GrpcEnvironment() { GrpcNativeInit(); + batchContextPool = new DefaultObjectPool(() => BatchContextSafeHandle.Create(this.batchContextPool), batchContextPoolSharedCapacity, batchContextPoolThreadLocalCapacity); threadPool = new GrpcThreadPool(this, GetThreadPoolSizeOrDefault(), GetCompletionQueueCountOrDefault(), inlineHandlers); threadPool.Start(); } @@ -264,6 +290,8 @@ namespace Grpc.Core } } + internal IObjectPool BatchContextPool => batchContextPool; + internal bool IsAlive { get @@ -325,6 +353,7 @@ namespace Grpc.Core await Task.Run(() => ShuttingDown?.Invoke(this, null)).ConfigureAwait(false); await threadPool.StopAsync().ConfigureAwait(false); + batchContextPool.Dispose(); GrpcNativeShutdown(); isShutdown = true; diff --git a/src/csharp/Grpc.Core/IAsyncStreamReader.cs b/src/csharp/Grpc.Core/IAsyncStreamReader.cs index 42bfbb87e01..3751d549e39 100644 --- a/src/csharp/Grpc.Core/IAsyncStreamReader.cs +++ b/src/csharp/Grpc.Core/IAsyncStreamReader.cs @@ -41,6 +41,13 @@ namespace Grpc.Core /// (MoveNext will return false) and the CancellationToken /// associated with the call will be cancelled to signal the failure. /// + /// + /// MoveNext() operations can be cancelled via a cancellation token. Cancelling + /// an individual read operation has the same effect as cancelling the entire call + /// (which will also result in the read operation returning prematurely), but the per-read cancellation + /// tokens passed to MoveNext() only result in cancelling the call if the read operation haven't finished + /// yet. + /// /// /// The message type. public interface IAsyncStreamReader : IAsyncEnumerator diff --git a/src/csharp/Grpc.Core/Internal/AsyncCall.cs b/src/csharp/Grpc.Core/Internal/AsyncCall.cs index 09fb722c816..9946d1a6cf9 100644 --- a/src/csharp/Grpc.Core/Internal/AsyncCall.cs +++ b/src/csharp/Grpc.Core/Internal/AsyncCall.cs @@ -27,7 +27,7 @@ namespace Grpc.Core.Internal /// /// Manages client side native call lifecycle. /// - internal class AsyncCall : AsyncCallBase + internal class AsyncCall : AsyncCallBase, IUnaryResponseClientCallback, IReceivedStatusOnClientCallback, IReceivedResponseHeadersCallback { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType>(); @@ -92,23 +92,28 @@ namespace Grpc.Core.Internal } using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) - using (var ctx = BatchContextSafeHandle.Create()) { - call.StartUnary(ctx, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); - - var ev = cq.Pluck(ctx.Handle); - - bool success = (ev.success != 0); + var ctx = details.Channel.Environment.BatchContextPool.Lease(); try { - using (profiler.NewScope("AsyncCall.UnaryCall.HandleBatch")) + call.StartUnary(ctx, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); + var ev = cq.Pluck(ctx.Handle); + bool success = (ev.success != 0); + try + { + using (profiler.NewScope("AsyncCall.UnaryCall.HandleBatch")) + { + HandleUnaryResponse(success, ctx.GetReceivedStatusOnClient(), ctx.GetReceivedMessage(), ctx.GetReceivedInitialMetadata()); + } + } + catch (Exception e) { - HandleUnaryResponse(success, ctx.GetReceivedStatusOnClient(), ctx.GetReceivedMessage(), ctx.GetReceivedInitialMetadata()); + Logger.Error(e, "Exception occured while invoking completion delegate."); } } - catch (Exception e) + finally { - Logger.Error(e, "Exception occured while invoking completion delegate."); + ctx.Recycle(); } } @@ -138,7 +143,7 @@ namespace Grpc.Core.Internal unaryResponseTcs = new TaskCompletionSource(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { - call.StartUnary(HandleUnaryResponse, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); + call.StartUnary(UnaryResponseClientCallback, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); } return unaryResponseTcs.Task; } @@ -162,7 +167,7 @@ namespace Grpc.Core.Internal unaryResponseTcs = new TaskCompletionSource(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { - call.StartClientStreaming(HandleUnaryResponse, metadataArray, details.Options.Flags); + call.StartClientStreaming(UnaryResponseClientCallback, metadataArray, details.Options.Flags); } return unaryResponseTcs.Task; @@ -188,9 +193,9 @@ namespace Grpc.Core.Internal streamingResponseCallFinishedTcs = new TaskCompletionSource(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { - call.StartServerStreaming(HandleFinished, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); + call.StartServerStreaming(ReceivedStatusOnClientCallback, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); } - call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders); + call.StartReceiveInitialMetadata(ReceivedResponseHeadersCallback); } } @@ -210,9 +215,9 @@ namespace Grpc.Core.Internal streamingResponseCallFinishedTcs = new TaskCompletionSource(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { - call.StartDuplexStreaming(HandleFinished, metadataArray, details.Options.Flags); + call.StartDuplexStreaming(ReceivedStatusOnClientCallback, metadataArray, details.Options.Flags); } - call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders); + call.StartReceiveInitialMetadata(ReceivedResponseHeadersCallback); } } @@ -256,7 +261,7 @@ namespace Grpc.Core.Internal halfcloseRequested = true; return TaskUtils.CompletedTask; } - call.StartSendCloseFromClient(HandleSendFinished); + call.StartSendCloseFromClient(SendCompletionCallback); halfcloseRequested = true; streamingWriteTcs = new TaskCompletionSource(); @@ -516,5 +521,26 @@ namespace Grpc.Core.Internal streamingResponseCallFinishedTcs.SetResult(null); } + + IUnaryResponseClientCallback UnaryResponseClientCallback => this; + + void IUnaryResponseClientCallback.OnUnaryResponseClient(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders) + { + HandleUnaryResponse(success, receivedStatus, receivedMessage, responseHeaders); + } + + IReceivedStatusOnClientCallback ReceivedStatusOnClientCallback => this; + + void IReceivedStatusOnClientCallback.OnReceivedStatusOnClient(bool success, ClientSideStatus receivedStatus) + { + HandleFinished(success, receivedStatus); + } + + IReceivedResponseHeadersCallback ReceivedResponseHeadersCallback => this; + + void IReceivedResponseHeadersCallback.OnReceivedResponseHeaders(bool success, Metadata responseHeaders) + { + HandleReceivedResponseHeaders(success, responseHeaders); + } } } diff --git a/src/csharp/Grpc.Core/Internal/AsyncCallBase.cs b/src/csharp/Grpc.Core/Internal/AsyncCallBase.cs index f379c85e00c..3273c26b88f 100644 --- a/src/csharp/Grpc.Core/Internal/AsyncCallBase.cs +++ b/src/csharp/Grpc.Core/Internal/AsyncCallBase.cs @@ -35,7 +35,7 @@ namespace Grpc.Core.Internal /// Base for handling both client side and server side calls. /// Manages native call lifecycle and provides convenience methods. /// - internal abstract class AsyncCallBase + internal abstract class AsyncCallBase : IReceivedMessageCallback, ISendCompletionCallback { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType>(); protected static readonly Status DeserializeResponseFailureStatus = new Status(StatusCode.Internal, "Failed to deserialize response message."); @@ -126,7 +126,7 @@ namespace Grpc.Core.Internal return earlyResult; } - call.StartSendMessage(HandleSendFinished, payload, writeFlags, !initialMetadataSent); + call.StartSendMessage(SendCompletionCallback, payload, writeFlags, !initialMetadataSent); initialMetadataSent = true; streamingWritesCounter++; @@ -154,7 +154,7 @@ namespace Grpc.Core.Internal GrpcPreconditions.CheckState(streamingReadTcs == null, "Only one read can be pending at a time"); GrpcPreconditions.CheckState(!disposed); - call.StartReceiveMessage(HandleReadFinished); + call.StartReceiveMessage(ReceivedMessageCallback); streamingReadTcs = new TaskCompletionSource(); return streamingReadTcs.Task; } @@ -342,5 +342,19 @@ namespace Grpc.Core.Internal } origTcs.SetResult(msg); } + + protected ISendCompletionCallback SendCompletionCallback => this; + + void ISendCompletionCallback.OnSendCompletion(bool success) + { + HandleSendFinished(success); + } + + IReceivedMessageCallback ReceivedMessageCallback => this; + + void IReceivedMessageCallback.OnReceivedMessage(bool success, byte[] receivedMessage) + { + HandleReadFinished(success, receivedMessage); + } } } diff --git a/src/csharp/Grpc.Core/Internal/AsyncCallServer.cs b/src/csharp/Grpc.Core/Internal/AsyncCallServer.cs index 271a6ffadfa..11acb275334 100644 --- a/src/csharp/Grpc.Core/Internal/AsyncCallServer.cs +++ b/src/csharp/Grpc.Core/Internal/AsyncCallServer.cs @@ -31,7 +31,7 @@ namespace Grpc.Core.Internal /// /// Manages server side native call lifecycle. /// - internal class AsyncCallServer : AsyncCallBase + internal class AsyncCallServer : AsyncCallBase, IReceivedCloseOnServerCallback, ISendStatusFromServerCompletionCallback { readonly TaskCompletionSource finishedServersideTcs = new TaskCompletionSource(); readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); @@ -70,7 +70,7 @@ namespace Grpc.Core.Internal started = true; - call.StartServerSide(HandleFinishedServerside); + call.StartServerSide(ReceiveCloseOnServerCallback); return finishedServersideTcs.Task; } } @@ -114,7 +114,7 @@ namespace Grpc.Core.Internal using (var metadataArray = MetadataArraySafeHandle.Create(headers)) { - call.StartSendInitialMetadata(HandleSendFinished, metadataArray); + call.StartSendInitialMetadata(SendCompletionCallback, metadataArray); } this.initialMetadataSent = true; @@ -127,10 +127,10 @@ namespace Grpc.Core.Internal /// Sends call result status, indicating we are done with writes. /// Sending a status different from StatusCode.OK will also implicitly cancel the call. /// - public Task SendStatusFromServerAsync(Status status, Metadata trailers, Tuple optionalWrite) + public Task SendStatusFromServerAsync(Status status, Metadata trailers, ResponseWithFlags? optionalWrite) { - byte[] payload = optionalWrite != null ? UnsafeSerialize(optionalWrite.Item1) : null; - var writeFlags = optionalWrite != null ? optionalWrite.Item2 : default(WriteFlags); + byte[] payload = optionalWrite.HasValue ? UnsafeSerialize(optionalWrite.Value.Response) : null; + var writeFlags = optionalWrite.HasValue ? optionalWrite.Value.WriteFlags : default(WriteFlags); lock (myLock) { @@ -140,13 +140,13 @@ namespace Grpc.Core.Internal using (var metadataArray = MetadataArraySafeHandle.Create(trailers)) { - call.StartSendStatusFromServer(HandleSendStatusFromServerFinished, status, metadataArray, !initialMetadataSent, + call.StartSendStatusFromServer(SendStatusFromServerCompletionCallback, status, metadataArray, !initialMetadataSent, payload, writeFlags); } halfcloseRequested = true; initialMetadataSent = true; sendStatusFromServerTcs = new TaskCompletionSource(); - if (optionalWrite != null) + if (optionalWrite.HasValue) { streamingWritesCounter++; } @@ -227,5 +227,31 @@ namespace Grpc.Core.Internal finishedServersideTcs.SetResult(null); } + + IReceivedCloseOnServerCallback ReceiveCloseOnServerCallback => this; + + void IReceivedCloseOnServerCallback.OnReceivedCloseOnServer(bool success, bool cancelled) + { + HandleFinishedServerside(success, cancelled); + } + + ISendStatusFromServerCompletionCallback SendStatusFromServerCompletionCallback => this; + + void ISendStatusFromServerCompletionCallback.OnSendStatusFromServerCompletion(bool success) + { + HandleSendStatusFromServerFinished(success); + } + + public struct ResponseWithFlags + { + public ResponseWithFlags(TResponse response, WriteFlags writeFlags) + { + this.Response = response; + this.WriteFlags = writeFlags; + } + + public TResponse Response { get; } + public WriteFlags WriteFlags { get; } + } } } diff --git a/src/csharp/Grpc.Core/Internal/BatchContextSafeHandle.cs b/src/csharp/Grpc.Core/Internal/BatchContextSafeHandle.cs index cd5e3d8911a..83385ad7d35 100644 --- a/src/csharp/Grpc.Core/Internal/BatchContextSafeHandle.cs +++ b/src/csharp/Grpc.Core/Internal/BatchContextSafeHandle.cs @@ -20,23 +20,36 @@ using System; using System.Runtime.InteropServices; using System.Text; using Grpc.Core; +using Grpc.Core.Logging; +using Grpc.Core.Utils; namespace Grpc.Core.Internal { + internal interface IOpCompletionCallback + { + void OnComplete(bool success); + } + /// /// grpcsharp_batch_context /// - internal class BatchContextSafeHandle : SafeHandleZeroIsInvalid + internal class BatchContextSafeHandle : SafeHandleZeroIsInvalid, IOpCompletionCallback { static readonly NativeMethods Native = NativeMethods.Get(); + static readonly ILogger Logger = GrpcEnvironment.Logger.ForType(); + + IObjectPool ownedByPool; + CompletionCallbackData completionCallbackData; private BatchContextSafeHandle() { } - public static BatchContextSafeHandle Create() + public static BatchContextSafeHandle Create(IObjectPool ownedByPool = null) { - return Native.grpcsharp_batch_context_create(); + var ctx = Native.grpcsharp_batch_context_create(); + ctx.ownedByPool = ownedByPool; + return ctx; } public IntPtr Handle @@ -47,19 +60,26 @@ namespace Grpc.Core.Internal } } + public void SetCompletionCallback(BatchCompletionDelegate callback, object state) + { + GrpcPreconditions.CheckState(completionCallbackData.Callback == null); + GrpcPreconditions.CheckNotNull(callback, nameof(callback)); + completionCallbackData = new CompletionCallbackData(callback, state); + } + // Gets data of recv_initial_metadata completion. public Metadata GetReceivedInitialMetadata() { IntPtr metadataArrayPtr = Native.grpcsharp_batch_context_recv_initial_metadata(this); return MetadataArraySafeHandle.ReadMetadataFromPtrUnsafe(metadataArrayPtr); } - + // Gets data of recv_status_on_client completion. public ClientSideStatus GetReceivedStatusOnClient() { UIntPtr detailsLength; IntPtr detailsPtr = Native.grpcsharp_batch_context_recv_status_on_client_details(this, out detailsLength); - string details = MarshalUtils.PtrToStringUTF8(detailsPtr, (int) detailsLength.ToUInt32()); + string details = MarshalUtils.PtrToStringUTF8(detailsPtr, (int)detailsLength.ToUInt32()); var status = new Status(Native.grpcsharp_batch_context_recv_status_on_client_status(this), details); IntPtr metadataArrayPtr = Native.grpcsharp_batch_context_recv_status_on_client_trailing_metadata(this); @@ -86,11 +106,53 @@ namespace Grpc.Core.Internal { return Native.grpcsharp_batch_context_recv_close_on_server_cancelled(this) != 0; } - + + public void Recycle() + { + if (ownedByPool != null) + { + Native.grpcsharp_batch_context_reset(this); + ownedByPool.Return(this); + } + else + { + Dispose(); + } + } + protected override bool ReleaseHandle() { Native.grpcsharp_batch_context_destroy(handle); return true; } + + void IOpCompletionCallback.OnComplete(bool success) + { + try + { + completionCallbackData.Callback(success, this, completionCallbackData.State); + } + catch (Exception e) + { + Logger.Error(e, "Exception occured while invoking batch completion delegate."); + } + finally + { + completionCallbackData = default(CompletionCallbackData); + Recycle(); + } + } + + struct CompletionCallbackData + { + public CompletionCallbackData(BatchCompletionDelegate callback, object state) + { + this.Callback = callback; + this.State = state; + } + + public BatchCompletionDelegate Callback { get; } + public object State { get; } + } } } diff --git a/src/csharp/Grpc.Core/Internal/CallSafeHandle.cs b/src/csharp/Grpc.Core/Internal/CallSafeHandle.cs index 3a7f97707b8..a3ef3e61ee1 100644 --- a/src/csharp/Grpc.Core/Internal/CallSafeHandle.cs +++ b/src/csharp/Grpc.Core/Internal/CallSafeHandle.cs @@ -32,6 +32,23 @@ namespace Grpc.Core.Internal public static readonly CallSafeHandle NullInstance = new CallSafeHandle(); static readonly NativeMethods Native = NativeMethods.Get(); + // Completion handlers are pre-allocated to avoid unneccessary delegate allocations. + // The "state" field is used to store the actual callback to invoke. + static readonly BatchCompletionDelegate CompletionHandler_IUnaryResponseClientCallback = + (success, context, state) => ((IUnaryResponseClientCallback)state).OnUnaryResponseClient(success, context.GetReceivedStatusOnClient(), context.GetReceivedMessage(), context.GetReceivedInitialMetadata()); + static readonly BatchCompletionDelegate CompletionHandler_IReceivedStatusOnClientCallback = + (success, context, state) => ((IReceivedStatusOnClientCallback)state).OnReceivedStatusOnClient(success, context.GetReceivedStatusOnClient()); + static readonly BatchCompletionDelegate CompletionHandler_IReceivedMessageCallback = + (success, context, state) => ((IReceivedMessageCallback)state).OnReceivedMessage(success, context.GetReceivedMessage()); + static readonly BatchCompletionDelegate CompletionHandler_IReceivedResponseHeadersCallback = + (success, context, state) => ((IReceivedResponseHeadersCallback)state).OnReceivedResponseHeaders(success, context.GetReceivedInitialMetadata()); + static readonly BatchCompletionDelegate CompletionHandler_ISendCompletionCallback = + (success, context, state) => ((ISendCompletionCallback)state).OnSendCompletion(success); + static readonly BatchCompletionDelegate CompletionHandler_ISendStatusFromServerCompletionCallback = + (success, context, state) => ((ISendStatusFromServerCompletionCallback)state).OnSendStatusFromServerCompletion(success); + static readonly BatchCompletionDelegate CompletionHandler_IReceivedCloseOnServerCallback = + (success, context, state) => ((IReceivedCloseOnServerCallback)state).OnReceivedCloseOnServer(success, context.GetReceivedCloseOnServerCancelled()); + const uint GRPC_WRITE_BUFFER_HINT = 1; CompletionQueueSafeHandle completionQueue; @@ -49,12 +66,11 @@ namespace Grpc.Core.Internal Native.grpcsharp_call_set_credentials(this, credentials).CheckOk(); } - public void StartUnary(UnaryResponseClientHandler callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) + public void StartUnary(IUnaryResponseClientCallback callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { using (completionQueue.NewScope()) { - var ctx = BatchContextSafeHandle.Create(); - completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient(), context.GetReceivedMessage(), context.GetReceivedInitialMetadata())); + var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IUnaryResponseClientCallback, callback); Native.grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), writeFlags, metadataArray, callFlags) .CheckOk(); } @@ -66,106 +82,96 @@ namespace Grpc.Core.Internal .CheckOk(); } - public void StartClientStreaming(UnaryResponseClientHandler callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags) + public void StartClientStreaming(IUnaryResponseClientCallback callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { using (completionQueue.NewScope()) { - var ctx = BatchContextSafeHandle.Create(); - completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient(), context.GetReceivedMessage(), context.GetReceivedInitialMetadata())); + var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IUnaryResponseClientCallback, callback); Native.grpcsharp_call_start_client_streaming(this, ctx, metadataArray, callFlags).CheckOk(); } } - public void StartServerStreaming(ReceivedStatusOnClientHandler callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) + public void StartServerStreaming(IReceivedStatusOnClientCallback callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { using (completionQueue.NewScope()) { - var ctx = BatchContextSafeHandle.Create(); - completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient())); + var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IReceivedStatusOnClientCallback, callback); Native.grpcsharp_call_start_server_streaming(this, ctx, payload, new UIntPtr((ulong)payload.Length), writeFlags, metadataArray, callFlags).CheckOk(); } } - public void StartDuplexStreaming(ReceivedStatusOnClientHandler callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags) + public void StartDuplexStreaming(IReceivedStatusOnClientCallback callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { using (completionQueue.NewScope()) { - var ctx = BatchContextSafeHandle.Create(); - completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient())); + var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IReceivedStatusOnClientCallback, callback); Native.grpcsharp_call_start_duplex_streaming(this, ctx, metadataArray, callFlags).CheckOk(); } } - public void StartSendMessage(SendCompletionHandler callback, byte[] payload, WriteFlags writeFlags, bool sendEmptyInitialMetadata) + public void StartSendMessage(ISendCompletionCallback callback, byte[] payload, WriteFlags writeFlags, bool sendEmptyInitialMetadata) { using (completionQueue.NewScope()) { - var ctx = BatchContextSafeHandle.Create(); - completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success)); + var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_ISendCompletionCallback, callback); Native.grpcsharp_call_send_message(this, ctx, payload, new UIntPtr((ulong)payload.Length), writeFlags, sendEmptyInitialMetadata ? 1 : 0).CheckOk(); } } - public void StartSendCloseFromClient(SendCompletionHandler callback) + public void StartSendCloseFromClient(ISendCompletionCallback callback) { using (completionQueue.NewScope()) { - var ctx = BatchContextSafeHandle.Create(); - completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success)); + var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_ISendCompletionCallback, callback); Native.grpcsharp_call_send_close_from_client(this, ctx).CheckOk(); } } - public void StartSendStatusFromServer(SendCompletionHandler callback, Status status, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata, + public void StartSendStatusFromServer(ISendStatusFromServerCompletionCallback callback, Status status, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata, byte[] optionalPayload, WriteFlags writeFlags) { using (completionQueue.NewScope()) { - var ctx = BatchContextSafeHandle.Create(); + var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_ISendStatusFromServerCompletionCallback, callback); var optionalPayloadLength = optionalPayload != null ? new UIntPtr((ulong)optionalPayload.Length) : UIntPtr.Zero; - completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success)); var statusDetailBytes = MarshalUtils.GetBytesUTF8(status.Detail); Native.grpcsharp_call_send_status_from_server(this, ctx, status.StatusCode, statusDetailBytes, new UIntPtr((ulong)statusDetailBytes.Length), metadataArray, sendEmptyInitialMetadata ? 1 : 0, optionalPayload, optionalPayloadLength, writeFlags).CheckOk(); } } - public void StartReceiveMessage(ReceivedMessageHandler callback) + public void StartReceiveMessage(IReceivedMessageCallback callback) { using (completionQueue.NewScope()) { - var ctx = BatchContextSafeHandle.Create(); - completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedMessage())); + var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IReceivedMessageCallback, callback); Native.grpcsharp_call_recv_message(this, ctx).CheckOk(); } } - public void StartReceiveInitialMetadata(ReceivedResponseHeadersHandler callback) + public void StartReceiveInitialMetadata(IReceivedResponseHeadersCallback callback) { using (completionQueue.NewScope()) { - var ctx = BatchContextSafeHandle.Create(); - completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedInitialMetadata())); + var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IReceivedResponseHeadersCallback, callback); Native.grpcsharp_call_recv_initial_metadata(this, ctx).CheckOk(); } } - public void StartServerSide(ReceivedCloseOnServerHandler callback) + public void StartServerSide(IReceivedCloseOnServerCallback callback) { using (completionQueue.NewScope()) { - var ctx = BatchContextSafeHandle.Create(); - completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedCloseOnServerCancelled())); + var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IReceivedCloseOnServerCallback, callback); Native.grpcsharp_call_start_serverside(this, ctx).CheckOk(); } } - public void StartSendInitialMetadata(SendCompletionHandler callback, MetadataArraySafeHandle metadataArray) + public void StartSendInitialMetadata(ISendCompletionCallback callback, MetadataArraySafeHandle metadataArray) { using (completionQueue.NewScope()) { - var ctx = BatchContextSafeHandle.Create(); - completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success)); + var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_ISendCompletionCallback, callback); Native.grpcsharp_call_send_initial_metadata(this, ctx, metadataArray).CheckOk(); } } diff --git a/src/csharp/Grpc.Core/Internal/ChannelSafeHandle.cs b/src/csharp/Grpc.Core/Internal/ChannelSafeHandle.cs index f826a17bad2..cd5f8ed92e6 100644 --- a/src/csharp/Grpc.Core/Internal/ChannelSafeHandle.cs +++ b/src/csharp/Grpc.Core/Internal/ChannelSafeHandle.cs @@ -64,10 +64,9 @@ namespace Grpc.Core.Internal return Native.grpcsharp_channel_check_connectivity_state(this, tryToConnect ? 1 : 0); } - public void WatchConnectivityState(ChannelState lastObservedState, Timespec deadline, CompletionQueueSafeHandle cq, BatchCompletionDelegate callback) + public void WatchConnectivityState(ChannelState lastObservedState, Timespec deadline, CompletionQueueSafeHandle cq, BatchCompletionDelegate callback, object callbackState) { - var ctx = BatchContextSafeHandle.Create(); - cq.CompletionRegistry.RegisterBatchCompletion(ctx, callback); + var ctx = cq.CompletionRegistry.RegisterBatchCompletion(callback, callbackState); Native.grpcsharp_channel_watch_connectivity_state(this, lastObservedState, deadline, cq, ctx); } diff --git a/src/csharp/Grpc.Core/Internal/ClientResponseStream.cs b/src/csharp/Grpc.Core/Internal/ClientResponseStream.cs index 851b6ca213c..ab649ee7662 100644 --- a/src/csharp/Grpc.Core/Internal/ClientResponseStream.cs +++ b/src/csharp/Grpc.Core/Internal/ClientResponseStream.cs @@ -49,19 +49,19 @@ namespace Grpc.Core.Internal public async Task MoveNext(CancellationToken token) { - if (token != CancellationToken.None) + var cancellationTokenRegistration = token.CanBeCanceled ? token.Register(() => call.Cancel()) : (IDisposable) null; + using (cancellationTokenRegistration) { - throw new InvalidOperationException("Cancellation of individual reads is not supported."); - } - var result = await call.ReadMessageAsync().ConfigureAwait(false); - this.current = result; + var result = await call.ReadMessageAsync().ConfigureAwait(false); + this.current = result; - if (result == null) - { - await call.StreamingResponseCallFinishedTask.ConfigureAwait(false); - return false; + if (result == null) + { + await call.StreamingResponseCallFinishedTask.ConfigureAwait(false); + return false; + } + return true; } - return true; } public void Dispose() diff --git a/src/csharp/Grpc.Core/Internal/CompletionRegistry.cs b/src/csharp/Grpc.Core/Internal/CompletionRegistry.cs index 3ce08e9a75c..cf3f3c0995a 100644 --- a/src/csharp/Grpc.Core/Internal/CompletionRegistry.cs +++ b/src/csharp/Grpc.Core/Internal/CompletionRegistry.cs @@ -19,15 +19,15 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Diagnostics; using System.Runtime.InteropServices; +using System.Threading; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core.Internal { - internal delegate void OpCompletionDelegate(bool success); - - internal delegate void BatchCompletionDelegate(bool success, BatchContextSafeHandle ctx); + internal delegate void BatchCompletionDelegate(bool success, BatchContextSafeHandle ctx, object state); internal delegate void RequestCallCompletionDelegate(bool success, RequestCallContextSafeHandle ctx); @@ -36,85 +36,74 @@ namespace Grpc.Core.Internal static readonly ILogger Logger = GrpcEnvironment.Logger.ForType(); readonly GrpcEnvironment environment; - readonly ConcurrentDictionary dict = new ConcurrentDictionary(new IntPtrComparer()); + readonly Func batchContextFactory; + readonly Dictionary dict = new Dictionary(new IntPtrComparer()); + SpinLock spinLock = new SpinLock(Debugger.IsAttached); IntPtr lastRegisteredKey; // only for testing - public CompletionRegistry(GrpcEnvironment environment) + public CompletionRegistry(GrpcEnvironment environment, Func batchContextFactory) { - this.environment = environment; + this.environment = GrpcPreconditions.CheckNotNull(environment); + this.batchContextFactory = GrpcPreconditions.CheckNotNull(batchContextFactory); } - public void Register(IntPtr key, OpCompletionDelegate callback) + public void Register(IntPtr key, IOpCompletionCallback callback) { environment.DebugStats.PendingBatchCompletions.Increment(); - GrpcPreconditions.CheckState(dict.TryAdd(key, callback)); - this.lastRegisteredKey = key; - } - public void RegisterBatchCompletion(BatchContextSafeHandle ctx, BatchCompletionDelegate callback) - { - OpCompletionDelegate opCallback = ((success) => HandleBatchCompletion(success, ctx, callback)); - Register(ctx.Handle, opCallback); - } + bool lockTaken = false; + try + { + spinLock.Enter(ref lockTaken); - public void RegisterRequestCallCompletion(RequestCallContextSafeHandle ctx, RequestCallCompletionDelegate callback) - { - OpCompletionDelegate opCallback = ((success) => HandleRequestCallCompletion(success, ctx, callback)); - Register(ctx.Handle, opCallback); + dict.Add(key, callback); + this.lastRegisteredKey = key; + } + finally + { + if (lockTaken) spinLock.Exit(); + } } - public OpCompletionDelegate Extract(IntPtr key) + public BatchContextSafeHandle RegisterBatchCompletion(BatchCompletionDelegate callback, object state) { - OpCompletionDelegate value; - GrpcPreconditions.CheckState(dict.TryRemove(key, out value)); - environment.DebugStats.PendingBatchCompletions.Decrement(); - return value; + var ctx = batchContextFactory(); + ctx.SetCompletionCallback(callback, state); + Register(ctx.Handle, ctx); + return ctx; } - /// - /// For testing purposes only. - /// - public IntPtr LastRegisteredKey + public void RegisterRequestCallCompletion(RequestCallContextSafeHandle ctx, RequestCallCompletionDelegate callback) { - get { return this.lastRegisteredKey; } + ctx.CompletionCallback = callback; + Register(ctx.Handle, ctx); } - private static void HandleBatchCompletion(bool success, BatchContextSafeHandle ctx, BatchCompletionDelegate callback) + public IOpCompletionCallback Extract(IntPtr key) { + IOpCompletionCallback value = null; + bool lockTaken = false; try { - callback(success, ctx); - } - catch (Exception e) - { - Logger.Error(e, "Exception occured while invoking batch completion delegate."); + spinLock.Enter(ref lockTaken); + + value = dict[key]; + dict.Remove(key); } finally { - if (ctx != null) - { - ctx.Dispose(); - } + if (lockTaken) spinLock.Exit(); } + environment.DebugStats.PendingBatchCompletions.Decrement(); + return value; } - private static void HandleRequestCallCompletion(bool success, RequestCallContextSafeHandle ctx, RequestCallCompletionDelegate callback) + /// + /// For testing purposes only. NOT threadsafe. + /// + public IntPtr LastRegisteredKey { - try - { - callback(success, ctx); - } - catch (Exception e) - { - Logger.Error(e, "Exception occured while invoking request call completion delegate."); - } - finally - { - if (ctx != null) - { - ctx.Dispose(); - } - } + get { return this.lastRegisteredKey; } } /// diff --git a/src/csharp/Grpc.Core/Internal/DefaultObjectPool.cs b/src/csharp/Grpc.Core/Internal/DefaultObjectPool.cs new file mode 100644 index 00000000000..2f030f3e026 --- /dev/null +++ b/src/csharp/Grpc.Core/Internal/DefaultObjectPool.cs @@ -0,0 +1,196 @@ +#region Copyright notice and license + +// Copyright 2017 gRPC authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#endregion + +using System; +using System.Threading; +using System.Collections.Generic; +using Grpc.Core.Utils; + +namespace Grpc.Core.Internal +{ + /// + /// Pool of objects that combines a shared pool and a thread local pool. + /// + internal class DefaultObjectPool : IObjectPool + where T : class, IDisposable + { + readonly object myLock = new object(); + readonly Func itemFactory; + + // Queue shared between threads, access needs to be synchronized. + readonly Queue sharedQueue; + readonly int sharedCapacity; + + readonly ThreadLocal threadLocalData; + readonly int threadLocalCapacity; + readonly int rentLimit; + + bool disposed; + + /// + /// Initializes a new instance of DefaultObjectPool with given shared capacity and thread local capacity. + /// Thread local capacity should be significantly smaller than the shared capacity as we don't guarantee immediately + /// disposing the objects in the thread local pool after this pool is disposed (they will eventually be garbage collected + /// after the thread that owns them has finished). + /// On average, the shared pool will only be accessed approx. once for every threadLocalCapacity / 2 rent or lease + /// operations. + /// + public DefaultObjectPool(Func itemFactory, int sharedCapacity, int threadLocalCapacity) + { + GrpcPreconditions.CheckArgument(sharedCapacity >= 0); + GrpcPreconditions.CheckArgument(threadLocalCapacity >= 0); + this.itemFactory = GrpcPreconditions.CheckNotNull(itemFactory, nameof(itemFactory)); + this.sharedQueue = new Queue(sharedCapacity); + this.sharedCapacity = sharedCapacity; + this.threadLocalData = new ThreadLocal(() => new ThreadLocalData(threadLocalCapacity), false); + this.threadLocalCapacity = threadLocalCapacity; + this.rentLimit = threadLocalCapacity != 1 ? threadLocalCapacity / 2 : 1; + } + + /// + /// Leases an item from the pool or creates a new instance if the pool is empty. + /// Attempts to retrieve the item from the thread local pool first. + /// If the thread local pool is empty, the item is taken from the shared pool + /// along with more items that are moved to the thread local pool to avoid + /// prevent acquiring the lock for shared pool too often. + /// The methods should not be called after the pool is disposed, but it won't + /// results in an error to do so (after depleting the items potentially left + /// in the thread local pool, it will continue returning new objects created by the factory). + /// + public T Lease() + { + var localData = threadLocalData.Value; + if (localData.Queue.Count > 0) + { + return localData.Queue.Dequeue(); + } + if (localData.CreateBudget > 0) + { + localData.CreateBudget --; + return itemFactory(); + } + + int itemsMoved = 0; + T leasedItem = null; + lock(myLock) + { + if (sharedQueue.Count > 0) + { + leasedItem = sharedQueue.Dequeue(); + } + while (sharedQueue.Count > 0 && itemsMoved < rentLimit) + { + localData.Queue.Enqueue(sharedQueue.Dequeue()); + itemsMoved ++; + } + } + + // If the shared pool didn't contain all rentLimit items, + // next time we try to lease we will just create those + // instead of trying to grab them from the shared queue. + // This is to guarantee we won't be accessing the shared queue too often. + localData.CreateBudget = rentLimit - itemsMoved; + + return leasedItem ?? itemFactory(); + } + + /// + /// Returns an item to the pool. + /// Attempts to add the item to the thread local pool first. + /// If the thread local pool is full, item is added to a shared pool, + /// along with half of the items for the thread local pool, which + /// should prevent acquiring the lock for shared pool too often. + /// If called after the pool is disposed, we make best effort not to + /// add anything to the thread local pool and we guarantee not to add + /// anything to the shared pool (items will be disposed instead). + /// + public void Return(T item) + { + GrpcPreconditions.CheckNotNull(item); + + var localData = threadLocalData.Value; + if (localData.Queue.Count < threadLocalCapacity && !disposed) + { + localData.Queue.Enqueue(item); + return; + } + if (localData.DisposeBudget > 0) + { + localData.DisposeBudget --; + item.Dispose(); + return; + } + + int itemsReturned = 0; + int returnLimit = rentLimit + 1; + lock (myLock) + { + if (sharedQueue.Count < sharedCapacity && !disposed) + { + sharedQueue.Enqueue(item); + itemsReturned ++; + } + while (sharedQueue.Count < sharedCapacity && itemsReturned < returnLimit && !disposed) + { + sharedQueue.Enqueue(localData.Queue.Dequeue()); + itemsReturned ++; + } + } + + // If the shared pool could not accomodate all returnLimit items, + // next time we try to return we will just dispose the item + // instead of trying to return them to the shared queue. + // This is to guarantee we won't be accessing the shared queue too often. + localData.DisposeBudget = returnLimit - itemsReturned; + + if (itemsReturned == 0) + { + localData.DisposeBudget --; + item.Dispose(); + } + } + + public void Dispose() + { + lock (myLock) + { + if (!disposed) + { + disposed = true; + + while (sharedQueue.Count > 0) + { + sharedQueue.Dequeue().Dispose(); + } + } + } + } + + class ThreadLocalData + { + public ThreadLocalData(int capacity) + { + this.Queue = new Queue(capacity); + } + + public Queue Queue { get; } + public int CreateBudget { get; set; } + public int DisposeBudget { get; set; } + } + } +} diff --git a/src/csharp/Grpc.Core/Internal/GrpcThreadPool.cs b/src/csharp/Grpc.Core/Internal/GrpcThreadPool.cs index 3c94b602c0d..f1b5a4f9ffd 100644 --- a/src/csharp/Grpc.Core/Internal/GrpcThreadPool.cs +++ b/src/csharp/Grpc.Core/Internal/GrpcThreadPool.cs @@ -68,8 +68,8 @@ namespace Grpc.Core.Internal GrpcPreconditions.CheckArgument(poolSize >= completionQueueCount, "Thread pool size cannot be smaller than the number of completion queues used."); - this.runCompletionQueueEventCallbackSuccess = new WaitCallback((callback) => RunCompletionQueueEventCallback((OpCompletionDelegate) callback, true)); - this.runCompletionQueueEventCallbackFailure = new WaitCallback((callback) => RunCompletionQueueEventCallback((OpCompletionDelegate) callback, false)); + this.runCompletionQueueEventCallbackSuccess = new WaitCallback((callback) => RunCompletionQueueEventCallback((IOpCompletionCallback) callback, true)); + this.runCompletionQueueEventCallbackFailure = new WaitCallback((callback) => RunCompletionQueueEventCallback((IOpCompletionCallback) callback, false)); } public void Start() @@ -176,10 +176,10 @@ namespace Grpc.Core.Internal try { var callback = cq.CompletionRegistry.Extract(tag); - // Use cached delegates to avoid unnecessary allocations + queuedContinuationCounter.Increment(); if (!inlineHandlers) { - queuedContinuationCounter.Increment(); + // Use cached delegates to avoid unnecessary allocations ThreadPool.QueueUserWorkItem(success ? runCompletionQueueEventCallbackSuccess : runCompletionQueueEventCallbackFailure, callback); } else @@ -219,17 +219,17 @@ namespace Grpc.Core.Internal var list = new List(); for (int i = 0; i < completionQueueCount; i++) { - var completionRegistry = new CompletionRegistry(environment); + var completionRegistry = new CompletionRegistry(environment, () => environment.BatchContextPool.Lease()); list.Add(CompletionQueueSafeHandle.CreateAsync(completionRegistry)); } return list.AsReadOnly(); } - private void RunCompletionQueueEventCallback(OpCompletionDelegate callback, bool success) + private void RunCompletionQueueEventCallback(IOpCompletionCallback callback, bool success) { try { - callback(success); + callback.OnComplete(success); } catch (Exception e) { diff --git a/src/csharp/Grpc.Core/Internal/INativeCall.cs b/src/csharp/Grpc.Core/Internal/INativeCall.cs index f9c06583c8b..5c35b2ba461 100644 --- a/src/csharp/Grpc.Core/Internal/INativeCall.cs +++ b/src/csharp/Grpc.Core/Internal/INativeCall.cs @@ -20,18 +20,41 @@ using Grpc.Core; namespace Grpc.Core.Internal { - internal delegate void UnaryResponseClientHandler(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders); + internal interface IUnaryResponseClientCallback + { + void OnUnaryResponseClient(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders); + } // Received status for streaming response calls. - internal delegate void ReceivedStatusOnClientHandler(bool success, ClientSideStatus receivedStatus); + internal interface IReceivedStatusOnClientCallback + { + void OnReceivedStatusOnClient(bool success, ClientSideStatus receivedStatus); + } - internal delegate void ReceivedMessageHandler(bool success, byte[] receivedMessage); + internal interface IReceivedMessageCallback + { + void OnReceivedMessage(bool success, byte[] receivedMessage); + } - internal delegate void ReceivedResponseHeadersHandler(bool success, Metadata responseHeaders); + internal interface IReceivedResponseHeadersCallback + { + void OnReceivedResponseHeaders(bool success, Metadata responseHeaders); + } - internal delegate void SendCompletionHandler(bool success); + internal interface ISendCompletionCallback + { + void OnSendCompletion(bool success); + } - internal delegate void ReceivedCloseOnServerHandler(bool success, bool cancelled); + internal interface ISendStatusFromServerCompletionCallback + { + void OnSendStatusFromServerCompletion(bool success); + } + + internal interface IReceivedCloseOnServerCallback + { + void OnReceivedCloseOnServer(bool success, bool cancelled); + } /// /// Abstraction of a native call object. @@ -44,28 +67,28 @@ namespace Grpc.Core.Internal string GetPeer(); - void StartUnary(UnaryResponseClientHandler callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags); + void StartUnary(IUnaryResponseClientCallback callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags); void StartUnary(BatchContextSafeHandle ctx, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags); - void StartClientStreaming(UnaryResponseClientHandler callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags); + void StartClientStreaming(IUnaryResponseClientCallback callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags); - void StartServerStreaming(ReceivedStatusOnClientHandler callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags); + void StartServerStreaming(IReceivedStatusOnClientCallback callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags); - void StartDuplexStreaming(ReceivedStatusOnClientHandler callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags); + void StartDuplexStreaming(IReceivedStatusOnClientCallback callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags); - void StartReceiveMessage(ReceivedMessageHandler callback); + void StartReceiveMessage(IReceivedMessageCallback callback); - void StartReceiveInitialMetadata(ReceivedResponseHeadersHandler callback); + void StartReceiveInitialMetadata(IReceivedResponseHeadersCallback callback); - void StartSendInitialMetadata(SendCompletionHandler callback, MetadataArraySafeHandle metadataArray); + void StartSendInitialMetadata(ISendCompletionCallback callback, MetadataArraySafeHandle metadataArray); - void StartSendMessage(SendCompletionHandler callback, byte[] payload, WriteFlags writeFlags, bool sendEmptyInitialMetadata); + void StartSendMessage(ISendCompletionCallback callback, byte[] payload, WriteFlags writeFlags, bool sendEmptyInitialMetadata); - void StartSendCloseFromClient(SendCompletionHandler callback); + void StartSendCloseFromClient(ISendCompletionCallback callback); - void StartSendStatusFromServer(SendCompletionHandler callback, Status status, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata, byte[] optionalPayload, WriteFlags writeFlags); + void StartSendStatusFromServer(ISendStatusFromServerCompletionCallback callback, Status status, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata, byte[] optionalPayload, WriteFlags writeFlags); - void StartServerSide(ReceivedCloseOnServerHandler callback); + void StartServerSide(IReceivedCloseOnServerCallback callback); } } diff --git a/src/node/test/test_service.proto b/src/csharp/Grpc.Core/Internal/IObjectPool.cs similarity index 58% rename from src/node/test/test_service.proto rename to src/csharp/Grpc.Core/Internal/IObjectPool.cs index b16dfecca71..f7d6e30a2ad 100644 --- a/src/node/test/test_service.proto +++ b/src/csharp/Grpc.Core/Internal/IObjectPool.cs @@ -1,4 +1,6 @@ -// Copyright 2015 gRPC authors. +#region Copyright notice and license + +// Copyright 2017 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,26 +14,22 @@ // See the License for the specific language governing permissions and // limitations under the License. -syntax = "proto3"; - -message Request { - bool error = 1; -} - -message Response { - int32 count = 1; -} - -service TestService { - rpc Unary (Request) returns (Response) { - } - - rpc ClientStream (stream Request) returns (Response) { - } +#endregion - rpc ServerStream (Request) returns (stream Response) { - } +using System; +using System.Threading; +using System.Collections.Generic; +using Grpc.Core.Utils; - rpc BidiStream (stream Request) returns (stream Response) { - } +namespace Grpc.Core.Internal +{ + /// + /// Pool of objects. + /// + internal interface IObjectPool : IDisposable + where T : class + { + T Lease(); + void Return(T item); + } } diff --git a/src/csharp/Grpc.Core/Internal/NativeMethods.cs b/src/csharp/Grpc.Core/Internal/NativeMethods.cs index 22faa19d9bf..43acb8f9156 100644 --- a/src/csharp/Grpc.Core/Internal/NativeMethods.cs +++ b/src/csharp/Grpc.Core/Internal/NativeMethods.cs @@ -29,6 +29,8 @@ using Grpc.Core.Utils; namespace Grpc.Core.Internal { + internal delegate void NativeCallbackTestDelegate(bool success); + /// /// Provides access to all native methods provided by NativeExtension. /// An extra level of indirection is added to P/Invoke calls to allow intelligent loading @@ -50,6 +52,7 @@ namespace Grpc.Core.Internal public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate grpcsharp_batch_context_recv_status_on_client_details; public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate grpcsharp_batch_context_recv_status_on_client_trailing_metadata; public readonly Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate grpcsharp_batch_context_recv_close_on_server_cancelled; + public readonly Delegates.grpcsharp_batch_context_reset_delegate grpcsharp_batch_context_reset; public readonly Delegates.grpcsharp_batch_context_destroy_delegate grpcsharp_batch_context_destroy; public readonly Delegates.grpcsharp_request_call_context_create_delegate grpcsharp_request_call_context_create; @@ -167,6 +170,7 @@ namespace Grpc.Core.Internal this.grpcsharp_batch_context_recv_status_on_client_details = GetMethodDelegate(library); this.grpcsharp_batch_context_recv_status_on_client_trailing_metadata = GetMethodDelegate(library); this.grpcsharp_batch_context_recv_close_on_server_cancelled = GetMethodDelegate(library); + this.grpcsharp_batch_context_reset = GetMethodDelegate(library); this.grpcsharp_batch_context_destroy = GetMethodDelegate(library); this.grpcsharp_request_call_context_create = GetMethodDelegate(library); @@ -309,6 +313,7 @@ namespace Grpc.Core.Internal public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_details_delegate(BatchContextSafeHandle ctx, out UIntPtr detailsLength); public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate(BatchContextSafeHandle ctx); public delegate int grpcsharp_batch_context_recv_close_on_server_cancelled_delegate(BatchContextSafeHandle ctx); + public delegate void grpcsharp_batch_context_reset_delegate(BatchContextSafeHandle ctx); public delegate void grpcsharp_batch_context_destroy_delegate(IntPtr ctx); public delegate RequestCallContextSafeHandle grpcsharp_request_call_context_create_delegate(); @@ -420,7 +425,7 @@ namespace Grpc.Core.Internal public delegate Timespec gprsharp_convert_clock_type_delegate(Timespec t, ClockType targetClock); public delegate int gprsharp_sizeof_timespec_delegate(); - public delegate CallError grpcsharp_test_callback_delegate([MarshalAs(UnmanagedType.FunctionPtr)] OpCompletionDelegate callback); + public delegate CallError grpcsharp_test_callback_delegate([MarshalAs(UnmanagedType.FunctionPtr)] NativeCallbackTestDelegate callback); public delegate IntPtr grpcsharp_test_nop_delegate(IntPtr ptr); public delegate void grpcsharp_test_override_method_delegate(string methodName, string variant); } diff --git a/src/csharp/Grpc.Core/Internal/RequestCallContextSafeHandle.cs b/src/csharp/Grpc.Core/Internal/RequestCallContextSafeHandle.cs index b7af0c102d2..09f5c3e4526 100644 --- a/src/csharp/Grpc.Core/Internal/RequestCallContextSafeHandle.cs +++ b/src/csharp/Grpc.Core/Internal/RequestCallContextSafeHandle.cs @@ -19,15 +19,17 @@ using System; using System.Runtime.InteropServices; using Grpc.Core; +using Grpc.Core.Logging; namespace Grpc.Core.Internal { /// /// grpcsharp_request_call_context /// - internal class RequestCallContextSafeHandle : SafeHandleZeroIsInvalid + internal class RequestCallContextSafeHandle : SafeHandleZeroIsInvalid, IOpCompletionCallback { static readonly NativeMethods Native = NativeMethods.Get(); + static readonly ILogger Logger = GrpcEnvironment.Logger.ForType(); private RequestCallContextSafeHandle() { @@ -46,6 +48,8 @@ namespace Grpc.Core.Internal } } + public RequestCallCompletionDelegate CompletionCallback { get; set; } + // Gets data of server_rpc_new completion. public ServerRpcNew GetServerRpcNew(Server server) { @@ -72,5 +76,22 @@ namespace Grpc.Core.Internal Native.grpcsharp_request_call_context_destroy(handle); return true; } + + void IOpCompletionCallback.OnComplete(bool success) + { + try + { + CompletionCallback(success, this); + } + catch (Exception e) + { + Logger.Error(e, "Exception occured while invoking request call completion delegate."); + } + finally + { + CompletionCallback = null; + Dispose(); + } + } } } diff --git a/src/csharp/Grpc.Core/Internal/ServerCallHandler.cs b/src/csharp/Grpc.Core/Internal/ServerCallHandler.cs index 6019f8e7934..98995a0862e 100644 --- a/src/csharp/Grpc.Core/Internal/ServerCallHandler.cs +++ b/src/csharp/Grpc.Core/Internal/ServerCallHandler.cs @@ -60,7 +60,7 @@ namespace Grpc.Core.Internal var responseStream = new ServerResponseStream(asyncCall); Status status; - Tuple responseTuple = null; + AsyncCallServer.ResponseWithFlags? responseWithFlags = null; var context = HandlerUtils.NewContext(newRpc, responseStream, asyncCall.CancellationToken); try { @@ -68,7 +68,7 @@ namespace Grpc.Core.Internal var request = requestStream.Current; var response = await handler(request, context).ConfigureAwait(false); status = context.Status; - responseTuple = Tuple.Create(response, HandlerUtils.GetWriteFlags(context.WriteOptions)); + responseWithFlags = new AsyncCallServer.ResponseWithFlags(response, HandlerUtils.GetWriteFlags(context.WriteOptions)); } catch (Exception e) { @@ -80,7 +80,7 @@ namespace Grpc.Core.Internal } try { - await asyncCall.SendStatusFromServerAsync(status, context.ResponseTrailers, responseTuple).ConfigureAwait(false); + await asyncCall.SendStatusFromServerAsync(status, context.ResponseTrailers, responseWithFlags).ConfigureAwait(false); } catch (Exception) { @@ -177,13 +177,13 @@ namespace Grpc.Core.Internal var responseStream = new ServerResponseStream(asyncCall); Status status; - Tuple responseTuple = null; + AsyncCallServer.ResponseWithFlags? responseWithFlags = null; var context = HandlerUtils.NewContext(newRpc, responseStream, asyncCall.CancellationToken); try { var response = await handler(requestStream, context).ConfigureAwait(false); status = context.Status; - responseTuple = Tuple.Create(response, HandlerUtils.GetWriteFlags(context.WriteOptions)); + responseWithFlags = new AsyncCallServer.ResponseWithFlags(response, HandlerUtils.GetWriteFlags(context.WriteOptions)); } catch (Exception e) { @@ -196,7 +196,7 @@ namespace Grpc.Core.Internal try { - await asyncCall.SendStatusFromServerAsync(status, context.ResponseTrailers, responseTuple).ConfigureAwait(false); + await asyncCall.SendStatusFromServerAsync(status, context.ResponseTrailers, responseWithFlags).ConfigureAwait(false); } catch (Exception) { diff --git a/src/csharp/Grpc.Core/Internal/ServerRequestStream.cs b/src/csharp/Grpc.Core/Internal/ServerRequestStream.cs index c65b960afb2..058dddb7ebb 100644 --- a/src/csharp/Grpc.Core/Internal/ServerRequestStream.cs +++ b/src/csharp/Grpc.Core/Internal/ServerRequestStream.cs @@ -49,13 +49,14 @@ namespace Grpc.Core.Internal public async Task MoveNext(CancellationToken token) { - if (token != CancellationToken.None) + + var cancellationTokenRegistration = token.CanBeCanceled ? token.Register(() => call.Cancel()) : (IDisposable) null; + using (cancellationTokenRegistration) { - throw new InvalidOperationException("Cancellation of individual reads is not supported."); + var result = await call.ReadMessageAsync().ConfigureAwait(false); + this.current = result; + return result != null; } - var result = await call.ReadMessageAsync().ConfigureAwait(false); - this.current = result; - return result != null; } public void Dispose() diff --git a/src/csharp/Grpc.Core/Internal/ServerSafeHandle.cs b/src/csharp/Grpc.Core/Internal/ServerSafeHandle.cs index 63000e9a221..9b7ea884dd0 100644 --- a/src/csharp/Grpc.Core/Internal/ServerSafeHandle.cs +++ b/src/csharp/Grpc.Core/Internal/ServerSafeHandle.cs @@ -59,13 +59,14 @@ namespace Grpc.Core.Internal { Native.grpcsharp_server_start(this); } - + public void ShutdownAndNotify(BatchCompletionDelegate callback, CompletionQueueSafeHandle completionQueue) { using (completionQueue.NewScope()) { - var ctx = BatchContextSafeHandle.Create(); - completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, callback); + // TODO(jtattermusch): delegate allocation by caller can be avoided by utilizing the "state" object, + // but server shutdown isn't worth optimizing right now. + var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(callback, null); Native.grpcsharp_server_shutdown_and_notify_callback(this, completionQueue, ctx); } } diff --git a/src/csharp/Grpc.Core/Server.cs b/src/csharp/Grpc.Core/Server.cs index 77ad876bdf6..71c7f108f33 100644 --- a/src/csharp/Grpc.Core/Server.cs +++ b/src/csharp/Grpc.Core/Server.cs @@ -387,7 +387,7 @@ namespace Grpc.Core /// /// Handles native callback. /// - private void HandleServerShutdown(bool success, BatchContextSafeHandle ctx) + private void HandleServerShutdown(bool success, BatchContextSafeHandle ctx, object state) { shutdownTcs.SetResult(null); } diff --git a/src/csharp/Grpc.Core/Version.csproj.include b/src/csharp/Grpc.Core/Version.csproj.include index b9ceaf82543..2d9e4ba16ae 100755 --- a/src/csharp/Grpc.Core/Version.csproj.include +++ b/src/csharp/Grpc.Core/Version.csproj.include @@ -1,7 +1,7 @@ - 1.8.0-dev + 1.9.0-dev 3.3.0 diff --git a/src/csharp/Grpc.Core/VersionInfo.cs b/src/csharp/Grpc.Core/VersionInfo.cs index dab938821fa..9b5da1c9475 100644 --- a/src/csharp/Grpc.Core/VersionInfo.cs +++ b/src/csharp/Grpc.Core/VersionInfo.cs @@ -33,11 +33,11 @@ namespace Grpc.Core /// /// Current AssemblyFileVersion of gRPC C# assemblies /// - public const string CurrentAssemblyFileVersion = "1.8.0.0"; + public const string CurrentAssemblyFileVersion = "1.9.0.0"; /// /// Current version of gRPC C# /// - public const string CurrentVersion = "1.8.0-dev"; + public const string CurrentVersion = "1.9.0-dev"; } } diff --git a/src/csharp/Grpc.IntegrationTesting/ClientRunners.cs b/src/csharp/Grpc.IntegrationTesting/ClientRunners.cs index 60696b62d91..9d41d34414a 100644 --- a/src/csharp/Grpc.IntegrationTesting/ClientRunners.cs +++ b/src/csharp/Grpc.IntegrationTesting/ClientRunners.cs @@ -72,7 +72,7 @@ namespace Grpc.IntegrationTesting Logger.Warning("ClientConfig.CoreList is not supported for C#. Ignoring the value"); } - var channels = CreateChannels(config.ClientChannels, config.ServerTargets, config.SecurityParams); + var channels = CreateChannels(config.ClientChannels, config.ServerTargets, config.SecurityParams, config.ChannelArgs); return new ClientRunnerImpl(channels, config.ClientType, @@ -84,19 +84,20 @@ namespace Grpc.IntegrationTesting () => GetNextProfiler()); } - private static List CreateChannels(int clientChannels, IEnumerable serverTargets, SecurityParams securityParams) + private static List CreateChannels(int clientChannels, IEnumerable serverTargets, SecurityParams securityParams, IEnumerable channelArguments) { GrpcPreconditions.CheckArgument(clientChannels > 0, "clientChannels needs to be at least 1."); GrpcPreconditions.CheckArgument(serverTargets.Count() > 0, "at least one serverTarget needs to be specified."); var credentials = securityParams != null ? TestCredentials.CreateSslCredentials() : ChannelCredentials.Insecure; - List channelOptions = null; + var channelOptions = new List(); if (securityParams != null && securityParams.ServerHostOverride != "") { - channelOptions = new List - { - new ChannelOption(ChannelOptions.SslTargetNameOverride, securityParams.ServerHostOverride) - }; + channelOptions.Add(new ChannelOption(ChannelOptions.SslTargetNameOverride, securityParams.ServerHostOverride)); + } + foreach (var channelArgument in channelArguments) + { + channelOptions.Add(channelArgument.ToChannelOption()); } var result = new List(); @@ -130,7 +131,7 @@ namespace Grpc.IntegrationTesting readonly List runnerTasks; readonly CancellationTokenSource stoppedCts = new CancellationTokenSource(); - readonly WallClockStopwatch wallClockStopwatch = new WallClockStopwatch(); + readonly TimeStats timeStats = new TimeStats(); readonly AtomicCounter statsResetCount = new AtomicCounter(); public ClientRunnerImpl(List channels, ClientType clientType, RpcType rpcType, int outstandingRpcsPerChannel, LoadParams loadParams, PayloadConfig payloadConfig, HistogramParams histogramParams, Func profilerFactory) @@ -164,7 +165,7 @@ namespace Grpc.IntegrationTesting hist.GetSnapshot(histogramData, reset); } - var secondsElapsed = wallClockStopwatch.GetElapsedSnapshot(reset).TotalSeconds; + var timeSnapshot = timeStats.GetSnapshot(reset); if (reset) { @@ -172,15 +173,14 @@ namespace Grpc.IntegrationTesting } GrpcEnvironment.Logger.Info("[ClientRunnerImpl.GetStats] GC collection counts: gen0 {0}, gen1 {1}, gen2 {2}, (histogram reset count:{3}, seconds since reset: {4})", - GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2), statsResetCount.Count, secondsElapsed); + GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2), statsResetCount.Count, timeSnapshot.WallClockTime.TotalSeconds); - // TODO: populate user time and system time return new ClientStats { Latencies = histogramData, - TimeElapsed = secondsElapsed, - TimeUser = 0, - TimeSystem = 0 + TimeElapsed = timeSnapshot.WallClockTime.TotalSeconds, + TimeUser = timeSnapshot.UserProcessorTime.TotalSeconds, + TimeSystem = timeSnapshot.PrivilegedProcessorTime.TotalSeconds }; } diff --git a/src/csharp/Grpc.IntegrationTesting/ControlExtensions.cs b/src/csharp/Grpc.IntegrationTesting/ControlExtensions.cs new file mode 100644 index 00000000000..67f5faed20c --- /dev/null +++ b/src/csharp/Grpc.IntegrationTesting/ControlExtensions.cs @@ -0,0 +1,43 @@ +#region Copyright notice and license + +// 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. + +#endregion + +using System; +using Grpc.Core; +using Grpc.Testing; + +namespace Grpc.IntegrationTesting +{ + /// + /// Helpers for Control.cs + /// + public static class ControlExtensions + { + public static ChannelOption ToChannelOption(this ChannelArg channelArgument) + { + switch (channelArgument.ValueCase) + { + case ChannelArg.ValueOneofCase.StrValue: + return new ChannelOption(channelArgument.Name, channelArgument.StrValue); + case ChannelArg.ValueOneofCase.IntValue: + return new ChannelOption(channelArgument.Name, channelArgument.IntValue); + default: + throw new ArgumentException("Unsupported channel argument value."); + } + } + } +} diff --git a/src/csharp/Grpc.IntegrationTesting/ServerRunners.cs b/src/csharp/Grpc.IntegrationTesting/ServerRunners.cs index 45bff3aaf8f..ea29bd74e50 100644 --- a/src/csharp/Grpc.IntegrationTesting/ServerRunners.cs +++ b/src/csharp/Grpc.IntegrationTesting/ServerRunners.cs @@ -78,7 +78,8 @@ namespace Grpc.IntegrationTesting throw new ArgumentException("Unsupported ServerType"); } - var server = new Server + var channelOptions = new List(config.ChannelArgs.Select((arg) => arg.ToChannelOption())); + var server = new Server(channelOptions) { Services = { service }, Ports = { new ServerPort("[::]", config.Port, credentials) } @@ -116,7 +117,7 @@ namespace Grpc.IntegrationTesting public class ServerRunnerImpl : IServerRunner { readonly Server server; - readonly WallClockStopwatch wallClockStopwatch = new WallClockStopwatch(); + readonly TimeStats timeStats = new TimeStats(); public ServerRunnerImpl(Server server) { @@ -137,17 +138,16 @@ namespace Grpc.IntegrationTesting /// The stats. public ServerStats GetStats(bool reset) { - var secondsElapsed = wallClockStopwatch.GetElapsedSnapshot(reset).TotalSeconds; + var timeSnapshot = timeStats.GetSnapshot(reset); GrpcEnvironment.Logger.Info("[ServerRunner.GetStats] GC collection counts: gen0 {0}, gen1 {1}, gen2 {2}, (seconds since last reset {3})", - GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2), secondsElapsed); + GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2), timeSnapshot.WallClockTime.TotalSeconds); - // TODO: populate user time and system time return new ServerStats { - TimeElapsed = secondsElapsed, - TimeUser = 0, - TimeSystem = 0 + TimeElapsed = timeSnapshot.WallClockTime.TotalSeconds, + TimeUser = timeSnapshot.UserProcessorTime.TotalSeconds, + TimeSystem = timeSnapshot.PrivilegedProcessorTime.TotalSeconds }; } diff --git a/src/csharp/Grpc.IntegrationTesting/StressTestClient.cs b/src/csharp/Grpc.IntegrationTesting/StressTestClient.cs index 11956e4ac8f..0c623807681 100644 --- a/src/csharp/Grpc.IntegrationTesting/StressTestClient.cs +++ b/src/csharp/Grpc.IntegrationTesting/StressTestClient.cs @@ -243,7 +243,7 @@ namespace Grpc.IntegrationTesting const string GaugeName = "csharp_overall_qps"; readonly Histogram histogram; - readonly WallClockStopwatch wallClockStopwatch = new WallClockStopwatch(); + readonly TimeStats timeStats = new TimeStats(); public MetricsServiceImpl(Histogram histogram) { @@ -280,9 +280,9 @@ namespace Grpc.IntegrationTesting long GetQpsAndReset() { var snapshot = histogram.GetSnapshot(true); - var elapsedSnapshot = wallClockStopwatch.GetElapsedSnapshot(true); + var timeSnapshot = timeStats.GetSnapshot(true); - return (long) (snapshot.Count / elapsedSnapshot.TotalSeconds); + return (long) (snapshot.Count / timeSnapshot.WallClockTime.TotalSeconds); } } } diff --git a/src/csharp/Grpc.IntegrationTesting/TimeStats.cs b/src/csharp/Grpc.IntegrationTesting/TimeStats.cs new file mode 100644 index 00000000000..6aba04c1949 --- /dev/null +++ b/src/csharp/Grpc.IntegrationTesting/TimeStats.cs @@ -0,0 +1,90 @@ +#region Copyright notice and license + +// Copyright 2015 gRPC authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#endregion + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using Google.Protobuf; +using Grpc.Core; +using Grpc.Core.Utils; +using NUnit.Framework; +using Grpc.Testing; + +namespace Grpc.IntegrationTesting +{ + /// + /// Snapshottable time statistics. + /// + public class TimeStats + { + readonly object myLock = new object(); + DateTime lastWallClock; + TimeSpan lastUserTime; + TimeSpan lastPrivilegedTime; + + public TimeStats() + { + lastWallClock = DateTime.UtcNow; + lastUserTime = Process.GetCurrentProcess().UserProcessorTime; + lastPrivilegedTime = Process.GetCurrentProcess().PrivilegedProcessorTime; + } + + public Snapshot GetSnapshot(bool reset) + { + lock (myLock) + { + var wallClock = DateTime.UtcNow; + var userTime = Process.GetCurrentProcess().UserProcessorTime; + var privilegedTime = Process.GetCurrentProcess().PrivilegedProcessorTime; + var snapshot = new Snapshot(wallClock - lastWallClock, userTime - lastUserTime, privilegedTime - lastPrivilegedTime); + + if (reset) + { + lastWallClock = wallClock; + lastUserTime = userTime; + lastPrivilegedTime = privilegedTime; + } + return snapshot; + } + } + + public class Snapshot + { + public TimeSpan WallClockTime { get; } + public TimeSpan UserProcessorTime { get; } + public TimeSpan PrivilegedProcessorTime { get; } + + public Snapshot(TimeSpan wallClockTime, TimeSpan userProcessorTime, TimeSpan privilegedProcessorTime) + { + this.WallClockTime = wallClockTime; + this.UserProcessorTime = userProcessorTime; + this.PrivilegedProcessorTime = privilegedProcessorTime; + } + + public override string ToString() + { + return string.Format("[TimeStats.Snapshot: wallClock {0}, userProcessor {1}, privilegedProcessor {2}]", WallClockTime, UserProcessorTime, PrivilegedProcessorTime); + } + } + } +} diff --git a/src/csharp/Grpc.IntegrationTesting/WallClockStopwatch.cs b/src/csharp/Grpc.IntegrationTesting/WallClockStopwatch.cs deleted file mode 100644 index 38b58f296c0..00000000000 --- a/src/csharp/Grpc.IntegrationTesting/WallClockStopwatch.cs +++ /dev/null @@ -1,63 +0,0 @@ -#region Copyright notice and license - -// Copyright 2015 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#endregion - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; -using Google.Protobuf; -using Grpc.Core; -using Grpc.Core.Utils; -using NUnit.Framework; -using Grpc.Testing; - -namespace Grpc.IntegrationTesting -{ - /// - /// Snapshottable wall clock stopwatch. - /// - public class WallClockStopwatch - { - long startTicks; - - public WallClockStopwatch() - { - this.startTicks = DateTime.UtcNow.Ticks; - } - - public TimeSpan GetElapsedSnapshot(bool reset) - { - var utcNow = DateTime.UtcNow; - - long oldStartTicks; - if (reset) - { - oldStartTicks = Interlocked.Exchange(ref this.startTicks, utcNow.Ticks); - } - else - { - oldStartTicks = this.startTicks; - } - return utcNow - new DateTime(oldStartTicks, DateTimeKind.Utc); - } - } -} diff --git a/src/csharp/Grpc.Microbenchmarks/CompletionRegistryBenchmark.cs b/src/csharp/Grpc.Microbenchmarks/CompletionRegistryBenchmark.cs new file mode 100644 index 00000000000..eefdb50e39f --- /dev/null +++ b/src/csharp/Grpc.Microbenchmarks/CompletionRegistryBenchmark.cs @@ -0,0 +1,78 @@ +#region Copyright notice and license + +// Copyright 2015 gRPC authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#endregion + +using System; +using System.Runtime.InteropServices; +using System.Threading; +using Grpc.Core; +using Grpc.Core.Internal; +using System.Collections.Generic; +using System.Diagnostics; + +namespace Grpc.Microbenchmarks +{ + public class CompletionRegistryBenchmark + { + GrpcEnvironment environment; + + public void Init() + { + environment = GrpcEnvironment.AddRef(); + } + + public void Cleanup() + { + GrpcEnvironment.ReleaseAsync().Wait(); + } + + public void Run(int threadCount, int iterations, bool useSharedRegistry) + { + Console.WriteLine(string.Format("CompletionRegistryBenchmark: threads={0}, iterations={1}, useSharedRegistry={2}", threadCount, iterations, useSharedRegistry)); + CompletionRegistry sharedRegistry = useSharedRegistry ? new CompletionRegistry(environment, () => BatchContextSafeHandle.Create()) : null; + var threadedBenchmark = new ThreadedBenchmark(threadCount, () => ThreadBody(iterations, sharedRegistry)); + threadedBenchmark.Run(); + // TODO: parametrize by number of pending completions + } + + private void ThreadBody(int iterations, CompletionRegistry optionalSharedRegistry) + { + var completionRegistry = optionalSharedRegistry ?? new CompletionRegistry(environment, () => BatchContextSafeHandle.Create()); + var ctx = BatchContextSafeHandle.Create(); + + var stopwatch = Stopwatch.StartNew(); + for (int i = 0; i < iterations; i++) + { + completionRegistry.Register(ctx.Handle, ctx); + var callback = completionRegistry.Extract(ctx.Handle); + // NOTE: we are not calling the callback to avoid disposing ctx. + } + stopwatch.Stop(); + Console.WriteLine("Elapsed millis: " + stopwatch.ElapsedMilliseconds); + + ctx.Recycle(); + } + + private class NopCompletionCallback : IOpCompletionCallback + { + public void OnComplete(bool success) + { + + } + } + } +} diff --git a/src/csharp/Grpc.Microbenchmarks/GCStats.cs b/src/csharp/Grpc.Microbenchmarks/GCStats.cs new file mode 100644 index 00000000000..ca7051ec4e5 --- /dev/null +++ b/src/csharp/Grpc.Microbenchmarks/GCStats.cs @@ -0,0 +1,69 @@ +#region Copyright notice and license + +// Copyright 2015 gRPC authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#endregion + +using System; +using Grpc.Core; +using Grpc.Core.Internal; + +namespace Grpc.Microbenchmarks +{ + internal class GCStats + { + readonly object myLock = new object(); + GCStatsSnapshot lastSnapshot; + + public GCStats() + { + lastSnapshot = new GCStatsSnapshot(GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2)); + } + + public GCStatsSnapshot GetSnapshot(bool reset = false) + { + lock (myLock) + { + var newSnapshot = new GCStatsSnapshot(GC.CollectionCount(0) - lastSnapshot.Gen0, + GC.CollectionCount(1) - lastSnapshot.Gen1, + GC.CollectionCount(2) - lastSnapshot.Gen2); + if (reset) + { + lastSnapshot = newSnapshot; + } + return newSnapshot; + } + } + } + + public class GCStatsSnapshot + { + public GCStatsSnapshot(int gen0, int gen1, int gen2) + { + this.Gen0 = gen0; + this.Gen1 = gen1; + this.Gen2 = gen2; + } + + public int Gen0 { get; } + public int Gen1 { get; } + public int Gen2 { get; } + + public override string ToString() + { + return string.Format("[GCCollectionCount: gen0 {0}, gen1 {1}, gen2 {2}]", Gen0, Gen1, Gen2); + } + } +} diff --git a/src/csharp/Grpc.Microbenchmarks/Grpc.Microbenchmarks.csproj b/src/csharp/Grpc.Microbenchmarks/Grpc.Microbenchmarks.csproj index 108357e4eb4..8a629f9748b 100644 --- a/src/csharp/Grpc.Microbenchmarks/Grpc.Microbenchmarks.csproj +++ b/src/csharp/Grpc.Microbenchmarks/Grpc.Microbenchmarks.csproj @@ -15,6 +15,10 @@ + + + + diff --git a/src/csharp/Grpc.Microbenchmarks/PInvokeByteArrayBenchmark.cs b/src/csharp/Grpc.Microbenchmarks/PInvokeByteArrayBenchmark.cs new file mode 100644 index 00000000000..787b5508fba --- /dev/null +++ b/src/csharp/Grpc.Microbenchmarks/PInvokeByteArrayBenchmark.cs @@ -0,0 +1,64 @@ +#region Copyright notice and license + +// Copyright 2015 gRPC authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#endregion + +using System; +using System.Runtime.InteropServices; +using System.Threading; +using Grpc.Core; +using Grpc.Core.Internal; +using System.Collections.Generic; +using System.Diagnostics; + +namespace Grpc.Microbenchmarks +{ + public class PInvokeByteArrayBenchmark + { + static readonly NativeMethods Native = NativeMethods.Get(); + + public void Init() + { + } + + public void Cleanup() + { + } + + public void Run(int threadCount, int iterations, int payloadSize) + { + Console.WriteLine(string.Format("PInvokeByteArrayBenchmark: threads={0}, iterations={1}, payloadSize={2}", threadCount, iterations, payloadSize)); + var threadedBenchmark = new ThreadedBenchmark(threadCount, () => ThreadBody(iterations, payloadSize)); + threadedBenchmark.Run(); + } + + private void ThreadBody(int iterations, int payloadSize) + { + var payload = new byte[payloadSize]; + + var stopwatch = Stopwatch.StartNew(); + for (int i = 0; i < iterations; i++) + { + var gcHandle = GCHandle.Alloc(payload, GCHandleType.Pinned); + var payloadPtr = gcHandle.AddrOfPinnedObject(); + Native.grpcsharp_test_nop(payloadPtr); + gcHandle.Free(); + } + stopwatch.Stop(); + Console.WriteLine("Elapsed millis: " + stopwatch.ElapsedMilliseconds); + } + } +} diff --git a/src/csharp/Grpc.Microbenchmarks/Program.cs b/src/csharp/Grpc.Microbenchmarks/Program.cs index d07d4187c45..a64c2979abe 100644 --- a/src/csharp/Grpc.Microbenchmarks/Program.cs +++ b/src/csharp/Grpc.Microbenchmarks/Program.cs @@ -20,14 +20,84 @@ using System; using Grpc.Core; using Grpc.Core.Internal; using Grpc.Core.Logging; +using CommandLine; +using CommandLine.Text; namespace Grpc.Microbenchmarks { class Program { + public enum MicrobenchmarkType + { + CompletionRegistry, + PInvokeByteArray, + SendMessage + } + + private class BenchmarkOptions + { + [Option("benchmark", Required = true, HelpText = "Benchmark to run")] + public MicrobenchmarkType Benchmark { get; set; } + } + public static void Main(string[] args) { GrpcEnvironment.SetLogger(new ConsoleLogger()); + var parserResult = Parser.Default.ParseArguments(args) + .WithNotParsed(errors => { + Console.WriteLine("Supported benchmarks:"); + foreach (var enumValue in Enum.GetValues(typeof(MicrobenchmarkType))) + { + Console.WriteLine(" " + enumValue); + } + Environment.Exit(1); + }) + .WithParsed(options => + { + switch (options.Benchmark) + { + case MicrobenchmarkType.CompletionRegistry: + RunCompletionRegistryBenchmark(); + break; + case MicrobenchmarkType.PInvokeByteArray: + RunPInvokeByteArrayBenchmark(); + break; + case MicrobenchmarkType.SendMessage: + RunSendMessageBenchmark(); + break; + default: + throw new ArgumentException("Unsupported benchmark."); + } + }); + } + + static void RunCompletionRegistryBenchmark() + { + var benchmark = new CompletionRegistryBenchmark(); + benchmark.Init(); + foreach (int threadCount in new int[] {1, 1, 2, 4, 8, 12}) + { + foreach (bool useSharedRegistry in new bool[] {false, true}) + { + benchmark.Run(threadCount, 4 * 1000 * 1000, useSharedRegistry); + } + } + benchmark.Cleanup(); + } + + static void RunPInvokeByteArrayBenchmark() + { + var benchmark = new PInvokeByteArrayBenchmark(); + benchmark.Init(); + foreach (int threadCount in new int[] {1, 1, 2, 4, 8, 12}) + { + benchmark.Run(threadCount, 4 * 1000 * 1000, 0); + } + benchmark.Cleanup(); + } + + static void RunSendMessageBenchmark() + { var benchmark = new SendMessageBenchmark(); benchmark.Init(); foreach (int threadCount in new int[] {1, 1, 2, 4, 8, 12}) diff --git a/src/csharp/Grpc.Microbenchmarks/SendMessageBenchmark.cs b/src/csharp/Grpc.Microbenchmarks/SendMessageBenchmark.cs index de67874580d..da4f35ff963 100644 --- a/src/csharp/Grpc.Microbenchmarks/SendMessageBenchmark.cs +++ b/src/csharp/Grpc.Microbenchmarks/SendMessageBenchmark.cs @@ -52,23 +52,20 @@ namespace Grpc.Microbenchmarks private void ThreadBody(int iterations, int payloadSize) { - // TODO(jtattermusch): parametrize by number of pending completions. - // TODO(jtattermusch): parametrize by cached/non-cached BatchContextSafeHandle - - var completionRegistry = new CompletionRegistry(environment); + var completionRegistry = new CompletionRegistry(environment, () => environment.BatchContextPool.Lease()); var cq = CompletionQueueSafeHandle.CreateAsync(completionRegistry); var call = CreateFakeCall(cq); - var sendCompletionHandler = new SendCompletionHandler((success) => { }); + var sendCompletionCallback = new NopSendCompletionCallback(); var payload = new byte[payloadSize]; var writeFlags = default(WriteFlags); var stopwatch = Stopwatch.StartNew(); for (int i = 0; i < iterations; i++) { - call.StartSendMessage(sendCompletionHandler, payload, writeFlags, false); + call.StartSendMessage(sendCompletionCallback, payload, writeFlags, false); var callback = completionRegistry.Extract(completionRegistry.LastRegisteredKey); - callback(true); + callback.OnComplete(true); } stopwatch.Stop(); Console.WriteLine("Elapsed millis: " + stopwatch.ElapsedMilliseconds); @@ -87,5 +84,13 @@ namespace Grpc.Microbenchmarks } return call; } + + private class NopSendCompletionCallback : ISendCompletionCallback + { + public void OnSendCompletion(bool success) + { + // NOP + } + } } } diff --git a/src/csharp/Grpc.Microbenchmarks/ThreadedBenchmark.cs b/src/csharp/Grpc.Microbenchmarks/ThreadedBenchmark.cs index feac8d16908..95b9aaaf3f9 100644 --- a/src/csharp/Grpc.Microbenchmarks/ThreadedBenchmark.cs +++ b/src/csharp/Grpc.Microbenchmarks/ThreadedBenchmark.cs @@ -46,6 +46,7 @@ namespace Grpc.Microbenchmarks public void Run() { Console.WriteLine("Running threads."); + var gcStats = new GCStats(); var threads = new List(); for (int i = 0; i < runners.Count; i++) { @@ -58,7 +59,7 @@ namespace Grpc.Microbenchmarks { thread.Join(); } - Console.WriteLine("All threads finished."); + Console.WriteLine("All threads finished (GC Stats Delta: " + gcStats.GetSnapshot() + ")"); } } } diff --git a/src/csharp/build_packages_dotnetcli.bat b/src/csharp/build_packages_dotnetcli.bat index ff013d56800..8f89e2846a5 100755 --- a/src/csharp/build_packages_dotnetcli.bat +++ b/src/csharp/build_packages_dotnetcli.bat @@ -13,7 +13,7 @@ @rem limitations under the License. @rem Current package versions -set VERSION=1.8.0-dev +set VERSION=1.9.0-dev @rem Adjust the location of nuget.exe set NUGET=C:\nuget\nuget.exe diff --git a/src/csharp/build_packages_dotnetcli.sh b/src/csharp/build_packages_dotnetcli.sh index 44a4791146b..6a6cafe2bdc 100755 --- a/src/csharp/build_packages_dotnetcli.sh +++ b/src/csharp/build_packages_dotnetcli.sh @@ -39,7 +39,7 @@ dotnet pack --configuration Release Grpc.Auth --output ../../../artifacts dotnet pack --configuration Release Grpc.HealthCheck --output ../../../artifacts dotnet pack --configuration Release Grpc.Reflection --output ../../../artifacts -nuget pack Grpc.nuspec -Version "1.8.0-dev" -OutputDirectory ../../artifacts -nuget pack Grpc.Tools.nuspec -Version "1.8.0-dev" -OutputDirectory ../../artifacts +nuget pack Grpc.nuspec -Version "1.9.0-dev" -OutputDirectory ../../artifacts +nuget pack Grpc.Tools.nuspec -Version "1.9.0-dev" -OutputDirectory ../../artifacts (cd ../../artifacts && zip csharp_nugets_dotnetcli.zip *.nupkg) diff --git a/src/csharp/ext/grpc_csharp_ext.c b/src/csharp/ext/grpc_csharp_ext.c index 92291f9011b..24d779e1e57 100644 --- a/src/csharp/ext/grpc_csharp_ext.c +++ b/src/csharp/ext/grpc_csharp_ext.c @@ -43,9 +43,9 @@ #define GPR_CALLTYPE #endif -grpc_byte_buffer *string_to_byte_buffer(const char *buffer, size_t len) { +grpc_byte_buffer* string_to_byte_buffer(const char* buffer, size_t len) { grpc_slice slice = grpc_slice_from_copied_buffer(buffer, len); - grpc_byte_buffer *bb = grpc_raw_byte_buffer_create(&slice, 1); + grpc_byte_buffer* bb = grpc_raw_byte_buffer_create(&slice, 1); grpc_slice_unref(slice); return bb; } @@ -55,12 +55,12 @@ grpc_byte_buffer *string_to_byte_buffer(const char *buffer, size_t len) { */ typedef struct grpcsharp_batch_context { grpc_metadata_array send_initial_metadata; - grpc_byte_buffer *send_message; + grpc_byte_buffer* send_message; struct { grpc_metadata_array trailing_metadata; } send_status_from_server; grpc_metadata_array recv_initial_metadata; - grpc_byte_buffer *recv_message; + grpc_byte_buffer* recv_message; struct { grpc_metadata_array trailing_metadata; grpc_status_code status; @@ -69,22 +69,22 @@ typedef struct grpcsharp_batch_context { int recv_close_on_server_cancelled; } grpcsharp_batch_context; -GPR_EXPORT grpcsharp_batch_context *GPR_CALLTYPE +GPR_EXPORT grpcsharp_batch_context* GPR_CALLTYPE grpcsharp_batch_context_create() { - grpcsharp_batch_context *ctx = gpr_malloc(sizeof(grpcsharp_batch_context)); + grpcsharp_batch_context* ctx = gpr_malloc(sizeof(grpcsharp_batch_context)); memset(ctx, 0, sizeof(grpcsharp_batch_context)); return ctx; } typedef struct { - grpc_call *call; + grpc_call* call; grpc_call_details call_details; grpc_metadata_array request_metadata; } grpcsharp_request_call_context; -GPR_EXPORT grpcsharp_request_call_context *GPR_CALLTYPE +GPR_EXPORT grpcsharp_request_call_context* GPR_CALLTYPE grpcsharp_request_call_context_create() { - grpcsharp_request_call_context *ctx = + grpcsharp_request_call_context* ctx = gpr_malloc(sizeof(grpcsharp_request_call_context)); memset(ctx, 0, sizeof(grpcsharp_request_call_context)); return ctx; @@ -95,7 +95,7 @@ grpcsharp_request_call_context_create() { * The array pointer itself is not freed. */ void grpcsharp_metadata_array_destroy_metadata_only( - grpc_metadata_array *array) { + grpc_metadata_array* array) { gpr_free(array->metadata); } @@ -104,7 +104,7 @@ void grpcsharp_metadata_array_destroy_metadata_only( * The array pointer itself is not freed. */ void grpcsharp_metadata_array_destroy_metadata_including_entries( - grpc_metadata_array *array) { + grpc_metadata_array* array) { size_t i; if (array->metadata) { for (i = 0; i < array->count; i++) { @@ -119,7 +119,7 @@ void grpcsharp_metadata_array_destroy_metadata_including_entries( * Fully destroys the metadata array. */ GPR_EXPORT void GPR_CALLTYPE -grpcsharp_metadata_array_destroy_full(grpc_metadata_array *array) { +grpcsharp_metadata_array_destroy_full(grpc_metadata_array* array) { if (!array) { return; } @@ -131,16 +131,16 @@ grpcsharp_metadata_array_destroy_full(grpc_metadata_array *array) { * Creates an empty metadata array with given capacity. * Array can later be destroyed by grpc_metadata_array_destroy_full. */ -GPR_EXPORT grpc_metadata_array *GPR_CALLTYPE +GPR_EXPORT grpc_metadata_array* GPR_CALLTYPE grpcsharp_metadata_array_create(size_t capacity) { - grpc_metadata_array *array = - (grpc_metadata_array *)gpr_malloc(sizeof(grpc_metadata_array)); + grpc_metadata_array* array = + (grpc_metadata_array*)gpr_malloc(sizeof(grpc_metadata_array)); grpc_metadata_array_init(array); array->capacity = capacity; array->count = 0; if (capacity > 0) { array->metadata = - (grpc_metadata *)gpr_malloc(sizeof(grpc_metadata) * capacity); + (grpc_metadata*)gpr_malloc(sizeof(grpc_metadata) * capacity); memset(array->metadata, 0, sizeof(grpc_metadata) * capacity); } else { array->metadata = NULL; @@ -149,8 +149,8 @@ grpcsharp_metadata_array_create(size_t capacity) { } GPR_EXPORT void GPR_CALLTYPE -grpcsharp_metadata_array_add(grpc_metadata_array *array, const char *key, - const char *value, size_t value_length) { +grpcsharp_metadata_array_add(grpc_metadata_array* array, const char* key, + const char* value, size_t value_length) { size_t i = array->count; GPR_ASSERT(array->count < array->capacity); array->metadata[i].key = grpc_slice_from_copied_string(key); @@ -159,27 +159,27 @@ grpcsharp_metadata_array_add(grpc_metadata_array *array, const char *key, } GPR_EXPORT intptr_t GPR_CALLTYPE -grpcsharp_metadata_array_count(grpc_metadata_array *array) { +grpcsharp_metadata_array_count(grpc_metadata_array* array) { return (intptr_t)array->count; } -GPR_EXPORT const char *GPR_CALLTYPE grpcsharp_metadata_array_get_key( - grpc_metadata_array *array, size_t index, size_t *key_length) { +GPR_EXPORT const char* GPR_CALLTYPE grpcsharp_metadata_array_get_key( + grpc_metadata_array* array, size_t index, size_t* key_length) { GPR_ASSERT(index < array->count); *key_length = GRPC_SLICE_LENGTH(array->metadata[index].key); - return (char *)GRPC_SLICE_START_PTR(array->metadata[index].key); + return (char*)GRPC_SLICE_START_PTR(array->metadata[index].key); } -GPR_EXPORT const char *GPR_CALLTYPE grpcsharp_metadata_array_get_value( - grpc_metadata_array *array, size_t index, size_t *value_length) { +GPR_EXPORT const char* GPR_CALLTYPE grpcsharp_metadata_array_get_value( + grpc_metadata_array* array, size_t index, size_t* value_length) { GPR_ASSERT(index < array->count); *value_length = GRPC_SLICE_LENGTH(array->metadata[index].value); - return (char *)GRPC_SLICE_START_PTR(array->metadata[index].value); + return (char*)GRPC_SLICE_START_PTR(array->metadata[index].value); } /* Move contents of metadata array */ -void grpcsharp_metadata_array_move(grpc_metadata_array *dest, - grpc_metadata_array *src) { +void grpcsharp_metadata_array_move(grpc_metadata_array* dest, + grpc_metadata_array* src) { if (!src) { dest->capacity = 0; dest->count = 0; @@ -197,10 +197,7 @@ void grpcsharp_metadata_array_move(grpc_metadata_array *dest, } GPR_EXPORT void GPR_CALLTYPE -grpcsharp_batch_context_destroy(grpcsharp_batch_context *ctx) { - if (!ctx) { - return; - } +grpcsharp_batch_context_reset(grpcsharp_batch_context* ctx) { grpcsharp_metadata_array_destroy_metadata_including_entries( &(ctx->send_initial_metadata)); @@ -216,12 +213,20 @@ grpcsharp_batch_context_destroy(grpcsharp_batch_context *ctx) { grpcsharp_metadata_array_destroy_metadata_only( &(ctx->recv_status_on_client.trailing_metadata)); grpc_slice_unref(ctx->recv_status_on_client.status_details); + memset(ctx, 0, sizeof(grpcsharp_batch_context)); +} +GPR_EXPORT void GPR_CALLTYPE +grpcsharp_batch_context_destroy(grpcsharp_batch_context* ctx) { + if (!ctx) { + return; + } + grpcsharp_batch_context_reset(ctx); gpr_free(ctx); } GPR_EXPORT void GPR_CALLTYPE -grpcsharp_request_call_context_destroy(grpcsharp_request_call_context *ctx) { +grpcsharp_request_call_context_destroy(grpcsharp_request_call_context* ctx) { if (!ctx) { return; } @@ -235,14 +240,14 @@ grpcsharp_request_call_context_destroy(grpcsharp_request_call_context *ctx) { gpr_free(ctx); } -GPR_EXPORT const grpc_metadata_array *GPR_CALLTYPE +GPR_EXPORT const grpc_metadata_array* GPR_CALLTYPE grpcsharp_batch_context_recv_initial_metadata( - const grpcsharp_batch_context *ctx) { + const grpcsharp_batch_context* ctx) { return &(ctx->recv_initial_metadata); } GPR_EXPORT intptr_t GPR_CALLTYPE grpcsharp_batch_context_recv_message_length( - const grpcsharp_batch_context *ctx) { + const grpcsharp_batch_context* ctx) { grpc_byte_buffer_reader reader; if (!ctx->recv_message) { return -1; @@ -260,7 +265,7 @@ GPR_EXPORT intptr_t GPR_CALLTYPE grpcsharp_batch_context_recv_message_length( * buffer is too small. */ GPR_EXPORT void GPR_CALLTYPE grpcsharp_batch_context_recv_message_to_buffer( - const grpcsharp_batch_context *ctx, char *buffer, size_t buffer_len) { + const grpcsharp_batch_context* ctx, char* buffer, size_t buffer_len) { grpc_byte_buffer_reader reader; grpc_slice slice; size_t offset = 0; @@ -281,56 +286,55 @@ GPR_EXPORT void GPR_CALLTYPE grpcsharp_batch_context_recv_message_to_buffer( GPR_EXPORT grpc_status_code GPR_CALLTYPE grpcsharp_batch_context_recv_status_on_client_status( - const grpcsharp_batch_context *ctx) { + const grpcsharp_batch_context* ctx) { return ctx->recv_status_on_client.status; } -GPR_EXPORT const char *GPR_CALLTYPE +GPR_EXPORT const char* GPR_CALLTYPE grpcsharp_batch_context_recv_status_on_client_details( - const grpcsharp_batch_context *ctx, size_t *details_length) { + const grpcsharp_batch_context* ctx, size_t* details_length) { *details_length = GRPC_SLICE_LENGTH(ctx->recv_status_on_client.status_details); - return (char *)GRPC_SLICE_START_PTR( - ctx->recv_status_on_client.status_details); + return (char*)GRPC_SLICE_START_PTR(ctx->recv_status_on_client.status_details); } -GPR_EXPORT const grpc_metadata_array *GPR_CALLTYPE +GPR_EXPORT const grpc_metadata_array* GPR_CALLTYPE grpcsharp_batch_context_recv_status_on_client_trailing_metadata( - const grpcsharp_batch_context *ctx) { + const grpcsharp_batch_context* ctx) { return &(ctx->recv_status_on_client.trailing_metadata); } -GPR_EXPORT grpc_call *GPR_CALLTYPE -grpcsharp_request_call_context_call(const grpcsharp_request_call_context *ctx) { +GPR_EXPORT grpc_call* GPR_CALLTYPE +grpcsharp_request_call_context_call(const grpcsharp_request_call_context* ctx) { return ctx->call; } -GPR_EXPORT const char *GPR_CALLTYPE grpcsharp_request_call_context_method( - const grpcsharp_request_call_context *ctx, size_t *method_length) { +GPR_EXPORT const char* GPR_CALLTYPE grpcsharp_request_call_context_method( + const grpcsharp_request_call_context* ctx, size_t* method_length) { *method_length = GRPC_SLICE_LENGTH(ctx->call_details.method); - return (char *)GRPC_SLICE_START_PTR(ctx->call_details.method); + return (char*)GRPC_SLICE_START_PTR(ctx->call_details.method); } -GPR_EXPORT const char *GPR_CALLTYPE grpcsharp_request_call_context_host( - const grpcsharp_request_call_context *ctx, size_t *host_length) { +GPR_EXPORT const char* GPR_CALLTYPE grpcsharp_request_call_context_host( + const grpcsharp_request_call_context* ctx, size_t* host_length) { *host_length = GRPC_SLICE_LENGTH(ctx->call_details.host); - return (char *)GRPC_SLICE_START_PTR(ctx->call_details.host); + return (char*)GRPC_SLICE_START_PTR(ctx->call_details.host); } GPR_EXPORT gpr_timespec GPR_CALLTYPE grpcsharp_request_call_context_deadline( - const grpcsharp_request_call_context *ctx) { + const grpcsharp_request_call_context* ctx) { return ctx->call_details.deadline; } -GPR_EXPORT const grpc_metadata_array *GPR_CALLTYPE +GPR_EXPORT const grpc_metadata_array* GPR_CALLTYPE grpcsharp_request_call_context_request_metadata( - const grpcsharp_request_call_context *ctx) { + const grpcsharp_request_call_context* ctx) { return &(ctx->request_metadata); } GPR_EXPORT int32_t GPR_CALLTYPE grpcsharp_batch_context_recv_close_on_server_cancelled( - const grpcsharp_batch_context *ctx) { + const grpcsharp_batch_context* ctx) { return (int32_t)ctx->recv_close_on_server_cancelled; } @@ -342,63 +346,63 @@ GPR_EXPORT void GPR_CALLTYPE grpcsharp_shutdown(void) { grpc_shutdown(); } /* Completion queue */ -GPR_EXPORT grpc_completion_queue *GPR_CALLTYPE +GPR_EXPORT grpc_completion_queue* GPR_CALLTYPE grpcsharp_completion_queue_create_async(void) { return grpc_completion_queue_create_for_next(NULL); } -GPR_EXPORT grpc_completion_queue *GPR_CALLTYPE +GPR_EXPORT grpc_completion_queue* GPR_CALLTYPE grpcsharp_completion_queue_create_sync(void) { return grpc_completion_queue_create_for_pluck(NULL); } GPR_EXPORT void GPR_CALLTYPE -grpcsharp_completion_queue_shutdown(grpc_completion_queue *cq) { +grpcsharp_completion_queue_shutdown(grpc_completion_queue* cq) { grpc_completion_queue_shutdown(cq); } GPR_EXPORT void GPR_CALLTYPE -grpcsharp_completion_queue_destroy(grpc_completion_queue *cq) { +grpcsharp_completion_queue_destroy(grpc_completion_queue* cq) { grpc_completion_queue_destroy(cq); } GPR_EXPORT grpc_event GPR_CALLTYPE -grpcsharp_completion_queue_next(grpc_completion_queue *cq) { +grpcsharp_completion_queue_next(grpc_completion_queue* cq) { return grpc_completion_queue_next(cq, gpr_inf_future(GPR_CLOCK_REALTIME), NULL); } GPR_EXPORT grpc_event GPR_CALLTYPE -grpcsharp_completion_queue_pluck(grpc_completion_queue *cq, void *tag) { +grpcsharp_completion_queue_pluck(grpc_completion_queue* cq, void* tag) { return grpc_completion_queue_pluck(cq, tag, gpr_inf_future(GPR_CLOCK_REALTIME), NULL); } /* Channel */ -GPR_EXPORT grpc_channel *GPR_CALLTYPE +GPR_EXPORT grpc_channel* GPR_CALLTYPE -grpcsharp_insecure_channel_create(const char *target, - const grpc_channel_args *args) { +grpcsharp_insecure_channel_create(const char* target, + const grpc_channel_args* args) { return grpc_insecure_channel_create(target, args, NULL); } -GPR_EXPORT void GPR_CALLTYPE grpcsharp_channel_destroy(grpc_channel *channel) { +GPR_EXPORT void GPR_CALLTYPE grpcsharp_channel_destroy(grpc_channel* channel) { grpc_channel_destroy(channel); } -GPR_EXPORT grpc_call *GPR_CALLTYPE grpcsharp_channel_create_call( - grpc_channel *channel, grpc_call *parent_call, uint32_t propagation_mask, - grpc_completion_queue *cq, const char *method, const char *host, +GPR_EXPORT grpc_call* GPR_CALLTYPE grpcsharp_channel_create_call( + grpc_channel* channel, grpc_call* parent_call, uint32_t propagation_mask, + grpc_completion_queue* cq, const char* method, const char* host, gpr_timespec deadline) { grpc_slice method_slice = grpc_slice_from_copied_string(method); - grpc_slice *host_slice_ptr = NULL; + grpc_slice* host_slice_ptr = NULL; grpc_slice host_slice; if (host != NULL) { host_slice = grpc_slice_from_copied_string(host); host_slice_ptr = &host_slice; } - grpc_call *ret = + grpc_call* ret = grpc_channel_create_call(channel, parent_call, propagation_mask, cq, method_slice, host_slice_ptr, deadline, NULL); grpc_slice_unref(method_slice); @@ -409,40 +413,40 @@ GPR_EXPORT grpc_call *GPR_CALLTYPE grpcsharp_channel_create_call( } GPR_EXPORT grpc_connectivity_state GPR_CALLTYPE -grpcsharp_channel_check_connectivity_state(grpc_channel *channel, +grpcsharp_channel_check_connectivity_state(grpc_channel* channel, int32_t try_to_connect) { return grpc_channel_check_connectivity_state(channel, try_to_connect); } GPR_EXPORT void GPR_CALLTYPE grpcsharp_channel_watch_connectivity_state( - grpc_channel *channel, grpc_connectivity_state last_observed_state, - gpr_timespec deadline, grpc_completion_queue *cq, - grpcsharp_batch_context *ctx) { + grpc_channel* channel, grpc_connectivity_state last_observed_state, + gpr_timespec deadline, grpc_completion_queue* cq, + grpcsharp_batch_context* ctx) { grpc_channel_watch_connectivity_state(channel, last_observed_state, deadline, cq, ctx); } -GPR_EXPORT char *GPR_CALLTYPE -grpcsharp_channel_get_target(grpc_channel *channel) { +GPR_EXPORT char* GPR_CALLTYPE +grpcsharp_channel_get_target(grpc_channel* channel) { return grpc_channel_get_target(channel); } /* Channel args */ -GPR_EXPORT grpc_channel_args *GPR_CALLTYPE +GPR_EXPORT grpc_channel_args* GPR_CALLTYPE grpcsharp_channel_args_create(size_t num_args) { - grpc_channel_args *args = - (grpc_channel_args *)gpr_malloc(sizeof(grpc_channel_args)); + grpc_channel_args* args = + (grpc_channel_args*)gpr_malloc(sizeof(grpc_channel_args)); memset(args, 0, sizeof(grpc_channel_args)); args->num_args = num_args; - args->args = (grpc_arg *)gpr_malloc(sizeof(grpc_arg) * num_args); + args->args = (grpc_arg*)gpr_malloc(sizeof(grpc_arg) * num_args); memset(args->args, 0, sizeof(grpc_arg) * num_args); return args; } GPR_EXPORT void GPR_CALLTYPE grpcsharp_channel_args_set_string( - grpc_channel_args *args, size_t index, const char *key, const char *value) { + grpc_channel_args* args, size_t index, const char* key, const char* value) { GPR_ASSERT(args); GPR_ASSERT(index < args->num_args); args->args[index].type = GRPC_ARG_STRING; @@ -451,7 +455,7 @@ GPR_EXPORT void GPR_CALLTYPE grpcsharp_channel_args_set_string( } GPR_EXPORT void GPR_CALLTYPE grpcsharp_channel_args_set_integer( - grpc_channel_args *args, size_t index, const char *key, int value) { + grpc_channel_args* args, size_t index, const char* key, int value) { GPR_ASSERT(args); GPR_ASSERT(index < args->num_args); args->args[index].type = GRPC_ARG_INTEGER; @@ -460,7 +464,7 @@ GPR_EXPORT void GPR_CALLTYPE grpcsharp_channel_args_set_integer( } GPR_EXPORT void GPR_CALLTYPE -grpcsharp_channel_args_destroy(grpc_channel_args *args) { +grpcsharp_channel_args_destroy(grpc_channel_args* args) { size_t i; if (args) { for (i = 0; i < args->num_args; i++) { @@ -501,61 +505,61 @@ GPR_EXPORT int32_t GPR_CALLTYPE gprsharp_sizeof_timespec(void) { /* Call */ -GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_cancel(grpc_call *call) { +GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_cancel(grpc_call* call) { return grpc_call_cancel(call, NULL); } GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_cancel_with_status( - grpc_call *call, grpc_status_code status, const char *description) { + grpc_call* call, grpc_status_code status, const char* description) { return grpc_call_cancel_with_status(call, status, description, NULL); } -GPR_EXPORT char *GPR_CALLTYPE grpcsharp_call_get_peer(grpc_call *call) { +GPR_EXPORT char* GPR_CALLTYPE grpcsharp_call_get_peer(grpc_call* call) { return grpc_call_get_peer(call); } -GPR_EXPORT void GPR_CALLTYPE gprsharp_free(void *p) { gpr_free(p); } +GPR_EXPORT void GPR_CALLTYPE gprsharp_free(void* p) { gpr_free(p); } -GPR_EXPORT void GPR_CALLTYPE grpcsharp_call_destroy(grpc_call *call) { +GPR_EXPORT void GPR_CALLTYPE grpcsharp_call_destroy(grpc_call* call) { grpc_call_unref(call); } -typedef grpc_call_error (*grpcsharp_call_start_batch_func)(grpc_call *call, - const grpc_op *ops, +typedef grpc_call_error (*grpcsharp_call_start_batch_func)(grpc_call* call, + const grpc_op* ops, size_t nops, - void *tag, - void *reserved); + void* tag, + void* reserved); /* Only for testing */ -static grpc_call_error grpcsharp_call_start_batch_nop(grpc_call *call, - const grpc_op *ops, - size_t nops, void *tag, - void *reserved) { +static grpc_call_error grpcsharp_call_start_batch_nop(grpc_call* call, + const grpc_op* ops, + size_t nops, void* tag, + void* reserved) { return GRPC_CALL_OK; } -static grpc_call_error grpcsharp_call_start_batch_default(grpc_call *call, - const grpc_op *ops, +static grpc_call_error grpcsharp_call_start_batch_default(grpc_call* call, + const grpc_op* ops, size_t nops, - void *tag, - void *reserved) { + void* tag, + void* reserved) { return grpc_call_start_batch(call, ops, nops, tag, reserved); } static grpcsharp_call_start_batch_func g_call_start_batch_func = grpcsharp_call_start_batch_default; -static grpc_call_error grpcsharp_call_start_batch(grpc_call *call, - const grpc_op *ops, - size_t nops, void *tag, - void *reserved) { +static grpc_call_error grpcsharp_call_start_batch(grpc_call* call, + const grpc_op* ops, + size_t nops, void* tag, + void* reserved) { return g_call_start_batch_func(call, ops, nops, tag, reserved); } GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_start_unary( - grpc_call *call, grpcsharp_batch_context *ctx, const char *send_buffer, + grpc_call* call, grpcsharp_batch_context* ctx, const char* send_buffer, size_t send_buffer_len, uint32_t write_flags, - grpc_metadata_array *initial_metadata, uint32_t initial_metadata_flags) { + grpc_metadata_array* initial_metadata, uint32_t initial_metadata_flags) { /* TODO: don't use magic number */ grpc_op ops[6]; memset(ops, 0, sizeof(ops)); @@ -604,8 +608,8 @@ GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_start_unary( } GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_start_client_streaming( - grpc_call *call, grpcsharp_batch_context *ctx, - grpc_metadata_array *initial_metadata, uint32_t initial_metadata_flags) { + grpc_call* call, grpcsharp_batch_context* ctx, + grpc_metadata_array* initial_metadata, uint32_t initial_metadata_flags) { /* TODO: don't use magic number */ grpc_op ops[4]; memset(ops, 0, sizeof(ops)); @@ -644,9 +648,9 @@ GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_start_client_streaming( } GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_start_server_streaming( - grpc_call *call, grpcsharp_batch_context *ctx, const char *send_buffer, + grpc_call* call, grpcsharp_batch_context* ctx, const char* send_buffer, size_t send_buffer_len, uint32_t write_flags, - grpc_metadata_array *initial_metadata, uint32_t initial_metadata_flags) { + grpc_metadata_array* initial_metadata, uint32_t initial_metadata_flags) { /* TODO: don't use magic number */ grpc_op ops[4]; memset(ops, 0, sizeof(ops)); @@ -684,8 +688,8 @@ GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_start_server_streaming( } GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_start_duplex_streaming( - grpc_call *call, grpcsharp_batch_context *ctx, - grpc_metadata_array *initial_metadata, uint32_t initial_metadata_flags) { + grpc_call* call, grpcsharp_batch_context* ctx, + grpc_metadata_array* initial_metadata, uint32_t initial_metadata_flags) { /* TODO: don't use magic number */ grpc_op ops[2]; memset(ops, 0, sizeof(ops)); @@ -713,7 +717,7 @@ GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_start_duplex_streaming( } GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_recv_initial_metadata( - grpc_call *call, grpcsharp_batch_context *ctx) { + grpc_call* call, grpcsharp_batch_context* ctx) { /* TODO: don't use magic number */ grpc_op ops[1]; ops[0].op = GRPC_OP_RECV_INITIAL_METADATA; @@ -727,7 +731,7 @@ GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_recv_initial_metadata( } GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_send_message( - grpc_call *call, grpcsharp_batch_context *ctx, const char *send_buffer, + grpc_call* call, grpcsharp_batch_context* ctx, const char* send_buffer, size_t send_buffer_len, uint32_t write_flags, int32_t send_empty_initial_metadata) { /* TODO: don't use magic number */ @@ -747,7 +751,7 @@ GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_send_message( } GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_send_close_from_client( - grpc_call *call, grpcsharp_batch_context *ctx) { + grpc_call* call, grpcsharp_batch_context* ctx) { /* TODO: don't use magic number */ grpc_op ops[1]; ops[0].op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; @@ -759,10 +763,10 @@ GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_send_close_from_client( } GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_send_status_from_server( - grpc_call *call, grpcsharp_batch_context *ctx, grpc_status_code status_code, - const char *status_details, size_t status_details_len, - grpc_metadata_array *trailing_metadata, int32_t send_empty_initial_metadata, - const char *optional_send_buffer, size_t optional_send_buffer_len, + grpc_call* call, grpcsharp_batch_context* ctx, grpc_status_code status_code, + const char* status_details, size_t status_details_len, + grpc_metadata_array* trailing_metadata, int32_t send_empty_initial_metadata, + const char* optional_send_buffer, size_t optional_send_buffer_len, uint32_t write_flags) { /* TODO: don't use magic number */ grpc_op ops[3]; @@ -802,7 +806,7 @@ GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_send_status_from_server( } GPR_EXPORT grpc_call_error GPR_CALLTYPE -grpcsharp_call_recv_message(grpc_call *call, grpcsharp_batch_context *ctx) { +grpcsharp_call_recv_message(grpc_call* call, grpcsharp_batch_context* ctx) { /* TODO: don't use magic number */ grpc_op ops[1]; ops[0].op = GRPC_OP_RECV_MESSAGE; @@ -814,7 +818,7 @@ grpcsharp_call_recv_message(grpc_call *call, grpcsharp_batch_context *ctx) { } GPR_EXPORT grpc_call_error GPR_CALLTYPE -grpcsharp_call_start_serverside(grpc_call *call, grpcsharp_batch_context *ctx) { +grpcsharp_call_start_serverside(grpc_call* call, grpcsharp_batch_context* ctx) { /* TODO: don't use magic number */ grpc_op ops[1]; ops[0].op = GRPC_OP_RECV_CLOSE_ON_SERVER; @@ -828,8 +832,8 @@ grpcsharp_call_start_serverside(grpc_call *call, grpcsharp_batch_context *ctx) { } GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_send_initial_metadata( - grpc_call *call, grpcsharp_batch_context *ctx, - grpc_metadata_array *initial_metadata) { + grpc_call* call, grpcsharp_batch_context* ctx, + grpc_metadata_array* initial_metadata) { /* TODO: don't use magic number */ grpc_op ops[1]; memset(ops, 0, sizeof(ops)); @@ -847,59 +851,59 @@ GPR_EXPORT grpc_call_error GPR_CALLTYPE grpcsharp_call_send_initial_metadata( } GPR_EXPORT grpc_call_error GPR_CALLTYPE -grpcsharp_call_set_credentials(grpc_call *call, grpc_call_credentials *creds) { +grpcsharp_call_set_credentials(grpc_call* call, grpc_call_credentials* creds) { return grpc_call_set_credentials(call, creds); } /* Server */ -GPR_EXPORT grpc_server *GPR_CALLTYPE -grpcsharp_server_create(const grpc_channel_args *args) { +GPR_EXPORT grpc_server* GPR_CALLTYPE +grpcsharp_server_create(const grpc_channel_args* args) { return grpc_server_create(args, NULL); } GPR_EXPORT void GPR_CALLTYPE grpcsharp_server_register_completion_queue( - grpc_server *server, grpc_completion_queue *cq) { + grpc_server* server, grpc_completion_queue* cq) { grpc_server_register_completion_queue(server, cq, NULL); } GPR_EXPORT int32_t GPR_CALLTYPE grpcsharp_server_add_insecure_http2_port( - grpc_server *server, const char *addr) { + grpc_server* server, const char* addr) { return grpc_server_add_insecure_http2_port(server, addr); } -GPR_EXPORT void GPR_CALLTYPE grpcsharp_server_start(grpc_server *server) { +GPR_EXPORT void GPR_CALLTYPE grpcsharp_server_start(grpc_server* server) { grpc_server_start(server); } GPR_EXPORT void GPR_CALLTYPE grpcsharp_server_shutdown_and_notify_callback( - grpc_server *server, grpc_completion_queue *cq, - grpcsharp_batch_context *ctx) { + grpc_server* server, grpc_completion_queue* cq, + grpcsharp_batch_context* ctx) { grpc_server_shutdown_and_notify(server, cq, ctx); } GPR_EXPORT void GPR_CALLTYPE -grpcsharp_server_cancel_all_calls(grpc_server *server) { +grpcsharp_server_cancel_all_calls(grpc_server* server) { grpc_server_cancel_all_calls(server); } -GPR_EXPORT void GPR_CALLTYPE grpcsharp_server_destroy(grpc_server *server) { +GPR_EXPORT void GPR_CALLTYPE grpcsharp_server_destroy(grpc_server* server) { grpc_server_destroy(server); } GPR_EXPORT grpc_call_error GPR_CALLTYPE -grpcsharp_server_request_call(grpc_server *server, grpc_completion_queue *cq, - grpcsharp_request_call_context *ctx) { +grpcsharp_server_request_call(grpc_server* server, grpc_completion_queue* cq, + grpcsharp_request_call_context* ctx) { return grpc_server_request_call(server, &(ctx->call), &(ctx->call_details), &(ctx->request_metadata), cq, cq, ctx); } /* Security */ -static char *default_pem_root_certs = NULL; +static char* default_pem_root_certs = NULL; static grpc_ssl_roots_override_result override_ssl_roots_handler( - char **pem_root_certs) { + char** pem_root_certs) { if (!default_pem_root_certs) { *pem_root_certs = NULL; return GRPC_SSL_ROOTS_OVERRIDE_FAIL_PERMANENTLY; @@ -909,7 +913,7 @@ static grpc_ssl_roots_override_result override_ssl_roots_handler( } GPR_EXPORT void GPR_CALLTYPE -grpcsharp_override_default_ssl_roots(const char *pem_root_certs) { +grpcsharp_override_default_ssl_roots(const char* pem_root_certs) { /* * This currently wastes ~300kB of memory by keeping a copy of roots * in a static variable, but for desktop/server use, the overhead @@ -920,10 +924,10 @@ grpcsharp_override_default_ssl_roots(const char *pem_root_certs) { grpc_set_ssl_roots_override_callback(override_ssl_roots_handler); } -GPR_EXPORT grpc_channel_credentials *GPR_CALLTYPE -grpcsharp_ssl_credentials_create(const char *pem_root_certs, - const char *key_cert_pair_cert_chain, - const char *key_cert_pair_private_key) { +GPR_EXPORT grpc_channel_credentials* GPR_CALLTYPE +grpcsharp_ssl_credentials_create(const char* pem_root_certs, + const char* key_cert_pair_cert_chain, + const char* key_cert_pair_private_key) { grpc_ssl_pem_key_cert_pair key_cert_pair; if (key_cert_pair_cert_chain || key_cert_pair_private_key) { key_cert_pair.cert_chain = key_cert_pair_cert_chain; @@ -937,29 +941,29 @@ grpcsharp_ssl_credentials_create(const char *pem_root_certs, } GPR_EXPORT void GPR_CALLTYPE -grpcsharp_channel_credentials_release(grpc_channel_credentials *creds) { +grpcsharp_channel_credentials_release(grpc_channel_credentials* creds) { grpc_channel_credentials_release(creds); } GPR_EXPORT void GPR_CALLTYPE -grpcsharp_call_credentials_release(grpc_call_credentials *creds) { +grpcsharp_call_credentials_release(grpc_call_credentials* creds) { grpc_call_credentials_release(creds); } -GPR_EXPORT grpc_channel *GPR_CALLTYPE grpcsharp_secure_channel_create( - grpc_channel_credentials *creds, const char *target, - const grpc_channel_args *args) { +GPR_EXPORT grpc_channel* GPR_CALLTYPE grpcsharp_secure_channel_create( + grpc_channel_credentials* creds, const char* target, + const grpc_channel_args* args) { return grpc_secure_channel_create(creds, target, args, NULL); } -GPR_EXPORT grpc_server_credentials *GPR_CALLTYPE +GPR_EXPORT grpc_server_credentials* GPR_CALLTYPE grpcsharp_ssl_server_credentials_create( - const char *pem_root_certs, const char **key_cert_pair_cert_chain_array, - const char **key_cert_pair_private_key_array, size_t num_key_cert_pairs, + const char* pem_root_certs, const char** key_cert_pair_cert_chain_array, + const char** key_cert_pair_private_key_array, size_t num_key_cert_pairs, int force_client_auth) { size_t i; - grpc_server_credentials *creds; - grpc_ssl_pem_key_cert_pair *key_cert_pairs = + grpc_server_credentials* creds; + grpc_ssl_pem_key_cert_pair* key_cert_pairs = gpr_malloc(sizeof(grpc_ssl_pem_key_cert_pair) * num_key_cert_pairs); memset(key_cert_pairs, 0, sizeof(grpc_ssl_pem_key_cert_pair) * num_key_cert_pairs); @@ -982,35 +986,35 @@ grpcsharp_ssl_server_credentials_create( } GPR_EXPORT void GPR_CALLTYPE -grpcsharp_server_credentials_release(grpc_server_credentials *creds) { +grpcsharp_server_credentials_release(grpc_server_credentials* creds) { grpc_server_credentials_release(creds); } GPR_EXPORT int32_t GPR_CALLTYPE grpcsharp_server_add_secure_http2_port( - grpc_server *server, const char *addr, grpc_server_credentials *creds) { + grpc_server* server, const char* addr, grpc_server_credentials* creds) { return grpc_server_add_secure_http2_port(server, addr, creds); } -GPR_EXPORT grpc_channel_credentials *GPR_CALLTYPE +GPR_EXPORT grpc_channel_credentials* GPR_CALLTYPE grpcsharp_composite_channel_credentials_create( - grpc_channel_credentials *channel_creds, - grpc_call_credentials *call_creds) { + grpc_channel_credentials* channel_creds, + grpc_call_credentials* call_creds) { return grpc_composite_channel_credentials_create(channel_creds, call_creds, NULL); } -GPR_EXPORT grpc_call_credentials *GPR_CALLTYPE -grpcsharp_composite_call_credentials_create(grpc_call_credentials *creds1, - grpc_call_credentials *creds2) { +GPR_EXPORT grpc_call_credentials* GPR_CALLTYPE +grpcsharp_composite_call_credentials_create(grpc_call_credentials* creds1, + grpc_call_credentials* creds2) { return grpc_composite_call_credentials_create(creds1, creds2, NULL); } /* Metadata credentials plugin */ GPR_EXPORT void GPR_CALLTYPE grpcsharp_metadata_credentials_notify_from_plugin( - grpc_credentials_plugin_metadata_cb cb, void *user_data, - grpc_metadata_array *metadata, grpc_status_code status, - const char *error_details) { + grpc_credentials_plugin_metadata_cb cb, void* user_data, + grpc_metadata_array* metadata, grpc_status_code status, + const char* error_details) { if (metadata) { cb(user_data, metadata->metadata, metadata->count, status, error_details); } else { @@ -1018,17 +1022,17 @@ GPR_EXPORT void GPR_CALLTYPE grpcsharp_metadata_credentials_notify_from_plugin( } } -typedef void(GPR_CALLTYPE *grpcsharp_metadata_interceptor_func)( - void *state, const char *service_url, const char *method_name, - grpc_credentials_plugin_metadata_cb cb, void *user_data, +typedef void(GPR_CALLTYPE* grpcsharp_metadata_interceptor_func)( + void* state, const char* service_url, const char* method_name, + grpc_credentials_plugin_metadata_cb cb, void* user_data, int32_t is_destroy); static int grpcsharp_get_metadata_handler( - void *state, grpc_auth_metadata_context context, - grpc_credentials_plugin_metadata_cb cb, void *user_data, + void* state, grpc_auth_metadata_context context, + grpc_credentials_plugin_metadata_cb cb, void* user_data, grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], - size_t *num_creds_md, grpc_status_code *status, - const char **error_details) { + size_t* num_creds_md, grpc_status_code* status, + const char** error_details) { grpcsharp_metadata_interceptor_func interceptor = (grpcsharp_metadata_interceptor_func)(intptr_t)state; interceptor(state, context.service_url, context.method_name, cb, user_data, @@ -1036,61 +1040,61 @@ static int grpcsharp_get_metadata_handler( return 0; /* Asynchronous return. */ } -static void grpcsharp_metadata_credentials_destroy_handler(void *state) { +static void grpcsharp_metadata_credentials_destroy_handler(void* state) { grpcsharp_metadata_interceptor_func interceptor = (grpcsharp_metadata_interceptor_func)(intptr_t)state; interceptor(state, NULL, NULL, NULL, NULL, 1); } -GPR_EXPORT grpc_call_credentials *GPR_CALLTYPE +GPR_EXPORT grpc_call_credentials* GPR_CALLTYPE grpcsharp_metadata_credentials_create_from_plugin( grpcsharp_metadata_interceptor_func metadata_interceptor) { grpc_metadata_credentials_plugin plugin; plugin.get_metadata = grpcsharp_get_metadata_handler; plugin.destroy = grpcsharp_metadata_credentials_destroy_handler; - plugin.state = (void *)(intptr_t)metadata_interceptor; + plugin.state = (void*)(intptr_t)metadata_interceptor; plugin.type = ""; return grpc_metadata_credentials_create_from_plugin(plugin, NULL); } /* Auth context */ -GPR_EXPORT grpc_auth_context *GPR_CALLTYPE -grpcsharp_call_auth_context(grpc_call *call) { +GPR_EXPORT grpc_auth_context* GPR_CALLTYPE +grpcsharp_call_auth_context(grpc_call* call) { return grpc_call_auth_context(call); } -GPR_EXPORT const char *GPR_CALLTYPE +GPR_EXPORT const char* GPR_CALLTYPE grpcsharp_auth_context_peer_identity_property_name( - const grpc_auth_context *ctx) { + const grpc_auth_context* ctx) { return grpc_auth_context_peer_identity_property_name(ctx); } GPR_EXPORT grpc_auth_property_iterator GPR_CALLTYPE -grpcsharp_auth_context_property_iterator(const grpc_auth_context *ctx) { +grpcsharp_auth_context_property_iterator(const grpc_auth_context* ctx) { return grpc_auth_context_property_iterator(ctx); } -GPR_EXPORT const grpc_auth_property *GPR_CALLTYPE -grpcsharp_auth_property_iterator_next(grpc_auth_property_iterator *it) { +GPR_EXPORT const grpc_auth_property* GPR_CALLTYPE +grpcsharp_auth_property_iterator_next(grpc_auth_property_iterator* it) { return grpc_auth_property_iterator_next(it); } GPR_EXPORT void GPR_CALLTYPE -grpcsharp_auth_context_release(grpc_auth_context *ctx) { +grpcsharp_auth_context_release(grpc_auth_context* ctx) { grpc_auth_context_release(ctx); } /* Logging */ -typedef void(GPR_CALLTYPE *grpcsharp_log_func)(const char *file, int32_t line, +typedef void(GPR_CALLTYPE* grpcsharp_log_func)(const char* file, int32_t line, uint64_t thd_id, - const char *severity_string, - const char *msg); + const char* severity_string, + const char* msg); static grpcsharp_log_func log_func = NULL; /* Redirects gpr_log to log_func callback */ -static void grpcsharp_log_handler(gpr_log_func_args *args) { +static void grpcsharp_log_handler(gpr_log_func_args* args) { log_func(args->file, args->line, gpr_thd_currentid(), gpr_log_severity_string(args->severity), args->message); } @@ -1101,10 +1105,10 @@ GPR_EXPORT void GPR_CALLTYPE grpcsharp_redirect_log(grpcsharp_log_func func) { gpr_set_log_function(grpcsharp_log_handler); } -typedef void(GPR_CALLTYPE *test_callback_funcptr)(int32_t success); +typedef void(GPR_CALLTYPE* test_callback_funcptr)(int32_t success); /* Version info */ -GPR_EXPORT const char *GPR_CALLTYPE grpcsharp_version_string() { +GPR_EXPORT const char* GPR_CALLTYPE grpcsharp_version_string() { return grpc_version_string(); } @@ -1115,7 +1119,7 @@ grpcsharp_test_callback(test_callback_funcptr callback) { } /* For testing */ -GPR_EXPORT void *GPR_CALLTYPE grpcsharp_test_nop(void *ptr) { return ptr; } +GPR_EXPORT void* GPR_CALLTYPE grpcsharp_test_nop(void* ptr) { return ptr; } /* For testing */ GPR_EXPORT int32_t GPR_CALLTYPE grpcsharp_sizeof_grpc_event(void) { @@ -1124,7 +1128,7 @@ GPR_EXPORT int32_t GPR_CALLTYPE grpcsharp_sizeof_grpc_event(void) { /* Override a method for testing */ GPR_EXPORT void GPR_CALLTYPE -grpcsharp_test_override_method(const char *method_name, const char *variant) { +grpcsharp_test_override_method(const char* method_name, const char* variant) { if (strcmp("grpcsharp_call_start_batch", method_name) == 0) { if (strcmp("nop", variant) == 0) { g_call_start_batch_func = grpcsharp_call_start_batch_nop; diff --git a/src/csharp/generate_proto_csharp.sh b/src/csharp/generate_proto_csharp.sh index 1a1adbbae56..299dc3f8167 100755 --- a/src/csharp/generate_proto_csharp.sh +++ b/src/csharp/generate_proto_csharp.sh @@ -33,6 +33,11 @@ $PROTOC --plugin=$PLUGIN --csharp_out=$HEALTHCHECK_DIR --grpc_out=$HEALTHCHECK_D $PROTOC --plugin=$PLUGIN --csharp_out=$REFLECTION_DIR --grpc_out=$REFLECTION_DIR \ -I src/proto src/proto/grpc/reflection/v1alpha/reflection.proto +# Put grp/core/stats.proto in a subdirectory to avoid collision with grpc/testing/stats.proto +mkdir -p $TESTING_DIR/CoreStats +$PROTOC --plugin=$PLUGIN --csharp_out=$TESTING_DIR/CoreStats --grpc_out=$TESTING_DIR/CoreStats \ + -I src/proto src/proto/grpc/core/stats.proto + # TODO(jtattermusch): following .proto files are a bit broken and import paths # don't match the package names. Setting -I to the correct value src/proto # breaks the code generation. diff --git a/src/csharp/tests.json b/src/csharp/tests.json index 78410510526..82573edecb8 100644 --- a/src/csharp/tests.json +++ b/src/csharp/tests.json @@ -5,11 +5,13 @@ "Grpc.Core.Internal.Tests.ChannelArgsSafeHandleTest", "Grpc.Core.Internal.Tests.CompletionQueueEventTest", "Grpc.Core.Internal.Tests.CompletionQueueSafeHandleTest", + "Grpc.Core.Internal.Tests.DefaultObjectPoolTest", "Grpc.Core.Internal.Tests.MetadataArraySafeHandleTest", "Grpc.Core.Internal.Tests.TimespecTest", "Grpc.Core.Tests.AppDomainUnloadTest", "Grpc.Core.Tests.AuthContextTest", "Grpc.Core.Tests.AuthPropertyTest", + "Grpc.Core.Tests.CallCancellationTest", "Grpc.Core.Tests.CallCredentialsTest", "Grpc.Core.Tests.CallOptionsTest", "Grpc.Core.Tests.ChannelCredentialsTest", diff --git a/src/node/.jshintignore b/src/node/.jshintignore deleted file mode 100644 index 0a73e1e2b6b..00000000000 --- a/src/node/.jshintignore +++ /dev/null @@ -1 +0,0 @@ -**/*_pb.js \ No newline at end of file diff --git a/src/node/README.md b/src/node/README.md deleted file mode 100644 index 3b98b97879b..00000000000 --- a/src/node/README.md +++ /dev/null @@ -1,36 +0,0 @@ -[![npm](https://img.shields.io/npm/v/grpc.svg)](https://www.npmjs.com/package/grpc) -# Node.js gRPC Library - -## PREREQUISITES -- `node`: This requires `node` to be installed, version `4.0` or above. If you instead have the `nodejs` executable on Debian, you should install the [`nodejs-legacy`](https://packages.debian.org/sid/nodejs-legacy) package. - -- **Note:** If you installed `node` via a package manager and the version is still less than `4.0`, try directly installing it from [nodejs.org](https://nodejs.org). - -## INSTALLATION - -Install the gRPC NPM package - -```sh -npm install grpc -``` - -## BUILD FROM SOURCE - 1. Clone [the grpc Git Repository](https://github.com/grpc/grpc). - 2. Run `npm install --build-from-source` from the repository root. - - - **Note:** On Windows, this might fail due to [nodejs issue #4932](https://github.com/nodejs/node/issues/4932) in which case, you will see something like the following in `npm install`'s output (towards the very beginning): - - ``` - .. - Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch. - WINDOWS_BUILD_WARNING - "..\IMPORTANT: Due to https:\github.com\nodejs\node\issues\4932, to build this library on Windows, you must first remove C:\Users\jenkins\.node-gyp\4.4.0\include\node\openssl" - ... - .. - ``` - - To fix this, you will have to delete the folder `C:\Users\\.node-gyp\\include\node\openssl` and retry `npm install` - - -## TESTING -To run the test suite, simply run `npm test` in the install location. diff --git a/src/node/ext/byte_buffer.cc b/src/node/ext/byte_buffer.cc deleted file mode 100644 index 1040f70d719..00000000000 --- a/src/node/ext/byte_buffer.cc +++ /dev/null @@ -1,79 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include - -#include -#include -#include "grpc/byte_buffer_reader.h" -#include "grpc/grpc.h" -#include "grpc/slice.h" - -#include "byte_buffer.h" -#include "slice.h" - -namespace grpc { -namespace node { - -using Nan::Callback; -using Nan::MaybeLocal; - -using v8::Function; -using v8::Local; -using v8::Object; -using v8::Number; -using v8::Value; - -grpc_byte_buffer *BufferToByteBuffer(Local buffer) { - Nan::HandleScope scope; - grpc_slice slice = CreateSliceFromBuffer(buffer); - grpc_byte_buffer *byte_buffer(grpc_raw_byte_buffer_create(&slice, 1)); - grpc_slice_unref(slice); - return byte_buffer; -} - -namespace { -void delete_buffer(char *data, void *hint) { - grpc_slice *slice = static_cast(hint); - grpc_slice_unref(*slice); - delete slice; -} -} - -Local ByteBufferToBuffer(grpc_byte_buffer *buffer) { - Nan::EscapableHandleScope scope; - if (buffer == NULL) { - return scope.Escape(Nan::Null()); - } - grpc_byte_buffer_reader reader; - if (!grpc_byte_buffer_reader_init(&reader, buffer)) { - Nan::ThrowError("Error initializing byte buffer reader."); - return scope.Escape(Nan::Undefined()); - } - grpc_slice *slice = new grpc_slice; - *slice = grpc_byte_buffer_reader_readall(&reader); - grpc_byte_buffer_reader_destroy(&reader); - char *result = reinterpret_cast(GRPC_SLICE_START_PTR(*slice)); - size_t length = GRPC_SLICE_LENGTH(*slice); - Local buf = - Nan::NewBuffer(result, length, delete_buffer, slice).ToLocalChecked(); - return scope.Escape(buf); -} - -} // namespace node -} // namespace grpc diff --git a/src/node/ext/byte_buffer.h b/src/node/ext/byte_buffer.h deleted file mode 100644 index 6223147607c..00000000000 --- a/src/node/ext/byte_buffer.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef NET_GRPC_NODE_BYTE_BUFFER_H_ -#define NET_GRPC_NODE_BYTE_BUFFER_H_ - -#include - -#include -#include -#include "grpc/grpc.h" - -namespace grpc { -namespace node { - -/* Convert a Node.js Buffer to grpc_byte_buffer. Requires that - ::node::Buffer::HasInstance(buffer) */ -grpc_byte_buffer *BufferToByteBuffer(v8::Local buffer); - -/* Convert a grpc_byte_buffer to a Node.js Buffer */ -v8::Local ByteBufferToBuffer(grpc_byte_buffer *buffer); - -} // namespace node -} // namespace grpc - -#endif // NET_GRPC_NODE_BYTE_BUFFER_H_ diff --git a/src/node/ext/call.cc b/src/node/ext/call.cc deleted file mode 100644 index 26095a78f9e..00000000000 --- a/src/node/ext/call.cc +++ /dev/null @@ -1,815 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include -#include -#include - -#include - -#include "byte_buffer.h" -#include "call.h" -#include "call_credentials.h" -#include "channel.h" -#include "completion_queue.h" -#include "grpc/grpc.h" -#include "grpc/grpc_security.h" -#include "grpc/support/alloc.h" -#include "grpc/support/log.h" -#include "grpc/support/time.h" -#include "slice.h" -#include "timeval.h" - -using std::unique_ptr; -using std::shared_ptr; -using std::vector; - -namespace grpc { -namespace node { - -using Nan::Callback; -using Nan::EscapableHandleScope; -using Nan::HandleScope; -using Nan::Maybe; -using Nan::MaybeLocal; -using Nan::ObjectWrap; -using Nan::Persistent; -using Nan::Utf8String; - -using v8::Array; -using v8::Boolean; -using v8::Exception; -using v8::External; -using v8::Function; -using v8::FunctionTemplate; -using v8::Integer; -using v8::Local; -using v8::Number; -using v8::Object; -using v8::ObjectTemplate; -using v8::Uint32; -using v8::String; -using v8::Value; - -Callback *Call::constructor; -Persistent Call::fun_tpl; - -/** - * Helper function for throwing errors with a grpc_call_error value. - * Modified from the answer by Gus Goose to - * http://stackoverflow.com/questions/31794200. - */ -Local nanErrorWithCode(const char *msg, grpc_call_error code) { - EscapableHandleScope scope; - Local err = Nan::Error(msg).As(); - Nan::Set(err, Nan::New("code").ToLocalChecked(), Nan::New(code)); - return scope.Escape(err); -} - -bool CreateMetadataArray(Local metadata, grpc_metadata_array *array) { - HandleScope scope; - Local keys = Nan::GetOwnPropertyNames(metadata).ToLocalChecked(); - for (unsigned int i = 0; i < keys->Length(); i++) { - Local current_key = - Nan::To(Nan::Get(keys, i).ToLocalChecked()).ToLocalChecked(); - Local value_array = Nan::Get(metadata, current_key).ToLocalChecked(); - if (!value_array->IsArray()) { - return false; - } - array->capacity += Local::Cast(value_array)->Length(); - } - array->metadata = reinterpret_cast( - gpr_zalloc(array->capacity * sizeof(grpc_metadata))); - for (unsigned int i = 0; i < keys->Length(); i++) { - Local current_key(Nan::To(keys->Get(i)).ToLocalChecked()); - Local values = - Local::Cast(Nan::Get(metadata, current_key).ToLocalChecked()); - grpc_slice key_slice = CreateSliceFromString(current_key); - grpc_slice key_intern_slice = grpc_slice_intern(key_slice); - grpc_slice_unref(key_slice); - for (unsigned int j = 0; j < values->Length(); j++) { - Local value = Nan::Get(values, j).ToLocalChecked(); - grpc_metadata *current = &array->metadata[array->count]; - current->key = key_intern_slice; - // Only allow binary headers for "-bin" keys - if (grpc_is_binary_header(key_intern_slice)) { - if (::node::Buffer::HasInstance(value)) { - current->value = CreateSliceFromBuffer(value); - } else { - return false; - } - } else { - if (value->IsString()) { - Local string_value = Nan::To(value).ToLocalChecked(); - current->value = CreateSliceFromString(string_value); - } else { - return false; - } - } - array->count += 1; - } - } - return true; -} - -void DestroyMetadataArray(grpc_metadata_array *array) { - for (size_t i = 0; i < array->count; i++) { - // Don't unref keys because they are interned - grpc_slice_unref(array->metadata[i].value); - } - grpc_metadata_array_destroy(array); -} - -Local ParseMetadata(const grpc_metadata_array *metadata_array) { - EscapableHandleScope scope; - grpc_metadata *metadata_elements = metadata_array->metadata; - size_t length = metadata_array->count; - Local metadata_object = Nan::New(); - for (unsigned int i = 0; i < length; i++) { - grpc_metadata *elem = &metadata_elements[i]; - // TODO(murgatroid99): Use zero-copy string construction instead - Local key_string = CopyStringFromSlice(elem->key); - Local array; - MaybeLocal maybe_array = Nan::Get(metadata_object, key_string); - if (maybe_array.IsEmpty() || !maybe_array.ToLocalChecked()->IsArray()) { - array = Nan::New(0); - Nan::Set(metadata_object, key_string, array); - } else { - array = Local::Cast(maybe_array.ToLocalChecked()); - } - if (grpc_is_binary_header(elem->key)) { - Nan::Set(array, array->Length(), CreateBufferFromSlice(elem->value)); - } else { - // TODO(murgatroid99): Use zero-copy string construction instead - Nan::Set(array, array->Length(), CopyStringFromSlice(elem->value)); - } - } - return scope.Escape(metadata_object); -} - -Local Op::GetOpType() const { - EscapableHandleScope scope; - return scope.Escape(Nan::New(GetTypeString()).ToLocalChecked()); -} - -Op::~Op() {} - -class SendMetadataOp : public Op { - public: - SendMetadataOp() { grpc_metadata_array_init(&send_metadata); } - ~SendMetadataOp() { DestroyMetadataArray(&send_metadata); } - Local GetNodeValue() const { - EscapableHandleScope scope; - return scope.Escape(Nan::True()); - } - bool ParseOp(Local value, grpc_op *out) { - if (!value->IsObject()) { - return false; - } - MaybeLocal maybe_metadata = Nan::To(value); - if (maybe_metadata.IsEmpty()) { - return false; - } - if (!CreateMetadataArray(maybe_metadata.ToLocalChecked(), &send_metadata)) { - return false; - } - out->data.send_initial_metadata.count = send_metadata.count; - out->data.send_initial_metadata.metadata = send_metadata.metadata; - return true; - } - bool IsFinalOp() { return false; } - void OnComplete(bool success) {} - - protected: - std::string GetTypeString() const { return "send_metadata"; } - - private: - grpc_metadata_array send_metadata; -}; - -class SendMessageOp : public Op { - public: - SendMessageOp() { send_message = NULL; } - ~SendMessageOp() { - if (send_message != NULL) { - grpc_byte_buffer_destroy(send_message); - } - } - Local GetNodeValue() const { - EscapableHandleScope scope; - return scope.Escape(Nan::True()); - } - bool ParseOp(Local value, grpc_op *out) { - if (!::node::Buffer::HasInstance(value)) { - return false; - } - Local object_value = Nan::To(value).ToLocalChecked(); - MaybeLocal maybe_flag_value = - Nan::Get(object_value, Nan::New("grpcWriteFlags").ToLocalChecked()); - if (!maybe_flag_value.IsEmpty()) { - Local flag_value = maybe_flag_value.ToLocalChecked(); - if (flag_value->IsUint32()) { - Maybe maybe_flag = Nan::To(flag_value); - out->flags = maybe_flag.FromMaybe(0) & GRPC_WRITE_USED_MASK; - } - } - send_message = BufferToByteBuffer(value); - out->data.send_message.send_message = send_message; - return true; - } - - bool IsFinalOp() { return false; } - void OnComplete(bool success) {} - - protected: - std::string GetTypeString() const { return "send_message"; } - - private: - grpc_byte_buffer *send_message; -}; - -class SendClientCloseOp : public Op { - public: - Local GetNodeValue() const { - EscapableHandleScope scope; - return scope.Escape(Nan::True()); - } - - bool ParseOp(Local value, grpc_op *out) { return true; } - bool IsFinalOp() { return false; } - void OnComplete(bool success) {} - - protected: - std::string GetTypeString() const { return "client_close"; } -}; - -class SendServerStatusOp : public Op { - public: - SendServerStatusOp() { - details = grpc_empty_slice(); - grpc_metadata_array_init(&status_metadata); - } - ~SendServerStatusOp() { - grpc_slice_unref(details); - DestroyMetadataArray(&status_metadata); - } - Local GetNodeValue() const { - EscapableHandleScope scope; - return scope.Escape(Nan::True()); - } - bool ParseOp(Local value, grpc_op *out) { - if (!value->IsObject()) { - return false; - } - Local server_status = Nan::To(value).ToLocalChecked(); - MaybeLocal maybe_metadata = - Nan::Get(server_status, Nan::New("metadata").ToLocalChecked()); - if (maybe_metadata.IsEmpty()) { - return false; - } - if (!maybe_metadata.ToLocalChecked()->IsObject()) { - return false; - } - Local metadata = - Nan::To(maybe_metadata.ToLocalChecked()).ToLocalChecked(); - MaybeLocal maybe_code = - Nan::Get(server_status, Nan::New("code").ToLocalChecked()); - if (maybe_code.IsEmpty()) { - return false; - } - if (!maybe_code.ToLocalChecked()->IsUint32()) { - return false; - } - uint32_t code = Nan::To(maybe_code.ToLocalChecked()).FromJust(); - MaybeLocal maybe_details = - Nan::Get(server_status, Nan::New("details").ToLocalChecked()); - if (maybe_details.IsEmpty()) { - return false; - } - if (!maybe_details.ToLocalChecked()->IsString()) { - return false; - } - Local details = - Nan::To(maybe_details.ToLocalChecked()).ToLocalChecked(); - if (!CreateMetadataArray(metadata, &status_metadata)) { - return false; - } - out->data.send_status_from_server.trailing_metadata_count = - status_metadata.count; - out->data.send_status_from_server.trailing_metadata = - status_metadata.metadata; - out->data.send_status_from_server.status = - static_cast(code); - this->details = CreateSliceFromString(details); - out->data.send_status_from_server.status_details = &this->details; - return true; - } - bool IsFinalOp() { return true; } - void OnComplete(bool success) {} - - protected: - std::string GetTypeString() const { return "send_status"; } - - private: - grpc_slice details; - grpc_metadata_array status_metadata; -}; - -class GetMetadataOp : public Op { - public: - GetMetadataOp() { grpc_metadata_array_init(&recv_metadata); } - - ~GetMetadataOp() { grpc_metadata_array_destroy(&recv_metadata); } - - Local GetNodeValue() const { - EscapableHandleScope scope; - return scope.Escape(ParseMetadata(&recv_metadata)); - } - - bool ParseOp(Local value, grpc_op *out) { - out->data.recv_initial_metadata.recv_initial_metadata = &recv_metadata; - return true; - } - bool IsFinalOp() { return false; } - void OnComplete(bool success) {} - - protected: - std::string GetTypeString() const { return "metadata"; } - - private: - grpc_metadata_array recv_metadata; -}; - -class ReadMessageOp : public Op { - public: - ReadMessageOp() { recv_message = NULL; } - ~ReadMessageOp() { - if (recv_message != NULL) { - grpc_byte_buffer_destroy(recv_message); - } - } - Local GetNodeValue() const { - EscapableHandleScope scope; - return scope.Escape(ByteBufferToBuffer(recv_message)); - } - - bool ParseOp(Local value, grpc_op *out) { - out->data.recv_message.recv_message = &recv_message; - return true; - } - bool IsFinalOp() { return false; } - void OnComplete(bool success) {} - - protected: - std::string GetTypeString() const { return "read"; } - - private: - grpc_byte_buffer *recv_message; -}; - -class ClientStatusOp : public Op { - public: - ClientStatusOp() { - grpc_metadata_array_init(&metadata_array); - status_details = grpc_empty_slice(); - } - - ~ClientStatusOp() { - grpc_metadata_array_destroy(&metadata_array); - grpc_slice_unref(status_details); - } - - bool ParseOp(Local value, grpc_op *out) { - out->data.recv_status_on_client.trailing_metadata = &metadata_array; - out->data.recv_status_on_client.status = &status; - out->data.recv_status_on_client.status_details = &status_details; - return true; - } - - Local GetNodeValue() const { - EscapableHandleScope scope; - Local status_obj = Nan::New(); - Nan::Set(status_obj, Nan::New("code").ToLocalChecked(), - Nan::New(status)); - Nan::Set(status_obj, Nan::New("details").ToLocalChecked(), - CopyStringFromSlice(status_details)); - Nan::Set(status_obj, Nan::New("metadata").ToLocalChecked(), - ParseMetadata(&metadata_array)); - return scope.Escape(status_obj); - } - bool IsFinalOp() { return true; } - void OnComplete(bool success) {} - - protected: - std::string GetTypeString() const { return "status"; } - - private: - grpc_metadata_array metadata_array; - grpc_status_code status; - grpc_slice status_details; -}; - -class ServerCloseResponseOp : public Op { - public: - Local GetNodeValue() const { - EscapableHandleScope scope; - return scope.Escape(Nan::New(cancelled)); - } - - bool ParseOp(Local value, grpc_op *out) { - out->data.recv_close_on_server.cancelled = &cancelled; - return true; - } - bool IsFinalOp() { return false; } - void OnComplete(bool success) {} - - protected: - std::string GetTypeString() const { return "cancelled"; } - - private: - int cancelled; -}; - -tag::tag(Callback *callback, OpVec *ops, Call *call, Local call_value) - : callback(callback), ops(ops), call(call) { - HandleScope scope; - call_persist.Reset(call_value); -} - -tag::~tag() { - delete callback; - delete ops; -} - -void CompleteTag(void *tag, const char *error_message) { - HandleScope scope; - struct tag *tag_struct = reinterpret_cast(tag); - Callback *callback = tag_struct->callback; - if (error_message == NULL) { - Local tag_obj = Nan::New(); - for (vector >::iterator it = tag_struct->ops->begin(); - it != tag_struct->ops->end(); ++it) { - Op *op_ptr = it->get(); - Nan::Set(tag_obj, op_ptr->GetOpType(), op_ptr->GetNodeValue()); - } - Local argv[] = {Nan::Null(), tag_obj}; - callback->Call(2, argv); - } else { - Local argv[] = {Nan::Error(error_message)}; - callback->Call(1, argv); - } - bool success = (error_message == NULL); - bool is_final_op = false; - for (vector >::iterator it = tag_struct->ops->begin(); - it != tag_struct->ops->end(); ++it) { - Op *op_ptr = it->get(); - op_ptr->OnComplete(success); - if (op_ptr->IsFinalOp()) { - is_final_op = true; - } - } - if (tag_struct->call == NULL) { - return; - } - tag_struct->call->CompleteBatch(is_final_op); -} - -void DestroyTag(void *tag) { - struct tag *tag_struct = reinterpret_cast(tag); - delete tag_struct; -} - -void Call::DestroyCall() { - if (this->wrapped_call != NULL) { - grpc_call_unref(this->wrapped_call); - this->wrapped_call = NULL; - } -} - -Call::Call(grpc_call *call) - : wrapped_call(call), pending_batches(0), has_final_op_completed(false) { - peer = grpc_call_get_peer(call); -} - -Call::~Call() { - DestroyCall(); - gpr_free(peer); -} - -void Call::Init(Local exports) { - HandleScope scope; - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("Call").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - Nan::SetPrototypeMethod(tpl, "startBatch", StartBatch); - Nan::SetPrototypeMethod(tpl, "cancel", Cancel); - Nan::SetPrototypeMethod(tpl, "cancelWithStatus", CancelWithStatus); - Nan::SetPrototypeMethod(tpl, "getPeer", GetPeer); - Nan::SetPrototypeMethod(tpl, "setCredentials", SetCredentials); - fun_tpl.Reset(tpl); - Local ctr = Nan::GetFunction(tpl).ToLocalChecked(); - Nan::Set(exports, Nan::New("Call").ToLocalChecked(), ctr); - constructor = new Callback(ctr); -} - -bool Call::HasInstance(Local val) { - HandleScope scope; - return Nan::New(fun_tpl)->HasInstance(val); -} - -Local Call::WrapStruct(grpc_call *call) { - EscapableHandleScope scope; - if (call == NULL) { - return scope.Escape(Nan::Null()); - } - const int argc = 1; - Local argv[argc] = { - Nan::New(reinterpret_cast(call))}; - MaybeLocal maybe_instance = - Nan::NewInstance(constructor->GetFunction(), argc, argv); - if (maybe_instance.IsEmpty()) { - return scope.Escape(Nan::Null()); - } else { - return scope.Escape(maybe_instance.ToLocalChecked()); - } -} - -void Call::CompleteBatch(bool is_final_op) { - if (is_final_op) { - this->has_final_op_completed = true; - } - this->pending_batches--; - if (this->has_final_op_completed && this->pending_batches == 0) { - this->DestroyCall(); - } -} - -NAN_METHOD(Call::New) { - /* Arguments: - * 0: Channel to make the call on - * 1: Method - * 2: Deadline - * 3: host - * 4: parent Call - * 5: propagation flags - */ - if (info.IsConstructCall()) { - Call *call; - if (info[0]->IsExternal()) { - Local ext = info[0].As(); - // This option is used for wrapping an existing call - grpc_call *call_value = reinterpret_cast(ext->Value()); - call = new Call(call_value); - } else { - if (!Channel::HasInstance(info[0])) { - return Nan::ThrowTypeError("Call's first argument must be a Channel"); - } - if (!info[1]->IsString()) { - return Nan::ThrowTypeError("Call's second argument must be a string"); - } - if (!(info[2]->IsNumber() || info[2]->IsDate())) { - return Nan::ThrowTypeError( - "Call's third argument must be a date or a number"); - } - // These arguments are at the end because they are optional - grpc_call *parent_call = NULL; - if (Call::HasInstance(info[4])) { - Call *parent_obj = - ObjectWrap::Unwrap(Nan::To(info[4]).ToLocalChecked()); - parent_call = parent_obj->wrapped_call; - } else if (!(info[4]->IsUndefined() || info[4]->IsNull())) { - return Nan::ThrowTypeError( - "Call's fifth argument must be another call, if provided"); - } - uint32_t propagate_flags = GRPC_PROPAGATE_DEFAULTS; - if (info[5]->IsUint32()) { - propagate_flags = Nan::To(info[5]).FromJust(); - } else if (!(info[5]->IsUndefined() || info[5]->IsNull())) { - return Nan::ThrowTypeError( - "Call's sixth argument must be propagate flags, if provided"); - } - Local channel_object = Nan::To(info[0]).ToLocalChecked(); - Channel *channel = ObjectWrap::Unwrap(channel_object); - if (channel->GetWrappedChannel() == NULL) { - return Nan::ThrowError("Call cannot be created from a closed channel"); - } - double deadline = Nan::To(info[2]).FromJust(); - grpc_channel *wrapped_channel = channel->GetWrappedChannel(); - grpc_call *wrapped_call; - grpc_slice method = - CreateSliceFromString(Nan::To(info[1]).ToLocalChecked()); - if (info[3]->IsString()) { - grpc_slice *host = new grpc_slice; - *host = - CreateSliceFromString(Nan::To(info[3]).ToLocalChecked()); - wrapped_call = grpc_channel_create_call( - wrapped_channel, parent_call, propagate_flags, GetCompletionQueue(), - method, host, MillisecondsToTimespec(deadline), NULL); - delete host; - } else if (info[3]->IsUndefined() || info[3]->IsNull()) { - wrapped_call = grpc_channel_create_call( - wrapped_channel, parent_call, propagate_flags, GetCompletionQueue(), - method, NULL, MillisecondsToTimespec(deadline), NULL); - } else { - return Nan::ThrowTypeError("Call's fourth argument must be a string"); - } - grpc_slice_unref(method); - call = new Call(wrapped_call); - Nan::Set(info.This(), Nan::New("channel_").ToLocalChecked(), - channel_object); - } - call->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } else { - const int argc = 4; - Local argv[argc] = {info[0], info[1], info[2], info[3]}; - MaybeLocal maybe_instance = - Nan::NewInstance(constructor->GetFunction(), argc, argv); - if (maybe_instance.IsEmpty()) { - // There's probably a pending exception - return; - } else { - info.GetReturnValue().Set(maybe_instance.ToLocalChecked()); - } - } -} - -NAN_METHOD(Call::StartBatch) { - if (!Call::HasInstance(info.This())) { - return Nan::ThrowTypeError("startBatch can only be called on Call objects"); - } - if (!info[0]->IsObject()) { - return Nan::ThrowError("startBatch's first argument must be an object"); - } - if (!info[1]->IsFunction()) { - return Nan::ThrowError("startBatch's second argument must be a callback"); - } - Local callback_func = info[1].As(); - Call *call = ObjectWrap::Unwrap(info.This()); - if (call->wrapped_call == NULL) { - /* This implies that the call has completed and has been destroyed. To - * emulate - * previous behavior, we should call the callback immediately with an error, - * as though the batch had failed in core */ - Local argv[] = { - Nan::Error("The async function failed because the call has completed")}; - Nan::Call(callback_func, Nan::New(), 1, argv); - return; - } - Local obj = Nan::To(info[0]).ToLocalChecked(); - Local keys = Nan::GetOwnPropertyNames(obj).ToLocalChecked(); - size_t nops = keys->Length(); - vector ops(nops); - unique_ptr op_vector(new OpVec()); - for (unsigned int i = 0; i < nops; i++) { - unique_ptr op; - MaybeLocal maybe_key = Nan::Get(keys, i); - if (maybe_key.IsEmpty() || (!maybe_key.ToLocalChecked()->IsUint32())) { - return Nan::ThrowError( - "startBatch's first argument's keys must be integers"); - } - uint32_t type = Nan::To(maybe_key.ToLocalChecked()).FromJust(); - ops[i].op = static_cast(type); - ops[i].flags = 0; - ops[i].reserved = NULL; - switch (type) { - case GRPC_OP_SEND_INITIAL_METADATA: - op.reset(new SendMetadataOp()); - break; - case GRPC_OP_SEND_MESSAGE: - op.reset(new SendMessageOp()); - break; - case GRPC_OP_SEND_CLOSE_FROM_CLIENT: - op.reset(new SendClientCloseOp()); - break; - case GRPC_OP_SEND_STATUS_FROM_SERVER: - op.reset(new SendServerStatusOp()); - break; - case GRPC_OP_RECV_INITIAL_METADATA: - op.reset(new GetMetadataOp()); - break; - case GRPC_OP_RECV_MESSAGE: - op.reset(new ReadMessageOp()); - break; - case GRPC_OP_RECV_STATUS_ON_CLIENT: - op.reset(new ClientStatusOp()); - break; - case GRPC_OP_RECV_CLOSE_ON_SERVER: - op.reset(new ServerCloseResponseOp()); - break; - default: - return Nan::ThrowError("Argument object had an unrecognized key"); - } - if (!op->ParseOp(obj->Get(type), &ops[i])) { - return Nan::ThrowTypeError("Incorrectly typed arguments to startBatch"); - } - op_vector->push_back(std::move(op)); - } - Callback *callback = new Callback(callback_func); - grpc_call_error error = grpc_call_start_batch( - call->wrapped_call, &ops[0], nops, - new struct tag(callback, op_vector.release(), call, info.This()), NULL); - if (error != GRPC_CALL_OK) { - return Nan::ThrowError(nanErrorWithCode("startBatch failed", error)); - } - call->pending_batches++; - CompletionQueueNext(); -} - -NAN_METHOD(Call::Cancel) { - if (!Call::HasInstance(info.This())) { - return Nan::ThrowTypeError("cancel can only be called on Call objects"); - } - Call *call = ObjectWrap::Unwrap(info.This()); - if (call->wrapped_call == NULL) { - /* Cancel is supposed to be idempotent. If the call has already finished, - * cancel should just complete silently */ - return; - } - grpc_call_error error = grpc_call_cancel(call->wrapped_call, NULL); - if (error != GRPC_CALL_OK) { - return Nan::ThrowError(nanErrorWithCode("cancel failed", error)); - } -} - -NAN_METHOD(Call::CancelWithStatus) { - Nan::HandleScope scope; - if (!HasInstance(info.This())) { - return Nan::ThrowTypeError("cancel can only be called on Call objects"); - } - if (!info[0]->IsUint32()) { - return Nan::ThrowTypeError( - "cancelWithStatus's first argument must be a status code"); - } - if (!info[1]->IsString()) { - return Nan::ThrowTypeError( - "cancelWithStatus's second argument must be a string"); - } - Call *call = ObjectWrap::Unwrap(info.This()); - if (call->wrapped_call == NULL) { - /* Cancel is supposed to be idempotent. If the call has already finished, - * cancel should just complete silently */ - return; - } - grpc_status_code code = - static_cast(Nan::To(info[0]).FromJust()); - if (code == GRPC_STATUS_OK) { - return Nan::ThrowRangeError( - "cancelWithStatus cannot be called with OK status"); - } - Utf8String details(info[1]); - grpc_call_cancel_with_status(call->wrapped_call, code, *details, NULL); -} - -NAN_METHOD(Call::GetPeer) { - Nan::HandleScope scope; - if (!HasInstance(info.This())) { - return Nan::ThrowTypeError("getPeer can only be called on Call objects"); - } - Call *call = ObjectWrap::Unwrap(info.This()); - Local peer_value = Nan::New(call->peer).ToLocalChecked(); - info.GetReturnValue().Set(peer_value); -} - -NAN_METHOD(Call::SetCredentials) { - Nan::HandleScope scope; - if (!HasInstance(info.This())) { - return Nan::ThrowTypeError( - "setCredentials can only be called on Call objects"); - } - if (!CallCredentials::HasInstance(info[0])) { - return Nan::ThrowTypeError( - "setCredentials' first argument must be a CallCredentials"); - } - Call *call = ObjectWrap::Unwrap(info.This()); - if (call->wrapped_call == NULL) { - return Nan::ThrowError( - "Cannot set credentials on a call that has already started"); - } - CallCredentials *creds_object = ObjectWrap::Unwrap( - Nan::To(info[0]).ToLocalChecked()); - grpc_call_credentials *creds = creds_object->GetWrappedCredentials(); - grpc_call_error error = GRPC_CALL_ERROR; - if (creds) { - error = grpc_call_set_credentials(call->wrapped_call, creds); - } - info.GetReturnValue().Set(Nan::New(error)); -} - -} // namespace node -} // namespace grpc diff --git a/src/node/ext/call.h b/src/node/ext/call.h deleted file mode 100644 index 50248c0bc64..00000000000 --- a/src/node/ext/call.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef NET_GRPC_NODE_CALL_H_ -#define NET_GRPC_NODE_CALL_H_ - -#include -#include - -#include -#include -#include "grpc/grpc.h" -#include "grpc/support/log.h" - -#include "channel.h" - -namespace grpc { -namespace node { - -using std::unique_ptr; -using std::shared_ptr; - -v8::Local nanErrorWithCode(const char *msg, grpc_call_error code); - -v8::Local ParseMetadata(const grpc_metadata_array *metadata_array); - -bool CreateMetadataArray(v8::Local metadata, - grpc_metadata_array *array); - -void DestroyMetadataArray(grpc_metadata_array *array); - -/* Wrapper class for grpc_call structs. */ -class Call : public Nan::ObjectWrap { - public: - static void Init(v8::Local exports); - static bool HasInstance(v8::Local val); - /* Wrap a grpc_call struct in a javascript object */ - static v8::Local WrapStruct(grpc_call *call); - - void CompleteBatch(bool is_final_op); - - private: - explicit Call(grpc_call *call); - ~Call(); - - // Prevent copying - Call(const Call &); - Call &operator=(const Call &); - - void DestroyCall(); - - static NAN_METHOD(New); - static NAN_METHOD(StartBatch); - static NAN_METHOD(Cancel); - static NAN_METHOD(CancelWithStatus); - static NAN_METHOD(GetPeer); - static NAN_METHOD(SetCredentials); - static Nan::Callback *constructor; - // Used for typechecking instances of this javascript class - static Nan::Persistent fun_tpl; - - grpc_call *wrapped_call; - // The number of ops that were started but not completed on this call - int pending_batches; - /* Indicates whether the "final" op on a call has completed. For a client - call, this is GRPC_OP_RECV_STATUS_ON_CLIENT and for a server call, this - is GRPC_OP_SEND_STATUS_FROM_SERVER */ - bool has_final_op_completed; - char *peer; -}; - -class Op { - public: - virtual v8::Local GetNodeValue() const = 0; - virtual bool ParseOp(v8::Local value, grpc_op *out) = 0; - virtual ~Op(); - v8::Local GetOpType() const; - virtual bool IsFinalOp() = 0; - virtual void OnComplete(bool success) = 0; - - protected: - virtual std::string GetTypeString() const = 0; -}; - -typedef std::vector> OpVec; -struct tag { - tag(Nan::Callback *callback, OpVec *ops, Call *call, - v8::Local call_value); - ~tag(); - Nan::Callback *callback; - OpVec *ops; - Call *call; - Nan::Persistent> - call_persist; -}; - -void DestroyTag(void *tag); - -void CompleteTag(void *tag, const char *error_message); - -} // namespace node -} // namespace grpc - -#endif // NET_GRPC_NODE_CALL_H_ diff --git a/src/node/ext/call_credentials.cc b/src/node/ext/call_credentials.cc deleted file mode 100644 index 0644a812e9a..00000000000 --- a/src/node/ext/call_credentials.cc +++ /dev/null @@ -1,276 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include -#include -#include - -#include - -#include "call.h" -#include "call_credentials.h" -#include "grpc/grpc.h" -#include "grpc/grpc_security.h" -#include "grpc/support/log.h" - -namespace grpc { -namespace node { - -using Nan::Callback; -using Nan::EscapableHandleScope; -using Nan::HandleScope; -using Nan::Maybe; -using Nan::MaybeLocal; -using Nan::ObjectWrap; -using Nan::Persistent; -using Nan::Utf8String; - -using v8::Exception; -using v8::External; -using v8::Function; -using v8::FunctionTemplate; -using v8::Integer; -using v8::Local; -using v8::Object; -using v8::ObjectTemplate; -using v8::Value; - -Nan::Callback *CallCredentials::constructor; -Persistent CallCredentials::fun_tpl; - -static Callback *plugin_callback; - -CallCredentials::CallCredentials(grpc_call_credentials *credentials) - : wrapped_credentials(credentials) {} - -CallCredentials::~CallCredentials() { - grpc_call_credentials_release(wrapped_credentials); -} - -void CallCredentials::Init(Local exports) { - HandleScope scope; - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("CallCredentials").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - Nan::SetPrototypeMethod(tpl, "compose", Compose); - fun_tpl.Reset(tpl); - Local ctr = Nan::GetFunction(tpl).ToLocalChecked(); - Nan::Set(ctr, Nan::New("createFromPlugin").ToLocalChecked(), - Nan::GetFunction(Nan::New(CreateFromPlugin)) - .ToLocalChecked()); - Nan::Set(exports, Nan::New("CallCredentials").ToLocalChecked(), ctr); - constructor = new Nan::Callback(ctr); - - Local callback_tpl = - Nan::New(PluginCallback); - plugin_callback = - new Callback(Nan::GetFunction(callback_tpl).ToLocalChecked()); -} - -bool CallCredentials::HasInstance(Local val) { - HandleScope scope; - return Nan::New(fun_tpl)->HasInstance(val); -} - -Local CallCredentials::WrapStruct(grpc_call_credentials *credentials) { - EscapableHandleScope scope; - const int argc = 1; - if (credentials == NULL) { - return scope.Escape(Nan::Null()); - } - Local argv[argc] = { - Nan::New(reinterpret_cast(credentials))}; - MaybeLocal maybe_instance = - Nan::NewInstance(constructor->GetFunction(), argc, argv); - if (maybe_instance.IsEmpty()) { - return scope.Escape(Nan::Null()); - } else { - return scope.Escape(maybe_instance.ToLocalChecked()); - } -} - -grpc_call_credentials *CallCredentials::GetWrappedCredentials() { - return wrapped_credentials; -} - -NAN_METHOD(CallCredentials::New) { - if (info.IsConstructCall()) { - if (!info[0]->IsExternal()) { - return Nan::ThrowTypeError( - "CallCredentials can only be created with the provided functions"); - } - Local ext = info[0].As(); - grpc_call_credentials *creds_value = - reinterpret_cast(ext->Value()); - CallCredentials *credentials = new CallCredentials(creds_value); - credentials->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - return; - } else { - // This should never be called directly - return Nan::ThrowTypeError( - "CallCredentials can only be created with the provided functions"); - } -} - -NAN_METHOD(CallCredentials::Compose) { - if (!CallCredentials::HasInstance(info.This())) { - return Nan::ThrowTypeError( - "compose can only be called on CallCredentials objects"); - } - if (!CallCredentials::HasInstance(info[0])) { - return Nan::ThrowTypeError( - "compose's first argument must be a CallCredentials object"); - } - CallCredentials *self = ObjectWrap::Unwrap(info.This()); - CallCredentials *other = ObjectWrap::Unwrap( - Nan::To(info[0]).ToLocalChecked()); - grpc_call_credentials *creds = grpc_composite_call_credentials_create( - self->wrapped_credentials, other->wrapped_credentials, NULL); - info.GetReturnValue().Set(WrapStruct(creds)); -} - -NAN_METHOD(CallCredentials::CreateFromPlugin) { - if (!info[0]->IsFunction()) { - return Nan::ThrowTypeError( - "createFromPlugin's argument must be a function"); - } - grpc_metadata_credentials_plugin plugin; - plugin_state *state = new plugin_state; - state->callback = new Nan::Callback(info[0].As()); - state->pending_callbacks = new std::queue(); - uv_mutex_init(&state->plugin_mutex); - uv_async_init(uv_default_loop(), &state->plugin_async, SendPluginCallback); - uv_unref((uv_handle_t *)&state->plugin_async); - - state->plugin_async.data = state; - - plugin.get_metadata = plugin_get_metadata; - plugin.destroy = plugin_destroy_state; - plugin.state = reinterpret_cast(state); - plugin.type = ""; - grpc_call_credentials *creds = - grpc_metadata_credentials_create_from_plugin(plugin, NULL); - info.GetReturnValue().Set(WrapStruct(creds)); -} - -NAN_METHOD(PluginCallback) { - // Arguments: status code, error details, metadata - if (!info[0]->IsUint32()) { - return Nan::ThrowTypeError( - "The callback's first argument must be a status code"); - } - if (!info[1]->IsString()) { - return Nan::ThrowTypeError( - "The callback's second argument must be a string"); - } - if (!info[2]->IsObject()) { - return Nan::ThrowTypeError( - "The callback's third argument must be an object"); - } - if (!info[3]->IsObject()) { - return Nan::ThrowTypeError( - "The callback's fourth argument must be an object"); - } - grpc_status_code code = - static_cast(Nan::To(info[0]).FromJust()); - Utf8String details_utf8_str(info[1]); - char *details = *details_utf8_str; - grpc_metadata_array array; - grpc_metadata_array_init(&array); - Local callback_data = Nan::To(info[3]).ToLocalChecked(); - if (!CreateMetadataArray(Nan::To(info[2]).ToLocalChecked(), &array)) { - return Nan::ThrowError("Failed to parse metadata"); - } - grpc_credentials_plugin_metadata_cb cb = - reinterpret_cast( - Nan::Get(callback_data, Nan::New("cb").ToLocalChecked()) - .ToLocalChecked() - .As() - ->Value()); - void *user_data = - Nan::Get(callback_data, Nan::New("user_data").ToLocalChecked()) - .ToLocalChecked() - .As() - ->Value(); - cb(user_data, array.metadata, array.count, code, details); - DestroyMetadataArray(&array); -} - -NAUV_WORK_CB(SendPluginCallback) { - Nan::HandleScope scope; - plugin_state *state = reinterpret_cast(async->data); - std::queue callbacks; - uv_mutex_lock(&state->plugin_mutex); - state->pending_callbacks->swap(callbacks); - uv_mutex_unlock(&state->plugin_mutex); - while (!callbacks.empty()) { - plugin_callback_data *data = callbacks.front(); - callbacks.pop(); - Local callback_data = Nan::New(); - Nan::Set(callback_data, Nan::New("cb").ToLocalChecked(), - Nan::New(reinterpret_cast(data->cb))); - Nan::Set(callback_data, Nan::New("user_data").ToLocalChecked(), - Nan::New(data->user_data)); - const int argc = 3; - v8::Local argv[argc] = { - Nan::New(data->service_url).ToLocalChecked(), callback_data, - // Get Local from Nan::Callback* - **plugin_callback}; - Nan::Callback *callback = state->callback; - callback->Call(argc, argv); - delete data; - } -} - -int plugin_get_metadata( - void *state, grpc_auth_metadata_context context, - grpc_credentials_plugin_metadata_cb cb, void *user_data, - grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], - size_t *num_creds_md, grpc_status_code *status, - const char **error_details) { - plugin_state *p_state = reinterpret_cast(state); - plugin_callback_data *data = new plugin_callback_data; - data->service_url = context.service_url; - data->cb = cb; - data->user_data = user_data; - - uv_mutex_lock(&p_state->plugin_mutex); - p_state->pending_callbacks->push(data); - uv_mutex_unlock(&p_state->plugin_mutex); - - uv_async_send(&p_state->plugin_async); - return 0; // Async processing. -} - -void plugin_uv_close_cb(uv_handle_t *handle) { - uv_async_t *async = reinterpret_cast(handle); - plugin_state *state = reinterpret_cast(async->data); - uv_mutex_destroy(&state->plugin_mutex); - delete state->pending_callbacks; - delete state->callback; - delete state; -} - -void plugin_destroy_state(void *ptr) { - plugin_state *state = reinterpret_cast(ptr); - uv_close((uv_handle_t *)&state->plugin_async, plugin_uv_close_cb); -} - -} // namespace node -} // namespace grpc diff --git a/src/node/ext/call_credentials.h b/src/node/ext/call_credentials.h deleted file mode 100644 index 3a54bbf0cf7..00000000000 --- a/src/node/ext/call_credentials.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_NODE_CALL_CREDENTIALS_H_ -#define GRPC_NODE_CALL_CREDENTIALS_H_ - -#include - -#include -#include -#include -#include "grpc/grpc_security.h" - -namespace grpc { -namespace node { - -class CallCredentials : public Nan::ObjectWrap { - public: - static void Init(v8::Local exports); - static bool HasInstance(v8::Local val); - /* Wrap a grpc_call_credentials struct in a javascript object */ - static v8::Local WrapStruct(grpc_call_credentials *credentials); - - /* Returns the grpc_call_credentials struct that this object wraps */ - grpc_call_credentials *GetWrappedCredentials(); - - private: - explicit CallCredentials(grpc_call_credentials *credentials); - ~CallCredentials(); - - // Prevent copying - CallCredentials(const CallCredentials &); - CallCredentials &operator=(const CallCredentials &); - - static NAN_METHOD(New); - static NAN_METHOD(CreateSsl); - static NAN_METHOD(CreateFromPlugin); - - static NAN_METHOD(Compose); - static Nan::Callback *constructor; - // Used for typechecking instances of this javascript class - static Nan::Persistent fun_tpl; - - grpc_call_credentials *wrapped_credentials; -}; - -/* Auth metadata plugin functionality */ - -typedef struct plugin_callback_data { - const char *service_url; - grpc_credentials_plugin_metadata_cb cb; - void *user_data; -} plugin_callback_data; - -typedef struct plugin_state { - Nan::Callback *callback; - std::queue *pending_callbacks; - uv_mutex_t plugin_mutex; - // async.data == this - uv_async_t plugin_async; -} plugin_state; - -int plugin_get_metadata( - void *state, grpc_auth_metadata_context context, - grpc_credentials_plugin_metadata_cb cb, void *user_data, - grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], - size_t *num_creds_md, grpc_status_code *status, const char **error_details); - -void plugin_destroy_state(void *state); - -NAN_METHOD(PluginCallback); - -NAUV_WORK_CB(SendPluginCallback); - -} // namespace node -} // namepsace grpc - -#endif // GRPC_NODE_CALL_CREDENTIALS_H_ diff --git a/src/node/ext/channel.cc b/src/node/ext/channel.cc deleted file mode 100644 index fc085fa011e..00000000000 --- a/src/node/ext/channel.cc +++ /dev/null @@ -1,272 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include - -#include "grpc/support/log.h" - -#include -#include -#include "call.h" -#include "channel.h" -#include "channel_credentials.h" -#include "completion_queue.h" -#include "grpc/grpc.h" -#include "grpc/grpc_security.h" -#include "timeval.h" - -namespace grpc { -namespace node { - -using Nan::Callback; -using Nan::EscapableHandleScope; -using Nan::HandleScope; -using Nan::Maybe; -using Nan::MaybeLocal; -using Nan::ObjectWrap; -using Nan::Persistent; -using Nan::Utf8String; - -using v8::Array; -using v8::Exception; -using v8::Function; -using v8::FunctionTemplate; -using v8::Integer; -using v8::Local; -using v8::Number; -using v8::Object; -using v8::String; -using v8::Value; - -Callback *Channel::constructor; -Persistent Channel::fun_tpl; - -bool ParseChannelArgs(Local args_val, - grpc_channel_args **channel_args_ptr) { - if (args_val->IsUndefined() || args_val->IsNull()) { - *channel_args_ptr = NULL; - return true; - } - if (!args_val->IsObject()) { - *channel_args_ptr = NULL; - return false; - } - grpc_channel_args *channel_args = - reinterpret_cast(malloc(sizeof(grpc_channel_args))); - *channel_args_ptr = channel_args; - Local args_hash = Nan::To(args_val).ToLocalChecked(); - Local keys = Nan::GetOwnPropertyNames(args_hash).ToLocalChecked(); - channel_args->num_args = keys->Length(); - channel_args->args = reinterpret_cast( - calloc(channel_args->num_args, sizeof(grpc_arg))); - for (unsigned int i = 0; i < channel_args->num_args; i++) { - Local key = Nan::Get(keys, i).ToLocalChecked(); - Utf8String key_str(key); - if (*key_str == NULL) { - // Key string onversion failed - return false; - } - Local value = Nan::Get(args_hash, key).ToLocalChecked(); - if (value->IsInt32()) { - channel_args->args[i].type = GRPC_ARG_INTEGER; - channel_args->args[i].value.integer = Nan::To(value).FromJust(); - } else if (value->IsString()) { - Utf8String val_str(value); - channel_args->args[i].type = GRPC_ARG_STRING; - channel_args->args[i].value.string = - reinterpret_cast(calloc(val_str.length() + 1, sizeof(char))); - memcpy(channel_args->args[i].value.string, *val_str, - val_str.length() + 1); - } else { - // The value does not match either of the accepted types - return false; - } - channel_args->args[i].key = - reinterpret_cast(calloc(key_str.length() + 1, sizeof(char))); - memcpy(channel_args->args[i].key, *key_str, key_str.length() + 1); - } - return true; -} - -void DeallocateChannelArgs(grpc_channel_args *channel_args) { - if (channel_args == NULL) { - return; - } - for (size_t i = 0; i < channel_args->num_args; i++) { - if (channel_args->args[i].key == NULL) { - /* NULL key implies that this argument and all subsequent arguments failed - * to parse */ - break; - } - free(channel_args->args[i].key); - if (channel_args->args[i].type == GRPC_ARG_STRING) { - free(channel_args->args[i].value.string); - } - } - free(channel_args->args); - free(channel_args); -} - -Channel::Channel(grpc_channel *channel) : wrapped_channel(channel) {} - -Channel::~Channel() { - gpr_log(GPR_DEBUG, "Destroying channel"); - if (wrapped_channel != NULL) { - grpc_channel_destroy(wrapped_channel); - } -} - -void Channel::Init(Local exports) { - Nan::HandleScope scope; - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("Channel").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - Nan::SetPrototypeMethod(tpl, "close", Close); - Nan::SetPrototypeMethod(tpl, "getTarget", GetTarget); - Nan::SetPrototypeMethod(tpl, "getConnectivityState", GetConnectivityState); - Nan::SetPrototypeMethod(tpl, "watchConnectivityState", - WatchConnectivityState); - fun_tpl.Reset(tpl); - Local ctr = Nan::GetFunction(tpl).ToLocalChecked(); - Nan::Set(exports, Nan::New("Channel").ToLocalChecked(), ctr); - constructor = new Callback(ctr); -} - -bool Channel::HasInstance(Local val) { - HandleScope scope; - return Nan::New(fun_tpl)->HasInstance(val); -} - -grpc_channel *Channel::GetWrappedChannel() { return this->wrapped_channel; } - -NAN_METHOD(Channel::New) { - if (info.IsConstructCall()) { - if (!info[0]->IsString()) { - return Nan::ThrowTypeError( - "Channel expects a string, a credential and an object"); - } - grpc_channel *wrapped_channel; - // Owned by the Channel object - Utf8String host(info[0]); - grpc_channel_credentials *creds; - if (!ChannelCredentials::HasInstance(info[1])) { - return Nan::ThrowTypeError( - "Channel's second argument must be a ChannelCredentials"); - } - ChannelCredentials *creds_object = ObjectWrap::Unwrap( - Nan::To(info[1]).ToLocalChecked()); - creds = creds_object->GetWrappedCredentials(); - grpc_channel_args *channel_args_ptr = NULL; - if (!ParseChannelArgs(info[2], &channel_args_ptr)) { - DeallocateChannelArgs(channel_args_ptr); - return Nan::ThrowTypeError( - "Channel options must be an object with " - "string keys and integer or string values"); - } - if (creds == NULL) { - wrapped_channel = - grpc_insecure_channel_create(*host, channel_args_ptr, NULL); - } else { - wrapped_channel = - grpc_secure_channel_create(creds, *host, channel_args_ptr, NULL); - } - DeallocateChannelArgs(channel_args_ptr); - Channel *channel = new Channel(wrapped_channel); - channel->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - return; - } else { - const int argc = 3; - Local argv[argc] = {info[0], info[1], info[2]}; - MaybeLocal maybe_instance = - Nan::NewInstance(constructor->GetFunction(), argc, argv); - if (maybe_instance.IsEmpty()) { - // There's probably a pending exception - return; - } else { - info.GetReturnValue().Set(maybe_instance.ToLocalChecked()); - } - } -} - -NAN_METHOD(Channel::Close) { - if (!HasInstance(info.This())) { - return Nan::ThrowTypeError("close can only be called on Channel objects"); - } - Channel *channel = ObjectWrap::Unwrap(info.This()); - if (channel->wrapped_channel != NULL) { - grpc_channel_destroy(channel->wrapped_channel); - channel->wrapped_channel = NULL; - } -} - -NAN_METHOD(Channel::GetTarget) { - if (!HasInstance(info.This())) { - return Nan::ThrowTypeError( - "getTarget can only be called on Channel objects"); - } - Channel *channel = ObjectWrap::Unwrap(info.This()); - info.GetReturnValue().Set( - Nan::New(grpc_channel_get_target(channel->wrapped_channel)) - .ToLocalChecked()); -} - -NAN_METHOD(Channel::GetConnectivityState) { - if (!HasInstance(info.This())) { - return Nan::ThrowTypeError( - "getConnectivityState can only be called on Channel objects"); - } - Channel *channel = ObjectWrap::Unwrap(info.This()); - int try_to_connect = (int)info[0]->Equals(Nan::True()); - info.GetReturnValue().Set(grpc_channel_check_connectivity_state( - channel->wrapped_channel, try_to_connect)); -} - -NAN_METHOD(Channel::WatchConnectivityState) { - if (!HasInstance(info.This())) { - return Nan::ThrowTypeError( - "watchConnectivityState can only be called on Channel objects"); - } - if (!info[0]->IsUint32()) { - return Nan::ThrowTypeError( - "watchConnectivityState's first argument must be a channel state"); - } - if (!(info[1]->IsNumber() || info[1]->IsDate())) { - return Nan::ThrowTypeError( - "watchConnectivityState's second argument must be a date or a number"); - } - if (!info[2]->IsFunction()) { - return Nan::ThrowTypeError( - "watchConnectivityState's third argument must be a callback"); - } - grpc_connectivity_state last_state = static_cast( - Nan::To(info[0]).FromJust()); - double deadline = Nan::To(info[1]).FromJust(); - Local callback_func = info[2].As(); - Nan::Callback *callback = new Callback(callback_func); - Channel *channel = ObjectWrap::Unwrap(info.This()); - unique_ptr ops(new OpVec()); - grpc_channel_watch_connectivity_state( - channel->wrapped_channel, last_state, MillisecondsToTimespec(deadline), - GetCompletionQueue(), - new struct tag(callback, ops.release(), NULL, Nan::Null())); - CompletionQueueNext(); -} - -} // namespace node -} // namespace grpc diff --git a/src/node/ext/channel.h b/src/node/ext/channel.h deleted file mode 100644 index a93dbe9d250..00000000000 --- a/src/node/ext/channel.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef NET_GRPC_NODE_CHANNEL_H_ -#define NET_GRPC_NODE_CHANNEL_H_ - -#include -#include -#include "grpc/grpc.h" - -namespace grpc { -namespace node { - -bool ParseChannelArgs(v8::Local args_val, - grpc_channel_args **channel_args_ptr); - -void DeallocateChannelArgs(grpc_channel_args *channel_args); - -/* Wrapper class for grpc_channel structs */ -class Channel : public Nan::ObjectWrap { - public: - static void Init(v8::Local exports); - static bool HasInstance(v8::Local val); - /* This is used to typecheck javascript objects before converting them to - this type */ - static v8::Persistent prototype; - - /* Returns the grpc_channel struct that this object wraps */ - grpc_channel *GetWrappedChannel(); - - private: - explicit Channel(grpc_channel *channel); - ~Channel(); - - // Prevent copying - Channel(const Channel &); - Channel &operator=(const Channel &); - - static NAN_METHOD(New); - static NAN_METHOD(Close); - static NAN_METHOD(GetTarget); - static NAN_METHOD(GetConnectivityState); - static NAN_METHOD(WatchConnectivityState); - static Nan::Callback *constructor; - static Nan::Persistent fun_tpl; - - grpc_channel *wrapped_channel; -}; - -} // namespace node -} // namespace grpc - -#endif // NET_GRPC_NODE_CHANNEL_H_ diff --git a/src/node/ext/channel_credentials.cc b/src/node/ext/channel_credentials.cc deleted file mode 100644 index 9e87fb61bbd..00000000000 --- a/src/node/ext/channel_credentials.cc +++ /dev/null @@ -1,188 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include - -#include "call.h" -#include "call_credentials.h" -#include "channel_credentials.h" -#include "grpc/grpc.h" -#include "grpc/grpc_security.h" -#include "grpc/support/log.h" - -namespace grpc { -namespace node { - -using Nan::Callback; -using Nan::EscapableHandleScope; -using Nan::HandleScope; -using Nan::Maybe; -using Nan::MaybeLocal; -using Nan::ObjectWrap; -using Nan::Persistent; -using Nan::Utf8String; - -using v8::Exception; -using v8::External; -using v8::Function; -using v8::FunctionTemplate; -using v8::Integer; -using v8::Local; -using v8::Object; -using v8::ObjectTemplate; -using v8::Value; - -Nan::Callback *ChannelCredentials::constructor; -Persistent ChannelCredentials::fun_tpl; - -ChannelCredentials::ChannelCredentials(grpc_channel_credentials *credentials) - : wrapped_credentials(credentials) {} - -ChannelCredentials::~ChannelCredentials() { - grpc_channel_credentials_release(wrapped_credentials); -} - -void ChannelCredentials::Init(Local exports) { - HandleScope scope; - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("ChannelCredentials").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - Nan::SetPrototypeMethod(tpl, "compose", Compose); - fun_tpl.Reset(tpl); - Local ctr = Nan::GetFunction(tpl).ToLocalChecked(); - Nan::Set( - ctr, Nan::New("createSsl").ToLocalChecked(), - Nan::GetFunction(Nan::New(CreateSsl)).ToLocalChecked()); - Nan::Set(ctr, Nan::New("createInsecure").ToLocalChecked(), - Nan::GetFunction(Nan::New(CreateInsecure)) - .ToLocalChecked()); - Nan::Set(exports, Nan::New("ChannelCredentials").ToLocalChecked(), ctr); - constructor = new Nan::Callback(ctr); -} - -bool ChannelCredentials::HasInstance(Local val) { - HandleScope scope; - return Nan::New(fun_tpl)->HasInstance(val); -} - -Local ChannelCredentials::WrapStruct( - grpc_channel_credentials *credentials) { - EscapableHandleScope scope; - const int argc = 1; - Local argv[argc] = { - Nan::New(reinterpret_cast(credentials))}; - MaybeLocal maybe_instance = - Nan::NewInstance(constructor->GetFunction(), argc, argv); - if (maybe_instance.IsEmpty()) { - return scope.Escape(Nan::Null()); - } else { - return scope.Escape(maybe_instance.ToLocalChecked()); - } -} - -grpc_channel_credentials *ChannelCredentials::GetWrappedCredentials() { - return wrapped_credentials; -} - -NAN_METHOD(ChannelCredentials::New) { - if (info.IsConstructCall()) { - if (!info[0]->IsExternal()) { - return Nan::ThrowTypeError( - "ChannelCredentials can only be created with the provided functions"); - } - Local ext = info[0].As(); - grpc_channel_credentials *creds_value = - reinterpret_cast(ext->Value()); - ChannelCredentials *credentials = new ChannelCredentials(creds_value); - credentials->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - return; - } else { - // This should never be called directly - return Nan::ThrowTypeError( - "ChannelCredentials can only be created with the provided functions"); - } -} - -NAN_METHOD(ChannelCredentials::CreateSsl) { - char *root_certs = NULL; - grpc_ssl_pem_key_cert_pair key_cert_pair = {NULL, NULL}; - if (::node::Buffer::HasInstance(info[0])) { - root_certs = ::node::Buffer::Data(info[0]); - } else if (!(info[0]->IsNull() || info[0]->IsUndefined())) { - return Nan::ThrowTypeError("createSsl's first argument must be a Buffer"); - } - if (::node::Buffer::HasInstance(info[1])) { - key_cert_pair.private_key = ::node::Buffer::Data(info[1]); - } else if (!(info[1]->IsNull() || info[1]->IsUndefined())) { - return Nan::ThrowTypeError( - "createSSl's second argument must be a Buffer if provided"); - } - if (::node::Buffer::HasInstance(info[2])) { - key_cert_pair.cert_chain = ::node::Buffer::Data(info[2]); - } else if (!(info[2]->IsNull() || info[2]->IsUndefined())) { - return Nan::ThrowTypeError( - "createSSl's third argument must be a Buffer if provided"); - } - if ((key_cert_pair.private_key == NULL) != - (key_cert_pair.cert_chain == NULL)) { - return Nan::ThrowError( - "createSsl's second and third arguments must be" - " provided or omitted together"); - } - grpc_channel_credentials *creds = grpc_ssl_credentials_create( - root_certs, key_cert_pair.private_key == NULL ? NULL : &key_cert_pair, - NULL); - if (creds == NULL) { - info.GetReturnValue().SetNull(); - } else { - info.GetReturnValue().Set(WrapStruct(creds)); - } -} - -NAN_METHOD(ChannelCredentials::Compose) { - if (!ChannelCredentials::HasInstance(info.This())) { - return Nan::ThrowTypeError( - "compose can only be called on ChannelCredentials objects"); - } - if (!CallCredentials::HasInstance(info[0])) { - return Nan::ThrowTypeError( - "compose's first argument must be a CallCredentials object"); - } - ChannelCredentials *self = - ObjectWrap::Unwrap(info.This()); - if (self->wrapped_credentials == NULL) { - return Nan::ThrowTypeError("Cannot compose insecure credential"); - } - CallCredentials *other = ObjectWrap::Unwrap( - Nan::To(info[0]).ToLocalChecked()); - grpc_channel_credentials *creds = grpc_composite_channel_credentials_create( - self->wrapped_credentials, other->GetWrappedCredentials(), NULL); - if (creds == NULL) { - info.GetReturnValue().SetNull(); - } else { - info.GetReturnValue().Set(WrapStruct(creds)); - } -} - -NAN_METHOD(ChannelCredentials::CreateInsecure) { - info.GetReturnValue().Set(WrapStruct(NULL)); -} - -} // namespace node -} // namespace grpc diff --git a/src/node/ext/channel_credentials.h b/src/node/ext/channel_credentials.h deleted file mode 100644 index 18c14837cc9..00000000000 --- a/src/node/ext/channel_credentials.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef NET_GRPC_NODE_CHANNEL_CREDENTIALS_H_ -#define NET_GRPC_NODE_CHANNEL_CREDENTIALS_H_ - -#include -#include -#include "grpc/grpc.h" -#include "grpc/grpc_security.h" - -namespace grpc { -namespace node { - -/* Wrapper class for grpc_channel_credentials structs */ -class ChannelCredentials : public Nan::ObjectWrap { - public: - static void Init(v8::Local exports); - static bool HasInstance(v8::Local val); - /* Wrap a grpc_channel_credentials struct in a javascript object */ - static v8::Local WrapStruct(grpc_channel_credentials *credentials); - - /* Returns the grpc_channel_credentials struct that this object wraps */ - grpc_channel_credentials *GetWrappedCredentials(); - - private: - explicit ChannelCredentials(grpc_channel_credentials *credentials); - ~ChannelCredentials(); - - // Prevent copying - ChannelCredentials(const ChannelCredentials &); - ChannelCredentials &operator=(const ChannelCredentials &); - - static NAN_METHOD(New); - static NAN_METHOD(CreateSsl); - static NAN_METHOD(CreateInsecure); - - static NAN_METHOD(Compose); - static Nan::Callback *constructor; - // Used for typechecking instances of this javascript class - static Nan::Persistent fun_tpl; - - grpc_channel_credentials *wrapped_credentials; -}; - -} // namespace node -} // namespace grpc - -#endif // NET_GRPC_NODE_CHANNEL_CREDENTIALS_H_ diff --git a/src/node/ext/completion_queue.cc b/src/node/ext/completion_queue.cc deleted file mode 100644 index a08febbb2cd..00000000000 --- a/src/node/ext/completion_queue.cc +++ /dev/null @@ -1,80 +0,0 @@ -/* - * - * 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 -#include -#include -#include - -#include "call.h" -#include "completion_queue.h" - -namespace grpc { -namespace node { - -using v8::Local; -using v8::Object; -using v8::Value; - -grpc_completion_queue *queue; -uv_prepare_t prepare; -int pending_batches; - -void drain_completion_queue(uv_prepare_t *handle) { - Nan::HandleScope scope; - grpc_event event; - (void)handle; - do { - event = grpc_completion_queue_next(queue, gpr_inf_past(GPR_CLOCK_MONOTONIC), - NULL); - - if (event.type == GRPC_OP_COMPLETE) { - const char *error_message; - if (event.success) { - error_message = NULL; - } else { - error_message = "The async function encountered an error"; - } - CompleteTag(event.tag, error_message); - grpc::node::DestroyTag(event.tag); - pending_batches--; - if (pending_batches == 0) { - uv_prepare_stop(&prepare); - } - } - } while (event.type != GRPC_QUEUE_TIMEOUT); -} - -grpc_completion_queue *GetCompletionQueue() { return queue; } - -void CompletionQueueNext() { - if (pending_batches == 0) { - GPR_ASSERT(!uv_is_active((uv_handle_t *)&prepare)); - uv_prepare_start(&prepare, drain_completion_queue); - } - pending_batches++; -} - -void CompletionQueueInit(Local exports) { - queue = grpc_completion_queue_create_for_next(NULL); - uv_prepare_init(uv_default_loop(), &prepare); - pending_batches = 0; -} - -} // namespace node -} // namespace grpc diff --git a/src/node/ext/node_grpc.cc b/src/node/ext/node_grpc.cc deleted file mode 100644 index 11ed0838bc7..00000000000 --- a/src/node/ext/node_grpc.cc +++ /dev/null @@ -1,311 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include - -#include -#include -#include -#include "grpc/grpc.h" -#include "grpc/grpc_security.h" -#include "grpc/support/alloc.h" -#include "grpc/support/log.h" -#include "grpc/support/time.h" - -// TODO(murgatroid99): Remove this when the endpoint API becomes public -extern "C" { -#include "src/core/lib/iomgr/pollset_uv.h" -} - -#include "call.h" -#include "call_credentials.h" -#include "channel.h" -#include "channel_credentials.h" -#include "completion_queue.h" -#include "server.h" -#include "server_credentials.h" -#include "slice.h" -#include "timeval.h" - -using grpc::node::CreateSliceFromString; - -using v8::FunctionTemplate; -using v8::Local; -using v8::Value; -using v8::Number; -using v8::Object; -using v8::Uint32; -using v8::String; - -typedef struct log_args { - gpr_log_func_args core_args; - gpr_timespec timestamp; -} log_args; - -typedef struct logger_state { - Nan::Callback *callback; - std::queue *pending_args; - uv_mutex_t mutex; - uv_async_t async; - // Indicates that a logger has been set - bool logger_set; -} logger_state; - -logger_state grpc_logger_state; - -static char *pem_root_certs = NULL; - -void InitOpTypeConstants(Local exports) { - Nan::HandleScope scope; - Local op_type = Nan::New(); - Nan::Set(exports, Nan::New("opType").ToLocalChecked(), op_type); - Local SEND_INITIAL_METADATA( - Nan::New(GRPC_OP_SEND_INITIAL_METADATA)); - Nan::Set(op_type, Nan::New("SEND_INITIAL_METADATA").ToLocalChecked(), - SEND_INITIAL_METADATA); - Local SEND_MESSAGE(Nan::New(GRPC_OP_SEND_MESSAGE)); - Nan::Set(op_type, Nan::New("SEND_MESSAGE").ToLocalChecked(), SEND_MESSAGE); - Local SEND_CLOSE_FROM_CLIENT( - Nan::New(GRPC_OP_SEND_CLOSE_FROM_CLIENT)); - Nan::Set(op_type, Nan::New("SEND_CLOSE_FROM_CLIENT").ToLocalChecked(), - SEND_CLOSE_FROM_CLIENT); - Local SEND_STATUS_FROM_SERVER( - Nan::New(GRPC_OP_SEND_STATUS_FROM_SERVER)); - Nan::Set(op_type, Nan::New("SEND_STATUS_FROM_SERVER").ToLocalChecked(), - SEND_STATUS_FROM_SERVER); - Local RECV_INITIAL_METADATA( - Nan::New(GRPC_OP_RECV_INITIAL_METADATA)); - Nan::Set(op_type, Nan::New("RECV_INITIAL_METADATA").ToLocalChecked(), - RECV_INITIAL_METADATA); - Local RECV_MESSAGE(Nan::New(GRPC_OP_RECV_MESSAGE)); - Nan::Set(op_type, Nan::New("RECV_MESSAGE").ToLocalChecked(), RECV_MESSAGE); - Local RECV_STATUS_ON_CLIENT( - Nan::New(GRPC_OP_RECV_STATUS_ON_CLIENT)); - Nan::Set(op_type, Nan::New("RECV_STATUS_ON_CLIENT").ToLocalChecked(), - RECV_STATUS_ON_CLIENT); - Local RECV_CLOSE_ON_SERVER( - Nan::New(GRPC_OP_RECV_CLOSE_ON_SERVER)); - Nan::Set(op_type, Nan::New("RECV_CLOSE_ON_SERVER").ToLocalChecked(), - RECV_CLOSE_ON_SERVER); -} - -void InitConnectivityStateConstants(Local exports) { - Nan::HandleScope scope; - Local channel_state = Nan::New(); - Nan::Set(exports, Nan::New("connectivityState").ToLocalChecked(), - channel_state); - Local IDLE(Nan::New(GRPC_CHANNEL_IDLE)); - Nan::Set(channel_state, Nan::New("IDLE").ToLocalChecked(), IDLE); - Local CONNECTING(Nan::New(GRPC_CHANNEL_CONNECTING)); - Nan::Set(channel_state, Nan::New("CONNECTING").ToLocalChecked(), CONNECTING); - Local READY(Nan::New(GRPC_CHANNEL_READY)); - Nan::Set(channel_state, Nan::New("READY").ToLocalChecked(), READY); - Local TRANSIENT_FAILURE( - Nan::New(GRPC_CHANNEL_TRANSIENT_FAILURE)); - Nan::Set(channel_state, Nan::New("TRANSIENT_FAILURE").ToLocalChecked(), - TRANSIENT_FAILURE); - Local FATAL_FAILURE(Nan::New(GRPC_CHANNEL_SHUTDOWN)); - Nan::Set(channel_state, Nan::New("FATAL_FAILURE").ToLocalChecked(), - FATAL_FAILURE); -} - -NAN_METHOD(MetadataKeyIsLegal) { - if (!info[0]->IsString()) { - return Nan::ThrowTypeError("headerKeyIsLegal's argument must be a string"); - } - Local key = Nan::To(info[0]).ToLocalChecked(); - grpc_slice slice = CreateSliceFromString(key); - info.GetReturnValue().Set(static_cast(grpc_header_key_is_legal(slice))); - grpc_slice_unref(slice); -} - -NAN_METHOD(MetadataNonbinValueIsLegal) { - if (!info[0]->IsString()) { - return Nan::ThrowTypeError( - "metadataNonbinValueIsLegal's argument must be a string"); - } - Local value = Nan::To(info[0]).ToLocalChecked(); - grpc_slice slice = CreateSliceFromString(value); - info.GetReturnValue().Set( - static_cast(grpc_header_nonbin_value_is_legal(slice))); - grpc_slice_unref(slice); -} - -NAN_METHOD(MetadataKeyIsBinary) { - if (!info[0]->IsString()) { - return Nan::ThrowTypeError( - "metadataKeyIsLegal's argument must be a string"); - } - Local key = Nan::To(info[0]).ToLocalChecked(); - grpc_slice slice = CreateSliceFromString(key); - info.GetReturnValue().Set(static_cast(grpc_is_binary_header(slice))); - grpc_slice_unref(slice); -} - -static grpc_ssl_roots_override_result get_ssl_roots_override( - char **pem_root_certs_ptr) { - *pem_root_certs_ptr = pem_root_certs; - if (pem_root_certs == NULL) { - return GRPC_SSL_ROOTS_OVERRIDE_FAIL; - } else { - return GRPC_SSL_ROOTS_OVERRIDE_OK; - } -} - -/* This should only be called once, and only before creating any - *ServerCredentials */ -NAN_METHOD(SetDefaultRootsPem) { - if (!info[0]->IsString()) { - return Nan::ThrowTypeError( - "setDefaultRootsPem's argument must be a string"); - } - Nan::Utf8String utf8_roots(info[0]); - size_t length = static_cast(utf8_roots.length()); - if (length > 0) { - const char *data = *utf8_roots; - pem_root_certs = (char *)gpr_malloc((length + 1) * sizeof(char)); - memcpy(pem_root_certs, data, length + 1); - } -} - -NAUV_WORK_CB(LogMessagesCallback) { - Nan::HandleScope scope; - std::queue args; - uv_mutex_lock(&grpc_logger_state.mutex); - grpc_logger_state.pending_args->swap(args); - uv_mutex_unlock(&grpc_logger_state.mutex); - /* Call the callback with each log message */ - while (!args.empty()) { - log_args *arg = args.front(); - args.pop(); - Local file = Nan::New(arg->core_args.file).ToLocalChecked(); - Local line = Nan::New(arg->core_args.line); - Local severity = - Nan::New(gpr_log_severity_string(arg->core_args.severity)) - .ToLocalChecked(); - Local message = Nan::New(arg->core_args.message).ToLocalChecked(); - Local timestamp = - Nan::New(grpc::node::TimespecToMilliseconds(arg->timestamp)) - .ToLocalChecked(); - const int argc = 5; - Local argv[argc] = {file, line, severity, message, timestamp}; - grpc_logger_state.callback->Call(argc, argv); - delete[] arg->core_args.message; - delete arg; - } -} - -void node_log_func(gpr_log_func_args *args) { - // TODO(mlumish): Use the core's log formatter when it becomes available - log_args *args_copy = new log_args; - size_t message_len = strlen(args->message) + 1; - char *message = new char[message_len]; - memcpy(message, args->message, message_len); - memcpy(&args_copy->core_args, args, sizeof(gpr_log_func_args)); - args_copy->core_args.message = message; - args_copy->timestamp = gpr_now(GPR_CLOCK_REALTIME); - - uv_mutex_lock(&grpc_logger_state.mutex); - grpc_logger_state.pending_args->push(args_copy); - uv_mutex_unlock(&grpc_logger_state.mutex); - - uv_async_send(&grpc_logger_state.async); -} - -void init_logger() { - memset(&grpc_logger_state, 0, sizeof(logger_state)); - grpc_logger_state.pending_args = new std::queue(); - uv_mutex_init(&grpc_logger_state.mutex); - uv_async_init(uv_default_loop(), &grpc_logger_state.async, - LogMessagesCallback); - uv_unref((uv_handle_t *)&grpc_logger_state.async); - grpc_logger_state.logger_set = false; - - gpr_log_verbosity_init(); -} - -/* This registers a JavaScript logger for messages from the gRPC core. Because - that handler has to be run in the context of the JavaScript event loop, it - will be run asynchronously. To minimize the problems that could cause for - debugging, we leave core to do its default synchronous logging until a - JavaScript logger is set */ -NAN_METHOD(SetDefaultLoggerCallback) { - if (!info[0]->IsFunction()) { - return Nan::ThrowTypeError( - "setDefaultLoggerCallback's argument must be a function"); - } - if (!grpc_logger_state.logger_set) { - gpr_set_log_function(node_log_func); - grpc_logger_state.logger_set = true; - } - grpc_logger_state.callback = new Nan::Callback(info[0].As()); -} - -NAN_METHOD(SetLogVerbosity) { - if (!info[0]->IsUint32()) { - return Nan::ThrowTypeError("setLogVerbosity's argument must be a number"); - } - gpr_log_severity severity = - static_cast(Nan::To(info[0]).FromJust()); - gpr_set_log_verbosity(severity); -} - -void init(Local exports) { - Nan::HandleScope scope; - grpc_init(); - grpc_set_ssl_roots_override_callback(get_ssl_roots_override); - init_logger(); - - InitOpTypeConstants(exports); - InitConnectivityStateConstants(exports); - - grpc_pollset_work_run_loop = 0; - - grpc::node::Call::Init(exports); - grpc::node::CallCredentials::Init(exports); - grpc::node::Channel::Init(exports); - grpc::node::ChannelCredentials::Init(exports); - grpc::node::Server::Init(exports); - grpc::node::ServerCredentials::Init(exports); - - grpc::node::CompletionQueueInit(exports); - - // Attach a few utility functions directly to the module - Nan::Set(exports, Nan::New("metadataKeyIsLegal").ToLocalChecked(), - Nan::GetFunction(Nan::New(MetadataKeyIsLegal)) - .ToLocalChecked()); - Nan::Set( - exports, Nan::New("metadataNonbinValueIsLegal").ToLocalChecked(), - Nan::GetFunction(Nan::New(MetadataNonbinValueIsLegal)) - .ToLocalChecked()); - Nan::Set(exports, Nan::New("metadataKeyIsBinary").ToLocalChecked(), - Nan::GetFunction(Nan::New(MetadataKeyIsBinary)) - .ToLocalChecked()); - Nan::Set(exports, Nan::New("setDefaultRootsPem").ToLocalChecked(), - Nan::GetFunction(Nan::New(SetDefaultRootsPem)) - .ToLocalChecked()); - Nan::Set( - exports, Nan::New("setDefaultLoggerCallback").ToLocalChecked(), - Nan::GetFunction(Nan::New(SetDefaultLoggerCallback)) - .ToLocalChecked()); - Nan::Set(exports, Nan::New("setLogVerbosity").ToLocalChecked(), - Nan::GetFunction(Nan::New(SetLogVerbosity)) - .ToLocalChecked()); -} - -NODE_MODULE(grpc_node, init) diff --git a/src/node/ext/server.cc b/src/node/ext/server.cc deleted file mode 100644 index c6ab5e18959..00000000000 --- a/src/node/ext/server.cc +++ /dev/null @@ -1,342 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include - -#include "server.h" - -#include -#include - -#include -#include "call.h" -#include "completion_queue.h" -#include "grpc/grpc.h" -#include "grpc/grpc_security.h" -#include "grpc/support/log.h" -#include "server_credentials.h" -#include "slice.h" -#include "timeval.h" - -namespace grpc { -namespace node { - -using Nan::Callback; -using Nan::EscapableHandleScope; -using Nan::HandleScope; -using Nan::Maybe; -using Nan::MaybeLocal; -using Nan::ObjectWrap; -using Nan::Persistent; -using Nan::Utf8String; - -using std::unique_ptr; -using v8::Array; -using v8::Boolean; -using v8::Date; -using v8::Exception; -using v8::External; -using v8::Function; -using v8::FunctionTemplate; -using v8::Local; -using v8::Number; -using v8::Object; -using v8::String; -using v8::Value; - -Nan::Callback *Server::constructor; -Persistent Server::fun_tpl; - -static Callback *shutdown_callback = NULL; - -class ServerShutdownOp : public Op { - public: - ServerShutdownOp(grpc_server *server) : server(server) {} - - ~ServerShutdownOp() {} - - Local GetNodeValue() const { return Nan::Null(); } - - bool ParseOp(Local value, grpc_op *out) { return true; } - bool IsFinalOp() { return false; } - void OnComplete(bool success) { - /* Because cancel_all_calls was called, we assume that shutdown_and_notify - completes successfully */ - grpc_server_destroy(server); - } - - grpc_server *server; - - protected: - std::string GetTypeString() const { return "shutdown"; } -}; - -class NewCallOp : public Op { - public: - NewCallOp() { - call = NULL; - grpc_call_details_init(&details); - grpc_metadata_array_init(&request_metadata); - } - - ~NewCallOp() { - grpc_call_details_destroy(&details); - grpc_metadata_array_destroy(&request_metadata); - } - - Local GetNodeValue() const { - Nan::EscapableHandleScope scope; - if (call == NULL) { - return scope.Escape(Nan::Null()); - } - Local obj = Nan::New(); - Nan::Set(obj, Nan::New("call").ToLocalChecked(), Call::WrapStruct(call)); - // TODO(murgatroid99): Use zero-copy string construction instead - Nan::Set(obj, Nan::New("method").ToLocalChecked(), - CopyStringFromSlice(details.method)); - Nan::Set(obj, Nan::New("host").ToLocalChecked(), - CopyStringFromSlice(details.host)); - Nan::Set(obj, Nan::New("deadline").ToLocalChecked(), - Nan::New(TimespecToMilliseconds(details.deadline)) - .ToLocalChecked()); - Nan::Set(obj, Nan::New("metadata").ToLocalChecked(), - ParseMetadata(&request_metadata)); - return scope.Escape(obj); - } - - bool ParseOp(Local value, grpc_op *out) { return true; } - bool IsFinalOp() { return false; } - void OnComplete(bool success) {} - - grpc_call *call; - grpc_call_details details; - grpc_metadata_array request_metadata; - - protected: - std::string GetTypeString() const { return "new_call"; } -}; - -class TryShutdownOp : public Op { - public: - TryShutdownOp(Server *server, Local server_value) : server(server) { - server_persist.Reset(server_value); - } - Local GetNodeValue() const { - EscapableHandleScope scope; - return scope.Escape(Nan::New(server_persist)); - } - bool ParseOp(Local value, grpc_op *out) { return true; } - bool IsFinalOp() { return false; } - void OnComplete(bool success) { - if (success) { - server->DestroyWrappedServer(); - } - } - - protected: - std::string GetTypeString() const { return "try_shutdown"; } - - private: - Server *server; - Nan::Persistent> - server_persist; -}; - -Server::Server(grpc_server *server) : wrapped_server(server) {} - -Server::~Server() { this->ShutdownServer(); } - -void Server::Init(Local exports) { - HandleScope scope; - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("Server").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - Nan::SetPrototypeMethod(tpl, "requestCall", RequestCall); - Nan::SetPrototypeMethod(tpl, "addHttp2Port", AddHttp2Port); - Nan::SetPrototypeMethod(tpl, "start", Start); - Nan::SetPrototypeMethod(tpl, "tryShutdown", TryShutdown); - Nan::SetPrototypeMethod(tpl, "forceShutdown", ForceShutdown); - fun_tpl.Reset(tpl); - Local ctr = Nan::GetFunction(tpl).ToLocalChecked(); - Nan::Set(exports, Nan::New("Server").ToLocalChecked(), ctr); - constructor = new Callback(ctr); -} - -bool Server::HasInstance(Local val) { - HandleScope scope; - return Nan::New(fun_tpl)->HasInstance(val); -} - -void Server::DestroyWrappedServer() { - if (this->wrapped_server != NULL) { - grpc_server_destroy(this->wrapped_server); - this->wrapped_server = NULL; - } -} - -NAN_METHOD(ServerShutdownCallback) { - if (!info[0]->IsNull()) { - return Nan::ThrowError("forceShutdown failed somehow"); - } -} - -void Server::ShutdownServer() { - Nan::HandleScope scope; - if (this->wrapped_server != NULL) { - if (shutdown_callback == NULL) { - Local callback_tpl = - Nan::New(ServerShutdownCallback); - shutdown_callback = - new Callback(Nan::GetFunction(callback_tpl).ToLocalChecked()); - } - - ServerShutdownOp *op = new ServerShutdownOp(this->wrapped_server); - unique_ptr ops(new OpVec()); - ops->push_back(unique_ptr(op)); - - grpc_server_shutdown_and_notify( - this->wrapped_server, GetCompletionQueue(), - new struct tag(new Callback(**shutdown_callback), ops.release(), NULL, - Nan::Null())); - grpc_server_cancel_all_calls(this->wrapped_server); - CompletionQueueNext(); - this->wrapped_server = NULL; - } -} - -NAN_METHOD(Server::New) { - /* If this is not a constructor call, make a constructor call and return - the result */ - if (!info.IsConstructCall()) { - const int argc = 1; - Local argv[argc] = {info[0]}; - MaybeLocal maybe_instance = - Nan::NewInstance(constructor->GetFunction(), argc, argv); - if (maybe_instance.IsEmpty()) { - // There's probably a pending exception - return; - } else { - info.GetReturnValue().Set(maybe_instance.ToLocalChecked()); - return; - } - } - grpc_server *wrapped_server; - grpc_completion_queue *queue = GetCompletionQueue(); - grpc_channel_args *channel_args; - if (!ParseChannelArgs(info[0], &channel_args)) { - DeallocateChannelArgs(channel_args); - return Nan::ThrowTypeError( - "Server options must be an object with " - "string keys and integer or string values"); - } - wrapped_server = grpc_server_create(channel_args, NULL); - DeallocateChannelArgs(channel_args); - grpc_server_register_completion_queue(wrapped_server, queue, NULL); - Server *server = new Server(wrapped_server); - server->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); -} - -NAN_METHOD(Server::RequestCall) { - if (!HasInstance(info.This())) { - return Nan::ThrowTypeError("requestCall can only be called on a Server"); - } - Server *server = ObjectWrap::Unwrap(info.This()); - NewCallOp *op = new NewCallOp(); - unique_ptr ops(new OpVec()); - ops->push_back(unique_ptr(op)); - grpc_call_error error = grpc_server_request_call( - server->wrapped_server, &op->call, &op->details, &op->request_metadata, - GetCompletionQueue(), GetCompletionQueue(), - new struct tag(new Callback(info[0].As()), ops.release(), NULL, - Nan::Null())); - if (error != GRPC_CALL_OK) { - return Nan::ThrowError(nanErrorWithCode("requestCall failed", error)); - } - CompletionQueueNext(); -} - -NAN_METHOD(Server::AddHttp2Port) { - if (!HasInstance(info.This())) { - return Nan::ThrowTypeError("addHttp2Port can only be called on a Server"); - } - if (!info[0]->IsString()) { - return Nan::ThrowTypeError( - "addHttp2Port's first argument must be a String"); - } - if (!ServerCredentials::HasInstance(info[1])) { - return Nan::ThrowTypeError( - "addHttp2Port's second argument must be ServerCredentials"); - } - Server *server = ObjectWrap::Unwrap(info.This()); - ServerCredentials *creds_object = ObjectWrap::Unwrap( - Nan::To(info[1]).ToLocalChecked()); - grpc_server_credentials *creds = creds_object->GetWrappedServerCredentials(); - int port; - if (creds == NULL) { - port = grpc_server_add_insecure_http2_port(server->wrapped_server, - *Utf8String(info[0])); - } else { - port = grpc_server_add_secure_http2_port(server->wrapped_server, - *Utf8String(info[0]), creds); - } - info.GetReturnValue().Set(Nan::New(port)); -} - -NAN_METHOD(Server::Start) { - Nan::HandleScope scope; - if (!HasInstance(info.This())) { - return Nan::ThrowTypeError("start can only be called on a Server"); - } - Server *server = ObjectWrap::Unwrap(info.This()); - grpc_server_start(server->wrapped_server); -} - -NAN_METHOD(Server::TryShutdown) { - Nan::HandleScope scope; - if (!HasInstance(info.This())) { - return Nan::ThrowTypeError("tryShutdown can only be called on a Server"); - } - Server *server = ObjectWrap::Unwrap(info.This()); - if (server->wrapped_server == NULL) { - // Server is already shut down. Call callback immediately. - Nan::Callback callback(info[0].As()); - callback.Call(0, {}); - return; - } - TryShutdownOp *op = new TryShutdownOp(server, info.This()); - unique_ptr ops(new OpVec()); - ops->push_back(unique_ptr(op)); - grpc_server_shutdown_and_notify( - server->wrapped_server, GetCompletionQueue(), - new struct tag(new Nan::Callback(info[0].As()), ops.release(), - NULL, Nan::Null())); - CompletionQueueNext(); -} - -NAN_METHOD(Server::ForceShutdown) { - Nan::HandleScope scope; - if (!HasInstance(info.This())) { - return Nan::ThrowTypeError("forceShutdown can only be called on a Server"); - } - Server *server = ObjectWrap::Unwrap(info.This()); - server->ShutdownServer(); -} - -} // namespace node -} // namespace grpc diff --git a/src/node/ext/server.h b/src/node/ext/server.h deleted file mode 100644 index 66b3ac52672..00000000000 --- a/src/node/ext/server.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef NET_GRPC_NODE_SERVER_H_ -#define NET_GRPC_NODE_SERVER_H_ - -#include -#include -#include "grpc/grpc.h" - -namespace grpc { -namespace node { - -/* Wraps grpc_server as a JavaScript object. Provides a constructor - and wrapper methods for grpc_server_create, grpc_server_request_call, - grpc_server_add_http2_port, and grpc_server_start. */ -class Server : public Nan::ObjectWrap { - public: - /* Initializes the Server class and exposes the constructor and - wrapper methods to JavaScript */ - static void Init(v8::Local exports); - /* Tests whether the given value was constructed by this class's - JavaScript constructor */ - static bool HasInstance(v8::Local val); - - void DestroyWrappedServer(); - - private: - explicit Server(grpc_server *server); - ~Server(); - - // Prevent copying - Server(const Server &); - Server &operator=(const Server &); - - void ShutdownServer(); - - static NAN_METHOD(New); - static NAN_METHOD(RequestCall); - static NAN_METHOD(AddHttp2Port); - static NAN_METHOD(Start); - static NAN_METHOD(TryShutdown); - static NAN_METHOD(ForceShutdown); - static Nan::Callback *constructor; - static Nan::Persistent fun_tpl; - - grpc_server *wrapped_server; - grpc_completion_queue *shutdown_queue; -}; - -} // namespace node -} // namespace grpc - -#endif // NET_GRPC_NODE_SERVER_H_ diff --git a/src/node/ext/server_credentials.cc b/src/node/ext/server_credentials.cc deleted file mode 100644 index b7fa4788445..00000000000 --- a/src/node/ext/server_credentials.cc +++ /dev/null @@ -1,190 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include - -#include "grpc/grpc.h" -#include "grpc/grpc_security.h" -#include "grpc/support/log.h" -#include "server_credentials.h" - -namespace grpc { -namespace node { - -using Nan::Callback; -using Nan::EscapableHandleScope; -using Nan::HandleScope; -using Nan::Maybe; -using Nan::MaybeLocal; -using Nan::ObjectWrap; -using Nan::Persistent; -using Nan::Utf8String; - -using v8::Array; -using v8::Exception; -using v8::External; -using v8::Function; -using v8::FunctionTemplate; -using v8::Integer; -using v8::Local; -using v8::Object; -using v8::ObjectTemplate; -using v8::String; -using v8::Value; - -Nan::Callback *ServerCredentials::constructor; -Persistent ServerCredentials::fun_tpl; - -ServerCredentials::ServerCredentials(grpc_server_credentials *credentials) - : wrapped_credentials(credentials) {} - -ServerCredentials::~ServerCredentials() { - grpc_server_credentials_release(wrapped_credentials); -} - -void ServerCredentials::Init(Local exports) { - Nan::HandleScope scope; - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("ServerCredentials").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - Local ctr = tpl->GetFunction(); - Nan::Set( - ctr, Nan::New("createSsl").ToLocalChecked(), - Nan::GetFunction(Nan::New(CreateSsl)).ToLocalChecked()); - Nan::Set(ctr, Nan::New("createInsecure").ToLocalChecked(), - Nan::GetFunction(Nan::New(CreateInsecure)) - .ToLocalChecked()); - fun_tpl.Reset(tpl); - constructor = new Nan::Callback(ctr); - Nan::Set(exports, Nan::New("ServerCredentials").ToLocalChecked(), ctr); -} - -bool ServerCredentials::HasInstance(Local val) { - Nan::HandleScope scope; - return Nan::New(fun_tpl)->HasInstance(val); -} - -Local ServerCredentials::WrapStruct( - grpc_server_credentials *credentials) { - Nan::EscapableHandleScope scope; - const int argc = 1; - Local argv[argc] = { - Nan::New(reinterpret_cast(credentials))}; - MaybeLocal maybe_instance = - Nan::NewInstance(constructor->GetFunction(), argc, argv); - if (maybe_instance.IsEmpty()) { - return scope.Escape(Nan::Null()); - } else { - return scope.Escape(maybe_instance.ToLocalChecked()); - } -} - -grpc_server_credentials *ServerCredentials::GetWrappedServerCredentials() { - return wrapped_credentials; -} - -NAN_METHOD(ServerCredentials::New) { - if (info.IsConstructCall()) { - if (!info[0]->IsExternal()) { - return Nan::ThrowTypeError( - "ServerCredentials can only be created with the provided functions"); - } - Local ext = info[0].As(); - grpc_server_credentials *creds_value = - reinterpret_cast(ext->Value()); - ServerCredentials *credentials = new ServerCredentials(creds_value); - credentials->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } else { - // This should never be called directly - return Nan::ThrowTypeError( - "ServerCredentials can only be created with the provided functions"); - } -} - -NAN_METHOD(ServerCredentials::CreateSsl) { - Nan::HandleScope scope; - char *root_certs = NULL; - if (::node::Buffer::HasInstance(info[0])) { - root_certs = ::node::Buffer::Data(info[0]); - } else if (!(info[0]->IsNull() || info[0]->IsUndefined())) { - return Nan::ThrowTypeError( - "createSSl's first argument must be a Buffer if provided"); - } - if (!info[1]->IsArray()) { - return Nan::ThrowTypeError( - "createSsl's second argument must be a list of objects"); - } - - // Default to not requesting the client certificate - grpc_ssl_client_certificate_request_type client_certificate_request = - GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE; - if (info[2]->IsBoolean()) { - client_certificate_request = - Nan::To(info[2]).FromJust() - ? GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY - : GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE; - } else if (!(info[2]->IsUndefined() || info[2]->IsNull())) { - return Nan::ThrowTypeError( - "createSsl's third argument must be a boolean if provided"); - } - Local pair_list = Local::Cast(info[1]); - uint32_t key_cert_pair_count = pair_list->Length(); - grpc_ssl_pem_key_cert_pair *key_cert_pairs = - new grpc_ssl_pem_key_cert_pair[key_cert_pair_count]; - - Local key_key = Nan::New("private_key").ToLocalChecked(); - Local cert_key = Nan::New("cert_chain").ToLocalChecked(); - - for (uint32_t i = 0; i < key_cert_pair_count; i++) { - Local pair_val = Nan::Get(pair_list, i).ToLocalChecked(); - if (!pair_val->IsObject()) { - delete[] key_cert_pairs; - return Nan::ThrowTypeError("Key/cert pairs must be objects"); - } - Local pair_obj = Nan::To(pair_val).ToLocalChecked(); - Local maybe_key = Nan::Get(pair_obj, key_key).ToLocalChecked(); - Local maybe_cert = Nan::Get(pair_obj, cert_key).ToLocalChecked(); - if (!::node::Buffer::HasInstance(maybe_key)) { - delete[] key_cert_pairs; - return Nan::ThrowTypeError("private_key must be a Buffer"); - } - if (!::node::Buffer::HasInstance(maybe_cert)) { - delete[] key_cert_pairs; - return Nan::ThrowTypeError("cert_chain must be a Buffer"); - } - key_cert_pairs[i].private_key = ::node::Buffer::Data(maybe_key); - key_cert_pairs[i].cert_chain = ::node::Buffer::Data(maybe_cert); - } - grpc_server_credentials *creds = grpc_ssl_server_credentials_create_ex( - root_certs, key_cert_pairs, key_cert_pair_count, - client_certificate_request, NULL); - delete[] key_cert_pairs; - if (creds == NULL) { - info.GetReturnValue().SetNull(); - } else { - info.GetReturnValue().Set(WrapStruct(creds)); - } -} - -NAN_METHOD(ServerCredentials::CreateInsecure) { - info.GetReturnValue().Set(WrapStruct(NULL)); -} - -} // namespace node -} // namespace grpc diff --git a/src/node/ext/server_credentials.h b/src/node/ext/server_credentials.h deleted file mode 100644 index 59f91481a23..00000000000 --- a/src/node/ext/server_credentials.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef NET_GRPC_NODE_SERVER_CREDENTIALS_H_ -#define NET_GRPC_NODE_SERVER_CREDENTIALS_H_ - -#include -#include -#include "grpc/grpc.h" -#include "grpc/grpc_security.h" - -namespace grpc { -namespace node { - -/* Wrapper class for grpc_server_credentials structs */ -class ServerCredentials : public Nan::ObjectWrap { - public: - static void Init(v8::Local exports); - static bool HasInstance(v8::Local val); - /* Wrap a grpc_server_credentials struct in a javascript object */ - static v8::Local WrapStruct(grpc_server_credentials *credentials); - - /* Returns the grpc_server_credentials struct that this object wraps */ - grpc_server_credentials *GetWrappedServerCredentials(); - - private: - explicit ServerCredentials(grpc_server_credentials *credentials); - ~ServerCredentials(); - - // Prevent copying - ServerCredentials(const ServerCredentials &); - ServerCredentials &operator=(const ServerCredentials &); - - static NAN_METHOD(New); - static NAN_METHOD(CreateSsl); - static NAN_METHOD(CreateInsecure); - static Nan::Callback *constructor; - // Used for typechecking instances of this javascript class - static Nan::Persistent fun_tpl; - - grpc_server_credentials *wrapped_credentials; -}; - -} // namespace node -} // namespace grpc - -#endif // NET_GRPC_NODE_SERVER_CREDENTIALS_H_ diff --git a/src/node/ext/slice.cc b/src/node/ext/slice.cc deleted file mode 100644 index 8806a61a9e2..00000000000 --- a/src/node/ext/slice.cc +++ /dev/null @@ -1,90 +0,0 @@ -/* - * - * 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 -#include -#include -#include - -#include "slice.h" - -namespace grpc { -namespace node { - -using Nan::Persistent; - -using v8::Local; -using v8::String; -using v8::Value; - -namespace { -void SliceFreeCallback(char *data, void *hint) { - grpc_slice *slice = reinterpret_cast(hint); - grpc_slice_unref(*slice); - delete slice; -} - -void string_destroy_func(void *user_data) { - delete reinterpret_cast(user_data); -} - -void buffer_destroy_func(void *user_data) { - delete reinterpret_cast(user_data); -} -} // namespace - -grpc_slice CreateSliceFromString(const Local source) { - Nan::HandleScope scope; - Nan::Utf8String *utf8_value = new Nan::Utf8String(source); - return grpc_slice_new_with_user_data(**utf8_value, source->Length(), - string_destroy_func, utf8_value); -} - -grpc_slice CreateSliceFromBuffer(const Local source) { - // Prerequisite: ::node::Buffer::HasInstance(source) - Nan::HandleScope scope; - return grpc_slice_new_with_user_data( - ::node::Buffer::Data(source), ::node::Buffer::Length(source), - buffer_destroy_func, new PersistentValue(source)); -} -Local CopyStringFromSlice(const grpc_slice slice) { - Nan::EscapableHandleScope scope; - if (GRPC_SLICE_LENGTH(slice) == 0) { - return scope.Escape(Nan::EmptyString()); - } - return scope.Escape( - Nan::New(const_cast(reinterpret_cast( - GRPC_SLICE_START_PTR(slice))), - GRPC_SLICE_LENGTH(slice)) - .ToLocalChecked()); -} - -Local CreateBufferFromSlice(const grpc_slice slice) { - Nan::EscapableHandleScope scope; - grpc_slice *slice_ptr = new grpc_slice; - *slice_ptr = grpc_slice_ref(slice); - return scope.Escape( - Nan::NewBuffer( - const_cast( - reinterpret_cast(GRPC_SLICE_START_PTR(*slice_ptr))), - GRPC_SLICE_LENGTH(*slice_ptr), SliceFreeCallback, slice_ptr) - .ToLocalChecked()); -} - -} // namespace node -} // namespace grpc diff --git a/src/node/ext/timeval.cc b/src/node/ext/timeval.cc deleted file mode 100644 index 6142584759c..00000000000 --- a/src/node/ext/timeval.cc +++ /dev/null @@ -1,53 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include -#include - -#include "grpc/grpc.h" -#include "grpc/support/time.h" -#include "timeval.h" - -namespace grpc { -namespace node { - -gpr_timespec MillisecondsToTimespec(double millis) { - if (millis == std::numeric_limits::infinity()) { - return gpr_inf_future(GPR_CLOCK_REALTIME); - } else if (millis == -std::numeric_limits::infinity()) { - return gpr_inf_past(GPR_CLOCK_REALTIME); - } else { - return gpr_time_from_micros(static_cast(millis * 1000), - GPR_CLOCK_REALTIME); - } -} - -double TimespecToMilliseconds(gpr_timespec timespec) { - timespec = gpr_convert_clock_type(timespec, GPR_CLOCK_REALTIME); - if (gpr_time_cmp(timespec, gpr_inf_future(GPR_CLOCK_REALTIME)) == 0) { - return std::numeric_limits::infinity(); - } else if (gpr_time_cmp(timespec, gpr_inf_past(GPR_CLOCK_REALTIME)) == 0) { - return -std::numeric_limits::infinity(); - } else { - return (static_cast(timespec.tv_sec) * 1000 + - static_cast(timespec.tv_nsec) / 1000000); - } -} - -} // namespace node -} // namespace grpc diff --git a/src/node/health_check/LICENSE b/src/node/health_check/LICENSE deleted file mode 100644 index 7750ce4fdd4..00000000000 --- a/src/node/health_check/LICENSE +++ /dev/null @@ -1,186 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for any such Derivative Works as a whole, provided Your use, - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2015-2017 gRPC authors. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/src/node/health_check/health.js b/src/node/health_check/health.js deleted file mode 100644 index 7ad2c1e217e..00000000000 --- a/src/node/health_check/health.js +++ /dev/null @@ -1,52 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var grpc = require('grpc'); - -var _ = require('lodash'); - -var health_messages = require('./v1/health_pb'); -var health_service = require('./v1/health_grpc_pb'); - -function HealthImplementation(statusMap) { - this.statusMap = _.clone(statusMap); -} - -HealthImplementation.prototype.setStatus = function(service, status) { - this.statusMap[service] = status; -}; - -HealthImplementation.prototype.check = function(call, callback){ - var service = call.request.getService(); - var status = _.get(this.statusMap, service, null); - if (status === null) { - callback({code:grpc.status.NOT_FOUND}); - } else { - var response = new health_messages.HealthCheckResponse(); - response.setStatus(status); - callback(null, response); - } -}; - -module.exports = { - Client: health_service.HealthClient, - service: health_service.HealthService, - Implementation: HealthImplementation -}; diff --git a/src/node/health_check/package.json b/src/node/health_check/package.json index 6f09c8f9f09..fca3a2a7a6b 100644 --- a/src/node/health_check/package.json +++ b/src/node/health_check/package.json @@ -1,6 +1,6 @@ { "name": "grpc-health-check", - "version": "1.8.0-dev", + "version": "1.7.2", "author": "Google Inc.", "description": "Health check service for use with gRPC", "repository": { @@ -15,7 +15,7 @@ } ], "dependencies": { - "grpc": "^1.8.0-dev", + "grpc": "^1.7.2", "lodash": "^3.9.3", "google-protobuf": "^3.0.0" }, diff --git a/src/node/health_check/v1/health_grpc_pb.js b/src/node/health_check/v1/health_grpc_pb.js deleted file mode 100644 index 2a1ac6ff75c..00000000000 --- a/src/node/health_check/v1/health_grpc_pb.js +++ /dev/null @@ -1,59 +0,0 @@ -// GENERATED CODE -- DO NOT EDIT! - -// Original file comments: -// Copyright 2015 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -'use strict'; -var grpc = require('grpc'); -var v1_health_pb = require('../v1/health_pb.js'); - -function serialize_HealthCheckRequest(arg) { - if (!(arg instanceof v1_health_pb.HealthCheckRequest)) { - throw new Error('Expected argument of type HealthCheckRequest'); - } - return new Buffer(arg.serializeBinary()); -} - -function deserialize_HealthCheckRequest(buffer_arg) { - return v1_health_pb.HealthCheckRequest.deserializeBinary(new Uint8Array(buffer_arg)); -} - -function serialize_HealthCheckResponse(arg) { - if (!(arg instanceof v1_health_pb.HealthCheckResponse)) { - throw new Error('Expected argument of type HealthCheckResponse'); - } - return new Buffer(arg.serializeBinary()); -} - -function deserialize_HealthCheckResponse(buffer_arg) { - return v1_health_pb.HealthCheckResponse.deserializeBinary(new Uint8Array(buffer_arg)); -} - - -var HealthService = exports.HealthService = { - check: { - path: '/grpc.health.v1.Health/Check', - requestStream: false, - responseStream: false, - requestType: v1_health_pb.HealthCheckRequest, - responseType: v1_health_pb.HealthCheckResponse, - requestSerialize: serialize_HealthCheckRequest, - requestDeserialize: deserialize_HealthCheckRequest, - responseSerialize: serialize_HealthCheckResponse, - responseDeserialize: deserialize_HealthCheckResponse, - }, -}; - -exports.HealthClient = grpc.makeGenericClientConstructor(HealthService); diff --git a/src/node/health_check/v1/health_pb.js b/src/node/health_check/v1/health_pb.js deleted file mode 100644 index b36d47cdbb9..00000000000 --- a/src/node/health_check/v1/health_pb.js +++ /dev/null @@ -1,342 +0,0 @@ -/** - * @fileoverview - * @enhanceable - * @public - */ -// GENERATED CODE -- DO NOT EDIT! - -var jspb = require('google-protobuf'); -var goog = jspb; -var global = Function('return this')(); - -goog.exportSymbol('proto.grpc.health.v1.HealthCheckRequest', null, global); -goog.exportSymbol('proto.grpc.health.v1.HealthCheckResponse', null, global); -goog.exportSymbol('proto.grpc.health.v1.HealthCheckResponse.ServingStatus', null, global); - -/** - * Generated by JsPbCodeGenerator. - * @param {Array=} opt_data Optional initial data array, typically from a - * server response, or constructed directly in Javascript. The array is used - * in place and becomes part of the constructed object. It is not cloned. - * If no data is provided, the constructed object will be empty, but still - * valid. - * @extends {jspb.Message} - * @constructor - */ -proto.grpc.health.v1.HealthCheckRequest = function(opt_data) { - jspb.Message.initialize(this, opt_data, 0, -1, null, null); -}; -goog.inherits(proto.grpc.health.v1.HealthCheckRequest, jspb.Message); -if (goog.DEBUG && !COMPILED) { - proto.grpc.health.v1.HealthCheckRequest.displayName = 'proto.grpc.health.v1.HealthCheckRequest'; -} - - -if (jspb.Message.GENERATE_TO_OBJECT) { -/** - * Creates an object representation of this proto suitable for use in Soy templates. - * Field names that are reserved in JavaScript and will be renamed to pb_name. - * To access a reserved field use, foo.pb_, eg, foo.pb_default. - * For the list of reserved names please see: - * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. - * @param {boolean=} opt_includeInstance Whether to include the JSPB instance - * for transitional soy proto support: http://goto/soy-param-migration - * @return {!Object} - */ -proto.grpc.health.v1.HealthCheckRequest.prototype.toObject = function(opt_includeInstance) { - return proto.grpc.health.v1.HealthCheckRequest.toObject(opt_includeInstance, this); -}; - - -/** - * Static version of the {@see toObject} method. - * @param {boolean|undefined} includeInstance Whether to include the JSPB - * instance for transitional soy proto support: - * http://goto/soy-param-migration - * @param {!proto.grpc.health.v1.HealthCheckRequest} msg The msg instance to transform. - * @return {!Object} - */ -proto.grpc.health.v1.HealthCheckRequest.toObject = function(includeInstance, msg) { - var f, obj = { - service: msg.getService() - }; - - if (includeInstance) { - obj.$jspbMessageInstance = msg; - } - return obj; -}; -} - - -/** - * Deserializes binary data (in protobuf wire format). - * @param {jspb.ByteSource} bytes The bytes to deserialize. - * @return {!proto.grpc.health.v1.HealthCheckRequest} - */ -proto.grpc.health.v1.HealthCheckRequest.deserializeBinary = function(bytes) { - var reader = new jspb.BinaryReader(bytes); - var msg = new proto.grpc.health.v1.HealthCheckRequest; - return proto.grpc.health.v1.HealthCheckRequest.deserializeBinaryFromReader(msg, reader); -}; - - -/** - * Deserializes binary data (in protobuf wire format) from the - * given reader into the given message object. - * @param {!proto.grpc.health.v1.HealthCheckRequest} msg The message object to deserialize into. - * @param {!jspb.BinaryReader} reader The BinaryReader to use. - * @return {!proto.grpc.health.v1.HealthCheckRequest} - */ -proto.grpc.health.v1.HealthCheckRequest.deserializeBinaryFromReader = function(msg, reader) { - while (reader.nextField()) { - if (reader.isEndGroup()) { - break; - } - var field = reader.getFieldNumber(); - switch (field) { - case 1: - var value = /** @type {string} */ (reader.readString()); - msg.setService(value); - break; - default: - reader.skipField(); - break; - } - } - return msg; -}; - - -/** - * Class method variant: serializes the given message to binary data - * (in protobuf wire format), writing to the given BinaryWriter. - * @param {!proto.grpc.health.v1.HealthCheckRequest} message - * @param {!jspb.BinaryWriter} writer - */ -proto.grpc.health.v1.HealthCheckRequest.serializeBinaryToWriter = function(message, writer) { - message.serializeBinaryToWriter(writer); -}; - - -/** - * Serializes the message to binary data (in protobuf wire format). - * @return {!Uint8Array} - */ -proto.grpc.health.v1.HealthCheckRequest.prototype.serializeBinary = function() { - var writer = new jspb.BinaryWriter(); - this.serializeBinaryToWriter(writer); - return writer.getResultBuffer(); -}; - - -/** - * Serializes the message to binary data (in protobuf wire format), - * writing to the given BinaryWriter. - * @param {!jspb.BinaryWriter} writer - */ -proto.grpc.health.v1.HealthCheckRequest.prototype.serializeBinaryToWriter = function (writer) { - var f = undefined; - f = this.getService(); - if (f.length > 0) { - writer.writeString( - 1, - f - ); - } -}; - - -/** - * Creates a deep clone of this proto. No data is shared with the original. - * @return {!proto.grpc.health.v1.HealthCheckRequest} The clone. - */ -proto.grpc.health.v1.HealthCheckRequest.prototype.cloneMessage = function() { - return /** @type {!proto.grpc.health.v1.HealthCheckRequest} */ (jspb.Message.cloneMessage(this)); -}; - - -/** - * optional string service = 1; - * @return {string} - */ -proto.grpc.health.v1.HealthCheckRequest.prototype.getService = function() { - return /** @type {string} */ (jspb.Message.getFieldProto3(this, 1, "")); -}; - - -/** @param {string} value */ -proto.grpc.health.v1.HealthCheckRequest.prototype.setService = function(value) { - jspb.Message.setField(this, 1, value); -}; - - - -/** - * Generated by JsPbCodeGenerator. - * @param {Array=} opt_data Optional initial data array, typically from a - * server response, or constructed directly in Javascript. The array is used - * in place and becomes part of the constructed object. It is not cloned. - * If no data is provided, the constructed object will be empty, but still - * valid. - * @extends {jspb.Message} - * @constructor - */ -proto.grpc.health.v1.HealthCheckResponse = function(opt_data) { - jspb.Message.initialize(this, opt_data, 0, -1, null, null); -}; -goog.inherits(proto.grpc.health.v1.HealthCheckResponse, jspb.Message); -if (goog.DEBUG && !COMPILED) { - proto.grpc.health.v1.HealthCheckResponse.displayName = 'proto.grpc.health.v1.HealthCheckResponse'; -} - - -if (jspb.Message.GENERATE_TO_OBJECT) { -/** - * Creates an object representation of this proto suitable for use in Soy templates. - * Field names that are reserved in JavaScript and will be renamed to pb_name. - * To access a reserved field use, foo.pb_, eg, foo.pb_default. - * For the list of reserved names please see: - * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. - * @param {boolean=} opt_includeInstance Whether to include the JSPB instance - * for transitional soy proto support: http://goto/soy-param-migration - * @return {!Object} - */ -proto.grpc.health.v1.HealthCheckResponse.prototype.toObject = function(opt_includeInstance) { - return proto.grpc.health.v1.HealthCheckResponse.toObject(opt_includeInstance, this); -}; - - -/** - * Static version of the {@see toObject} method. - * @param {boolean|undefined} includeInstance Whether to include the JSPB - * instance for transitional soy proto support: - * http://goto/soy-param-migration - * @param {!proto.grpc.health.v1.HealthCheckResponse} msg The msg instance to transform. - * @return {!Object} - */ -proto.grpc.health.v1.HealthCheckResponse.toObject = function(includeInstance, msg) { - var f, obj = { - status: msg.getStatus() - }; - - if (includeInstance) { - obj.$jspbMessageInstance = msg; - } - return obj; -}; -} - - -/** - * Deserializes binary data (in protobuf wire format). - * @param {jspb.ByteSource} bytes The bytes to deserialize. - * @return {!proto.grpc.health.v1.HealthCheckResponse} - */ -proto.grpc.health.v1.HealthCheckResponse.deserializeBinary = function(bytes) { - var reader = new jspb.BinaryReader(bytes); - var msg = new proto.grpc.health.v1.HealthCheckResponse; - return proto.grpc.health.v1.HealthCheckResponse.deserializeBinaryFromReader(msg, reader); -}; - - -/** - * Deserializes binary data (in protobuf wire format) from the - * given reader into the given message object. - * @param {!proto.grpc.health.v1.HealthCheckResponse} msg The message object to deserialize into. - * @param {!jspb.BinaryReader} reader The BinaryReader to use. - * @return {!proto.grpc.health.v1.HealthCheckResponse} - */ -proto.grpc.health.v1.HealthCheckResponse.deserializeBinaryFromReader = function(msg, reader) { - while (reader.nextField()) { - if (reader.isEndGroup()) { - break; - } - var field = reader.getFieldNumber(); - switch (field) { - case 1: - var value = /** @type {!proto.grpc.health.v1.HealthCheckResponse.ServingStatus} */ (reader.readEnum()); - msg.setStatus(value); - break; - default: - reader.skipField(); - break; - } - } - return msg; -}; - - -/** - * Class method variant: serializes the given message to binary data - * (in protobuf wire format), writing to the given BinaryWriter. - * @param {!proto.grpc.health.v1.HealthCheckResponse} message - * @param {!jspb.BinaryWriter} writer - */ -proto.grpc.health.v1.HealthCheckResponse.serializeBinaryToWriter = function(message, writer) { - message.serializeBinaryToWriter(writer); -}; - - -/** - * Serializes the message to binary data (in protobuf wire format). - * @return {!Uint8Array} - */ -proto.grpc.health.v1.HealthCheckResponse.prototype.serializeBinary = function() { - var writer = new jspb.BinaryWriter(); - this.serializeBinaryToWriter(writer); - return writer.getResultBuffer(); -}; - - -/** - * Serializes the message to binary data (in protobuf wire format), - * writing to the given BinaryWriter. - * @param {!jspb.BinaryWriter} writer - */ -proto.grpc.health.v1.HealthCheckResponse.prototype.serializeBinaryToWriter = function (writer) { - var f = undefined; - f = this.getStatus(); - if (f !== 0.0) { - writer.writeEnum( - 1, - f - ); - } -}; - - -/** - * Creates a deep clone of this proto. No data is shared with the original. - * @return {!proto.grpc.health.v1.HealthCheckResponse} The clone. - */ -proto.grpc.health.v1.HealthCheckResponse.prototype.cloneMessage = function() { - return /** @type {!proto.grpc.health.v1.HealthCheckResponse} */ (jspb.Message.cloneMessage(this)); -}; - - -/** - * optional ServingStatus status = 1; - * @return {!proto.grpc.health.v1.HealthCheckResponse.ServingStatus} - */ -proto.grpc.health.v1.HealthCheckResponse.prototype.getStatus = function() { - return /** @type {!proto.grpc.health.v1.HealthCheckResponse.ServingStatus} */ (jspb.Message.getFieldProto3(this, 1, 0)); -}; - - -/** @param {!proto.grpc.health.v1.HealthCheckResponse.ServingStatus} value */ -proto.grpc.health.v1.HealthCheckResponse.prototype.setStatus = function(value) { - jspb.Message.setField(this, 1, value); -}; - - -/** - * @enum {number} - */ -proto.grpc.health.v1.HealthCheckResponse.ServingStatus = { - UNKNOWN: 0, - SERVING: 1, - NOT_SERVING: 2 -}; - -goog.object.extend(exports, proto.grpc.health.v1); diff --git a/src/node/index.js b/src/node/index.js deleted file mode 100644 index 452b11f6dba..00000000000 --- a/src/node/index.js +++ /dev/null @@ -1,255 +0,0 @@ -/** - * @license - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var path = require('path'); -var fs = require('fs'); - -var SSL_ROOTS_PATH = path.resolve(__dirname, '..', '..', 'etc', 'roots.pem'); - -var _ = require('lodash'); - -var ProtoBuf = require('protobufjs'); - -var client = require('./src/client.js'); - -var server = require('./src/server.js'); - -var common = require('./src/common.js'); - -var Metadata = require('./src/metadata.js'); - -var grpc = require('./src/grpc_extension'); - -var protobuf_js_5_common = require('./src/protobuf_js_5_common'); -var protobuf_js_6_common = require('./src/protobuf_js_6_common'); - -var constants = require('./src/constants.js'); - -grpc.setDefaultRootsPem(fs.readFileSync(SSL_ROOTS_PATH, 'ascii')); - -/** - * @namespace grpc - */ - -/** - * Load a ProtoBuf.js object as a gRPC object. - * @memberof grpc - * @alias grpc.loadObject - * @param {Object} value The ProtoBuf.js reflection object to load - * @param {Object=} options Options to apply to the loaded file - * @param {bool=} [options.binaryAsBase64=false] deserialize bytes values as - * base64 strings instead of Buffers - * @param {bool=} [options.longsAsStrings=true] deserialize long values as - * strings instead of objects - * @param {bool=} [options.enumsAsStrings=true] deserialize enum values as - * strings instead of numbers. Only works with Protobuf.js 6 values. - * @param {bool=} [options.deprecatedArgumentOrder=false] use the beta method - * argument order for client methods, with optional arguments after the - * callback. This option is only a temporary stopgap measure to smooth an - * API breakage. It is deprecated, and new code should not use it. - * @param {(number|string)=} [options.protobufjsVersion='detect'] 5 and 6 - * respectively indicate that an object from the corresponding version of - * Protobuf.js is provided in the value argument. If the option is 'detect', - * gRPC wll guess what the version is based on the structure of the value. - * @return {Object} The resulting gRPC object. - */ -exports.loadObject = function loadObject(value, options) { - options = _.defaults(options, common.defaultGrpcOptions); - options = _.defaults(options, {'protobufjsVersion': 'detect'}); - var protobufjsVersion; - if (options.protobufjsVersion === 'detect') { - if (protobuf_js_6_common.isProbablyProtobufJs6(value)) { - protobufjsVersion = 6; - } else if (protobuf_js_5_common.isProbablyProtobufJs5(value)) { - protobufjsVersion = 5; - } else { - var error_message = 'Could not detect ProtoBuf.js version. Please ' + - 'specify the version number with the "protobufjs_version" option'; - throw new Error(error_message); - } - } else { - protobufjsVersion = options.protobufjsVersion; - } - switch (protobufjsVersion) { - case 6: return protobuf_js_6_common.loadObject(value, options); - case 5: - return protobuf_js_5_common.loadObject(value, options); - default: - throw new Error('Unrecognized protobufjsVersion', protobufjsVersion); - } -}; - -var loadObject = exports.loadObject; - -/** - * Load a gRPC object from a .proto file. - * @memberof grpc - * @alias grpc.load - * @param {string|{root: string, file: string}} filename The file to load - * @param {string=} format The file format to expect. Must be either 'proto' or - * 'json'. Defaults to 'proto' - * @param {Object=} options Options to apply to the loaded file - * @param {bool=} [options.convertFieldsToCamelCase=false] Load this file with - * field names in camel case instead of their original case - * @param {bool=} [options.binaryAsBase64=false] deserialize bytes values as - * base64 strings instead of Buffers - * @param {bool=} [options.longsAsStrings=true] deserialize long values as - * strings instead of objects - * @param {bool=} [options.deprecatedArgumentOrder=false] use the beta method - * argument order for client methods, with optional arguments after the - * callback. This option is only a temporary stopgap measure to smooth an - * API breakage. It is deprecated, and new code should not use it. - * @return {Object} The resulting gRPC object - */ -exports.load = function load(filename, format, options) { - options = _.defaults(options, common.defaultGrpcOptions); - options.protobufjsVersion = 5; - if (!format) { - format = 'proto'; - } - var convertFieldsToCamelCaseOriginal = ProtoBuf.convertFieldsToCamelCase; - if(options && options.hasOwnProperty('convertFieldsToCamelCase')) { - ProtoBuf.convertFieldsToCamelCase = options.convertFieldsToCamelCase; - } - var builder; - try { - switch(format) { - case 'proto': - builder = ProtoBuf.loadProtoFile(filename); - break; - case 'json': - builder = ProtoBuf.loadJsonFile(filename); - break; - default: - throw new Error('Unrecognized format "' + format + '"'); - } - } finally { - ProtoBuf.convertFieldsToCamelCase = convertFieldsToCamelCaseOriginal; - } - return loadObject(builder.ns, options); -}; - -var log_template = _.template( - '{severity} {timestamp}\t{file}:{line}]\t{message}', - {interpolate: /{([\s\S]+?)}/g}); - -/** - * Sets the logger function for the gRPC module. For debugging purposes, the C - * core will log synchronously directly to stdout unless this function is - * called. Note: the output format here is intended to be informational, and - * is not guaranteed to stay the same in the future. - * Logs will be directed to logger.error. - * @memberof grpc - * @alias grpc.setLogger - * @param {Console} logger A Console-like object. - */ -exports.setLogger = function setLogger(logger) { - common.logger = logger; - grpc.setDefaultLoggerCallback(function(file, line, severity, - message, timestamp) { - logger.error(log_template({ - file: path.basename(file), - line: line, - severity: severity, - message: message, - timestamp: timestamp.toISOString() - })); - }); -}; - -/** - * Sets the logger verbosity for gRPC module logging. The options are members - * of the grpc.logVerbosity map. - * @memberof grpc - * @alias grpc.setLogVerbosity - * @param {Number} verbosity The minimum severity to log - */ -exports.setLogVerbosity = function setLogVerbosity(verbosity) { - common.logVerbosity = verbosity; - grpc.setLogVerbosity(verbosity); -}; - -exports.Server = server.Server; - -exports.Metadata = Metadata; - -exports.status = constants.status; - -exports.propagate = constants.propagate; - -exports.callError = constants.callError; - -exports.writeFlags = constants.writeFlags; - -exports.logVerbosity = constants.logVerbosity; - -exports.credentials = require('./src/credentials.js'); - -/** - * ServerCredentials factories - * @constructor ServerCredentials - * @memberof grpc - */ -exports.ServerCredentials = grpc.ServerCredentials; - -/** - * Create insecure server credentials - * @name grpc.ServerCredentials.createInsecure - * @kind function - * @return grpc.ServerCredentials - */ - -/** - * A private key and certificate pair - * @typedef {Object} grpc.ServerCredentials~keyCertPair - * @property {Buffer} privateKey The server's private key - * @property {Buffer} certChain The server's certificate chain - */ - -/** - * Create SSL server credentials - * @name grpc.ServerCredentials.createInsecure - * @kind function - * @param {?Buffer} rootCerts Root CA certificates for validating client - * certificates - * @param {Array} keyCertPairs A list of - * private key and certificate chain pairs to be used for authenticating - * the server - * @param {boolean} [checkClientCertificate=false] Indicates that the server - * should request and verify the client's certificates - * @return grpc.ServerCredentials - */ - -exports.makeGenericClientConstructor = client.makeClientConstructor; - -exports.getClientChannel = client.getClientChannel; - -exports.waitForClientReady = client.waitForClientReady; - -/** - * @memberof grpc - * @alias grpc.closeClient - * @param {grpc.Client} client_obj The client to close - */ -exports.closeClient = function closeClient(client_obj) { - client.Client.prototype.close.apply(client_obj); -}; - -exports.Client = client.Client; diff --git a/src/node/interop/async_delay_queue.js b/src/node/interop/async_delay_queue.js deleted file mode 100644 index 43ac5738746..00000000000 --- a/src/node/interop/async_delay_queue.js +++ /dev/null @@ -1,64 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var _ = require('lodash'); - -/** - * This class represents a queue of callbacks that must happen sequentially, - * each with a specific delay after the previous event. - */ -function AsyncDelayQueue() { - this.queue = []; - - this.callback_pending = false; -} - -/** - * Run the next callback after its corresponding delay, if there are any - * remaining. - */ -AsyncDelayQueue.prototype.runNext = function() { - var next = this.queue.shift(); - var continueCallback = _.bind(this.runNext, this); - if (next) { - this.callback_pending = true; - setTimeout(function() { - next.callback(continueCallback); - }, next.delay); - } else { - this.callback_pending = false; - } -}; - -/** - * Add a callback to be called with a specific delay after now or after the - * current last item in the queue or current pending callback, whichever is - * latest. - * @param {function(function())} callback The callback - * @param {Number} The delay to apply, in milliseconds - */ -AsyncDelayQueue.prototype.add = function(callback, delay) { - this.queue.push({callback: callback, delay: delay}); - if (!this.callback_pending) { - this.runNext(); - } -}; - -module.exports = AsyncDelayQueue; diff --git a/src/node/interop/interop_client.js b/src/node/interop/interop_client.js deleted file mode 100644 index f321d58aa61..00000000000 --- a/src/node/interop/interop_client.js +++ /dev/null @@ -1,621 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var fs = require('fs'); -var path = require('path'); -var grpc = require('..'); -var testProto = grpc.load({ - root: __dirname + '/../../..', - file: 'src/proto/grpc/testing/test.proto'}).grpc.testing; -var GoogleAuth = require('google-auth-library'); - -var assert = require('assert'); - -var SERVICE_ACCOUNT_EMAIL; -try { - SERVICE_ACCOUNT_EMAIL = require( - process.env.GOOGLE_APPLICATION_CREDENTIALS).client_email; -} catch (e) { - // This will cause the tests to fail if they need that string - SERVICE_ACCOUNT_EMAIL = null; -} - -var ECHO_INITIAL_KEY = 'x-grpc-test-echo-initial'; -var ECHO_TRAILING_KEY = 'x-grpc-test-echo-trailing-bin'; - -/** - * Create a buffer filled with size zeroes - * @param {number} size The length of the buffer - * @return {Buffer} The new buffer - */ -function zeroBuffer(size) { - var zeros = new Buffer(size); - zeros.fill(0); - return zeros; -} - -/** - * This is used for testing functions with multiple asynchronous calls that - * can happen in different orders. This should be passed the number of async - * function invocations that can occur last, and each of those should call this - * function's return value - * @param {function()} done The function that should be called when a test is - * complete. - * @param {number} count The number of calls to the resulting function if the - * test passes. - * @return {function()} The function that should be called at the end of each - * sequence of asynchronous functions. - */ -function multiDone(done, count) { - return function() { - count -= 1; - if (count <= 0) { - done(); - } - }; -} - -/** - * Run the empty_unary test - * @param {Client} client The client to test against - * @param {function} done Callback to call when the test is completed. Included - * primarily for use with mocha - */ -function emptyUnary(client, done) { - client.emptyCall({}, function(err, resp) { - assert.ifError(err); - if (done) { - done(); - } - }); -} - -/** - * Run the large_unary test - * @param {Client} client The client to test against - * @param {function} done Callback to call when the test is completed. Included - * primarily for use with mocha - */ -function largeUnary(client, done) { - var arg = { - response_type: 'COMPRESSABLE', - response_size: 314159, - payload: { - body: zeroBuffer(271828) - } - }; - client.unaryCall(arg, function(err, resp) { - assert.ifError(err); - assert.strictEqual(resp.payload.type, 'COMPRESSABLE'); - assert.strictEqual(resp.payload.body.length, 314159); - if (done) { - done(); - } - }); -} - -/** - * Run the client_streaming test - * @param {Client} client The client to test against - * @param {function} done Callback to call when the test is completed. Included - * primarily for use with mocha - */ -function clientStreaming(client, done) { - var call = client.streamingInputCall(function(err, resp) { - assert.ifError(err); - assert.strictEqual(resp.aggregated_payload_size, 74922); - if (done) { - done(); - } - }); - var payload_sizes = [27182, 8, 1828, 45904]; - for (var i = 0; i < payload_sizes.length; i++) { - call.write({payload: {body: zeroBuffer(payload_sizes[i])}}); - } - call.end(); -} - -/** - * Run the server_streaming test - * @param {Client} client The client to test against - * @param {function} done Callback to call when the test is completed. Included - * primarily for use with mocha - */ -function serverStreaming(client, done) { - var arg = { - response_type: 'COMPRESSABLE', - response_parameters: [ - {size: 31415}, - {size: 9}, - {size: 2653}, - {size: 58979} - ] - }; - var call = client.streamingOutputCall(arg); - var resp_index = 0; - call.on('data', function(value) { - assert(resp_index < 4); - assert.strictEqual(value.payload.type, 'COMPRESSABLE'); - assert.strictEqual(value.payload.body.length, - arg.response_parameters[resp_index].size); - resp_index += 1; - }); - call.on('end', function() { - assert.strictEqual(resp_index, 4); - if (done) { - done(); - } - }); - call.on('status', function(status) { - assert.strictEqual(status.code, grpc.status.OK); - }); -} - -/** - * Run the ping_pong test - * @param {Client} client The client to test against - * @param {function} done Callback to call when the test is completed. Included - * primarily for use with mocha - */ -function pingPong(client, done) { - var payload_sizes = [27182, 8, 1828, 45904]; - var response_sizes = [31415, 9, 2653, 58979]; - var call = client.fullDuplexCall(); - call.on('status', function(status) { - assert.strictEqual(status.code, grpc.status.OK); - if (done) { - done(); - } - }); - var index = 0; - call.write({ - response_type: 'COMPRESSABLE', - response_parameters: [ - {size: response_sizes[index]} - ], - payload: {body: zeroBuffer(payload_sizes[index])} - }); - call.on('data', function(response) { - assert.strictEqual(response.payload.type, 'COMPRESSABLE'); - assert.equal(response.payload.body.length, response_sizes[index]); - index += 1; - if (index === 4) { - call.end(); - } else { - call.write({ - response_type: 'COMPRESSABLE', - response_parameters: [ - {size: response_sizes[index]} - ], - payload: {body: zeroBuffer(payload_sizes[index])} - }); - } - }); -} - -/** - * Run the empty_stream test. - * @param {Client} client The client to test against - * @param {function} done Callback to call when the test is completed. Included - * primarily for use with mocha - */ -function emptyStream(client, done) { - var call = client.fullDuplexCall(); - call.on('status', function(status) { - assert.strictEqual(status.code, grpc.status.OK); - if (done) { - done(); - } - }); - call.on('data', function(value) { - assert.fail(value, null, 'No data should have been received', '!=='); - }); - call.end(); -} - -/** - * Run the cancel_after_begin test. - * @param {Client} client The client to test against - * @param {function} done Callback to call when the test is completed. Included - * primarily for use with mocha - */ -function cancelAfterBegin(client, done) { - var call = client.streamingInputCall(function(err, resp) { - assert.strictEqual(err.code, grpc.status.CANCELLED); - done(); - }); - call.cancel(); -} - -/** - * Run the cancel_after_first_response test. - * @param {Client} client The client to test against - * @param {function} done Callback to call when the test is completed. Included - * primarily for use with mocha - */ -function cancelAfterFirstResponse(client, done) { - var call = client.fullDuplexCall(); - call.write({ - response_type: 'COMPRESSABLE', - response_parameters: [ - {size: 31415} - ], - payload: {body: zeroBuffer(27182)} - }); - call.on('data', function(data) { - call.cancel(); - }); - call.on('error', function(error) { - assert.strictEqual(error.code, grpc.status.CANCELLED); - done(); - }); -} - -function timeoutOnSleepingServer(client, done) { - var deadline = new Date(); - deadline.setMilliseconds(deadline.getMilliseconds() + 1); - var call = client.fullDuplexCall({deadline: deadline}); - call.write({ - payload: {body: zeroBuffer(27182)} - }); - call.on('data', function() {}); - call.on('error', function(error) { - - assert(error.code === grpc.status.DEADLINE_EXCEEDED || - error.code === grpc.status.INTERNAL); - done(); - }); -} - -function customMetadata(client, done) { - done = multiDone(done, 5); - var metadata = new grpc.Metadata(); - metadata.set(ECHO_INITIAL_KEY, 'test_initial_metadata_value'); - metadata.set(ECHO_TRAILING_KEY, new Buffer('ababab', 'hex')); - var arg = { - response_type: 'COMPRESSABLE', - response_size: 314159, - payload: { - body: zeroBuffer(271828) - } - }; - var streaming_arg = { - response_parameters: [ - {size: 314159} - ], - payload: { - body: zeroBuffer(271828) - } - }; - var unary = client.unaryCall(arg, metadata, function(err, resp) { - assert.ifError(err); - done(); - }); - unary.on('metadata', function(metadata) { - assert.deepEqual(metadata.get(ECHO_INITIAL_KEY), - ['test_initial_metadata_value']); - done(); - }); - unary.on('status', function(status) { - var echo_trailer = status.metadata.get(ECHO_TRAILING_KEY); - assert(echo_trailer.length > 0); - assert.strictEqual(echo_trailer[0].toString('hex'), 'ababab'); - done(); - }); - var stream = client.fullDuplexCall(metadata); - stream.on('metadata', function(metadata) { - assert.deepEqual(metadata.get(ECHO_INITIAL_KEY), - ['test_initial_metadata_value']); - done(); - }); - stream.on('data', function() {}); - stream.on('status', function(status) { - var echo_trailer = status.metadata.get(ECHO_TRAILING_KEY); - assert(echo_trailer.length > 0); - assert.strictEqual(echo_trailer[0].toString('hex'), 'ababab'); - done(); - }); - stream.write(streaming_arg); - stream.end(); -} - -function statusCodeAndMessage(client, done) { - done = multiDone(done, 2); - var arg = { - response_status: { - code: 2, - message: 'test status message' - } - }; - client.unaryCall(arg, function(err, resp) { - assert(err); - assert.strictEqual(err.code, 2); - assert.strictEqual(err.message, 'test status message'); - done(); - }); - var duplex = client.fullDuplexCall(); - duplex.on('data', function() {}); - duplex.on('status', function(status) { - assert(status); - assert.strictEqual(status.code, 2); - assert.strictEqual(status.details, 'test status message'); - done(); - }); - duplex.on('error', function(){}); - duplex.write(arg); - duplex.end(); -} - -// NOTE: the client param to this function is from UnimplementedService -function unimplementedService(client, done) { - client.unimplementedCall({}, function(err, resp) { - assert(err); - assert.strictEqual(err.code, grpc.status.UNIMPLEMENTED); - done(); - }); -} - -// NOTE: the client param to this function is from TestService -function unimplementedMethod(client, done) { - client.unimplementedCall({}, function(err, resp) { - assert(err); - assert.strictEqual(err.code, grpc.status.UNIMPLEMENTED); - done(); - }); -} - -/** - * Run one of the authentication tests. - * @param {string} expected_user The expected username in the response - * @param {Client} client The client to test against - * @param {?string} scope The scope to apply to the credentials - * @param {function} done Callback to call when the test is completed. Included - * primarily for use with mocha - */ -function authTest(expected_user, scope, client, done) { - var arg = { - response_type: 'COMPRESSABLE', - response_size: 314159, - payload: { - body: zeroBuffer(271828) - }, - fill_username: true, - fill_oauth_scope: true - }; - client.unaryCall(arg, function(err, resp) { - assert.ifError(err); - assert.strictEqual(resp.payload.type, 'COMPRESSABLE'); - assert.strictEqual(resp.payload.body.length, 314159); - assert.strictEqual(resp.username, expected_user); - if (scope) { - assert(scope.indexOf(resp.oauth_scope) > -1); - } - if (done) { - done(); - } - }); -} - -function computeEngineCreds(client, done, extra) { - authTest(extra.service_account, null, client, done); -} - -function serviceAccountCreds(client, done, extra) { - authTest(SERVICE_ACCOUNT_EMAIL, extra.oauth_scope, client, done); -} - -function jwtTokenCreds(client, done, extra) { - authTest(SERVICE_ACCOUNT_EMAIL, null, client, done); -} - -function oauth2Test(client, done, extra) { - var arg = { - fill_username: true, - fill_oauth_scope: true - }; - client.unaryCall(arg, function(err, resp) { - assert.ifError(err); - assert.strictEqual(resp.username, SERVICE_ACCOUNT_EMAIL); - assert(extra.oauth_scope.indexOf(resp.oauth_scope) > -1); - if (done) { - done(); - } - }); -} - -function perRpcAuthTest(client, done, extra) { - (new GoogleAuth()).getApplicationDefault(function(err, credential) { - assert.ifError(err); - var arg = { - fill_username: true, - fill_oauth_scope: true - }; - var scope = extra.oauth_scope; - if (credential.createScopedRequired() && scope) { - credential = credential.createScoped(scope); - } - var creds = grpc.credentials.createFromGoogleCredential(credential); - client.unaryCall(arg, {credentials: creds}, function(err, resp) { - assert.ifError(err); - assert.strictEqual(resp.username, SERVICE_ACCOUNT_EMAIL); - assert(extra.oauth_scope.indexOf(resp.oauth_scope) > -1); - if (done) { - done(); - } - }); - }); -} - -function getApplicationCreds(scope, callback) { - (new GoogleAuth()).getApplicationDefault(function(err, credential) { - if (err) { - callback(err); - return; - } - if (credential.createScopedRequired() && scope) { - credential = credential.createScoped(scope); - } - callback(null, grpc.credentials.createFromGoogleCredential(credential)); - }); -} - -function getOauth2Creds(scope, callback) { - (new GoogleAuth()).getApplicationDefault(function(err, credential) { - if (err) { - callback(err); - return; - } - credential = credential.createScoped(scope); - credential.getAccessToken(function(err, token) { - if (err) { - callback(err); - return; - } - var updateMd = function(service_url, callback) { - var metadata = new grpc.Metadata(); - metadata.add('authorization', 'Bearer ' + token); - callback(null, metadata); - }; - callback(null, grpc.credentials.createFromMetadataGenerator(updateMd)); - }); - }); -} - -/** - * Map from test case names to test functions - */ -var test_cases = { - empty_unary: {run: emptyUnary, - Client: testProto.TestService}, - large_unary: {run: largeUnary, - Client: testProto.TestService}, - client_streaming: {run: clientStreaming, - Client: testProto.TestService}, - server_streaming: {run: serverStreaming, - Client: testProto.TestService}, - ping_pong: {run: pingPong, - Client: testProto.TestService}, - empty_stream: {run: emptyStream, - Client: testProto.TestService}, - cancel_after_begin: {run: cancelAfterBegin, - Client: testProto.TestService}, - cancel_after_first_response: {run: cancelAfterFirstResponse, - Client: testProto.TestService}, - timeout_on_sleeping_server: {run: timeoutOnSleepingServer, - Client: testProto.TestService}, - custom_metadata: {run: customMetadata, - Client: testProto.TestService}, - status_code_and_message: {run: statusCodeAndMessage, - Client: testProto.TestService}, - unimplemented_service: {run: unimplementedService, - Client: testProto.UnimplementedService}, - unimplemented_method: {run: unimplementedMethod, - Client: testProto.TestService}, - compute_engine_creds: {run: computeEngineCreds, - Client: testProto.TestService, - getCreds: getApplicationCreds}, - service_account_creds: {run: serviceAccountCreds, - Client: testProto.TestService, - getCreds: getApplicationCreds}, - jwt_token_creds: {run: jwtTokenCreds, - Client: testProto.TestService, - getCreds: getApplicationCreds}, - oauth2_auth_token: {run: oauth2Test, - Client: testProto.TestService, - getCreds: getOauth2Creds}, - per_rpc_creds: {run: perRpcAuthTest, - Client: testProto.TestService} -}; - -exports.test_cases = test_cases; - -/** - * Execute a single test case. - * @param {string} address The address of the server to connect to, in the - * format 'hostname:port' - * @param {string} host_overrirde The hostname of the server to use as an SSL - * override - * @param {string} test_case The name of the test case to run - * @param {bool} tls Indicates that a secure channel should be used - * @param {function} done Callback to call when the test is completed. Included - * primarily for use with mocha - * @param {object=} extra Extra options for some tests - */ -function runTest(address, host_override, test_case, tls, test_ca, done, extra) { - // TODO(mlumish): enable TLS functionality - var options = {}; - var creds; - if (tls) { - var ca_path; - if (test_ca) { - ca_path = path.join(__dirname, '../test/data/ca.pem'); - var ca_data = fs.readFileSync(ca_path); - creds = grpc.credentials.createSsl(ca_data); - } else { - creds = grpc.credentials.createSsl(); - } - if (host_override) { - options['grpc.ssl_target_name_override'] = host_override; - options['grpc.default_authority'] = host_override; - } - } else { - creds = grpc.credentials.createInsecure(); - } - var test = test_cases[test_case]; - - var execute = function(err, creds) { - assert.ifError(err); - var client = new test.Client(address, creds, options); - test.run(client, done, extra); - }; - - if (test.getCreds) { - test.getCreds(extra.oauth_scope, function(err, new_creds) { - assert.ifError(err); - execute(err, grpc.credentials.combineChannelCredentials( - creds, new_creds)); - }); - } else { - execute(null, creds); - } -} - -if (require.main === module) { - var parseArgs = require('minimist'); - var argv = parseArgs(process.argv, { - string: ['server_host', 'server_host_override', 'server_port', 'test_case', - 'use_tls', 'use_test_ca', 'default_service_account', 'oauth_scope', - 'service_account_key_file'] - }); - var extra_args = { - service_account: argv.default_service_account, - oauth_scope: argv.oauth_scope - }; - runTest(argv.server_host + ':' + argv.server_port, argv.server_host_override, - argv.test_case, argv.use_tls === 'true', argv.use_test_ca === 'true', - function () { - console.log('OK:', argv.test_case); - }, extra_args); -} - -/** - * See docs for runTest - */ -exports.runTest = runTest; diff --git a/src/node/interop/interop_server.js b/src/node/interop/interop_server.js deleted file mode 100644 index c2028af4a15..00000000000 --- a/src/node/interop/interop_server.js +++ /dev/null @@ -1,241 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var fs = require('fs'); -var path = require('path'); -var _ = require('lodash'); -var AsyncDelayQueue = require('./async_delay_queue'); -var grpc = require('..'); -var testProto = grpc.load({ - root: __dirname + '/../../..', - file: 'src/proto/grpc/testing/test.proto'}).grpc.testing; - -var ECHO_INITIAL_KEY = 'x-grpc-test-echo-initial'; -var ECHO_TRAILING_KEY = 'x-grpc-test-echo-trailing-bin'; - -/** - * Create a buffer filled with size zeroes - * @param {number} size The length of the buffer - * @return {Buffer} The new buffer - */ -function zeroBuffer(size) { - var zeros = new Buffer(size); - zeros.fill(0); - return zeros; -} - -/** - * Echos a header metadata item as specified in the interop spec. - * @param {Call} call The call to echo metadata on - */ -function echoHeader(call) { - var echo_initial = call.metadata.get(ECHO_INITIAL_KEY); - if (echo_initial.length > 0) { - var response_metadata = new grpc.Metadata(); - response_metadata.set(ECHO_INITIAL_KEY, echo_initial[0]); - call.sendMetadata(response_metadata); - } -} - -/** - * Gets the trailer metadata that should be echoed when the call is done, - * as specified in the interop spec. - * @param {Call} call The call to get metadata from - * @return {grpc.Metadata} The metadata to send as a trailer - */ -function getEchoTrailer(call) { - var echo_trailer = call.metadata.get(ECHO_TRAILING_KEY); - var response_trailer = new grpc.Metadata(); - if (echo_trailer.length > 0) { - response_trailer.set(ECHO_TRAILING_KEY, echo_trailer[0]); - } - return response_trailer; -} - -function getPayload(payload_type, size) { - var body = zeroBuffer(size); - return {type: payload_type, body: body}; -} - -/** - * Respond to an empty parameter with an empty response. - * NOTE: this currently does not work due to issue #137 - * @param {Call} call Call to handle - * @param {function(Error, Object)} callback Callback to call with result - * or error - */ -function handleEmpty(call, callback) { - echoHeader(call); - callback(null, {}, getEchoTrailer(call)); -} - -/** - * Handle a unary request by sending the requested payload - * @param {Call} call Call to handle - * @param {function(Error, Object)} callback Callback to call with result or - * error - */ -function handleUnary(call, callback) { - echoHeader(call); - var req = call.request; - if (req.response_status) { - var status = req.response_status; - status.metadata = getEchoTrailer(call); - callback(status); - return; - } - var payload = getPayload(req.response_type, req.response_size); - callback(null, {payload: payload}, - getEchoTrailer(call)); -} - -/** - * Respond to a streaming call with the total size of all payloads - * @param {Call} call Call to handle - * @param {function(Error, Object)} callback Callback to call with result or - * error - */ -function handleStreamingInput(call, callback) { - echoHeader(call); - var aggregate_size = 0; - call.on('data', function(value) { - aggregate_size += value.payload.body.length; - }); - call.on('end', function() { - callback(null, {aggregated_payload_size: aggregate_size}, - getEchoTrailer(call)); - }); -} - -/** - * Respond to a payload request with a stream of the requested payloads - * @param {Call} call Call to handle - */ -function handleStreamingOutput(call) { - echoHeader(call); - var delay_queue = new AsyncDelayQueue(); - var req = call.request; - if (req.response_status) { - var status = req.response_status; - status.metadata = getEchoTrailer(call); - call.emit('error', status); - return; - } - _.each(req.response_parameters, function(resp_param) { - delay_queue.add(function(next) { - call.write({payload: getPayload(req.response_type, resp_param.size)}); - next(); - }, resp_param.interval_us); - }); - delay_queue.add(function(next) { - call.end(getEchoTrailer(call)); - next(); - }); -} - -/** - * Respond to a stream of payload requests with a stream of payload responses as - * they arrive. - * @param {Call} call Call to handle - */ -function handleFullDuplex(call) { - echoHeader(call); - var delay_queue = new AsyncDelayQueue(); - call.on('data', function(value) { - if (value.response_status) { - var status = value.response_status; - status.metadata = getEchoTrailer(call); - call.emit('error', status); - return; - } - _.each(value.response_parameters, function(resp_param) { - delay_queue.add(function(next) { - call.write({payload: getPayload(value.response_type, resp_param.size)}); - next(); - }, resp_param.interval_us); - }); - }); - call.on('end', function() { - delay_queue.add(function(next) { - call.end(getEchoTrailer(call)); - next(); - }); - }); -} - -/** - * Respond to a stream of payload requests with a stream of payload responses - * after all requests have arrived - * @param {Call} call Call to handle - */ -function handleHalfDuplex(call) { - call.emit('error', Error('HalfDuplexCall not yet implemented')); -} - -/** - * Get a server object bound to the given port - * @param {string} port Port to which to bind - * @param {boolean} tls Indicates that the bound port should use TLS - * @return {{server: Server, port: number}} Server object bound to the support, - * and port number that the server is bound to - */ -function getServer(port, tls) { - // TODO(mlumish): enable TLS functionality - var options = {}; - var server_creds; - if (tls) { - var key_path = path.join(__dirname, '../test/data/server1.key'); - var pem_path = path.join(__dirname, '../test/data/server1.pem'); - - var key_data = fs.readFileSync(key_path); - var pem_data = fs.readFileSync(pem_path); - server_creds = grpc.ServerCredentials.createSsl(null, - [{private_key: key_data, - cert_chain: pem_data}]); - } else { - server_creds = grpc.ServerCredentials.createInsecure(); - } - var server = new grpc.Server(options); - server.addService(testProto.TestService.service, { - emptyCall: handleEmpty, - unaryCall: handleUnary, - streamingOutputCall: handleStreamingOutput, - streamingInputCall: handleStreamingInput, - fullDuplexCall: handleFullDuplex, - halfDuplexCall: handleHalfDuplex - }); - var port_num = server.bind('0.0.0.0:' + port, server_creds); - return {server: server, port: port_num}; -} - -if (require.main === module) { - var parseArgs = require('minimist'); - var argv = parseArgs(process.argv, { - string: ['port', 'use_tls'] - }); - var server_obj = getServer(argv.port, argv.use_tls === 'true'); - console.log('Server attaching to port ' + argv.port); - server_obj.server.start(); -} - -/** - * See docs for getServer - */ -exports.getServer = getServer; diff --git a/src/node/jsdoc_conf.json b/src/node/jsdoc_conf.json deleted file mode 100644 index 2d967753c1e..00000000000 --- a/src/node/jsdoc_conf.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "tags": { - "allowUnknownTags": true - }, - "source": { - "include": [ "src/node/index.js", "src/node/src" ], - "includePattern": "src/node/.+\\.js(doc)?$", - "excludePattern": "(^|\\/|\\\\)_" - }, - "opts": { - "package": "package.json", - "readme": "src/node/README.md" - }, - "plugins": ["plugins/markdown"], - "templates": { - "cleverLinks": false, - "monospaceLinks": false, - "default": { - "outputSourceFiles": true - } - } -} diff --git a/src/node/performance/benchmark_client.js b/src/node/performance/benchmark_client.js deleted file mode 100644 index 68afb8a6338..00000000000 --- a/src/node/performance/benchmark_client.js +++ /dev/null @@ -1,365 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/** - * Benchmark client module - * @module - */ - -'use strict'; - -var fs = require('fs'); -var path = require('path'); -var util = require('util'); -var EventEmitter = require('events'); - -var async = require('async'); -var _ = require('lodash'); -var PoissonProcess = require('poisson-process'); -var Histogram = require('./histogram'); - -var genericService = require('./generic_service'); - -var grpc = require('../../../'); -var serviceProto = grpc.load({ - root: __dirname + '/../../..', - file: 'src/proto/grpc/testing/services.proto'}).grpc.testing; - -/** - * Create a buffer filled with size zeroes - * @param {number} size The length of the buffer - * @return {Buffer} The new buffer - */ -function zeroBuffer(size) { - var zeros = new Buffer(size); - zeros.fill(0); - return zeros; -} - -/** - * Convert a time difference, as returned by process.hrtime, to a number of - * nanoseconds. - * @param {Array.} time_diff The time diff, represented as - * [seconds, nanoseconds] - * @return {number} The total number of nanoseconds - */ -function timeDiffToNanos(time_diff) { - return time_diff[0] * 1e9 + time_diff[1]; -} - -/** - * The BenchmarkClient class. Opens channels to servers and makes RPCs based on - * parameters from the driver, and records statistics about those RPCs. - * @param {Array.} server_targets List of servers to connect to - * @param {number} channels The total number of channels to open - * @param {Object} histogram_params Options for setting up the histogram - * @param {Object=} security_params Options for TLS setup. If absent, don't use - * TLS - */ -function BenchmarkClient(server_targets, channels, histogram_params, - security_params) { - var options = { - "grpc.max_receive_message_length": -1, - "grpc.max_send_message_length": -1 - }; - var creds; - if (security_params) { - var ca_path; - if (security_params.use_test_ca) { - ca_path = path.join(__dirname, '../test/data/ca.pem'); - var ca_data = fs.readFileSync(ca_path); - creds = grpc.credentials.createSsl(ca_data); - } else { - creds = grpc.credentials.createSsl(); - } - if (security_params.server_host_override) { - var host_override = security_params.server_host_override; - options['grpc.ssl_target_name_override'] = host_override; - options['grpc.default_authority'] = host_override; - } - } else { - creds = grpc.credentials.createInsecure(); - } - - this.clients = []; - var GenericClient = grpc.makeGenericClientConstructor(genericService); - this.genericClients = []; - - for (var i = 0; i < channels; i++) { - this.clients[i] = new serviceProto.BenchmarkService( - server_targets[i % server_targets.length], creds, options); - this.genericClients[i] = new GenericClient( - server_targets[i % server_targets.length], creds, options); - } - - this.histogram = new Histogram(histogram_params.resolution, - histogram_params.max_possible); - - this.running = false; - - this.pending_calls = 0; -}; - -util.inherits(BenchmarkClient, EventEmitter); - -/** - * Start every client in the list of clients by waiting for each to be ready, - * then starting outstanding_rpcs_per_channel calls on each of them - * @param {Array} client_list The list of clients - * @param {Number} outstanding_rpcs_per_channel The number of calls to start - * on each client - * @param {function(grpc.Client)} makeCall Function to make a single call on - * a single client - * @param {EventEmitter} emitter The event emitter to send errors on, if - * necessary - */ -function startAllClients(client_list, outstanding_rpcs_per_channel, makeCall, - emitter) { - var ready_wait_funcs = _.map(client_list, function(client) { - return _.partial(grpc.waitForClientReady, client, Infinity); - }); - async.parallel(ready_wait_funcs, function(err) { - if (err) { - emitter.emit('error', err); - return; - } - - _.each(client_list, function(client) { - _.times(outstanding_rpcs_per_channel, function() { - makeCall(client); - }); - }); - }); -} - -/** - * Start a closed-loop test. For each channel, start - * outstanding_rpcs_per_channel RPCs. Then, whenever an RPC finishes, start - * another one. - * @param {number} outstanding_rpcs_per_channel Number of RPCs to start per - * channel - * @param {string} rpc_type Which method to call. Should be 'UNARY' or - * 'STREAMING' - * @param {number} req_size The size of the payload to send with each request - * @param {number} resp_size The size of payload to request be sent in responses - * @param {boolean} generic Indicates that the generic (non-proto) clients - * should be used - */ -BenchmarkClient.prototype.startClosedLoop = function( - outstanding_rpcs_per_channel, rpc_type, req_size, resp_size, generic) { - var self = this; - - self.running = true; - - self.last_wall_time = process.hrtime(); - - self.last_usage = process.cpuUsage(); - - var makeCall; - - var argument; - var client_list; - if (generic) { - argument = zeroBuffer(req_size); - client_list = self.genericClients; - } else { - argument = { - response_size: resp_size, - payload: { - body: zeroBuffer(req_size) - } - }; - client_list = self.clients; - } - - if (rpc_type == 'UNARY') { - makeCall = function(client) { - if (self.running) { - self.pending_calls++; - var start_time = process.hrtime(); - client.unaryCall(argument, function(error, response) { - if (error) { - self.emit('error', new Error('Client error: ' + error.message)); - self.running = false; - return; - } - var time_diff = process.hrtime(start_time); - self.histogram.add(timeDiffToNanos(time_diff)); - makeCall(client); - self.pending_calls--; - if ((!self.running) && self.pending_calls == 0) { - self.emit('finished'); - } - }); - } - }; - } else { - makeCall = function(client) { - if (self.running) { - self.pending_calls++; - var call = client.streamingCall(); - var start_time = process.hrtime(); - call.write(argument); - call.on('data', function() { - var time_diff = process.hrtime(start_time); - self.histogram.add(timeDiffToNanos(time_diff)); - self.pending_calls--; - if (self.running) { - self.pending_calls++; - start_time = process.hrtime(); - call.write(argument); - } else { - call.end(); - if (self.pending_calls == 0) { - self.emit('finished'); - } - } - }); - call.on('error', function(error) { - self.emit('error', new Error('Client error: ' + error.message)); - self.running = false; - }); - } - }; - } - - startAllClients(client_list, outstanding_rpcs_per_channel, makeCall, self); -}; - -/** - * Start a poisson test. For each channel, this initiates a number of Poisson - * processes equal to outstanding_rpcs_per_channel, where each Poisson process - * has the load parameter offered_load. - * @param {number} outstanding_rpcs_per_channel Number of RPCs to start per - * channel - * @param {string} rpc_type Which method to call. Should be 'UNARY' or - * 'STREAMING' - * @param {number} req_size The size of the payload to send with each request - * @param {number} resp_size The size of payload to request be sent in responses - * @param {number} offered_load The load parameter for the Poisson process - * @param {boolean} generic Indicates that the generic (non-proto) clients - * should be used - */ -BenchmarkClient.prototype.startPoisson = function( - outstanding_rpcs_per_channel, rpc_type, req_size, resp_size, offered_load, - generic) { - var self = this; - - self.running = true; - - self.last_wall_time = process.hrtime(); - - self.last_usage = process.cpuUsage(); - - var makeCall; - - var argument; - var client_list; - if (generic) { - argument = zeroBuffer(req_size); - client_list = self.genericClients; - } else { - argument = { - response_size: resp_size, - payload: { - body: zeroBuffer(req_size) - } - }; - client_list = self.clients; - } - - if (rpc_type == 'UNARY') { - makeCall = function(client, poisson) { - if (self.running) { - self.pending_calls++; - var start_time = process.hrtime(); - client.unaryCall(argument, function(error, response) { - if (error) { - self.emit('error', new Error('Client error: ' + error.message)); - self.running = false; - return; - } - var time_diff = process.hrtime(start_time); - self.histogram.add(timeDiffToNanos(time_diff)); - self.pending_calls--; - if ((!self.running) && self.pending_calls == 0) { - self.emit('finished'); - } - }); - } else { - poisson.stop(); - } - }; - } else { - self.emit('error', new Error('Streaming Poisson benchmarks not supported')); - return; - } - - var averageIntervalMs = (1 / offered_load) * 1000; - - startAllClients(client_list, outstanding_rpcs_per_channel, function(client){ - var p = PoissonProcess.create(averageIntervalMs, function() { - makeCall(client, p); - }); - p.start(); - }, self); -}; - -/** - * Return curent statistics for the client. If reset is set, restart - * statistic collection. - * @param {boolean} reset Indicates that statistics should be reset - * @return {object} Client statistics - */ -BenchmarkClient.prototype.mark = function(reset) { - var wall_time_diff = process.hrtime(this.last_wall_time); - var usage_diff = process.cpuUsage(this.last_usage); - var histogram = this.histogram; - if (reset) { - this.last_wall_time = process.hrtime(); - this.last_usage = process.cpuUsage(); - this.histogram = new Histogram(histogram.resolution, - histogram.max_possible); - } - - return { - latencies: { - bucket: histogram.getContents(), - min_seen: histogram.minimum(), - max_seen: histogram.maximum(), - sum: histogram.getSum(), - sum_of_squares: histogram.sumOfSquares(), - count: histogram.getCount() - }, - time_elapsed: wall_time_diff[0] + wall_time_diff[1] / 1e9, - time_user: usage_diff.user / 1000000, - time_system: usage_diff.system / 1000000 - }; -}; - -/** - * Stop the clients. - * @param {function} callback Called when the clients have finished shutting - * down - */ -BenchmarkClient.prototype.stop = function(callback) { - this.running = false; - this.on('finished', callback); -}; - -module.exports = BenchmarkClient; diff --git a/src/node/performance/benchmark_client_express.js b/src/node/performance/benchmark_client_express.js deleted file mode 100644 index 815843fede8..00000000000 --- a/src/node/performance/benchmark_client_express.js +++ /dev/null @@ -1,287 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/** - * Benchmark client module - * @module - */ - -'use strict'; - -var fs = require('fs'); -var path = require('path'); -var util = require('util'); -var EventEmitter = require('events'); -var http = require('http'); -var https = require('https'); - -var async = require('async'); -var _ = require('lodash'); -var PoissonProcess = require('poisson-process'); -var Histogram = require('./histogram'); - -/** - * Convert a time difference, as returned by process.hrtime, to a number of - * nanoseconds. - * @param {Array.} time_diff The time diff, represented as - * [seconds, nanoseconds] - * @return {number} The total number of nanoseconds - */ -function timeDiffToNanos(time_diff) { - return time_diff[0] * 1e9 + time_diff[1]; -} - -function BenchmarkClient(server_targets, channels, histogram_params, - security_params) { - var options = { - method: 'PUT', - headers: { - 'Content-Type': 'application/json' - } - }; - var protocol; - if (security_params) { - var ca_path; - protocol = https; - this.request = _.bind(https.request, https); - if (security_params.use_test_ca) { - ca_path = path.join(__dirname, '../test/data/ca.pem'); - var ca_data = fs.readFileSync(ca_path); - options.ca = ca_data; - } - if (security_params.server_host_override) { - var host_override = security_params.server_host_override; - options.servername = host_override; - } - } else { - protocol = http; - } - - this.request = _.bind(protocol.request, protocol); - - this.client_options = []; - - for (var i = 0; i < channels; i++) { - var host_port; - host_port = server_targets[i % server_targets.length].split(':'); - var new_options = _.assign({hostname: host_port[0], port: +host_port[1]}, options); - this.client_options[i] = new_options; - } - - this.histogram = new Histogram(histogram_params.resolution, - histogram_params.max_possible); - - this.running = false; - - this.pending_calls = 0; -} - -util.inherits(BenchmarkClient, EventEmitter); - -function startAllClients(client_options_list, outstanding_rpcs_per_channel, - makeCall, emitter) { - _.each(client_options_list, function(client_options) { - _.times(outstanding_rpcs_per_channel, function() { - makeCall(client_options); - }); - }); -} - -BenchmarkClient.prototype.startClosedLoop = function( - outstanding_rpcs_per_channel, rpc_type, req_size, resp_size, generic) { - var self = this; - - var options = {}; - - self.running = true; - - if (rpc_type == 'UNARY') { - options.path = '/serviceProto.BenchmarkService.service/unaryCall'; - } else { - self.emit('error', new Error('Unsupported rpc_type: ' + rpc_type)); - } - - if (generic) { - self.emit('error', new Error('Generic client not supported')); - } - - self.last_wall_time = process.hrtime(); - self.last_usage = process.cpuUsage(); - - var argument = { - response_size: resp_size, - payload: { - body: '0'.repeat(req_size) - } - }; - - function makeCall(client_options) { - if (self.running) { - self.pending_calls++; - var start_time = process.hrtime(); - function finishCall(success) { - if (success) { - var time_diff = process.hrtime(start_time); - self.histogram.add(timeDiffToNanos(time_diff)); - } - makeCall(client_options); - self.pending_calls--; - if ((!self.running) && self.pending_calls == 0) { - self.emit('finished'); - } - } - var req = self.request(client_options, function(res) { - var res_data = ''; - res.on('data', function(data) { - res_data += data; - }); - res.on('end', function() { - JSON.parse(res_data); - finishCall(true); - }); - }); - req.write(JSON.stringify(argument)); - req.end(); - req.on('error', function(error) { - if (error.code === 'ECONNRESET' || error.code === 'ETIMEDOUT') { - finishCall(false); - return; - } - self.emit('error', new Error('Client error: ' + error.message)); - self.running = false; - }); - } - } - - startAllClients(_.map(self.client_options, _.partial(_.assign, options)), - outstanding_rpcs_per_channel, makeCall, self); -}; - -BenchmarkClient.prototype.startPoisson = function( - outstanding_rpcs_per_channel, rpc_type, req_size, resp_size, offered_load, - generic) { - var self = this; - - var options = {}; - - self.running = true; - - if (rpc_type == 'UNARY') { - options.path = '/serviceProto.BenchmarkService.service/unaryCall'; - } else { - self.emit('error', new Error('Unsupported rpc_type: ' + rpc_type)); - } - - if (generic) { - self.emit('error', new Error('Generic client not supported')); - } - - self.last_wall_time = process.hrtime(); - self.last_usage = process.cpuUsage(); - - var argument = { - response_size: resp_size, - payload: { - body: '0'.repeat(req_size) - } - }; - - function makeCall(client_options, poisson) { - if (self.running) { - self.pending_calls++; - var start_time = process.hrtime(); - var req = self.request(client_options, function(res) { - var res_data = ''; - res.on('data', function(data) { - res_data += data; - }); - res.on('end', function() { - JSON.parse(res_data); - var time_diff = process.hrtime(start_time); - self.histogram.add(timeDiffToNanos(time_diff)); - self.pending_calls--; - if ((!self.running) && self.pending_calls == 0) { - self.emit('finished'); - } - }); - }); - req.write(JSON.stringify(argument)); - req.end(); - req.on('error', function(error) { - self.emit('error', new Error('Client error: ' + error.message)); - self.running = false; - }); - } else { - poisson.stop(); - } - } - - var averageIntervalMs = (1 / offered_load) * 1000; - - startAllClients(_.map(self.client_options, _.partial(_.assign, options)), - outstanding_rpcs_per_channel, function(opts){ - var p = PoissonProcess.create(averageIntervalMs, function() { - makeCall(opts, p); - }); - p.start(); - }, self); -}; - -/** - * Return curent statistics for the client. If reset is set, restart - * statistic collection. - * @param {boolean} reset Indicates that statistics should be reset - * @return {object} Client statistics - */ -BenchmarkClient.prototype.mark = function(reset) { - var wall_time_diff = process.hrtime(this.last_wall_time); - var usage_diff = process.cpuUsage(this.last_usage); - var histogram = this.histogram; - if (reset) { - this.last_wall_time = process.hrtime(); - this.last_usage = process.cpuUsage(); - this.histogram = new Histogram(histogram.resolution, - histogram.max_possible); - } - - return { - latencies: { - bucket: histogram.getContents(), - min_seen: histogram.minimum(), - max_seen: histogram.maximum(), - sum: histogram.getSum(), - sum_of_squares: histogram.sumOfSquares(), - count: histogram.getCount() - }, - time_elapsed: wall_time_diff[0] + wall_time_diff[1] / 1e9, - time_user: usage_diff.user / 1000000, - time_system: usage_diff.system / 1000000 - }; -}; - -/** - * Stop the clients. - * @param {function} callback Called when the clients have finished shutting - * down - */ -BenchmarkClient.prototype.stop = function(callback) { - this.running = false; - this.on('finished', callback); -}; - -module.exports = BenchmarkClient; diff --git a/src/node/performance/benchmark_server.js b/src/node/performance/benchmark_server.js deleted file mode 100644 index 8d3a2b90490..00000000000 --- a/src/node/performance/benchmark_server.js +++ /dev/null @@ -1,189 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/** - * Benchmark server module - * @module - */ - -'use strict'; - -var fs = require('fs'); -var path = require('path'); -var EventEmitter = require('events'); -var util = require('util'); - -var genericService = require('./generic_service'); - -var grpc = require('../../../'); -var serviceProto = grpc.load({ - root: __dirname + '/../../..', - file: 'src/proto/grpc/testing/services.proto'}).grpc.testing; - -/** - * Create a buffer filled with size zeroes - * @param {number} size The length of the buffer - * @return {Buffer} The new buffer - */ -function zeroBuffer(size) { - var zeros = new Buffer(size); - zeros.fill(0); - return zeros; -} - -/** - * Handler for the unary benchmark method. Simply responds with a payload - * containing the requested number of zero bytes. - * @param {Call} call The call object to be handled - * @param {function} callback The callback to call with the response - */ -function unaryCall(call, callback) { - var req = call.request; - var payload = {body: zeroBuffer(req.response_size)}; - callback(null, {payload: payload}); -} - -/** - * Handler for the streaming benchmark method. Simply responds to each request - * with a payload containing the requested number of zero bytes. - * @param {Call} call The call object to be handled - */ -function streamingCall(call) { - call.on('data', function(value) { - var payload = {body: zeroBuffer(value.response_size)}; - call.write({payload: payload}); - }); - call.on('end', function() { - call.end(); - }); -} - -function makeUnaryGenericCall(response_size) { - var response = zeroBuffer(response_size); - return function unaryGenericCall(call, callback) { - callback(null, response); - }; -} - -function makeStreamingGenericCall(response_size) { - var response = zeroBuffer(response_size); - return function streamingGenericCall(call) { - call.on('data', function(value) { - call.write(response); - }); - call.on('end', function() { - call.end(); - }); - }; -} - -/** - * BenchmarkServer class. Constructed based on parameters from the driver and - * stores statistics. - * @param {string} host The host to serve on - * @param {number} port The port to listen to - * @param {boolean} tls Indicates whether TLS should be used - * @param {boolean} generic Indicates whether to use the generic service - * @param {number=} response_size The response size for the generic service - */ -function BenchmarkServer(host, port, tls, generic, response_size) { - var server_creds; - var host_override; - if (tls) { - var key_path = path.join(__dirname, '../test/data/server1.key'); - var pem_path = path.join(__dirname, '../test/data/server1.pem'); - - var key_data = fs.readFileSync(key_path); - var pem_data = fs.readFileSync(pem_path); - server_creds = grpc.ServerCredentials.createSsl(null, - [{private_key: key_data, - cert_chain: pem_data}]); - } else { - server_creds = grpc.ServerCredentials.createInsecure(); - } - - var options = { - "grpc.max_receive_message_length": -1, - "grpc.max_send_message_length": -1 - }; - - var server = new grpc.Server(options); - this.port = server.bind(host + ':' + port, server_creds); - if (generic) { - server.addService(genericService, { - unaryCall: makeUnaryGenericCall(response_size), - streamingCall: makeStreamingGenericCall(response_size) - }); - } else { - server.addService(serviceProto.BenchmarkService.service, { - unaryCall: unaryCall, - streamingCall: streamingCall - }); - } - this.server = server; -} - -util.inherits(BenchmarkServer, EventEmitter); - -/** - * Start the benchmark server. - */ -BenchmarkServer.prototype.start = function() { - this.server.start(); - this.last_wall_time = process.hrtime(); - this.last_usage = process.cpuUsage(); - this.emit('started'); -}; - -/** - * Return the port number that the server is bound to. - * @return {Number} The port number - */ -BenchmarkServer.prototype.getPort = function() { - return this.port; -}; - -/** - * Return current statistics for the server. If reset is set, restart - * statistic collection. - * @param {boolean} reset Indicates that statistics should be reset - * @return {object} Server statistics - */ -BenchmarkServer.prototype.mark = function(reset) { - var wall_time_diff = process.hrtime(this.last_wall_time); - var usage_diff = process.cpuUsage(this.last_usage); - if (reset) { - this.last_wall_time = process.hrtime(); - this.last_usage = process.cpuUsage(); - } - return { - time_elapsed: wall_time_diff[0] + wall_time_diff[1] / 1e9, - time_user: usage_diff.user / 1000000, - time_system: usage_diff.system / 1000000 - }; -}; - -/** - * Stop the server. - * @param {function} callback Called when the server has finished shutting down - */ -BenchmarkServer.prototype.stop = function(callback) { - this.server.tryShutdown(callback); -}; - -module.exports = BenchmarkServer; diff --git a/src/node/performance/benchmark_server_express.js b/src/node/performance/benchmark_server_express.js deleted file mode 100644 index 73e54091a4c..00000000000 --- a/src/node/performance/benchmark_server_express.js +++ /dev/null @@ -1,96 +0,0 @@ -/* - * - * 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. - * - */ - -/** - * Benchmark server module - * @module - */ - -'use strict'; - -var fs = require('fs'); -var path = require('path'); -var http = require('http'); -var https = require('https'); -var EventEmitter = require('events'); -var util = require('util'); - -var express = require('express'); -var bodyParser = require('body-parser'); - -function unaryCall(req, res) { - var reqObj = req.body; - var payload = {body: '0'.repeat(reqObj.response_size)}; - res.json(payload); -} - -function BenchmarkServer(host, port, tls, generic, response_size) { - var app = express(); - app.use(bodyParser.json()); - app.put('/serviceProto.BenchmarkService.service/unaryCall', unaryCall); - this.input_host = host; - this.input_port = port; - if (tls) { - var credentials = {}; - var key_path = path.join(__dirname, '../test/data/server1.key'); - var pem_path = path.join(__dirname, '../test/data/server1.pem'); - - var key_data = fs.readFileSync(key_path); - var pem_data = fs.readFileSync(pem_path); - credentials['key'] = key_data; - credentials['cert'] = pem_data; - this.server = https.createServer(credentials, app); - } else { - this.server = http.createServer(app); - } -} - -util.inherits(BenchmarkServer, EventEmitter); - -BenchmarkServer.prototype.start = function() { - var self = this; - this.server.listen(this.input_port, this.input_hostname, function() { - self.last_wall_time = process.hrtime(); - self.last_usage = process.cpuUsage(); - self.emit('started'); - }); -}; - -BenchmarkServer.prototype.getPort = function() { - return this.server.address().port; -}; - -BenchmarkServer.prototype.mark = function(reset) { - var wall_time_diff = process.hrtime(this.last_wall_time); - var usage_diff = process.cpuUsage(this.last_usage); - if (reset) { - this.last_wall_time = process.hrtime(); - this.last_usage = process.cpuUsage(); - } - return { - time_elapsed: wall_time_diff[0] + wall_time_diff[1] / 1e9, - time_user: usage_diff.user / 1000000, - time_system: usage_diff.system / 1000000 - }; -}; - -BenchmarkServer.prototype.stop = function(callback) { - this.server.close(callback); -}; - -module.exports = BenchmarkServer; diff --git a/src/node/performance/generic_service.js b/src/node/performance/generic_service.js deleted file mode 100644 index 8e76c50d587..00000000000 --- a/src/node/performance/generic_service.js +++ /dev/null @@ -1,40 +0,0 @@ -/* - * - * 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. - * - */ - -var _ = require('lodash'); - -module.exports = { - 'unaryCall' : { - path: '/grpc.testing.BenchmarkService/UnaryCall', - requestStream: false, - responseStream: false, - requestSerialize: _.identity, - requestDeserialize: _.identity, - responseSerialize: _.identity, - responseDeserialize: _.identity - }, - 'streamingCall' : { - path: '/grpc.testing.BenchmarkService/StreamingCall', - requestStream: true, - responseStream: true, - requestSerialize: _.identity, - requestDeserialize: _.identity, - responseSerialize: _.identity, - responseDeserialize: _.identity - } -}; diff --git a/src/node/performance/histogram.js b/src/node/performance/histogram.js deleted file mode 100644 index a03f2c13a23..00000000000 --- a/src/node/performance/histogram.js +++ /dev/null @@ -1,165 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/** - * Histogram module. Exports the Histogram class - * @module - */ - -'use strict'; - -/** - * Histogram class. Collects data and exposes a histogram and other statistics. - * This data structure is taken directly from src/core/support/histogram.c, but - * pared down to the statistics needed for client stats in - * test/proto/benchmarks/stats.proto. - * @constructor - * @param {number} resolution The histogram's bucket resolution. Must be positive - * @param {number} max_possible The maximum allowed value. Must be greater than 1 - */ -function Histogram(resolution, max_possible) { - this.resolution = resolution; - this.max_possible = max_possible; - - this.sum = 0; - this.sum_of_squares = 0; - this.multiplier = 1 + resolution; - this.count = 0; - this.min_seen = max_possible; - this.max_seen = 0; - this.buckets = []; - for (var i = 0; i < this.bucketFor(max_possible) + 1; i++) { - this.buckets[i] = 0; - } -} - -/** - * Get the bucket index for a given value. - * @param {number} value The value to check - * @return {number} The bucket index - */ -Histogram.prototype.bucketFor = function(value) { - return Math.floor(Math.log(value) / Math.log(this.multiplier)); -}; - -/** - * Get the minimum value for a given bucket index - * @param {number} The bucket index to check - * @return {number} The minimum value for that bucket - */ -Histogram.prototype.bucketStart = function(index) { - return Math.pow(this.multiplier, index); -}; - -/** - * Add a value to the histogram. This updates all statistics with the new - * value. Those statistics should not be modified except with this function - * @param {number} value The value to add - */ -Histogram.prototype.add = function(value) { - // Ensure value is a number - value = +value; - this.sum += value; - this.sum_of_squares += value * value; - this.count++; - if (value < this.min_seen) { - this.min_seen = value; - } - if (value > this.max_seen) { - this.max_seen = value; - } - this.buckets[this.bucketFor(value)]++; -}; - -/** - * Get the mean of all added values - * @return {number} The mean - */ -Histogram.prototype.mean = function() { - return this.sum / this.count; -}; - -/** - * Get the variance of all added values. Used to calulate the standard deviation - * @return {number} The variance - */ -Histogram.prototype.variance = function() { - if (this.count == 0) { - return 0; - } - return (this.sum_of_squares * this.count - this.sum * this.sum) / - (this.count * this.count); -}; - -/** - * Get the standard deviation of all added values - * @return {number} The standard deviation - */ -Histogram.prototype.stddev = function() { - return Math.sqrt(this.variance); -}; - -/** - * Get the maximum among all added values - * @return {number} The maximum - */ -Histogram.prototype.maximum = function() { - return this.max_seen; -}; - -/** - * Get the minimum among all added values - * @return {number} The minimum - */ -Histogram.prototype.minimum = function() { - return this.min_seen; -}; - -/** - * Get the number of all added values - * @return {number} The count - */ -Histogram.prototype.getCount = function() { - return this.count; -}; - -/** - * Get the sum of all added values - * @return {number} The sum - */ -Histogram.prototype.getSum = function() { - return this.sum; -}; - -/** - * Get the sum of squares of all added values - * @return {number} The sum of squares - */ -Histogram.prototype.sumOfSquares = function() { - return this.sum_of_squares; -}; - -/** - * Get the raw histogram as a list of bucket sizes - * @return {Array.} The buckets - */ -Histogram.prototype.getContents = function() { - return this.buckets; -}; - -module.exports = Histogram; diff --git a/src/node/performance/worker.js b/src/node/performance/worker.js deleted file mode 100644 index d0fb3bcb286..00000000000 --- a/src/node/performance/worker.js +++ /dev/null @@ -1,50 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var console = require('console'); -var WorkerServiceImpl = require('./worker_service_impl'); - -var grpc = require('../../../'); -var serviceProto = grpc.load({ - root: __dirname + '/../../..', - file: 'src/proto/grpc/testing/services.proto'}).grpc.testing; - -function runServer(port, benchmark_impl) { - var server_creds = grpc.ServerCredentials.createInsecure(); - var server = new grpc.Server(); - server.addService(serviceProto.WorkerService.service, - new WorkerServiceImpl(benchmark_impl, server)); - var address = '0.0.0.0:' + port; - server.bind(address, server_creds); - server.start(); - console.log('running QPS worker on %s', address); - return server; -} - -if (require.main === module) { - Error.stackTraceLimit = Infinity; - var parseArgs = require('minimist'); - var argv = parseArgs(process.argv, { - string: ['driver_port', 'benchmark_impl'] - }); - runServer(argv.driver_port, argv.benchmark_impl); -} - -exports.runServer = runServer; diff --git a/src/node/performance/worker_service_impl.js b/src/node/performance/worker_service_impl.js deleted file mode 100644 index a73d77efc34..00000000000 --- a/src/node/performance/worker_service_impl.js +++ /dev/null @@ -1,183 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var os = require('os'); -var console = require('console'); -var BenchmarkClient = require('./benchmark_client'); -var BenchmarkServer = require('./benchmark_server'); - -module.exports = function WorkerServiceImpl(benchmark_impl, server) { - var BenchmarkClient; - var BenchmarkServer; - switch (benchmark_impl) { - case 'grpc': - BenchmarkClient = require('./benchmark_client'); - BenchmarkServer = require('./benchmark_server'); - break; - case 'express': - BenchmarkClient = require('./benchmark_client_express'); - BenchmarkServer = require('./benchmark_server_express'); - break; - default: - throw new Error('Unrecognized benchmark impl: ' + benchmark_impl); - } - - this.quitWorker = function quitWorker(call, callback) { - callback(null, {}); - server.tryShutdown(function() {}); - }; - - this.runClient = function runClient(call) { - var client; - call.on('data', function(request) { - var stats; - switch (request.argtype) { - case 'setup': - var setup = request.setup; - console.log('ClientConfig %j', setup); - client = new BenchmarkClient(setup.server_targets, - setup.client_channels, - setup.histogram_params, - setup.security_params); - client.on('error', function(error) { - call.emit('error', error); - }); - var req_size, resp_size, generic; - switch (setup.payload_config.payload) { - case 'bytebuf_params': - req_size = setup.payload_config.bytebuf_params.req_size; - resp_size = setup.payload_config.bytebuf_params.resp_size; - generic = true; - break; - case 'simple_params': - req_size = setup.payload_config.simple_params.req_size; - resp_size = setup.payload_config.simple_params.resp_size; - generic = false; - break; - default: - call.emit('error', new Error('Unsupported PayloadConfig type' + - setup.payload_config.payload)); - return; - } - switch (setup.load_params.load) { - case 'closed_loop': - client.startClosedLoop(setup.outstanding_rpcs_per_channel, - setup.rpc_type, req_size, resp_size, generic); - break; - case 'poisson': - client.startPoisson(setup.outstanding_rpcs_per_channel, - setup.rpc_type, req_size, resp_size, - setup.load_params.poisson.offered_load, generic); - break; - default: - call.emit('error', new Error('Unsupported LoadParams type' + - setup.load_params.load)); - return; - } - stats = client.mark(); - call.write({ - stats: stats - }); - break; - case 'mark': - if (client) { - stats = client.mark(request.mark.reset); - call.write({ - stats: stats - }); - } else { - call.emit('error', new Error('Got Mark before ClientConfig')); - } - break; - default: - throw new Error('Nonexistent client argtype option: ' + request.argtype); - } - }); - call.on('end', function() { - client.stop(function() { - call.end(); - }); - }); - }; - - this.runServer = function runServer(call) { - var server; - call.on('data', function(request) { - var stats; - switch (request.argtype) { - case 'setup': - console.log('ServerConfig %j', request.setup); - var setup = request.setup; - var resp_size, generic; - if (setup.payload_config) { - switch (setup.payload_config.payload) { - case 'bytebuf_params': - resp_size = setup.payload_config.bytebuf_params.resp_size; - generic = true; - break; - case 'simple_params': - resp_size = setup.payload_config.simple_params.resp_size; - generic = false; - break; - default: - call.emit('error', new Error('Unsupported PayloadConfig type' + - setup.payload_config.payload)); - return; - } - } - server = new BenchmarkServer('[::]', request.setup.port, - request.setup.security_params, - generic, resp_size); - server.on('started', function() { - stats = server.mark(); - call.write({ - stats: stats, - port: server.getPort() - }); - }); - server.start(); - break; - case 'mark': - if (server) { - stats = server.mark(request.mark.reset); - call.write({ - stats: stats, - port: server.getPort(), - cores: 1 - }); - } else { - call.emit('error', new Error('Got Mark before ServerConfig')); - } - break; - default: - throw new Error('Nonexistent server argtype option'); - } - }); - call.on('end', function() { - server.stop(function() { - call.end(); - }); - }); - }; - - this.coreCount = function coreCount(call, callback) { - callback(null, {cores: os.cpus().length}); - }; -}; diff --git a/src/node/src/client.js b/src/node/src/client.js deleted file mode 100644 index edc51b78028..00000000000 --- a/src/node/src/client.js +++ /dev/null @@ -1,951 +0,0 @@ -/** - * @license - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/** - * Client module - * - * This module contains the factory method for creating Client classes, and the - * method calling code for all types of methods. - * - * @example Create a client and call a method on it - * - * var proto_obj = grpc.load(proto_file_path); - * var Client = proto_obj.package.subpackage.ServiceName; - * var client = new Client(server_address, client_credentials); - * var call = client.unaryMethod(arguments, callback); - */ - -'use strict'; - -var _ = require('lodash'); -var arguejs = require('arguejs'); - -var grpc = require('./grpc_extension'); - -var common = require('./common'); - -var Metadata = require('./metadata'); - -var constants = require('./constants'); - -var EventEmitter = require('events').EventEmitter; - -var stream = require('stream'); - -var Readable = stream.Readable; -var Writable = stream.Writable; -var Duplex = stream.Duplex; -var util = require('util'); -var version = require('../../../package.json').version; - -/** - * Initial response metadata sent by the server when it starts processing the - * call - * @event grpc~ClientUnaryCall#metadata - * @type {grpc.Metadata} - */ - -/** - * Status of the call when it has completed. - * @event grpc~ClientUnaryCall#status - * @type grpc~StatusObject - */ - -util.inherits(ClientUnaryCall, EventEmitter); - -/** - * An EventEmitter. Used for unary calls. - * @constructor grpc~ClientUnaryCall - * @extends external:EventEmitter - * @param {grpc.internal~Call} call The call object associated with the request - */ -function ClientUnaryCall(call) { - EventEmitter.call(this); - this.call = call; -} - -util.inherits(ClientWritableStream, Writable); - -/** - * A stream that the client can write to. Used for calls that are streaming from - * the client side. - * @constructor grpc~ClientWritableStream - * @extends external:Writable - * @borrows grpc~ClientUnaryCall#cancel as grpc~ClientWritableStream#cancel - * @borrows grpc~ClientUnaryCall#getPeer as grpc~ClientWritableStream#getPeer - * @borrows grpc~ClientUnaryCall#event:metadata as - * grpc~ClientWritableStream#metadata - * @borrows grpc~ClientUnaryCall#event:status as - * grpc~ClientWritableStream#status - * @param {grpc.internal~Call} call The call object to send data with - * @param {grpc~serialize=} [serialize=identity] Serialization - * function for writes. - */ -function ClientWritableStream(call, serialize) { - Writable.call(this, {objectMode: true}); - this.call = call; - this.serialize = common.wrapIgnoreNull(serialize); - this.on('finish', function() { - var batch = {}; - batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true; - call.startBatch(batch, function() {}); - }); -} - -/** - * Write a message to the request stream. If serializing the argument fails, - * the call will be cancelled and the stream will end with an error. - * @name grpc~ClientWritableStream#write - * @kind function - * @override - * @param {*} message The message to write. Must be a valid argument to the - * serialize function of the corresponding method - * @param {grpc.writeFlags} flags Flags to modify how the message is written - * @param {Function} callback Callback for when this chunk of data is flushed - * @return {boolean} As defined for [Writable]{@link external:Writable} - */ - -/** - * Attempt to write the given chunk. Calls the callback when done. This is an - * implementation of a method needed for implementing stream.Writable. - * @private - * @param {*} chunk The chunk to write - * @param {grpc.writeFlags} encoding Used to pass write flags - * @param {function(Error=)} callback Called when the write is complete - */ -function _write(chunk, encoding, callback) { - /* jshint validthis: true */ - var batch = {}; - var message; - var self = this; - if (this.writeFailed) { - /* Once a write fails, just call the callback immediately to let the caller - flush any pending writes. */ - setImmediate(callback); - return; - } - try { - message = this.serialize(chunk); - } catch (e) { - /* Sending this error to the server and emitting it immediately on the - client may put the call in a slightly weird state on the client side, - but passing an object that causes a serialization failure is a misuse - of the API anyway, so that's OK. The primary purpose here is to give the - programmer a useful error and to stop the stream properly */ - this.call.cancelWithStatus(constants.status.INTERNAL, - 'Serialization failure'); - callback(e); - return; - } - if (_.isFinite(encoding)) { - /* Attach the encoding if it is a finite number. This is the closest we - * can get to checking that it is valid flags */ - message.grpcWriteFlags = encoding; - } - batch[grpc.opType.SEND_MESSAGE] = message; - this.call.startBatch(batch, function(err, event) { - if (err) { - /* Assume that the call is complete and that writing failed because a - status was received. In that case, set a flag to discard all future - writes */ - self.writeFailed = true; - } - callback(); - }); -} - -ClientWritableStream.prototype._write = _write; - -util.inherits(ClientReadableStream, Readable); - -/** - * A stream that the client can read from. Used for calls that are streaming - * from the server side. - * @constructor grpc~ClientReadableStream - * @extends external:Readable - * @borrows grpc~ClientUnaryCall#cancel as grpc~ClientReadableStream#cancel - * @borrows grpc~ClientUnaryCall#getPeer as grpc~ClientReadableStream#getPeer - * @borrows grpc~ClientUnaryCall#event:metadata as - * grpc~ClientReadableStream#metadata - * @borrows grpc~ClientUnaryCall#event:status as - * grpc~ClientReadableStream#status - * @param {grpc.internal~Call} call The call object to read data with - * @param {grpc~deserialize=} [deserialize=identity] - * Deserialization function for reads - */ -function ClientReadableStream(call, deserialize) { - Readable.call(this, {objectMode: true}); - this.call = call; - this.finished = false; - this.reading = false; - this.deserialize = common.wrapIgnoreNull(deserialize); - /* Status generated from reading messages from the server. Overrides the - * status from the server if not OK */ - this.read_status = null; - /* Status received from the server. */ - this.received_status = null; -} - -/** - * Called when all messages from the server have been processed. The status - * parameter indicates that the call should end with that status. status - * defaults to OK if not provided. - * @param {Object!} status The status that the call should end with - * @private - */ -function _readsDone(status) { - /* jshint validthis: true */ - if (!status) { - status = {code: constants.status.OK, details: 'OK'}; - } - if (status.code !== constants.status.OK) { - this.call.cancelWithStatus(status.code, status.details); - } - this.finished = true; - this.read_status = status; - this._emitStatusIfDone(); -} - -ClientReadableStream.prototype._readsDone = _readsDone; - -/** - * Called to indicate that we have received a status from the server. - * @private - */ -function _receiveStatus(status) { - /* jshint validthis: true */ - this.received_status = status; - this._emitStatusIfDone(); -} - -ClientReadableStream.prototype._receiveStatus = _receiveStatus; - -/** - * If we have both processed all incoming messages and received the status from - * the server, emit the status. Otherwise, do nothing. - * @private - */ -function _emitStatusIfDone() { - /* jshint validthis: true */ - var status; - if (this.read_status && this.received_status) { - if (this.read_status.code !== constants.status.OK) { - status = this.read_status; - } else { - status = this.received_status; - } - if (status.code === constants.status.OK) { - this.push(null); - } else { - var error = new Error(status.details); - error.code = status.code; - error.metadata = status.metadata; - this.emit('error', error); - } - this.emit('status', status); - } -} - -ClientReadableStream.prototype._emitStatusIfDone = _emitStatusIfDone; - -/** - * Read the next object from the stream. - * @private - * @param {*} size Ignored because we use objectMode=true - */ -function _read(size) { - /* jshint validthis: true */ - var self = this; - /** - * Callback to be called when a READ event is received. Pushes the data onto - * the read queue and starts reading again if applicable - * @param {grpc.Event} event READ event object - */ - function readCallback(err, event) { - if (err) { - // Something has gone wrong. Stop reading and wait for status - self.finished = true; - self._readsDone(); - return; - } - var data = event.read; - var deserialized; - try { - deserialized = self.deserialize(data); - } catch (e) { - self._readsDone({code: constants.status.INTERNAL, - details: 'Failed to parse server response'}); - return; - } - if (data === null) { - self._readsDone(); - return; - } - if (self.push(deserialized) && data !== null) { - var read_batch = {}; - read_batch[grpc.opType.RECV_MESSAGE] = true; - self.call.startBatch(read_batch, readCallback); - } else { - self.reading = false; - } - } - if (self.finished) { - self.push(null); - } else { - if (!self.reading) { - self.reading = true; - var read_batch = {}; - read_batch[grpc.opType.RECV_MESSAGE] = true; - self.call.startBatch(read_batch, readCallback); - } - } -} - -ClientReadableStream.prototype._read = _read; - -util.inherits(ClientDuplexStream, Duplex); - -/** - * A stream that the client can read from or write to. Used for calls with - * duplex streaming. - * @constructor grpc~ClientDuplexStream - * @extends external:Duplex - * @borrows grpc~ClientUnaryCall#cancel as grpc~ClientDuplexStream#cancel - * @borrows grpc~ClientUnaryCall#getPeer as grpc~ClientDuplexStream#getPeer - * @borrows grpc~ClientWritableStream#write as grpc~ClientDuplexStream#write - * @borrows grpc~ClientUnaryCall#event:metadata as - * grpc~ClientDuplexStream#metadata - * @borrows grpc~ClientUnaryCall#event:status as - * grpc~ClientDuplexStream#status - * @param {grpc.internal~Call} call Call object to proxy - * @param {grpc~serialize=} [serialize=identity] Serialization - * function for requests - * @param {grpc~deserialize=} [deserialize=identity] - * Deserialization function for responses - */ -function ClientDuplexStream(call, serialize, deserialize) { - Duplex.call(this, {objectMode: true}); - this.serialize = common.wrapIgnoreNull(serialize); - this.deserialize = common.wrapIgnoreNull(deserialize); - this.call = call; - /* Status generated from reading messages from the server. Overrides the - * status from the server if not OK */ - this.read_status = null; - /* Status received from the server. */ - this.received_status = null; - this.on('finish', function() { - var batch = {}; - batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true; - call.startBatch(batch, function() {}); - }); -} - -ClientDuplexStream.prototype._readsDone = _readsDone; -ClientDuplexStream.prototype._receiveStatus = _receiveStatus; -ClientDuplexStream.prototype._emitStatusIfDone = _emitStatusIfDone; -ClientDuplexStream.prototype._read = _read; -ClientDuplexStream.prototype._write = _write; - -/** - * Cancel the ongoing call. Results in the call ending with a CANCELLED status, - * unless it has already ended with some other status. - * @alias grpc~ClientUnaryCall#cancel - */ -function cancel() { - /* jshint validthis: true */ - this.call.cancel(); -} - -ClientUnaryCall.prototype.cancel = cancel; -ClientReadableStream.prototype.cancel = cancel; -ClientWritableStream.prototype.cancel = cancel; -ClientDuplexStream.prototype.cancel = cancel; - -/** - * Get the endpoint this call/stream is connected to. - * @return {string} The URI of the endpoint - * @alias grpc~ClientUnaryCall#getPeer - */ -function getPeer() { - /* jshint validthis: true */ - return this.call.getPeer(); -} - -ClientUnaryCall.prototype.getPeer = getPeer; -ClientReadableStream.prototype.getPeer = getPeer; -ClientWritableStream.prototype.getPeer = getPeer; -ClientDuplexStream.prototype.getPeer = getPeer; - -/** - * Any client call type - * @typedef {(ClientUnaryCall|ClientReadableStream| - * ClientWritableStream|ClientDuplexStream)} - * grpc.Client~Call - */ - -/** - * Options that can be set on a call. - * @typedef {Object} grpc.Client~CallOptions - * @property {grpc~Deadline} deadline The deadline for the entire call to - * complete. - * @property {string} host Server hostname to set on the call. Only meaningful - * if different from the server address used to construct the client. - * @property {grpc.Client~Call} parent Parent call. Used in servers when - * making a call as part of the process of handling a call. Used to - * propagate some information automatically, as specified by - * propagate_flags. - * @property {number} propagate_flags Indicates which properties of a parent - * call should propagate to this call. Bitwise combination of flags in - * {@link grpc.propagate}. - * @property {grpc.credentials~CallCredentials} credentials The credentials that - * should be used to make this particular call. - */ - -/** - * Get a call object built with the provided options. - * @access private - * @param {grpc.Client~CallOptions=} options Options object. - */ -function getCall(channel, method, options) { - var deadline; - var host; - var parent; - var propagate_flags; - var credentials; - if (options) { - deadline = options.deadline; - host = options.host; - parent = _.get(options, 'parent.call'); - propagate_flags = options.propagate_flags; - credentials = options.credentials; - } - if (deadline === undefined) { - deadline = Infinity; - } - var call = new grpc.Call(channel, method, deadline, host, - parent, propagate_flags); - if (credentials) { - call.setCredentials(credentials); - } - return call; -} - -/** - * A generic gRPC client. Primarily useful as a base class for generated clients - * @memberof grpc - * @constructor - * @param {string} address Server address to connect to - * @param {grpc~ChannelCredentials} credentials Credentials to use to connect to - * the server - * @param {Object} options Options to apply to channel creation - */ -function Client(address, credentials, options) { - if (!options) { - options = {}; - } - /* Append the grpc-node user agent string after the application user agent - * string, and put the combination at the beginning of the user agent string - */ - if (options['grpc.primary_user_agent']) { - options['grpc.primary_user_agent'] += ' '; - } else { - options['grpc.primary_user_agent'] = ''; - } - options['grpc.primary_user_agent'] += 'grpc-node/' + version; - /* Private fields use $ as a prefix instead of _ because it is an invalid - * prefix of a method name */ - this.$channel = new grpc.Channel(address, credentials, options); -} - -exports.Client = Client; - -/** - * @callback grpc.Client~requestCallback - * @param {?grpc~ServiceError} error The error, if the call - * failed - * @param {*} value The response value, if the call succeeded - */ - -/** - * Make a unary request to the given method, using the given serialize - * and deserialize functions, with the given argument. - * @param {string} method The name of the method to request - * @param {grpc~serialize} serialize The serialization function for - * inputs - * @param {grpc~deserialize} deserialize The deserialization - * function for outputs - * @param {*} argument The argument to the call. Should be serializable with - * serialize - * @param {grpc.Metadata=} metadata Metadata to add to the call - * @param {grpc.Client~CallOptions=} options Options map - * @param {grpc.Client~requestCallback} callback The callback to - * for when the response is received - * @return {grpc~ClientUnaryCall} An event emitter for stream related events - */ -Client.prototype.makeUnaryRequest = function(method, serialize, deserialize, - argument, metadata, options, - callback) { - /* While the arguments are listed in the function signature, those variables - * are not used directly. Instead, ArgueJS processes the arguments - * object. This allows for simple handling of optional arguments in the - * middle of the argument list, and also provides type checking. */ - var args = arguejs({method: String, serialize: Function, - deserialize: Function, - argument: null, metadata: [Metadata, new Metadata()], - options: [Object], callback: Function}, arguments); - var call = getCall(this.$channel, method, args.options); - var emitter = new ClientUnaryCall(call); - metadata = args.metadata.clone(); - var client_batch = {}; - var message = serialize(args.argument); - if (args.options) { - message.grpcWriteFlags = args.options.flags; - } - - client_batch[grpc.opType.SEND_INITIAL_METADATA] = - metadata._getCoreRepresentation(); - client_batch[grpc.opType.SEND_MESSAGE] = message; - client_batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true; - client_batch[grpc.opType.RECV_INITIAL_METADATA] = true; - client_batch[grpc.opType.RECV_MESSAGE] = true; - client_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true; - call.startBatch(client_batch, function(err, response) { - response.status.metadata = Metadata._fromCoreRepresentation( - response.status.metadata); - var status = response.status; - var error; - var deserialized; - emitter.emit('metadata', Metadata._fromCoreRepresentation( - response.metadata)); - if (status.code === constants.status.OK) { - if (err) { - // Got a batch error, but OK status. Something went wrong - args.callback(err); - return; - } else { - try { - deserialized = deserialize(response.read); - } catch (e) { - /* Change status to indicate bad server response. This will result - * in passing an error to the callback */ - status = { - code: constants.status.INTERNAL, - details: 'Failed to parse server response' - }; - } - } - } - if (status.code !== constants.status.OK) { - error = new Error(status.details); - error.code = status.code; - error.metadata = status.metadata; - args.callback(error); - } else { - args.callback(null, deserialized); - } - emitter.emit('status', status); - }); - return emitter; -}; - -/** - * Make a client stream request to the given method, using the given serialize - * and deserialize functions, with the given argument. - * @param {string} method The name of the method to request - * @param {grpc~serialize} serialize The serialization function for - * inputs - * @param {grpc~deserialize} deserialize The deserialization - * function for outputs - * @param {grpc.Metadata=} metadata Array of metadata key/value pairs to add to - * the call - * @param {grpc.Client~CallOptions=} options Options map - * @param {grpc.Client~requestCallback} callback The callback to for when the - * response is received - * @return {grpc~ClientWritableStream} An event emitter for stream related - * events - */ -Client.prototype.makeClientStreamRequest = function(method, serialize, - deserialize, metadata, - options, callback) { - /* While the arguments are listed in the function signature, those variables - * are not used directly. Instead, ArgueJS processes the arguments - * object. This allows for simple handling of optional arguments in the - * middle of the argument list, and also provides type checking. */ - var args = arguejs({method:String, serialize: Function, - deserialize: Function, - metadata: [Metadata, new Metadata()], - options: [Object], callback: Function}, arguments); - var call = getCall(this.$channel, method, args.options); - metadata = args.metadata.clone(); - var stream = new ClientWritableStream(call, serialize); - var metadata_batch = {}; - metadata_batch[grpc.opType.SEND_INITIAL_METADATA] = - metadata._getCoreRepresentation(); - metadata_batch[grpc.opType.RECV_INITIAL_METADATA] = true; - call.startBatch(metadata_batch, function(err, response) { - if (err) { - // The call has stopped for some reason. A non-OK status will arrive - // in the other batch. - return; - } - stream.emit('metadata', Metadata._fromCoreRepresentation( - response.metadata)); - }); - var client_batch = {}; - client_batch[grpc.opType.RECV_MESSAGE] = true; - client_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true; - call.startBatch(client_batch, function(err, response) { - response.status.metadata = Metadata._fromCoreRepresentation( - response.status.metadata); - var status = response.status; - var error; - var deserialized; - if (status.code === constants.status.OK) { - if (err) { - // Got a batch error, but OK status. Something went wrong - args.callback(err); - return; - } else { - try { - deserialized = deserialize(response.read); - } catch (e) { - /* Change status to indicate bad server response. This will result - * in passing an error to the callback */ - status = { - code: constants.status.INTERNAL, - details: 'Failed to parse server response' - }; - } - } - } - if (status.code !== constants.status.OK) { - error = new Error(response.status.details); - error.code = status.code; - error.metadata = status.metadata; - args.callback(error); - } else { - args.callback(null, deserialized); - } - stream.emit('status', status); - }); - return stream; -}; - -/** - * Make a server stream request to the given method, with the given serialize - * and deserialize function, using the given argument - * @param {string} method The name of the method to request - * @param {grpc~serialize} serialize The serialization function for inputs - * @param {grpc~deserialize} deserialize The deserialization - * function for outputs - * @param {*} argument The argument to the call. Should be serializable with - * serialize - * @param {grpc.Metadata=} metadata Array of metadata key/value pairs to add to - * the call - * @param {grpc.Client~CallOptions=} options Options map - * @return {grpc~ClientReadableStream} An event emitter for stream related - * events - */ -Client.prototype.makeServerStreamRequest = function(method, serialize, - deserialize, argument, - metadata, options) { - /* While the arguments are listed in the function signature, those variables - * are not used directly. Instead, ArgueJS processes the arguments - * object. */ - var args = arguejs({method:String, serialize: Function, - deserialize: Function, - argument: null, metadata: [Metadata, new Metadata()], - options: [Object]}, arguments); - var call = getCall(this.$channel, method, args.options); - metadata = args.metadata.clone(); - var stream = new ClientReadableStream(call, deserialize); - var start_batch = {}; - var message = serialize(args.argument); - if (args.options) { - message.grpcWriteFlags = args.options.flags; - } - start_batch[grpc.opType.SEND_INITIAL_METADATA] = - metadata._getCoreRepresentation(); - start_batch[grpc.opType.RECV_INITIAL_METADATA] = true; - start_batch[grpc.opType.SEND_MESSAGE] = message; - start_batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true; - call.startBatch(start_batch, function(err, response) { - if (err) { - // The call has stopped for some reason. A non-OK status will arrive - // in the other batch. - return; - } - stream.emit('metadata', Metadata._fromCoreRepresentation( - response.metadata)); - }); - var status_batch = {}; - status_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true; - call.startBatch(status_batch, function(err, response) { - if (err) { - stream.emit('error', err); - return; - } - response.status.metadata = Metadata._fromCoreRepresentation( - response.status.metadata); - stream._receiveStatus(response.status); - }); - return stream; -}; - - -/** - * Make a bidirectional stream request with this method on the given channel. - * @param {string} method The name of the method to request - * @param {grpc~serialize} serialize The serialization function for inputs - * @param {grpc~deserialize} deserialize The deserialization - * function for outputs - * @param {grpc.Metadata=} metadata Array of metadata key/value - * pairs to add to the call - * @param {grpc.Client~CallOptions=} options Options map - * @return {grpc~ClientDuplexStream} An event emitter for stream related events - */ -Client.prototype.makeBidiStreamRequest = function(method, serialize, - deserialize, metadata, - options) { - /* While the arguments are listed in the function signature, those variables - * are not used directly. Instead, ArgueJS processes the arguments - * object. */ - var args = arguejs({method:String, serialize: Function, - deserialize: Function, - metadata: [Metadata, new Metadata()], - options: [Object]}, arguments); - var call = getCall(this.$channel, method, args.options); - metadata = args.metadata.clone(); - var stream = new ClientDuplexStream(call, serialize, deserialize); - var start_batch = {}; - start_batch[grpc.opType.SEND_INITIAL_METADATA] = - metadata._getCoreRepresentation(); - start_batch[grpc.opType.RECV_INITIAL_METADATA] = true; - call.startBatch(start_batch, function(err, response) { - if (err) { - // The call has stopped for some reason. A non-OK status will arrive - // in the other batch. - return; - } - stream.emit('metadata', Metadata._fromCoreRepresentation( - response.metadata)); - }); - var status_batch = {}; - status_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true; - call.startBatch(status_batch, function(err, response) { - if (err) { - stream.emit('error', err); - return; - } - response.status.metadata = Metadata._fromCoreRepresentation( - response.status.metadata); - stream._receiveStatus(response.status); - }); - return stream; -}; - -/** - * Close this client. - */ -Client.prototype.close = function() { - this.$channel.close(); -}; - -/** - * Return the underlying channel object for the specified client - * @return {Channel} The channel - */ -Client.prototype.getChannel = function() { - return this.$channel; -}; - -/** - * Wait for the client to be ready. The callback will be called when the - * client has successfully connected to the server, and it will be called - * with an error if the attempt to connect to the server has unrecoverablly - * failed or if the deadline expires. This function will make the channel - * start connecting if it has not already done so. - * @param {grpc~Deadline} deadline When to stop waiting for a connection. - * @param {function(Error)} callback The callback to call when done attempting - * to connect. - */ -Client.prototype.waitForReady = function(deadline, callback) { - var self = this; - var checkState = function(err) { - if (err) { - callback(new Error('Failed to connect before the deadline')); - return; - } - var new_state = self.$channel.getConnectivityState(true); - if (new_state === grpc.connectivityState.READY) { - callback(); - } else if (new_state === grpc.connectivityState.FATAL_FAILURE) { - callback(new Error('Failed to connect to server')); - } else { - self.$channel.watchConnectivityState(new_state, deadline, checkState); - } - }; - checkState(); -}; - -/** - * Map with short names for each of the requester maker functions. Used in - * makeClientConstructor - * @private - */ -var requester_funcs = { - unary: Client.prototype.makeUnaryRequest, - server_stream: Client.prototype.makeServerStreamRequest, - client_stream: Client.prototype.makeClientStreamRequest, - bidi: Client.prototype.makeBidiStreamRequest -}; - -function getDefaultValues(metadata, options) { - var res = {}; - res.metadata = metadata || new Metadata(); - res.options = options || {}; - return res; -} - -/** - * Map with wrappers for each type of requester function to make it use the old - * argument order with optional arguments after the callback. - * @access private - */ -var deprecated_request_wrap = { - unary: function(makeUnaryRequest) { - return function makeWrappedUnaryRequest(argument, callback, - metadata, options) { - /* jshint validthis: true */ - var opt_args = getDefaultValues(metadata, metadata); - return makeUnaryRequest.call(this, argument, opt_args.metadata, - opt_args.options, callback); - }; - }, - client_stream: function(makeServerStreamRequest) { - return function makeWrappedClientStreamRequest(callback, metadata, - options) { - /* jshint validthis: true */ - var opt_args = getDefaultValues(metadata, options); - return makeServerStreamRequest.call(this, opt_args.metadata, - opt_args.options, callback); - }; - }, - server_stream: _.identity, - bidi: _.identity -}; - -/** - * Creates a constructor for a client with the given methods, as specified in - * the methods argument. The resulting class will have an instance method for - * each method in the service, which is a partial application of one of the - * [Client]{@link grpc.Client} request methods, depending on `requestSerialize` - * and `responseSerialize`, with the `method`, `serialize`, and `deserialize` - * arguments predefined. - * @memberof grpc - * @alias grpc~makeGenericClientConstructor - * @param {grpc~ServiceDefinition} methods An object mapping method names to - * method attributes - * @param {string} serviceName The fully qualified name of the service - * @param {Object} class_options An options object. - * @param {boolean=} [class_options.deprecatedArgumentOrder=false] Indicates - * that the old argument order should be used for methods, with optional - * arguments at the end instead of the callback at the end. This option - * is only a temporary stopgap measure to smooth an API breakage. - * It is deprecated, and new code should not use it. - * @return {function} New client constructor, which is a subclass of - * {@link grpc.Client}, and has the same arguments as that constructor. - */ -exports.makeClientConstructor = function(methods, serviceName, - class_options) { - if (!class_options) { - class_options = {}; - } - - function ServiceClient(address, credentials, options) { - Client.call(this, address, credentials, options); - } - - util.inherits(ServiceClient, Client); - - _.each(methods, function(attrs, name) { - var method_type; - if (_.startsWith(name, '$')) { - throw new Error('Method names cannot start with $'); - } - if (attrs.requestStream) { - if (attrs.responseStream) { - method_type = 'bidi'; - } else { - method_type = 'client_stream'; - } - } else { - if (attrs.responseStream) { - method_type = 'server_stream'; - } else { - method_type = 'unary'; - } - } - var serialize = attrs.requestSerialize; - var deserialize = attrs.responseDeserialize; - var method_func = _.partial(requester_funcs[method_type], attrs.path, - serialize, deserialize); - if (class_options.deprecatedArgumentOrder) { - ServiceClient.prototype[name] = deprecated_request_wrap(method_func); - } else { - ServiceClient.prototype[name] = method_func; - } - // Associate all provided attributes with the method - _.assign(ServiceClient.prototype[name], attrs); - }); - - ServiceClient.service = methods; - - return ServiceClient; -}; - -/** - * Return the underlying channel object for the specified client - * @memberof grpc - * @alias grpc~getClientChannel - * @param {Client} client - * @return {Channel} The channel - * @see grpc.Client#getChannel - */ -exports.getClientChannel = function(client) { - return Client.prototype.getChannel.call(client); -}; - -/** - * Wait for the client to be ready. The callback will be called when the - * client has successfully connected to the server, and it will be called - * with an error if the attempt to connect to the server has unrecoverablly - * failed or if the deadline expires. This function will make the channel - * start connecting if it has not already done so. - * @memberof grpc - * @alias grpc~waitForClientReady - * @param {Client} client The client to wait on - * @param {grpc~Deadline} deadline When to stop waiting for a connection. Pass - * Infinity to wait forever. - * @param {function(Error)} callback The callback to call when done attempting - * to connect. - * @see grpc.Client#waitForReady - */ -exports.waitForClientReady = function(client, deadline, callback) { - Client.prototype.waitForReady.call(client, deadline, callback); -}; diff --git a/src/node/src/common.js b/src/node/src/common.js deleted file mode 100644 index 5a444f5e963..00000000000 --- a/src/node/src/common.js +++ /dev/null @@ -1,172 +0,0 @@ -/** - * @license - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var _ = require('lodash'); - -/** - * Wrap a function to pass null-like values through without calling it. If no - * function is given, just uses the identity. - * @private - * @param {?function} func The function to wrap - * @return {function} The wrapped function - */ -exports.wrapIgnoreNull = function wrapIgnoreNull(func) { - if (!func) { - return _.identity; - } - return function(arg) { - if (arg === null || arg === undefined) { - return null; - } - return func(arg); - }; -}; - -/** - * The logger object for the gRPC module. Defaults to console. - * @private - */ -exports.logger = console; - -/** - * The current logging verbosity. 0 corresponds to logging everything - * @private - */ -exports.logVerbosity = 0; - -/** - * Log a message if the severity is at least as high as the current verbosity - * @private - * @param {Number} severity A value of the grpc.logVerbosity map - * @param {String} message The message to log - */ -exports.log = function log(severity, message) { - if (severity >= exports.logVerbosity) { - exports.logger.error(message); - } -}; - -/** - * Default options for loading proto files into gRPC - * @alias grpc~defaultLoadOptions - */ -exports.defaultGrpcOptions = { - convertFieldsToCamelCase: false, - binaryAsBase64: false, - longsAsStrings: true, - enumsAsStrings: true, - deprecatedArgumentOrder: false -}; - -// JSDoc definitions that are used in multiple other modules - -/** - * Represents the status of a completed request. If `code` is - * {@link grpc.status}.OK, then the request has completed successfully. - * Otherwise, the request has failed, `details` will contain a description of - * the error. Either way, `metadata` contains the trailing response metadata - * sent by the server when it finishes processing the call. - * @typedef {object} grpc~StatusObject - * @property {number} code The error code, a key of {@link grpc.status} - * @property {string} details Human-readable description of the status - * @property {grpc.Metadata} metadata Trailing metadata sent with the status, - * if applicable - */ - -/** - * Describes how a request has failed. The member `message` will be the same as - * `details` in {@link grpc~StatusObject}, and `code` and `metadata` are the - * same as in that object. - * @typedef {Error} grpc~ServiceError - * @property {number} code The error code, a key of {@link grpc.status} that is - * not `grpc.status.OK` - * @property {grpc.Metadata} metadata Trailing metadata sent with the status, - * if applicable - */ - -/** - * The EventEmitter class in the event standard module - * @external EventEmitter - * @see https://nodejs.org/api/events.html#events_class_eventemitter - */ - -/** - * The Readable class in the stream standard module - * @external Readable - * @see https://nodejs.org/api/stream.html#stream_readable_streams - */ - -/** - * The Writable class in the stream standard module - * @external Writable - * @see https://nodejs.org/api/stream.html#stream_writable_streams - */ - -/** - * The Duplex class in the stream standard module - * @external Duplex - * @see https://nodejs.org/api/stream.html#stream_class_stream_duplex - */ - -/** - * A serialization function - * @callback grpc~serialize - * @param {*} value The value to serialize - * @return {Buffer} The value serialized as a byte sequence - */ - -/** - * A deserialization function - * @callback grpc~deserialize - * @param {Buffer} data The byte sequence to deserialize - * @return {*} The data deserialized as a value - */ - -/** - * The deadline of an operation. If it is a date, the deadline is reached at - * the date and time specified. If it is a finite number, it is treated as - * a number of milliseconds since the Unix Epoch. If it is Infinity, the - * deadline will never be reached. If it is -Infinity, the deadline has already - * passed. - * @typedef {(number|date)} grpc~Deadline - */ - -/** - * An object that completely defines a service method signature. - * @typedef {Object} grpc~MethodDefinition - * @property {string} path The method's URL path - * @property {boolean} requestStream Indicates whether the method accepts - * a stream of requests - * @property {boolean} responseStream Indicates whether the method returns - * a stream of responses - * @property {grpc~serialize} requestSerialize Serialization - * function for request values - * @property {grpc~serialize} responseSerialize Serialization - * function for response values - * @property {grpc~deserialize} requestDeserialize Deserialization - * function for request data - * @property {grpc~deserialize} responseDeserialize Deserialization - * function for repsonse data - */ - -/** - * An object that completely defines a service. - * @typedef {Object.} grpc~ServiceDefinition - */ diff --git a/src/node/src/constants.js b/src/node/src/constants.js deleted file mode 100644 index c90e44d0d3a..00000000000 --- a/src/node/src/constants.js +++ /dev/null @@ -1,236 +0,0 @@ -/** - * @license - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/* The comments about status codes are copied verbatim (with some formatting - * modifications) from include/grpc/impl/codegen/status.h, for the purpose of - * including them in generated documentation. - */ -/** - * Enum of status codes that gRPC can return - * @memberof grpc - * @alias grpc.status - * @readonly - * @enum {number} - */ -exports.status = { - /** Not an error; returned on success */ - OK: 0, - /** The operation was cancelled (typically by the caller). */ - CANCELLED: 1, - /** - * Unknown error. An example of where this error may be returned is - * if a status value received from another address space belongs to - * an error-space that is not known in this address space. Also - * errors raised by APIs that do not return enough error information - * may be converted to this error. - */ - UNKNOWN: 2, - /** - * Client specified an invalid argument. Note that this differs - * from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments - * that are problematic regardless of the state of the system - * (e.g., a malformed file name). - */ - INVALID_ARGUMENT: 3, - /** - * Deadline expired before operation could complete. For operations - * that change the state of the system, this error may be returned - * even if the operation has completed successfully. For example, a - * successful response from a server could have been delayed long - * enough for the deadline to expire. - */ - DEADLINE_EXCEEDED: 4, - /** Some requested entity (e.g., file or directory) was not found. */ - NOT_FOUND: 5, - /** - * Some entity that we attempted to create (e.g., file or directory) - * already exists. - */ - ALREADY_EXISTS: 6, - /** - * The caller does not have permission to execute the specified - * operation. PERMISSION_DENIED must not be used for rejections - * caused by exhausting some resource (use RESOURCE_EXHAUSTED - * instead for those errors). PERMISSION_DENIED must not be - * used if the caller can not be identified (use UNAUTHENTICATED - * instead for those errors). - */ - PERMISSION_DENIED: 7, - /** - * Some resource has been exhausted, perhaps a per-user quota, or - * perhaps the entire file system is out of space. - */ - RESOURCE_EXHAUSTED: 8, - /** - * Operation was rejected because the system is not in a state - * required for the operation's execution. For example, directory - * to be deleted may be non-empty, an rmdir operation is applied to - * a non-directory, etc. - * - * A litmus test that may help a service implementor in deciding - * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: - * - * - Use UNAVAILABLE if the client can retry just the failing call. - * - Use ABORTED if the client should retry at a higher-level - * (e.g., restarting a read-modify-write sequence). - * - Use FAILED_PRECONDITION if the client should not retry until - * the system state has been explicitly fixed. E.g., if an "rmdir" - * fails because the directory is non-empty, FAILED_PRECONDITION - * should be returned since the client should not retry unless - * they have first fixed up the directory by deleting files from it. - * - Use FAILED_PRECONDITION if the client performs conditional - * REST Get/Update/Delete on a resource and the resource on the - * server does not match the condition. E.g., conflicting - * read-modify-write on the same resource. - */ - FAILED_PRECONDITION: 9, - /** - * The operation was aborted, typically due to a concurrency issue - * like sequencer check failures, transaction aborts, etc. - * - * See litmus test above for deciding between FAILED_PRECONDITION, - * ABORTED, and UNAVAILABLE. - */ - ABORTED: 10, - /** - * Operation was attempted past the valid range. E.g., seeking or - * reading past end of file. - * - * Unlike INVALID_ARGUMENT, this error indicates a problem that may - * be fixed if the system state changes. For example, a 32-bit file - * system will generate INVALID_ARGUMENT if asked to read at an - * offset that is not in the range [0,2^32-1], but it will generate - * OUT_OF_RANGE if asked to read from an offset past the current - * file size. - * - * There is a fair bit of overlap between FAILED_PRECONDITION and - * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific - * error) when it applies so that callers who are iterating through - * a space can easily look for an OUT_OF_RANGE error to detect when - * they are done. - */ - OUT_OF_RANGE: 11, - /** Operation is not implemented or not supported/enabled in this service. */ - UNIMPLEMENTED: 12, - /** - * Internal errors. Means some invariants expected by underlying - * system has been broken. If you see one of these errors, - * something is very broken. - */ - INTERNAL: 13, - /** - * The service is currently unavailable. This is a most likely a - * transient condition and may be corrected by retrying with - * a backoff. - * - * See litmus test above for deciding between FAILED_PRECONDITION, - * ABORTED, and UNAVAILABLE. */ - UNAVAILABLE: 14, - /** Unrecoverable data loss or corruption. */ - DATA_LOSS: 15, - /** - * The request does not have valid authentication credentials for the - * operation. - */ - UNAUTHENTICATED: 16 -}; - -/* The comments about propagation bit flags are copied rom - * include/grpc/impl/codegen/propagation_bits.h for the purpose of including - * them in generated documentation. - */ -/** - * Propagation flags: these can be bitwise or-ed to form the propagation option - * for calls. - * - * Users are encouraged to write propagation masks as deltas from the default. - * i.e. write `grpc.propagate.DEFAULTS & ~grpc.propagate.DEADLINE` to disable - * deadline propagation. - * @memberof grpc - * @alias grpc.propagate - * @enum {number} - */ -exports.propagate = { - DEADLINE: 1, - CENSUS_STATS_CONTEXT: 2, - CENSUS_TRACING_CONTEXT: 4, - CANCELLATION: 8, - DEFAULTS: 65535 -}; - -/* Many of the following comments are copied from - * include/grpc/impl/codegen/grpc_types.h - */ -/** - * Call error constants. Call errors almost always indicate bugs in the gRPC - * library, and these error codes are mainly useful for finding those bugs. - * @memberof grpc - * @readonly - * @enum {number} - */ -const callError = { - OK: 0, - ERROR: 1, - NOT_ON_SERVER: 2, - NOT_ON_CLIENT: 3, - ALREADY_INVOKED: 5, - NOT_INVOKED: 6, - ALREADY_FINISHED: 7, - TOO_MANY_OPERATIONS: 8, - INVALID_FLAGS: 9, - INVALID_METADATA: 10, - INVALID_MESSAGE: 11, - NOT_SERVER_COMPLETION_QUEUE: 12, - BATCH_TOO_BIG: 13, - PAYLOAD_TYPE_MISMATCH: 14 -}; - -exports.callError = callError; - -/** - * Write flags: these can be bitwise or-ed to form write options that modify - * how data is written. - * @memberof grpc - * @alias grpc.writeFlags - * @readonly - * @enum {number} - */ -exports.writeFlags = { - /** - * Hint that the write may be buffered and need not go out on the wire - * immediately. GRPC is free to buffer the message until the next non-buffered - * write, or until writes_done, but it need not buffer completely or at all. - */ - BUFFER_HINT: 1, - /** - * Force compression to be disabled for a particular write - */ - NO_COMPRESS: 2 -}; - -/** - * @memberof grpc - * @alias grpc.logVerbosity - * @readonly - * @enum {number} - */ -exports.logVerbosity = { - DEBUG: 0, - INFO: 1, - ERROR: 2 -}; diff --git a/src/node/src/credentials.js b/src/node/src/credentials.js deleted file mode 100644 index d68d888e6a1..00000000000 --- a/src/node/src/credentials.js +++ /dev/null @@ -1,207 +0,0 @@ -/** - * @license - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/** - * Credentials module - * - * This module contains factory methods for two different credential types: - * CallCredentials and ChannelCredentials. ChannelCredentials are things like - * SSL credentials that can be used to secure a connection, and are used to - * construct a Client object. CallCredentials genrally modify metadata, so they - * can be attached to an individual method call. - * - * CallCredentials can be composed with other CallCredentials to create - * CallCredentials. ChannelCredentials can be composed with CallCredentials - * to create ChannelCredentials. No combined credential can have more than - * one ChannelCredentials. - * - * For example, to create a client secured with SSL that uses Google - * default application credentials to authenticate: - * - * @example - * var channel_creds = credentials.createSsl(root_certs); - * (new GoogleAuth()).getApplicationDefault(function(err, credential) { - * var call_creds = credentials.createFromGoogleCredential(credential); - * var combined_creds = credentials.combineChannelCredentials( - * channel_creds, call_creds); - * var client = new Client(address, combined_creds); - * }); - * - * @namespace grpc.credentials - */ - -'use strict'; - -var grpc = require('./grpc_extension'); - -/** - * This cannot be constructed directly. Instead, instances of this class should - * be created using the factory functions in {@link grpc.credentials} - * @constructor grpc.credentials~CallCredentials - */ -var CallCredentials = grpc.CallCredentials; - -/** - * This cannot be constructed directly. Instead, instances of this class should - * be created using the factory functions in {@link grpc.credentials} - * @constructor grpc.credentials~ChannelCredentials - */ -var ChannelCredentials = grpc.ChannelCredentials; - -var Metadata = require('./metadata.js'); - -var common = require('./common.js'); - -var constants = require('./constants'); - -var _ = require('lodash'); - -/** - * @external GoogleCredential - * @see https://github.com/google/google-auth-library-nodejs - */ - -/** - * Create an SSL Credentials object. If using a client-side certificate, both - * the second and third arguments must be passed. - * @memberof grpc.credentials - * @alias grpc.credentials.createSsl - * @kind function - * @param {Buffer=} root_certs The root certificate data - * @param {Buffer=} private_key The client certificate private key, if - * applicable - * @param {Buffer=} cert_chain The client certificate cert chain, if applicable - * @return {grpc.credentials.ChannelCredentials} The SSL Credentials object - */ -exports.createSsl = ChannelCredentials.createSsl; - -/** - * @callback grpc.credentials~metadataCallback - * @param {Error} error The error, if getting metadata failed - * @param {grpc.Metadata} metadata The metadata - */ - -/** - * @callback grpc.credentials~generateMetadata - * @param {Object} params Parameters that can modify metadata generation - * @param {string} params.service_url The URL of the service that the call is - * going to - * @param {grpc.credentials~metadataCallback} callback - */ - -/** - * Create a gRPC credentials object from a metadata generation function. This - * function gets the service URL and a callback as parameters. The error - * passed to the callback can optionally have a 'code' value attached to it, - * which corresponds to a status code that this library uses. - * @memberof grpc.credentials - * @alias grpc.credentials.createFromMetadataGenerator - * @param {grpc.credentials~generateMetadata} metadata_generator The function - * that generates metadata - * @return {grpc.credentials.CallCredentials} The credentials object - */ -exports.createFromMetadataGenerator = function(metadata_generator) { - return CallCredentials.createFromPlugin(function(service_url, cb_data, - callback) { - metadata_generator({service_url: service_url}, function(error, metadata) { - var code = constants.status.OK; - var message = ''; - if (error) { - message = error.message; - if (error.hasOwnProperty('code') && _.isFinite(error.code)) { - code = error.code; - } else { - code = constants.status.UNAUTHENTICATED; - } - if (!metadata) { - metadata = new Metadata(); - } - } - callback(code, message, metadata._getCoreRepresentation(), cb_data); - }); - }); -}; - -/** - * Create a gRPC credential from a Google credential object. - * @memberof grpc.credentials - * @alias grpc.credentials.createFromGoogleCredential - * @param {external:GoogleCredential} google_credential The Google credential - * object to use - * @return {grpc.credentials.CallCredentials} The resulting credentials object - */ -exports.createFromGoogleCredential = function(google_credential) { - return exports.createFromMetadataGenerator(function(auth_context, callback) { - var service_url = auth_context.service_url; - google_credential.getRequestMetadata(service_url, function(err, header) { - if (err) { - common.log(constants.logVerbosity.INFO, 'Auth error:' + err); - callback(err); - return; - } - var metadata = new Metadata(); - metadata.add('authorization', header.Authorization); - callback(null, metadata); - }); - }); -}; - -/** - * Combine a ChannelCredentials with any number of CallCredentials into a single - * ChannelCredentials object. - * @memberof grpc.credentials - * @alias grpc.credentials.combineChannelCredentials - * @param {ChannelCredentials} channel_credential The ChannelCredentials to - * start with - * @param {...CallCredentials} credentials The CallCredentials to compose - * @return ChannelCredentials A credentials object that combines all of the - * input credentials - */ -exports.combineChannelCredentials = function(channel_credential) { - var current = channel_credential; - for (var i = 1; i < arguments.length; i++) { - current = current.compose(arguments[i]); - } - return current; -}; - -/** - * Combine any number of CallCredentials into a single CallCredentials object - * @memberof grpc.credentials - * @alias grpc.credentials.combineCallCredentials - * @param {...CallCredentials} credentials the CallCredentials to compose - * @return CallCredentials A credentials object that combines all of the input - * credentials - */ -exports.combineCallCredentials = function() { - var current = arguments[0]; - for (var i = 1; i < arguments.length; i++) { - current = current.compose(arguments[i]); - } - return current; -}; - -/** - * Create an insecure credentials object. This is used to create a channel that - * does not use SSL. This cannot be composed with anything. - * @memberof grpc.credentials - * @alias grpc.credentials.createInsecure - * @kind function - * @return {ChannelCredentials} The insecure credentials object - */ -exports.createInsecure = ChannelCredentials.createInsecure; diff --git a/src/node/src/grpc_extension.js b/src/node/src/grpc_extension.js deleted file mode 100644 index af43eacad2d..00000000000 --- a/src/node/src/grpc_extension.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * @license - * 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. - * - */ - -/** - * @module - * @private - */ - -'use strict'; - -var binary = require('node-pre-gyp/lib/pre-binding'); -var path = require('path'); -var binding_path = - binary.find(path.resolve(path.join(__dirname, '../../../package.json'))); -var binding = require(binding_path); - -module.exports = binding; diff --git a/src/node/src/metadata.js b/src/node/src/metadata.js deleted file mode 100644 index 46f9e0feada..00000000000 --- a/src/node/src/metadata.js +++ /dev/null @@ -1,172 +0,0 @@ -/** - * @license - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var _ = require('lodash'); - -var grpc = require('./grpc_extension'); - -/** - * Class for storing metadata. Keys are normalized to lowercase ASCII. - * @memberof grpc - * @constructor - * @example - * var metadata = new metadata_module.Metadata(); - * metadata.set('key1', 'value1'); - * metadata.add('key1', 'value2'); - * metadata.get('key1') // returns ['value1', 'value2'] - */ -function Metadata() { - this._internal_repr = {}; -} - -function normalizeKey(key) { - key = key.toLowerCase(); - if (grpc.metadataKeyIsLegal(key)) { - return key; - } else { - throw new Error('Metadata key"' + key + '" contains illegal characters'); - } -} - -function validate(key, value) { - if (grpc.metadataKeyIsBinary(key)) { - if (!(value instanceof Buffer)) { - throw new Error('keys that end with \'-bin\' must have Buffer values'); - } - } else { - if (!_.isString(value)) { - throw new Error( - 'keys that don\'t end with \'-bin\' must have String values'); - } - if (!grpc.metadataNonbinValueIsLegal(value)) { - throw new Error('Metadata string value "' + value + - '" contains illegal characters'); - } - } -} - -/** - * Sets the given value for the given key, replacing any other values associated - * with that key. Normalizes the key. - * @param {String} key The key to set - * @param {String|Buffer} value The value to set. Must be a buffer if and only - * if the normalized key ends with '-bin' - */ -Metadata.prototype.set = function(key, value) { - key = normalizeKey(key); - validate(key, value); - this._internal_repr[key] = [value]; -}; - -/** - * Adds the given value for the given key. Normalizes the key. - * @param {String} key The key to add to. - * @param {String|Buffer} value The value to add. Must be a buffer if and only - * if the normalized key ends with '-bin' - */ -Metadata.prototype.add = function(key, value) { - key = normalizeKey(key); - validate(key, value); - if (!this._internal_repr[key]) { - this._internal_repr[key] = []; - } - this._internal_repr[key].push(value); -}; - -/** - * Remove the given key and any associated values. Normalizes the key. - * @param {String} key The key to remove - */ -Metadata.prototype.remove = function(key) { - key = normalizeKey(key); - if (Object.prototype.hasOwnProperty.call(this._internal_repr, key)) { - delete this._internal_repr[key]; - } -}; - -/** - * Gets a list of all values associated with the key. Normalizes the key. - * @param {String} key The key to get - * @return {Array.} The values associated with that key - */ -Metadata.prototype.get = function(key) { - key = normalizeKey(key); - if (Object.prototype.hasOwnProperty.call(this._internal_repr, key)) { - return this._internal_repr[key]; - } else { - return []; - } -}; - -/** - * Get a map of each key to a single associated value. This reflects the most - * common way that people will want to see metadata. - * @return {Object.} A key/value mapping of the metadata - */ -Metadata.prototype.getMap = function() { - var result = {}; - _.forOwn(this._internal_repr, function(values, key) { - if(values.length > 0) { - result[key] = values[0]; - } - }); - return result; -}; - -/** - * Clone the metadata object. - * @return {Metadata} The new cloned object - */ -Metadata.prototype.clone = function() { - var copy = new Metadata(); - _.forOwn(this._internal_repr, function(value, key) { - copy._internal_repr[key] = _.clone(value); - }); - return copy; -}; - -/** - * Gets the metadata in the format used by interal code. Intended for internal - * use only. API stability is not guaranteed. - * @private - * @return {Object.>} The metadata - */ -Metadata.prototype._getCoreRepresentation = function() { - return this._internal_repr; -}; - -/** - * Creates a Metadata object from a metadata map in the internal format. - * Intended for internal use only. API stability is not guaranteed. - * @private - * @param {Object.>} The metadata - * @return {Metadata} The new Metadata object - */ -Metadata._fromCoreRepresentation = function(metadata) { - var newMetadata = new Metadata(); - if (metadata) { - _.forOwn(metadata, function(value, key) { - newMetadata._internal_repr[key] = _.clone(value); - }); - } - return newMetadata; -}; - -module.exports = Metadata; diff --git a/src/node/src/protobuf_js_5_common.js b/src/node/src/protobuf_js_5_common.js deleted file mode 100644 index 541965fd0ab..00000000000 --- a/src/node/src/protobuf_js_5_common.js +++ /dev/null @@ -1,171 +0,0 @@ -/** - * @license - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/** - * @module - * @private - */ - -'use strict'; - -var _ = require('lodash'); -var client = require('./client'); - -/** - * Get a function that deserializes a specific type of protobuf. - * @param {function()} cls The constructor of the message type to deserialize - * @param {bool=} binaryAsBase64 Deserialize bytes fields as base64 strings - * instead of Buffers. Defaults to false - * @param {bool=} longsAsStrings Deserialize long values as strings instead of - * objects. Defaults to true - * @return {function(Buffer):cls} The deserialization function - */ -exports.deserializeCls = function deserializeCls(cls, options) { - /** - * Deserialize a buffer to a message object - * @param {Buffer} arg_buf The buffer to deserialize - * @return {cls} The resulting object - */ - return function deserialize(arg_buf) { - // Convert to a native object with binary fields as Buffers (first argument) - // and longs as strings (second argument) - return cls.decode(arg_buf).toRaw(options.binaryAsBase64, - options.longsAsStrings); - }; -}; - -var deserializeCls = exports.deserializeCls; - -/** - * Get a function that serializes objects to a buffer by protobuf class. - * @param {function()} Cls The constructor of the message type to serialize - * @return {function(Cls):Buffer} The serialization function - */ -exports.serializeCls = function serializeCls(Cls) { - /** - * Serialize an object to a Buffer - * @param {Object} arg The object to serialize - * @return {Buffer} The serialized object - */ - return function serialize(arg) { - return new Buffer(new Cls(arg).encode().toBuffer()); - }; -}; - -var serializeCls = exports.serializeCls; - -/** - * Get the fully qualified (dotted) name of a ProtoBuf.Reflect value. - * @param {ProtoBuf.Reflect.Namespace} value The value to get the name of - * @return {string} The fully qualified name of the value - */ -exports.fullyQualifiedName = function fullyQualifiedName(value) { - if (value === null || value === undefined) { - return ''; - } - var name = value.name; - var parent_name = fullyQualifiedName(value.parent); - if (parent_name !== '') { - name = parent_name + '.' + name; - } - return name; -}; - -var fullyQualifiedName = exports.fullyQualifiedName; - -/** - * Return a map from method names to method attributes for the service. - * @param {ProtoBuf.Reflect.Service} service The service to get attributes for - * @param {Object=} options Options to apply to these attributes - * @return {Object} The attributes map - */ -exports.getProtobufServiceAttrs = function getProtobufServiceAttrs(service, - options) { - var prefix = '/' + fullyQualifiedName(service) + '/'; - var binaryAsBase64, longsAsStrings; - if (options) { - binaryAsBase64 = options.binaryAsBase64; - longsAsStrings = options.longsAsStrings; - } - /* This slightly awkward construction is used to make sure we only use - lodash@3.10.1-compatible functions. A previous version used - _.fromPairs, which would be cleaner, but was introduced in lodash - version 4 */ - return _.zipObject(_.map(service.children, function(method) { - return _.camelCase(method.name); - }), _.map(service.children, function(method) { - return { - originalName: method.name, - path: prefix + method.name, - requestStream: method.requestStream, - responseStream: method.responseStream, - requestType: method.resolvedRequestType, - responseType: method.resolvedResponseType, - requestSerialize: serializeCls(method.resolvedRequestType.build()), - requestDeserialize: deserializeCls(method.resolvedRequestType.build(), - options), - responseSerialize: serializeCls(method.resolvedResponseType.build()), - responseDeserialize: deserializeCls(method.resolvedResponseType.build(), - options) - }; - })); -}; - -var getProtobufServiceAttrs = exports.getProtobufServiceAttrs; - -/** - * Load a gRPC object from an existing ProtoBuf.Reflect object. - * @param {ProtoBuf.Reflect.Namespace} value The ProtoBuf object to load. - * @param {Object=} options Options to apply to the loaded object - * @return {Object} The resulting gRPC object - */ -exports.loadObject = function loadObject(value, options) { - var result = {}; - if (!value) { - return value; - } - if (value.hasOwnProperty('ns')) { - return loadObject(value.ns, options); - } - if (value.className === 'Namespace') { - _.each(value.children, function(child) { - result[child.name] = loadObject(child, options); - }); - return result; - } else if (value.className === 'Service') { - return client.makeClientConstructor(getProtobufServiceAttrs(value, options), - options); - } else if (value.className === 'Message' || value.className === 'Enum') { - return value.build(); - } else { - return value; - } -}; - -/** - * The primary purpose of this method is to distinguish between reflection - * objects from different versions of ProtoBuf.js. This is just a heuristic, - * checking for properties that are (currently) specific to this version of - * ProtoBuf.js - * @param {Object} obj The object to check - * @return {boolean} Whether the object appears to be a Protobuf.js 5 - * ReflectionObject - */ -exports.isProbablyProtobufJs5 = function isProbablyProtobufJs5(obj) { - return _.isArray(obj.children) && (typeof obj.build === 'function'); -}; diff --git a/src/node/src/protobuf_js_6_common.js b/src/node/src/protobuf_js_6_common.js deleted file mode 100644 index 0f072516777..00000000000 --- a/src/node/src/protobuf_js_6_common.js +++ /dev/null @@ -1,160 +0,0 @@ -/** - * @license - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/** - * @module - * @private - */ - -'use strict'; - -var _ = require('lodash'); -var client = require('./client'); - -/** - * Get a function that deserializes a specific type of protobuf. - * @param {function()} cls The constructor of the message type to deserialize - * @param {bool=} binaryAsBase64 Deserialize bytes fields as base64 strings - * instead of Buffers. Defaults to false - * @param {bool=} longsAsStrings Deserialize long values as strings instead of - * objects. Defaults to true - * @return {function(Buffer):cls} The deserialization function - */ -exports.deserializeCls = function deserializeCls(cls, options) { - var conversion_options = { - defaults: true, - bytes: options.binaryAsBase64 ? String : Buffer, - longs: options.longsAsStrings ? String : null, - enums: options.enumsAsStrings ? String : null, - oneofs: true - }; - /** - * Deserialize a buffer to a message object - * @param {Buffer} arg_buf The buffer to deserialize - * @return {cls} The resulting object - */ - return function deserialize(arg_buf) { - return cls.toObject(cls.decode(arg_buf), conversion_options); - }; -}; - -var deserializeCls = exports.deserializeCls; - -/** - * Get a function that serializes objects to a buffer by protobuf class. - * @param {function()} Cls The constructor of the message type to serialize - * @return {function(Cls):Buffer} The serialization function - */ -exports.serializeCls = function serializeCls(cls) { - /** - * Serialize an object to a Buffer - * @param {Object} arg The object to serialize - * @return {Buffer} The serialized object - */ - return function serialize(arg) { - var message = cls.fromObject(arg); - return cls.encode(message).finish(); - }; -}; - -var serializeCls = exports.serializeCls; - -/** - * Get the fully qualified (dotted) name of a ProtoBuf.Reflect value. - * @param {ProtoBuf.ReflectionObject} value The value to get the name of - * @return {string} The fully qualified name of the value - */ -exports.fullyQualifiedName = function fullyQualifiedName(value) { - if (value === null || value === undefined) { - return ''; - } - var name = value.name; - var parent_fqn = fullyQualifiedName(value.parent); - if (parent_fqn !== '') { - name = parent_fqn + '.' + name; - } - return name; -}; - -var fullyQualifiedName = exports.fullyQualifiedName; - -/** - * Return a map from method names to method attributes for the service. - * @param {ProtoBuf.Service} service The service to get attributes for - * @param {Object=} options Options to apply to these attributes - * @return {Object} The attributes map - */ -exports.getProtobufServiceAttrs = function getProtobufServiceAttrs(service, - options) { - var prefix = '/' + fullyQualifiedName(service) + '/'; - service.resolveAll(); - return _.zipObject(_.map(service.methods, function(method) { - return _.camelCase(method.name); - }), _.map(service.methods, function(method) { - return { - originalName: method.name, - path: prefix + method.name, - requestStream: !!method.requestStream, - responseStream: !!method.responseStream, - requestType: method.resolvedRequestType, - responseType: method.resolvedResponseType, - requestSerialize: serializeCls(method.resolvedRequestType), - requestDeserialize: deserializeCls(method.resolvedRequestType, options), - responseSerialize: serializeCls(method.resolvedResponseType), - responseDeserialize: deserializeCls(method.resolvedResponseType, options) - }; - })); -}; - -var getProtobufServiceAttrs = exports.getProtobufServiceAttrs; - -exports.loadObject = function loadObject(value, options) { - var result = {}; - if (!value) { - return value; - } - if (value.hasOwnProperty('methods')) { - // It's a service object - var service_attrs = getProtobufServiceAttrs(value, options); - return client.makeClientConstructor(service_attrs); - } - - if (value.hasOwnProperty('nested')) { - // It's a namespace or root object - _.each(value.nested, function(nested, name) { - result[name] = loadObject(nested, options); - }); - return result; - } - - // Otherwise, it's not something we need to change - return value; -}; - -/** - * The primary purpose of this method is to distinguish between reflection - * objects from different versions of ProtoBuf.js. This is just a heuristic, - * checking for properties that are (currently) specific to this version of - * ProtoBuf.js - * @param {Object} obj The object to check - * @return {boolean} Whether the object appears to be a Protobuf.js 6 - * ReflectionObject - */ -exports.isProbablyProtobufJs6 = function isProbablyProtobufJs6(obj) { - return (typeof obj.root === 'object') && (typeof obj.resolve === 'function'); -}; diff --git a/src/node/src/server.js b/src/node/src/server.js deleted file mode 100644 index 8b7c0b68627..00000000000 --- a/src/node/src/server.js +++ /dev/null @@ -1,965 +0,0 @@ -/** - * @license - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var _ = require('lodash'); - -var grpc = require('./grpc_extension'); - -var common = require('./common'); - -var Metadata = require('./metadata'); - -var constants = require('./constants'); - -var stream = require('stream'); - -var Readable = stream.Readable; -var Writable = stream.Writable; -var Duplex = stream.Duplex; -var util = require('util'); - -var EventEmitter = require('events').EventEmitter; - -/** - * Handle an error on a call by sending it as a status - * @private - * @param {grpc.internal~Call} call The call to send the error on - * @param {(Object|Error)} error The error object - */ -function handleError(call, error) { - var statusMetadata = new Metadata(); - var status = { - code: constants.status.UNKNOWN, - details: 'Unknown Error' - }; - if (error.hasOwnProperty('message')) { - status.details = error.message; - } - if (error.hasOwnProperty('code')) { - status.code = error.code; - if (error.hasOwnProperty('details')) { - status.details = error.details; - } - } - if (error.hasOwnProperty('metadata')) { - statusMetadata = error.metadata; - } - status.metadata = statusMetadata._getCoreRepresentation(); - var error_batch = {}; - if (!call.metadataSent) { - error_batch[grpc.opType.SEND_INITIAL_METADATA] = - (new Metadata())._getCoreRepresentation(); - } - error_batch[grpc.opType.SEND_STATUS_FROM_SERVER] = status; - call.startBatch(error_batch, function(){}); -} - -/** - * Send a response to a unary or client streaming call. - * @private - * @param {grpc.Call} call The call to respond on - * @param {*} value The value to respond with - * @param {grpc~serialize} serialize Serialization function for the - * response - * @param {grpc.Metadata=} metadata Optional trailing metadata to send with - * status - * @param {number=} [flags=0] Flags for modifying how the message is sent. - */ -function sendUnaryResponse(call, value, serialize, metadata, flags) { - var end_batch = {}; - var statusMetadata = new Metadata(); - var status = { - code: constants.status.OK, - details: 'OK' - }; - if (metadata) { - statusMetadata = metadata; - } - var message; - try { - message = serialize(value); - } catch (e) { - e.code = constants.status.INTERNAL; - handleError(call, e); - return; - } - status.metadata = statusMetadata._getCoreRepresentation(); - if (!call.metadataSent) { - end_batch[grpc.opType.SEND_INITIAL_METADATA] = - (new Metadata())._getCoreRepresentation(); - call.metadataSent = true; - } - message.grpcWriteFlags = flags; - end_batch[grpc.opType.SEND_MESSAGE] = message; - end_batch[grpc.opType.SEND_STATUS_FROM_SERVER] = status; - call.startBatch(end_batch, function (){}); -} - -/** - * Initialize a writable stream. This is used for both the writable and duplex - * stream constructors. - * @private - * @param {Writable} stream The stream to set up - * @param {function(*):Buffer=} Serialization function for responses - */ -function setUpWritable(stream, serialize) { - stream.finished = false; - stream.status = { - code : constants.status.OK, - details : 'OK', - metadata : new Metadata() - }; - stream.serialize = common.wrapIgnoreNull(serialize); - function sendStatus() { - var batch = {}; - if (!stream.call.metadataSent) { - stream.call.metadataSent = true; - batch[grpc.opType.SEND_INITIAL_METADATA] = - (new Metadata())._getCoreRepresentation(); - } - - if (stream.status.metadata) { - stream.status.metadata = stream.status.metadata._getCoreRepresentation(); - } - batch[grpc.opType.SEND_STATUS_FROM_SERVER] = stream.status; - stream.call.startBatch(batch, function(){}); - } - stream.on('finish', sendStatus); - /** - * Set the pending status to a given error status. If the error does not have - * code or details properties, the code will be set to grpc.status.UNKNOWN - * and the details will be set to 'Unknown Error'. - * @param {Error} err The error object - */ - function setStatus(err) { - var code = constants.status.UNKNOWN; - var details = 'Unknown Error'; - var metadata = new Metadata(); - if (err.hasOwnProperty('message')) { - details = err.message; - } - if (err.hasOwnProperty('code')) { - code = err.code; - if (err.hasOwnProperty('details')) { - details = err.details; - } - } - if (err.hasOwnProperty('metadata')) { - metadata = err.metadata; - } - stream.status = {code: code, details: details, metadata: metadata}; - } - /** - * Terminate the call. This includes indicating that reads are done, draining - * all pending writes, and sending the given error as a status - * @param {Error} err The error object - * @this GrpcServerStream - */ - function terminateCall(err) { - // Drain readable data - setStatus(err); - stream.end(); - } - stream.on('error', terminateCall); - /** - * Override of Writable#end method that allows for sending metadata with a - * success status. - * @param {Metadata=} metadata Metadata to send with the status - */ - stream.end = function(metadata) { - if (metadata) { - stream.status.metadata = metadata; - } - Writable.prototype.end.call(this); - }; -} - -/** - * Initialize a readable stream. This is used for both the readable and duplex - * stream constructors. - * @private - * @param {Readable} stream The stream to initialize - * @param {grpc~deserialize} deserialize Deserialization function for - * incoming data. - */ -function setUpReadable(stream, deserialize) { - stream.deserialize = common.wrapIgnoreNull(deserialize); - stream.finished = false; - stream.reading = false; - - stream.terminate = function() { - stream.finished = true; - stream.on('data', function() {}); - }; - - stream.on('cancelled', function() { - stream.terminate(); - }); -} - -/** - * Emitted when the call has been cancelled. After this has been emitted, the - * call's `cancelled` property will be set to `true`. - * @event grpc~ServerUnaryCall~cancelled - */ - -util.inherits(ServerUnaryCall, EventEmitter); - -/** - * An EventEmitter. Used for unary calls. - * @constructor grpc~ServerUnaryCall - * @extends external:EventEmitter - * @param {grpc.internal~Call} call The call object associated with the request - * @param {grpc.Metadata} metadata The request metadata from the client - */ -function ServerUnaryCall(call, metadata) { - EventEmitter.call(this); - this.call = call; - /** - * Indicates if the call has been cancelled - * @member {boolean} grpc~ServerUnaryCall#cancelled - */ - this.cancelled = false; - /** - * The request metadata from the client - * @member {grpc.Metadata} grpc~ServerUnaryCall#metadata - */ - this.metadata = metadata; - /** - * The request message from the client - * @member {*} grpc~ServerUnaryCall#request - */ - this.request = undefined; -} - -/** - * Emitted when the call has been cancelled. After this has been emitted, the - * call's `cancelled` property will be set to `true`. - * @event grpc~ServerWritableStream~cancelled - */ - -util.inherits(ServerWritableStream, Writable); - -/** - * A stream that the server can write to. Used for calls that are streaming from - * the server side. - * @constructor grpc~ServerWritableStream - * @extends external:Writable - * @borrows grpc~ServerUnaryCall#sendMetadata as - * grpc~ServerWritableStream#sendMetadata - * @borrows grpc~ServerUnaryCall#getPeer as grpc~ServerWritableStream#getPeer - * @param {grpc.internal~Call} call The call object to send data with - * @param {grpc.Metadata} metadata The request metadata from the client - * @param {grpc~serialize} serialize Serialization function for writes - */ -function ServerWritableStream(call, metadata, serialize) { - Writable.call(this, {objectMode: true}); - this.call = call; - - this.finished = false; - setUpWritable(this, serialize); - /** - * Indicates if the call has been cancelled - * @member {boolean} grpc~ServerWritableStream#cancelled - */ - this.cancelled = false; - /** - * The request metadata from the client - * @member {grpc.Metadata} grpc~ServerWritableStream#metadata - */ - this.metadata = metadata; - /** - * The request message from the client - * @member {*} grpc~ServerWritableStream#request - */ - this.request = undefined; -} - -/** - * Start writing a chunk of data. This is an implementation of a method required - * for implementing stream.Writable. - * @private - * @param {Buffer} chunk The chunk of data to write - * @param {string} encoding Used to pass write flags - * @param {function(Error=)} callback Callback to indicate that the write is - * complete - */ -function _write(chunk, encoding, callback) { - /* jshint validthis: true */ - var batch = {}; - var self = this; - var message; - try { - message = this.serialize(chunk); - } catch (e) { - e.code = constants.status.INTERNAL; - callback(e); - return; - } - if (!this.call.metadataSent) { - batch[grpc.opType.SEND_INITIAL_METADATA] = - (new Metadata())._getCoreRepresentation(); - this.call.metadataSent = true; - } - if (_.isFinite(encoding)) { - /* Attach the encoding if it is a finite number. This is the closest we - * can get to checking that it is valid flags */ - message.grpcWriteFlags = encoding; - } - batch[grpc.opType.SEND_MESSAGE] = message; - this.call.startBatch(batch, function(err, value) { - if (err) { - self.emit('error', err); - return; - } - callback(); - }); -} - -ServerWritableStream.prototype._write = _write; - -/** - * Emitted when the call has been cancelled. After this has been emitted, the - * call's `cancelled` property will be set to `true`. - * @event grpc~ServerReadableStream~cancelled - */ - -util.inherits(ServerReadableStream, Readable); - -/** - * A stream that the server can read from. Used for calls that are streaming - * from the client side. - * @constructor grpc~ServerReadableStream - * @extends external:Readable - * @borrows grpc~ServerUnaryCall#sendMetadata as - * grpc~ServerReadableStream#sendMetadata - * @borrows grpc~ServerUnaryCall#getPeer as grpc~ServerReadableStream#getPeer - * @param {grpc.internal~Call} call The call object to read data with - * @param {grpc.Metadata} metadata The request metadata from the client - * @param {grpc~deserialize} deserialize Deserialization function for reads - */ -function ServerReadableStream(call, metadata, deserialize) { - Readable.call(this, {objectMode: true}); - this.call = call; - setUpReadable(this, deserialize); - /** - * Indicates if the call has been cancelled - * @member {boolean} grpc~ServerReadableStream#cancelled - */ - this.cancelled = false; - /** - * The request metadata from the client - * @member {grpc.Metadata} grpc~ServerReadableStream#metadata - */ - this.metadata = metadata; -} - -/** - * Start reading from the gRPC data source. This is an implementation of a - * method required for implementing stream.Readable - * @access private - * @param {number} size Ignored - */ -function _read(size) { - /* jshint validthis: true */ - var self = this; - /** - * Callback to be called when a READ event is received. Pushes the data onto - * the read queue and starts reading again if applicable - * @param {grpc.Event} event READ event object - */ - function readCallback(err, event) { - if (err) { - self.terminate(); - return; - } - if (self.finished) { - self.push(null); - return; - } - var data = event.read; - var deserialized; - try { - deserialized = self.deserialize(data); - } catch (e) { - e.code = constants.status.INTERNAL; - self.emit('error', e); - return; - } - if (self.push(deserialized) && data !== null) { - var read_batch = {}; - read_batch[grpc.opType.RECV_MESSAGE] = true; - self.call.startBatch(read_batch, readCallback); - } else { - self.reading = false; - } - } - if (self.finished) { - self.push(null); - } else { - if (!self.reading) { - self.reading = true; - var batch = {}; - batch[grpc.opType.RECV_MESSAGE] = true; - self.call.startBatch(batch, readCallback); - } - } -} - -ServerReadableStream.prototype._read = _read; - -/** - * Emitted when the call has been cancelled. After this has been emitted, the - * call's `cancelled` property will be set to `true`. - * @event grpc~ServerDuplexStream~cancelled - */ - -util.inherits(ServerDuplexStream, Duplex); - -/** - * A stream that the server can read from or write to. Used for calls with - * duplex streaming. - * @constructor grpc~ServerDuplexStream - * @extends external:Duplex - * @borrows grpc~ServerUnaryCall#sendMetadata as - * grpc~ServerDuplexStream#sendMetadata - * @borrows grpc~ServerUnaryCall#getPeer as grpc~ServerDuplexStream#getPeer - * @param {grpc.internal~Call} call Call object to proxy - * @param {grpc.Metadata} metadata The request metadata from the client - * @param {grpc~serialize} serialize Serialization function for requests - * @param {grpc~deserialize} deserialize Deserialization function for - * responses - */ -function ServerDuplexStream(call, metadata, serialize, deserialize) { - Duplex.call(this, {objectMode: true}); - this.call = call; - setUpWritable(this, serialize); - setUpReadable(this, deserialize); - /** - * Indicates if the call has been cancelled - * @member {boolean} grpc~ServerReadableStream#cancelled - */ - this.cancelled = false; - /** - * The request metadata from the client - * @member {grpc.Metadata} grpc~ServerReadableStream#metadata - */ - this.metadata = metadata; -} - -ServerDuplexStream.prototype._read = _read; -ServerDuplexStream.prototype._write = _write; - -/** - * Send the initial metadata for a writable stream. - * @alias grpc~ServerUnaryCall#sendMetadata - * @param {Metadata} responseMetadata Metadata to send - */ -function sendMetadata(responseMetadata) { - /* jshint validthis: true */ - var self = this; - if (!this.call.metadataSent) { - this.call.metadataSent = true; - var batch = {}; - batch[grpc.opType.SEND_INITIAL_METADATA] = - responseMetadata._getCoreRepresentation(); - this.call.startBatch(batch, function(err) { - if (err) { - self.emit('error', err); - return; - } - }); - } -} - -ServerUnaryCall.prototype.sendMetadata = sendMetadata; -ServerWritableStream.prototype.sendMetadata = sendMetadata; -ServerReadableStream.prototype.sendMetadata = sendMetadata; -ServerDuplexStream.prototype.sendMetadata = sendMetadata; - -/** - * Get the endpoint this call/stream is connected to. - * @alias grpc~ServerUnaryCall#getPeer - * @return {string} The URI of the endpoint - */ -function getPeer() { - /* jshint validthis: true */ - return this.call.getPeer(); -} - -ServerUnaryCall.prototype.getPeer = getPeer; -ServerReadableStream.prototype.getPeer = getPeer; -ServerWritableStream.prototype.getPeer = getPeer; -ServerDuplexStream.prototype.getPeer = getPeer; - -/** - * Wait for the client to close, then emit a cancelled event if the client - * cancelled. - * @private - */ -function waitForCancel() { - /* jshint validthis: true */ - var self = this; - var cancel_batch = {}; - cancel_batch[grpc.opType.RECV_CLOSE_ON_SERVER] = true; - self.call.startBatch(cancel_batch, function(err, result) { - if (err) { - self.emit('error', err); - } - if (result.cancelled) { - self.cancelled = true; - self.emit('cancelled'); - } - }); -} - -ServerUnaryCall.prototype.waitForCancel = waitForCancel; -ServerReadableStream.prototype.waitForCancel = waitForCancel; -ServerWritableStream.prototype.waitForCancel = waitForCancel; -ServerDuplexStream.prototype.waitForCancel = waitForCancel; - -/** - * Callback function passed to server handlers that handle methods with unary - * responses. - * @callback grpc.Server~sendUnaryData - * @param {grpc~ServiceError} error An error, if the call failed - * @param {*} value The response value. Must be a valid argument to the - * `responseSerialize` method of the method that is being handled - * @param {grpc.Metadata=} trailer Trailing metadata to send, if applicable - * @param {grpc.writeFlags=} flags Flags to modify writing the response - */ - -/** - * User-provided method to handle unary requests on a server - * @callback grpc.Server~handleUnaryCall - * @param {grpc~ServerUnaryCall} call The call object - * @param {grpc.Server~sendUnaryData} callback The callback to call to respond - * to the request - */ - -/** - * Fully handle a unary call - * @private - * @param {grpc.internal~Call} call The call to handle - * @param {Object} handler Request handler object for the method that was called - * @param {grpc~Server.handleUnaryCall} handler.func The handler function - * @param {grpc~deserialize} handler.deserialize The deserialization function - * for request data - * @param {grpc~serialize} handler.serialize The serialization function for - * response data - * @param {grpc.Metadata} metadata Metadata from the client - */ -function handleUnary(call, handler, metadata) { - var emitter = new ServerUnaryCall(call, metadata); - emitter.on('error', function(error) { - handleError(call, error); - }); - emitter.waitForCancel(); - var batch = {}; - batch[grpc.opType.RECV_MESSAGE] = true; - call.startBatch(batch, function(err, result) { - if (err) { - handleError(call, err); - return; - } - try { - emitter.request = handler.deserialize(result.read); - } catch (e) { - e.code = constants.status.INTERNAL; - handleError(call, e); - return; - } - if (emitter.cancelled) { - return; - } - handler.func(emitter, function sendUnaryData(err, value, trailer, flags) { - if (err) { - if (trailer) { - err.metadata = trailer; - } - handleError(call, err); - } else { - sendUnaryResponse(call, value, handler.serialize, trailer, flags); - } - }); - }); -} - -/** - * User provided method to handle server streaming methods on the server. - * @callback grpc.Server~handleServerStreamingCall - * @param {grpc~ServerWritableStream} call The call object - */ - -/** - * Fully handle a server streaming call - * @private - * @param {grpc.internal~Call} call The call to handle - * @param {Object} handler Request handler object for the method that was called - * @param {grpc~Server.handleServerStreamingCall} handler.func The handler - * function - * @param {grpc~deserialize} handler.deserialize The deserialization function - * for request data - * @param {grpc~serialize} handler.serialize The serialization function for - * response data - * @param {grpc.Metadata} metadata Metadata from the client - */ -function handleServerStreaming(call, handler, metadata) { - var stream = new ServerWritableStream(call, metadata, handler.serialize); - stream.waitForCancel(); - var batch = {}; - batch[grpc.opType.RECV_MESSAGE] = true; - call.startBatch(batch, function(err, result) { - if (err) { - stream.emit('error', err); - return; - } - try { - stream.request = handler.deserialize(result.read); - } catch (e) { - e.code = constants.status.INTERNAL; - stream.emit('error', e); - return; - } - handler.func(stream); - }); -} - -/** - * User provided method to handle client streaming methods on the server. - * @callback grpc.Server~handleClientStreamingCall - * @param {grpc~ServerReadableStream} call The call object - * @param {grpc.Server~sendUnaryData} callback The callback to call to respond - * to the request - */ - -/** - * Fully handle a client streaming call - * @access private - * @param {grpc.internal~Call} call The call to handle - * @param {Object} handler Request handler object for the method that was called - * @param {grpc~Server.handleClientStreamingCall} handler.func The handler - * function - * @param {grpc~deserialize} handler.deserialize The deserialization function - * for request data - * @param {grpc~serialize} handler.serialize The serialization function for - * response data - * @param {grpc.Metadata} metadata Metadata from the client - */ -function handleClientStreaming(call, handler, metadata) { - var stream = new ServerReadableStream(call, metadata, handler.deserialize); - stream.on('error', function(error) { - handleError(call, error); - }); - stream.waitForCancel(); - handler.func(stream, function(err, value, trailer, flags) { - stream.terminate(); - if (err) { - if (trailer) { - err.metadata = trailer; - } - handleError(call, err); - } else { - sendUnaryResponse(call, value, handler.serialize, trailer, flags); - } - }); -} - -/** - * User provided method to handle bidirectional streaming calls on the server. - * @callback grpc.Server~handleBidiStreamingCall - * @param {grpc~ServerDuplexStream} call The call object - */ - -/** - * Fully handle a bidirectional streaming call - * @private - * @param {grpc.internal~Call} call The call to handle - * @param {Object} handler Request handler object for the method that was called - * @param {grpc~Server.handleBidiStreamingCall} handler.func The handler - * function - * @param {grpc~deserialize} handler.deserialize The deserialization function - * for request data - * @param {grpc~serialize} handler.serialize The serialization function for - * response data - * @param {Metadata} metadata Metadata from the client - */ -function handleBidiStreaming(call, handler, metadata) { - var stream = new ServerDuplexStream(call, metadata, handler.serialize, - handler.deserialize); - stream.waitForCancel(); - handler.func(stream); -} - -var streamHandlers = { - unary: handleUnary, - server_stream: handleServerStreaming, - client_stream: handleClientStreaming, - bidi: handleBidiStreaming -}; - -/** - * Constructs a server object that stores request handlers and delegates - * incoming requests to those handlers - * @memberof grpc - * @constructor - * @param {Object=} options Options that should be passed to the internal server - * implementation - * @example - * var server = new grpc.Server(); - * server.addProtoService(protobuf_service_descriptor, service_implementation); - * server.bind('address:port', server_credential); - * server.start(); - */ -function Server(options) { - this.handlers = {}; - var server = new grpc.Server(options); - this._server = server; - this.started = false; -} - -/** - * Start the server and begin handling requests - */ -Server.prototype.start = function() { - if (this.started) { - throw new Error('Server is already running'); - } - var self = this; - this.started = true; - this._server.start(); - /** - * Handles the SERVER_RPC_NEW event. If there is a handler associated with - * the requested method, use that handler to respond to the request. Then - * wait for the next request - * @param {grpc.internal~Event} event The event to handle with tag - * SERVER_RPC_NEW - */ - function handleNewCall(err, event) { - if (err) { - return; - } - var details = event.new_call; - var call = details.call; - var method = details.method; - var metadata = Metadata._fromCoreRepresentation(details.metadata); - if (method === null) { - return; - } - self._server.requestCall(handleNewCall); - var handler; - if (self.handlers.hasOwnProperty(method)) { - handler = self.handlers[method]; - } else { - var batch = {}; - batch[grpc.opType.SEND_INITIAL_METADATA] = - (new Metadata())._getCoreRepresentation(); - batch[grpc.opType.SEND_STATUS_FROM_SERVER] = { - code: constants.status.UNIMPLEMENTED, - details: '', - metadata: {} - }; - batch[grpc.opType.RECV_CLOSE_ON_SERVER] = true; - call.startBatch(batch, function() {}); - return; - } - streamHandlers[handler.type](call, handler, metadata); - } - this._server.requestCall(handleNewCall); -}; - -/** - * Unified type for application handlers for all types of calls - * @typedef {(grpc.Server~handleUnaryCall - * |grpc.Server~handleClientStreamingCall - * |grpc.Server~handleServerStreamingCall - * |grpc.Server~handleBidiStreamingCall)} grpc.Server~handleCall - */ - -/** - * Registers a handler to handle the named method. Fails if there already is - * a handler for the given method. Returns true on success - * @param {string} name The name of the method that the provided function should - * handle/respond to. - * @param {grpc.Server~handleCall} handler Function that takes a stream of - * request values and returns a stream of response values - * @param {grpc~serialize} serialize Serialization function for responses - * @param {grpc~deserialize} deserialize Deserialization function for requests - * @param {string} type The streaming type of method that this handles - * @return {boolean} True if the handler was set. False if a handler was already - * set for that name. - */ -Server.prototype.register = function(name, handler, serialize, deserialize, - type) { - if (this.handlers.hasOwnProperty(name)) { - return false; - } - this.handlers[name] = { - func: handler, - serialize: serialize, - deserialize: deserialize, - type: type - }; - return true; -}; - -/** - * Gracefully shuts down the server. The server will stop receiving new calls, - * and any pending calls will complete. The callback will be called when all - * pending calls have completed and the server is fully shut down. This method - * is idempotent with itself and forceShutdown. - * @param {function()} callback The shutdown complete callback - */ -Server.prototype.tryShutdown = function(callback) { - this._server.tryShutdown(callback); -}; - -/** - * Forcibly shuts down the server. The server will stop receiving new calls - * and cancel all pending calls. When it returns, the server has shut down. - * This method is idempotent with itself and tryShutdown, and it will trigger - * any outstanding tryShutdown callbacks. - */ -Server.prototype.forceShutdown = function() { - this._server.forceShutdown(); -}; - -var unimplementedStatusResponse = { - code: constants.status.UNIMPLEMENTED, - details: 'The server does not implement this method' -}; - -var defaultHandler = { - unary: function(call, callback) { - callback(unimplementedStatusResponse); - }, - client_stream: function(call, callback) { - callback(unimplementedStatusResponse); - }, - server_stream: function(call) { - call.emit('error', unimplementedStatusResponse); - }, - bidi: function(call) { - call.emit('error', unimplementedStatusResponse); - } -}; - -/** - * Add a service to the server, with a corresponding implementation. - * @param {grpc~ServiceDefinition} service The service descriptor - * @param {Object} implementation Map of method - * names to method implementation for the provided service. - */ -Server.prototype.addService = function(service, implementation) { - if (!_.isObject(service) || !_.isObject(implementation)) { - throw new Error('addService requires two objects as arguments'); - } - if (_.keys(service).length === 0) { - throw new Error('Cannot add an empty service to a server'); - } - if (this.started) { - throw new Error('Can\'t add a service to a started server.'); - } - var self = this; - _.forOwn(service, function(attrs, name) { - var method_type; - if (attrs.requestStream) { - if (attrs.responseStream) { - method_type = 'bidi'; - } else { - method_type = 'client_stream'; - } - } else { - if (attrs.responseStream) { - method_type = 'server_stream'; - } else { - method_type = 'unary'; - } - } - var impl; - if (implementation[name] === undefined) { - /* Handle the case where the method is passed with the name exactly as - written in the proto file, instead of using JavaScript function - naming style */ - if (implementation[attrs.originalName] === undefined) { - common.log(constants.logVerbosity.ERROR, 'Method handler ' + name + - ' for ' + attrs.path + ' expected but not provided'); - impl = defaultHandler[method_type]; - } else { - impl = _.bind(implementation[attrs.originalName], implementation); - } - } else { - impl = _.bind(implementation[name], implementation); - } - var serialize = attrs.responseSerialize; - var deserialize = attrs.requestDeserialize; - var register_success = self.register(attrs.path, impl, serialize, - deserialize, method_type); - if (!register_success) { - throw new Error('Method handler for ' + attrs.path + - ' already provided.'); - } - }); -}; - -/** - * Add a proto service to the server, with a corresponding implementation - * @deprecated Use {@link grpc.Server#addService} instead - * @param {Protobuf.Reflect.Service} service The proto service descriptor - * @param {Object} implementation Map of method - * names to method implementation for the provided service. - */ -Server.prototype.addProtoService = util.deprecate(function(service, - implementation) { - var options; - var protobuf_js_5_common = require('./protobuf_js_5_common'); - var protobuf_js_6_common = require('./protobuf_js_6_common'); - if (protobuf_js_5_common.isProbablyProtobufJs5(service)) { - options = _.defaults(service.grpc_options, common.defaultGrpcOptions); - this.addService( - protobuf_js_5_common.getProtobufServiceAttrs(service, options), - implementation); - } else if (protobuf_js_6_common.isProbablyProtobufJs6(service)) { - options = _.defaults(service.grpc_options, common.defaultGrpcOptions); - this.addService( - protobuf_js_6_common.getProtobufServiceAttrs(service, options), - implementation); - } else { - // We assume that this is a service attributes object - this.addService(service, implementation); - } -}, 'Server#addProtoService: Use Server#addService instead'); - -/** - * Binds the server to the given port, with SSL disabled if creds is an - * insecure credentials object - * @param {string} port The port that the server should bind on, in the format - * "address:port" - * @param {grpc.ServerCredentials} creds Server credential object to be used for - * SSL. Pass an insecure credentials object for an insecure port. - */ -Server.prototype.bind = function(port, creds) { - if (this.started) { - throw new Error('Can\'t bind an already running server to an address'); - } - return this._server.addHttp2Port(port, creds); -}; - -exports.Server = Server; diff --git a/src/node/stress/metrics_client.js b/src/node/stress/metrics_client.js deleted file mode 100644 index 68506010798..00000000000 --- a/src/node/stress/metrics_client.js +++ /dev/null @@ -1,46 +0,0 @@ -/* - * - * 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. - * - */ - -'use strict'; - -var grpc = require('../../..'); - -var proto = grpc.load(__dirname + '/../../proto/grpc/testing/metrics.proto'); -var metrics = proto.grpc.testing; - -function main() { - var parseArgs = require('minimist'); - var argv = parseArgs(process.argv, { - string: 'metrics_server_address', - boolean: 'total_only' - }); - var client = new metrics.MetricsService(argv.metrics_server_address, - grpc.credentials.createInsecure()); - if (argv.total_only) { - client.getGauge({name: 'qps'}, function(err, data) { - console.log(data.name + ':', data.long_value); - }); - } else { - var call = client.getAllGauges({}); - call.on('data', function(data) { - console.log(data.name + ':', data.long_value); - }); - } -} - -main(); diff --git a/src/node/stress/metrics_server.js b/src/node/stress/metrics_server.js deleted file mode 100644 index 52ef27be5ed..00000000000 --- a/src/node/stress/metrics_server.js +++ /dev/null @@ -1,72 +0,0 @@ -/* - * - * 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. - * - */ - -'use strict'; - -var _ = require('lodash'); - -var grpc = require('../../..'); - -var proto = grpc.load(__dirname + '/../../proto/grpc/testing/metrics.proto'); -var metrics = proto.grpc.testing; - -function getGauge(call, callback) { - /* jshint validthis: true */ - // Should be bound to a MetricsServer object - var name = call.request.name; - if (this.gauges.hasOwnProperty(name)) { - callback(null, _.assign({name: name}, this.gauges[name]())); - } else { - callback({code: grpc.status.NOT_FOUND, - details: 'No such gauge: ' + name}); - } -} - -function getAllGauges(call) { - /* jshint validthis: true */ - // Should be bound to a MetricsServer object - _.each(this.gauges, function(getter, name) { - call.write(_.assign({name: name}, getter())); - }); - call.end(); -} - -function MetricsServer(port) { - var server = new grpc.Server(); - server.addService(metrics.MetricsService.service, { - getGauge: _.bind(getGauge, this), - getAllGauges: _.bind(getAllGauges, this) - }); - server.bind('localhost:' + port, grpc.ServerCredentials.createInsecure()); - this.server = server; - this.gauges = {}; -} - -MetricsServer.prototype.start = function() { - this.server.start(); -} - -MetricsServer.prototype.registerGauge = function(name, getter) { - this.gauges[name] = getter; -}; - -MetricsServer.prototype.shutdown = function() { - this.server.forceShutdown(); -}; - -module.exports = MetricsServer; diff --git a/src/node/stress/stress_client.js b/src/node/stress/stress_client.js deleted file mode 100644 index fc35d45f4d0..00000000000 --- a/src/node/stress/stress_client.js +++ /dev/null @@ -1,111 +0,0 @@ -/* - * - * 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. - * - */ - -'use strict'; - -var _ = require('lodash'); - -var grpc = require('../../..'); - -var interop_client = require('../interop/interop_client'); -var MetricsServer = require('./metrics_server'); - -var running; - -var metrics_server; - -var start_time; -var query_count; - -function makeCall(client, test_cases) { - if (!running) { - return; - } - var test_case = test_cases[_.random(test_cases.length - 1)]; - interop_client.test_cases[test_case].run(client, function() { - query_count += 1; - makeCall(client, test_cases); - }); -} - -function makeCalls(client, test_cases, parallel_calls_per_channel) { - _.times(parallel_calls_per_channel, function() { - makeCall(client, test_cases); - }); -} - -function getQps() { - var diff = process.hrtime(start_time); - var seconds = diff[0] + diff[1] / 1e9; - return {long_value: query_count / seconds}; -} - -function start(server_addresses, test_cases, channels_per_server, - parallel_calls_per_channel, metrics_port) { - running = true; - /* Assuming that we are not calling unimplemented_method. The client class - * used by empty_unary is (currently) the client class used by every interop - * test except unimplemented_method */ - var Client = interop_client.test_cases.empty_unary.Client; - /* Make channels_per_server clients connecting to each server address */ - var channels = _.flatten(_.times( - channels_per_server, _.partial(_.map, server_addresses, function(address) { - return new Client(address, grpc.credentials.createInsecure()); - }))); - metrics_server = new MetricsServer(metrics_port); - metrics_server.registerGauge('qps', getQps); - start_time = process.hrtime(); - query_count = 0; - _.each(channels, _.partial(makeCalls, _, test_cases, - parallel_calls_per_channel)); - metrics_server.start(); -} - -function stop() { - running = false; - metrics_server.shutdown(); - console.log('QPS: ' + getQps().long_value); -} - -function main() { - var parseArgs = require('minimist'); - var argv = parseArgs(process.argv, { - string: ['server_addresses', 'test_cases', 'metrics_port'], - default: {'server_addresses': 'localhost:8080', - 'test_duration_secs': -1, - 'num_channels_per_server': 1, - 'num_stubs_per_channel': 1, - 'metrics_port': '8081'} - }); - var server_addresses = argv.server_addresses.split(','); - /* Generate an array of test cases, where the number of instances of each name - * corresponds to the number given in the argument. - * e.g. 'empty_unary:1,large_unary:2' => - * ['empty_unary', 'large_unary', 'large_unary'] */ - var test_cases = _.flatten(_.map(argv.test_cases.split(','), function(value) { - var split = value.split(':'); - return _.times(split[1], _.constant(split[0])); - })); - start(server_addresses, test_cases, argv.num_channels_per_server, - argv.num_stubs_per_channel, argv.metrics_port); - if (argv.test_duration_secs > -1) { - setTimeout(stop, argv.test_duration_secs * 1000); - } -} - -main(); diff --git a/src/node/test/async_test.js b/src/node/test/async_test.js deleted file mode 100644 index b62b4149736..00000000000 --- a/src/node/test/async_test.js +++ /dev/null @@ -1,83 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var assert = require('assert'); - -var grpc = require('..'); -var math = grpc.load(__dirname + '/../../proto/math/math.proto').math; - - -/** - * Client to use to make requests to a running server. - */ -var math_client; - -/** - * Server to test against - */ -var getServer = require('./math/math_server.js'); - -var server = getServer(); - -describe('Async functionality', function() { - before(function(done) { - var port_num = server.bind('0.0.0.0:0', - grpc.ServerCredentials.createInsecure()); - server.start(); - math_client = new math.Math('localhost:' + port_num, - grpc.credentials.createInsecure()); - done(); - }); - after(function() { - grpc.closeClient(math_client); - server.forceShutdown(); - }); - it('should not hang', function(done) { - var chunkCount=0; - var call = math_client.sum(function handleSumResult(err, value) { - assert.ifError(err); - assert.equal(value.num, chunkCount); - }); - - var path = require('path'); - var fs = require('fs'); - var fileToRead = path.join(__dirname, 'numbers.txt'); - var readStream = fs.createReadStream(fileToRead); - - readStream.once('readable', function () { - readStream.on('data', function (chunk) { - call.write({'num': 1}); - chunkCount += 1; - }); - - readStream.on('end', function () { - call.end(); - }); - - readStream.on('error', function (error) { - }); - }); - - call.on('status', function checkStatus(status) { - assert.strictEqual(status.code, grpc.status.OK); - done(); - }); - }); -}); diff --git a/src/node/test/call_test.js b/src/node/test/call_test.js deleted file mode 100644 index b5246c4f31a..00000000000 --- a/src/node/test/call_test.js +++ /dev/null @@ -1,339 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var assert = require('assert'); -var grpc = require('../src/grpc_extension'); -var constants = require('../src/constants'); - -/** - * Helper function to return an absolute deadline given a relative timeout in - * seconds. - * @param {number} timeout_secs The number of seconds to wait before timing out - * @return {Date} A date timeout_secs in the future - */ -function getDeadline(timeout_secs) { - var deadline = new Date(); - deadline.setSeconds(deadline.getSeconds() + timeout_secs); - return deadline; -} - -var insecureCreds = grpc.ChannelCredentials.createInsecure(); - -describe('call', function() { - var channel; - var server; - before(function() { - server = new grpc.Server(); - var port = server.addHttp2Port('localhost:0', - grpc.ServerCredentials.createInsecure()); - server.start(); - channel = new grpc.Channel('localhost:' + port, insecureCreds); - }); - after(function() { - server.forceShutdown(); - }); - describe('constructor', function() { - it('should reject anything less than 3 arguments', function() { - assert.throws(function() { - new grpc.Call(); - }, TypeError); - assert.throws(function() { - new grpc.Call(channel); - }, TypeError); - assert.throws(function() { - new grpc.Call(channel, 'method'); - }, TypeError); - }); - it('should succeed with a Channel, a string, and a date or number', - function() { - assert.doesNotThrow(function() { - new grpc.Call(channel, 'method', new Date()); - }); - assert.doesNotThrow(function() { - new grpc.Call(channel, 'method', 0); - }); - }); - it('should accept an optional fourth string parameter', function() { - assert.doesNotThrow(function() { - new grpc.Call(channel, 'method', new Date(), 'host_override'); - }); - }); - it('should fail with a closed channel', function() { - var local_channel = new grpc.Channel('hostname', insecureCreds); - local_channel.close(); - assert.throws(function() { - new grpc.Call(channel, 'method'); - }); - }); - it('should fail with other types', function() { - assert.throws(function() { - new grpc.Call({}, 'method', 0); - }, TypeError); - assert.throws(function() { - new grpc.Call(channel, null, 0); - }, TypeError); - assert.throws(function() { - new grpc.Call(channel, 'method', 'now'); - }, TypeError); - }); - it('should succeed without the new keyword', function() { - assert.doesNotThrow(function() { - var call = grpc.Call(channel, 'method', new Date()); - assert(call instanceof grpc.Call); - }); - }); - }); - describe('deadline', function() { - it('should time out immediately with negative deadline', function(done) { - var call = new grpc.Call(channel, 'method', -Infinity); - var batch = {}; - batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true; - call.startBatch(batch, function(err, response) { - assert.strictEqual(response.status.code, - constants.status.DEADLINE_EXCEEDED); - done(); - }); - }); - }); - describe('startBatch', function() { - it('should fail without an object and a function', function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - assert.throws(function() { - call.startBatch(); - }); - assert.throws(function() { - call.startBatch({}); - }); - assert.throws(function() { - call.startBatch(null, function(){}); - }); - }); - it('should succeed with an empty object', function(done) { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - assert.doesNotThrow(function() { - call.startBatch({}, function(err) { - assert.ifError(err); - done(); - }); - }); - }); - }); - describe('startBatch with metadata', function() { - it('should succeed with a map of strings to string arrays', function(done) { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - assert.doesNotThrow(function() { - var batch = {}; - batch[grpc.opType.SEND_INITIAL_METADATA] = {'key1': ['value1'], - 'key2': ['value2']}; - call.startBatch(batch, function(err, resp) { - assert.ifError(err); - assert.deepEqual(resp, {'send_metadata': true}); - done(); - }); - }); - }); - it('should succeed with a map of strings to buffer arrays', function(done) { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - assert.doesNotThrow(function() { - var batch = {}; - batch[grpc.opType.SEND_INITIAL_METADATA] = { - 'key1-bin': [new Buffer('value1')], - 'key2-bin': [new Buffer('value2')] - }; - call.startBatch(batch, function(err, resp) { - assert.ifError(err); - assert.deepEqual(resp, {'send_metadata': true}); - done(); - }); - }); - }); - it('should fail with other parameter types', function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - assert.throws(function() { - var batch = {}; - batch[grpc.opType.SEND_INITIAL_METADATA] = undefined; - call.startBatch(batch, function(){}); - }); - assert.throws(function() { - var batch = {}; - batch[grpc.opType.SEND_INITIAL_METADATA] = null; - call.startBatch(batch, function(){}); - }, TypeError); - assert.throws(function() { - var batch = {}; - batch[grpc.opType.SEND_INITIAL_METADATA] = 'value'; - call.startBatch(batch, function(){}); - }, TypeError); - assert.throws(function() { - var batch = {}; - batch[grpc.opType.SEND_INITIAL_METADATA] = 5; - call.startBatch(batch, function(){}); - }, TypeError); - }); - }); - describe('startBatch with message', function() { - it('should fail with null argument', function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - assert.throws(function() { - var batch = {}; - batch[grpc.opType.SEND_MESSAGE] = null; - call.startBatch(batch, function(){}); - }, TypeError); - }); - it('should fail with numeric argument', function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - assert.throws(function() { - var batch = {}; - batch[grpc.opType.SEND_MESSAGE] = 5; - call.startBatch(batch, function(){}); - }, TypeError); - }); - it('should fail with string argument', function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - assert.throws(function() { - var batch = {}; - batch[grpc.opType.SEND_MESSAGE] = 'value'; - call.startBatch(batch, function(){}); - }, TypeError); - }); - }); - describe('startBatch with status', function() { - it('should fail without a code', function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - assert.throws(function() { - var batch = {}; - batch[grpc.opType.SEND_STATUS_FROM_SERVER] = { - details: 'details string', - metadata: {} - }; - call.startBatch(batch, function(){}); - }, TypeError); - }); - it('should fail without details', function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - assert.throws(function() { - var batch = {}; - batch[grpc.opType.SEND_STATUS_FROM_SERVER] = { - code: 0, - metadata: {} - }; - call.startBatch(batch, function(){}); - }, TypeError); - }); - it('should fail without metadata', function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - assert.throws(function() { - var batch = {}; - batch[grpc.opType.SEND_STATUS_FROM_SERVER] = { - code: 0, - details: 'details string' - }; - call.startBatch(batch, function(){}); - }, TypeError); - }); - it('should fail with incorrectly typed code argument', function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - assert.throws(function() { - var batch = {}; - batch[grpc.opType.SEND_STATUS_FROM_SERVER] = { - code: 'code string', - details: 'details string', - metadata: {} - }; - call.startBatch(batch, function(){}); - }, TypeError); - }); - it('should fail with incorrectly typed details argument', function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - assert.throws(function() { - var batch = {}; - batch[grpc.opType.SEND_STATUS_FROM_SERVER] = { - code: 0, - details: 5, - metadata: {} - }; - call.startBatch(batch, function(){}); - }, TypeError); - }); - it('should fail with incorrectly typed metadata argument', function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - assert.throws(function() { - var batch = {}; - batch[grpc.opType.SEND_STATUS_FROM_SERVER] = { - code: 0, - details: 'details string', - metadata: 'abc' - }; - call.startBatch(batch, function(){}); - }, TypeError); - }); - }); - describe('cancel', function() { - it('should succeed', function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - assert.doesNotThrow(function() { - call.cancel(); - }); - }); - }); - describe('cancelWithStatus', function() { - it('should reject anything other than an integer and a string', function() { - assert.doesNotThrow(function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - call.cancelWithStatus(1, 'details'); - }); - assert.throws(function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - call.cancelWithStatus(); - }); - assert.throws(function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - call.cancelWithStatus(''); - }); - assert.throws(function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - call.cancelWithStatus(5, {}); - }); - }); - it('should reject the OK status code', function() { - assert.throws(function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - call.cancelWithStatus(0, 'details'); - }); - }); - it('should result in the call ending with a status', function(done) { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - var batch = {}; - batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true; - call.startBatch(batch, function(err, response) { - assert.strictEqual(response.status.code, 5); - assert.strictEqual(response.status.details, 'details'); - done(); - }); - call.cancelWithStatus(5, 'details'); - }); - }); - describe('getPeer', function() { - it('should return a string', function() { - var call = new grpc.Call(channel, 'method', getDeadline(1)); - assert.strictEqual(typeof call.getPeer(), 'string'); - }); - }); -}); diff --git a/src/node/test/channel_test.js b/src/node/test/channel_test.js deleted file mode 100644 index 373c5ac3c82..00000000000 --- a/src/node/test/channel_test.js +++ /dev/null @@ -1,181 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var assert = require('assert'); -var grpc = require('../src/grpc_extension'); - -/** - * This is used for testing functions with multiple asynchronous calls that - * can happen in different orders. This should be passed the number of async - * function invocations that can occur last, and each of those should call this - * function's return value - * @param {function()} done The function that should be called when a test is - * complete. - * @param {number} count The number of calls to the resulting function if the - * test passes. - * @return {function()} The function that should be called at the end of each - * sequence of asynchronous functions. - */ -function multiDone(done, count) { - return function() { - count -= 1; - if (count <= 0) { - done(); - } - }; -} -var insecureCreds = grpc.ChannelCredentials.createInsecure(); - -describe('channel', function() { - describe('constructor', function() { - it('should require a string for the first argument', function() { - assert.doesNotThrow(function() { - new grpc.Channel('hostname', insecureCreds); - }); - assert.throws(function() { - new grpc.Channel(); - }, TypeError); - assert.throws(function() { - new grpc.Channel(5); - }); - }); - it('should require a credential for the second argument', function() { - assert.doesNotThrow(function() { - new grpc.Channel('hostname', insecureCreds); - }); - assert.throws(function() { - new grpc.Channel('hostname', 5); - }); - assert.throws(function() { - new grpc.Channel('hostname'); - }); - }); - it('should accept an object for the third argument', function() { - assert.doesNotThrow(function() { - new grpc.Channel('hostname', insecureCreds, {}); - }); - assert.throws(function() { - new grpc.Channel('hostname', insecureCreds, 'abc'); - }); - }); - it('should only accept objects with string or int values', function() { - assert.doesNotThrow(function() { - new grpc.Channel('hostname', insecureCreds,{'key' : 'value'}); - }); - assert.doesNotThrow(function() { - new grpc.Channel('hostname', insecureCreds, {'key' : 5}); - }); - assert.throws(function() { - new grpc.Channel('hostname', insecureCreds, {'key' : null}); - }); - assert.throws(function() { - new grpc.Channel('hostname', insecureCreds, {'key' : new Date()}); - }); - }); - it('should succeed without the new keyword', function() { - assert.doesNotThrow(function() { - var channel = grpc.Channel('hostname', insecureCreds); - assert(channel instanceof grpc.Channel); - }); - }); - }); - describe('close', function() { - var channel; - beforeEach(function() { - channel = new grpc.Channel('hostname', insecureCreds, {}); - }); - it('should succeed silently', function() { - assert.doesNotThrow(function() { - channel.close(); - }); - }); - it('should be idempotent', function() { - assert.doesNotThrow(function() { - channel.close(); - channel.close(); - }); - }); - }); - describe('getTarget', function() { - var channel; - beforeEach(function() { - channel = new grpc.Channel('hostname', insecureCreds, {}); - }); - it('should return a string', function() { - assert.strictEqual(typeof channel.getTarget(), 'string'); - }); - }); - describe('getConnectivityState', function() { - var channel; - beforeEach(function() { - channel = new grpc.Channel('hostname', insecureCreds, {}); - }); - it('should return IDLE for a new channel', function() { - assert.strictEqual(channel.getConnectivityState(), - grpc.connectivityState.IDLE); - }); - }); - describe('watchConnectivityState', function() { - var channel; - beforeEach(function() { - channel = new grpc.Channel('localhost', insecureCreds, {}); - }); - afterEach(function() { - channel.close(); - }); - it('should time out if called alone', function(done) { - var old_state = channel.getConnectivityState(); - var deadline = new Date(); - deadline.setSeconds(deadline.getSeconds() + 1); - channel.watchConnectivityState(old_state, deadline, function(err, value) { - assert(err); - done(); - }); - }); - it('should complete if a connection attempt is forced', function(done) { - var old_state = channel.getConnectivityState(); - var deadline = new Date(); - deadline.setSeconds(deadline.getSeconds() + 1); - channel.watchConnectivityState(old_state, deadline, function(err, value) { - assert.ifError(err); - assert.notEqual(value.new_state, old_state); - done(); - }); - channel.getConnectivityState(true); - }); - it('should complete twice if called twice', function(done) { - done = multiDone(done, 2); - var old_state = channel.getConnectivityState(); - var deadline = new Date(); - deadline.setSeconds(deadline.getSeconds() + 1); - channel.watchConnectivityState(old_state, deadline, function(err, value) { - assert.ifError(err); - assert.notEqual(value.new_state, old_state); - done(); - }); - channel.watchConnectivityState(old_state, deadline, function(err, value) { - assert.ifError(err); - assert.notEqual(value.new_state, old_state); - done(); - }); - channel.getConnectivityState(true); - }); - }); -}); diff --git a/src/node/test/common_test.js b/src/node/test/common_test.js deleted file mode 100644 index d50c1a2761d..00000000000 --- a/src/node/test/common_test.js +++ /dev/null @@ -1,190 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var assert = require('assert'); -var _ = require('lodash'); - -var common = require('../src/common'); -var protobuf_js_5_common = require('../src/protobuf_js_5_common'); - -var serializeCls = protobuf_js_5_common.serializeCls; -var deserializeCls = protobuf_js_5_common.deserializeCls; - -var ProtoBuf = require('protobufjs'); - -var messages_proto = ProtoBuf.loadProtoFile( - __dirname + '/test_messages.proto').build(); - -var default_options = common.defaultGrpcOptions; - -describe('Proto message long int serialize and deserialize', function() { - var longSerialize = serializeCls(messages_proto.LongValues); - var longDeserialize = deserializeCls(messages_proto.LongValues, - default_options); - var pos_value = '314159265358979'; - var neg_value = '-27182818284590'; - it('should preserve positive int64 values', function() { - var serialized = longSerialize({int_64: pos_value}); - assert.strictEqual(longDeserialize(serialized).int_64.toString(), - pos_value); - }); - it('should preserve negative int64 values', function() { - var serialized = longSerialize({int_64: neg_value}); - assert.strictEqual(longDeserialize(serialized).int_64.toString(), - neg_value); - }); - it('should preserve uint64 values', function() { - var serialized = longSerialize({uint_64: pos_value}); - assert.strictEqual(longDeserialize(serialized).uint_64.toString(), - pos_value); - }); - it('should preserve positive sint64 values', function() { - var serialized = longSerialize({sint_64: pos_value}); - assert.strictEqual(longDeserialize(serialized).sint_64.toString(), - pos_value); - }); - it('should preserve negative sint64 values', function() { - var serialized = longSerialize({sint_64: neg_value}); - assert.strictEqual(longDeserialize(serialized).sint_64.toString(), - neg_value); - }); - it('should preserve fixed64 values', function() { - var serialized = longSerialize({fixed_64: pos_value}); - assert.strictEqual(longDeserialize(serialized).fixed_64.toString(), - pos_value); - }); - it('should preserve positive sfixed64 values', function() { - var serialized = longSerialize({sfixed_64: pos_value}); - assert.strictEqual(longDeserialize(serialized).sfixed_64.toString(), - pos_value); - }); - it('should preserve negative sfixed64 values', function() { - var serialized = longSerialize({sfixed_64: neg_value}); - assert.strictEqual(longDeserialize(serialized).sfixed_64.toString(), - neg_value); - }); - it('should deserialize as a number with the right option set', function() { - var num_options = _.defaults({longsAsStrings: false}, default_options); - var longNumDeserialize = deserializeCls(messages_proto.LongValues, - num_options); - var serialized = longSerialize({int_64: pos_value}); - assert.strictEqual(typeof longDeserialize(serialized).int_64, 'string'); - /* With the longsAsStrings option disabled, long values are represented as - * objects with 3 keys: low, high, and unsigned */ - assert.strictEqual(typeof longNumDeserialize(serialized).int_64, 'object'); - }); -}); -describe('Proto message bytes serialize and deserialize', function() { - var sequenceSerialize = serializeCls(messages_proto.SequenceValues); - var sequenceDeserialize = deserializeCls( - messages_proto.SequenceValues, default_options); - var b64_options = _.defaults({binaryAsBase64: true}, default_options); - var sequenceBase64Deserialize = deserializeCls( - messages_proto.SequenceValues, b64_options); - var buffer_val = new Buffer([0x69, 0xb7]); - var base64_val = 'abc='; - it('should preserve a buffer', function() { - var serialized = sequenceSerialize({bytes_field: buffer_val}); - var deserialized = sequenceDeserialize(serialized); - assert.strictEqual(deserialized.bytes_field.compare(buffer_val), 0); - }); - it('should accept base64 encoded strings', function() { - var serialized = sequenceSerialize({bytes_field: base64_val}); - var deserialized = sequenceDeserialize(serialized); - assert.strictEqual(deserialized.bytes_field.compare(buffer_val), 0); - }); - it('should output base64 encoded strings with an option set', function() { - var serialized = sequenceSerialize({bytes_field: base64_val}); - var deserialized = sequenceBase64Deserialize(serialized); - assert.strictEqual(deserialized.bytes_field, base64_val); - }); - it('should serialize a repeated field as packed by default', function() { - var expected_serialize = new Buffer([0x12, 0x01, 0x0a]); - var serialized = sequenceSerialize({repeated_field: [10]}); - assert.strictEqual(expected_serialize.compare(serialized), 0); - }); - // This tests a bug that was fixed in Protobuf.js 6 - it.skip('should deserialize packed or unpacked repeated', function() { - var expectedDeserialize = { - bytes_field: new Buffer(''), - repeated_field: [10] - }; - var packedSerialized = new Buffer([0x12, 0x01, 0x0a]); - var unpackedSerialized = new Buffer([0x10, 0x0a]); - var packedDeserialized; - var unpackedDeserialized; - assert.doesNotThrow(function() { - packedDeserialized = sequenceDeserialize(packedSerialized); - }); - assert.doesNotThrow(function() { - unpackedDeserialized = sequenceDeserialize(unpackedSerialized); - }); - assert.deepEqual(packedDeserialized, expectedDeserialize); - assert.deepEqual(unpackedDeserialized, expectedDeserialize); - }); -}); -// This tests a bug that was fixed in Protobuf.js 6 -describe.skip('Proto message oneof serialize and deserialize', function() { - var oneofSerialize = serializeCls(messages_proto.OneOfValues); - var oneofDeserialize = deserializeCls( - messages_proto.OneOfValues, default_options); - it('Should have idempotent round trips', function() { - var test_message = {oneof_choice: 'int_choice', int_choice: 5}; - var serialized1 = oneofSerialize(test_message); - var deserialized1 = oneofDeserialize(serialized1); - assert.equal(deserialized1.int_choice, 5); - var serialized2 = oneofSerialize(deserialized1); - var deserialized2 = oneofDeserialize(serialized2); - assert.deepEqual(deserialized1, deserialized2); - }); - it('Should emit a property indicating which field was chosen', function() { - var test_message1 = {oneof_choice: 'int_choice', int_choice: 5}; - var serialized1 = oneofSerialize(test_message1); - var deserialized1 = oneofDeserialize(serialized1); - assert.equal(deserialized1.oneof_choice, 'int_choice'); - var test_message2 = {oneof_choice: 'string_choice', string_choice: 'abc'}; - var serialized2 = oneofSerialize(test_message2); - var deserialized2 = oneofDeserialize(serialized2); - assert.equal(deserialized2.oneof_choice, 'string_choice'); - }); -}); -describe('Proto message enum serialize and deserialize', function() { - var enumSerialize = serializeCls(messages_proto.EnumValues); - var enumDeserialize = deserializeCls( - messages_proto.EnumValues, default_options); - var enumIntOptions = _.defaults({enumsAsStrings: false}, default_options); - var enumIntDeserialize = deserializeCls( - messages_proto.EnumValues, enumIntOptions); - it('Should accept both names and numbers', function() { - var nameSerialized = enumSerialize({enum_value: 'ONE'}); - var numberSerialized = enumSerialize({enum_value: 1}); - assert.strictEqual(messages_proto.TestEnum.ONE, 1); - assert.deepEqual(enumDeserialize(nameSerialized), - enumDeserialize(numberSerialized)); - }); - // This tests a bug that was fixed in Protobuf.js 6 - it.skip('Should correctly handle the enumsAsStrings option', function() { - var serialized = enumSerialize({enum_value: 'TWO'}); - var nameDeserialized = enumDeserialize(serialized); - var numberDeserialized = enumIntDeserialize(serialized); - assert.deepEqual(nameDeserialized, {enum_value: 'TWO'}); - assert.deepEqual(numberDeserialized, {enum_value: 2}); - }); -}); diff --git a/src/node/test/credentials_test.js b/src/node/test/credentials_test.js deleted file mode 100644 index 0ff838e7d05..00000000000 --- a/src/node/test/credentials_test.js +++ /dev/null @@ -1,452 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); - -var grpc = require('..'); - -/** - * This is used for testing functions with multiple asynchronous calls that - * can happen in different orders. This should be passed the number of async - * function invocations that can occur last, and each of those should call this - * function's return value - * @param {function()} done The function that should be called when a test is - * complete. - * @param {number} count The number of calls to the resulting function if the - * test passes. - * @return {function()} The function that should be called at the end of each - * sequence of asynchronous functions. - */ -function multiDone(done, count) { - return function() { - count -= 1; - if (count <= 0) { - done(); - } - }; -} - -var fakeSuccessfulGoogleCredentials = { - getRequestMetadata: function(service_url, callback) { - setTimeout(function() { - callback(null, {Authorization: 'success'}); - }, 0); - } -}; - -var fakeFailingGoogleCredentials = { - getRequestMetadata: function(service_url, callback) { - setTimeout(function() { - // Google credentials currently adds string error codes to auth errors - var error = new Error('Authentication failure'); - error.code = 'ENOENT'; - callback(error); - }, 0); - } -}; - -var key_data, pem_data, ca_data; - -before(function() { - var key_path = path.join(__dirname, './data/server1.key'); - var pem_path = path.join(__dirname, './data/server1.pem'); - var ca_path = path.join(__dirname, '../test/data/ca.pem'); - key_data = fs.readFileSync(key_path); - pem_data = fs.readFileSync(pem_path); - ca_data = fs.readFileSync(ca_path); -}); - -describe('channel credentials', function() { - describe('#createSsl', function() { - it('works with no arguments', function() { - var creds; - assert.doesNotThrow(function() { - creds = grpc.credentials.createSsl(); - }); - assert.notEqual(creds, null); - }); - it('works with just one Buffer argument', function() { - var creds; - assert.doesNotThrow(function() { - creds = grpc.credentials.createSsl(ca_data); - }); - assert.notEqual(creds, null); - }); - it('works with 3 Buffer arguments', function() { - var creds; - assert.doesNotThrow(function() { - creds = grpc.credentials.createSsl(ca_data, key_data, pem_data); - }); - assert.notEqual(creds, null); - }); - it('works if the first argument is null', function() { - var creds; - assert.doesNotThrow(function() { - creds = grpc.credentials.createSsl(null, key_data, pem_data); - }); - assert.notEqual(creds, null); - }); - it('fails if the first argument is a non-Buffer value', function() { - assert.throws(function() { - grpc.credentials.createSsl('test'); - }, TypeError); - }); - it('fails if the second argument is a non-Buffer value', function() { - assert.throws(function() { - grpc.credentials.createSsl(null, 'test', pem_data); - }, TypeError); - }); - it('fails if the third argument is a non-Buffer value', function() { - assert.throws(function() { - grpc.credentials.createSsl(null, key_data, 'test'); - }, TypeError); - }); - it('fails if only 1 of the last 2 arguments is provided', function() { - assert.throws(function() { - grpc.credentials.createSsl(null, key_data); - }); - assert.throws(function() { - grpc.credentials.createSsl(null, null, pem_data); - }); - }); - }); -}); - -describe('server credentials', function() { - describe('#createSsl', function() { - it('accepts a buffer and array as the first 2 arguments', function() { - var creds; - assert.doesNotThrow(function() { - creds = grpc.ServerCredentials.createSsl(ca_data, []); - }); - assert.notEqual(creds, null); - }); - it('accepts a boolean as the third argument', function() { - var creds; - assert.doesNotThrow(function() { - creds = grpc.ServerCredentials.createSsl(ca_data, [], true); - }); - assert.notEqual(creds, null); - }); - it('accepts an object with two buffers in the second argument', function() { - var creds; - assert.doesNotThrow(function() { - creds = grpc.ServerCredentials.createSsl(null, - [{private_key: key_data, - cert_chain: pem_data}]); - }); - assert.notEqual(creds, null); - }); - it('accepts multiple objects in the second argument', function() { - var creds; - assert.doesNotThrow(function() { - creds = grpc.ServerCredentials.createSsl(null, - [{private_key: key_data, - cert_chain: pem_data}, - {private_key: key_data, - cert_chain: pem_data}]); - }); - assert.notEqual(creds, null); - }); - it('fails if the second argument is not an Array', function() { - assert.throws(function() { - grpc.ServerCredentials.createSsl(ca_data, 'test'); - }, TypeError); - }); - it('fails if the first argument is a non-Buffer value', function() { - assert.throws(function() { - grpc.ServerCredentials.createSsl('test', []); - }, TypeError); - }); - it('fails if the third argument is a non-boolean value', function() { - assert.throws(function() { - grpc.ServerCredentials.createSsl(ca_data, [], 'test'); - }, TypeError); - }); - it('fails if the array elements are not objects', function() { - assert.throws(function() { - grpc.ServerCredentials.createSsl(ca_data, 'test'); - }, TypeError); - }); - it('fails if the object does not have a Buffer private_key', function() { - assert.throws(function() { - grpc.ServerCredentials.createSsl(null, - [{private_key: 'test', - cert_chain: pem_data}]); - }, TypeError); - }); - it('fails if the object does not have a Buffer cert_chain', function() { - assert.throws(function() { - grpc.ServerCredentials.createSsl(null, - [{private_key: key_data, - cert_chain: 'test'}]); - }, TypeError); - }); - }); -}); - -describe('client credentials', function() { - var Client; - var server; - var port; - var client_ssl_creds; - var client_options = {}; - before(function() { - var proto = grpc.load(__dirname + '/test_service.proto'); - server = new grpc.Server(); - server.addService(proto.TestService.service, { - unary: function(call, cb) { - call.sendMetadata(call.metadata); - cb(null, {}); - }, - clientStream: function(stream, cb){ - stream.on('data', function(data) {}); - stream.on('end', function() { - stream.sendMetadata(stream.metadata); - cb(null, {}); - }); - }, - serverStream: function(stream) { - stream.sendMetadata(stream.metadata); - stream.end(); - }, - bidiStream: function(stream) { - stream.on('data', function(data) {}); - stream.on('end', function() { - stream.sendMetadata(stream.metadata); - stream.end(); - }); - } - }); - var creds = grpc.ServerCredentials.createSsl(null, - [{private_key: key_data, - cert_chain: pem_data}]); - port = server.bind('localhost:0', creds); - server.start(); - - Client = proto.TestService; - client_ssl_creds = grpc.credentials.createSsl(ca_data); - var host_override = 'foo.test.google.fr'; - client_options['grpc.ssl_target_name_override'] = host_override; - client_options['grpc.default_authority'] = host_override; - }); - after(function() { - server.forceShutdown(); - }); - it('Should accept SSL creds for a client', function(done) { - var client = new Client('localhost:' + port, client_ssl_creds, - client_options); - client.unary({}, function(err, data) { - assert.ifError(err); - done(); - }); - }); - it('Should update metadata with SSL creds', function(done) { - var metadataUpdater = function(service_url, callback) { - var metadata = new grpc.Metadata(); - metadata.set('plugin_key', 'plugin_value'); - callback(null, metadata); - }; - var creds = grpc.credentials.createFromMetadataGenerator(metadataUpdater); - var combined_creds = grpc.credentials.combineChannelCredentials( - client_ssl_creds, creds); - var client = new Client('localhost:' + port, combined_creds, - client_options); - var call = client.unary({}, function(err, data) { - assert.ifError(err); - }); - call.on('metadata', function(metadata) { - assert.deepEqual(metadata.get('plugin_key'), ['plugin_value']); - done(); - }); - }); - it('Should update metadata for two simultaneous calls', function(done) { - done = multiDone(done, 2); - var metadataUpdater = function(service_url, callback) { - var metadata = new grpc.Metadata(); - metadata.set('plugin_key', 'plugin_value'); - callback(null, metadata); - }; - var creds = grpc.credentials.createFromMetadataGenerator(metadataUpdater); - var combined_creds = grpc.credentials.combineChannelCredentials( - client_ssl_creds, creds); - var client = new Client('localhost:' + port, combined_creds, - client_options); - var call = client.unary({}, function(err, data) { - assert.ifError(err); - }); - call.on('metadata', function(metadata) { - assert.deepEqual(metadata.get('plugin_key'), ['plugin_value']); - done(); - }); - var call2 = client.unary({}, function(err, data) { - assert.ifError(err); - }); - call2.on('metadata', function(metadata) { - assert.deepEqual(metadata.get('plugin_key'), ['plugin_value']); - done(); - }); - }); - it('should propagate errors that the updater emits', function(done) { - var metadataUpdater = function(service_url, callback) { - var error = new Error('Authentication error'); - error.code = grpc.status.UNAUTHENTICATED; - callback(error); - }; - var creds = grpc.credentials.createFromMetadataGenerator(metadataUpdater); - var combined_creds = grpc.credentials.combineChannelCredentials( - client_ssl_creds, creds); - var client = new Client('localhost:' + port, combined_creds, - client_options); - client.unary({}, function(err, data) { - assert(err); - assert.strictEqual(err.message, - 'Getting metadata from plugin failed with error: ' + - 'Authentication error'); - assert.strictEqual(err.code, grpc.status.UNAUTHENTICATED); - done(); - }); - }); - it('should successfully wrap a Google credential', function(done) { - var creds = grpc.credentials.createFromGoogleCredential( - fakeSuccessfulGoogleCredentials); - var combined_creds = grpc.credentials.combineChannelCredentials( - client_ssl_creds, creds); - var client = new Client('localhost:' + port, combined_creds, - client_options); - var call = client.unary({}, function(err, data) { - assert.ifError(err); - }); - call.on('metadata', function(metadata) { - assert.deepEqual(metadata.get('authorization'), ['success']); - done(); - }); - }); - it('Should not add metadata with just SSL credentials', function(done) { - // Tests idempotency of credentials composition - var metadataUpdater = function(service_url, callback) { - var metadata = new grpc.Metadata(); - metadata.set('plugin_key', 'plugin_value'); - callback(null, metadata); - }; - var creds = grpc.credentials.createFromMetadataGenerator(metadataUpdater); - grpc.credentials.combineChannelCredentials(client_ssl_creds, creds); - var client = new Client('localhost:' + port, client_ssl_creds, - client_options); - var call = client.unary({}, function(err, data) { - assert.ifError(err); - }); - call.on('metadata', function(metadata) { - assert.deepEqual(metadata.get('plugin_key'), []); - done(); - }); - }); - it('should get an error from a Google credential', function(done) { - var creds = grpc.credentials.createFromGoogleCredential( - fakeFailingGoogleCredentials); - var combined_creds = grpc.credentials.combineChannelCredentials( - client_ssl_creds, creds); - var client = new Client('localhost:' + port, combined_creds, - client_options); - client.unary({}, function(err, data) { - assert(err); - assert.strictEqual(err.message, - 'Getting metadata from plugin failed with error: ' + - 'Authentication failure'); - done(); - }); - }); - describe('Per-rpc creds', function() { - var client; - var updater_creds; - before(function() { - client = new Client('localhost:' + port, client_ssl_creds, - client_options); - var metadataUpdater = function(service_url, callback) { - var metadata = new grpc.Metadata(); - metadata.set('plugin_key', 'plugin_value'); - callback(null, metadata); - }; - updater_creds = grpc.credentials.createFromMetadataGenerator( - metadataUpdater); - }); - it('Should update metadata on a unary call', function(done) { - var call = client.unary({}, {credentials: updater_creds}, - function(err, data) { - assert.ifError(err); - }); - call.on('metadata', function(metadata) { - assert.deepEqual(metadata.get('plugin_key'), ['plugin_value']); - done(); - }); - }); - it('should update metadata on a client streaming call', function(done) { - var call = client.clientStream({credentials: updater_creds}, - function(err, data) { - assert.ifError(err); - }); - call.on('metadata', function(metadata) { - assert.deepEqual(metadata.get('plugin_key'), ['plugin_value']); - done(); - }); - call.end(); - }); - it('should update metadata on a server streaming call', function(done) { - var call = client.serverStream({}, {credentials: updater_creds}); - call.on('data', function() {}); - call.on('metadata', function(metadata) { - assert.deepEqual(metadata.get('plugin_key'), ['plugin_value']); - done(); - }); - }); - it('should update metadata on a bidi streaming call', function(done) { - var call = client.bidiStream({credentials: updater_creds}); - call.on('data', function() {}); - call.on('metadata', function(metadata) { - assert.deepEqual(metadata.get('plugin_key'), ['plugin_value']); - done(); - }); - call.end(); - }); - it('should be able to use multiple plugin credentials', function(done) { - var altMetadataUpdater = function(service_url, callback) { - var metadata = new grpc.Metadata(); - metadata.set('other_plugin_key', 'other_plugin_value'); - callback(null, metadata); - }; - var alt_updater_creds = grpc.credentials.createFromMetadataGenerator( - altMetadataUpdater); - var combined_updater = grpc.credentials.combineCallCredentials( - updater_creds, alt_updater_creds); - var call = client.unary({}, {credentials: combined_updater}, - function(err, data) { - assert.ifError(err); - }); - call.on('metadata', function(metadata) { - assert.deepEqual(metadata.get('plugin_key'), ['plugin_value']); - assert.deepEqual(metadata.get('other_plugin_key'), - ['other_plugin_value']); - done(); - }); - }); - }); -}); diff --git a/src/node/test/data/README b/src/node/test/data/README deleted file mode 100644 index 888d95b9004..00000000000 --- a/src/node/test/data/README +++ /dev/null @@ -1 +0,0 @@ -CONFIRMEDTESTKEY diff --git a/src/node/test/data/ca.pem b/src/node/test/data/ca.pem deleted file mode 100644 index 6c8511a73c6..00000000000 --- a/src/node/test/data/ca.pem +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICSjCCAbOgAwIBAgIJAJHGGR4dGioHMA0GCSqGSIb3DQEBCwUAMFYxCzAJBgNV -BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX -aWRnaXRzIFB0eSBMdGQxDzANBgNVBAMTBnRlc3RjYTAeFw0xNDExMTEyMjMxMjla -Fw0yNDExMDgyMjMxMjlaMFYxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0 -YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQxDzANBgNVBAMT -BnRlc3RjYTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAwEDfBV5MYdlHVHJ7 -+L4nxrZy7mBfAVXpOc5vMYztssUI7mL2/iYujiIXM+weZYNTEpLdjyJdu7R5gGUu -g1jSVK/EPHfc74O7AyZU34PNIP4Sh33N+/A5YexrNgJlPY+E3GdVYi4ldWJjgkAd -Qah2PH5ACLrIIC6tRka9hcaBlIECAwEAAaMgMB4wDAYDVR0TBAUwAwEB/zAOBgNV -HQ8BAf8EBAMCAgQwDQYJKoZIhvcNAQELBQADgYEAHzC7jdYlzAVmddi/gdAeKPau -sPBG/C2HCWqHzpCUHcKuvMzDVkY/MP2o6JIW2DBbY64bO/FceExhjcykgaYtCH/m -oIU63+CFOTtR7otyQAWHqXa7q4SbCDlG7DyRFxqG0txPtGvy12lgldA2+RgcigQG -Dfcog5wrJytaQ6UA0wE= ------END CERTIFICATE----- diff --git a/src/node/test/data/server1.key b/src/node/test/data/server1.key deleted file mode 100644 index 143a5b87658..00000000000 --- a/src/node/test/data/server1.key +++ /dev/null @@ -1,16 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAOHDFScoLCVJpYDD -M4HYtIdV6Ake/sMNaaKdODjDMsux/4tDydlumN+fm+AjPEK5GHhGn1BgzkWF+slf -3BxhrA/8dNsnunstVA7ZBgA/5qQxMfGAq4wHNVX77fBZOgp9VlSMVfyd9N8YwbBY -AckOeUQadTi2X1S6OgJXgQ0m3MWhAgMBAAECgYAn7qGnM2vbjJNBm0VZCkOkTIWm -V10okw7EPJrdL2mkre9NasghNXbE1y5zDshx5Nt3KsazKOxTT8d0Jwh/3KbaN+YY -tTCbKGW0pXDRBhwUHRcuRzScjli8Rih5UOCiZkhefUTcRb6xIhZJuQy71tjaSy0p -dHZRmYyBYO2YEQ8xoQJBAPrJPhMBkzmEYFtyIEqAxQ/o/A6E+E4w8i+KM7nQCK7q -K4JXzyXVAjLfyBZWHGM2uro/fjqPggGD6QH1qXCkI4MCQQDmdKeb2TrKRh5BY1LR -81aJGKcJ2XbcDu6wMZK4oqWbTX2KiYn9GB0woM6nSr/Y6iy1u145YzYxEV/iMwff -DJULAkB8B2MnyzOg0pNFJqBJuH29bKCcHa8gHJzqXhNO5lAlEbMK95p/P2Wi+4Hd -aiEIAF1BF326QJcvYKmwSmrORp85AkAlSNxRJ50OWrfMZnBgzVjDx3xG6KsFQVk2 -ol6VhqL6dFgKUORFUWBvnKSyhjJxurlPEahV6oo6+A+mPhFY8eUvAkAZQyTdupP3 -XEFQKctGz+9+gKkemDp7LBBMEMBXrGTLPhpEfcjv/7KPdnFHYmhYeBTBnuVmTVWe -F98XJ7tIFfJq ------END PRIVATE KEY----- diff --git a/src/node/test/data/server1.pem b/src/node/test/data/server1.pem deleted file mode 100644 index f3d43fcc5be..00000000000 --- a/src/node/test/data/server1.pem +++ /dev/null @@ -1,16 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICnDCCAgWgAwIBAgIBBzANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJBVTET -MBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0cyBQ -dHkgTHRkMQ8wDQYDVQQDEwZ0ZXN0Y2EwHhcNMTUxMTA0MDIyMDI0WhcNMjUxMTAx -MDIyMDI0WjBlMQswCQYDVQQGEwJVUzERMA8GA1UECBMISWxsaW5vaXMxEDAOBgNV -BAcTB0NoaWNhZ28xFTATBgNVBAoTDEV4YW1wbGUsIENvLjEaMBgGA1UEAxQRKi50 -ZXN0Lmdvb2dsZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOHDFSco -LCVJpYDDM4HYtIdV6Ake/sMNaaKdODjDMsux/4tDydlumN+fm+AjPEK5GHhGn1Bg -zkWF+slf3BxhrA/8dNsnunstVA7ZBgA/5qQxMfGAq4wHNVX77fBZOgp9VlSMVfyd -9N8YwbBYAckOeUQadTi2X1S6OgJXgQ0m3MWhAgMBAAGjazBpMAkGA1UdEwQCMAAw -CwYDVR0PBAQDAgXgME8GA1UdEQRIMEaCECoudGVzdC5nb29nbGUuZnKCGHdhdGVy -em9vaS50ZXN0Lmdvb2dsZS5iZYISKi50ZXN0LnlvdXR1YmUuY29thwTAqAEDMA0G -CSqGSIb3DQEBCwUAA4GBAJFXVifQNub1LUP4JlnX5lXNlo8FxZ2a12AFQs+bzoJ6 -hM044EDjqyxUqSbVePK0ni3w1fHQB5rY9yYC5f8G7aqqTY1QOhoUk8ZTSTRpnkTh -y4jjdvTZeLDVBlueZUTDRmy2feY5aZIU18vFDK08dTG0A87pppuv1LNIR3loveU8 ------END CERTIFICATE----- diff --git a/src/node/test/echo_service.proto b/src/node/test/echo_service.proto deleted file mode 100644 index 0b27c8b16b4..00000000000 --- a/src/node/test/echo_service.proto +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2015 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -message EchoMessage { - string value = 1; - int32 value2 = 2; -} - -service EchoService { - rpc Echo (EchoMessage) returns (EchoMessage); -} diff --git a/src/node/test/end_to_end_test.js b/src/node/test/end_to_end_test.js deleted file mode 100644 index c11dfa93c2b..00000000000 --- a/src/node/test/end_to_end_test.js +++ /dev/null @@ -1,292 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var assert = require('assert'); -var grpc = require('../src/grpc_extension'); -var constants = require('../src/constants'); - -/** - * This is used for testing functions with multiple asynchronous calls that - * can happen in different orders. This should be passed the number of async - * function invocations that can occur last, and each of those should call this - * function's return value - * @param {function()} done The function that should be called when a test is - * complete. - * @param {number} count The number of calls to the resulting function if the - * test passes. - * @return {function()} The function that should be called at the end of each - * sequence of asynchronous functions. - */ -function multiDone(done, count) { - return function() { - count -= 1; - if (count <= 0) { - done(); - } - }; -} - -var insecureCreds = grpc.ChannelCredentials.createInsecure(); - -describe('end-to-end', function() { - var server; - var channel; - before(function() { - server = new grpc.Server(); - var port_num = server.addHttp2Port('0.0.0.0:0', - grpc.ServerCredentials.createInsecure()); - server.start(); - channel = new grpc.Channel('localhost:' + port_num, insecureCreds); - }); - after(function() { - server.forceShutdown(); - }); - it('should start and end a request without error', function(complete) { - var done = multiDone(complete, 2); - var status_text = 'xyz'; - var call = new grpc.Call(channel, - 'dummy_method', - Infinity); - var client_batch = {}; - client_batch[grpc.opType.SEND_INITIAL_METADATA] = {}; - client_batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true; - client_batch[grpc.opType.RECV_INITIAL_METADATA] = true; - client_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true; - call.startBatch(client_batch, function(err, response) { - assert.ifError(err); - assert.deepEqual(response, { - send_metadata: true, - client_close: true, - metadata: {}, - status: { - code: constants.status.OK, - details: status_text, - metadata: {} - } - }); - done(); - }); - - server.requestCall(function(err, call_details) { - var new_call = call_details.new_call; - assert.notEqual(new_call, null); - var server_call = new_call.call; - assert.notEqual(server_call, null); - var server_batch = {}; - server_batch[grpc.opType.SEND_INITIAL_METADATA] = {}; - server_batch[grpc.opType.SEND_STATUS_FROM_SERVER] = { - metadata: {}, - code: constants.status.OK, - details: status_text - }; - server_batch[grpc.opType.RECV_CLOSE_ON_SERVER] = true; - server_call.startBatch(server_batch, function(err, response) { - assert.ifError(err); - assert.deepEqual(response, { - send_metadata: true, - send_status: true, - cancelled: false - }); - done(); - }); - }); - }); - it('should successfully send and receive metadata', function(complete) { - var done = multiDone(complete, 2); - var status_text = 'xyz'; - var call = new grpc.Call(channel, - 'dummy_method', - Infinity); - var client_batch = {}; - client_batch[grpc.opType.SEND_INITIAL_METADATA] = { - client_key: ['client_value'] - }; - client_batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true; - client_batch[grpc.opType.RECV_INITIAL_METADATA] = true; - client_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true; - call.startBatch(client_batch, function(err, response) { - assert.ifError(err); - assert.deepEqual(response,{ - send_metadata: true, - client_close: true, - metadata: {server_key: ['server_value']}, - status: {code: constants.status.OK, - details: status_text, - metadata: {}} - }); - done(); - }); - - server.requestCall(function(err, call_details) { - var new_call = call_details.new_call; - assert.notEqual(new_call, null); - assert.strictEqual(new_call.metadata.client_key[0], - 'client_value'); - var server_call = new_call.call; - assert.notEqual(server_call, null); - var server_batch = {}; - server_batch[grpc.opType.SEND_INITIAL_METADATA] = { - server_key: ['server_value'] - }; - server_batch[grpc.opType.SEND_STATUS_FROM_SERVER] = { - metadata: {}, - code: constants.status.OK, - details: status_text - }; - server_batch[grpc.opType.RECV_CLOSE_ON_SERVER] = true; - server_call.startBatch(server_batch, function(err, response) { - assert.ifError(err); - assert.deepEqual(response, { - send_metadata: true, - send_status: true, - cancelled: false - }); - done(); - }); - }); - }); - it('should send and receive data without error', function(complete) { - var req_text = 'client_request'; - var reply_text = 'server_response'; - var done = multiDone(complete, 2); - var status_text = 'success'; - var call = new grpc.Call(channel, - 'dummy_method', - Infinity); - var client_batch = {}; - client_batch[grpc.opType.SEND_INITIAL_METADATA] = {}; - client_batch[grpc.opType.SEND_MESSAGE] = new Buffer(req_text); - client_batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true; - client_batch[grpc.opType.RECV_INITIAL_METADATA] = true; - client_batch[grpc.opType.RECV_MESSAGE] = true; - client_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true; - call.startBatch(client_batch, function(err, response) { - assert.ifError(err); - assert(response.send_metadata); - assert(response.client_close); - assert.deepEqual(response.metadata, {}); - assert(response.send_message); - assert.strictEqual(response.read.toString(), reply_text); - assert.deepEqual(response.status, {code: constants.status.OK, - details: status_text, - metadata: {}}); - done(); - }); - - server.requestCall(function(err, call_details) { - var new_call = call_details.new_call; - assert.notEqual(new_call, null); - var server_call = new_call.call; - assert.notEqual(server_call, null); - var server_batch = {}; - server_batch[grpc.opType.SEND_INITIAL_METADATA] = {}; - server_batch[grpc.opType.RECV_MESSAGE] = true; - server_call.startBatch(server_batch, function(err, response) { - assert.ifError(err); - assert(response.send_metadata); - assert.strictEqual(response.read.toString(), req_text); - var response_batch = {}; - response_batch[grpc.opType.SEND_MESSAGE] = new Buffer(reply_text); - response_batch[grpc.opType.SEND_STATUS_FROM_SERVER] = { - metadata: {}, - code: constants.status.OK, - details: status_text - }; - response_batch[grpc.opType.RECV_CLOSE_ON_SERVER] = true; - server_call.startBatch(response_batch, function(err, response) { - assert(response.send_status); - assert(!response.cancelled); - done(); - }); - }); - }); - }); - it('should send multiple messages', function(complete) { - var done = multiDone(complete, 2); - var requests = ['req1', 'req2']; - var status_text = 'xyz'; - var call = new grpc.Call(channel, - 'dummy_method', - Infinity); - var client_batch = {}; - client_batch[grpc.opType.SEND_INITIAL_METADATA] = {}; - client_batch[grpc.opType.SEND_MESSAGE] = new Buffer(requests[0]); - client_batch[grpc.opType.RECV_INITIAL_METADATA] = true; - call.startBatch(client_batch, function(err, response) { - assert.ifError(err); - assert.deepEqual(response, { - send_metadata: true, - send_message: true, - metadata: {} - }); - var req2_batch = {}; - req2_batch[grpc.opType.SEND_MESSAGE] = new Buffer(requests[1]); - req2_batch[grpc.opType.SEND_CLOSE_FROM_CLIENT] = true; - req2_batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true; - call.startBatch(req2_batch, function(err, resp) { - assert.ifError(err); - assert.deepEqual(resp, { - send_message: true, - client_close: true, - status: { - code: constants.status.OK, - details: status_text, - metadata: {} - } - }); - done(); - }); - }); - - server.requestCall(function(err, call_details) { - var new_call = call_details.new_call; - assert.notEqual(new_call, null); - var server_call = new_call.call; - assert.notEqual(server_call, null); - var server_batch = {}; - server_batch[grpc.opType.SEND_INITIAL_METADATA] = {}; - server_batch[grpc.opType.RECV_MESSAGE] = true; - server_call.startBatch(server_batch, function(err, response) { - assert.ifError(err); - assert(response.send_metadata); - assert.strictEqual(response.read.toString(), requests[0]); - var snd_batch = {}; - snd_batch[grpc.opType.RECV_MESSAGE] = true; - server_call.startBatch(snd_batch, function(err, response) { - assert.ifError(err); - assert.strictEqual(response.read.toString(), requests[1]); - var end_batch = {}; - end_batch[grpc.opType.RECV_CLOSE_ON_SERVER] = true; - end_batch[grpc.opType.SEND_STATUS_FROM_SERVER] = { - metadata: {}, - code: constants.status.OK, - details: status_text - }; - server_call.startBatch(end_batch, function(err, response) { - assert.ifError(err); - assert(response.send_status); - assert(!response.cancelled); - done(); - }); - }); - }); - }); - }); -}); diff --git a/src/node/test/health_test.js b/src/node/test/health_test.js deleted file mode 100644 index dc008644d81..00000000000 --- a/src/node/test/health_test.js +++ /dev/null @@ -1,103 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var assert = require('assert'); - -var health = require('../health_check/health'); - -var health_messages = require('../health_check/v1/health_pb'); - -var ServingStatus = health_messages.HealthCheckResponse.ServingStatus; - -var grpc = require('../'); - -describe('Health Checking', function() { - var statusMap = { - '': ServingStatus.SERVING, - 'grpc.test.TestServiceNotServing': ServingStatus.NOT_SERVING, - 'grpc.test.TestServiceServing': ServingStatus.SERVING - }; - var healthServer; - var healthImpl; - var healthClient; - before(function() { - healthServer = new grpc.Server(); - healthImpl = new health.Implementation(statusMap); - healthServer.addService(health.service, healthImpl); - var port_num = healthServer.bind('0.0.0.0:0', - grpc.ServerCredentials.createInsecure()); - healthServer.start(); - healthClient = new health.Client('localhost:' + port_num, - grpc.credentials.createInsecure()); - }); - after(function() { - healthServer.forceShutdown(); - }); - it('should say an enabled service is SERVING', function(done) { - var request = new health_messages.HealthCheckRequest(); - request.setService(''); - healthClient.check(request, function(err, response) { - assert.ifError(err); - assert.strictEqual(response.getStatus(), ServingStatus.SERVING); - done(); - }); - }); - it('should say that a disabled service is NOT_SERVING', function(done) { - var request = new health_messages.HealthCheckRequest(); - request.setService('grpc.test.TestServiceNotServing'); - healthClient.check(request, function(err, response) { - assert.ifError(err); - assert.strictEqual(response.getStatus(), ServingStatus.NOT_SERVING); - done(); - }); - }); - it('should say that an enabled service is SERVING', function(done) { - var request = new health_messages.HealthCheckRequest(); - request.setService('grpc.test.TestServiceServing'); - healthClient.check(request, function(err, response) { - assert.ifError(err); - assert.strictEqual(response.getStatus(), ServingStatus.SERVING); - done(); - }); - }); - it('should get NOT_FOUND if the service is not registered', function(done) { - var request = new health_messages.HealthCheckRequest(); - request.setService('not_registered'); - healthClient.check(request, function(err, response) { - assert(err); - assert.strictEqual(err.code, grpc.status.NOT_FOUND); - done(); - }); - }); - it('should get a different response if the status changes', function(done) { - var request = new health_messages.HealthCheckRequest(); - request.setService('transient'); - healthClient.check(request, function(err, response) { - assert(err); - assert.strictEqual(err.code, grpc.status.NOT_FOUND); - healthImpl.setStatus('transient', ServingStatus.SERVING); - healthClient.check(request, function(err, response) { - assert.ifError(err); - assert.strictEqual(response.getStatus(), ServingStatus.SERVING); - done(); - }); - }); - }); -}); diff --git a/src/node/test/interop_sanity_test.js b/src/node/test/interop_sanity_test.js deleted file mode 100644 index b3f65a03407..00000000000 --- a/src/node/test/interop_sanity_test.js +++ /dev/null @@ -1,94 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var interop_server = require('../interop/interop_server.js'); -var interop_client = require('../interop/interop_client.js'); - -var server; - -var port; - -var name_override = 'foo.test.google.fr'; - -describe('Interop tests', function() { - before(function(done) { - var server_obj = interop_server.getServer(0, true); - server = server_obj.server; - server.start(); - port = 'localhost:' + server_obj.port; - done(); - }); - after(function() { - server.forceShutdown(); - }); - // This depends on not using a binary stream - it('should pass empty_unary', function(done) { - interop_client.runTest(port, name_override, 'empty_unary', true, true, - done); - }); - // This fails due to an unknown bug - it('should pass large_unary', function(done) { - interop_client.runTest(port, name_override, 'large_unary', true, true, - done); - }); - it('should pass client_streaming', function(done) { - interop_client.runTest(port, name_override, 'client_streaming', true, true, - done); - }); - it('should pass server_streaming', function(done) { - interop_client.runTest(port, name_override, 'server_streaming', true, true, - done); - }); - it('should pass ping_pong', function(done) { - interop_client.runTest(port, name_override, 'ping_pong', true, true, done); - }); - it('should pass empty_stream', function(done) { - interop_client.runTest(port, name_override, 'empty_stream', true, true, - done); - }); - it('should pass cancel_after_begin', function(done) { - interop_client.runTest(port, name_override, 'cancel_after_begin', true, - true, done); - }); - it('should pass cancel_after_first_response', function(done) { - interop_client.runTest(port, name_override, 'cancel_after_first_response', - true, true, done); - }); - it('should pass timeout_on_sleeping_server', function(done) { - interop_client.runTest(port, name_override, 'timeout_on_sleeping_server', - true, true, done); - }); - it('should pass custom_metadata', function(done) { - interop_client.runTest(port, name_override, 'custom_metadata', - true, true, done); - }); - it('should pass status_code_and_message', function(done) { - interop_client.runTest(port, name_override, 'status_code_and_message', - true, true, done); - }); - it('should pass unimplemented_service', function(done) { - interop_client.runTest(port, name_override, 'unimplemented_service', - true, true, done); - }); - it('should pass unimplemented_method', function(done) { - interop_client.runTest(port, name_override, 'unimplemented_method', - true, true, done); - }); -}); diff --git a/src/node/test/math/math_grpc_pb.js b/src/node/test/math/math_grpc_pb.js deleted file mode 100644 index afd08a34aab..00000000000 --- a/src/node/test/math/math_grpc_pb.js +++ /dev/null @@ -1,125 +0,0 @@ -// GENERATED CODE -- DO NOT EDIT! - -// Original file comments: -// Copyright 2015 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -'use strict'; -var grpc = require('grpc'); -var math_math_pb = require('../math/math_pb.js'); - -function serialize_DivArgs(arg) { - if (!(arg instanceof math_math_pb.DivArgs)) { - throw new Error('Expected argument of type DivArgs'); - } - return new Buffer(arg.serializeBinary()); -} - -function deserialize_DivArgs(buffer_arg) { - return math_math_pb.DivArgs.deserializeBinary(new Uint8Array(buffer_arg)); -} - -function serialize_DivReply(arg) { - if (!(arg instanceof math_math_pb.DivReply)) { - throw new Error('Expected argument of type DivReply'); - } - return new Buffer(arg.serializeBinary()); -} - -function deserialize_DivReply(buffer_arg) { - return math_math_pb.DivReply.deserializeBinary(new Uint8Array(buffer_arg)); -} - -function serialize_FibArgs(arg) { - if (!(arg instanceof math_math_pb.FibArgs)) { - throw new Error('Expected argument of type FibArgs'); - } - return new Buffer(arg.serializeBinary()); -} - -function deserialize_FibArgs(buffer_arg) { - return math_math_pb.FibArgs.deserializeBinary(new Uint8Array(buffer_arg)); -} - -function serialize_Num(arg) { - if (!(arg instanceof math_math_pb.Num)) { - throw new Error('Expected argument of type Num'); - } - return new Buffer(arg.serializeBinary()); -} - -function deserialize_Num(buffer_arg) { - return math_math_pb.Num.deserializeBinary(new Uint8Array(buffer_arg)); -} - - -var MathService = exports.MathService = { - // Div divides args.dividend by args.divisor and returns the quotient and - // remainder. - div: { - path: '/math.Math/Div', - requestStream: false, - responseStream: false, - requestType: math_math_pb.DivArgs, - responseType: math_math_pb.DivReply, - requestSerialize: serialize_DivArgs, - requestDeserialize: deserialize_DivArgs, - responseSerialize: serialize_DivReply, - responseDeserialize: deserialize_DivReply, - }, - // DivMany accepts an arbitrary number of division args from the client stream - // and sends back the results in the reply stream. The stream continues until - // the client closes its end; the server does the same after sending all the - // replies. The stream ends immediately if either end aborts. - divMany: { - path: '/math.Math/DivMany', - requestStream: true, - responseStream: true, - requestType: math_math_pb.DivArgs, - responseType: math_math_pb.DivReply, - requestSerialize: serialize_DivArgs, - requestDeserialize: deserialize_DivArgs, - responseSerialize: serialize_DivReply, - responseDeserialize: deserialize_DivReply, - }, - // Fib generates numbers in the Fibonacci sequence. If args.limit > 0, Fib - // generates up to limit numbers; otherwise it continues until the call is - // canceled. Unlike Fib above, Fib has no final FibReply. - fib: { - path: '/math.Math/Fib', - requestStream: false, - responseStream: true, - requestType: math_math_pb.FibArgs, - responseType: math_math_pb.Num, - requestSerialize: serialize_FibArgs, - requestDeserialize: deserialize_FibArgs, - responseSerialize: serialize_Num, - responseDeserialize: deserialize_Num, - }, - // Sum sums a stream of numbers, returning the final result once the stream - // is closed. - sum: { - path: '/math.Math/Sum', - requestStream: true, - responseStream: false, - requestType: math_math_pb.Num, - responseType: math_math_pb.Num, - requestSerialize: serialize_Num, - requestDeserialize: deserialize_Num, - responseSerialize: serialize_Num, - responseDeserialize: deserialize_Num, - }, -}; - -exports.MathClient = grpc.makeGenericClientConstructor(MathService); diff --git a/src/node/test/math/math_pb.js b/src/node/test/math/math_pb.js deleted file mode 100644 index ccc05c6e06d..00000000000 --- a/src/node/test/math/math_pb.js +++ /dev/null @@ -1,866 +0,0 @@ -/** - * @fileoverview - * @enhanceable - * @public - */ -// GENERATED CODE -- DO NOT EDIT! - -var jspb = require('google-protobuf'); -var goog = jspb; -var global = Function('return this')(); - -goog.exportSymbol('proto.math.DivArgs', null, global); -goog.exportSymbol('proto.math.DivReply', null, global); -goog.exportSymbol('proto.math.FibArgs', null, global); -goog.exportSymbol('proto.math.FibReply', null, global); -goog.exportSymbol('proto.math.Num', null, global); - -/** - * Generated by JsPbCodeGenerator. - * @param {Array=} opt_data Optional initial data array, typically from a - * server response, or constructed directly in Javascript. The array is used - * in place and becomes part of the constructed object. It is not cloned. - * If no data is provided, the constructed object will be empty, but still - * valid. - * @extends {jspb.Message} - * @constructor - */ -proto.math.DivArgs = function(opt_data) { - jspb.Message.initialize(this, opt_data, 0, -1, null, null); -}; -goog.inherits(proto.math.DivArgs, jspb.Message); -if (goog.DEBUG && !COMPILED) { - proto.math.DivArgs.displayName = 'proto.math.DivArgs'; -} - - -if (jspb.Message.GENERATE_TO_OBJECT) { -/** - * Creates an object representation of this proto suitable for use in Soy templates. - * Field names that are reserved in JavaScript and will be renamed to pb_name. - * To access a reserved field use, foo.pb_, eg, foo.pb_default. - * For the list of reserved names please see: - * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. - * @param {boolean=} opt_includeInstance Whether to include the JSPB instance - * for transitional soy proto support: http://goto/soy-param-migration - * @return {!Object} - */ -proto.math.DivArgs.prototype.toObject = function(opt_includeInstance) { - return proto.math.DivArgs.toObject(opt_includeInstance, this); -}; - - -/** - * Static version of the {@see toObject} method. - * @param {boolean|undefined} includeInstance Whether to include the JSPB - * instance for transitional soy proto support: - * http://goto/soy-param-migration - * @param {!proto.math.DivArgs} msg The msg instance to transform. - * @return {!Object} - */ -proto.math.DivArgs.toObject = function(includeInstance, msg) { - var f, obj = { - dividend: msg.getDividend(), - divisor: msg.getDivisor() - }; - - if (includeInstance) { - obj.$jspbMessageInstance = msg; - } - return obj; -}; -} - - -/** - * Deserializes binary data (in protobuf wire format). - * @param {jspb.ByteSource} bytes The bytes to deserialize. - * @return {!proto.math.DivArgs} - */ -proto.math.DivArgs.deserializeBinary = function(bytes) { - var reader = new jspb.BinaryReader(bytes); - var msg = new proto.math.DivArgs; - return proto.math.DivArgs.deserializeBinaryFromReader(msg, reader); -}; - - -/** - * Deserializes binary data (in protobuf wire format) from the - * given reader into the given message object. - * @param {!proto.math.DivArgs} msg The message object to deserialize into. - * @param {!jspb.BinaryReader} reader The BinaryReader to use. - * @return {!proto.math.DivArgs} - */ -proto.math.DivArgs.deserializeBinaryFromReader = function(msg, reader) { - while (reader.nextField()) { - if (reader.isEndGroup()) { - break; - } - var field = reader.getFieldNumber(); - switch (field) { - case 1: - var value = /** @type {number} */ (reader.readInt64()); - msg.setDividend(value); - break; - case 2: - var value = /** @type {number} */ (reader.readInt64()); - msg.setDivisor(value); - break; - default: - reader.skipField(); - break; - } - } - return msg; -}; - - -/** - * Class method variant: serializes the given message to binary data - * (in protobuf wire format), writing to the given BinaryWriter. - * @param {!proto.math.DivArgs} message - * @param {!jspb.BinaryWriter} writer - */ -proto.math.DivArgs.serializeBinaryToWriter = function(message, writer) { - message.serializeBinaryToWriter(writer); -}; - - -/** - * Serializes the message to binary data (in protobuf wire format). - * @return {!Uint8Array} - */ -proto.math.DivArgs.prototype.serializeBinary = function() { - var writer = new jspb.BinaryWriter(); - this.serializeBinaryToWriter(writer); - return writer.getResultBuffer(); -}; - - -/** - * Serializes the message to binary data (in protobuf wire format), - * writing to the given BinaryWriter. - * @param {!jspb.BinaryWriter} writer - */ -proto.math.DivArgs.prototype.serializeBinaryToWriter = function (writer) { - var f = undefined; - f = this.getDividend(); - if (f !== 0) { - writer.writeInt64( - 1, - f - ); - } - f = this.getDivisor(); - if (f !== 0) { - writer.writeInt64( - 2, - f - ); - } -}; - - -/** - * Creates a deep clone of this proto. No data is shared with the original. - * @return {!proto.math.DivArgs} The clone. - */ -proto.math.DivArgs.prototype.cloneMessage = function() { - return /** @type {!proto.math.DivArgs} */ (jspb.Message.cloneMessage(this)); -}; - - -/** - * optional int64 dividend = 1; - * @return {number} - */ -proto.math.DivArgs.prototype.getDividend = function() { - return /** @type {number} */ (jspb.Message.getFieldProto3(this, 1, 0)); -}; - - -/** @param {number} value */ -proto.math.DivArgs.prototype.setDividend = function(value) { - jspb.Message.setField(this, 1, value); -}; - - -/** - * optional int64 divisor = 2; - * @return {number} - */ -proto.math.DivArgs.prototype.getDivisor = function() { - return /** @type {number} */ (jspb.Message.getFieldProto3(this, 2, 0)); -}; - - -/** @param {number} value */ -proto.math.DivArgs.prototype.setDivisor = function(value) { - jspb.Message.setField(this, 2, value); -}; - - - -/** - * Generated by JsPbCodeGenerator. - * @param {Array=} opt_data Optional initial data array, typically from a - * server response, or constructed directly in Javascript. The array is used - * in place and becomes part of the constructed object. It is not cloned. - * If no data is provided, the constructed object will be empty, but still - * valid. - * @extends {jspb.Message} - * @constructor - */ -proto.math.DivReply = function(opt_data) { - jspb.Message.initialize(this, opt_data, 0, -1, null, null); -}; -goog.inherits(proto.math.DivReply, jspb.Message); -if (goog.DEBUG && !COMPILED) { - proto.math.DivReply.displayName = 'proto.math.DivReply'; -} - - -if (jspb.Message.GENERATE_TO_OBJECT) { -/** - * Creates an object representation of this proto suitable for use in Soy templates. - * Field names that are reserved in JavaScript and will be renamed to pb_name. - * To access a reserved field use, foo.pb_, eg, foo.pb_default. - * For the list of reserved names please see: - * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. - * @param {boolean=} opt_includeInstance Whether to include the JSPB instance - * for transitional soy proto support: http://goto/soy-param-migration - * @return {!Object} - */ -proto.math.DivReply.prototype.toObject = function(opt_includeInstance) { - return proto.math.DivReply.toObject(opt_includeInstance, this); -}; - - -/** - * Static version of the {@see toObject} method. - * @param {boolean|undefined} includeInstance Whether to include the JSPB - * instance for transitional soy proto support: - * http://goto/soy-param-migration - * @param {!proto.math.DivReply} msg The msg instance to transform. - * @return {!Object} - */ -proto.math.DivReply.toObject = function(includeInstance, msg) { - var f, obj = { - quotient: msg.getQuotient(), - remainder: msg.getRemainder() - }; - - if (includeInstance) { - obj.$jspbMessageInstance = msg; - } - return obj; -}; -} - - -/** - * Deserializes binary data (in protobuf wire format). - * @param {jspb.ByteSource} bytes The bytes to deserialize. - * @return {!proto.math.DivReply} - */ -proto.math.DivReply.deserializeBinary = function(bytes) { - var reader = new jspb.BinaryReader(bytes); - var msg = new proto.math.DivReply; - return proto.math.DivReply.deserializeBinaryFromReader(msg, reader); -}; - - -/** - * Deserializes binary data (in protobuf wire format) from the - * given reader into the given message object. - * @param {!proto.math.DivReply} msg The message object to deserialize into. - * @param {!jspb.BinaryReader} reader The BinaryReader to use. - * @return {!proto.math.DivReply} - */ -proto.math.DivReply.deserializeBinaryFromReader = function(msg, reader) { - while (reader.nextField()) { - if (reader.isEndGroup()) { - break; - } - var field = reader.getFieldNumber(); - switch (field) { - case 1: - var value = /** @type {number} */ (reader.readInt64()); - msg.setQuotient(value); - break; - case 2: - var value = /** @type {number} */ (reader.readInt64()); - msg.setRemainder(value); - break; - default: - reader.skipField(); - break; - } - } - return msg; -}; - - -/** - * Class method variant: serializes the given message to binary data - * (in protobuf wire format), writing to the given BinaryWriter. - * @param {!proto.math.DivReply} message - * @param {!jspb.BinaryWriter} writer - */ -proto.math.DivReply.serializeBinaryToWriter = function(message, writer) { - message.serializeBinaryToWriter(writer); -}; - - -/** - * Serializes the message to binary data (in protobuf wire format). - * @return {!Uint8Array} - */ -proto.math.DivReply.prototype.serializeBinary = function() { - var writer = new jspb.BinaryWriter(); - this.serializeBinaryToWriter(writer); - return writer.getResultBuffer(); -}; - - -/** - * Serializes the message to binary data (in protobuf wire format), - * writing to the given BinaryWriter. - * @param {!jspb.BinaryWriter} writer - */ -proto.math.DivReply.prototype.serializeBinaryToWriter = function (writer) { - var f = undefined; - f = this.getQuotient(); - if (f !== 0) { - writer.writeInt64( - 1, - f - ); - } - f = this.getRemainder(); - if (f !== 0) { - writer.writeInt64( - 2, - f - ); - } -}; - - -/** - * Creates a deep clone of this proto. No data is shared with the original. - * @return {!proto.math.DivReply} The clone. - */ -proto.math.DivReply.prototype.cloneMessage = function() { - return /** @type {!proto.math.DivReply} */ (jspb.Message.cloneMessage(this)); -}; - - -/** - * optional int64 quotient = 1; - * @return {number} - */ -proto.math.DivReply.prototype.getQuotient = function() { - return /** @type {number} */ (jspb.Message.getFieldProto3(this, 1, 0)); -}; - - -/** @param {number} value */ -proto.math.DivReply.prototype.setQuotient = function(value) { - jspb.Message.setField(this, 1, value); -}; - - -/** - * optional int64 remainder = 2; - * @return {number} - */ -proto.math.DivReply.prototype.getRemainder = function() { - return /** @type {number} */ (jspb.Message.getFieldProto3(this, 2, 0)); -}; - - -/** @param {number} value */ -proto.math.DivReply.prototype.setRemainder = function(value) { - jspb.Message.setField(this, 2, value); -}; - - - -/** - * Generated by JsPbCodeGenerator. - * @param {Array=} opt_data Optional initial data array, typically from a - * server response, or constructed directly in Javascript. The array is used - * in place and becomes part of the constructed object. It is not cloned. - * If no data is provided, the constructed object will be empty, but still - * valid. - * @extends {jspb.Message} - * @constructor - */ -proto.math.FibArgs = function(opt_data) { - jspb.Message.initialize(this, opt_data, 0, -1, null, null); -}; -goog.inherits(proto.math.FibArgs, jspb.Message); -if (goog.DEBUG && !COMPILED) { - proto.math.FibArgs.displayName = 'proto.math.FibArgs'; -} - - -if (jspb.Message.GENERATE_TO_OBJECT) { -/** - * Creates an object representation of this proto suitable for use in Soy templates. - * Field names that are reserved in JavaScript and will be renamed to pb_name. - * To access a reserved field use, foo.pb_, eg, foo.pb_default. - * For the list of reserved names please see: - * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. - * @param {boolean=} opt_includeInstance Whether to include the JSPB instance - * for transitional soy proto support: http://goto/soy-param-migration - * @return {!Object} - */ -proto.math.FibArgs.prototype.toObject = function(opt_includeInstance) { - return proto.math.FibArgs.toObject(opt_includeInstance, this); -}; - - -/** - * Static version of the {@see toObject} method. - * @param {boolean|undefined} includeInstance Whether to include the JSPB - * instance for transitional soy proto support: - * http://goto/soy-param-migration - * @param {!proto.math.FibArgs} msg The msg instance to transform. - * @return {!Object} - */ -proto.math.FibArgs.toObject = function(includeInstance, msg) { - var f, obj = { - limit: msg.getLimit() - }; - - if (includeInstance) { - obj.$jspbMessageInstance = msg; - } - return obj; -}; -} - - -/** - * Deserializes binary data (in protobuf wire format). - * @param {jspb.ByteSource} bytes The bytes to deserialize. - * @return {!proto.math.FibArgs} - */ -proto.math.FibArgs.deserializeBinary = function(bytes) { - var reader = new jspb.BinaryReader(bytes); - var msg = new proto.math.FibArgs; - return proto.math.FibArgs.deserializeBinaryFromReader(msg, reader); -}; - - -/** - * Deserializes binary data (in protobuf wire format) from the - * given reader into the given message object. - * @param {!proto.math.FibArgs} msg The message object to deserialize into. - * @param {!jspb.BinaryReader} reader The BinaryReader to use. - * @return {!proto.math.FibArgs} - */ -proto.math.FibArgs.deserializeBinaryFromReader = function(msg, reader) { - while (reader.nextField()) { - if (reader.isEndGroup()) { - break; - } - var field = reader.getFieldNumber(); - switch (field) { - case 1: - var value = /** @type {number} */ (reader.readInt64()); - msg.setLimit(value); - break; - default: - reader.skipField(); - break; - } - } - return msg; -}; - - -/** - * Class method variant: serializes the given message to binary data - * (in protobuf wire format), writing to the given BinaryWriter. - * @param {!proto.math.FibArgs} message - * @param {!jspb.BinaryWriter} writer - */ -proto.math.FibArgs.serializeBinaryToWriter = function(message, writer) { - message.serializeBinaryToWriter(writer); -}; - - -/** - * Serializes the message to binary data (in protobuf wire format). - * @return {!Uint8Array} - */ -proto.math.FibArgs.prototype.serializeBinary = function() { - var writer = new jspb.BinaryWriter(); - this.serializeBinaryToWriter(writer); - return writer.getResultBuffer(); -}; - - -/** - * Serializes the message to binary data (in protobuf wire format), - * writing to the given BinaryWriter. - * @param {!jspb.BinaryWriter} writer - */ -proto.math.FibArgs.prototype.serializeBinaryToWriter = function (writer) { - var f = undefined; - f = this.getLimit(); - if (f !== 0) { - writer.writeInt64( - 1, - f - ); - } -}; - - -/** - * Creates a deep clone of this proto. No data is shared with the original. - * @return {!proto.math.FibArgs} The clone. - */ -proto.math.FibArgs.prototype.cloneMessage = function() { - return /** @type {!proto.math.FibArgs} */ (jspb.Message.cloneMessage(this)); -}; - - -/** - * optional int64 limit = 1; - * @return {number} - */ -proto.math.FibArgs.prototype.getLimit = function() { - return /** @type {number} */ (jspb.Message.getFieldProto3(this, 1, 0)); -}; - - -/** @param {number} value */ -proto.math.FibArgs.prototype.setLimit = function(value) { - jspb.Message.setField(this, 1, value); -}; - - - -/** - * Generated by JsPbCodeGenerator. - * @param {Array=} opt_data Optional initial data array, typically from a - * server response, or constructed directly in Javascript. The array is used - * in place and becomes part of the constructed object. It is not cloned. - * If no data is provided, the constructed object will be empty, but still - * valid. - * @extends {jspb.Message} - * @constructor - */ -proto.math.Num = function(opt_data) { - jspb.Message.initialize(this, opt_data, 0, -1, null, null); -}; -goog.inherits(proto.math.Num, jspb.Message); -if (goog.DEBUG && !COMPILED) { - proto.math.Num.displayName = 'proto.math.Num'; -} - - -if (jspb.Message.GENERATE_TO_OBJECT) { -/** - * Creates an object representation of this proto suitable for use in Soy templates. - * Field names that are reserved in JavaScript and will be renamed to pb_name. - * To access a reserved field use, foo.pb_, eg, foo.pb_default. - * For the list of reserved names please see: - * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. - * @param {boolean=} opt_includeInstance Whether to include the JSPB instance - * for transitional soy proto support: http://goto/soy-param-migration - * @return {!Object} - */ -proto.math.Num.prototype.toObject = function(opt_includeInstance) { - return proto.math.Num.toObject(opt_includeInstance, this); -}; - - -/** - * Static version of the {@see toObject} method. - * @param {boolean|undefined} includeInstance Whether to include the JSPB - * instance for transitional soy proto support: - * http://goto/soy-param-migration - * @param {!proto.math.Num} msg The msg instance to transform. - * @return {!Object} - */ -proto.math.Num.toObject = function(includeInstance, msg) { - var f, obj = { - num: msg.getNum() - }; - - if (includeInstance) { - obj.$jspbMessageInstance = msg; - } - return obj; -}; -} - - -/** - * Deserializes binary data (in protobuf wire format). - * @param {jspb.ByteSource} bytes The bytes to deserialize. - * @return {!proto.math.Num} - */ -proto.math.Num.deserializeBinary = function(bytes) { - var reader = new jspb.BinaryReader(bytes); - var msg = new proto.math.Num; - return proto.math.Num.deserializeBinaryFromReader(msg, reader); -}; - - -/** - * Deserializes binary data (in protobuf wire format) from the - * given reader into the given message object. - * @param {!proto.math.Num} msg The message object to deserialize into. - * @param {!jspb.BinaryReader} reader The BinaryReader to use. - * @return {!proto.math.Num} - */ -proto.math.Num.deserializeBinaryFromReader = function(msg, reader) { - while (reader.nextField()) { - if (reader.isEndGroup()) { - break; - } - var field = reader.getFieldNumber(); - switch (field) { - case 1: - var value = /** @type {number} */ (reader.readInt64()); - msg.setNum(value); - break; - default: - reader.skipField(); - break; - } - } - return msg; -}; - - -/** - * Class method variant: serializes the given message to binary data - * (in protobuf wire format), writing to the given BinaryWriter. - * @param {!proto.math.Num} message - * @param {!jspb.BinaryWriter} writer - */ -proto.math.Num.serializeBinaryToWriter = function(message, writer) { - message.serializeBinaryToWriter(writer); -}; - - -/** - * Serializes the message to binary data (in protobuf wire format). - * @return {!Uint8Array} - */ -proto.math.Num.prototype.serializeBinary = function() { - var writer = new jspb.BinaryWriter(); - this.serializeBinaryToWriter(writer); - return writer.getResultBuffer(); -}; - - -/** - * Serializes the message to binary data (in protobuf wire format), - * writing to the given BinaryWriter. - * @param {!jspb.BinaryWriter} writer - */ -proto.math.Num.prototype.serializeBinaryToWriter = function (writer) { - var f = undefined; - f = this.getNum(); - if (f !== 0) { - writer.writeInt64( - 1, - f - ); - } -}; - - -/** - * Creates a deep clone of this proto. No data is shared with the original. - * @return {!proto.math.Num} The clone. - */ -proto.math.Num.prototype.cloneMessage = function() { - return /** @type {!proto.math.Num} */ (jspb.Message.cloneMessage(this)); -}; - - -/** - * optional int64 num = 1; - * @return {number} - */ -proto.math.Num.prototype.getNum = function() { - return /** @type {number} */ (jspb.Message.getFieldProto3(this, 1, 0)); -}; - - -/** @param {number} value */ -proto.math.Num.prototype.setNum = function(value) { - jspb.Message.setField(this, 1, value); -}; - - - -/** - * Generated by JsPbCodeGenerator. - * @param {Array=} opt_data Optional initial data array, typically from a - * server response, or constructed directly in Javascript. The array is used - * in place and becomes part of the constructed object. It is not cloned. - * If no data is provided, the constructed object will be empty, but still - * valid. - * @extends {jspb.Message} - * @constructor - */ -proto.math.FibReply = function(opt_data) { - jspb.Message.initialize(this, opt_data, 0, -1, null, null); -}; -goog.inherits(proto.math.FibReply, jspb.Message); -if (goog.DEBUG && !COMPILED) { - proto.math.FibReply.displayName = 'proto.math.FibReply'; -} - - -if (jspb.Message.GENERATE_TO_OBJECT) { -/** - * Creates an object representation of this proto suitable for use in Soy templates. - * Field names that are reserved in JavaScript and will be renamed to pb_name. - * To access a reserved field use, foo.pb_, eg, foo.pb_default. - * For the list of reserved names please see: - * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. - * @param {boolean=} opt_includeInstance Whether to include the JSPB instance - * for transitional soy proto support: http://goto/soy-param-migration - * @return {!Object} - */ -proto.math.FibReply.prototype.toObject = function(opt_includeInstance) { - return proto.math.FibReply.toObject(opt_includeInstance, this); -}; - - -/** - * Static version of the {@see toObject} method. - * @param {boolean|undefined} includeInstance Whether to include the JSPB - * instance for transitional soy proto support: - * http://goto/soy-param-migration - * @param {!proto.math.FibReply} msg The msg instance to transform. - * @return {!Object} - */ -proto.math.FibReply.toObject = function(includeInstance, msg) { - var f, obj = { - count: msg.getCount() - }; - - if (includeInstance) { - obj.$jspbMessageInstance = msg; - } - return obj; -}; -} - - -/** - * Deserializes binary data (in protobuf wire format). - * @param {jspb.ByteSource} bytes The bytes to deserialize. - * @return {!proto.math.FibReply} - */ -proto.math.FibReply.deserializeBinary = function(bytes) { - var reader = new jspb.BinaryReader(bytes); - var msg = new proto.math.FibReply; - return proto.math.FibReply.deserializeBinaryFromReader(msg, reader); -}; - - -/** - * Deserializes binary data (in protobuf wire format) from the - * given reader into the given message object. - * @param {!proto.math.FibReply} msg The message object to deserialize into. - * @param {!jspb.BinaryReader} reader The BinaryReader to use. - * @return {!proto.math.FibReply} - */ -proto.math.FibReply.deserializeBinaryFromReader = function(msg, reader) { - while (reader.nextField()) { - if (reader.isEndGroup()) { - break; - } - var field = reader.getFieldNumber(); - switch (field) { - case 1: - var value = /** @type {number} */ (reader.readInt64()); - msg.setCount(value); - break; - default: - reader.skipField(); - break; - } - } - return msg; -}; - - -/** - * Class method variant: serializes the given message to binary data - * (in protobuf wire format), writing to the given BinaryWriter. - * @param {!proto.math.FibReply} message - * @param {!jspb.BinaryWriter} writer - */ -proto.math.FibReply.serializeBinaryToWriter = function(message, writer) { - message.serializeBinaryToWriter(writer); -}; - - -/** - * Serializes the message to binary data (in protobuf wire format). - * @return {!Uint8Array} - */ -proto.math.FibReply.prototype.serializeBinary = function() { - var writer = new jspb.BinaryWriter(); - this.serializeBinaryToWriter(writer); - return writer.getResultBuffer(); -}; - - -/** - * Serializes the message to binary data (in protobuf wire format), - * writing to the given BinaryWriter. - * @param {!jspb.BinaryWriter} writer - */ -proto.math.FibReply.prototype.serializeBinaryToWriter = function (writer) { - var f = undefined; - f = this.getCount(); - if (f !== 0) { - writer.writeInt64( - 1, - f - ); - } -}; - - -/** - * Creates a deep clone of this proto. No data is shared with the original. - * @return {!proto.math.FibReply} The clone. - */ -proto.math.FibReply.prototype.cloneMessage = function() { - return /** @type {!proto.math.FibReply} */ (jspb.Message.cloneMessage(this)); -}; - - -/** - * optional int64 count = 1; - * @return {number} - */ -proto.math.FibReply.prototype.getCount = function() { - return /** @type {number} */ (jspb.Message.getFieldProto3(this, 1, 0)); -}; - - -/** @param {number} value */ -proto.math.FibReply.prototype.setCount = function(value) { - jspb.Message.setField(this, 1, value); -}; - - -goog.object.extend(exports, proto.math); diff --git a/src/node/test/math/math_server.js b/src/node/test/math/math_server.js deleted file mode 100644 index 4291ae18b4a..00000000000 --- a/src/node/test/math/math_server.js +++ /dev/null @@ -1,124 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var grpc = require('../..'); -var grpcMath = require('./math_grpc_pb'); -var math = require('./math_pb'); - -/** - * Server function for division. Provides the /Math/DivMany and /Math/Div - * functions (Div is just DivMany with only one stream element). For each - * DivArgs parameter, responds with a DivReply with the results of the division - * @param {Object} call The object containing request and cancellation info - * @param {function(Error, *)} cb Response callback - */ -function mathDiv(call, cb) { - var req = call.request; - var divisor = req.getDivisor(); - var dividend = req.getDividend(); - // Unary + is explicit coersion to integer - if (req.getDivisor() === 0) { - cb(new Error('cannot divide by zero')); - } else { - var response = new math.DivReply(); - response.setQuotient(Math.floor(dividend / divisor)); - response.setRemainder(dividend % divisor); - cb(null, response); - } -} - -/** - * Server function for Fibonacci numbers. Provides the /Math/Fib function. Reads - * a single parameter that indicates the number of responses, and then responds - * with a stream of that many Fibonacci numbers. - * @param {stream} stream The stream for sending responses. - */ -function mathFib(stream) { - // Here, call is a standard writable Node object Stream - var previous = 0, current = 1; - for (var i = 0; i < stream.request.getLimit(); i++) { - var response = new math.Num(); - response.setNum(current); - stream.write(response); - var temp = current; - current += previous; - previous = temp; - } - stream.end(); -} - -/** - * Server function for summation. Provides the /Math/Sum function. Reads a - * stream of number parameters, then responds with their sum. - * @param {stream} call The stream of arguments. - * @param {function(Error, *)} cb Response callback - */ -function mathSum(call, cb) { - // Here, call is a standard readable Node object Stream - var sum = 0; - call.on('data', function(data) { - sum += data.getNum(); - }); - call.on('end', function() { - var response = new math.Num(); - response.setNum(sum); - cb(null, response); - }); -} - -function mathDivMany(stream) { - stream.on('data', function(div_args) { - var divisor = div_args.getDivisor(); - var dividend = div_args.getDividend(); - if (divisor === 0) { - stream.emit('error', new Error('cannot divide by zero')); - } else { - var response = new math.DivReply(); - response.setQuotient(Math.floor(dividend / divisor)); - response.setRemainder(dividend % divisor); - stream.write(response); - } - }); - stream.on('end', function() { - stream.end(); - }); -} - -function getMathServer() { - var server = new grpc.Server(); - server.addService(grpcMath.MathService, { - div: mathDiv, - fib: mathFib, - sum: mathSum, - divMany: mathDivMany - }); - return server; -} - -if (require.main === module) { - var server = getMathServer(); - server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure()); - server.start(); -} - -/** - * See docs for server - */ -module.exports = getMathServer; diff --git a/src/node/test/math/node_modules/grpc.js b/src/node/test/math/node_modules/grpc.js deleted file mode 100644 index b824d8ddc69..00000000000 --- a/src/node/test/math/node_modules/grpc.js +++ /dev/null @@ -1,22 +0,0 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/* This exists solely to allow the generated code to import the grpc module - * without using a relative path */ - -module.exports = require('../../..'); diff --git a/src/node/test/math_client_test.js b/src/node/test/math_client_test.js deleted file mode 100644 index 11deda34f14..00000000000 --- a/src/node/test/math_client_test.js +++ /dev/null @@ -1,140 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var assert = require('assert'); - -var grpc = require('..'); -var math = require('./math/math_pb'); -var MathClient = require('./math/math_grpc_pb').MathClient; - -/** - * Client to use to make requests to a running server. - */ -var math_client; - -/** - * Server to test against - */ -var getServer = require('./math/math_server.js'); - -var server = getServer(); - -describe('Math client', function() { - before(function(done) { - var port_num = server.bind('0.0.0.0:0', - grpc.ServerCredentials.createInsecure()); - server.start(); - math_client = new MathClient('localhost:' + port_num, - grpc.credentials.createInsecure()); - done(); - }); - after(function() { - server.forceShutdown(); - }); - it('should handle a single request', function(done) { - var arg = new math.DivArgs(); - arg.setDividend(7); - arg.setDivisor(4); - math_client.div(arg, function handleDivResult(err, value) { - assert.ifError(err); - assert.equal(value.getQuotient(), 1); - assert.equal(value.getRemainder(), 3); - done(); - }); - }); - it('should handle an error from a unary request', function(done) { - var arg = new math.DivArgs(); - arg.setDividend(7); - arg.setDivisor(0); - math_client.div(arg, function handleDivResult(err, value) { - assert(err); - done(); - }); - }); - it('should handle a server streaming request', function(done) { - var arg = new math.FibArgs(); - arg.setLimit(7); - var call = math_client.fib(arg); - var expected_results = [1, 1, 2, 3, 5, 8, 13]; - var next_expected = 0; - call.on('data', function checkResponse(value) { - assert.equal(value.getNum(), expected_results[next_expected]); - next_expected += 1; - }); - call.on('status', function checkStatus(status) { - assert.strictEqual(status.code, grpc.status.OK); - done(); - }); - }); - it('should handle a client streaming request', function(done) { - var call = math_client.sum(function handleSumResult(err, value) { - assert.ifError(err); - assert.equal(value.getNum(), 21); - }); - for (var i = 0; i < 7; i++) { - var arg = new math.Num(); - arg.setNum(i); - call.write(arg); - } - call.end(); - call.on('status', function checkStatus(status) { - assert.strictEqual(status.code, grpc.status.OK); - done(); - }); - }); - it('should handle a bidirectional streaming request', function(done) { - function checkResponse(index, value) { - assert.equal(value.getQuotient(), index); - assert.equal(value.getRemainder(), 1); - } - var call = math_client.divMany(); - var response_index = 0; - call.on('data', function(value) { - checkResponse(response_index, value); - response_index += 1; - }); - for (var i = 0; i < 7; i++) { - var arg = new math.DivArgs(); - arg.setDividend(2 * i + 1); - arg.setDivisor(2); - call.write(arg); - } - call.end(); - call.on('status', function checkStatus(status) { - assert.strictEqual(status.code, grpc.status.OK); - done(); - }); - }); - it('should handle an error from a bidi request', function(done) { - var call = math_client.divMany(); - call.on('data', function(value) { - assert.fail(value, undefined, 'Unexpected data response on failing call', - '!='); - }); - var arg = new math.DivArgs(); - arg.setDividend(7); - arg.setDivisor(0); - call.write(arg); - call.end(); - call.on('error', function checkStatus(status) { - done(); - }); - }); -}); diff --git a/src/node/test/metadata_test.js b/src/node/test/metadata_test.js deleted file mode 100644 index 4ba54e0aa00..00000000000 --- a/src/node/test/metadata_test.js +++ /dev/null @@ -1,178 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var Metadata = require('../src/metadata.js'); - -var assert = require('assert'); - -describe('Metadata', function() { - var metadata; - beforeEach(function() { - metadata = new Metadata(); - }); - describe('#set', function() { - it('Only accepts string values for non "-bin" keys', function() { - assert.throws(function() { - metadata.set('key', new Buffer('value')); - }); - assert.doesNotThrow(function() { - metadata.set('key', 'value'); - }); - }); - it('Only accepts Buffer values for "-bin" keys', function() { - assert.throws(function() { - metadata.set('key-bin', 'value'); - }); - assert.doesNotThrow(function() { - metadata.set('key-bin', new Buffer('value')); - }); - }); - it('Rejects invalid keys', function() { - assert.throws(function() { - metadata.set('key$', 'value'); - }); - assert.throws(function() { - metadata.set('', 'value'); - }); - }); - it('Rejects values with non-ASCII characters', function() { - assert.throws(function() { - metadata.set('key', 'résumé'); - }); - }); - it('Saves values that can be retrieved', function() { - metadata.set('key', 'value'); - assert.deepEqual(metadata.get('key'), ['value']); - }); - it('Overwrites previous values', function() { - metadata.set('key', 'value1'); - metadata.set('key', 'value2'); - assert.deepEqual(metadata.get('key'), ['value2']); - }); - it('Normalizes keys', function() { - metadata.set('Key', 'value1'); - assert.deepEqual(metadata.get('key'), ['value1']); - metadata.set('KEY', 'value2'); - assert.deepEqual(metadata.get('key'), ['value2']); - }); - }); - describe('#add', function() { - it('Only accepts string values for non "-bin" keys', function() { - assert.throws(function() { - metadata.add('key', new Buffer('value')); - }); - assert.doesNotThrow(function() { - metadata.add('key', 'value'); - }); - }); - it('Only accepts Buffer values for "-bin" keys', function() { - assert.throws(function() { - metadata.add('key-bin', 'value'); - }); - assert.doesNotThrow(function() { - metadata.add('key-bin', new Buffer('value')); - }); - }); - it('Rejects invalid keys', function() { - assert.throws(function() { - metadata.add('key$', 'value'); - }); - assert.throws(function() { - metadata.add('', 'value'); - }); - }); - it('Saves values that can be retrieved', function() { - metadata.add('key', 'value'); - assert.deepEqual(metadata.get('key'), ['value']); - }); - it('Combines with previous values', function() { - metadata.add('key', 'value1'); - metadata.add('key', 'value2'); - assert.deepEqual(metadata.get('key'), ['value1', 'value2']); - }); - it('Normalizes keys', function() { - metadata.add('Key', 'value1'); - assert.deepEqual(metadata.get('key'), ['value1']); - metadata.add('KEY', 'value2'); - assert.deepEqual(metadata.get('key'), ['value1', 'value2']); - }); - }); - describe('#remove', function() { - it('clears values from a key', function() { - metadata.add('key', 'value'); - metadata.remove('key'); - assert.deepEqual(metadata.get('key'), []); - }); - it('Normalizes keys', function() { - metadata.add('key', 'value'); - metadata.remove('KEY'); - assert.deepEqual(metadata.get('key'), []); - }); - }); - describe('#get', function() { - beforeEach(function() { - metadata.add('key', 'value1'); - metadata.add('key', 'value2'); - metadata.add('key-bin', new Buffer('value')); - }); - it('gets all values associated with a key', function() { - assert.deepEqual(metadata.get('key'), ['value1', 'value2']); - }); - it('Normalizes keys', function() { - assert.deepEqual(metadata.get('KEY'), ['value1', 'value2']); - }); - it('returns an empty list for non-existent keys', function() { - assert.deepEqual(metadata.get('non-existent-key'), []); - }); - it('returns Buffers for "-bin" keys', function() { - assert(metadata.get('key-bin')[0] instanceof Buffer); - }); - }); - describe('#getMap', function() { - it('gets a map of keys to values', function() { - metadata.add('key1', 'value1'); - metadata.add('Key2', 'value2'); - metadata.add('KEY3', 'value3'); - assert.deepEqual(metadata.getMap(), - {key1: 'value1', - key2: 'value2', - key3: 'value3'}); - }); - }); - describe('#clone', function() { - it('retains values from the original', function() { - metadata.add('key', 'value'); - var copy = metadata.clone(); - assert.deepEqual(copy.get('key'), ['value']); - }); - it('Does not see newly added values', function() { - metadata.add('key', 'value1'); - var copy = metadata.clone(); - metadata.add('key', 'value2'); - assert.deepEqual(copy.get('key'), ['value1']); - }); - it('Does not add new values to the original', function() { - metadata.add('key', 'value1'); - var copy = metadata.clone(); - copy.add('key', 'value2'); - assert.deepEqual(metadata.get('key'), ['value1']); - }); - }); -}); diff --git a/src/node/test/numbers.txt b/src/node/test/numbers.txt deleted file mode 100644 index 4972919b4e3..00000000000 --- a/src/node/test/numbers.txt +++ /dev/null @@ -1,496 +0,0 @@ -1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 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 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 diff --git a/src/node/test/server_test.js b/src/node/test/server_test.js deleted file mode 100644 index 454acbda1dc..00000000000 --- a/src/node/test/server_test.js +++ /dev/null @@ -1,138 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); -var grpc = require('../src/grpc_extension'); - -describe('server', function() { - describe('constructor', function() { - it('should work with no arguments', function() { - assert.doesNotThrow(function() { - new grpc.Server(); - }); - }); - it('should work with an empty object argument', function() { - assert.doesNotThrow(function() { - new grpc.Server({}); - }); - }); - it('should work without the new keyword', function() { - var server; - assert.doesNotThrow(function() { - server = grpc.Server(); - }); - assert(server instanceof grpc.Server); - }); - it('should only accept objects with string or int values', function() { - assert.doesNotThrow(function() { - new grpc.Server({'key' : 'value'}); - }); - assert.doesNotThrow(function() { - new grpc.Server({'key' : 5}); - }); - assert.throws(function() { - new grpc.Server({'key' : null}); - }); - assert.throws(function() { - new grpc.Server({'key' : new Date()}); - }); - }); - }); - describe('addHttp2Port', function() { - var server; - before(function() { - server = new grpc.Server(); - }); - it('should bind to an unused port', function() { - var port; - assert.doesNotThrow(function() { - port = server.addHttp2Port('0.0.0.0:0', - grpc.ServerCredentials.createInsecure()); - }); - assert(port > 0); - }); - it('should bind to an unused port with ssl credentials', function() { - var port; - var key_path = path.join(__dirname, '../test/data/server1.key'); - var pem_path = path.join(__dirname, '../test/data/server1.pem'); - var key_data = fs.readFileSync(key_path); - var pem_data = fs.readFileSync(pem_path); - var creds = grpc.ServerCredentials.createSsl(null, - [{private_key: key_data, - cert_chain: pem_data}]); - assert.doesNotThrow(function() { - port = server.addHttp2Port('0.0.0.0:0', creds); - }); - assert(port > 0); - }); - }); - describe('addSecureHttp2Port', function() { - var server; - before(function() { - server = new grpc.Server(); - }); - }); - describe('start', function() { - var server; - before(function() { - server = new grpc.Server(); - server.addHttp2Port('0.0.0.0:0', grpc.ServerCredentials.createInsecure()); - }); - after(function() { - server.forceShutdown(); - }); - it('should start without error', function() { - assert.doesNotThrow(function() { - server.start(); - }); - }); - }); - describe('shutdown', function() { - var server; - beforeEach(function() { - server = new grpc.Server(); - server.addHttp2Port('0.0.0.0:0', grpc.ServerCredentials.createInsecure()); - server.start(); - }); - afterEach(function() { - server.forceShutdown(); - }); - it('tryShutdown should shutdown successfully', function(done) { - server.tryShutdown(done); - }); - it('forceShutdown should shutdown successfully', function() { - server.forceShutdown(); - }); - it('tryShutdown should be idempotent', function(done) { - server.tryShutdown(done); - server.tryShutdown(function() {}); - }); - it('forceShutdown should be idempotent', function() { - server.forceShutdown(); - server.forceShutdown(); - }); - it('forceShutdown should trigger tryShutdown', function(done) { - server.tryShutdown(done); - server.forceShutdown(); - }); - }); -}); diff --git a/src/node/test/surface_test.js b/src/node/test/surface_test.js deleted file mode 100644 index 0b0b393e323..00000000000 --- a/src/node/test/surface_test.js +++ /dev/null @@ -1,1424 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -'use strict'; - -var assert = require('assert'); -var _ = require('lodash'); - -var surface_client = require('../src/client.js'); -var common = require('../src/common'); - -var ProtoBuf = require('protobufjs'); - -var grpc = require('..'); - -var math_proto = ProtoBuf.loadProtoFile(__dirname + - '/../../proto/math/math.proto'); - -var mathService = math_proto.lookup('math.Math'); -var mathServiceAttrs = grpc.loadObject( - mathService, common.defaultGrpcOptions).service; - -/** - * This is used for testing functions with multiple asynchronous calls that - * can happen in different orders. This should be passed the number of async - * function invocations that can occur last, and each of those should call this - * function's return value - * @param {function()} done The function that should be called when a test is - * complete. - * @param {number} count The number of calls to the resulting function if the - * test passes. - * @return {function()} The function that should be called at the end of each - * sequence of asynchronous functions. - */ -function multiDone(done, count) { - return function() { - count -= 1; - if (count <= 0) { - done(); - } - }; -} - -var server_insecure_creds = grpc.ServerCredentials.createInsecure(); - -describe('File loader', function() { - it('Should load a proto file by default', function() { - assert.doesNotThrow(function() { - grpc.load(__dirname + '/test_service.proto'); - }); - }); - it('Should load a proto file with the proto format', function() { - assert.doesNotThrow(function() { - grpc.load(__dirname + '/test_service.proto', 'proto'); - }); - }); - it('Should load a json file with the json format', function() { - assert.doesNotThrow(function() { - grpc.load(__dirname + '/test_service.json', 'json'); - }); - }); -}); -describe('surface Server', function() { - var server; - beforeEach(function() { - server = new grpc.Server(); - }); - afterEach(function() { - server.forceShutdown(); - }); - it('should error if started twice', function() { - server.start(); - assert.throws(function() { - server.start(); - }); - }); - it('should error if a port is bound after the server starts', function() { - server.start(); - assert.throws(function() { - server.bind('localhost:0', grpc.ServerCredentials.createInsecure()); - }); - }); - it('should successfully shutdown if tryShutdown is called', function(done) { - server.start(); - server.tryShutdown(done); - }); -}); -describe('Server.prototype.addProtoService', function() { - var server; - var dummyImpls = { - 'div': function() {}, - 'divMany': function() {}, - 'fib': function() {}, - 'sum': function() {} - }; - beforeEach(function() { - server = new grpc.Server(); - }); - afterEach(function() { - server.forceShutdown(); - }); - it('Should succeed with a single proto service', function() { - assert.doesNotThrow(function() { - server.addProtoService(mathService, dummyImpls); - }); - }); - it('Should succeed with a single service attributes object', function() { - assert.doesNotThrow(function() { - server.addProtoService(mathServiceAttrs, dummyImpls); - }); - }); -}); -describe('Server.prototype.addService', function() { - var server; - var dummyImpls = { - 'div': function() {}, - 'divMany': function() {}, - 'fib': function() {}, - 'sum': function() {} - }; - beforeEach(function() { - server = new grpc.Server(); - }); - afterEach(function() { - server.forceShutdown(); - }); - it('Should succeed with a single service', function() { - assert.doesNotThrow(function() { - server.addService(mathServiceAttrs, dummyImpls); - }); - }); - it('Should fail with conflicting method names', function() { - server.addService(mathServiceAttrs, dummyImpls); - assert.throws(function() { - server.addService(mathServiceAttrs, dummyImpls); - }); - }); - it('Should allow method names as originally written', function() { - var altDummyImpls = { - 'Div': function() {}, - 'DivMany': function() {}, - 'Fib': function() {}, - 'Sum': function() {} - }; - assert.doesNotThrow(function() { - server.addProtoService(mathService, altDummyImpls); - }); - }); - it('Should have a conflict between name variations', function() { - /* This is really testing that both name variations are actually used, - by checking that the method actually gets registered, for the - corresponding function, in both cases */ - var altDummyImpls = { - 'Div': function() {}, - 'DivMany': function() {}, - 'Fib': function() {}, - 'Sum': function() {} - }; - server.addProtoService(mathService, altDummyImpls); - assert.throws(function() { - server.addProtoService(mathService, dummyImpls); - }); - }); - it('Should fail if the server has been started', function() { - server.start(); - assert.throws(function() { - server.addService(mathServiceAttrs, dummyImpls); - }); - }); - describe('Default handlers', function() { - var client; - beforeEach(function() { - server.addService(mathServiceAttrs, {}); - var port = server.bind('localhost:0', server_insecure_creds); - var Client = grpc.loadObject(mathService); - client = new Client('localhost:' + port, - grpc.credentials.createInsecure()); - server.start(); - }); - it('should respond to a unary call with UNIMPLEMENTED', function(done) { - client.div({divisor: 4, dividend: 3}, function(error, response) { - assert(error); - assert.strictEqual(error.code, grpc.status.UNIMPLEMENTED); - done(); - }); - }); - it('should respond to a client stream with UNIMPLEMENTED', function(done) { - var call = client.sum(function(error, respones) { - assert(error); - assert.strictEqual(error.code, grpc.status.UNIMPLEMENTED); - done(); - }); - call.end(); - }); - it('should respond to a server stream with UNIMPLEMENTED', function(done) { - var call = client.fib({limit: 5}); - call.on('data', function(value) { - assert.fail('No messages expected'); - }); - call.on('error', function(err) { - assert.strictEqual(err.code, grpc.status.UNIMPLEMENTED); - done(); - }); - call.on('error', function(status) { /* Do nothing */ }); - }); - it('should respond to a bidi call with UNIMPLEMENTED', function(done) { - var call = client.divMany(); - call.on('data', function(value) { - assert.fail('No messages expected'); - }); - call.on('error', function(err) { - assert.strictEqual(err.code, grpc.status.UNIMPLEMENTED); - done(); - }); - call.on('error', function(status) { /* Do nothing */ }); - call.end(); - }); - }); -}); -describe('Client constructor building', function() { - var illegal_service_attrs = { - $method : { - path: '/illegal/$method', - requestStream: false, - responseStream: false, - requestSerialize: _.identity, - requestDeserialize: _.identity, - responseSerialize: _.identity, - responseDeserialize: _.identity - } - }; - it('Should reject method names starting with $', function() { - assert.throws(function() { - grpc.makeGenericClientConstructor(illegal_service_attrs); - }, /\$/); - }); -}); -describe('waitForClientReady', function() { - var server; - var port; - var Client; - var client; - before(function() { - server = new grpc.Server(); - port = server.bind('localhost:0', grpc.ServerCredentials.createInsecure()); - server.start(); - Client = grpc.loadObject(mathService); - }); - beforeEach(function() { - client = new Client('localhost:' + port, grpc.credentials.createInsecure()); - }); - after(function() { - server.forceShutdown(); - }); - it('should complete when called alone', function(done) { - grpc.waitForClientReady(client, Infinity, function(error) { - assert.ifError(error); - done(); - }); - }); - it('should complete when a call is initiated', function(done) { - grpc.waitForClientReady(client, Infinity, function(error) { - assert.ifError(error); - done(); - }); - var call = client.div({}, function(err, response) {}); - call.cancel(); - }); - it('should complete if called more than once', function(done) { - done = multiDone(done, 2); - grpc.waitForClientReady(client, Infinity, function(error) { - assert.ifError(error); - done(); - }); - grpc.waitForClientReady(client, Infinity, function(error) { - assert.ifError(error); - done(); - }); - }); - it('should complete if called when already ready', function(done) { - grpc.waitForClientReady(client, Infinity, function(error) { - assert.ifError(error); - grpc.waitForClientReady(client, Infinity, function(error) { - assert.ifError(error); - done(); - }); - }); - }); - it('should time out if the server does not exist', function(done) { - var bad_client = new Client('nonexistent_hostname', - grpc.credentials.createInsecure()); - var deadline = new Date(); - deadline.setSeconds(deadline.getSeconds() + 1); - grpc.waitForClientReady(bad_client, deadline, function(error) { - assert(error); - done(); - }); - }); -}); -describe('Echo service', function() { - var server; - var client; - before(function() { - var test_proto = ProtoBuf.loadProtoFile(__dirname + '/echo_service.proto'); - var echo_service = test_proto.lookup('EchoService'); - var Client = grpc.loadObject(echo_service); - server = new grpc.Server(); - server.addService(Client.service, { - echo: function(call, callback) { - callback(null, call.request); - } - }); - var port = server.bind('localhost:0', server_insecure_creds); - client = new Client('localhost:' + port, grpc.credentials.createInsecure()); - server.start(); - }); - after(function() { - server.forceShutdown(); - }); - it('should echo the recieved message directly', function(done) { - client.echo({value: 'test value', value2: 3}, function(error, response) { - assert.ifError(error); - assert.deepEqual(response, {value: 'test value', value2: 3}); - done(); - }); - }); - it('Should convert an undefined argument to default values', function(done) { - client.echo(undefined, function(error, response) { - assert.ifError(error); - assert.deepEqual(response, {value: '', value2: 0}); - done(); - }); - }); -}); -describe('Generic client and server', function() { - function toString(val) { - return val.toString(); - } - function toBuffer(str) { - return new Buffer(str); - } - var string_service_attrs = { - 'capitalize' : { - path: '/string/capitalize', - requestStream: false, - responseStream: false, - requestSerialize: toBuffer, - requestDeserialize: toString, - responseSerialize: toBuffer, - responseDeserialize: toString - } - }; - describe('String client and server', function() { - var client; - var server; - before(function() { - server = new grpc.Server(); - server.addService(string_service_attrs, { - capitalize: function(call, callback) { - callback(null, _.capitalize(call.request)); - } - }); - var port = server.bind('localhost:0', server_insecure_creds); - server.start(); - var Client = grpc.makeGenericClientConstructor(string_service_attrs); - client = new Client('localhost:' + port, - grpc.credentials.createInsecure()); - }); - after(function() { - server.forceShutdown(); - }); - it('Should respond with a capitalized string', function(done) { - client.capitalize('abc', function(err, response) { - assert.ifError(err); - assert.strictEqual(response, 'Abc'); - done(); - }); - }); - }); -}); -describe('Server-side getPeer', function() { - function toString(val) { - return val.toString(); - } - function toBuffer(str) { - return new Buffer(str); - } - var string_service_attrs = { - 'getPeer' : { - path: '/string/getPeer', - requestStream: false, - responseStream: false, - requestSerialize: toBuffer, - requestDeserialize: toString, - responseSerialize: toBuffer, - responseDeserialize: toString - } - }; - var client; - var server; - before(function() { - server = new grpc.Server(); - server.addService(string_service_attrs, { - getPeer: function(call, callback) { - try { - callback(null, call.getPeer()); - } catch (e) { - call.emit('error', e); - } - } - }); - var port = server.bind('localhost:0', server_insecure_creds); - server.start(); - var Client = grpc.makeGenericClientConstructor(string_service_attrs); - client = new Client('localhost:' + port, - grpc.credentials.createInsecure()); - }); - after(function() { - server.forceShutdown(); - }); - it('should respond with a string representing the client', function(done) { - client.getPeer('', function(err, response) { - assert.ifError(err); - // We don't expect a specific value, just that it worked without error - done(); - }); - }); -}); -describe('Echo metadata', function() { - var client; - var server; - var metadata; - before(function() { - var test_proto = ProtoBuf.loadProtoFile(__dirname + '/test_service.proto'); - var test_service = test_proto.lookup('TestService'); - var Client = grpc.loadObject(test_service); - server = new grpc.Server(); - server.addService(Client.service, { - unary: function(call, cb) { - call.sendMetadata(call.metadata); - cb(null, {}); - }, - clientStream: function(stream, cb){ - stream.on('data', function(data) {}); - stream.on('end', function() { - stream.sendMetadata(stream.metadata); - cb(null, {}); - }); - }, - serverStream: function(stream) { - stream.sendMetadata(stream.metadata); - stream.end(); - }, - bidiStream: function(stream) { - stream.on('data', function(data) {}); - stream.on('end', function() { - stream.sendMetadata(stream.metadata); - stream.end(); - }); - } - }); - var port = server.bind('localhost:0', server_insecure_creds); - client = new Client('localhost:' + port, grpc.credentials.createInsecure()); - server.start(); - metadata = new grpc.Metadata(); - metadata.set('key', 'value'); - }); - after(function() { - server.forceShutdown(); - }); - it('with unary call', function(done) { - var call = client.unary({}, metadata, function(err, data) { - assert.ifError(err); - }); - call.on('metadata', function(metadata) { - assert.deepEqual(metadata.get('key'), ['value']); - done(); - }); - }); - it('with client stream call', function(done) { - var call = client.clientStream(metadata, function(err, data) { - assert.ifError(err); - }); - call.on('metadata', function(metadata) { - assert.deepEqual(metadata.get('key'), ['value']); - done(); - }); - call.end(); - }); - it('with server stream call', function(done) { - var call = client.serverStream({}, metadata); - call.on('data', function() {}); - call.on('metadata', function(metadata) { - assert.deepEqual(metadata.get('key'), ['value']); - done(); - }); - }); - it('with bidi stream call', function(done) { - var call = client.bidiStream(metadata); - call.on('data', function() {}); - call.on('metadata', function(metadata) { - assert.deepEqual(metadata.get('key'), ['value']); - done(); - }); - call.end(); - }); - it('shows the correct user-agent string', function(done) { - var version = require('../../../package.json').version; - var call = client.unary({}, metadata, - function(err, data) { assert.ifError(err); }); - call.on('metadata', function(metadata) { - assert(_.startsWith(metadata.get('user-agent')[0], - 'grpc-node/' + version)); - done(); - }); - }); - it('properly handles duplicate values', function(done) { - var dup_metadata = metadata.clone(); - dup_metadata.add('key', 'value2'); - var call = client.unary({}, dup_metadata, - function(err, data) {assert.ifError(err); }); - call.on('metadata', function(resp_metadata) { - // Two arrays are equal iff their symmetric difference is empty - assert.deepEqual(_.xor(dup_metadata.get('key'), resp_metadata.get('key')), - []); - done(); - }); - }); -}); -describe('Client malformed response handling', function() { - var server; - var client; - var badArg = new Buffer([0xFF]); - before(function() { - var test_proto = ProtoBuf.loadProtoFile(__dirname + '/test_service.proto'); - var test_service = test_proto.lookup('TestService'); - var malformed_test_service = { - unary: { - path: '/TestService/Unary', - requestStream: false, - responseStream: false, - requestDeserialize: _.identity, - responseSerialize: _.identity - }, - clientStream: { - path: '/TestService/ClientStream', - requestStream: true, - responseStream: false, - requestDeserialize: _.identity, - responseSerialize: _.identity - }, - serverStream: { - path: '/TestService/ServerStream', - requestStream: false, - responseStream: true, - requestDeserialize: _.identity, - responseSerialize: _.identity - }, - bidiStream: { - path: '/TestService/BidiStream', - requestStream: true, - responseStream: true, - requestDeserialize: _.identity, - responseSerialize: _.identity - } - }; - server = new grpc.Server(); - server.addService(malformed_test_service, { - unary: function(call, cb) { - cb(null, badArg); - }, - clientStream: function(stream, cb) { - stream.on('data', function() {/* Ignore requests */}); - stream.on('end', function() { - cb(null, badArg); - }); - }, - serverStream: function(stream) { - stream.write(badArg); - stream.end(); - }, - bidiStream: function(stream) { - stream.on('data', function() { - // Ignore requests - stream.write(badArg); - }); - stream.on('end', function() { - stream.end(); - }); - } - }); - var port = server.bind('localhost:0', server_insecure_creds); - var Client = grpc.loadObject(test_service); - client = new Client('localhost:' + port, grpc.credentials.createInsecure()); - server.start(); - }); - after(function() { - server.forceShutdown(); - }); - it('should get an INTERNAL status with a unary call', function(done) { - client.unary({}, function(err, data) { - assert(err); - assert.strictEqual(err.code, grpc.status.INTERNAL); - done(); - }); - }); - it('should get an INTERNAL status with a client stream call', function(done) { - var call = client.clientStream(function(err, data) { - assert(err); - assert.strictEqual(err.code, grpc.status.INTERNAL); - done(); - }); - call.write({}); - call.end(); - }); - it('should get an INTERNAL status with a server stream call', function(done) { - var call = client.serverStream({}); - call.on('data', function(){}); - call.on('error', function(err) { - assert.strictEqual(err.code, grpc.status.INTERNAL); - done(); - }); - }); - it('should get an INTERNAL status with a bidi stream call', function(done) { - var call = client.bidiStream(); - call.on('data', function(){}); - call.on('error', function(err) { - assert.strictEqual(err.code, grpc.status.INTERNAL); - done(); - }); - call.write({}); - call.end(); - }); -}); -describe('Server serialization failure handling', function() { - function serializeFail(obj) { - throw new Error('Serialization failed'); - } - var client; - var server; - before(function() { - var test_proto = ProtoBuf.loadProtoFile(__dirname + '/test_service.proto'); - var test_service = test_proto.lookup('TestService'); - var malformed_test_service = { - unary: { - path: '/TestService/Unary', - requestStream: false, - responseStream: false, - requestDeserialize: _.identity, - responseSerialize: serializeFail - }, - clientStream: { - path: '/TestService/ClientStream', - requestStream: true, - responseStream: false, - requestDeserialize: _.identity, - responseSerialize: serializeFail - }, - serverStream: { - path: '/TestService/ServerStream', - requestStream: false, - responseStream: true, - requestDeserialize: _.identity, - responseSerialize: serializeFail - }, - bidiStream: { - path: '/TestService/BidiStream', - requestStream: true, - responseStream: true, - requestDeserialize: _.identity, - responseSerialize: serializeFail - } - }; - server = new grpc.Server(); - server.addService(malformed_test_service, { - unary: function(call, cb) { - cb(null, {}); - }, - clientStream: function(stream, cb) { - stream.on('data', function() {/* Ignore requests */}); - stream.on('end', function() { - cb(null, {}); - }); - }, - serverStream: function(stream) { - stream.write({}); - stream.end(); - }, - bidiStream: function(stream) { - stream.on('data', function() { - // Ignore requests - stream.write({}); - }); - stream.on('end', function() { - stream.end(); - }); - } - }); - var port = server.bind('localhost:0', server_insecure_creds); - var Client = grpc.loadObject(test_service); - client = new Client('localhost:' + port, grpc.credentials.createInsecure()); - server.start(); - }); - after(function() { - server.forceShutdown(); - }); - it('should get an INTERNAL status with a unary call', function(done) { - client.unary({}, function(err, data) { - assert(err); - assert.strictEqual(err.code, grpc.status.INTERNAL); - done(); - }); - }); - it('should get an INTERNAL status with a client stream call', function(done) { - var call = client.clientStream(function(err, data) { - assert(err); - assert.strictEqual(err.code, grpc.status.INTERNAL); - done(); - }); - call.write({}); - call.end(); - }); - it('should get an INTERNAL status with a server stream call', function(done) { - var call = client.serverStream({}); - call.on('data', function(){}); - call.on('error', function(err) { - assert.strictEqual(err.code, grpc.status.INTERNAL); - done(); - }); - }); - it('should get an INTERNAL status with a bidi stream call', function(done) { - var call = client.bidiStream(); - call.on('data', function(){}); - call.on('error', function(err) { - assert.strictEqual(err.code, grpc.status.INTERNAL); - done(); - }); - call.write({}); - call.end(); - }); -}); -describe('Other conditions', function() { - var Client; - var client; - var server; - var port; - before(function() { - var test_proto = ProtoBuf.loadProtoFile(__dirname + '/test_service.proto'); - var test_service = test_proto.lookup('TestService'); - Client = grpc.loadObject(test_service); - server = new grpc.Server(); - var trailer_metadata = new grpc.Metadata(); - trailer_metadata.add('trailer-present', 'yes'); - server.addService(Client.service, { - unary: function(call, cb) { - var req = call.request; - if (req.error) { - cb({code: grpc.status.UNKNOWN, - details: 'Requested error'}, null, trailer_metadata); - } else { - cb(null, {count: 1}, trailer_metadata); - } - }, - clientStream: function(stream, cb){ - var count = 0; - var errored; - stream.on('data', function(data) { - if (data.error) { - errored = true; - cb(new Error('Requested error'), null, trailer_metadata); - } else { - count += 1; - } - }); - stream.on('end', function() { - if (!errored) { - cb(null, {count: count}, trailer_metadata); - } - }); - }, - serverStream: function(stream) { - var req = stream.request; - if (req.error) { - var err = {code: grpc.status.UNKNOWN, - details: 'Requested error'}; - err.metadata = trailer_metadata; - stream.emit('error', err); - } else { - for (var i = 0; i < 5; i++) { - stream.write({count: i}); - } - stream.end(trailer_metadata); - } - }, - bidiStream: function(stream) { - var count = 0; - stream.on('data', function(data) { - if (data.error) { - var err = new Error('Requested error'); - err.metadata = trailer_metadata.clone(); - err.metadata.add('count', '' + count); - stream.emit('error', err); - } else { - stream.write({count: count}); - count += 1; - } - }); - stream.on('end', function() { - stream.end(trailer_metadata); - }); - } - }); - port = server.bind('localhost:0', server_insecure_creds); - client = new Client('localhost:' + port, grpc.credentials.createInsecure()); - server.start(); - }); - after(function() { - server.forceShutdown(); - }); - it('channel.getTarget should be available', function() { - assert.strictEqual(typeof grpc.getClientChannel(client).getTarget(), - 'string'); - }); - it('client should be able to pause and resume a stream', function(done) { - var call = client.bidiStream(); - call.on('data', function(data) { - assert(data.count < 3); - call.pause(); - setTimeout(function() { - call.resume(); - }, 10); - }); - call.on('end', function() { - done(); - }); - call.write({}); - call.write({}); - call.write({}); - call.end(); - }); - describe('Server recieving bad input', function() { - var misbehavingClient; - var badArg = new Buffer([0xFF]); - before(function() { - var test_service_attrs = { - unary: { - path: '/TestService/Unary', - requestStream: false, - responseStream: false, - requestSerialize: _.identity, - responseDeserialize: _.identity - }, - clientStream: { - path: '/TestService/ClientStream', - requestStream: true, - responseStream: false, - requestSerialize: _.identity, - responseDeserialize: _.identity - }, - serverStream: { - path: '/TestService/ServerStream', - requestStream: false, - responseStream: true, - requestSerialize: _.identity, - responseDeserialize: _.identity - }, - bidiStream: { - path: '/TestService/BidiStream', - requestStream: true, - responseStream: true, - requestSerialize: _.identity, - responseDeserialize: _.identity - } - }; - var Client = surface_client.makeClientConstructor(test_service_attrs, - 'TestService'); - misbehavingClient = new Client('localhost:' + port, - grpc.credentials.createInsecure()); - }); - it('should respond correctly to a unary call', function(done) { - misbehavingClient.unary(badArg, function(err, data) { - assert(err); - assert.strictEqual(err.code, grpc.status.INTERNAL); - done(); - }); - }); - it('should respond correctly to a client stream', function(done) { - var call = misbehavingClient.clientStream(function(err, data) { - assert(err); - assert.strictEqual(err.code, grpc.status.INTERNAL); - done(); - }); - call.write(badArg); - // TODO(mlumish): Remove call.end() - call.end(); - }); - it('should respond correctly to a server stream', function(done) { - var call = misbehavingClient.serverStream(badArg); - call.on('data', function(data) { - assert.fail(data, null, 'Unexpected data', '==='); - }); - call.on('error', function(err) { - assert.strictEqual(err.code, grpc.status.INTERNAL); - done(); - }); - }); - it('should respond correctly to a bidi stream', function(done) { - var call = misbehavingClient.bidiStream(); - call.on('data', function(data) { - assert.fail(data, null, 'Unexpected data', '==='); - }); - call.on('error', function(err) { - assert.strictEqual(err.code, grpc.status.INTERNAL); - done(); - }); - call.write(badArg); - // TODO(mlumish): Remove call.end() - call.end(); - }); - }); - describe('Trailing metadata', function() { - it('should be present when a unary call succeeds', function(done) { - var call = client.unary({error: false}, function(err, data) { - assert.ifError(err); - }); - call.on('status', function(status) { - assert.deepEqual(status.metadata.get('trailer-present'), ['yes']); - done(); - }); - }); - it('should be present when a unary call fails', function(done) { - var call = client.unary({error: true}, function(err, data) { - assert(err); - }); - call.on('status', function(status) { - assert.deepEqual(status.metadata.get('trailer-present'), ['yes']); - done(); - }); - }); - it('should be present when a client stream call succeeds', function(done) { - var call = client.clientStream(function(err, data) { - assert.ifError(err); - }); - call.write({error: false}); - call.write({error: false}); - call.end(); - call.on('status', function(status) { - assert.deepEqual(status.metadata.get('trailer-present'), ['yes']); - done(); - }); - }); - it('should be present when a client stream call fails', function(done) { - var call = client.clientStream(function(err, data) { - assert(err); - }); - call.write({error: false}); - call.write({error: true}); - call.end(); - call.on('status', function(status) { - assert.deepEqual(status.metadata.get('trailer-present'), ['yes']); - done(); - }); - }); - it('should be present when a server stream call succeeds', function(done) { - var call = client.serverStream({error: false}); - call.on('data', function(){}); - call.on('status', function(status) { - assert.strictEqual(status.code, grpc.status.OK); - assert.deepEqual(status.metadata.get('trailer-present'), ['yes']); - done(); - }); - }); - it('should be present when a server stream call fails', function(done) { - var call = client.serverStream({error: true}); - call.on('data', function(){}); - call.on('error', function(error) { - assert.deepEqual(error.metadata.get('trailer-present'), ['yes']); - done(); - }); - }); - it('should be present when a bidi stream succeeds', function(done) { - var call = client.bidiStream(); - call.write({error: false}); - call.write({error: false}); - call.end(); - call.on('data', function(){}); - call.on('status', function(status) { - assert.strictEqual(status.code, grpc.status.OK); - assert.deepEqual(status.metadata.get('trailer-present'), ['yes']); - done(); - }); - }); - it('should be present when a bidi stream fails', function(done) { - var call = client.bidiStream(); - call.write({error: false}); - call.write({error: true}); - call.end(); - call.on('data', function(){}); - call.on('error', function(error) { - assert.deepEqual(error.metadata.get('trailer-present'), ['yes']); - done(); - }); - }); - }); - describe('Error object should contain the status', function() { - it('for a unary call', function(done) { - client.unary({error: true}, function(err, data) { - assert(err); - assert.strictEqual(err.code, grpc.status.UNKNOWN); - assert.strictEqual(err.message, 'Requested error'); - done(); - }); - }); - it('for a client stream call', function(done) { - var call = client.clientStream(function(err, data) { - assert(err); - assert.strictEqual(err.code, grpc.status.UNKNOWN); - assert.strictEqual(err.message, 'Requested error'); - done(); - }); - call.write({error: false}); - call.write({error: true}); - call.end(); - }); - it('for a server stream call', function(done) { - var call = client.serverStream({error: true}); - call.on('data', function(){}); - call.on('error', function(error) { - assert.strictEqual(error.code, grpc.status.UNKNOWN); - assert.strictEqual(error.message, 'Requested error'); - done(); - }); - }); - it('for a bidi stream call', function(done) { - var call = client.bidiStream(); - call.write({error: false}); - call.write({error: true}); - call.end(); - call.on('data', function(){}); - call.on('error', function(error) { - assert.strictEqual(error.code, grpc.status.UNKNOWN); - assert.strictEqual(error.message, 'Requested error'); - done(); - }); - }); - }); - describe('call.getPeer should return the peer', function() { - it('for a unary call', function(done) { - var call = client.unary({error: false}, function(err, data) { - assert.ifError(err); - done(); - }); - assert.strictEqual(typeof call.getPeer(), 'string'); - }); - it('for a client stream call', function(done) { - var call = client.clientStream(function(err, data) { - assert.ifError(err); - done(); - }); - assert.strictEqual(typeof call.getPeer(), 'string'); - call.write({error: false}); - call.end(); - }); - it('for a server stream call', function(done) { - var call = client.serverStream({error: false}); - assert.strictEqual(typeof call.getPeer(), 'string'); - call.on('data', function(){}); - call.on('status', function(status) { - assert.strictEqual(status.code, grpc.status.OK); - done(); - }); - }); - it('for a bidi stream call', function(done) { - var call = client.bidiStream(); - assert.strictEqual(typeof call.getPeer(), 'string'); - call.write({error: false}); - call.end(); - call.on('data', function(){}); - call.on('status', function(status) { - done(); - }); - }); - it('after the call has fully completed', function(done) { - var peer; - var call = client.unary({error: false}, function(err, data) { - assert.ifError(err); - setImmediate(function() { - assert.strictEqual(peer, call.getPeer()); - done(); - }); - }); - peer = call.getPeer(); - assert.strictEqual(typeof peer, 'string'); - }); - }); -}); -describe('Call propagation', function() { - var proxy; - var proxy_impl; - - var Client; - var client; - var server; - before(function() { - var test_proto = ProtoBuf.loadProtoFile(__dirname + '/test_service.proto'); - var test_service = test_proto.lookup('TestService'); - server = new grpc.Server(); - Client = grpc.loadObject(test_service); - server.addService(Client.service, { - unary: function(call) {}, - clientStream: function(stream) {}, - serverStream: function(stream) {}, - bidiStream: function(stream) {} - }); - var port = server.bind('localhost:0', server_insecure_creds); - client = new Client('localhost:' + port, grpc.credentials.createInsecure()); - server.start(); - }); - after(function() { - server.forceShutdown(); - }); - beforeEach(function() { - proxy = new grpc.Server(); - proxy_impl = { - unary: function(call) {}, - clientStream: function(stream) {}, - serverStream: function(stream) {}, - bidiStream: function(stream) {} - }; - }); - afterEach(function() { - proxy.forceShutdown(); - }); - describe('Cancellation', function() { - it('With a unary call', function(done) { - done = multiDone(done, 2); - var call; - proxy_impl.unary = function(parent, callback) { - client.unary(parent.request, {parent: parent}, function(err, value) { - try { - assert(err); - assert.strictEqual(err.code, grpc.status.CANCELLED); - } finally { - callback(err, value); - done(); - } - }); - call.cancel(); - }; - proxy.addService(Client.service, proxy_impl); - var proxy_port = proxy.bind('localhost:0', server_insecure_creds); - proxy.start(); - var proxy_client = new Client('localhost:' + proxy_port, - grpc.credentials.createInsecure()); - call = proxy_client.unary({}, function(err, value) { done(); }); - }); - it('With a client stream call', function(done) { - done = multiDone(done, 2); - var call; - proxy_impl.clientStream = function(parent, callback) { - client.clientStream({parent: parent}, function(err, value) { - try { - assert(err); - assert.strictEqual(err.code, grpc.status.CANCELLED); - } finally { - callback(err, value); - done(); - } - }); - call.cancel(); - }; - proxy.addService(Client.service, proxy_impl); - var proxy_port = proxy.bind('localhost:0', server_insecure_creds); - proxy.start(); - var proxy_client = new Client('localhost:' + proxy_port, - grpc.credentials.createInsecure()); - call = proxy_client.clientStream(function(err, value) { done(); }); - }); - it('With a server stream call', function(done) { - done = multiDone(done, 2); - var call; - proxy_impl.serverStream = function(parent) { - var child = client.serverStream(parent.request, {parent: parent}); - child.on('data', function() {}); - child.on('error', function(err) { - assert(err); - assert.strictEqual(err.code, grpc.status.CANCELLED); - done(); - }); - call.cancel(); - }; - proxy.addService(Client.service, proxy_impl); - var proxy_port = proxy.bind('localhost:0', server_insecure_creds); - proxy.start(); - var proxy_client = new Client('localhost:' + proxy_port, - grpc.credentials.createInsecure()); - call = proxy_client.serverStream({}); - call.on('data', function() {}); - call.on('error', function(err) { - done(); - }); - }); - it('With a bidi stream call', function(done) { - done = multiDone(done, 2); - var call; - proxy_impl.bidiStream = function(parent) { - var child = client.bidiStream({parent: parent}); - child.on('data', function() {}); - child.on('error', function(err) { - assert(err); - assert.strictEqual(err.code, grpc.status.CANCELLED); - done(); - }); - call.cancel(); - }; - proxy.addService(Client.service, proxy_impl); - var proxy_port = proxy.bind('localhost:0', server_insecure_creds); - proxy.start(); - var proxy_client = new Client('localhost:' + proxy_port, - grpc.credentials.createInsecure()); - call = proxy_client.bidiStream(); - call.on('data', function() {}); - call.on('error', function(err) { - done(); - }); - }); - }); - describe('Deadline', function() { - /* jshint bitwise:false */ - var deadline_flags = (grpc.propagate.DEFAULTS & - ~grpc.propagate.CANCELLATION); - it('With a client stream call', function(done) { - done = multiDone(done, 2); - proxy_impl.clientStream = function(parent, callback) { - var options = {parent: parent, propagate_flags: deadline_flags}; - client.clientStream(options, function(err, value) { - try { - assert(err); - assert(err.code === grpc.status.DEADLINE_EXCEEDED || - err.code === grpc.status.INTERNAL); - } finally { - callback(err, value); - done(); - } - }); - }; - proxy.addService(Client.service, proxy_impl); - var proxy_port = proxy.bind('localhost:0', server_insecure_creds); - proxy.start(); - var proxy_client = new Client('localhost:' + proxy_port, - grpc.credentials.createInsecure()); - var deadline = new Date(); - deadline.setSeconds(deadline.getSeconds() + 1); - proxy_client.clientStream({deadline: deadline}, function(err, value) { - done(); - }); - }); - it('With a bidi stream call', function(done) { - done = multiDone(done, 2); - proxy_impl.bidiStream = function(parent) { - var child = client.bidiStream( - {parent: parent, propagate_flags: deadline_flags}); - child.on('data', function() {}); - child.on('error', function(err) { - assert(err); - assert(err.code === grpc.status.DEADLINE_EXCEEDED || - err.code === grpc.status.INTERNAL); - done(); - }); - }; - proxy.addService(Client.service, proxy_impl); - var proxy_port = proxy.bind('localhost:0', server_insecure_creds); - proxy.start(); - var proxy_client = new Client('localhost:' + proxy_port, - grpc.credentials.createInsecure()); - var deadline = new Date(); - deadline.setSeconds(deadline.getSeconds() + 1); - var call = proxy_client.bidiStream({deadline: deadline}); - call.on('data', function() {}); - call.on('error', function(err) { - done(); - }); - }); - }); -}); -describe('Cancelling surface client', function() { - var client; - var server; - before(function() { - server = new grpc.Server(); - server.addService(mathServiceAttrs, { - 'div': function(stream) {}, - 'divMany': function(stream) {}, - 'fib': function(stream) {}, - 'sum': function(stream) {} - }); - var port = server.bind('localhost:0', server_insecure_creds); - var Client = surface_client.makeClientConstructor(mathServiceAttrs); - client = new Client('localhost:' + port, grpc.credentials.createInsecure()); - server.start(); - }); - after(function() { - server.forceShutdown(); - }); - it('Should correctly cancel a unary call', function(done) { - var call = client.div({'divisor': 0, 'dividend': 0}, function(err, resp) { - assert.strictEqual(err.code, grpc.status.CANCELLED); - done(); - }); - call.cancel(); - }); - it('Should correctly cancel a client stream call', function(done) { - var call = client.sum(function(err, resp) { - assert.strictEqual(err.code, grpc.status.CANCELLED); - done(); - }); - call.cancel(); - }); - it('Should correctly cancel a server stream call', function(done) { - var call = client.fib({'limit': 5}); - call.on('data', function() {}); - call.on('error', function(error) { - assert.strictEqual(error.code, grpc.status.CANCELLED); - done(); - }); - call.cancel(); - }); - it('Should correctly cancel a bidi stream call', function(done) { - var call = client.divMany(); - call.on('data', function() {}); - call.on('error', function(error) { - assert.strictEqual(error.code, grpc.status.CANCELLED); - done(); - }); - call.cancel(); - }); - it('Should be idempotent', function(done) { - var call = client.div({'divisor': 0, 'dividend': 0}, function(err, resp) { - assert.strictEqual(err.code, grpc.status.CANCELLED); - // Call asynchronously to try cancelling after call is fully completed - setImmediate(function() { - assert.doesNotThrow(function() { - call.cancel(); - }); - done(); - }); - }); - call.cancel(); - }); -}); -describe('Client reconnect', function() { - var server; - var Client; - var client; - var port; - beforeEach(function() { - var test_proto = ProtoBuf.loadProtoFile(__dirname + '/echo_service.proto'); - var echo_service = test_proto.lookup('EchoService'); - Client = grpc.loadObject(echo_service); - server = new grpc.Server(); - server.addService(Client.service, { - echo: function(call, callback) { - callback(null, call.request); - } - }); - port = server.bind('localhost:0', server_insecure_creds); - client = new Client('localhost:' + port, grpc.credentials.createInsecure()); - server.start(); - }); - afterEach(function() { - server.forceShutdown(); - }); - it('should reconnect after server restart', function(done) { - client.echo({value: 'test value', value2: 3}, function(error, response) { - assert.ifError(error); - assert.deepEqual(response, {value: 'test value', value2: 3}); - server.tryShutdown(function() { - server = new grpc.Server(); - server.addService(Client.service, { - echo: function(call, callback) { - callback(null, call.request); - } - }); - server.bind('localhost:' + port, server_insecure_creds); - server.start(); - - /* We create a new client, that will not throw an error if the server - * is not immediately available. Instead, it will wait for the server - * to be available, then the call will complete. Once this happens, the - * original client should be able to make a new call and connect to the - * restarted server without having the call fail due to connection - * errors. */ - var client2 = new Client('localhost:' + port, - grpc.credentials.createInsecure()); - client2.echo({value: 'test', value2: 3}, function(error, response) { - assert.ifError(error); - client.echo(undefined, function(error, response) { - if (error) { - console.log(error); - } - assert.ifError(error); - assert.deepEqual(response, {value: '', value2: 0}); - done(); - }); - }); - }); - }); - }); -}); diff --git a/src/node/test/test_messages.proto b/src/node/test/test_messages.proto deleted file mode 100644 index da1ef5658da..00000000000 --- a/src/node/test/test_messages.proto +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2015 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -message LongValues { - int64 int_64 = 1; - uint64 uint_64 = 2; - sint64 sint_64 = 3; - fixed64 fixed_64 = 4; - sfixed64 sfixed_64 = 5; -} - -message SequenceValues { - bytes bytes_field = 1; - repeated int32 repeated_field = 2; -} - -message OneOfValues { - oneof oneof_choice { - int32 int_choice = 1; - string string_choice = 2; - } -} - -enum TestEnum { - ZERO = 0; - ONE = 1; - TWO = 2; -} - -message EnumValues { - TestEnum enum_value = 1; -} diff --git a/src/node/test/test_service.json b/src/node/test/test_service.json deleted file mode 100644 index 6f952c6ad22..00000000000 --- a/src/node/test/test_service.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "package": null, - "messages": [ - { - "name": "Request", - "fields": [ - { - "rule": "optional", - "type": "bool", - "name": "error", - "id": 1 - } - ] - }, - { - "name": "Response", - "fields": [ - { - "rule": "optional", - "type": "int32", - "name": "count", - "id": 1 - } - ] - } - ], - "services": [ - { - "name": "TestService", - "options": {}, - "rpc": { - "Unary": { - "request": "Request", - "response": "Response", - "options": {} - }, - "ClientStream": { - "request": "Request", - "response": "Response", - "options": {} - }, - "ServerStream": { - "request": "Request", - "response": "Response", - "options": {} - }, - "BidiStream": { - "request": "Request", - "response": "Response", - "options": {} - } - } - } - ] -} \ No newline at end of file diff --git a/src/node/tools/bin/protoc.js b/src/node/tools/bin/protoc.js deleted file mode 100755 index 490817b3cef..00000000000 --- a/src/node/tools/bin/protoc.js +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env node -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/** - * This file is required because package.json cannot reference a file that - * is not distributed with the package, and we use node-pre-gyp to distribute - * the protoc binary - */ - -'use strict'; - -var path = require('path'); -var execFile = require('child_process').execFile; - -var exe_ext = process.platform === 'win32' ? '.exe' : ''; - -var protoc = path.resolve(__dirname, 'protoc' + exe_ext); - -var plugin = path.resolve(__dirname, 'grpc_node_plugin' + exe_ext); - -var args = ['--plugin=protoc-gen-grpc=' + plugin].concat(process.argv.slice(2)); - -var child_process = execFile(protoc, args, function(error, stdout, stderr) { - if (error) { - throw error; - } -}); - -child_process.stdout.pipe(process.stdout); -child_process.stderr.pipe(process.stderr); diff --git a/src/node/tools/bin/protoc_plugin.js b/src/node/tools/bin/protoc_plugin.js deleted file mode 100755 index fbdafff7d29..00000000000 --- a/src/node/tools/bin/protoc_plugin.js +++ /dev/null @@ -1,43 +0,0 @@ -#!/usr/bin/env node -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/** - * This file is required because package.json cannot reference a file that - * is not distributed with the package, and we use node-pre-gyp to distribute - * the plugin binary - */ - -'use strict'; - -var path = require('path'); -var execFile = require('child_process').execFile; - -var exe_ext = process.platform === 'win32' ? '.exe' : ''; - -var plugin = path.resolve(__dirname, 'grpc_node_plugin' + exe_ext); - -var child_process = execFile(plugin, process.argv.slice(2), {encoding: 'buffer'}, function(error, stdout, stderr) { - if (error) { - throw error; - } -}); - -process.stdin.pipe(child_process.stdin); -child_process.stdout.pipe(process.stdout); -child_process.stderr.pipe(process.stderr); diff --git a/src/node/tools/package.json b/src/node/tools/package.json index f88fc65cdf4..99fd8540672 100644 --- a/src/node/tools/package.json +++ b/src/node/tools/package.json @@ -1,6 +1,6 @@ { "name": "grpc-tools", - "version": "1.8.0-dev", + "version": "1.7.2", "author": "Google Inc.", "description": "Tools for developing with gRPC on Node.js", "homepage": "https://grpc.io/", diff --git a/src/objective-c/!ProtoCompiler-gRPCPlugin.podspec b/src/objective-c/!ProtoCompiler-gRPCPlugin.podspec index 9065ab9f73e..22501765f9d 100644 --- a/src/objective-c/!ProtoCompiler-gRPCPlugin.podspec +++ b/src/objective-c/!ProtoCompiler-gRPCPlugin.podspec @@ -42,7 +42,7 @@ Pod::Spec.new do |s| # exclamation mark ensures that other "regular" pods will be able to find it as it'll be installed # before them. s.name = '!ProtoCompiler-gRPCPlugin' - v = '1.8.0-dev' + v = '1.9.0-dev' s.version = v s.summary = 'The gRPC ProtoC plugin generates Objective-C files from .proto services.' s.description = <<-DESC @@ -101,7 +101,7 @@ Pod::Spec.new do |s| s.preserve_paths = plugin # Restrict the protoc version to the one supported by this plugin. - s.dependency '!ProtoCompiler', '3.4.0' + s.dependency '!ProtoCompiler', '3.5.0' # For the Protobuf dependency not to complain: s.ios.deployment_target = '7.0' s.osx.deployment_target = '10.9' diff --git a/src/objective-c/!ProtoCompiler.podspec b/src/objective-c/!ProtoCompiler.podspec index 25c437911f6..12598e616a6 100644 --- a/src/objective-c/!ProtoCompiler.podspec +++ b/src/objective-c/!ProtoCompiler.podspec @@ -36,7 +36,7 @@ Pod::Spec.new do |s| # exclamation mark ensures that other "regular" pods will be able to find it as it'll be installed # before them. s.name = '!ProtoCompiler' - v = '3.4.0' + v = '3.5.0' s.version = v s.summary = 'The Protobuf Compiler (protoc) generates Objective-C files from .proto files' s.description = <<-DESC diff --git a/src/objective-c/GRPCClient/GRPCCall.m b/src/objective-c/GRPCClient/GRPCCall.m index d6c3a3c165a..ac4596da253 100644 --- a/src/objective-c/GRPCClient/GRPCCall.m +++ b/src/objective-c/GRPCClient/GRPCCall.m @@ -112,10 +112,13 @@ static NSString * const kBearerPrefix = @"Bearer "; @synthesize state = _state; -// TODO(jcanizales): If grpc_init is idempotent, this should be changed from load to initialize. -+ (void)load { - grpc_init(); - callFlags = [NSMutableDictionary dictionary]; ++ (void)initialize { + // Guarantees the code in {} block is invoked only once. See ref at: + // https://developer.apple.com/documentation/objectivec/nsobject/1418639-initialize?language=objc + if (self == [GRPCCall self]) { + grpc_init(); + callFlags = [NSMutableDictionary dictionary]; + } } + (void)setCallSafety:(GRPCCallSafety)callSafety host:(NSString *)host path:(NSString *)path { @@ -296,7 +299,7 @@ static NSString * const kBearerPrefix = @"Bearer "; // network queue if the write didn't succeed. // If the call is a unary call, parameter \a errorHandler will be ignored and // the error handler of GRPCOpSendClose will be executed in case of error. -- (void)writeMessage:(NSData *)message withErrorHandler:(void (^)())errorHandler { +- (void)writeMessage:(NSData *)message withErrorHandler:(void (^)(void))errorHandler { __weak GRPCCall *weakSelf = self; void(^resumingHandler)(void) = ^{ @@ -342,7 +345,7 @@ static NSString * const kBearerPrefix = @"Bearer "; // Only called from the call queue. The error handler will be called from the // network queue if the requests stream couldn't be closed successfully. -- (void)finishRequestWithErrorHandler:(void (^)())errorHandler { +- (void)finishRequestWithErrorHandler:(void (^)(void))errorHandler { if (!_unaryCall) { [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendClose alloc] init]] errorHandler:errorHandler]; @@ -438,7 +441,7 @@ static NSString * const kBearerPrefix = @"Bearer "; } _connectivityMonitor = [GRPCConnectivityMonitor monitorWithHost:host]; __weak typeof(self) weakSelf = self; - void (^handler)() = ^{ + void (^handler)(void) = ^{ typeof(self) strongSelf = weakSelf; [strongSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain code:GRPCErrorCodeUnavailable diff --git a/src/objective-c/GRPCClient/private/GRPCConnectivityMonitor.h b/src/objective-c/GRPCClient/private/GRPCConnectivityMonitor.h index 8d3c45ee501..cb55e46d70e 100644 --- a/src/objective-c/GRPCClient/private/GRPCConnectivityMonitor.h +++ b/src/objective-c/GRPCClient/private/GRPCConnectivityMonitor.h @@ -57,6 +57,6 @@ * Only one handler is active at a time, so if this method is called again before the previous * handler has been called, it might never be called at all (or yes, if it has already been queued). */ -- (void)handleLossWithHandler:(nullable void (^)())lossHandler - wifiStatusChangeHandler:(nullable void (^)())wifiStatusChangeHandler; +- (void)handleLossWithHandler:(nullable void (^)(void))lossHandler + wifiStatusChangeHandler:(nullable void (^)(void))wifiStatusChangeHandler; @end diff --git a/src/objective-c/GRPCClient/private/GRPCConnectivityMonitor.m b/src/objective-c/GRPCClient/private/GRPCConnectivityMonitor.m index b3226385005..c8e10dd75f1 100644 --- a/src/objective-c/GRPCClient/private/GRPCConnectivityMonitor.m +++ b/src/objective-c/GRPCClient/private/GRPCConnectivityMonitor.m @@ -136,8 +136,8 @@ static void PassFlagsToContextInfoBlock(SCNetworkReachabilityRef target, return returnValue; } -- (void)handleLossWithHandler:(nullable void (^)())lossHandler - wifiStatusChangeHandler:(nullable void (^)())wifiStatusChangeHandler { +- (void)handleLossWithHandler:(nullable void (^)(void))lossHandler + wifiStatusChangeHandler:(nullable void (^)(void))wifiStatusChangeHandler { __weak typeof(self) weakSelf = self; [self startListeningWithHandler:^(GRPCReachabilityFlags *flags) { typeof(self) strongSelf = weakSelf; diff --git a/src/objective-c/GRPCClient/private/GRPCHost.m b/src/objective-c/GRPCClient/private/GRPCHost.m index f73e9cbc507..a0f41187400 100644 --- a/src/objective-c/GRPCClient/private/GRPCHost.m +++ b/src/objective-c/GRPCClient/private/GRPCHost.m @@ -93,7 +93,7 @@ static GRPCConnectivityMonitor *connectivityMonitor = nil; if (!connectivityMonitor) { connectivityMonitor = [GRPCConnectivityMonitor monitorWithHost:hostURL.host]; - void (^handler)() = ^{ + void (^handler)(void) = ^{ [GRPCHost flushChannelCache]; }; [connectivityMonitor handleLossWithHandler:handler diff --git a/src/objective-c/GRPCClient/private/GRPCWrappedCall.h b/src/objective-c/GRPCClient/private/GRPCWrappedCall.h index 1cd9da8f3ea..f569895e7c2 100644 --- a/src/objective-c/GRPCClient/private/GRPCWrappedCall.h +++ b/src/objective-c/GRPCClient/private/GRPCWrappedCall.h @@ -30,24 +30,24 @@ @interface GRPCOpSendMetadata : GRPCOperation - (instancetype)initWithMetadata:(NSDictionary *)metadata - handler:(void(^)())handler; + handler:(void(^)(void))handler; - (instancetype)initWithMetadata:(NSDictionary *)metadata flags:(uint32_t)flags - handler:(void(^)())handler NS_DESIGNATED_INITIALIZER; + handler:(void(^)(void))handler NS_DESIGNATED_INITIALIZER; @end @interface GRPCOpSendMessage : GRPCOperation - (instancetype)initWithMessage:(NSData *)message - handler:(void(^)())handler NS_DESIGNATED_INITIALIZER; + handler:(void(^)(void))handler NS_DESIGNATED_INITIALIZER; @end @interface GRPCOpSendClose : GRPCOperation -- (instancetype)initWithHandler:(void(^)())handler NS_DESIGNATED_INITIALIZER; +- (instancetype)initWithHandler:(void(^)(void))handler NS_DESIGNATED_INITIALIZER; @end @@ -79,7 +79,7 @@ path:(NSString *)path timeout:(NSTimeInterval)timeout NS_DESIGNATED_INITIALIZER; -- (void)startBatchWithOperations:(NSArray *)ops errorHandler:(void(^)())errorHandler; +- (void)startBatchWithOperations:(NSArray *)ops errorHandler:(void(^)(void))errorHandler; - (void)startBatchWithOperations:(NSArray *)ops; diff --git a/src/objective-c/GRPCClient/private/GRPCWrappedCall.m b/src/objective-c/GRPCClient/private/GRPCWrappedCall.m index b0b1223b64c..d26d13475d3 100644 --- a/src/objective-c/GRPCClient/private/GRPCWrappedCall.m +++ b/src/objective-c/GRPCClient/private/GRPCWrappedCall.m @@ -36,12 +36,12 @@ // Most operation subclasses don't set any flags in the grpc_op, and rely on the flag member being // initialized to zero. grpc_op _op; - void(^_handler)(); + void(^_handler)(void); } - (void)finish { if (_handler) { - void(^handler)() = _handler; + void(^handler)(void) = _handler; _handler = nil; handler(); } @@ -55,13 +55,13 @@ } - (instancetype)initWithMetadata:(NSDictionary *)metadata - handler:(void (^)())handler { + handler:(void (^)(void))handler { return [self initWithMetadata:metadata flags:0 handler:handler]; } - (instancetype)initWithMetadata:(NSDictionary *)metadata flags:(uint32_t)flags - handler:(void (^)())handler { + handler:(void (^)(void))handler { if (self = [super init]) { _op.op = GRPC_OP_SEND_INITIAL_METADATA; _op.data.send_initial_metadata.count = metadata.count; @@ -92,7 +92,7 @@ return [self initWithMessage:nil handler:nil]; } -- (instancetype)initWithMessage:(NSData *)message handler:(void (^)())handler { +- (instancetype)initWithMessage:(NSData *)message handler:(void (^)(void))handler { if (!message) { [NSException raise:NSInvalidArgumentException format:@"message cannot be nil"]; } @@ -116,7 +116,7 @@ return [self initWithHandler:nil]; } -- (instancetype)initWithHandler:(void (^)())handler { +- (instancetype)initWithHandler:(void (^)(void))handler { if (self = [super init]) { _op.op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; _handler = handler; @@ -271,7 +271,7 @@ [self startBatchWithOperations:operations errorHandler:nil]; } -- (void)startBatchWithOperations:(NSArray *)operations errorHandler:(void (^)())errorHandler { +- (void)startBatchWithOperations:(NSArray *)operations errorHandler:(void (^)(void))errorHandler { // Keep logs of op batches when we are running tests. Disabled when in production for improved // performance. #ifdef GRPC_TEST_OBJC diff --git a/src/objective-c/GRPCClient/private/version.h b/src/objective-c/GRPCClient/private/version.h index db589d12de6..69dd6266fd6 100644 --- a/src/objective-c/GRPCClient/private/version.h +++ b/src/objective-c/GRPCClient/private/version.h @@ -23,4 +23,4 @@ // `tools/buildgen/generate_projects.sh`. -#define GRPC_OBJC_VERSION_STRING @"1.8.0-dev" +#define GRPC_OBJC_VERSION_STRING @"1.9.0-dev" diff --git a/src/objective-c/RxLibrary/GRXConcurrentWriteable.h b/src/objective-c/RxLibrary/GRXConcurrentWriteable.h index cec45fae715..f16a3d052ad 100644 --- a/src/objective-c/RxLibrary/GRXConcurrentWriteable.h +++ b/src/objective-c/RxLibrary/GRXConcurrentWriteable.h @@ -46,7 +46,7 @@ * Enqueues writeValue: to be sent to the writeable in the main thread. * The passed handler is invoked from the main thread after writeValue: returns. */ -- (void)enqueueValue:(id)value completionHandler:(void (^)())handler; +- (void)enqueueValue:(id)value completionHandler:(void (^)(void))handler; /** * Enqueues writesFinishedWithError:nil to be sent to the writeable in the main thread. After that diff --git a/src/objective-c/RxLibrary/GRXConcurrentWriteable.m b/src/objective-c/RxLibrary/GRXConcurrentWriteable.m index bbfe491783b..37bc975f874 100644 --- a/src/objective-c/RxLibrary/GRXConcurrentWriteable.m +++ b/src/objective-c/RxLibrary/GRXConcurrentWriteable.m @@ -50,7 +50,7 @@ dispatchQueue:dispatch_get_main_queue()]; } -- (void)enqueueValue:(id)value completionHandler:(void (^)())handler { +- (void)enqueueValue:(id)value completionHandler:(void (^)(void))handler { dispatch_async(_writeableQueue, ^{ // We're racing a possible cancellation performed by another thread. To turn all already- // enqueued messages into noops, cancellation nillifies the writeable property. If we get it diff --git a/src/objective-c/RxLibrary/GRXImmediateWriter.h b/src/objective-c/RxLibrary/GRXImmediateWriter.h index bdcf5d59374..f88e46b1698 100644 --- a/src/objective-c/RxLibrary/GRXImmediateWriter.h +++ b/src/objective-c/RxLibrary/GRXImmediateWriter.h @@ -46,7 +46,7 @@ * Returns a writer that pushes to its writeable the successive values returned by the passed * block. When the block first returns nil, it is released. */ -+ (GRXWriter *)writerWithValueSupplier:(id (^)())block; ++ (GRXWriter *)writerWithValueSupplier:(id (^)(void))block; /** * Returns a writer that iterates over the values of the passed container and pushes them to diff --git a/src/objective-c/RxLibrary/GRXImmediateWriter.m b/src/objective-c/RxLibrary/GRXImmediateWriter.m index d8c6975801c..c5d6d1310ae 100644 --- a/src/objective-c/RxLibrary/GRXImmediateWriter.m +++ b/src/objective-c/RxLibrary/GRXImmediateWriter.m @@ -52,7 +52,7 @@ return [self writerWithEnumerator:enumerator error:nil]; } -+ (GRXWriter *)writerWithValueSupplier:(id (^)())block { ++ (GRXWriter *)writerWithValueSupplier:(id (^)(void))block { return [self writerWithEnumerator:[NSEnumerator grx_enumeratorWithValueSupplier:block]]; } diff --git a/src/objective-c/RxLibrary/GRXWriter+Immediate.h b/src/objective-c/RxLibrary/GRXWriter+Immediate.h index 292a35f61fd..d7935deaa22 100644 --- a/src/objective-c/RxLibrary/GRXWriter+Immediate.h +++ b/src/objective-c/RxLibrary/GRXWriter+Immediate.h @@ -30,7 +30,7 @@ * Returns a writer that pushes to its writeable the successive values returned by the passed * block. When the block first returns nil, it is released. */ -+ (instancetype)writerWithValueSupplier:(id (^)())block; ++ (instancetype)writerWithValueSupplier:(id (^)(void))block; /** * Returns a writer that iterates over the values of the passed container and pushes them to diff --git a/src/objective-c/RxLibrary/GRXWriter+Immediate.m b/src/objective-c/RxLibrary/GRXWriter+Immediate.m index 43aa9c54375..a36a56764d2 100644 --- a/src/objective-c/RxLibrary/GRXWriter+Immediate.m +++ b/src/objective-c/RxLibrary/GRXWriter+Immediate.m @@ -27,7 +27,7 @@ return [GRXImmediateWriter writerWithEnumerator:enumerator]; } -+ (instancetype)writerWithValueSupplier:(id (^)())block { ++ (instancetype)writerWithValueSupplier:(id (^)(void))block { return [GRXImmediateWriter writerWithValueSupplier:block]; } diff --git a/src/objective-c/RxLibrary/NSEnumerator+GRXUtil.h b/src/objective-c/RxLibrary/NSEnumerator+GRXUtil.h index 8c72f7858d8..38dbaaf9a4d 100644 --- a/src/objective-c/RxLibrary/NSEnumerator+GRXUtil.h +++ b/src/objective-c/RxLibrary/NSEnumerator+GRXUtil.h @@ -38,5 +38,5 @@ * Returns a NSEnumerator instance that delegates the invocations of nextObject to the passed block. * When the block first returns nil, it is released. */ -+ (NSEnumerator *)grx_enumeratorWithValueSupplier:(id (^)())block; ++ (NSEnumerator *)grx_enumeratorWithValueSupplier:(id (^)(void))block; @end diff --git a/src/objective-c/RxLibrary/NSEnumerator+GRXUtil.m b/src/objective-c/RxLibrary/NSEnumerator+GRXUtil.m index 309e25ede54..7d8191d0f7a 100644 --- a/src/objective-c/RxLibrary/NSEnumerator+GRXUtil.m +++ b/src/objective-c/RxLibrary/NSEnumerator+GRXUtil.m @@ -33,7 +33,7 @@ return [[GRXNSScalarEnumerator alloc] initWithValue:value]; } -+ (NSEnumerator *)grx_enumeratorWithValueSupplier:(id (^)())block { ++ (NSEnumerator *)grx_enumeratorWithValueSupplier:(id (^)(void))block { return [[GRXNSBlockEnumerator alloc] initWithValueSupplier:block]; } @end diff --git a/src/objective-c/RxLibrary/private/GRXNSBlockEnumerator.h b/src/objective-c/RxLibrary/private/GRXNSBlockEnumerator.h index c45338acdd7..c3317b2d049 100644 --- a/src/objective-c/RxLibrary/private/GRXNSBlockEnumerator.h +++ b/src/objective-c/RxLibrary/private/GRXNSBlockEnumerator.h @@ -27,5 +27,5 @@ * The first time the passed block returns nil, the enumeration will end and the block will be * released. */ -- (instancetype)initWithValueSupplier:(id (^)())block; +- (instancetype)initWithValueSupplier:(id (^)(void))block; @end diff --git a/src/objective-c/RxLibrary/private/GRXNSBlockEnumerator.m b/src/objective-c/RxLibrary/private/GRXNSBlockEnumerator.m index 7e7cc572b85..eddfd266802 100644 --- a/src/objective-c/RxLibrary/private/GRXNSBlockEnumerator.m +++ b/src/objective-c/RxLibrary/private/GRXNSBlockEnumerator.m @@ -19,14 +19,14 @@ #import "GRXNSBlockEnumerator.h" @implementation GRXNSBlockEnumerator { - id (^_block)(); + id (^_block)(void); } - (instancetype)init { return [self initWithValueSupplier:nil]; } -- (instancetype)initWithValueSupplier:(id (^)())block { +- (instancetype)initWithValueSupplier:(id (^)(void))block { if ((self = [super init])) { _block = block; } diff --git a/src/objective-c/tests/CoreCronetEnd2EndTests/CoreCronetEnd2EndTests.m b/src/objective-c/tests/CoreCronetEnd2EndTests/CoreCronetEnd2EndTests.mm similarity index 75% rename from src/objective-c/tests/CoreCronetEnd2EndTests/CoreCronetEnd2EndTests.m rename to src/objective-c/tests/CoreCronetEnd2EndTests/CoreCronetEnd2EndTests.mm index 453b0752c31..d5e668a858a 100644 --- a/src/objective-c/tests/CoreCronetEnd2EndTests/CoreCronetEnd2EndTests.m +++ b/src/objective-c/tests/CoreCronetEnd2EndTests/CoreCronetEnd2EndTests.mm @@ -58,7 +58,7 @@ static grpc_end2end_test_fixture chttp2_create_fixture_secure_fullstack( grpc_end2end_test_fixture f; int port = grpc_pick_unused_port_or_die(); fullstack_secure_fixture_data *ffd = - gpr_malloc(sizeof(fullstack_secure_fixture_data)); + (fullstack_secure_fixture_data*)gpr_malloc(sizeof(fullstack_secure_fixture_data)); memset(&f, 0, sizeof(f)); gpr_join_host_port(&ffd->localaddr, "127.0.0.1", port); @@ -81,7 +81,7 @@ static void process_auth_failure(void *state, grpc_auth_context *ctx, static void cronet_init_client_secure_fullstack(grpc_end2end_test_fixture *f, grpc_channel_args *client_args, stream_engine *cronetEngine) { - fullstack_secure_fixture_data *ffd = f->fixture_data; + fullstack_secure_fixture_data *ffd = (fullstack_secure_fixture_data *)f->fixture_data; f->client = grpc_cronet_secure_channel_create(cronetEngine, ffd->localaddr, client_args, NULL); GPR_ASSERT(f->client != NULL); @@ -90,7 +90,7 @@ static void cronet_init_client_secure_fullstack(grpc_end2end_test_fixture *f, static void chttp2_init_server_secure_fullstack( grpc_end2end_test_fixture *f, grpc_channel_args *server_args, grpc_server_credentials *server_creds) { - fullstack_secure_fixture_data *ffd = f->fixture_data; + fullstack_secure_fixture_data *ffd = (fullstack_secure_fixture_data *)f->fixture_data; if (f->server) { grpc_server_destroy(f->server); } @@ -103,7 +103,7 @@ static void chttp2_init_server_secure_fullstack( } static void chttp2_tear_down_secure_fullstack(grpc_end2end_test_fixture *f) { - fullstack_secure_fixture_data *ffd = f->fixture_data; + fullstack_secure_fixture_data *ffd = (fullstack_secure_fixture_data *)f->fixture_data; gpr_free(ffd->localaddr); gpr_free(ffd); } @@ -171,7 +171,7 @@ static char *roots_filename; FILE *roots_file; size_t roots_size = strlen(test_root_cert); - char *argv[] = {"CoreCronetEnd2EndTests"}; + char *argv[] = {(char *)"CoreCronetEnd2EndTests"}; grpc_test_init(1, argv); grpc_end2end_tests_pre_init(); @@ -207,7 +207,7 @@ static char *roots_filename; } - (void)testIndividualCase:(char *)test_case { - char *argv[] = {"h2_ssl", test_case}; + char *argv[] = {(char *)"h2_ssl", test_case}; for (int i = 0; i < sizeof(configs) / sizeof(*configs); i++) { grpc_end2end_tests(sizeof(argv) / sizeof(argv[0]), argv, configs[i]); @@ -217,182 +217,182 @@ static char *roots_filename; // TODO(mxyan): Use NSStringFromSelector(_cmd) to acquire test name from the // test case method name, so that bodies of test cases can stay identical - (void)testAuthorityNotSupported { - [self testIndividualCase:"authority_not_supported"]; + [self testIndividualCase:(char *)"authority_not_supported"]; } - (void)testBadHostname { - [self testIndividualCase:"bad_hostname"]; + [self testIndividualCase:(char *)"bad_hostname"]; } - (void)testBinaryMetadata { // NOT SUPPORTED - //[self testIndividualCase:"binary_metadata"]; + //[self testIndividualCase:(char *)"binary_metadata"]; } - (void)testCallCreds { // NOT SUPPORTED - // [self testIndividualCase:"call_creds"]; + // [self testIndividualCase:(char *)"call_creds"]; } - (void)testCancelAfterAccept { - [self testIndividualCase:"cancel_after_accept"]; + [self testIndividualCase:(char *)"cancel_after_accept"]; } - (void)testCancelAfterClientDone { - [self testIndividualCase:"cancel_after_client_done"]; + [self testIndividualCase:(char *)"cancel_after_client_done"]; } - (void)testCancelAfterInvoke { - [self testIndividualCase:"cancel_after_invoke"]; + [self testIndividualCase:(char *)"cancel_after_invoke"]; } - (void)testCancelAfterRoundTrip { - [self testIndividualCase:"cancel_after_round_trip"]; + [self testIndividualCase:(char *)"cancel_after_round_trip"]; } - (void)testCancelBeforeInvoke { - [self testIndividualCase:"cancel_before_invoke"]; + [self testIndividualCase:(char *)"cancel_before_invoke"]; } - (void)testCancelInAVacuum { - [self testIndividualCase:"cancel_in_a_vacuum"]; + [self testIndividualCase:(char *)"cancel_in_a_vacuum"]; } - (void)testCancelWithStatus { - [self testIndividualCase:"cancel_with_status"]; + [self testIndividualCase:(char *)"cancel_with_status"]; } - (void)testCompressedPayload { - [self testIndividualCase:"compressed_payload"]; + [self testIndividualCase:(char *)"compressed_payload"]; } - (void)testConnectivity { // NOT SUPPORTED - // [self testIndividualCase:"connectivity"]; + // [self testIndividualCase:(char *)"connectivity"]; } - (void)testDefaultHost { - [self testIndividualCase:"default_host"]; + [self testIndividualCase:(char *)"default_host"]; } - (void)testDisappearingServer { - [self testIndividualCase:"disappearing_server"]; + [self testIndividualCase:(char *)"disappearing_server"]; } - (void)testEmptyBatch { - [self testIndividualCase:"empty_batch"]; + [self testIndividualCase:(char *)"empty_batch"]; } - (void)testFilterCausesClose { // NOT SUPPORTED - // [self testIndividualCase:"filter_causes_close"]; + // [self testIndividualCase:(char *)"filter_causes_close"]; } - (void)testGracefulServerShutdown { - [self testIndividualCase:"graceful_server_shutdown"]; + [self testIndividualCase:(char *)"graceful_server_shutdown"]; } - (void)testHighInitialSeqno { - [self testIndividualCase:"high_initial_seqno"]; + [self testIndividualCase:(char *)"high_initial_seqno"]; } - (void)testHpackSize { // NOT SUPPORTED - // [self testIndividualCase:"hpack_size"]; + // [self testIndividualCase:(char *)"hpack_size"]; } - (void)testIdempotentRequest { // NOT SUPPORTED - // [self testIndividualCase:"idempotent_request"]; + // [self testIndividualCase:(char *)"idempotent_request"]; } - (void)testInvokeLargeRequest { // NOT SUPPORTED (frame size) - // [self testIndividualCase:"invoke_large_request"]; + // [self testIndividualCase:(char *)"invoke_large_request"]; } - (void)testLargeMetadata { // NOT SUPPORTED - // [self testIndividualCase:"large_metadata"]; + // [self testIndividualCase:(char *)"large_metadata"]; } - (void)testMaxConcurrentStreams { - [self testIndividualCase:"max_concurrent_streams"]; + [self testIndividualCase:(char *)"max_concurrent_streams"]; } - (void)testMaxMessageLength { // NOT SUPPORTED (close_error) - // [self testIndividualCase:"max_message_length"]; + // [self testIndividualCase:(char *)"max_message_length"]; } - (void)testNegativeDeadline { - [self testIndividualCase:"negative_deadline"]; + [self testIndividualCase:(char *)"negative_deadline"]; } - (void)testNetworkStatusChange { - [self testIndividualCase:"network_status_change"]; + [self testIndividualCase:(char *)"network_status_change"]; } - (void)testNoOp { - [self testIndividualCase:"no_op"]; + [self testIndividualCase:(char *)"no_op"]; } - (void)testPayload { - [self testIndividualCase:"payload"]; + [self testIndividualCase:(char *)"payload"]; } - (void)testPing { // NOT SUPPORTED - // [self testIndividualCase:"ping"]; + // [self testIndividualCase:(char *)"ping"]; } - (void)testPingPongStreaming { - [self testIndividualCase:"ping_pong_streaming"]; + [self testIndividualCase:(char *)"ping_pong_streaming"]; } - (void)testRegisteredCall { - [self testIndividualCase:"registered_call"]; + [self testIndividualCase:(char *)"registered_call"]; } - (void)testRequestWithFlags { // NOT SUPPORTED - // [self testIndividualCase:"request_with_flags"]; + // [self testIndividualCase:(char *)"request_with_flags"]; } - (void)testRequestWithPayload { - [self testIndividualCase:"request_with_payload"]; + [self testIndividualCase:(char *)"request_with_payload"]; } - (void)testServerFinishesRequest { - [self testIndividualCase:"server_finishes_request"]; + [self testIndividualCase:(char *)"server_finishes_request"]; } - (void)testShutdownFinishesCalls { - [self testIndividualCase:"shutdown_finishes_calls"]; + [self testIndividualCase:(char *)"shutdown_finishes_calls"]; } - (void)testShutdownFinishesTags { - [self testIndividualCase:"shutdown_finishes_tags"]; + [self testIndividualCase:(char *)"shutdown_finishes_tags"]; } - (void)testSimpleDelayedRequest { - [self testIndividualCase:"simple_delayed_request"]; + [self testIndividualCase:(char *)"simple_delayed_request"]; } - (void)testSimpleMetadata { - [self testIndividualCase:"simple_metadata"]; + [self testIndividualCase:(char *)"simple_metadata"]; } - (void)testSimpleRequest { - [self testIndividualCase:"simple_request"]; + [self testIndividualCase:(char *)"simple_request"]; } - (void)testStreamingErrorResponse { - [self testIndividualCase:"streaming_error_response"]; + [self testIndividualCase:(char *)"streaming_error_response"]; } - (void)testTrailingMetadata { - [self testIndividualCase:"trailing_metadata"]; + [self testIndividualCase:(char *)"trailing_metadata"]; } @end diff --git a/src/objective-c/tests/CronetUnitTests/CronetUnitTests.m b/src/objective-c/tests/CronetUnitTests/CronetUnitTests.m index 0d295fb3c0b..92bc20e5b92 100644 --- a/src/objective-c/tests/CronetUnitTests/CronetUnitTests.m +++ b/src/objective-c/tests/CronetUnitTests/CronetUnitTests.m @@ -56,7 +56,7 @@ static void drain_cq(grpc_completion_queue *cq) { + (void)setUp { [super setUp]; - char *argv[] = {"CoreCronetEnd2EndTests"}; + char *argv[] = {(char *)"CoreCronetEnd2EndTests"}; grpc_test_init(1, argv); grpc_init(); @@ -100,7 +100,7 @@ void init_ctx(SSL_CTX *ctx) { // Install server certificate BIO *pem = BIO_new_mem_buf((void *)test_server1_cert, (int)strlen(test_server1_cert)); - X509 *cert = PEM_read_bio_X509_AUX(pem, NULL, NULL, ""); + X509 *cert = PEM_read_bio_X509_AUX(pem, NULL, NULL, (char *)""); SSL_CTX_use_certificate(ctx, cert); X509_free(cert); BIO_free(pem); @@ -108,7 +108,7 @@ void init_ctx(SSL_CTX *ctx) { // Install server private key pem = BIO_new_mem_buf((void *)test_server1_key, (int)strlen(test_server1_key)); - EVP_PKEY *key = PEM_read_bio_PrivateKey(pem, NULL, NULL, ""); + EVP_PKEY *key = PEM_read_bio_PrivateKey(pem, NULL, NULL, (char *)""); SSL_CTX_use_PrivateKey(ctx, key); EVP_PKEY_free(key); BIO_free(pem); @@ -258,7 +258,7 @@ unsigned int parse_h2_length(const char *field) { - (void)packetCoalescing:(BOOL)useCoalescing { grpc_arg arg; - arg.key = GRPC_ARG_USE_CRONET_PACKET_COALESCING; + arg.key = (char *)GRPC_ARG_USE_CRONET_PACKET_COALESCING; arg.type = GRPC_ARG_INTEGER; arg.value.integer = useCoalescing ? 1 : 0; grpc_channel_args *args = grpc_channel_args_copy_and_add(NULL, &arg, 1); diff --git a/src/objective-c/tests/GRPCClientTests.m b/src/objective-c/tests/GRPCClientTests.m index 5672bdad4c1..3bab7f66711 100644 --- a/src/objective-c/tests/GRPCClientTests.m +++ b/src/objective-c/tests/GRPCClientTests.m @@ -95,6 +95,10 @@ static GRPCProtoMethod *kFullDuplexCallMethod; @implementation GRPCClientTests ++ (void)setUp { + NSLog(@"GRPCClientTests Started"); +} + - (void)setUp { // Add a custom user agent prefix that will be used in test [GRPCCall setUserAgentPrefix:@"Foo" forHost:kHostAddress]; diff --git a/src/objective-c/tests/InteropTests.m b/src/objective-c/tests/InteropTests.m index e5fcab26d86..0be8669aa2f 100644 --- a/src/objective-c/tests/InteropTests.m +++ b/src/objective-c/tests/InteropTests.m @@ -86,6 +86,7 @@ } + (void)setUp { + NSLog(@"InteropTest Started, class: %@", [[self class] description]); #ifdef GRPC_COMPILE_WITH_CRONET // Cronet setup [Cronet setHttp2Enabled:YES]; diff --git a/src/objective-c/tests/RxLibraryUnitTests.m b/src/objective-c/tests/RxLibraryUnitTests.m index 3a5adbbf378..aa178f8d454 100644 --- a/src/objective-c/tests/RxLibraryUnitTests.m +++ b/src/objective-c/tests/RxLibraryUnitTests.m @@ -58,6 +58,10 @@ @implementation RxLibraryUnitTests ++ (void)setUp { + NSLog(@"GRPCClientTests Started"); +} + #pragma mark Writeable - (void)testWriteableSingleHandlerIsCalledForValue { diff --git a/src/objective-c/tests/Tests.xcodeproj/project.pbxproj b/src/objective-c/tests/Tests.xcodeproj/project.pbxproj index 2f0c8cfe18e..9a6cb0e7d73 100644 --- a/src/objective-c/tests/Tests.xcodeproj/project.pbxproj +++ b/src/objective-c/tests/Tests.xcodeproj/project.pbxproj @@ -14,7 +14,7 @@ 20DFDF829DD993A4A00D5662 /* libPods-RxLibraryUnitTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A58BE6DF1C62D1739EBB2C78 /* libPods-RxLibraryUnitTests.a */; }; 333E8FC01C8285B7C547D799 /* libPods-InteropTestsLocalCleartext.a in Frameworks */ = {isa = PBXBuildFile; fileRef = FD346DB2C23F676C4842F3FF /* libPods-InteropTestsLocalCleartext.a */; }; 3D7C85F6AA68C4A205E3BA16 /* libPods-Tests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 20DFF2F3C97EF098FE5A3171 /* libPods-Tests.a */; }; - 5E8A5DA71D3840B4000F8BC4 /* CoreCronetEnd2EndTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 5E8A5DA61D3840B4000F8BC4 /* CoreCronetEnd2EndTests.m */; }; + 5E8A5DA71D3840B4000F8BC4 /* CoreCronetEnd2EndTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5E8A5DA61D3840B4000F8BC4 /* CoreCronetEnd2EndTests.mm */; }; 5E8A5DA91D3840B4000F8BC4 /* libTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 635697C71B14FC11007A7283 /* libTests.a */; }; 5EAD6D271E27047400002378 /* CronetUnitTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 5EAD6D261E27047400002378 /* CronetUnitTests.m */; }; 5EAD6D291E27047400002378 /* libTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 635697C71B14FC11007A7283 /* libTests.a */; }; @@ -140,7 +140,7 @@ 573450F334B331D0BED8B961 /* Pods-CoreCronetEnd2EndTests.cronet.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-CoreCronetEnd2EndTests.cronet.xcconfig"; path = "Pods/Target Support Files/Pods-CoreCronetEnd2EndTests/Pods-CoreCronetEnd2EndTests.cronet.xcconfig"; sourceTree = ""; }; 5761E98978DDDF136A58CB7E /* Pods-AllTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AllTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-AllTests/Pods-AllTests.release.xcconfig"; sourceTree = ""; }; 5E8A5DA41D3840B4000F8BC4 /* CoreCronetEnd2EndTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CoreCronetEnd2EndTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 5E8A5DA61D3840B4000F8BC4 /* CoreCronetEnd2EndTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = CoreCronetEnd2EndTests.m; sourceTree = ""; }; + 5E8A5DA61D3840B4000F8BC4 /* CoreCronetEnd2EndTests.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = CoreCronetEnd2EndTests.mm; sourceTree = ""; }; 5EAD6D241E27047400002378 /* CronetUnitTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CronetUnitTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 5EAD6D261E27047400002378 /* CronetUnitTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = CronetUnitTests.m; sourceTree = ""; }; 5EAD6D281E27047400002378 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; @@ -343,7 +343,7 @@ 5E8A5DA51D3840B4000F8BC4 /* CoreCronetEnd2EndTests */ = { isa = PBXGroup; children = ( - 5E8A5DA61D3840B4000F8BC4 /* CoreCronetEnd2EndTests.m */, + 5E8A5DA61D3840B4000F8BC4 /* CoreCronetEnd2EndTests.mm */, ); path = CoreCronetEnd2EndTests; sourceTree = ""; @@ -1196,7 +1196,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 5E8A5DA71D3840B4000F8BC4 /* CoreCronetEnd2EndTests.m in Sources */, + 5E8A5DA71D3840B4000F8BC4 /* CoreCronetEnd2EndTests.mm in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1518,6 +1518,7 @@ "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_TESTABILITY = YES; + GCC_INPUT_FILETYPE = sourcecode.cpp.objcpp; INFOPLIST_FILE = CronetUnitTests/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 9.3; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; @@ -1567,6 +1568,7 @@ "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_TESTABILITY = YES; + GCC_INPUT_FILETYPE = sourcecode.cpp.objcpp; INFOPLIST_FILE = CronetUnitTests/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 9.3; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; @@ -1582,6 +1584,7 @@ buildSettings = { CLANG_ANALYZER_NONNULL = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + GCC_INPUT_FILETYPE = sourcecode.cpp.objcpp; INFOPLIST_FILE = CronetUnitTests/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 9.3; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; @@ -1597,6 +1600,7 @@ buildSettings = { CLANG_ANALYZER_NONNULL = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + GCC_INPUT_FILETYPE = sourcecode.cpp.objcpp; INFOPLIST_FILE = CronetUnitTests/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 9.3; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; diff --git a/src/objective-c/tests/run_tests.sh b/src/objective-c/tests/run_tests.sh index 608ae6884b6..62c4e10b993 100755 --- a/src/objective-c/tests/run_tests.sh +++ b/src/objective-c/tests/run_tests.sh @@ -38,7 +38,7 @@ trap 'kill -9 `jobs -p` ; echo "EXIT TIME: $(date)"' EXIT # element of the pipe fails. # TODO(jcanizales): Use xctool instead? Issue #2540. set -o pipefail -XCODEBUILD_FILTER='(^CompileC |^Ld |^.*clang |^ *cd |^ *export |^Libtool |^.*libtool |^CpHeader |^ *builtin-copy )' +XCODEBUILD_FILTER='(^CompileC |^Ld |^ *[^ ]*clang |^ *cd |^ *export |^Libtool |^ *[^ ]*libtool |^CpHeader |^ *builtin-copy )' echo "TIME: $(date)" xcodebuild \ -workspace Tests.xcworkspace \ diff --git a/src/objective-c/tests/version.h b/src/objective-c/tests/version.h index 02515063fa1..6e3a073020f 100644 --- a/src/objective-c/tests/version.h +++ b/src/objective-c/tests/version.h @@ -23,5 +23,5 @@ // `tools/buildgen/generate_projects.sh`. -#define GRPC_OBJC_VERSION_STRING @"1.8.0-dev" +#define GRPC_OBJC_VERSION_STRING @"1.9.0-dev" #define GRPC_C_VERSION_STRING @"5.0.0-dev" diff --git a/src/php/composer.json b/src/php/composer.json index 09471d23fee..43833980f9d 100644 --- a/src/php/composer.json +++ b/src/php/composer.json @@ -2,7 +2,7 @@ "name": "grpc/grpc-dev", "description": "gRPC library for PHP - for Developement use only", "license": "Apache-2.0", - "version": "1.8.0", + "version": "1.9.0", "require": { "php": ">=5.5.0", "google/protobuf": "^v3.3.0" diff --git a/src/php/ext/grpc/version.h b/src/php/ext/grpc/version.h index 93dd563cffb..48131d72d1a 100644 --- a/src/php/ext/grpc/version.h +++ b/src/php/ext/grpc/version.h @@ -20,6 +20,6 @@ #ifndef VERSION_H #define VERSION_H -#define PHP_GRPC_VERSION "1.8.0dev" +#define PHP_GRPC_VERSION "1.9.0dev" #endif /* VERSION_H */ diff --git a/src/php/tests/unit_tests/ChannelTest.php b/src/php/tests/unit_tests/ChannelTest.php index c375a16269d..13a770caff6 100644 --- a/src/php/tests/unit_tests/ChannelTest.php +++ b/src/php/tests/unit_tests/ChannelTest.php @@ -81,10 +81,14 @@ class ChannelTest extends PHPUnit_Framework_TestCase { $this->channel = new Grpc\Channel('localhost:0', ['credentials' => Grpc\ChannelCredentials::createInsecure()]); - $time = new Grpc\Timeval(1000); - $state = $this->channel->watchConnectivityState(1, $time); + $now = Grpc\Timeval::now(); + $deadline = $now->add(new Grpc\Timeval(100*1000)); // 100ms + // we act as if 'CONNECTING'(=1) was the last state + // we saw, so the default state of 'IDLE' should be delivered instantly + $state = $this->channel->watchConnectivityState(1, $deadline); $this->assertTrue($state); - unset($time); + unset($now); + unset($deadline); } public function testClose() diff --git a/src/proto/grpc/testing/BUILD b/src/proto/grpc/testing/BUILD index 36d37822621..7c49fe2472a 100644 --- a/src/proto/grpc/testing/BUILD +++ b/src/proto/grpc/testing/BUILD @@ -76,7 +76,6 @@ grpc_proto_library( deps = [ "control_proto", "messages_proto", - "stats_proto", ], ) diff --git a/src/proto/grpc/testing/services.proto b/src/proto/grpc/testing/services.proto index 2e6583d99c5..93c21f42d11 100644 --- a/src/proto/grpc/testing/services.proto +++ b/src/proto/grpc/testing/services.proto @@ -18,7 +18,6 @@ syntax = "proto3"; import "src/proto/grpc/testing/messages.proto"; import "src/proto/grpc/testing/control.proto"; -import "src/proto/grpc/testing/stats.proto"; package grpc.testing; diff --git a/src/python/grpcio/grpc/__init__.py b/src/python/grpcio/grpc/__init__.py index c9f9ac27d91..564772527e8 100644 --- a/src/python/grpcio/grpc/__init__.py +++ b/src/python/grpcio/grpc/__init__.py @@ -348,26 +348,25 @@ class Call(six.with_metaclass(abc.ABCMeta, RpcContext)): class ChannelCredentials(object): """An encapsulation of the data required to create a secure Channel. - This class has no supported interface - it exists to define the type of its - instances and its instances exist to be passed to other functions. For - example, ssl_channel_credentials returns an instance, and secure_channel - consumes an instance of this class. - """ + This class has no supported interface - it exists to define the type of its + instances and its instances exist to be passed to other functions. For + example, ssl_channel_credentials returns an instance of this class and + secure_channel requires an instance of this class. + """ def __init__(self, credentials): self._credentials = credentials class CallCredentials(object): - """An encapsulation of the data required to assert an identity over a - channel. + """An encapsulation of the data required to assert an identity over a call. - A CallCredentials may be composed with ChannelCredentials to always assert - identity for every call over that Channel. + A CallCredentials may be composed with ChannelCredentials to always assert + identity for every call over that Channel. - This class has no supported interface - it exists to define the type of its - instances and its instances exist to be passed to other functions. - """ + This class has no supported interface - it exists to define the type of its + instances and its instances exist to be passed to other functions. + """ def __init__(self, credentials): self._credentials = credentials @@ -376,23 +375,22 @@ class CallCredentials(object): class AuthMetadataContext(six.with_metaclass(abc.ABCMeta)): """Provides information to call credentials metadata plugins. - Attributes: - service_url: A string URL of the service being called into. - method_name: A string of the fully qualified method name being called. - """ + Attributes: + service_url: A string URL of the service being called into. + method_name: A string of the fully qualified method name being called. + """ class AuthMetadataPluginCallback(six.with_metaclass(abc.ABCMeta)): """Callback object received by a metadata plugin.""" def __call__(self, metadata, error): - """Inform the gRPC runtime of the metadata to construct a - CallCredentials. + """Passes to the gRPC runtime authentication metadata for an RPC. - Args: - metadata: The :term:`metadata` used to construct the CallCredentials. - error: An Exception to indicate error or None to indicate success. - """ + Args: + metadata: The :term:`metadata` used to construct the CallCredentials. + error: An Exception to indicate error or None to indicate success. + """ raise NotImplementedError() @@ -402,14 +400,14 @@ class AuthMetadataPlugin(six.with_metaclass(abc.ABCMeta)): def __call__(self, context, callback): """Implements authentication by passing metadata to a callback. - Implementations of this method must not block. + Implementations of this method must not block. - Args: - context: An AuthMetadataContext providing information on the RPC that the - plugin is being called to authenticate. - callback: An AuthMetadataPluginCallback to be invoked either synchronously - or asynchronously. - """ + Args: + context: An AuthMetadataContext providing information on the RPC that + the plugin is being called to authenticate. + callback: An AuthMetadataPluginCallback to be invoked either + synchronously or asynchronously. + """ raise NotImplementedError() @@ -424,6 +422,21 @@ class ServerCredentials(object): self._credentials = credentials +class ServerCertificateConfiguration(object): + """A certificate configuration for use with an SSL-enabled Server. + + Instances of this class can be returned in the certificate configuration + fetching callback. + + This class has no supported interface -- it exists to define the + type of its instances and its instances exist to be passed to + other functions. + """ + + def __init__(self, certificate_configuration): + self._certificate_configuration = certificate_configuration + + ######################## Multi-Callable Interfaces ########################### @@ -1123,99 +1136,86 @@ def ssl_channel_credentials(root_certificates=None, certificate_chain=None): """Creates a ChannelCredentials for use with an SSL-enabled Channel. - Args: - root_certificates: The PEM-encoded root certificates as a byte string, - or None to retrieve them from a default location chosen by gRPC runtime. - private_key: The PEM-encoded private key as a byte string, or None if no - private key should be used. - certificate_chain: The PEM-encoded certificate chain as a byte string - to use or or None if no certificate chain should be used. + Args: + root_certificates: The PEM-encoded root certificates as a byte string, + or None to retrieve them from a default location chosen by gRPC + runtime. + private_key: The PEM-encoded private key as a byte string, or None if no + private key should be used. + certificate_chain: The PEM-encoded certificate chain as a byte string + to use or or None if no certificate chain should be used. - Returns: - A ChannelCredentials for use with an SSL-enabled Channel. - """ - if private_key is not None or certificate_chain is not None: - pair = _cygrpc.SslPemKeyCertPair(private_key, certificate_chain) - else: - pair = None + Returns: + A ChannelCredentials for use with an SSL-enabled Channel. + """ return ChannelCredentials( - _cygrpc.channel_credentials_ssl(root_certificates, pair)) + _cygrpc.SSLChannelCredentials(root_certificates, private_key, + certificate_chain)) def metadata_call_credentials(metadata_plugin, name=None): """Construct CallCredentials from an AuthMetadataPlugin. - Args: - metadata_plugin: An AuthMetadataPlugin to use for authentication. - name: An optional name for the plugin. + Args: + metadata_plugin: An AuthMetadataPlugin to use for authentication. + name: An optional name for the plugin. - Returns: - A CallCredentials. - """ + Returns: + A CallCredentials. + """ from grpc import _plugin_wrapping # pylint: disable=cyclic-import - if name is None: - try: - effective_name = metadata_plugin.__name__ - except AttributeError: - effective_name = metadata_plugin.__class__.__name__ - else: - effective_name = name - return CallCredentials( - _plugin_wrapping.call_credentials_metadata_plugin(metadata_plugin, - effective_name)) + return _plugin_wrapping.metadata_plugin_call_credentials(metadata_plugin, + name) def access_token_call_credentials(access_token): """Construct CallCredentials from an access token. - Args: - access_token: A string to place directly in the http request - authorization header, for example - "authorization: Bearer ". + Args: + access_token: A string to place directly in the http request + authorization header, for example + "authorization: Bearer ". - Returns: - A CallCredentials. - """ + Returns: + A CallCredentials. + """ from grpc import _auth # pylint: disable=cyclic-import - return metadata_call_credentials( - _auth.AccessTokenCallCredentials(access_token)) + from grpc import _plugin_wrapping # pylint: disable=cyclic-import + return _plugin_wrapping.metadata_plugin_call_credentials( + _auth.AccessTokenAuthMetadataPlugin(access_token), None) def composite_call_credentials(*call_credentials): """Compose multiple CallCredentials to make a new CallCredentials. - Args: - *call_credentials: At least two CallCredentials objects. + Args: + *call_credentials: At least two CallCredentials objects. - Returns: - A CallCredentials object composed of the given CallCredentials objects. - """ - from grpc import _credential_composition # pylint: disable=cyclic-import - cygrpc_call_credentials = tuple( - single_call_credentials._credentials - for single_call_credentials in call_credentials) + Returns: + A CallCredentials object composed of the given CallCredentials objects. + """ return CallCredentials( - _credential_composition.call(cygrpc_call_credentials)) + _cygrpc.CompositeCallCredentials( + tuple(single_call_credentials._credentials + for single_call_credentials in call_credentials))) def composite_channel_credentials(channel_credentials, *call_credentials): """Compose a ChannelCredentials and one or more CallCredentials objects. - Args: - channel_credentials: A ChannelCredentials object. - *call_credentials: One or more CallCredentials objects. + Args: + channel_credentials: A ChannelCredentials object. + *call_credentials: One or more CallCredentials objects. - Returns: - A ChannelCredentials composed of the given ChannelCredentials and - CallCredentials objects. - """ - from grpc import _credential_composition # pylint: disable=cyclic-import - cygrpc_call_credentials = tuple( - single_call_credentials._credentials - for single_call_credentials in call_credentials) + Returns: + A ChannelCredentials composed of the given ChannelCredentials and + CallCredentials objects. + """ return ChannelCredentials( - _credential_composition.channel(channel_credentials._credentials, - cygrpc_call_credentials)) + _cygrpc.CompositeChannelCredentials( + tuple(single_call_credentials._credentials + for single_call_credentials in call_credentials), + channel_credentials._credentials)) def ssl_server_credentials(private_key_certificate_chain_pairs, @@ -1252,6 +1252,61 @@ def ssl_server_credentials(private_key_certificate_chain_pairs, ], require_client_auth)) +def ssl_server_certificate_configuration(private_key_certificate_chain_pairs, + root_certificates=None): + """Creates a ServerCertificateConfiguration for use with a Server. + + Args: + private_key_certificate_chain_pairs: A collection of pairs of + the form [PEM-encoded private key, PEM-encoded certificate + chain]. + root_certificates: An optional byte string of PEM-encoded client root + certificates that the server will use to verify client authentication. + + Returns: + A ServerCertificateConfiguration that can be returned in the certificate + configuration fetching callback. + """ + if len(private_key_certificate_chain_pairs) == 0: + raise ValueError( + 'At least one private key-certificate chain pair is required!') + else: + return ServerCertificateConfiguration( + _cygrpc.server_certificate_config_ssl(root_certificates, [ + _cygrpc.SslPemKeyCertPair(key, pem) + for key, pem in private_key_certificate_chain_pairs + ])) + + +def dynamic_ssl_server_credentials(initial_certificate_configuration, + certificate_configuration_fetcher, + require_client_authentication=False): + """Creates a ServerCredentials for use with an SSL-enabled Server. + + Args: + initial_certificate_configuration (ServerCertificateConfiguration): The + certificate configuration with which the server will be initialized. + certificate_configuration_fetcher (callable): A callable that takes no + arguments and should return a ServerCertificateConfiguration to + replace the server's current certificate, or None for no change + (i.e., the server will continue its current certificate + config). The library will call this callback on *every* new + client connection before starting the TLS handshake with the + client, thus allowing the user application to optionally + return a new ServerCertificateConfiguration that the server will then + use for the handshake. + require_client_authentication: A boolean indicating whether or not to + require clients to be authenticated. + + Returns: + A ServerCredentials. + """ + return ServerCredentials( + _cygrpc.server_credentials_ssl_dynamic_cert_config( + initial_certificate_configuration, + certificate_configuration_fetcher, require_client_authentication)) + + def channel_ready_future(channel): """Creates a Future that tracks when a Channel is ready. @@ -1334,7 +1389,8 @@ __all__ = ('FutureTimeoutError', 'FutureCancelledError', 'Future', 'ChannelConnectivity', 'StatusCode', 'RpcError', 'RpcContext', 'Call', 'ChannelCredentials', 'CallCredentials', 'AuthMetadataContext', 'AuthMetadataPluginCallback', - 'AuthMetadataPlugin', 'ServerCredentials', 'UnaryUnaryMultiCallable', + 'AuthMetadataPlugin', 'ServerCertificateConfiguration', + 'ServerCredentials', 'UnaryUnaryMultiCallable', 'UnaryStreamMultiCallable', 'StreamUnaryMultiCallable', 'StreamStreamMultiCallable', 'Channel', 'ServicerContext', 'RpcMethodHandler', 'HandlerCallDetails', 'GenericRpcHandler', @@ -1344,8 +1400,9 @@ __all__ = ('FutureTimeoutError', 'FutureCancelledError', 'Future', 'method_handlers_generic_handler', 'ssl_channel_credentials', 'metadata_call_credentials', 'access_token_call_credentials', 'composite_call_credentials', 'composite_channel_credentials', - 'ssl_server_credentials', 'channel_ready_future', 'insecure_channel', - 'secure_channel', 'server',) + 'ssl_server_credentials', 'ssl_server_certificate_configuration', + 'dynamic_ssl_server_credentials', 'channel_ready_future', + 'insecure_channel', 'secure_channel', 'server',) ############################### Extension Shims ################################ diff --git a/src/python/grpcio/grpc/_auth.py b/src/python/grpcio/grpc/_auth.py index c6542d01354..9a339b59004 100644 --- a/src/python/grpcio/grpc/_auth.py +++ b/src/python/grpcio/grpc/_auth.py @@ -63,7 +63,7 @@ class GoogleCallCredentials(grpc.AuthMetadataPlugin): self._pool.shutdown(wait=False) -class AccessTokenCallCredentials(grpc.AuthMetadataPlugin): +class AccessTokenAuthMetadataPlugin(grpc.AuthMetadataPlugin): """Metadata wrapper for raw access token credentials.""" def __init__(self, access_token): diff --git a/src/python/grpcio/grpc/_credential_composition.py b/src/python/grpcio/grpc/_credential_composition.py deleted file mode 100644 index f652cc3ae79..00000000000 --- a/src/python/grpcio/grpc/_credential_composition.py +++ /dev/null @@ -1,33 +0,0 @@ -# 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. - -from grpc._cython import cygrpc - - -def _call(call_credentialses): - call_credentials_iterator = iter(call_credentialses) - composition = next(call_credentials_iterator) - for additional_call_credentials in call_credentials_iterator: - composition = cygrpc.call_credentials_composite( - composition, additional_call_credentials) - return composition - - -def call(call_credentialses): - return _call(call_credentialses) - - -def channel(channel_credentials, call_credentialses): - return cygrpc.channel_credentials_composite(channel_credentials, - _call(call_credentialses)) diff --git a/src/python/grpcio/grpc/_cython/_cygrpc/call.pyx.pxi b/src/python/grpcio/grpc/_cython/_cygrpc/call.pyx.pxi index 752fb330d01..6b3a276097f 100644 --- a/src/python/grpcio/grpc/_cython/_cygrpc/call.pyx.pxi +++ b/src/python/grpcio/grpc/_cython/_cygrpc/call.pyx.pxi @@ -72,13 +72,12 @@ cdef class Call: result = grpc_call_cancel(self.c_call, NULL) return result - def set_credentials( - self, CallCredentials call_credentials not None): - cdef grpc_call_error result - with nogil: - result = grpc_call_set_credentials( - self.c_call, call_credentials.c_credentials) - return result + def set_credentials(self, CallCredentials call_credentials not None): + cdef grpc_call_credentials *c_call_credentials = call_credentials.c() + cdef grpc_call_error call_error = grpc_call_set_credentials( + self.c_call, c_call_credentials) + grpc_call_credentials_release(c_call_credentials) + return call_error def peer(self): cdef char *peer = NULL diff --git a/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi b/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi index aeabdba021d..4c397f8f644 100644 --- a/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi +++ b/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi @@ -33,10 +33,10 @@ cdef class Channel: self.c_channel = grpc_insecure_channel_create(c_target, c_arguments, NULL) else: - with nogil: - self.c_channel = grpc_secure_channel_create( - channel_credentials.c_credentials, c_target, c_arguments, NULL) - self.references.append(channel_credentials) + c_channel_credentials = channel_credentials.c() + self.c_channel = grpc_secure_channel_create( + c_channel_credentials, c_target, c_arguments, NULL) + grpc_channel_credentials_release(c_channel_credentials) self.references.append(target) self.references.append(arguments) diff --git a/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pxd.pxi b/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pxd.pxi index 41975cbe9e9..7e9ea33ca04 100644 --- a/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pxd.pxi +++ b/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pxd.pxi @@ -12,49 +12,86 @@ # See the License for the specific language governing permissions and # limitations under the License. -cimport cpython +cdef class CallCredentials: -cdef class ChannelCredentials: + cdef grpc_call_credentials *c(self) - cdef grpc_channel_credentials *c_credentials - cdef grpc_ssl_pem_key_cert_pair c_ssl_pem_key_cert_pair - cdef list references + # TODO(https://github.com/grpc/grpc/issues/12531): remove. + cdef grpc_call_credentials *c_credentials -cdef class CallCredentials: +cdef int _get_metadata( + void *state, grpc_auth_metadata_context context, + grpc_credentials_plugin_metadata_cb cb, void *user_data, + grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], + size_t *num_creds_md, grpc_status_code *status, + const char **error_details) with gil - cdef grpc_call_credentials *c_credentials - cdef list references +cdef void _destroy(void *state) with gil -cdef class ServerCredentials: +cdef class MetadataPluginCallCredentials(CallCredentials): - cdef grpc_server_credentials *c_credentials - cdef grpc_ssl_pem_key_cert_pair *c_ssl_pem_key_cert_pairs - cdef size_t c_ssl_pem_key_cert_pairs_count - cdef list references + cdef readonly object _metadata_plugin + cdef readonly bytes _name + cdef grpc_call_credentials *c(self) -cdef class CredentialsMetadataPlugin: - cdef object plugin_callback - cdef bytes plugin_name +cdef grpc_call_credentials *_composition(call_credentialses) -cdef grpc_metadata_credentials_plugin _c_plugin(CredentialsMetadataPlugin plugin) +cdef class CompositeCallCredentials(CallCredentials): + cdef readonly tuple _call_credentialses -cdef class AuthMetadataContext: + cdef grpc_call_credentials *c(self) - cdef grpc_auth_metadata_context context +cdef class ChannelCredentials: -cdef int plugin_get_metadata( - void *state, grpc_auth_metadata_context context, - grpc_credentials_plugin_metadata_cb cb, void *user_data, - grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], - size_t *num_creds_md, grpc_status_code *status, - const char **error_details) with gil + cdef grpc_channel_credentials *c(self) -cdef void plugin_destroy_c_plugin_state(void *state) with gil + # TODO(https://github.com/grpc/grpc/issues/12531): remove. + cdef grpc_channel_credentials *c_credentials + + +cdef class SSLChannelCredentials(ChannelCredentials): + + cdef readonly object _pem_root_certificates + cdef readonly object _private_key + cdef readonly object _certificate_chain + + cdef grpc_channel_credentials *c(self) + + +cdef class CompositeChannelCredentials(ChannelCredentials): + + cdef readonly tuple _call_credentialses + cdef readonly ChannelCredentials _channel_credentials + + cdef grpc_channel_credentials *c(self) + + +cdef class ServerCertificateConfig: + + cdef grpc_ssl_server_certificate_config *c_cert_config + cdef const char *c_pem_root_certs + cdef grpc_ssl_pem_key_cert_pair *c_ssl_pem_key_cert_pairs + cdef size_t c_ssl_pem_key_cert_pairs_count + cdef list references + + +cdef class ServerCredentials: + + cdef grpc_server_credentials *c_credentials + cdef grpc_ssl_pem_key_cert_pair *c_ssl_pem_key_cert_pairs + cdef size_t c_ssl_pem_key_cert_pairs_count + cdef list references + # the cert config related state is used only if this credentials is + # created with cert config/fetcher + cdef object initial_cert_config + cdef object cert_config_fetcher + # whether C-core has asked for the initial_cert_config + cdef bint initial_cert_config_fetched diff --git a/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pyx.pxi b/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pyx.pxi index 0fabda19ce6..246a2718934 100644 --- a/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pyx.pxi +++ b/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pyx.pxi @@ -14,274 +14,237 @@ cimport cpython +import grpc import threading -import traceback -cdef class ChannelCredentials: +cdef class CallCredentials: - def __cinit__(self): - grpc_init() - self.c_credentials = NULL - self.c_ssl_pem_key_cert_pair.private_key = NULL - self.c_ssl_pem_key_cert_pair.certificate_chain = NULL - self.references = [] + cdef grpc_call_credentials *c(self): + raise NotImplementedError() - # The object *can* be invalid in Python if we fail to make the credentials - # (and the core thus returns NULL credentials). Used primarily for debugging. - @property - def is_valid(self): - return self.c_credentials != NULL - def __dealloc__(self): - if self.c_credentials != NULL: - grpc_channel_credentials_release(self.c_credentials) - grpc_shutdown() +cdef int _get_metadata( + void *state, grpc_auth_metadata_context context, + grpc_credentials_plugin_metadata_cb cb, void *user_data, + grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], + size_t *num_creds_md, grpc_status_code *status, + const char **error_details) with gil: + def callback(Metadata metadata, grpc_status_code status, bytes error_details): + if status is StatusCode.ok: + cb(user_data, metadata.c_metadata, metadata.c_count, status, NULL) + else: + cb(user_data, NULL, 0, status, error_details) + args = context.service_url, context.method_name, callback, + threading.Thread(target=state, args=args).start() + return 0 # Asynchronous return -cdef class CallCredentials: +cdef void _destroy(void *state) with gil: + cpython.Py_DECREF(state) - def __cinit__(self): - grpc_init() - self.c_credentials = NULL - self.references = [] - # The object *can* be invalid in Python if we fail to make the credentials - # (and the core thus returns NULL credentials). Used primarily for debugging. - @property - def is_valid(self): - return self.c_credentials != NULL +cdef class MetadataPluginCallCredentials(CallCredentials): - def __dealloc__(self): - if self.c_credentials != NULL: - grpc_call_credentials_release(self.c_credentials) - grpc_shutdown() + def __cinit__(self, metadata_plugin, name): + self._metadata_plugin = metadata_plugin + self._name = name + cdef grpc_call_credentials *c(self): + cdef grpc_metadata_credentials_plugin c_metadata_plugin + c_metadata_plugin.get_metadata = _get_metadata + c_metadata_plugin.destroy = _destroy + c_metadata_plugin.state = self._metadata_plugin + c_metadata_plugin.type = self._name + cpython.Py_INCREF(self._metadata_plugin) + return grpc_metadata_credentials_create_from_plugin(c_metadata_plugin, NULL) -cdef class ServerCredentials: - def __cinit__(self): - grpc_init() - self.c_credentials = NULL - self.references = [] +cdef grpc_call_credentials *_composition(call_credentialses): + call_credentials_iterator = iter(call_credentialses) + cdef CallCredentials composition = next(call_credentials_iterator) + cdef grpc_call_credentials *c_composition = composition.c() + cdef CallCredentials additional_call_credentials + cdef grpc_call_credentials *c_additional_call_credentials + cdef grpc_call_credentials *c_next_composition + for additional_call_credentials in call_credentials_iterator: + c_additional_call_credentials = additional_call_credentials.c() + c_next_composition = grpc_composite_call_credentials_create( + c_composition, c_additional_call_credentials, NULL) + grpc_call_credentials_release(c_composition) + grpc_call_credentials_release(c_additional_call_credentials) + c_composition = c_next_composition + return c_composition - def __dealloc__(self): - if self.c_credentials != NULL: - grpc_server_credentials_release(self.c_credentials) - grpc_shutdown() +cdef class CompositeCallCredentials(CallCredentials): -cdef class CredentialsMetadataPlugin: + def __cinit__(self, call_credentialses): + self._call_credentialses = call_credentialses - def __cinit__(self, object plugin_callback, bytes name): - """ - Args: - plugin_callback (callable): Callback accepting a service URL (str/bytes) - and callback object (accepting a MetadataArray, - grpc_status_code, and a str/bytes error message). This argument - when called should be non-blocking and eventually call the callback - object with the appropriate status code/details and metadata (if - successful). - name (bytes): Plugin name. - """ - grpc_init() - if not callable(plugin_callback): - raise ValueError('expected callable plugin_callback') - self.plugin_callback = plugin_callback - self.plugin_name = name + cdef grpc_call_credentials *c(self): + return _composition(self._call_credentialses) - def __dealloc__(self): - grpc_shutdown() +cdef class ChannelCredentials: -cdef grpc_metadata_credentials_plugin _c_plugin(CredentialsMetadataPlugin plugin): - cdef grpc_metadata_credentials_plugin c_plugin - c_plugin.get_metadata = plugin_get_metadata - c_plugin.destroy = plugin_destroy_c_plugin_state - c_plugin.state = plugin - c_plugin.type = plugin.plugin_name - cpython.Py_INCREF(plugin) - return c_plugin + cdef grpc_channel_credentials *c(self): + raise NotImplementedError() -cdef class AuthMetadataContext: +cdef class SSLChannelCredentials(ChannelCredentials): - def __cinit__(self): - grpc_init() - self.context.service_url = NULL - self.context.method_name = NULL + def __cinit__(self, pem_root_certificates, private_key, certificate_chain): + self._pem_root_certificates = pem_root_certificates + self._private_key = private_key + self._certificate_chain = certificate_chain - @property - def service_url(self): - return self.context.service_url + cdef grpc_channel_credentials *c(self): + cdef const char *c_pem_root_certificates + cdef grpc_ssl_pem_key_cert_pair c_pem_key_certificate_pair + if self._pem_root_certificates is None: + c_pem_root_certificates = NULL + else: + c_pem_root_certificates = self._pem_root_certificates + if self._private_key is None and self._certificate_chain is None: + return grpc_ssl_credentials_create( + c_pem_root_certificates, NULL, NULL) + else: + c_pem_key_certificate_pair.private_key = self._private_key + c_pem_key_certificate_pair.certificate_chain = self._certificate_chain + return grpc_ssl_credentials_create( + c_pem_root_certificates, &c_pem_key_certificate_pair, NULL) - @property - def method_name(self): - return self.context.method_name - def __dealloc__(self): - grpc_shutdown() +cdef class CompositeChannelCredentials(ChannelCredentials): + def __cinit__(self, call_credentialses, channel_credentials): + self._call_credentialses = call_credentialses + self._channel_credentials = channel_credentials -cdef int plugin_get_metadata( - void *state, grpc_auth_metadata_context context, - grpc_credentials_plugin_metadata_cb cb, void *user_data, - grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], - size_t *num_creds_md, grpc_status_code *status, - const char **error_details) with gil: - called_flag = [False] - def python_callback( - Metadata metadata, grpc_status_code status, - bytes error_details): - cb(user_data, metadata.c_metadata, metadata.c_count, status, error_details) - called_flag[0] = True - cdef CredentialsMetadataPlugin self = state - cdef AuthMetadataContext cy_context = AuthMetadataContext() - cy_context.context = context - def async_callback(): - try: - self.plugin_callback(cy_context, python_callback) - except Exception as error: - if not called_flag[0]: - cb(user_data, NULL, 0, StatusCode.unknown, - traceback.format_exc().encode()) - threading.Thread(group=None, target=async_callback).start() - return 0 # Asynchronous return + cdef grpc_channel_credentials *c(self): + cdef grpc_channel_credentials *c_channel_credentials + c_channel_credentials = self._channel_credentials.c() + cdef grpc_call_credentials *c_call_credentials_composition = _composition( + self._call_credentialses) + cdef grpc_channel_credentials *composition + c_composition = grpc_composite_channel_credentials_create( + c_channel_credentials, c_call_credentials_composition, NULL) + grpc_channel_credentials_release(c_channel_credentials) + grpc_call_credentials_release(c_call_credentials_composition) + return c_composition -cdef void plugin_destroy_c_plugin_state(void *state) with gil: - cpython.Py_DECREF(state) -def channel_credentials_google_default(): - cdef ChannelCredentials credentials = ChannelCredentials(); - with nogil: - credentials.c_credentials = grpc_google_default_credentials_create() - return credentials +cdef class ServerCertificateConfig: -def channel_credentials_ssl(pem_root_certificates, - SslPemKeyCertPair ssl_pem_key_cert_pair): - pem_root_certificates = str_to_bytes(pem_root_certificates) - cdef ChannelCredentials credentials = ChannelCredentials() - cdef const char *c_pem_root_certificates = NULL - if pem_root_certificates is not None: - c_pem_root_certificates = pem_root_certificates - credentials.references.append(pem_root_certificates) - if ssl_pem_key_cert_pair is not None: - with nogil: - credentials.c_credentials = grpc_ssl_credentials_create( - c_pem_root_certificates, &ssl_pem_key_cert_pair.c_pair, NULL) - credentials.references.append(ssl_pem_key_cert_pair) - else: - with nogil: - credentials.c_credentials = grpc_ssl_credentials_create( - c_pem_root_certificates, NULL, NULL) - return credentials + def __cinit__(self): + grpc_init() + self.c_cert_config = NULL + self.c_pem_root_certs = NULL + self.c_ssl_pem_key_cert_pairs = NULL + self.references = [] -def channel_credentials_composite( - ChannelCredentials credentials_1 not None, - CallCredentials credentials_2 not None): - if not credentials_1.is_valid or not credentials_2.is_valid: - raise ValueError("passed credentials must both be valid") - cdef ChannelCredentials credentials = ChannelCredentials() - with nogil: - credentials.c_credentials = grpc_composite_channel_credentials_create( - credentials_1.c_credentials, credentials_2.c_credentials, NULL) - credentials.references.append(credentials_1) - credentials.references.append(credentials_2) - return credentials + def __dealloc__(self): + grpc_ssl_server_certificate_config_destroy(self.c_cert_config) + gpr_free(self.c_ssl_pem_key_cert_pairs) + grpc_shutdown() -def call_credentials_composite( - CallCredentials credentials_1 not None, - CallCredentials credentials_2 not None): - if not credentials_1.is_valid or not credentials_2.is_valid: - raise ValueError("passed credentials must both be valid") - cdef CallCredentials credentials = CallCredentials() - with nogil: - credentials.c_credentials = grpc_composite_call_credentials_create( - credentials_1.c_credentials, credentials_2.c_credentials, NULL) - credentials.references.append(credentials_1) - credentials.references.append(credentials_2) - return credentials -def call_credentials_google_compute_engine(): - cdef CallCredentials credentials = CallCredentials() - with nogil: - credentials.c_credentials = ( - grpc_google_compute_engine_credentials_create(NULL)) - return credentials +cdef class ServerCredentials: -def call_credentials_service_account_jwt_access( - json_key, Timespec token_lifetime not None): - json_key = str_to_bytes(json_key) - cdef CallCredentials credentials = CallCredentials() - cdef char *json_key_c_string = json_key - with nogil: - credentials.c_credentials = ( - grpc_service_account_jwt_access_credentials_create( - json_key_c_string, token_lifetime.c_time, NULL)) - credentials.references.append(json_key) - return credentials + def __cinit__(self): + grpc_init() + self.c_credentials = NULL + self.references = [] + self.initial_cert_config = None + self.cert_config_fetcher = None + self.initial_cert_config_fetched = False -def call_credentials_google_refresh_token(json_refresh_token): - json_refresh_token = str_to_bytes(json_refresh_token) - cdef CallCredentials credentials = CallCredentials() - cdef char *json_refresh_token_c_string = json_refresh_token - with nogil: - credentials.c_credentials = grpc_google_refresh_token_credentials_create( - json_refresh_token_c_string, NULL) - credentials.references.append(json_refresh_token) - return credentials + def __dealloc__(self): + if self.c_credentials != NULL: + grpc_server_credentials_release(self.c_credentials) + grpc_shutdown() -def call_credentials_google_iam(authorization_token, authority_selector): - authorization_token = str_to_bytes(authorization_token) - authority_selector = str_to_bytes(authority_selector) - cdef CallCredentials credentials = CallCredentials() - cdef char *authorization_token_c_string = authorization_token - cdef char *authority_selector_c_string = authority_selector - with nogil: - credentials.c_credentials = grpc_google_iam_credentials_create( - authorization_token_c_string, authority_selector_c_string, NULL) - credentials.references.append(authorization_token) - credentials.references.append(authority_selector) - return credentials +cdef const char* _get_c_pem_root_certs(pem_root_certs): + if pem_root_certs is None: + return NULL + else: + return pem_root_certs -def call_credentials_metadata_plugin(CredentialsMetadataPlugin plugin): - cdef CallCredentials credentials = CallCredentials() - cdef grpc_metadata_credentials_plugin c_plugin = _c_plugin(plugin) +cdef grpc_ssl_pem_key_cert_pair* _create_c_ssl_pem_key_cert_pairs(pem_key_cert_pairs): + # return a malloc'ed grpc_ssl_pem_key_cert_pair from a _list_ of SslPemKeyCertPair + for pair in pem_key_cert_pairs: + if not isinstance(pair, SslPemKeyCertPair): + raise TypeError("expected pem_key_cert_pairs to be sequence of " + "SslPemKeyCertPair") + cdef size_t c_ssl_pem_key_cert_pairs_count = len(pem_key_cert_pairs) + cdef grpc_ssl_pem_key_cert_pair* c_ssl_pem_key_cert_pairs = NULL with nogil: - credentials.c_credentials = ( - grpc_metadata_credentials_create_from_plugin(c_plugin, NULL)) - # TODO(atash): the following held reference is *probably* never necessary - credentials.references.append(plugin) - return credentials + c_ssl_pem_key_cert_pairs = ( + gpr_malloc( + sizeof(grpc_ssl_pem_key_cert_pair) * c_ssl_pem_key_cert_pairs_count)) + for i in range(c_ssl_pem_key_cert_pairs_count): + c_ssl_pem_key_cert_pairs[i] = ( + (pem_key_cert_pairs[i]).c_pair) + return c_ssl_pem_key_cert_pairs def server_credentials_ssl(pem_root_certs, pem_key_cert_pairs, bint force_client_auth): pem_root_certs = str_to_bytes(pem_root_certs) - cdef char *c_pem_root_certs = NULL - if pem_root_certs is not None: - c_pem_root_certs = pem_root_certs pem_key_cert_pairs = list(pem_key_cert_pairs) - for pair in pem_key_cert_pairs: - if not isinstance(pair, SslPemKeyCertPair): - raise TypeError("expected pem_key_cert_pairs to be sequence of " - "SslPemKeyCertPair") cdef ServerCredentials credentials = ServerCredentials() - credentials.references.append(pem_key_cert_pairs) credentials.references.append(pem_root_certs) + credentials.references.append(pem_key_cert_pairs) + cdef const char * c_pem_root_certs = _get_c_pem_root_certs(pem_root_certs) credentials.c_ssl_pem_key_cert_pairs_count = len(pem_key_cert_pairs) - with nogil: - credentials.c_ssl_pem_key_cert_pairs = ( - gpr_malloc( - sizeof(grpc_ssl_pem_key_cert_pair) * - credentials.c_ssl_pem_key_cert_pairs_count - )) - for i in range(credentials.c_ssl_pem_key_cert_pairs_count): - credentials.c_ssl_pem_key_cert_pairs[i] = ( - (pem_key_cert_pairs[i]).c_pair) - credentials.c_credentials = grpc_ssl_server_credentials_create( - c_pem_root_certs, credentials.c_ssl_pem_key_cert_pairs, - credentials.c_ssl_pem_key_cert_pairs_count, - GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY if force_client_auth else GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE, - NULL) + credentials.c_ssl_pem_key_cert_pairs = _create_c_ssl_pem_key_cert_pairs(pem_key_cert_pairs) + cdef grpc_ssl_server_certificate_config *c_cert_config = NULL + c_cert_config = grpc_ssl_server_certificate_config_create( + c_pem_root_certs, credentials.c_ssl_pem_key_cert_pairs, + credentials.c_ssl_pem_key_cert_pairs_count) + cdef grpc_ssl_server_credentials_options* c_options = NULL + # C-core assumes ownership of c_cert_config + c_options = grpc_ssl_server_credentials_create_options_using_config( + GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY + if force_client_auth else + GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE, + c_cert_config) + # C-core assumes ownership of c_options + credentials.c_credentials = grpc_ssl_server_credentials_create_with_options(c_options) return credentials +def server_certificate_config_ssl(pem_root_certs, pem_key_cert_pairs): + pem_root_certs = str_to_bytes(pem_root_certs) + pem_key_cert_pairs = list(pem_key_cert_pairs) + cdef ServerCertificateConfig cert_config = ServerCertificateConfig() + cert_config.references.append(pem_root_certs) + cert_config.references.append(pem_key_cert_pairs) + cert_config.c_pem_root_certs = _get_c_pem_root_certs(pem_root_certs) + cert_config.c_ssl_pem_key_cert_pairs_count = len(pem_key_cert_pairs) + cert_config.c_ssl_pem_key_cert_pairs = _create_c_ssl_pem_key_cert_pairs(pem_key_cert_pairs) + cert_config.c_cert_config = grpc_ssl_server_certificate_config_create( + cert_config.c_pem_root_certs, cert_config.c_ssl_pem_key_cert_pairs, + cert_config.c_ssl_pem_key_cert_pairs_count) + return cert_config + +def server_credentials_ssl_dynamic_cert_config(initial_cert_config, + cert_config_fetcher, + bint force_client_auth): + if not isinstance(initial_cert_config, grpc.ServerCertificateConfiguration): + raise TypeError( + 'initial_cert_config must be a grpc.ServerCertificateConfiguration') + if not callable(cert_config_fetcher): + raise TypeError('cert_config_fetcher must be callable') + cdef ServerCredentials credentials = ServerCredentials() + credentials.initial_cert_config = initial_cert_config + credentials.cert_config_fetcher = cert_config_fetcher + cdef grpc_ssl_server_credentials_options* c_options = NULL + c_options = grpc_ssl_server_credentials_create_options_using_config_fetcher( + GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY + if force_client_auth else + GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE, + _server_cert_config_fetcher_wrapper, + credentials) + # C-core assumes ownership of c_options + credentials.c_credentials = grpc_ssl_server_credentials_create_with_options(c_options) + return credentials diff --git a/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi b/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi index f115106e605..660263fc09d 100644 --- a/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi +++ b/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi @@ -391,6 +391,42 @@ cdef extern from "grpc/grpc_security.h": GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY + ctypedef enum grpc_ssl_certificate_config_reload_status: + GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED + GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_NEW + GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL + + ctypedef struct grpc_ssl_server_certificate_config: + # We don't care about the internals + pass + + ctypedef struct grpc_ssl_server_credentials_options: + # We don't care about the internals + pass + + grpc_ssl_server_certificate_config * grpc_ssl_server_certificate_config_create( + const char *pem_root_certs, + const grpc_ssl_pem_key_cert_pair *pem_key_cert_pairs, + size_t num_key_cert_pairs) + + void grpc_ssl_server_certificate_config_destroy(grpc_ssl_server_certificate_config *config) + + ctypedef grpc_ssl_certificate_config_reload_status (*grpc_ssl_server_certificate_config_callback)( + void *user_data, + grpc_ssl_server_certificate_config **config) + + grpc_ssl_server_credentials_options *grpc_ssl_server_credentials_create_options_using_config( + grpc_ssl_client_certificate_request_type client_certificate_request, + grpc_ssl_server_certificate_config *certificate_config) + + grpc_ssl_server_credentials_options* grpc_ssl_server_credentials_create_options_using_config_fetcher( + grpc_ssl_client_certificate_request_type client_certificate_request, + grpc_ssl_server_certificate_config_callback cb, + void *user_data) + + grpc_server_credentials *grpc_ssl_server_credentials_create_with_options( + grpc_ssl_server_credentials_options *options) + ctypedef struct grpc_ssl_pem_key_cert_pair: const char *private_key const char *certificate_chain "cert_chain" @@ -440,10 +476,6 @@ cdef extern from "grpc/grpc_security.h": # We don't care about the internals (and in fact don't know them) pass - grpc_server_credentials *grpc_ssl_server_credentials_create( - const char *pem_root_certs, - grpc_ssl_pem_key_cert_pair *pem_key_cert_pairs, - size_t num_key_cert_pairs, int force_client_auth, void *reserved) void grpc_server_credentials_release(grpc_server_credentials *creds) nogil int grpc_server_add_secure_http2_port(grpc_server *server, const char *addr, diff --git a/src/python/grpcio/grpc/_cython/_cygrpc/server.pyx.pxi b/src/python/grpcio/grpc/_cython/_cygrpc/server.pyx.pxi index b8db27469f9..5f3405936c6 100644 --- a/src/python/grpcio/grpc/_cython/_cygrpc/server.pyx.pxi +++ b/src/python/grpcio/grpc/_cython/_cygrpc/server.pyx.pxi @@ -14,8 +14,46 @@ cimport cpython +import logging import time +import grpc +cdef grpc_ssl_certificate_config_reload_status _server_cert_config_fetcher_wrapper( + void* user_data, grpc_ssl_server_certificate_config **config) with gil: + # This is a credentials.ServerCertificateConfig + cdef ServerCertificateConfig cert_config = None + if not user_data: + raise ValueError('internal error: user_data must be specified') + credentials = user_data + if not credentials.initial_cert_config_fetched: + # C-core is asking for the initial cert config + credentials.initial_cert_config_fetched = True + cert_config = credentials.initial_cert_config._certificate_configuration + else: + user_cb = credentials.cert_config_fetcher + try: + cert_config_wrapper = user_cb() + except Exception: + logging.exception('Error fetching certificate config') + return GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL + if cert_config_wrapper is None: + return GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED + elif not isinstance( + cert_config_wrapper, grpc.ServerCertificateConfiguration): + logging.error( + 'Error fetching certificate configuration: certificate ' + 'configuration must be of type grpc.ServerCertificateConfiguration, ' + 'not %s' % type(cert_config_wrapper).__name__) + return GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL + else: + cert_config = cert_config_wrapper._certificate_configuration + config[0] = cert_config.c_cert_config + # our caller will assume ownership of memory, so we have to recreate + # a copy of c_cert_config here + cert_config.c_cert_config = grpc_ssl_server_certificate_config_create( + cert_config.c_pem_root_certs, cert_config.c_ssl_pem_key_cert_pairs, + cert_config.c_ssl_pem_key_cert_pairs_count) + return GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_NEW cdef class Server: diff --git a/src/python/grpcio/grpc/_grpcio_metadata.py b/src/python/grpcio/grpc/_grpcio_metadata.py index 0887ac17224..993c49d4af2 100644 --- a/src/python/grpcio/grpc/_grpcio_metadata.py +++ b/src/python/grpcio/grpc/_grpcio_metadata.py @@ -14,4 +14,4 @@ # AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio/grpc/_grpcio_metadata.py.template`!!! -__version__ = """1.8.0.dev0""" +__version__ = """1.9.0.dev0""" diff --git a/src/python/grpcio/grpc/_plugin_wrapping.py b/src/python/grpcio/grpc/_plugin_wrapping.py index bea2c0f1396..cd17f4a0493 100644 --- a/src/python/grpcio/grpc/_plugin_wrapping.py +++ b/src/python/grpcio/grpc/_plugin_wrapping.py @@ -13,6 +13,7 @@ # limitations under the License. import collections +import logging import threading import grpc @@ -20,89 +21,79 @@ from grpc import _common from grpc._cython import cygrpc -class AuthMetadataContext( +class _AuthMetadataContext( collections.namedtuple('AuthMetadataContext', ( 'service_url', 'method_name',)), grpc.AuthMetadataContext): pass -class AuthMetadataPluginCallback(grpc.AuthMetadataContext): +class _CallbackState(object): - def __init__(self, callback): - self._callback = callback - - def __call__(self, metadata, error): - self._callback(metadata, error) + def __init__(self): + self.lock = threading.Lock() + self.called = False + self.exception = None -class _WrappedCygrpcCallback(object): +class _AuthMetadataPluginCallback(grpc.AuthMetadataPluginCallback): - def __init__(self, cygrpc_callback): - self.is_called = False - self.error = None - self.is_called_lock = threading.Lock() - self.cygrpc_callback = cygrpc_callback - - def _invoke_failure(self, error): - # TODO(atash) translate different Exception superclasses into different - # status codes. - self.cygrpc_callback(_common.EMPTY_METADATA, cygrpc.StatusCode.internal, - _common.encode(str(error))) - - def _invoke_success(self, metadata): - try: - cygrpc_metadata = _common.to_cygrpc_metadata(metadata) - except Exception as exception: # pylint: disable=broad-except - self._invoke_failure(exception) - return - self.cygrpc_callback(cygrpc_metadata, cygrpc.StatusCode.ok, b'') + def __init__(self, state, callback): + self._state = state + self._callback = callback def __call__(self, metadata, error): - with self.is_called_lock: - if self.is_called: - raise RuntimeError('callback should only ever be invoked once') - if self.error: - self._invoke_failure(self.error) - return - self.is_called = True + with self._state.lock: + if self._state.exception is None: + if self._state.called: + raise RuntimeError( + 'AuthMetadataPluginCallback invoked more than once!') + else: + self._state.called = True + else: + raise RuntimeError( + 'AuthMetadataPluginCallback raised exception "{}"!'.format( + self._state.exception)) if error is None: - self._invoke_success(metadata) + self._callback( + _common.to_cygrpc_metadata(metadata), cygrpc.StatusCode.ok, + None) else: - self._invoke_failure(error) - - def notify_failure(self, error): - with self.is_called_lock: - if not self.is_called: - self.error = error + self._callback(None, cygrpc.StatusCode.internal, + _common.encode(str(error))) -class _WrappedPlugin(object): +class _Plugin(object): - def __init__(self, plugin): - self.plugin = plugin + def __init__(self, metadata_plugin): + self._metadata_plugin = metadata_plugin - def __call__(self, context, cygrpc_callback): - wrapped_cygrpc_callback = _WrappedCygrpcCallback(cygrpc_callback) - wrapped_context = AuthMetadataContext( - _common.decode(context.service_url), - _common.decode(context.method_name)) + def __call__(self, service_url, method_name, callback): + context = _AuthMetadataContext( + _common.decode(service_url), _common.decode(method_name)) + callback_state = _CallbackState() + try: + self._metadata_plugin( + context, _AuthMetadataPluginCallback(callback_state, callback)) + except Exception as exception: # pylint: disable=broad-except + logging.exception( + 'AuthMetadataPluginCallback "%s" raised exception!', + self._metadata_plugin) + with callback_state.lock: + callback_state.exception = exception + if callback_state.called: + return + callback(None, cygrpc.StatusCode.internal, + _common.encode(str(exception))) + + +def metadata_plugin_call_credentials(metadata_plugin, name): + if name is None: try: - self.plugin(wrapped_context, - AuthMetadataPluginCallback(wrapped_cygrpc_callback)) - except Exception as error: - wrapped_cygrpc_callback.notify_failure(error) - raise - - -def call_credentials_metadata_plugin(plugin, name): - """ - Args: - plugin: A callable accepting a grpc.AuthMetadataContext - object and a callback (itself accepting a list of metadata key/value - 2-tuples and a None-able exception value). The callback must be eventually - called, but need not be called in plugin's invocation. - plugin's invocation must be non-blocking. - """ - return cygrpc.call_credentials_metadata_plugin( - cygrpc.CredentialsMetadataPlugin( - _WrappedPlugin(plugin), _common.encode(name))) + effective_name = metadata_plugin.__name__ + except AttributeError: + effective_name = metadata_plugin.__class__.__name__ + else: + effective_name = name + return grpc.CallCredentials( + cygrpc.MetadataPluginCallCredentials( + _Plugin(metadata_plugin), _common.encode(effective_name))) diff --git a/src/python/grpcio/grpc/_server.py b/src/python/grpcio/grpc/_server.py index cd59b07c04c..5b4812bffe8 100644 --- a/src/python/grpcio/grpc/_server.py +++ b/src/python/grpcio/grpc/_server.py @@ -374,10 +374,10 @@ def _call_behavior(rpc_event, state, behavior, argument, request_deserializer): context = _Context(rpc_event, state, request_deserializer) try: return behavior(argument, context), True - except Exception as e: # pylint: disable=broad-except + except Exception as exception: # pylint: disable=broad-except with state.condition: - if e not in state.rpc_errors: - details = 'Exception calling application: {}'.format(e) + if exception not in state.rpc_errors: + details = 'Exception calling application: {}'.format(exception) logging.exception(details) _abort(state, rpc_event.operation_call, cygrpc.StatusCode.unknown, _common.encode(details)) @@ -389,10 +389,10 @@ def _take_response_from_response_iterator(rpc_event, state, response_iterator): return next(response_iterator), True except StopIteration: return None, True - except Exception as e: # pylint: disable=broad-except + except Exception as exception: # pylint: disable=broad-except with state.condition: - if e not in state.rpc_errors: - details = 'Exception iterating responses: {}'.format(e) + if exception not in state.rpc_errors: + details = 'Exception iterating responses: {}'.format(exception) logging.exception(details) _abort(state, rpc_event.operation_call, cygrpc.StatusCode.unknown, _common.encode(details)) @@ -591,7 +591,13 @@ def _handle_call(rpc_event, generic_handlers, thread_pool, if not rpc_event.success: return None, None if rpc_event.request_call_details.method is not None: - method_handler = _find_method_handler(rpc_event, generic_handlers) + try: + method_handler = _find_method_handler(rpc_event, generic_handlers) + except Exception as exception: # pylint: disable=broad-except + details = 'Exception servicing handler: {}'.format(exception) + logging.exception(details) + return _reject_rpc(rpc_event, cygrpc.StatusCode.unknown, + b'Error in service handler!'), None if method_handler is None: return _reject_rpc(rpc_event, cygrpc.StatusCode.unimplemented, b'Method not found!'), None diff --git a/src/python/grpcio/grpc_core_dependencies.py b/src/python/grpcio/grpc_core_dependencies.py index bb7d990078f..d2a68f0902f 100644 --- a/src/python/grpcio/grpc_core_dependencies.py +++ b/src/python/grpcio/grpc_core_dependencies.py @@ -29,7 +29,7 @@ CORE_SOURCE_FILES = [ 'src/core/lib/support/env_linux.cc', 'src/core/lib/support/env_posix.cc', 'src/core/lib/support/env_windows.cc', - 'src/core/lib/support/histogram.cc', + 'src/core/lib/support/fork.cc', 'src/core/lib/support/host_port.cc', 'src/core/lib/support/log.cc', 'src/core/lib/support/log_android.cc', @@ -38,7 +38,6 @@ CORE_SOURCE_FILES = [ 'src/core/lib/support/log_windows.cc', 'src/core/lib/support/mpscq.cc', 'src/core/lib/support/murmur_hash.cc', - 'src/core/lib/support/stack_lockfree.cc', 'src/core/lib/support/string.cc', 'src/core/lib/support/string_posix.cc', 'src/core/lib/support/string_util_windows.cc', @@ -80,7 +79,6 @@ CORE_SOURCE_FILES = [ 'src/core/lib/http/httpcli.cc', 'src/core/lib/http/parser.cc', 'src/core/lib/iomgr/call_combiner.cc', - 'src/core/lib/iomgr/closure.cc', 'src/core/lib/iomgr/combiner.cc', 'src/core/lib/iomgr/endpoint.cc', 'src/core/lib/iomgr/endpoint_pair_posix.cc', @@ -95,6 +93,8 @@ CORE_SOURCE_FILES = [ 'src/core/lib/iomgr/ev_windows.cc', 'src/core/lib/iomgr/exec_ctx.cc', 'src/core/lib/iomgr/executor.cc', + 'src/core/lib/iomgr/fork_posix.cc', + 'src/core/lib/iomgr/fork_windows.cc', 'src/core/lib/iomgr/gethostname_fallback.cc', 'src/core/lib/iomgr/gethostname_host_name_max.cc', 'src/core/lib/iomgr/gethostname_sysconf.cc', diff --git a/src/python/grpcio/grpc_version.py b/src/python/grpcio/grpc_version.py index 61c41573756..8f07f3b30b2 100644 --- a/src/python/grpcio/grpc_version.py +++ b/src/python/grpcio/grpc_version.py @@ -14,4 +14,4 @@ # AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio/grpc_version.py.template`!!! -VERSION='1.8.0.dev0' +VERSION='1.9.0.dev0' diff --git a/src/python/grpcio_health_checking/MANIFEST.in b/src/python/grpcio_health_checking/MANIFEST.in index 5255e4c4036..996c74a9d49 100644 --- a/src/python/grpcio_health_checking/MANIFEST.in +++ b/src/python/grpcio_health_checking/MANIFEST.in @@ -1,4 +1,3 @@ include grpc_version.py -include health_commands.py -graft grpc_health +recursive-include grpc_health *.py global-exclude *.pyc diff --git a/src/python/grpcio_health_checking/grpc_version.py b/src/python/grpcio_health_checking/grpc_version.py index 889297f0209..0987d57261d 100644 --- a/src/python/grpcio_health_checking/grpc_version.py +++ b/src/python/grpcio_health_checking/grpc_version.py @@ -14,4 +14,4 @@ # AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_health_checking/grpc_version.py.template`!!! -VERSION='1.8.0.dev0' +VERSION='1.9.0.dev0' diff --git a/src/python/grpcio_health_checking/setup.py b/src/python/grpcio_health_checking/setup.py index 1f5e9c5130b..c105f57509f 100644 --- a/src/python/grpcio_health_checking/setup.py +++ b/src/python/grpcio_health_checking/setup.py @@ -20,10 +20,26 @@ import setuptools # Ensure we're in the proper directory whether or not we're being used by pip. os.chdir(os.path.dirname(os.path.abspath(__file__))) -# Break import-style to ensure we can actually find our commands module. -import health_commands +# Break import-style to ensure we can actually find our local modules. import grpc_version + +class _NoOpCommand(setuptools.Command): + """No-op command.""" + + description = '' + user_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + pass + + CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python', @@ -40,17 +56,26 @@ PACKAGE_DIRECTORIES = { '': '.', } -SETUP_REQUIRES = ( - 'grpcio-tools>={version}'.format(version=grpc_version.VERSION),) - -INSTALL_REQUIRES = ('protobuf>=3.3.0', +INSTALL_REQUIRES = ('protobuf>=3.5.0.post1', 'grpcio>={version}'.format(version=grpc_version.VERSION),) -COMMAND_CLASS = { - # Run preprocess from the repository *before* doing any packaging! - 'preprocess': health_commands.CopyProtoModules, - 'build_package_protos': health_commands.BuildPackageProtos, -} +try: + import health_commands as _health_commands + # we are in the build environment, otherwise the above import fails + SETUP_REQUIRES = ( + 'grpcio-tools=={version}'.format(version=grpc_version.VERSION),) + COMMAND_CLASS = { + # Run preprocess from the repository *before* doing any packaging! + 'preprocess': _health_commands.CopyProtoModules, + 'build_package_protos': _health_commands.BuildPackageProtos, + } +except ImportError: + SETUP_REQUIRES = () + COMMAND_CLASS = { + # wire up commands to no-op not to break the external dependencies + 'preprocess': _NoOpCommand, + 'build_package_protos': _NoOpCommand, + } setuptools.setup( name='grpcio-health-checking', diff --git a/src/python/grpcio_reflection/MANIFEST.in b/src/python/grpcio_reflection/MANIFEST.in index 0f2130c0b58..d6fb6ce73aa 100644 --- a/src/python/grpcio_reflection/MANIFEST.in +++ b/src/python/grpcio_reflection/MANIFEST.in @@ -1,4 +1,3 @@ include grpc_version.py -include reflection_commands.py -graft grpc_reflection +recursive-include grpc_reflection *.py global-exclude *.pyc diff --git a/src/python/grpcio_reflection/grpc_version.py b/src/python/grpcio_reflection/grpc_version.py index 192f4cc2174..95d2ff143ad 100644 --- a/src/python/grpcio_reflection/grpc_version.py +++ b/src/python/grpcio_reflection/grpc_version.py @@ -14,4 +14,4 @@ # AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_reflection/grpc_version.py.template`!!! -VERSION='1.8.0.dev0' +VERSION='1.9.0.dev0' diff --git a/src/python/grpcio_reflection/reflection_commands.py b/src/python/grpcio_reflection/reflection_commands.py index e2b1aa015bc..6f91f6b8751 100644 --- a/src/python/grpcio_reflection/reflection_commands.py +++ b/src/python/grpcio_reflection/reflection_commands.py @@ -19,7 +19,7 @@ import shutil import setuptools ROOT_DIR = os.path.abspath(os.path.dirname(os.path.abspath(__file__))) -HEALTH_PROTO = os.path.join( +REFLECTION_PROTO = os.path.join( ROOT_DIR, '../../proto/grpc/reflection/v1alpha/reflection.proto') @@ -36,9 +36,9 @@ class CopyProtoModules(setuptools.Command): pass def run(self): - if os.path.isfile(HEALTH_PROTO): + if os.path.isfile(REFLECTION_PROTO): shutil.copyfile( - HEALTH_PROTO, + REFLECTION_PROTO, os.path.join(ROOT_DIR, 'grpc_reflection/v1alpha/reflection.proto')) diff --git a/src/python/grpcio_reflection/setup.py b/src/python/grpcio_reflection/setup.py index 9360550afbc..760b89373af 100644 --- a/src/python/grpcio_reflection/setup.py +++ b/src/python/grpcio_reflection/setup.py @@ -21,10 +21,26 @@ import setuptools # Ensure we're in the proper directory whether or not we're being used by pip. os.chdir(os.path.dirname(os.path.abspath(__file__))) -# Break import-style to ensure we can actually find our commands module. -import reflection_commands +# Break import-style to ensure we can actually find our local modules. import grpc_version + +class _NoOpCommand(setuptools.Command): + """No-op command.""" + + description = '' + user_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + pass + + CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python', @@ -41,17 +57,26 @@ PACKAGE_DIRECTORIES = { '': '.', } -SETUP_REQUIRES = ( - 'grpcio-tools>={version}'.format(version=grpc_version.VERSION),) - -INSTALL_REQUIRES = ('protobuf>=3.3.0', +INSTALL_REQUIRES = ('protobuf>=3.5.0.post1', 'grpcio>={version}'.format(version=grpc_version.VERSION),) -COMMAND_CLASS = { - # Run preprocess from the repository *before* doing any packaging! - 'preprocess': reflection_commands.CopyProtoModules, - 'build_package_protos': reflection_commands.BuildPackageProtos, -} +try: + import reflection_commands as _reflection_commands + # we are in the build environment, otherwise the above import fails + SETUP_REQUIRES = ( + 'grpcio-tools=={version}'.format(version=grpc_version.VERSION),) + COMMAND_CLASS = { + # Run preprocess from the repository *before* doing any packaging! + 'preprocess': _reflection_commands.CopyProtoModules, + 'build_package_protos': _reflection_commands.BuildPackageProtos, + } +except ImportError: + SETUP_REQUIRES = () + COMMAND_CLASS = { + # wire up commands to no-op not to break the external dependencies + 'preprocess': _NoOpCommand, + 'build_package_protos': _NoOpCommand, + } setuptools.setup( name='grpcio-reflection', diff --git a/src/python/grpcio_testing/grpc_version.py b/src/python/grpcio_testing/grpc_version.py index 83470c28253..afc6dd83f29 100644 --- a/src/python/grpcio_testing/grpc_version.py +++ b/src/python/grpcio_testing/grpc_version.py @@ -14,4 +14,4 @@ # AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_testing/grpc_version.py.template`!!! -VERSION='1.8.0.dev0' +VERSION='1.9.0.dev0' diff --git a/src/python/grpcio_testing/setup.py b/src/python/grpcio_testing/setup.py index 0cc336abd1f..fa40424f6a2 100644 --- a/src/python/grpcio_testing/setup.py +++ b/src/python/grpcio_testing/setup.py @@ -28,7 +28,7 @@ PACKAGE_DIRECTORIES = { '': '.', } -INSTALL_REQUIRES = ('protobuf>=3.3.0', +INSTALL_REQUIRES = ('protobuf>=3.5.0.post1', 'grpcio>={version}'.format(version=grpc_version.VERSION),) setuptools.setup( diff --git a/src/python/grpcio_tests/grpc_version.py b/src/python/grpcio_tests/grpc_version.py index 7065edd3bfc..99ca3fd82dd 100644 --- a/src/python/grpcio_tests/grpc_version.py +++ b/src/python/grpcio_tests/grpc_version.py @@ -14,4 +14,4 @@ # AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_tests/grpc_version.py.template`!!! -VERSION='1.8.0.dev0' +VERSION='1.9.0.dev0' diff --git a/src/python/grpcio_tests/setup.py b/src/python/grpcio_tests/setup.py index debe14c40e5..aeb4ea9c53d 100644 --- a/src/python/grpcio_tests/setup.py +++ b/src/python/grpcio_tests/setup.py @@ -41,8 +41,8 @@ INSTALL_REQUIRES = ( 'grpcio>={version}'.format(version=grpc_version.VERSION), 'grpcio-tools>={version}'.format(version=grpc_version.VERSION), 'grpcio-health-checking>={version}'.format(version=grpc_version.VERSION), - 'oauth2client>=1.4.7', 'protobuf>=3.3.0', 'six>=1.10', 'google-auth>=1.0.0', - 'requests>=2.14.2') + 'oauth2client>=1.4.7', 'protobuf>=3.5.0.post1', 'six>=1.10', + 'google-auth>=1.0.0', 'requests>=2.14.2') COMMAND_CLASS = { # Run `preprocess` *before* doing any packaging! diff --git a/src/python/grpcio_tests/tests/interop/client.py b/src/python/grpcio_tests/tests/interop/client.py index e520c082903..383b5f033d7 100644 --- a/src/python/grpcio_tests/tests/interop/client.py +++ b/src/python/grpcio_tests/tests/interop/client.py @@ -29,37 +29,40 @@ def _args(): parser = argparse.ArgumentParser() parser.add_argument( '--server_host', - help='the host to which to connect', + default="localhost", type=str, - default="localhost") + help='the host to which to connect') parser.add_argument( - '--server_port', help='the port to which to connect', type=int) + '--server_port', + type=int, + required=True, + help='the port to which to connect') parser.add_argument( '--test_case', - help='the test case to execute', + default='large_unary', type=str, - default="large_unary") + help='the test case to execute') parser.add_argument( '--use_tls', - help='require a secure connection', default=False, - type=resources.parse_bool) + type=resources.parse_bool, + help='require a secure connection') parser.add_argument( '--use_test_ca', - help='replace platform root CAs with ca.pem', default=False, - type=resources.parse_bool) + type=resources.parse_bool, + help='replace platform root CAs with ca.pem') parser.add_argument( '--server_host_override', default="foo.test.google.fr", - help='the server host to which to claim to connect', - type=str) + type=str, + help='the server host to which to claim to connect') parser.add_argument( - '--oauth_scope', help='scope for OAuth tokens', type=str) + '--oauth_scope', type=str, help='scope for OAuth tokens') parser.add_argument( '--default_service_account', - help='email address of the default service account', - type=str) + type=str, + help='email address of the default service account') return parser.parse_args() diff --git a/src/python/grpcio_tests/tests/interop/server.py b/src/python/grpcio_tests/tests/interop/server.py index 8ad1f5f7cd5..eeb41a21d23 100644 --- a/src/python/grpcio_tests/tests/interop/server.py +++ b/src/python/grpcio_tests/tests/interop/server.py @@ -29,12 +29,13 @@ _ONE_DAY_IN_SECONDS = 60 * 60 * 24 def serve(): parser = argparse.ArgumentParser() - parser.add_argument('--port', help='the port on which to serve', type=int) + parser.add_argument( + '--port', type=int, required=True, help='the port on which to serve') parser.add_argument( '--use_tls', - help='require a secure connection', default=False, - type=resources.parse_bool) + type=resources.parse_bool, + help='require a secure connection') args = parser.parse_args() server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) diff --git a/src/python/grpcio_tests/tests/tests.json b/src/python/grpcio_tests/tests/tests.json index 8512d5b96fa..34cbade92c3 100644 --- a/src/python/grpcio_tests/tests/tests.json +++ b/src/python/grpcio_tests/tests/tests.json @@ -22,7 +22,7 @@ "unit._api_test.ChannelConnectivityTest", "unit._api_test.ChannelTest", "unit._auth_context_test.AuthContextTest", - "unit._auth_test.AccessTokenCallCredentialsTest", + "unit._auth_test.AccessTokenAuthMetadataPluginTest", "unit._auth_test.GoogleCallCredentialsTest", "unit._channel_args_test.ChannelArgsTest", "unit._channel_connectivity_test.ChannelConnectivityTest", @@ -46,6 +46,10 @@ "unit._reconnect_test.ReconnectTest", "unit._resource_exhausted_test.ResourceExhaustedTest", "unit._rpc_test.RPCTest", + "unit._server_ssl_cert_config_test.ServerSSLCertConfigFetcherParamsChecks", + "unit._server_ssl_cert_config_test.ServerSSLCertReloadTestCertConfigReuse", + "unit._server_ssl_cert_config_test.ServerSSLCertReloadTestWithClientAuth", + "unit._server_ssl_cert_config_test.ServerSSLCertReloadTestWithoutClientAuth", "unit._thread_cleanup_test.CleanupThreadTest", "unit.beta._beta_features_test.BetaFeaturesTest", "unit.beta._beta_features_test.ContextManagementAndLifecycleTest", diff --git a/src/python/grpcio_tests/tests/unit/_api_test.py b/src/python/grpcio_tests/tests/unit/_api_test.py index a3351aab504..b14e8d5c753 100644 --- a/src/python/grpcio_tests/tests/unit/_api_test.py +++ b/src/python/grpcio_tests/tests/unit/_api_test.py @@ -30,18 +30,20 @@ class AllTest(unittest.TestCase): 'ChannelConnectivity', 'StatusCode', 'RpcError', 'RpcContext', 'Call', 'ChannelCredentials', 'CallCredentials', 'AuthMetadataContext', 'AuthMetadataPluginCallback', - 'AuthMetadataPlugin', 'ServerCredentials', - 'UnaryUnaryMultiCallable', 'UnaryStreamMultiCallable', - 'StreamUnaryMultiCallable', 'StreamStreamMultiCallable', 'Channel', - 'ServicerContext', 'RpcMethodHandler', 'HandlerCallDetails', - 'GenericRpcHandler', 'ServiceRpcHandler', 'Server', - 'unary_unary_rpc_method_handler', 'unary_stream_rpc_method_handler', + 'AuthMetadataPlugin', 'ServerCertificateConfiguration', + 'ServerCredentials', 'UnaryUnaryMultiCallable', + 'UnaryStreamMultiCallable', 'StreamUnaryMultiCallable', + 'StreamStreamMultiCallable', 'Channel', 'ServicerContext', + 'RpcMethodHandler', 'HandlerCallDetails', 'GenericRpcHandler', + 'ServiceRpcHandler', 'Server', 'unary_unary_rpc_method_handler', + 'unary_stream_rpc_method_handler', 'stream_unary_rpc_method_handler', 'stream_stream_rpc_method_handler', 'method_handlers_generic_handler', 'ssl_channel_credentials', 'metadata_call_credentials', 'access_token_call_credentials', 'composite_call_credentials', 'composite_channel_credentials', - 'ssl_server_credentials', 'channel_ready_future', + 'ssl_server_credentials', 'ssl_server_certificate_configuration', + 'dynamic_ssl_server_credentials', 'channel_ready_future', 'insecure_channel', 'secure_channel', 'server',) six.assertCountEqual(self, expected_grpc_code_elements, diff --git a/src/python/grpcio_tests/tests/unit/_auth_test.py b/src/python/grpcio_tests/tests/unit/_auth_test.py index f61951b80a0..e2cb9389368 100644 --- a/src/python/grpcio_tests/tests/unit/_auth_test.py +++ b/src/python/grpcio_tests/tests/unit/_auth_test.py @@ -61,7 +61,7 @@ class GoogleCallCredentialsTest(unittest.TestCase): self.assertTrue(callback_event.wait(1.0)) -class AccessTokenCallCredentialsTest(unittest.TestCase): +class AccessTokenAuthMetadataPluginTest(unittest.TestCase): def test_google_call_credentials_success(self): callback_event = threading.Event() @@ -71,8 +71,8 @@ class AccessTokenCallCredentialsTest(unittest.TestCase): self.assertIsNone(error) callback_event.set() - call_creds = _auth.AccessTokenCallCredentials('token') - call_creds(None, mock_callback) + metadata_plugin = _auth.AccessTokenAuthMetadataPlugin('token') + metadata_plugin(None, mock_callback) self.assertTrue(callback_event.wait(1.0)) diff --git a/src/python/grpcio_tests/tests/unit/_cython/cygrpc_test.py b/src/python/grpcio_tests/tests/unit/_cython/cygrpc_test.py index 18d4a6df64c..da94cf80286 100644 --- a/src/python/grpcio_tests/tests/unit/_cython/cygrpc_test.py +++ b/src/python/grpcio_tests/tests/unit/_cython/cygrpc_test.py @@ -28,7 +28,7 @@ _CALL_CREDENTIALS_METADATA_VALUE = 'call-creds-value' _EMPTY_FLAGS = 0 -def _metadata_plugin_callback(context, callback): +def _metadata_plugin(context, callback): callback( cygrpc.Metadata([ cygrpc.Metadatum(_CALL_CREDENTIALS_METADATA_KEY, @@ -105,17 +105,9 @@ class TypeSmokeTest(unittest.TestCase): channel = cygrpc.Channel(b'[::]:0', cygrpc.ChannelArgs([])) del channel - def testCredentialsMetadataPluginUpDown(self): - plugin = cygrpc.CredentialsMetadataPlugin( - lambda ignored_a, ignored_b: None, b'') - del plugin - - def testCallCredentialsFromPluginUpDown(self): - plugin = cygrpc.CredentialsMetadataPlugin(_metadata_plugin_callback, - b'') - call_credentials = cygrpc.call_credentials_metadata_plugin(plugin) - del plugin - del call_credentials + def test_metadata_plugin_call_credentials_up_down(self): + cygrpc.MetadataPluginCallCredentials(_metadata_plugin, + b'test plugin name!') def testServerStartNoExplicitShutdown(self): server = cygrpc.Server(cygrpc.ChannelArgs([])) @@ -205,7 +197,7 @@ class ServerClientMixin(object): return test_utilities.SimpleFuture(performer) - def testEcho(self): + def test_echo(self): DEADLINE = time.time() + 5 DEADLINE_TOLERANCE = 0.25 CLIENT_METADATA_ASCII_KEY = b'key' @@ -439,8 +431,8 @@ class SecureServerSecureClient(unittest.TestCase, ServerClientMixin): cygrpc.SslPemKeyCertPair(resources.private_key(), resources.certificate_chain()) ], False) - client_credentials = cygrpc.channel_credentials_ssl( - resources.test_root_certificates(), None) + client_credentials = cygrpc.SSLChannelCredentials( + resources.test_root_certificates(), None, None) self.setUpMixin(server_credentials, client_credentials, _SSL_HOST_OVERRIDE) diff --git a/src/python/grpcio_tests/tests/unit/_invocation_defects_test.py b/src/python/grpcio_tests/tests/unit/_invocation_defects_test.py index 0a1e50c94cb..2a1a49ce747 100644 --- a/src/python/grpcio_tests/tests/unit/_invocation_defects_test.py +++ b/src/python/grpcio_tests/tests/unit/_invocation_defects_test.py @@ -32,6 +32,7 @@ _UNARY_UNARY = '/test/UnaryUnary' _UNARY_STREAM = '/test/UnaryStream' _STREAM_UNARY = '/test/StreamUnary' _STREAM_STREAM = '/test/StreamStream' +_DEFECTIVE_GENERIC_RPC_HANDLER = '/test/DefectiveGenericRpcHandler' class _Callback(object): @@ -95,6 +96,9 @@ class _Handler(object): yield request self._control.control() + def defective_generic_rpc_handler(self): + raise test_control.Defect() + class _MethodHandler(grpc.RpcMethodHandler): @@ -132,6 +136,8 @@ class _GenericHandler(grpc.GenericRpcHandler): elif handler_call_details.method == _STREAM_STREAM: return _MethodHandler(True, True, None, None, None, None, None, self._handler.handle_stream_stream) + elif handler_call_details.method == _DEFECTIVE_GENERIC_RPC_HANDLER: + return self._handler.defective_generic_rpc_handler() else: return None @@ -176,6 +182,10 @@ def _stream_stream_multi_callable(channel): return channel.stream_stream(_STREAM_STREAM) +def _defective_handler_multi_callable(channel): + return channel.unary_unary(_DEFECTIVE_GENERIC_RPC_HANDLER) + + class InvocationDefectsTest(unittest.TestCase): def setUp(self): @@ -235,6 +245,18 @@ class InvocationDefectsTest(unittest.TestCase): for _ in range(test_constants.STREAM_LENGTH // 2 + 1): next(response_iterator) + def testDefectiveGenericRpcHandlerUnaryResponse(self): + request = b'\x07\x08' + multi_callable = _defective_handler_multi_callable(self._channel) + + with self.assertRaises(grpc.RpcError) as exception_context: + response = multi_callable( + request, + metadata=(('test', 'DefectiveGenericRpcHandlerUnary'),)) + + self.assertIs(grpc.StatusCode.UNKNOWN, + exception_context.exception.code()) + if __name__ == '__main__': unittest.main(verbosity=2) diff --git a/src/python/grpcio_tests/tests/unit/_server_ssl_cert_config_test.py b/src/python/grpcio_tests/tests/unit/_server_ssl_cert_config_test.py new file mode 100644 index 00000000000..005d16ea757 --- /dev/null +++ b/src/python/grpcio_tests/tests/unit/_server_ssl_cert_config_test.py @@ -0,0 +1,519 @@ +# Copyright 2017 gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests server certificate rotation. + +Here we test various aspects of gRPC Python, and in some cases gRPC +Core by extension, support for server certificate rotation. + +* ServerSSLCertReloadTestWithClientAuth: test ability to rotate + server's SSL cert for use in future channels with clients while not + affecting any existing channel. The server requires client + authentication. + +* ServerSSLCertReloadTestWithoutClientAuth: like + ServerSSLCertReloadTestWithClientAuth except that the server does + not authenticate the client. + +* ServerSSLCertReloadTestCertConfigReuse: tests gRPC Python's ability + to deal with user's reuse of ServerCertificateConfiguration instances. +""" + +import abc +import collections +import os +import six +import threading +import unittest + +from concurrent import futures + +import grpc +from tests.unit import resources +from tests.testing import _application_common +from tests.testing import _server_application +from tests.testing.proto import services_pb2_grpc + +CA_1_PEM = resources.cert_hier_1_root_ca_cert() +CA_2_PEM = resources.cert_hier_2_root_ca_cert() + +CLIENT_KEY_1_PEM = resources.cert_hier_1_client_1_key() +CLIENT_CERT_CHAIN_1_PEM = (resources.cert_hier_1_client_1_cert() + + resources.cert_hier_1_intermediate_ca_cert()) + +CLIENT_KEY_2_PEM = resources.cert_hier_2_client_1_key() +CLIENT_CERT_CHAIN_2_PEM = (resources.cert_hier_2_client_1_cert() + + resources.cert_hier_2_intermediate_ca_cert()) + +SERVER_KEY_1_PEM = resources.cert_hier_1_server_1_key() +SERVER_CERT_CHAIN_1_PEM = (resources.cert_hier_1_server_1_cert() + + resources.cert_hier_1_intermediate_ca_cert()) + +SERVER_KEY_2_PEM = resources.cert_hier_2_server_1_key() +SERVER_CERT_CHAIN_2_PEM = (resources.cert_hier_2_server_1_cert() + + resources.cert_hier_2_intermediate_ca_cert()) + +# for use with the CertConfigFetcher. Roughly a simple custom mock +# implementation +Call = collections.namedtuple('Call', ['did_raise', 'returned_cert_config']) + + +def _create_client_stub( + port, + expect_success, + root_certificates=None, + private_key=None, + certificate_chain=None,): + channel = grpc.secure_channel('localhost:{}'.format(port), + grpc.ssl_channel_credentials( + root_certificates=root_certificates, + private_key=private_key, + certificate_chain=certificate_chain)) + if expect_success: + # per Nathaniel: there's some robustness issue if we start + # using a channel without waiting for it to be actually ready + grpc.channel_ready_future(channel).result(timeout=10) + return services_pb2_grpc.FirstServiceStub(channel) + + +class CertConfigFetcher(object): + + def __init__(self): + self._lock = threading.Lock() + self._calls = [] + self._should_raise = False + self._cert_config = None + + def reset(self): + with self._lock: + self._calls = [] + self._should_raise = False + self._cert_config = None + + def configure(self, should_raise, cert_config): + assert not (should_raise and cert_config), ( + "should not specify both should_raise and a cert_config at the same time" + ) + with self._lock: + self._should_raise = should_raise + self._cert_config = cert_config + + def getCalls(self): + with self._lock: + return self._calls + + def __call__(self): + with self._lock: + if self._should_raise: + self._calls.append(Call(True, None)) + raise ValueError('just for fun, should not affect the test') + else: + self._calls.append(Call(False, self._cert_config)) + return self._cert_config + + +class _ServerSSLCertReloadTest( + six.with_metaclass(abc.ABCMeta, unittest.TestCase)): + + def __init__(self, *args, **kwargs): + super(_ServerSSLCertReloadTest, self).__init__(*args, **kwargs) + self.server = None + self.port = None + + @abc.abstractmethod + def require_client_auth(self): + raise NotImplementedError() + + def setUp(self): + self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) + services_pb2_grpc.add_FirstServiceServicer_to_server( + _server_application.FirstServiceServicer(), self.server) + switch_cert_on_client_num = 10 + initial_cert_config = grpc.ssl_server_certificate_configuration( + [(SERVER_KEY_1_PEM, SERVER_CERT_CHAIN_1_PEM)], + root_certificates=CA_2_PEM) + self.cert_config_fetcher = CertConfigFetcher() + server_credentials = grpc.dynamic_ssl_server_credentials( + initial_cert_config, + self.cert_config_fetcher, + require_client_authentication=self.require_client_auth()) + self.port = self.server.add_secure_port('[::]:0', server_credentials) + self.server.start() + + def tearDown(self): + if self.server: + self.server.stop(None) + + def _perform_rpc(self, client_stub, expect_success): + # we don't care about the actual response of the rpc; only + # whether we can perform it or not, and if not, the status + # code must be UNAVAILABLE + request = _application_common.UNARY_UNARY_REQUEST + if expect_success: + response = client_stub.UnUn(request) + self.assertEqual(response, _application_common.UNARY_UNARY_RESPONSE) + else: + with self.assertRaises(grpc.RpcError) as exception_context: + client_stub.UnUn(request) + self.assertEqual(exception_context.exception.code(), + grpc.StatusCode.UNAVAILABLE) + + def _do_one_shot_client_rpc(self, + expect_success, + root_certificates=None, + private_key=None, + certificate_chain=None): + client_stub = _create_client_stub( + self.port, + expect_success, + root_certificates=root_certificates, + private_key=private_key, + certificate_chain=certificate_chain) + self._perform_rpc(client_stub, expect_success) + del client_stub + + def _test(self): + # things should work... + self.cert_config_fetcher.configure(False, None) + self._do_one_shot_client_rpc( + True, + root_certificates=CA_1_PEM, + private_key=CLIENT_KEY_2_PEM, + certificate_chain=CLIENT_CERT_CHAIN_2_PEM) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertEqual(len(actual_calls), 1) + self.assertFalse(actual_calls[0].did_raise) + self.assertIsNone(actual_calls[0].returned_cert_config) + + # client should reject server... + # fails because client trusts ca2 and so will reject server + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, None) + self._do_one_shot_client_rpc( + False, + root_certificates=CA_2_PEM, + private_key=CLIENT_KEY_2_PEM, + certificate_chain=CLIENT_CERT_CHAIN_2_PEM) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertGreaterEqual(len(actual_calls), 1) + self.assertFalse(actual_calls[0].did_raise) + for i, call in enumerate(actual_calls): + self.assertFalse(call.did_raise, 'i= {}'.format(i)) + self.assertIsNone(call.returned_cert_config, 'i= {}'.format(i)) + + # should work again... + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(True, None) + self._do_one_shot_client_rpc( + True, + root_certificates=CA_1_PEM, + private_key=CLIENT_KEY_2_PEM, + certificate_chain=CLIENT_CERT_CHAIN_2_PEM) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertEqual(len(actual_calls), 1) + self.assertTrue(actual_calls[0].did_raise) + self.assertIsNone(actual_calls[0].returned_cert_config) + + # if with_client_auth, then client should be rejected by + # server because client uses key/cert1, but server trusts ca2, + # so server will reject + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, None) + self._do_one_shot_client_rpc( + not self.require_client_auth(), + root_certificates=CA_1_PEM, + private_key=CLIENT_KEY_1_PEM, + certificate_chain=CLIENT_CERT_CHAIN_1_PEM) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertGreaterEqual(len(actual_calls), 1) + for i, call in enumerate(actual_calls): + self.assertFalse(call.did_raise, 'i= {}'.format(i)) + self.assertIsNone(call.returned_cert_config, 'i= {}'.format(i)) + + # should work again... + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, None) + self._do_one_shot_client_rpc( + True, + root_certificates=CA_1_PEM, + private_key=CLIENT_KEY_2_PEM, + certificate_chain=CLIENT_CERT_CHAIN_2_PEM) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertEqual(len(actual_calls), 1) + self.assertFalse(actual_calls[0].did_raise) + self.assertIsNone(actual_calls[0].returned_cert_config) + + # now create the "persistent" clients + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, None) + persistent_client_stub_A = _create_client_stub( + self.port, + True, + root_certificates=CA_1_PEM, + private_key=CLIENT_KEY_2_PEM, + certificate_chain=CLIENT_CERT_CHAIN_2_PEM) + self._perform_rpc(persistent_client_stub_A, True) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertEqual(len(actual_calls), 1) + self.assertFalse(actual_calls[0].did_raise) + self.assertIsNone(actual_calls[0].returned_cert_config) + + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, None) + persistent_client_stub_B = _create_client_stub( + self.port, + True, + root_certificates=CA_1_PEM, + private_key=CLIENT_KEY_2_PEM, + certificate_chain=CLIENT_CERT_CHAIN_2_PEM) + self._perform_rpc(persistent_client_stub_B, True) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertEqual(len(actual_calls), 1) + self.assertFalse(actual_calls[0].did_raise) + self.assertIsNone(actual_calls[0].returned_cert_config) + + # moment of truth!! client should reject server because the + # server switch cert... + cert_config = grpc.ssl_server_certificate_configuration( + [(SERVER_KEY_2_PEM, SERVER_CERT_CHAIN_2_PEM)], + root_certificates=CA_1_PEM) + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, cert_config) + self._do_one_shot_client_rpc( + False, + root_certificates=CA_1_PEM, + private_key=CLIENT_KEY_2_PEM, + certificate_chain=CLIENT_CERT_CHAIN_2_PEM) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertGreaterEqual(len(actual_calls), 1) + self.assertFalse(actual_calls[0].did_raise) + for i, call in enumerate(actual_calls): + self.assertFalse(call.did_raise, 'i= {}'.format(i)) + self.assertEqual(call.returned_cert_config, cert_config, + 'i= {}'.format(i)) + + # now should work again... + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, None) + self._do_one_shot_client_rpc( + True, + root_certificates=CA_2_PEM, + private_key=CLIENT_KEY_1_PEM, + certificate_chain=CLIENT_CERT_CHAIN_1_PEM) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertEqual(len(actual_calls), 1) + self.assertFalse(actual_calls[0].did_raise) + self.assertIsNone(actual_calls[0].returned_cert_config) + + # client should be rejected by server if with_client_auth + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, None) + self._do_one_shot_client_rpc( + not self.require_client_auth(), + root_certificates=CA_2_PEM, + private_key=CLIENT_KEY_2_PEM, + certificate_chain=CLIENT_CERT_CHAIN_2_PEM) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertGreaterEqual(len(actual_calls), 1) + for i, call in enumerate(actual_calls): + self.assertFalse(call.did_raise, 'i= {}'.format(i)) + self.assertIsNone(call.returned_cert_config, 'i= {}'.format(i)) + + # here client should reject server... + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, None) + self._do_one_shot_client_rpc( + False, + root_certificates=CA_1_PEM, + private_key=CLIENT_KEY_2_PEM, + certificate_chain=CLIENT_CERT_CHAIN_2_PEM) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertGreaterEqual(len(actual_calls), 1) + for i, call in enumerate(actual_calls): + self.assertFalse(call.did_raise, 'i= {}'.format(i)) + self.assertIsNone(call.returned_cert_config, 'i= {}'.format(i)) + + # persistent clients should continue to work + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, None) + self._perform_rpc(persistent_client_stub_A, True) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertEqual(len(actual_calls), 0) + + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, None) + self._perform_rpc(persistent_client_stub_B, True) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertEqual(len(actual_calls), 0) + + +class ServerSSLCertConfigFetcherParamsChecks(unittest.TestCase): + + def test_check_on_initial_config(self): + with self.assertRaises(TypeError): + grpc.dynamic_ssl_server_credentials(None, str) + with self.assertRaises(TypeError): + grpc.dynamic_ssl_server_credentials(1, str) + + def test_check_on_config_fetcher(self): + cert_config = grpc.ssl_server_certificate_configuration( + [(SERVER_KEY_2_PEM, SERVER_CERT_CHAIN_2_PEM)], + root_certificates=CA_1_PEM) + with self.assertRaises(TypeError): + grpc.dynamic_ssl_server_credentials(cert_config, None) + with self.assertRaises(TypeError): + grpc.dynamic_ssl_server_credentials(cert_config, 1) + + +class ServerSSLCertReloadTestWithClientAuth(_ServerSSLCertReloadTest): + + def require_client_auth(self): + return True + + test = _ServerSSLCertReloadTest._test + + +class ServerSSLCertReloadTestWithoutClientAuth(_ServerSSLCertReloadTest): + + def require_client_auth(self): + return False + + test = _ServerSSLCertReloadTest._test + + +class ServerSSLCertReloadTestCertConfigReuse(_ServerSSLCertReloadTest): + """Ensures that `ServerCertificateConfiguration` instances can be reused. + + Because gRPC Core takes ownership of the + `grpc_ssl_server_certificate_config` encapsulated by + `ServerCertificateConfiguration`, this test reuses the same + `ServerCertificateConfiguration` instances multiple times to make sure + gRPC Python takes care of maintaining the validity of + `ServerCertificateConfiguration` instances, so that such instances can be + re-used by user application. + """ + + def require_client_auth(self): + return True + + def setUp(self): + self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) + services_pb2_grpc.add_FirstServiceServicer_to_server( + _server_application.FirstServiceServicer(), self.server) + self.cert_config_A = grpc.ssl_server_certificate_configuration( + [(SERVER_KEY_1_PEM, SERVER_CERT_CHAIN_1_PEM)], + root_certificates=CA_2_PEM) + self.cert_config_B = grpc.ssl_server_certificate_configuration( + [(SERVER_KEY_2_PEM, SERVER_CERT_CHAIN_2_PEM)], + root_certificates=CA_1_PEM) + self.cert_config_fetcher = CertConfigFetcher() + server_credentials = grpc.dynamic_ssl_server_credentials( + self.cert_config_A, + self.cert_config_fetcher, + require_client_authentication=True) + self.port = self.server.add_secure_port('[::]:0', server_credentials) + self.server.start() + + def test_cert_config_reuse(self): + + # succeed with A + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, self.cert_config_A) + self._do_one_shot_client_rpc( + True, + root_certificates=CA_1_PEM, + private_key=CLIENT_KEY_2_PEM, + certificate_chain=CLIENT_CERT_CHAIN_2_PEM) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertEqual(len(actual_calls), 1) + self.assertFalse(actual_calls[0].did_raise) + self.assertEqual(actual_calls[0].returned_cert_config, + self.cert_config_A) + + # fail with A + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, self.cert_config_A) + self._do_one_shot_client_rpc( + False, + root_certificates=CA_2_PEM, + private_key=CLIENT_KEY_1_PEM, + certificate_chain=CLIENT_CERT_CHAIN_1_PEM) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertGreaterEqual(len(actual_calls), 1) + self.assertFalse(actual_calls[0].did_raise) + for i, call in enumerate(actual_calls): + self.assertFalse(call.did_raise, 'i= {}'.format(i)) + self.assertEqual(call.returned_cert_config, self.cert_config_A, + 'i= {}'.format(i)) + + # succeed again with A + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, self.cert_config_A) + self._do_one_shot_client_rpc( + True, + root_certificates=CA_1_PEM, + private_key=CLIENT_KEY_2_PEM, + certificate_chain=CLIENT_CERT_CHAIN_2_PEM) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertEqual(len(actual_calls), 1) + self.assertFalse(actual_calls[0].did_raise) + self.assertEqual(actual_calls[0].returned_cert_config, + self.cert_config_A) + + # succeed with B + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, self.cert_config_B) + self._do_one_shot_client_rpc( + True, + root_certificates=CA_2_PEM, + private_key=CLIENT_KEY_1_PEM, + certificate_chain=CLIENT_CERT_CHAIN_1_PEM) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertEqual(len(actual_calls), 1) + self.assertFalse(actual_calls[0].did_raise) + self.assertEqual(actual_calls[0].returned_cert_config, + self.cert_config_B) + + # fail with B + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, self.cert_config_B) + self._do_one_shot_client_rpc( + False, + root_certificates=CA_1_PEM, + private_key=CLIENT_KEY_2_PEM, + certificate_chain=CLIENT_CERT_CHAIN_2_PEM) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertGreaterEqual(len(actual_calls), 1) + self.assertFalse(actual_calls[0].did_raise) + for i, call in enumerate(actual_calls): + self.assertFalse(call.did_raise, 'i= {}'.format(i)) + self.assertEqual(call.returned_cert_config, self.cert_config_B, + 'i= {}'.format(i)) + + # succeed again with B + self.cert_config_fetcher.reset() + self.cert_config_fetcher.configure(False, self.cert_config_B) + self._do_one_shot_client_rpc( + True, + root_certificates=CA_2_PEM, + private_key=CLIENT_KEY_1_PEM, + certificate_chain=CLIENT_CERT_CHAIN_1_PEM) + actual_calls = self.cert_config_fetcher.getCalls() + self.assertEqual(len(actual_calls), 1) + self.assertFalse(actual_calls[0].did_raise) + self.assertEqual(actual_calls[0].returned_cert_config, + self.cert_config_B) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/src/python/grpcio_tests/tests/unit/credentials/README b/src/python/grpcio_tests/tests/unit/credentials/README deleted file mode 100644 index cb20dcb49fb..00000000000 --- a/src/python/grpcio_tests/tests/unit/credentials/README +++ /dev/null @@ -1 +0,0 @@ -These are test keys *NOT* to be used in production. diff --git a/src/python/grpcio_tests/tests/unit/credentials/README.md b/src/python/grpcio_tests/tests/unit/credentials/README.md new file mode 100644 index 00000000000..100b43c1aaf --- /dev/null +++ b/src/python/grpcio_tests/tests/unit/credentials/README.md @@ -0,0 +1,15 @@ +These are test keys *NOT* to be used in production. + +The `certificate_hierarchy_1` and `certificate_hierarchy_2` contain +two disjoint but similarly organized certificate hierarchies. Each +contains: + +* The respective root CA cert in `certs/ca.cert.pem` + +* The intermediate CA cert in + `intermediate/certs/intermediate.cert.pem`, signed by the root CA + +* A client cert and a server cert--both signed by the intermediate + CA--in `intermediate/certs/client.cert.pem` and + `intermediate/certs/localhost-1.cert.pem`; the corresponding keys + are in `intermediate/private` diff --git a/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/certs/ca.cert.pem b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/certs/ca.cert.pem new file mode 100644 index 00000000000..604b86fdff3 --- /dev/null +++ b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/certs/ca.cert.pem @@ -0,0 +1,31 @@ +-----BEGIN CERTIFICATE----- +MIIFZDCCA0ygAwIBAgIJAKfkDFZ6+Ly/MA0GCSqGSIb3DQEBCwUAMD8xCzAJBgNV +BAYTAnVzMQ4wDAYDVQQIDAVkdW1teTEOMAwGA1UECgwFZHVtbXkxEDAOBgNVBAMM +B3Jvb3QgY2EwHhcNMTcxMTAyMDAzNzA1WhcNMzcxMDI4MDAzNzA1WjA/MQswCQYD +VQQGEwJ1czEOMAwGA1UECAwFZHVtbXkxDjAMBgNVBAoMBWR1bW15MRAwDgYDVQQD +DAdyb290IGNhMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxlSUuSbi +o66tT2ZCqu9wNqSX8VhAJkmrAT5y6m2V0VlQ8Gz7ddynW5UVSmtvDNTebZ15FrvO +6Ng7QnwXXNs/dEzl6oMe6AKDZpuWScVkiqH1UYWBkMLRygWCTEYpSTWTpZWk1zxj +DJ2LlIoO1X/ufLyLOfy2a2XEz8ICzJePmqVca6fmfEtCTj1/8FcwCBF6YlUWVzlR +wewjanQo/lorTYbub+Q6LGxPXZ8W0qoKZzLDSD9cnj4pcJzGGFeu9KkNaW4rldZG +t7mTGQqIRc98dDRc9Jb7PqL8tMPLidw1KErUi05ofxggc5vqNnj4xBl6aX6b/EYN +rBLzO2e0FazX6TwNKwwg68vbOanpDq5LVmIUH8bY1zNZ+JPBGO9pXlAA0YwLx86r +R7YhQ431ZpJ2KGnYjVhYnZ2L3NjV3UYX3x5Z3OrDj9hybhucJB48DMQ1+loEabwK +fSUJtcSPc8dCIibxVKid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7bwS699/W965pa5nug== +-----END CERTIFICATE----- diff --git a/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/intermediate/certs/client.cert.pem b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/intermediate/certs/client.cert.pem new file mode 100644 index 00000000000..44bc5625990 --- /dev/null +++ b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/intermediate/certs/client.cert.pem @@ -0,0 +1,28 @@ +-----BEGIN CERTIFICATE----- +MIIExzCCAq+gAwIBAgICEAMwDQYJKoZIhvcNAQELBQAwRzELMAkGA1UEBhMCdXMx +DjAMBgNVBAgMBWR1bW15MQ4wDAYDVQQKDAVkdW1teTEYMBYGA1UEAwwPaW50ZXJt +ZWRpYXRlIGNhMB4XDTE3MTEwMjAwMzcwNloXDTI3MTAzMTAwMzcwNlowPjELMAkG +A1UEBhMCdXMxDjAMBgNVBAgMBWR1bW15MQ4wDAYDVQQKDAVkdW1teTEPMA0GA1UE +AwwGY2xpZW50MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwquL6gtP +R7P9xJK76FTj8fI5TSJa3cAMt1p6CmessjHQq7nQ6DWLGVi4XIt9Sc/1C3rXupOe +90Ok4L0tsuVZH78Wn0EBmBH7S4IbhU9P+aJ9mcigepj1lnxWqoVblgeJYKMOOwAf +pAKUNMWDSm+nCfwE+R5d8d8cfA41Awq1jTRjOVpiJq6aoKfs791a1ZkZde3kFrNV +AVjC06GgA1lZd3sHf94hmLeC+xJztRXVE9e+7dcc7nFDH0t5DIKYBAklsHg77mZa +3IK4aOZew7Lm6diPoMnAzXh2rWpJU6RrEE29gIkJBsF8CL1Ndg9MzssCg6KBjoai +Vt5dJ+4TSEGCOwIDAQABo4HFMIHCMAkGA1UdEwQCMAAwEQYJYIZIAYb4QgEBBAQD +AgWgMDMGCWCGSAGG+EIBDQQmFiRPcGVuU1NMIEdlbmVyYXRlZCBDbGllbnQgQ2Vy +dGlmaWNhdGUwHQYDVR0OBBYEFPeuKDCswk8jaH9tl6X+uXjo+WM1MB8GA1UdIwQY +MBaAFCoqYgmKh3CUafVp+paXxfz+He+FMA4GA1UdDwEB/wQEAwIF4DAdBgNVHSUE +FjAUBggrBgEFBQcDAgYIKwYBBQUHAwQwDQYJKoZIhvcNAQELBQADggIBADYAp8XS +UjMEpX/zVjRWpAAT4HNEJylCV1QNyhBIAyx38A6xJYuFIx966Htd6W9/Rw4sUY6y +F4pOmnLCRxIPqFzzMYcBHSpynlcu5G7zqIod3wYIk7BNlB0AzkZn6yD8bM1y5Plf +myzQVDEGggrDtaW2EehhNIB+wOmbRGITjIcZUEr8V4BlLXkCqOuxauxl82d5/k2w +LAhjOb9d1VW6RT8+Lcn6drhHZdvtSCe8Z27BcXhaQLL8366mhbigKYJt5adD0KOx +pl0MQcoL1Rth5cJEj+1/lgUaxcnvh7TaIIGEx0h3olQXsTxSTypU/nww2Ic41xdG +xl3xvHsxe20IvOOAMRfS/LPW7MCtQ3k0BqB/rAQvmB0r5YITLlMJuBqg+zjYrG/j +s5szSGAz9r0leFuPraeuZA41d9UBTAJMoVrrQZ4xVHMXQi1oz9E9KlIdbO9+spvC +ulfO+D+Z4a9trYSWhnQL2dSHT0+kHqJ/8GipiUNP/yAC76dRpDVR3xtYNr73iw0j +hyDsVjihTD8JBebs3axnt+Bc+FwoCCd6CVcsggfGUNhu/N5LS78b13PcaRzrUNjU +Eh+8cJvMLst+UQzePlyazzpn7jjN3KsBzWUkbnXCtUs2qRMn8f2gZqliDo7JSFvy +WtBSCYpikOivuJSQUlrHQ8NaXeddyWQzLY79 +-----END CERTIFICATE----- diff --git a/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/intermediate/certs/intermediate.cert.pem b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/intermediate/certs/intermediate.cert.pem new file mode 100644 index 00000000000..98e13669c0f --- /dev/null +++ b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/intermediate/certs/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zAgMBAAGjZjBkMB0GA1UdDgQWBBQq +KmIJiodwlGn1afqWl8X8/h3vhTAfBgNVHSMEGDAWgBSVhLUME20woGVjTdPFUsY3 +TQNKGjASBgNVHRMBAf8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG +9w0BAQsFAAOCAgEAvzLu/Jc8DlfCltVufC54UZ8DVwUfxdGapNBGv4icrs1wMV3S +xqdaLO+vSp9NeEufi724+/hj4URapW9kSt2TMD7BNJ61QSATZFJajxTFgGa0Zz95 +RBDw8/b5Arz/2pOF4VX+FJ+wqHvoH/2A0T+fwz8hLORhxZHv/cUN6kif4FKCwryQ +s89e694kXkEiJfquvu7DR9hYCLOJwzMOOJiTnjz3hlQg4WGu7Z8ZvqzCM+how1hr +nYbUx6a+HfoUf79AHJB0N1EsEEetJ+omvTdrrayCvy1bHA3QgHlJ28QZIJ7MzX9E +n11/xQ95iTuSp8iWurzjTjbrm7eHnGUh+5QubYLXOzbqKzNZu72w0uvWv6ptIudU +usttltiwW8H9kP0ArWTcZDPhhPfS9impFlhiPDk1wUv2/7g+Zz1OaOb7IiSH0s8y +FG72AB8ucJ5dNa/2q5dJiM8Gm5CbiVw5RXTBjlfTTkNeM6LBI3dRghpPdU7Kbfhn +xYs9vnRZeRMJHrcodLuwVcpY/gyeJ0k5LD6eIPCJmatkYZ122isYyMX8lL2P5aR+ +7d2hhqcOCproOrtThjp6nW2jWTB+R/O2+s6mhKSPgfbY2cdky1Y9FSJxSNayb9B8 +eQ+A29iOHrGVAA0R/rvw119rLAYxjXzToM28owx7IyXKrBaU4RMv5yokgag= +-----END CERTIFICATE----- diff --git a/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/intermediate/certs/localhost-1.cert.pem b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/intermediate/certs/localhost-1.cert.pem new file mode 100644 index 00000000000..f15f1cf5c2f --- /dev/null +++ b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy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GCAhAAMA4GA1UdDwEB/wQEAwIFoDATBgNVHSUEDDAKBggr +BgEFBQcDATANBgkqhkiG9w0BAQsFAAOCAgEA2cvXxJw120Z9oWXyGwR6CH7TcXoy +1i77B1M5j0Krvkjh2/MkEU+JxpZcrhAgZODK9wMPeIUIpJNw2t6Hg+vigpInu7pY +MXR4IA5XLnhGV/hueXa0JLia5FG1TISxr4piW6Jd9P2pOt3ECm3Url/F0OeFF/74 +jGaAlWkbhqWJ9M7Gd4QP2wUNm0P4CwAqS9DC6dnMz+JXTakEUirOpmq7U8UKT+5N +QS1K4WuH671n4MiYye3+UoRYt4zPjOzN+QxzvAMtkUBspPmWD6txmD5tKUYDECqn +0sSbY6ytD30OTHIbICFp40arOffmEEJSriL+uQNPPmvqMxX1G2kUFGm15NLPs8Xa +J7ChrAaJzssN5J3myZUbDfCuxmTkWg+hGvGmxLraVNWc3fzKFmdszSkXrGIdf2HR +gZeFI3w6M4Ktx3KctXlsjwqQTYZI/WwLOEpsrHQBPBLQhISyNw4xjZ4MxK8SFZuQ +IiGps/do0eEgeQ+o3gD1dIXt8YxFIxrgk0pzJONpXGgv/cZrukbLNTBdkTSkIwtx +TXKdiJbO17H24MvW+UxFdsIoJXmfQZWdQC3p+Dl0iP+K80aI6WbaysmToHuOi216 +e49nmiM72Izul2zmBi7Cq2nRQbHAETsFfqC34FzJlx0aP8WS953IBD0jNi1BB+AX +BxwiZ1rPjeMvekI= +-----END CERTIFICATE----- diff --git a/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/intermediate/private/client.key.pem b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/intermediate/private/client.key.pem new file mode 100644 index 00000000000..d8a21632ab4 --- /dev/null +++ b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/intermediate/private/client.key.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEogIBAAKCAQEAwquL6gtPR7P9xJK76FTj8fI5TSJa3cAMt1p6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pPD1Er8GPDkEaeQPAGa+r03OTjr9GVOG+IFQ8I4S81w +o/M66x129XxOj2vDJ3ZGUIExr88MXnbkfeRVfasRXET5S5T9RWPOj5mwEe8lyz3b +5J5SkS4rSeJ9rN7yvPUVmQKBgAvrrB67LRzldxSNpfFLSn7nGBYx2oi2zEbYlQA7 +ImhZWqw64S5iLz2yR3x4G9cmhmZjnXrAqcfVIez14PgzLL6V2wI0ID6qCZf+V25b +OdW4M69UZMOHks5HTUJRfe8Z87rXWdq9KQu5GUaIAnSP/D2MNfPbf2yfpV4bV0Yz +qtC9AoGAD3/XXaeGCdV5DPomEmehp84JXU2q/YECRvph46tr4jArG67PCvx2m84B ++W6my4Yi7QJcW4gC0gsdAuxbJl4Y7MCZBnTtNIRCRnHEIciKITJ/+brFln5QUgyn +WnXEPN8q7VjSVXGrljFuLWkzi2Vh8iZDgourNfW+iYDGCJjx1H0= +-----END RSA PRIVATE KEY----- diff --git a/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/intermediate/private/localhost-1.key.pem b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/intermediate/private/localhost-1.key.pem new file mode 100644 index 00000000000..aa83f1a4a2c --- /dev/null +++ b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_1/intermediate/private/localhost-1.key.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEogIBAAKCAQEArRAy0Nim9P883BAisXdFoKmgHGTtcLH/SzwkkPWTFHz0rHU1 +Klwzw8u3OkRyvgoQp7DqkohboNMDwg5VrOOcfKwtM2GZ5jixo+YKvJ25oj8Jfr+4 +0baznyWTmOcfoviKrb7u2T9BPEEz5og+lXRDAsTFATGaQDX2LN3Dd9KIw+7sWY+g +c3Zi13HHaWYhtmfJjzFbH1vDxHKCdSdgtPyEhqcJ4OC6wbgp/mQ01VlPAr08kRfk +C8mTTS7atqc410irKViF3sWi4YNPf7LuBrjo75FIIOp+sQgZE6xwOuZ/9bT2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uR7sPk3ftTX98YPqEJ/n8Ktz5COO8GH2umKInEKNXc +UGW1AoGAfENy7vInNv0tzFWPSYdFgesvzo7e8mXyVO8hCyWvY3rxW2on7qfLF3Z9 +fHjd7P9gULja0n1kvmxwUC3u20RrvpY59F4hfi+ji2EiubS9Yhszd2e1CLeRMkln +ojDjnflN32ZbWVHX/i6g3Dabq9JOD0FsOaOlriLMuofdA6jTUFE= +-----END RSA PRIVATE KEY----- diff --git a/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/certs/ca.cert.pem b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/certs/ca.cert.pem new file mode 100644 index 00000000000..212b5862cb2 --- /dev/null +++ b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/certs/ca.cert.pem @@ -0,0 +1,31 @@ +-----BEGIN CERTIFICATE----- +MIIFZDCCA0ygAwIBAgIJALhSfZ8i0rWTMA0GCSqGSIb3DQEBCwUAMD8xCzAJBgNV +BAYTAnVzMQ4wDAYDVQQIDAVkdW1teTEOMAwGA1UECgwFZHVtbXkxEDAOBgNVBAMM +B3Jvb3QgY2EwHhcNMTcxMTAyMDAzNzU4WhcNMzcxMDI4MDAzNzU4WjA/MQswCQYD +VQQGEwJ1czEOMAwGA1UECAwFZHVtbXkxDjAMBgNVBAoMBWR1bW15MRAwDgYDVQQD +DAdyb290IGNhMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEArHaQ3uyp +wVaVPZDYvy/EJbnP7KbZNPBvKpQCDEqg9B2TPaC8WVjiqT6I88c+KcGuB8nADJdk +o10iZC5AwbrXK4ELSCOvBpxYI5sjoFcv3lZ/oe4e650QO2L/ADmtwLaLYK6rZkwW +Sd90yCGF7ZOTZTJZDwmWEl+ohi+2ow6sRMHKcSKUNfx9G5BB7TOzoqUxqH+moEds +YpjVMEcKzQi2FmbRd+8Dlg2eGqA2V4faprGQwoYz8NqJZGa/KPpRvXE2VjSTDN6b +rJ7mmui6eY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BB2uT47sbiGrAeco+GxFGUVqi1IjObqrkIrPzV +OjQhTZV6qgYCOuniJiGfoiMeHqdaDybpqo1bIrxSlvGRNcVoOsKt2/KP1DzW4ARZ +hoRvayU2apHz/T5TAailqAW2MsrjGRaVHQTmeZKag8CKtAcjWzui0J2DnfXxUMn8 +R3ruFu3xJduOT1VghT9L9udvX9YhPCIKVL9+B5eFX9eMV6N7hUnVug== +-----END CERTIFICATE----- diff --git a/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/intermediate/certs/client.cert.pem b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/intermediate/certs/client.cert.pem new file mode 100644 index 00000000000..b6f42801680 --- /dev/null +++ b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/intermediate/certs/client.cert.pem @@ -0,0 +1,28 @@ +-----BEGIN CERTIFICATE----- +MIIExzCCAq+gAwIBAgICEAMwDQYJKoZIhvcNAQELBQAwRzELMAkGA1UEBhMCdXMx +DjAMBgNVBAgMBWR1bW15MQ4wDAYDVQQKDAVkdW1teTEYMBYGA1UEAwwPaW50ZXJt +ZWRpYXRlIGNhMB4XDTE3MTEwMjAwMzgwMFoXDTI3MTAzMTAwMzgwMFowPjELMAkG +A1UEBhMCdXMxDjAMBgNVBAgMBWR1bW15MQ4wDAYDVQQKDAVkdW1teTEPMA0GA1UE +AwwGY2xpZW50MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyxZFTLqv +Gd9SpFAykyRyLQgHcR5hgD55mz+9fl1OfnMoAc7yTdPVLksDLmeFUlxcvCtLHysJ +klIBX62c6LzbsVcfLg/DPJlQxFnkhJCRKen4fp7x9h62qqJkDFVXsiEFza9L1lsN +4OwqU8i4RRgZ/xggM/s/wVBtynioeW9QADNmKZ1n6HVKkYwdOynbFSggYfFrL3HL +54bC9roZUETin0G5wZ9QU+srgivT0a/KC3ourBYHXAI40iHuuOBf3syDVJ6xId/r +3UO3qkiQ5q7pwglg+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END CERTIFICATE----- diff --git a/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/intermediate/certs/intermediate.cert.pem b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/intermediate/certs/intermediate.cert.pem new file mode 100644 index 00000000000..4305e5333f8 --- /dev/null +++ b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/intermediate/certs/intermediate.cert.pem @@ -0,0 +1,31 @@ +-----BEGIN CERTIFICATE----- +MIIFaDCCA1CgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPzELMAkGA1UEBhMCdXMx +DjAMBgNVBAgMBWR1bW15MQ4wDAYDVQQKDAVkdW1teTEQMA4GA1UEAwwHcm9vdCBj +YTAeFw0xNzExMDIwMDM3NTlaFw0yNzEwMzEwMDM3NTlaMEcxCzAJBgNVBAYTAnVz +MQ4wDAYDVQQIDAVkdW1teTEOMAwGA1UECgwFZHVtbXkxGDAWBgNVBAMMD2ludGVy +bWVkaWF0ZSBjYTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKuM2iFz +CCKmbs4uLj/8wjtxf+jFmkwzN4Pps4hqJ3NJqWB326LhzWyqM4WiTAJWE02wSJbS +16RPfbjkVC77OI4+PUdwqxU9vNAP/95w0h6hBSFtkysuT5VVUt5jiY7wnUKgqTCi +MYhYOl+HEP32O4cnxAazkUKKvtyrd4/PvejJ9zz+iYexRnaaGfOFR3co7jQ5QKar +oK4UgJC3mVDZQEMBV0oljkpgVQMAVb4XQU7e+o25JOUkOoK6LdK/b/95khR0jTyD +OBLqd4mCEzxNi+jZ0jLTLPk0c+DnGmRfoNUxnFb40R8QnEIEKwf+JKyl6p89oqOl +pvIZFLZlUWIS4qL+993l1SCqPkWJOAdTg+s/Zh6DeAOhrUn9/wk0aQwZrK7wQQLJ +4GGhxC/FfuUGsLqZszAVkP8jDEWnzhN2rw3V+C7v6lj4qHhUwqGHuYzCx2Hxl+B8 +UyBmZb9gXKVUtAvaZjaL2PD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yKaHPeFU= +-----END CERTIFICATE----- diff --git a/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/intermediate/certs/localhost-1.cert.pem b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/intermediate/certs/localhost-1.cert.pem new file mode 100644 index 00000000000..2850e42fe91 --- /dev/null +++ b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/intermediate/certs/localhost-1.cert.pem @@ -0,0 +1,30 @@ +-----BEGIN CERTIFICATE----- +MIIFFzCCAv+gAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwRzELMAkGA1UEBhMCdXMx +DjAMBgNVBAgMBWR1bW15MQ4wDAYDVQQKDAVkdW1teTEYMBYGA1UEAwwPaW50ZXJt +ZWRpYXRlIGNhMB4XDTE3MTEwMjAwMzc1OVoXDTI3MTAzMTAwMzc1OVowTTELMAkG +A1UEBhMCdXMxDjAMBgNVBAgMBWR1bW15MQ4wDAYDVQQKDAVkdW1teTEKMAgGA1UE +CwwBMTESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A +MIIBCgKCAQEAycY/7H1xk3/XHZRopULV7YsOzPIrMG25zoACbpDZxjS0I+2r1c7V +wnvE8TszAkloLi+Skku5CYC7IvVEEEuKuIuV+8M48FJEwlCPge8LPiy18C+npCEd +fgDzCV/O9DfJj6UaiCUayVE7UujXoke7AlKQEJcqvnD/CoTv2Y8jV1A6mPf6CTEI +Sl1BMeFSmeFyvZll+xJ8Up1KfQZxKhtpP1s/rp6ZNlqSs1LM5+vcDHHZ6COTbq7t +2vvcmGDTqeCLsqicBg1kJyMPRtqa0bNPj2bcVtcK0Ndfn6eL2hi+EoBy2nIXi6aG +PpXf85b9bCLd5pZI80nHzFlhdvV+SxqrfwIDAQABo4IBBTCCAQEwCQYDVR0TBAIw +ADARBglghkgBhvhCAQEEBAMCBkAwMwYJYIZIAYb4QgENBCYWJE9wZW5TU0wgR2Vu +ZXJhdGVkIFNlcnZlciBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUoYjECaDz/ZELru/r +jfTB1ShlVrAwaAYDVR0jBGEwX4AU5bMt3t4EnBI1vNGo2wPsxAMIeD+hQ6RBMD8x +CzAJBgNVBAYTAnVzMQ4wDAYDVQQIDAVkdW1teTEOMAwGA1UECgwFZHVtbXkxEDAO +BgNVBAMMB3Jvb3QgY2GCAhAAMA4GA1UdDwEB/wQEAwIFoDATBgNVHSUEDDAKBggr +BgEFBQcDATANBgkqhkiG9w0BAQsFAAOCAgEAiiR2knMMym4O+3fD1KlYSnc2UR3v +0FlRVAsr8wvTlVjJhx7DbRusBNJHWX66mUgK9x5OLnhyvyqlFVhR9AwlnxgfLWz9 +nnACeXzcjQZnKWFQWu8bJSC6Ene6rd1g2acK6SOjxavVbj7JVFnmlHF/naZUzvMl +mJivYta4k7ob8UcX0I5TlJpzglU3UHyyJd5d9zhbF8wqbBq63zR2ovWci4pYCg+F +jYcTGYVZJti3SHO+9/EqTC9x2KDNs3o0+rreJ3GuoonkInKZMQQZJQ6qILvkxlhT +jyU5xlcaJ+0tSaiFK3eF0nXIpFYdZbIHYPCdLjh9AZ2dkFcAgSa/L8+tsVt60k8D +HTO0Hz6dW5D2ckeebZvz5LACMN89gVzrc/rVkeg7QmpSbjkTSLC2KJS53hJzWcEI +3KB73B9iY+ZYytcYBTYLizsAxd5g7j9z8UXrmVQ4mWbh2+xKiG+9aVOzCZ09AYi6 +WVK2aRcMQshgkkqPOloN9OeQNCE8Exf7N/zHsBhygorJXoD/PFgnV1VZm8xkOdiJ +zTb3bpGdmL5+bzzS6wP8Q7pGZGYdlnB7JNO8oMYPPtzX8OOx92BTkPnqJnnRWTpR +SjMEEdQe8K7iXxejQkjaAq5BlwaAOjCjPTqYomECcYjC0WaXsmrPcnZwSqpnHZZ2 +OiINYJub5cvBLNo= +-----END CERTIFICATE----- diff --git a/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/intermediate/private/client.key.pem b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/intermediate/private/client.key.pem new file mode 100644 index 00000000000..a4c5fd4a564 --- /dev/null +++ b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/intermediate/private/client.key.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAyxZFTLqvGd9SpFAykyRyLQgHcR5hgD55mz+9fl1OfnMoAc7y +TdPVLksDLmeFUlxcvCtLHysJklIBX62c6LzbsVcfLg/DPJlQxFnkhJCRKen4fp7x +9h62qqJkDFVXsiEFza9L1lsN4OwqU8i4RRgZ/xggM/s/wVBtynioeW9QADNmKZ1n +6HVKkYwdOynbFSggYfFrL3HL54bC9roZUETin0G5wZ9QU+srgivT0a/KC3ourBYH +XAI40iHuuOBf3syDVJ6xId/r3UO3qkiQ5q7pwglg+8Nx7Q3CFtGZY3ewxSSSDo6B +OyweGYMsBaxMO3EyTqecyfXn3n4XPqwmDalWYQIDAQABAoIBAFhIOR3OtVlw3BLz +jdiq6jsrF1kUFNxTzDcxsSUiWIHde1G17Vzpre0uzJY6iBkyb1mZFFHbOpDxtwkp +hmEh3/qqXbJ/RaatGxAP56e81G28+LnKTHJqDYwFhapa2wFjG4u7HSN0d4cEAq5j +Pb9DZ+GdUjpmiON3HBL8+ne3bLZ42uI+DSVe8d3irbqg2rqsiANf0gdimMW4nuI4 +rVxf8HrY43PdQn/Vby+7qLRE3tmIlpbTqJGRtWRjdeBBI91APCrRljjXrKqT6Zpa +E6Daz3YIQvXkIT0q+WkeN1VmQbtRnk7kRsPNp15kSwpHfmv6o/vkO9OUb1n71P2F +wnB0WDECgYEA8iltnKxXnjqwZ/vzIWzcd94j+mdZg/K2/JCOqjwMvpSGCvx2zUmq +Y2nxO2K85AVeOm/Yt87SMODB6AQ9CsrVGEUAzzacvCJDb8oUhaOL5gypnyvZiGCy +snzXfgB+v/xuGekIjs2y7E8h3GG40j0aNQnUY1Fuc6iaeJG4BtjkuQUCgYEA1rE4 +DrTSsUh3hLYQusIHZR8Lecrrd4QUZSMKLkWjobiSTw3m4mglx1s2G4eZ3WuzOyFq +Dp3/b3yfT8prdPBGA6shHNFf+1TO1q1/pIt15dc3sFwxMkuunai8N4QZJRqZLbYq +FkNFkZ20hFHcH/NHDsAsRL/0tJdEmJ2ruP+Qdq0CgYBsdPGKwgVb8J0hdU4nIkJ7 +zRoABFmrJwGdjIDY7Zwnnw2JzhjHSL7vV3ubRVWkKmNReNZvPEoXahJuf7d3JfDa +tczvAV6hRBc/8hnO4Li/h9xQVatP0T83gYJiBIbAJaaKJDyY+Lex7p8TvRCx2Hvs +VUKyWL5HPrQwW9M3/dwyoQKBgQCNQoPA4Wcz8Jt7PZQaXaoh9eBGHab6t3P366s6 +MOXudZQG4f3FgINC/ZfHW1x43PFL+btfrMOyJkxoYqZ7hdB7f3DFFlpR80Y46GVw +7bYAKbBhoPdZwYQ+BhT5bjhhOnQJKK/egBrZKevpmDb+6sIZSYaXIbovzMv8otmn +WrhB7QKBgAdl+KYBQULCUBp8qCQH5sAQoWErpyuD2FNN6LGknpPqn4DdujvwEP0Z +OSvbauLkI0Qc9/MezKPTeYXlFqdbpItwyySJsUkiI3HhVYlBgDkZ7xb6uHIH5E6I +bKgIW5JEf5I7Eu1iurORkXxCCGMkiQmEs4X5kSXXRYgXfNgAD0FX +-----END RSA PRIVATE KEY----- diff --git a/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/intermediate/private/localhost-1.key.pem b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/intermediate/private/localhost-1.key.pem new file mode 100644 index 00000000000..8cba174841a --- /dev/null +++ b/src/python/grpcio_tests/tests/unit/credentials/certificate_hierarchy_2/intermediate/private/localhost-1.key.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpAIBAAKCAQEAycY/7H1xk3/XHZRopULV7YsOzPIrMG25zoACbpDZxjS0I+2r +1c7VwnvE8TszAk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jn6lECJKXW//Af6fZg7mPJwN/wN5 +xYGQLNbYrrGRW2HDUBP4YU1WtHGIC3+EAL+BEztdMzmpGuh1YTSvmSvwkMltXA1D +iz0amArw72lOsz29n3+6FfBFAoGAIpRqMC8k9vq80/yth6TAQifnvo3G2v4uyLo8 +vqv5IaPvNy70hB8rN9G0gEnI99Dgjdoa3SNBB4dKvUwbTgUN0OB/meBHL13I5Af+ +uGGiu6V1eS/6gUbeAX/Gq/PjF99PQareKAZJ4cBGKTbSayHfBjp1nFflBSbqZ13b ++JEFJvUCgYBOs2J2XXamPbI7gu7B2TE9j/62v0SJyoHq2LHMmYUDRuPdPk3eKCt3 +283w+E8XUIFbctaxsbo8msNjjvV22D/Nci3d87aPe8bn1SVto3GnTuwnOpRq3E+3 +wAarqrhiZbGZSCcAkEOk7FlxAwYnCM6paqMxDEMCJ4qChMM42E9ZyQ== +-----END RSA PRIVATE KEY----- diff --git a/src/python/grpcio_tests/tests/unit/resources.py b/src/python/grpcio_tests/tests/unit/resources.py index 823d2307d33..11ef9e85656 100644 --- a/src/python/grpcio_tests/tests/unit/resources.py +++ b/src/python/grpcio_tests/tests/unit/resources.py @@ -11,7 +11,7 @@ # 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. -"""Constants and functions for data used in interoperability testing.""" +"""Constants and functions for data used in testing.""" import os @@ -34,3 +34,81 @@ def private_key(): def certificate_chain(): return pkg_resources.resource_string(__name__, _CERTIFICATE_CHAIN_RESOURCE_PATH) + + +def cert_hier_1_root_ca_cert(): + return pkg_resources.resource_string( + __name__, 'credentials/certificate_hierarchy_1/certs/ca.cert.pem') + + +def cert_hier_1_intermediate_ca_cert(): + return pkg_resources.resource_string( + __name__, + 'credentials/certificate_hierarchy_1/intermediate/certs/intermediate.cert.pem' + ) + + +def cert_hier_1_client_1_key(): + return pkg_resources.resource_string( + __name__, + 'credentials/certificate_hierarchy_1/intermediate/private/client.key.pem' + ) + + +def cert_hier_1_client_1_cert(): + return pkg_resources.resource_string( + __name__, + 'credentials/certificate_hierarchy_1/intermediate/certs/client.cert.pem') + + +def cert_hier_1_server_1_key(): + return pkg_resources.resource_string( + __name__, + 'credentials/certificate_hierarchy_1/intermediate/private/localhost-1.key.pem' + ) + + +def cert_hier_1_server_1_cert(): + return pkg_resources.resource_string( + __name__, + 'credentials/certificate_hierarchy_1/intermediate/certs/localhost-1.cert.pem' + ) + + +def cert_hier_2_root_ca_cert(): + return pkg_resources.resource_string( + __name__, 'credentials/certificate_hierarchy_2/certs/ca.cert.pem') + + +def cert_hier_2_intermediate_ca_cert(): + return pkg_resources.resource_string( + __name__, + 'credentials/certificate_hierarchy_2/intermediate/certs/intermediate.cert.pem' + ) + + +def cert_hier_2_client_1_key(): + return pkg_resources.resource_string( + __name__, + 'credentials/certificate_hierarchy_2/intermediate/private/client.key.pem' + ) + + +def cert_hier_2_client_1_cert(): + return pkg_resources.resource_string( + __name__, + 'credentials/certificate_hierarchy_2/intermediate/certs/client.cert.pem') + + +def cert_hier_2_server_1_key(): + return pkg_resources.resource_string( + __name__, + 'credentials/certificate_hierarchy_2/intermediate/private/localhost-1.key.pem' + ) + + +def cert_hier_2_server_1_cert(): + return pkg_resources.resource_string( + __name__, + 'credentials/certificate_hierarchy_2/intermediate/certs/localhost-1.cert.pem' + ) diff --git a/src/ruby/end2end/channel_closing_driver.rb b/src/ruby/end2end/channel_closing_driver.rb index 0ceb3667eba..57544b03985 100755 --- a/src/ruby/end2end/channel_closing_driver.rb +++ b/src/ruby/end2end/channel_closing_driver.rb @@ -23,13 +23,11 @@ def main STDERR.puts 'start server' server_runner = ServerRunner.new(EchoServerImpl) server_port = server_runner.run - - sleep 1 - STDERR.puts 'start client' control_stub, client_pid = start_client('channel_closing_client.rb', server_port) - + # sleep to allow time for the client to get into + # the middle of a "watch connectivity state" call sleep 3 begin diff --git a/src/ruby/end2end/channel_state_driver.rb b/src/ruby/end2end/channel_state_driver.rb index 98339baebeb..f4b1cd2bb86 100755 --- a/src/ruby/end2end/channel_state_driver.rb +++ b/src/ruby/end2end/channel_state_driver.rb @@ -22,14 +22,11 @@ def main STDERR.puts 'start server' server_runner = ServerRunner.new(EchoServerImpl) server_port = server_runner.run - - sleep 1 - STDERR.puts 'start client' _, client_pid = start_client('channel_state_client.rb', server_port) - + # sleep to allow time for the client to get into + # the middle of a "watch connectivity state" call sleep 3 - Process.kill('SIGTERM', client_pid) begin diff --git a/src/ruby/end2end/end2end_common.rb b/src/ruby/end2end/end2end_common.rb index a1b824fcbf6..790fc23e923 100755 --- a/src/ruby/end2end/end2end_common.rb +++ b/src/ruby/end2end/end2end_common.rb @@ -40,12 +40,13 @@ end # ServerRunner starts an "echo server" that test clients can make calls to class ServerRunner - def initialize(service_impl) + def initialize(service_impl, rpc_server_args: {}) @service_impl = service_impl + @rpc_server_args = rpc_server_args end def run - @srv = GRPC::RpcServer.new + @srv = GRPC::RpcServer.new(@rpc_server_args) port = @srv.add_http2_port('0.0.0.0:0', :this_port_is_insecure) @srv.handle(@service_impl) @@ -75,7 +76,6 @@ def start_client(client_main, server_port) client_path, "--client_control_port=#{client_control_port}", "--server_port=#{server_port}") - sleep 1 control_stub = ClientControl::ClientController::Stub.new( "localhost:#{client_control_port}", :this_channel_is_insecure) [control_stub, client_pid] diff --git a/src/ruby/end2end/forking_client_driver.rb b/src/ruby/end2end/forking_client_driver.rb index 63565395f7d..5cf1d73112d 100755 --- a/src/ruby/end2end/forking_client_driver.rb +++ b/src/ruby/end2end/forking_client_driver.rb @@ -20,12 +20,6 @@ def main STDERR.puts 'start server' server_runner = ServerRunner.new(EchoServerImpl) server_port = server_runner.run - - # TODO(apolcyn) Can we get rid of this sleep? - # Without it, an immediate call to the just started EchoServer - # fails with UNAVAILABLE - sleep 1 - STDERR.puts 'start client' _, client_pid = start_client('forking_client_client.rb', server_port) diff --git a/src/ruby/end2end/grpc_class_init_client.rb b/src/ruby/end2end/grpc_class_init_client.rb index c35719a71fd..ff40350cfae 100755 --- a/src/ruby/end2end/grpc_class_init_client.rb +++ b/src/ruby/end2end/grpc_class_init_client.rb @@ -54,7 +54,7 @@ def run_concurrency_stress_test(test_proc) test_proc.call - fail 'exception thrown while child thread initing class' + fail '(expected) exception thrown while child thread initing class' end # default (no gc_stress and no concurrency_stress) diff --git a/src/ruby/end2end/killed_client_thread_driver.rb b/src/ruby/end2end/killed_client_thread_driver.rb index fce5d13e825..370f7e686bb 100755 --- a/src/ruby/end2end/killed_client_thread_driver.rb +++ b/src/ruby/end2end/killed_client_thread_driver.rb @@ -17,56 +17,46 @@ require_relative './end2end_common' # Service that sleeps for a long time upon receiving an 'echo request' -# Also, this notifies @call_started_cv once it has received a request. +# Also, this calls it's callback upon receiving an RPC as a method +# of synchronization/waiting for the child to start. class SleepingEchoServerImpl < Echo::EchoServer::Service - def initialize(call_started, call_started_mu, call_started_cv) - @call_started = call_started - @call_started_mu = call_started_mu - @call_started_cv = call_started_cv + def initialize(received_rpc_callback) + @received_rpc_callback = received_rpc_callback end def echo(echo_req, _) - @call_started_mu.synchronize do - @call_started.set_true - @call_started_cv.signal - end - sleep 1000 + @received_rpc_callback.call + # sleep forever to get the client stuck waiting + sleep Echo::EchoReply.new(response: echo_req.request) end end -# Mutable boolean -class BoolHolder - attr_reader :val - - def init - @val = false - end - - def set_true - @val = true - end -end - def main STDERR.puts 'start server' - call_started = BoolHolder.new - call_started_mu = Mutex.new - call_started_cv = ConditionVariable.new + client_started = false + client_started_mu = Mutex.new + client_started_cv = ConditionVariable.new + received_rpc_callback = proc do + client_started_mu.synchronize do + client_started = true + client_started_cv.signal + end + end - service_impl = SleepingEchoServerImpl.new(call_started, - call_started_mu, - call_started_cv) - server_runner = ServerRunner.new(service_impl) + service_impl = SleepingEchoServerImpl.new(received_rpc_callback) + # RPCs against the server will all be hanging, so kill thread + # pool workers immediately rather than after waiting for a second. + rpc_server_args = { poll_period: 0, pool_keep_alive: 0 } + server_runner = ServerRunner.new(service_impl, rpc_server_args: rpc_server_args) server_port = server_runner.run - STDERR.puts 'start client' _, client_pid = start_client('killed_client_thread_client.rb', server_port) - call_started_mu.synchronize do - call_started_cv.wait(call_started_mu) until call_started.val + client_started_mu.synchronize do + client_started_cv.wait(client_started_mu) until client_started end # SIGTERM the child process now that it's diff --git a/src/ruby/end2end/multiple_killed_watching_threads_driver.rb b/src/ruby/end2end/multiple_killed_watching_threads_driver.rb index 94d5e9da2d3..59f6f275e46 100755 --- a/src/ruby/end2end/multiple_killed_watching_threads_driver.rb +++ b/src/ruby/end2end/multiple_killed_watching_threads_driver.rb @@ -26,6 +26,8 @@ def watch_state(ch) fail "non-idle state: #{state}" unless state == IDLE ch.watch_connectivity_state(IDLE, Time.now + 360) end + # sleep to get the thread into the middle of a + # "watch connectivity state" call sleep 0.1 thd.kill end diff --git a/src/ruby/end2end/sig_handling_client.rb b/src/ruby/end2end/sig_handling_client.rb index 41b5f334be3..129ad7cb7fd 100755 --- a/src/ruby/end2end/sig_handling_client.rb +++ b/src/ruby/end2end/sig_handling_client.rb @@ -30,16 +30,18 @@ class SigHandlingClientController < ClientControl::ClientController::Service end def shutdown(_, _) - Thread.new do - # TODO(apolcyn) There is a race between stopping the - # server and the "shutdown" rpc completing, - # See if stop method on server can end active RPC cleanly, to - # avoid this sleep. - sleep 3 + # Spawn a new thread because RpcServer#stop is + # synchronous and blocks until either this RPC has finished, + # or the server's "poll_period" seconds have passed. + @shutdown_thread = Thread.new do @srv.stop end ClientControl::Void.new end + + def join_shutdown_thread + @shutdown_thread.join + end end def main @@ -62,13 +64,23 @@ def main STDERR.puts 'SIGINT received' end - srv = GRPC::RpcServer.new + # The "shutdown" RPC should end very quickly. + # Allow a few seconds to be safe. + srv = GRPC::RpcServer.new(poll_period: 3) srv.add_http2_port("0.0.0.0:#{client_control_port}", :this_port_is_insecure) stub = Echo::EchoServer::Stub.new("localhost:#{server_port}", :this_channel_is_insecure) - srv.handle(SigHandlingClientController.new(srv, stub)) - srv.run + control_service = SigHandlingClientController.new(srv, stub) + srv.handle(control_service) + server_thread = Thread.new do + srv.run + end + srv.wait_till_running + # send a first RPC to notify the parent process that we've started + stub.echo(Echo::EchoRequest.new(request: 'client/child started')) + server_thread.join + control_service.join_shutdown_thread end main diff --git a/src/ruby/end2end/sig_handling_driver.rb b/src/ruby/end2end/sig_handling_driver.rb index 291bf29424c..0ad1cbd661d 100755 --- a/src/ruby/end2end/sig_handling_driver.rb +++ b/src/ruby/end2end/sig_handling_driver.rb @@ -19,17 +19,42 @@ require_relative './end2end_common' +# A service that calls back it's received_rpc_callback +# upon receiving an RPC. Used for synchronization/waiting +# for child process to start. +class ClientStartedService < Echo::EchoServer::Service + def initialize(received_rpc_callback) + @received_rpc_callback = received_rpc_callback + end + + def echo(echo_req, _) + @received_rpc_callback.call unless @received_rpc_callback.nil? + @received_rpc_callback = nil + Echo::EchoReply.new(response: echo_req.request) + end +end + def main STDERR.puts 'start server' - server_runner = ServerRunner.new(EchoServerImpl) - server_port = server_runner.run - - sleep 1 + client_started = false + client_started_mu = Mutex.new + client_started_cv = ConditionVariable.new + received_rpc_callback = proc do + client_started_mu.synchronize do + client_started = true + client_started_cv.signal + end + end + client_started_service = ClientStartedService.new(received_rpc_callback) + server_runner = ServerRunner.new(client_started_service) + server_port = server_runner.run STDERR.puts 'start client' control_stub, client_pid = start_client('sig_handling_client.rb', server_port) - sleep 1 + client_started_mu.synchronize do + client_started_cv.wait(client_started_mu) until client_started + end count = 0 while count < 5 diff --git a/src/ruby/end2end/sig_int_during_channel_watch_driver.rb b/src/ruby/end2end/sig_int_during_channel_watch_driver.rb index b054f0f5f31..2df22f48a2e 100755 --- a/src/ruby/end2end/sig_int_during_channel_watch_driver.rb +++ b/src/ruby/end2end/sig_int_during_channel_watch_driver.rb @@ -23,13 +23,9 @@ def main STDERR.puts 'start server' server_runner = ServerRunner.new(EchoServerImpl) server_port = server_runner.run - - sleep 1 - STDERR.puts 'start client' _, client_pid = start_client('sig_int_during_channel_watch_client.rb', server_port) - # give time for the client to get into the middle # of a channel state watch call sleep 1 diff --git a/src/ruby/ext/grpc/rb_byte_buffer.c b/src/ruby/ext/grpc/rb_byte_buffer.c index 8aa7a7eb031..e11c7e82a8a 100644 --- a/src/ruby/ext/grpc/rb_byte_buffer.c +++ b/src/ruby/ext/grpc/rb_byte_buffer.c @@ -26,14 +26,14 @@ #include #include "rb_grpc.h" -grpc_byte_buffer *grpc_rb_s_to_byte_buffer(char *string, size_t length) { +grpc_byte_buffer* grpc_rb_s_to_byte_buffer(char* string, size_t length) { grpc_slice slice = grpc_slice_from_copied_buffer(string, length); - grpc_byte_buffer *buffer = grpc_raw_byte_buffer_create(&slice, 1); + grpc_byte_buffer* buffer = grpc_raw_byte_buffer_create(&slice, 1); grpc_slice_unref(slice); return buffer; } -VALUE grpc_rb_byte_buffer_to_s(grpc_byte_buffer *buffer) { +VALUE grpc_rb_byte_buffer_to_s(grpc_byte_buffer* buffer) { VALUE rb_string; grpc_byte_buffer_reader reader; grpc_slice next; @@ -46,7 +46,7 @@ VALUE grpc_rb_byte_buffer_to_s(grpc_byte_buffer *buffer) { return Qnil; } while (grpc_byte_buffer_reader_next(&reader, &next) != 0) { - rb_str_cat(rb_string, (const char *)GRPC_SLICE_START_PTR(next), + rb_str_cat(rb_string, (const char*)GRPC_SLICE_START_PTR(next), GRPC_SLICE_LENGTH(next)); grpc_slice_unref(next); } @@ -59,6 +59,6 @@ VALUE grpc_rb_slice_to_ruby_string(grpc_slice slice) { rb_raise(rb_eRuntimeError, "attempt to convert uninitialized grpc_slice to ruby string"); } - return rb_str_new((char *)GRPC_SLICE_START_PTR(slice), + return rb_str_new((char*)GRPC_SLICE_START_PTR(slice), GRPC_SLICE_LENGTH(slice)); } diff --git a/src/ruby/ext/grpc/rb_byte_buffer.h b/src/ruby/ext/grpc/rb_byte_buffer.h index c64a9900a09..9cb58aa85b0 100644 --- a/src/ruby/ext/grpc/rb_byte_buffer.h +++ b/src/ruby/ext/grpc/rb_byte_buffer.h @@ -24,10 +24,10 @@ #include /* Converts a char* with a length to a grpc_byte_buffer */ -grpc_byte_buffer *grpc_rb_s_to_byte_buffer(char *string, size_t length); +grpc_byte_buffer* grpc_rb_s_to_byte_buffer(char* string, size_t length); /* Converts a grpc_byte_buffer to a ruby string */ -VALUE grpc_rb_byte_buffer_to_s(grpc_byte_buffer *buffer); +VALUE grpc_rb_byte_buffer_to_s(grpc_byte_buffer* buffer); /* Converts a grpc_slice to a ruby string */ VALUE grpc_rb_slice_to_ruby_string(grpc_slice slice); diff --git a/src/ruby/ext/grpc/rb_call.c b/src/ruby/ext/grpc/rb_call.c index e920fc86c52..7f3ca2a8e70 100644 --- a/src/ruby/ext/grpc/rb_call.c +++ b/src/ruby/ext/grpc/rb_call.c @@ -24,7 +24,6 @@ #include #include #include -#include #include #include "rb_byte_buffer.h" @@ -81,11 +80,11 @@ static VALUE sym_status; static VALUE sym_cancelled; typedef struct grpc_rb_call { - grpc_call *wrapped; - grpc_completion_queue *queue; + grpc_call* wrapped; + grpc_completion_queue* queue; } grpc_rb_call; -static void destroy_call(grpc_rb_call *call) { +static void destroy_call(grpc_rb_call* call) { /* Ensure that we only try to destroy the call once */ if (call->wrapped != NULL) { grpc_call_unref(call->wrapped); @@ -96,19 +95,19 @@ static void destroy_call(grpc_rb_call *call) { } /* Destroys a Call. */ -static void grpc_rb_call_destroy(void *p) { +static void grpc_rb_call_destroy(void* p) { if (p == NULL) { return; } - destroy_call((grpc_rb_call *)p); + destroy_call((grpc_rb_call*)p); xfree(p); } -static size_t md_ary_datasize(const void *p) { - const grpc_metadata_array *const ary = (grpc_metadata_array *)p; +static size_t md_ary_datasize(const void* p) { + const grpc_metadata_array* const ary = (grpc_metadata_array*)p; size_t i, datasize = sizeof(grpc_metadata_array); for (i = 0; i < ary->count; ++i) { - const grpc_metadata *const md = &ary->metadata[i]; + const grpc_metadata* const md = &ary->metadata[i]; datasize += GRPC_SLICE_LENGTH(md->key); datasize += GRPC_SLICE_LENGTH(md->value); } @@ -151,9 +150,9 @@ static const rb_data_type_t grpc_call_data_type = {"grpc_call", VALUE rb_error_code_details; /* Obtains the error detail string for given error code */ -const char *grpc_call_error_detail_of(grpc_call_error err) { +const char* grpc_call_error_detail_of(grpc_call_error err) { VALUE detail_ref = rb_hash_aref(rb_error_code_details, UINT2NUM(err)); - const char *detail = "unknown error code!"; + const char* detail = "unknown error code!"; if (detail_ref != Qnil) { detail = StringValueCStr(detail_ref); } @@ -163,7 +162,7 @@ const char *grpc_call_error_detail_of(grpc_call_error err) { /* Called by clients to cancel an RPC on the server. Can be called multiple times, from any thread. */ static VALUE grpc_rb_call_cancel(VALUE self) { - grpc_rb_call *call = NULL; + grpc_rb_call* call = NULL; grpc_call_error err; if (RTYPEDDATA_DATA(self) == NULL) { // This call has been closed @@ -187,7 +186,7 @@ static VALUE grpc_rb_call_cancel(VALUE self) { * message. */ static VALUE grpc_rb_call_cancel_with_status(VALUE self, VALUE status_code, VALUE details) { - grpc_rb_call *call = NULL; + grpc_rb_call* call = NULL; grpc_call_error err; if (RTYPEDDATA_DATA(self) == NULL) { // This call has been closed @@ -217,7 +216,7 @@ static VALUE grpc_rb_call_cancel_with_status(VALUE self, VALUE status_code, processed. */ static VALUE grpc_rb_call_close(VALUE self) { - grpc_rb_call *call = NULL; + grpc_rb_call* call = NULL; TypedData_Get_Struct(self, grpc_rb_call, &grpc_call_data_type, call); if (call != NULL) { destroy_call(call); @@ -230,8 +229,8 @@ static VALUE grpc_rb_call_close(VALUE self) { /* Called to obtain the peer that this call is connected to. */ static VALUE grpc_rb_call_get_peer(VALUE self) { VALUE res = Qnil; - grpc_rb_call *call = NULL; - char *peer = NULL; + grpc_rb_call* call = NULL; + char* peer = NULL; if (RTYPEDDATA_DATA(self) == NULL) { rb_raise(grpc_rb_eCallError, "Cannot get peer value on closed call"); return Qnil; @@ -246,9 +245,9 @@ static VALUE grpc_rb_call_get_peer(VALUE self) { /* Called to obtain the x509 cert of an authenticated peer. */ static VALUE grpc_rb_call_get_peer_cert(VALUE self) { - grpc_rb_call *call = NULL; + grpc_rb_call* call = NULL; VALUE res = Qnil; - grpc_auth_context *ctx = NULL; + grpc_auth_context* ctx = NULL; if (RTYPEDDATA_DATA(self) == NULL) { rb_raise(grpc_rb_eCallError, "Cannot get peer cert on closed call"); return Qnil; @@ -264,7 +263,7 @@ static VALUE grpc_rb_call_get_peer_cert(VALUE self) { { grpc_auth_property_iterator it = grpc_auth_context_find_properties_by_name( ctx, GRPC_X509_PEM_CERT_PROPERTY_NAME); - const grpc_auth_property *prop = grpc_auth_property_iterator_next(&it); + const grpc_auth_property* prop = grpc_auth_property_iterator_next(&it); if (prop == NULL) { return Qnil; } @@ -379,8 +378,8 @@ static VALUE grpc_rb_call_set_write_flag(VALUE self, VALUE write_flag) { Sets credentials on a call */ static VALUE grpc_rb_call_set_credentials(VALUE self, VALUE credentials) { - grpc_rb_call *call = NULL; - grpc_call_credentials *creds; + grpc_rb_call* call = NULL; + grpc_call_credentials* creds; grpc_call_error err; if (RTYPEDDATA_DATA(self) == NULL) { rb_raise(grpc_rb_eCallError, "Cannot set credentials of closed call"); @@ -407,12 +406,12 @@ static VALUE grpc_rb_call_set_credentials(VALUE self, VALUE credentials) { grpc_rb_md_ary_capacity_hash_cb */ static int grpc_rb_md_ary_fill_hash_cb(VALUE key, VALUE val, VALUE md_ary_obj) { - grpc_metadata_array *md_ary = NULL; + grpc_metadata_array* md_ary = NULL; long array_length; long i; grpc_slice key_slice; grpc_slice value_slice; - char *tmp_str = NULL; + char* tmp_str = NULL; if (TYPE(key) == T_SYMBOL) { key_slice = grpc_slice_from_static_string(rb_id2name(SYM2ID(key))); @@ -482,7 +481,7 @@ static int grpc_rb_md_ary_fill_hash_cb(VALUE key, VALUE val, VALUE md_ary_obj) { */ static int grpc_rb_md_ary_capacity_hash_cb(VALUE key, VALUE val, VALUE md_ary_obj) { - grpc_metadata_array *md_ary = NULL; + grpc_metadata_array* md_ary = NULL; (void)key; @@ -503,7 +502,7 @@ static int grpc_rb_md_ary_capacity_hash_cb(VALUE key, VALUE val, /* grpc_rb_md_ary_convert converts a ruby metadata hash into a grpc_metadata_array. */ -void grpc_rb_md_ary_convert(VALUE md_ary_hash, grpc_metadata_array *md_ary) { +void grpc_rb_md_ary_convert(VALUE md_ary_hash, grpc_metadata_array* md_ary) { VALUE md_ary_obj = Qnil; if (md_ary_hash == Qnil) { return; /* Do nothing if the expected has value is nil */ @@ -524,7 +523,7 @@ void grpc_rb_md_ary_convert(VALUE md_ary_hash, grpc_metadata_array *md_ary) { } /* Converts a metadata array to a hash. */ -VALUE grpc_rb_md_ary_to_h(grpc_metadata_array *md_ary) { +VALUE grpc_rb_md_ary_to_h(grpc_metadata_array* md_ary) { VALUE key = Qnil; VALUE new_ary = Qnil; VALUE value = Qnil; @@ -587,7 +586,7 @@ static int grpc_rb_call_check_op_keys_hash_cb(VALUE key, VALUE val, struct to the 'send_status_from_server' portion of an op. */ static void grpc_rb_op_update_status_from_server( - grpc_op *op, grpc_metadata_array *md_ary, grpc_slice *send_status_details, + grpc_op* op, grpc_metadata_array* md_ary, grpc_slice* send_status_details, VALUE status) { VALUE code = rb_struct_aref(status, sym_code); VALUE details = rb_struct_aref(status, sym_details); @@ -627,7 +626,7 @@ typedef struct run_batch_stack { grpc_metadata_array send_trailing_metadata; /* Data being received */ - grpc_byte_buffer *recv_message; + grpc_byte_buffer* recv_message; grpc_metadata_array recv_metadata; grpc_metadata_array recv_trailing_metadata; int recv_cancelled; @@ -639,7 +638,7 @@ typedef struct run_batch_stack { /* grpc_run_batch_stack_init ensures the run_batch_stack is properly * initialized */ -static void grpc_run_batch_stack_init(run_batch_stack *st, +static void grpc_run_batch_stack_init(run_batch_stack* st, unsigned write_flag) { MEMZERO(st, run_batch_stack, 1); grpc_metadata_array_init(&st->send_metadata); @@ -651,7 +650,7 @@ static void grpc_run_batch_stack_init(run_batch_stack *st, } void grpc_rb_metadata_array_destroy_including_entries( - grpc_metadata_array *array) { + grpc_metadata_array* array) { size_t i; if (array->metadata) { for (i = 0; i < array->count; i++) { @@ -664,7 +663,7 @@ void grpc_rb_metadata_array_destroy_including_entries( /* grpc_run_batch_stack_cleanup ensures the run_batch_stack is properly * cleaned up */ -static void grpc_run_batch_stack_cleanup(run_batch_stack *st) { +static void grpc_run_batch_stack_cleanup(run_batch_stack* st) { size_t i = 0; grpc_rb_metadata_array_destroy_including_entries(&st->send_metadata); @@ -693,7 +692,7 @@ static void grpc_run_batch_stack_cleanup(run_batch_stack *st) { /* grpc_run_batch_stack_fill_ops fills the run_batch_stack ops array from * ops_hash */ -static void grpc_run_batch_stack_fill_ops(run_batch_stack *st, VALUE ops_hash) { +static void grpc_run_batch_stack_fill_ops(run_batch_stack* st, VALUE ops_hash) { VALUE this_op = Qnil; VALUE this_value = Qnil; VALUE ops_ary = rb_ary_new(); @@ -760,7 +759,7 @@ static void grpc_run_batch_stack_fill_ops(run_batch_stack *st, VALUE ops_hash) { /* grpc_run_batch_stack_build_result fills constructs a ruby BatchResult struct after the results have run */ -static VALUE grpc_run_batch_stack_build_result(run_batch_stack *st) { +static VALUE grpc_run_batch_stack_build_result(run_batch_stack* st) { size_t i = 0; VALUE result = rb_struct_new(grpc_rb_sBatchResult, Qnil, Qnil, Qnil, Qnil, Qnil, Qnil, Qnil, Qnil, NULL); @@ -823,14 +822,14 @@ static VALUE grpc_run_batch_stack_build_result(run_batch_stack *st) { Only one operation of each type can be active at once in any given batch */ static VALUE grpc_rb_call_run_batch(VALUE self, VALUE ops_hash) { - run_batch_stack *st = NULL; - grpc_rb_call *call = NULL; + run_batch_stack* st = NULL; + grpc_rb_call* call = NULL; grpc_event ev; grpc_call_error err; VALUE result = Qnil; VALUE rb_write_flag = rb_ivar_get(self, id_write_flag); unsigned write_flag = 0; - void *tag = (void *)&st; + void* tag = (void*)&st; if (RTYPEDDATA_DATA(self) == NULL) { rb_raise(grpc_rb_eCallError, "Cannot run batch on closed call"); @@ -997,8 +996,8 @@ void Init_grpc_call() { rb_define_method(grpc_rb_cCall, "metadata=", grpc_rb_call_set_metadata, 1); rb_define_method(grpc_rb_cCall, "trailing_metadata", grpc_rb_call_get_trailing_metadata, 0); - rb_define_method(grpc_rb_cCall, "trailing_metadata=", - grpc_rb_call_set_trailing_metadata, 1); + rb_define_method(grpc_rb_cCall, + "trailing_metadata=", grpc_rb_call_set_trailing_metadata, 1); rb_define_method(grpc_rb_cCall, "write_flag", grpc_rb_call_get_write_flag, 0); rb_define_method(grpc_rb_cCall, "write_flag=", grpc_rb_call_set_write_flag, 1); @@ -1035,15 +1034,15 @@ void Init_grpc_call() { } /* Gets the call from the ruby object */ -grpc_call *grpc_rb_get_wrapped_call(VALUE v) { - grpc_rb_call *call = NULL; +grpc_call* grpc_rb_get_wrapped_call(VALUE v) { + grpc_rb_call* call = NULL; TypedData_Get_Struct(v, grpc_rb_call, &grpc_call_data_type, call); return call->wrapped; } /* Obtains the wrapped object for a given call */ -VALUE grpc_rb_wrap_call(grpc_call *c, grpc_completion_queue *q) { - grpc_rb_call *wrapper; +VALUE grpc_rb_wrap_call(grpc_call* c, grpc_completion_queue* q) { + grpc_rb_call* wrapper; if (c == NULL || q == NULL) { return Qnil; } diff --git a/src/ruby/ext/grpc/rb_call.h b/src/ruby/ext/grpc/rb_call.h index bfe8035e0fb..a2202eb8d31 100644 --- a/src/ruby/ext/grpc/rb_call.h +++ b/src/ruby/ext/grpc/rb_call.h @@ -24,24 +24,24 @@ #include /* Gets the wrapped call from a VALUE. */ -grpc_call *grpc_rb_get_wrapped_call(VALUE v); +grpc_call* grpc_rb_get_wrapped_call(VALUE v); /* Gets the VALUE corresponding to given grpc_call. */ -VALUE grpc_rb_wrap_call(grpc_call *c, grpc_completion_queue *q); +VALUE grpc_rb_wrap_call(grpc_call* c, grpc_completion_queue* q); /* Provides the details of an call error */ -const char *grpc_call_error_detail_of(grpc_call_error err); +const char* grpc_call_error_detail_of(grpc_call_error err); /* Converts a metadata array to a hash. */ -VALUE grpc_rb_md_ary_to_h(grpc_metadata_array *md_ary); +VALUE grpc_rb_md_ary_to_h(grpc_metadata_array* md_ary); /* grpc_rb_md_ary_convert converts a ruby metadata hash into a grpc_metadata_array. */ -void grpc_rb_md_ary_convert(VALUE md_ary_hash, grpc_metadata_array *md_ary); +void grpc_rb_md_ary_convert(VALUE md_ary_hash, grpc_metadata_array* md_ary); void grpc_rb_metadata_array_destroy_including_entries( - grpc_metadata_array *md_ary); + grpc_metadata_array* md_ary); /* grpc_rb_eCallError is the ruby class of the exception thrown during call operations. */ diff --git a/src/ruby/ext/grpc/rb_call_credentials.c b/src/ruby/ext/grpc/rb_call_credentials.c index 4214a0811bd..be325975920 100644 --- a/src/ruby/ext/grpc/rb_call_credentials.c +++ b/src/ruby/ext/grpc/rb_call_credentials.c @@ -44,13 +44,13 @@ typedef struct grpc_rb_call_credentials { VALUE mark; /* The actual credentials */ - grpc_call_credentials *wrapped; + grpc_call_credentials* wrapped; } grpc_rb_call_credentials; typedef struct callback_params { VALUE get_metadata; grpc_auth_metadata_context context; - void *user_data; + void* user_data; grpc_credentials_plugin_metadata_cb callback; } callback_params; @@ -82,8 +82,8 @@ static VALUE grpc_rb_call_credentials_callback_rescue(VALUE args, return result; } -static void grpc_rb_call_credentials_callback_with_gil(void *param) { - callback_params *const params = (callback_params *)param; +static void grpc_rb_call_credentials_callback_with_gil(void* param) { + callback_params* const params = (callback_params*)param; VALUE auth_uri = rb_str_new_cstr(params->context.service_url); /* Pass the arguments to the proc in a hash, which currently only has they key 'auth_uri' */ @@ -93,7 +93,7 @@ static void grpc_rb_call_credentials_callback_with_gil(void *param) { grpc_metadata_array md_ary; grpc_status_code status; VALUE details; - char *error_details; + char* error_details; grpc_metadata_array_init(&md_ary); rb_hash_aset(args, ID2SYM(rb_intern("jwt_aud_uri")), auth_uri); rb_ary_push(callback_args, params->get_metadata); @@ -113,34 +113,34 @@ static void grpc_rb_call_credentials_callback_with_gil(void *param) { } static int grpc_rb_call_credentials_plugin_get_metadata( - void *state, grpc_auth_metadata_context context, - grpc_credentials_plugin_metadata_cb cb, void *user_data, + void* state, grpc_auth_metadata_context context, + grpc_credentials_plugin_metadata_cb cb, void* user_data, grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], - size_t *num_creds_md, grpc_status_code *status, - const char **error_details) { - callback_params *params = gpr_malloc(sizeof(callback_params)); + size_t* num_creds_md, grpc_status_code* status, + const char** error_details) { + callback_params* params = gpr_malloc(sizeof(callback_params)); params->get_metadata = (VALUE)state; params->context = context; params->user_data = user_data; params->callback = cb; grpc_rb_event_queue_enqueue(grpc_rb_call_credentials_callback_with_gil, - (void *)(params)); + (void*)(params)); return 0; // Async return. } -static void grpc_rb_call_credentials_plugin_destroy(void *state) { +static void grpc_rb_call_credentials_plugin_destroy(void* state) { (void)state; // Not sure what needs to be done here } /* Destroys the credentials instances. */ -static void grpc_rb_call_credentials_free(void *p) { - grpc_rb_call_credentials *wrapper; +static void grpc_rb_call_credentials_free(void* p) { + grpc_rb_call_credentials* wrapper; if (p == NULL) { return; } - wrapper = (grpc_rb_call_credentials *)p; + wrapper = (grpc_rb_call_credentials*)p; grpc_call_credentials_release(wrapper->wrapped); wrapper->wrapped = NULL; @@ -148,12 +148,12 @@ static void grpc_rb_call_credentials_free(void *p) { } /* Protects the mark object from GC */ -static void grpc_rb_call_credentials_mark(void *p) { - grpc_rb_call_credentials *wrapper = NULL; +static void grpc_rb_call_credentials_mark(void* p) { + grpc_rb_call_credentials* wrapper = NULL; if (p == NULL) { return; } - wrapper = (grpc_rb_call_credentials *)p; + wrapper = (grpc_rb_call_credentials*)p; if (wrapper->mark != Qnil) { rb_gc_mark(wrapper->mark); } @@ -175,7 +175,7 @@ static rb_data_type_t grpc_rb_call_credentials_data_type = { /* Allocates CallCredentials instances. Provides safe initial defaults for the instance fields. */ static VALUE grpc_rb_call_credentials_alloc(VALUE cls) { - grpc_rb_call_credentials *wrapper = ALLOC(grpc_rb_call_credentials); + grpc_rb_call_credentials* wrapper = ALLOC(grpc_rb_call_credentials); wrapper->wrapped = NULL; wrapper->mark = Qnil; return TypedData_Wrap_Struct(cls, &grpc_rb_call_credentials_data_type, @@ -185,9 +185,9 @@ static VALUE grpc_rb_call_credentials_alloc(VALUE cls) { /* Creates a wrapping object for a given call credentials. This should only be * called with grpc_call_credentials objects that are not already associated * with any Ruby object */ -VALUE grpc_rb_wrap_call_credentials(grpc_call_credentials *c, VALUE mark) { +VALUE grpc_rb_wrap_call_credentials(grpc_call_credentials* c, VALUE mark) { VALUE rb_wrapper; - grpc_rb_call_credentials *wrapper; + grpc_rb_call_credentials* wrapper; if (c == NULL) { return Qnil; } @@ -208,8 +208,8 @@ static ID id_callback; proc: (required) Proc that generates auth metadata Initializes CallCredential instances. */ static VALUE grpc_rb_call_credentials_init(VALUE self, VALUE proc) { - grpc_rb_call_credentials *wrapper = NULL; - grpc_call_credentials *creds = NULL; + grpc_rb_call_credentials* wrapper = NULL; + grpc_call_credentials* creds = NULL; grpc_metadata_credentials_plugin plugin; grpc_ruby_once_init(); @@ -223,7 +223,7 @@ static VALUE grpc_rb_call_credentials_init(VALUE self, VALUE proc) { rb_raise(rb_eTypeError, "Argument to CallCredentials#new must be a proc"); return Qnil; } - plugin.state = (void *)proc; + plugin.state = (void*)proc; plugin.type = ""; creds = grpc_metadata_credentials_create_from_plugin(plugin, NULL); @@ -239,11 +239,11 @@ static VALUE grpc_rb_call_credentials_init(VALUE self, VALUE proc) { return self; } -static VALUE grpc_rb_call_credentials_compose(int argc, VALUE *argv, +static VALUE grpc_rb_call_credentials_compose(int argc, VALUE* argv, VALUE self) { - grpc_call_credentials *creds; - grpc_call_credentials *other; - grpc_call_credentials *prev = NULL; + grpc_call_credentials* creds; + grpc_call_credentials* other; + grpc_call_credentials* prev = NULL; VALUE mark; if (argc == 0) { return self; @@ -282,8 +282,8 @@ void Init_grpc_call_credentials() { } /* Gets the wrapped grpc_call_credentials from the ruby wrapper */ -grpc_call_credentials *grpc_rb_get_wrapped_call_credentials(VALUE v) { - grpc_rb_call_credentials *wrapper = NULL; +grpc_call_credentials* grpc_rb_get_wrapped_call_credentials(VALUE v) { + grpc_rb_call_credentials* wrapper = NULL; TypedData_Get_Struct(v, grpc_rb_call_credentials, &grpc_rb_call_credentials_data_type, wrapper); return wrapper->wrapped; diff --git a/src/ruby/ext/grpc/rb_channel.c b/src/ruby/ext/grpc/rb_channel.c index f0af54d9e58..1d11a53aa72 100644 --- a/src/ruby/ext/grpc/rb_channel.c +++ b/src/ruby/ext/grpc/rb_channel.c @@ -54,9 +54,9 @@ static VALUE grpc_rb_cChannel = Qnil; static VALUE grpc_rb_cChannelArgs; typedef struct bg_watched_channel { - grpc_channel *channel; + grpc_channel* channel; // these fields must only be accessed under global_connection_polling_mu - struct bg_watched_channel *next; + struct bg_watched_channel* next; int channel_destroyed; int refcount; } bg_watched_channel; @@ -67,7 +67,7 @@ typedef struct grpc_rb_channel { /* The actual channel (protected in a wrapper to tell when it's safe to * destroy) */ - bg_watched_channel *bg_wrapped; + bg_watched_channel* bg_wrapped; } grpc_rb_channel; typedef enum { CONTINUOUS_WATCH, WATCH_STATE_API } watch_state_op_type; @@ -82,40 +82,40 @@ typedef struct watch_state_op { int called_back; } api_callback_args; struct { - bg_watched_channel *bg; + bg_watched_channel* bg; } continuous_watch_callback_args; } op; } watch_state_op; -static bg_watched_channel *bg_watched_channel_list_head = NULL; +static bg_watched_channel* bg_watched_channel_list_head = NULL; static void grpc_rb_channel_try_register_connection_polling( - bg_watched_channel *bg); -static void *wait_until_channel_polling_thread_started_no_gil(void *); -static void wait_until_channel_polling_thread_started_unblocking_func(void *); -static void *channel_init_try_register_connection_polling_without_gil( - void *arg); + bg_watched_channel* bg); +static void* wait_until_channel_polling_thread_started_no_gil(void*); +static void wait_until_channel_polling_thread_started_unblocking_func(void*); +static void* channel_init_try_register_connection_polling_without_gil( + void* arg); typedef struct channel_init_try_register_stack { - grpc_channel *channel; - grpc_rb_channel *wrapper; + grpc_channel* channel; + grpc_rb_channel* wrapper; } channel_init_try_register_stack; -static grpc_completion_queue *channel_polling_cq; +static grpc_completion_queue* channel_polling_cq; static gpr_mu global_connection_polling_mu; static gpr_cv global_connection_polling_cv; static int abort_channel_polling = 0; static int channel_polling_thread_started = 0; -static int bg_watched_channel_list_lookup(bg_watched_channel *bg); -static bg_watched_channel *bg_watched_channel_list_create_and_add( - grpc_channel *channel); -static void bg_watched_channel_list_free_and_remove(bg_watched_channel *bg); -static void run_poll_channels_loop_unblocking_func(void *arg); +static int bg_watched_channel_list_lookup(bg_watched_channel* bg); +static bg_watched_channel* bg_watched_channel_list_create_and_add( + grpc_channel* channel); +static void bg_watched_channel_list_free_and_remove(bg_watched_channel* bg); +static void run_poll_channels_loop_unblocking_func(void* arg); // Needs to be called under global_connection_polling_mu static void grpc_rb_channel_watch_connection_state_op_complete( - watch_state_op *op, int success) { + watch_state_op* op, int success) { GPR_ASSERT(!op->op.api_callback_args.called_back); op->op.api_callback_args.called_back = 1; op->op.api_callback_args.success = success; @@ -124,7 +124,7 @@ static void grpc_rb_channel_watch_connection_state_op_complete( } /* Avoids destroying a channel twice. */ -static void grpc_rb_channel_safe_destroy(bg_watched_channel *bg) { +static void grpc_rb_channel_safe_destroy(bg_watched_channel* bg) { gpr_mu_lock(&global_connection_polling_mu); GPR_ASSERT(bg_watched_channel_list_lookup(bg)); if (!bg->channel_destroyed) { @@ -138,18 +138,18 @@ static void grpc_rb_channel_safe_destroy(bg_watched_channel *bg) { gpr_mu_unlock(&global_connection_polling_mu); } -static void *channel_safe_destroy_without_gil(void *arg) { - grpc_rb_channel_safe_destroy((bg_watched_channel *)arg); +static void* channel_safe_destroy_without_gil(void* arg) { + grpc_rb_channel_safe_destroy((bg_watched_channel*)arg); return NULL; } /* Destroys Channel instances. */ -static void grpc_rb_channel_free(void *p) { - grpc_rb_channel *ch = NULL; +static void grpc_rb_channel_free(void* p) { + grpc_rb_channel* ch = NULL; if (p == NULL) { return; }; - ch = (grpc_rb_channel *)p; + ch = (grpc_rb_channel*)p; if (ch->bg_wrapped != NULL) { /* assumption made here: it's ok to directly gpr_mu_lock the global @@ -164,12 +164,12 @@ static void grpc_rb_channel_free(void *p) { } /* Protects the mark object from GC */ -static void grpc_rb_channel_mark(void *p) { - grpc_rb_channel *channel = NULL; +static void grpc_rb_channel_mark(void* p) { + grpc_rb_channel* channel = NULL; if (p == NULL) { return; } - channel = (grpc_rb_channel *)p; + channel = (grpc_rb_channel*)p; if (channel->credentials != Qnil) { rb_gc_mark(channel->credentials); } @@ -189,7 +189,7 @@ static rb_data_type_t grpc_channel_data_type = {"grpc_channel", /* Allocates grpc_rb_channel instances. */ static VALUE grpc_rb_channel_alloc(VALUE cls) { - grpc_rb_channel *wrapper = ALLOC(grpc_rb_channel); + grpc_rb_channel* wrapper = ALLOC(grpc_rb_channel); wrapper->bg_wrapped = NULL; wrapper->credentials = Qnil; return TypedData_Wrap_Struct(cls, &grpc_channel_data_type, wrapper); @@ -203,14 +203,14 @@ static VALUE grpc_rb_channel_alloc(VALUE cls) { secure_channel = Channel:new("myhost:443", {'arg1': 'value1'}, creds) Creates channel instances. */ -static VALUE grpc_rb_channel_init(int argc, VALUE *argv, VALUE self) { +static VALUE grpc_rb_channel_init(int argc, VALUE* argv, VALUE self) { VALUE channel_args = Qnil; VALUE credentials = Qnil; VALUE target = Qnil; - grpc_rb_channel *wrapper = NULL; - grpc_channel *ch = NULL; - grpc_channel_credentials *creds = NULL; - char *target_chars = NULL; + grpc_rb_channel* wrapper = NULL; + grpc_channel* ch = NULL; + grpc_channel_credentials* creds = NULL; + char* target_chars = NULL; grpc_channel_args args; channel_init_try_register_stack stack; int stop_waiting_for_thread_start = 0; @@ -262,13 +262,13 @@ static VALUE grpc_rb_channel_init(int argc, VALUE *argv, VALUE self) { } typedef struct get_state_stack { - bg_watched_channel *bg; + bg_watched_channel* bg; int try_to_connect; int out; } get_state_stack; -static void *get_state_without_gil(void *arg) { - get_state_stack *stack = (get_state_stack *)arg; +static void* get_state_without_gil(void* arg) { + get_state_stack* stack = (get_state_stack*)arg; gpr_mu_lock(&global_connection_polling_mu); GPR_ASSERT(abort_channel_polling || channel_polling_thread_started); @@ -292,10 +292,10 @@ static void *get_state_without_gil(void *arg) { constants defined in GRPC::Core::ConnectivityStates. It also tries to connect if the chennel is idle in the second form. */ -static VALUE grpc_rb_channel_get_connectivity_state(int argc, VALUE *argv, +static VALUE grpc_rb_channel_get_connectivity_state(int argc, VALUE* argv, VALUE self) { VALUE try_to_connect_param = Qfalse; - grpc_rb_channel *wrapper = NULL; + grpc_rb_channel* wrapper = NULL; get_state_stack stack; /* "01" == 0 mandatory args, 1 (try_to_connect) is optional */ @@ -315,22 +315,22 @@ static VALUE grpc_rb_channel_get_connectivity_state(int argc, VALUE *argv, } typedef struct watch_state_stack { - grpc_channel *channel; + grpc_channel* channel; gpr_timespec deadline; int last_state; } watch_state_stack; -static void *wait_for_watch_state_op_complete_without_gvl(void *arg) { - watch_state_stack *stack = (watch_state_stack *)arg; - watch_state_op *op = NULL; - void *success = (void *)0; +static void* wait_for_watch_state_op_complete_without_gvl(void* arg) { + watch_state_stack* stack = (watch_state_stack*)arg; + watch_state_op* op = NULL; + void* success = (void*)0; gpr_mu_lock(&global_connection_polling_mu); // its unsafe to do a "watch" after "channel polling abort" because the cq has // been shut down. if (abort_channel_polling) { gpr_mu_unlock(&global_connection_polling_mu); - return (void *)0; + return (void*)0; } op = gpr_zalloc(sizeof(watch_state_op)); op->op_type = WATCH_STATE_API; @@ -343,15 +343,15 @@ static void *wait_for_watch_state_op_complete_without_gvl(void *arg) { gpr_inf_future(GPR_CLOCK_REALTIME)); } if (op->op.api_callback_args.success) { - success = (void *)1; + success = (void*)1; } gpr_free(op); gpr_mu_unlock(&global_connection_polling_mu); return success; } -static void wait_for_watch_state_op_complete_unblocking_func(void *arg) { - bg_watched_channel *bg = (bg_watched_channel *)arg; +static void wait_for_watch_state_op_complete_unblocking_func(void* arg) { + bg_watched_channel* bg = (bg_watched_channel*)arg; gpr_mu_lock(&global_connection_polling_mu); if (!bg->channel_destroyed) { grpc_channel_destroy(bg->channel); @@ -370,9 +370,9 @@ static void wait_for_watch_state_op_complete_unblocking_func(void *arg) { static VALUE grpc_rb_channel_watch_connectivity_state(VALUE self, VALUE last_state, VALUE deadline) { - grpc_rb_channel *wrapper = NULL; + grpc_rb_channel* wrapper = NULL; watch_state_stack stack; - void *op_success = 0; + void* op_success = 0; TypedData_Get_Struct(self, grpc_rb_channel, &grpc_channel_data_type, wrapper); @@ -405,15 +405,15 @@ static VALUE grpc_rb_channel_create_call(VALUE self, VALUE parent, VALUE mask, VALUE method, VALUE host, VALUE deadline) { VALUE res = Qnil; - grpc_rb_channel *wrapper = NULL; - grpc_call *call = NULL; - grpc_call *parent_call = NULL; - grpc_completion_queue *cq = NULL; + grpc_rb_channel* wrapper = NULL; + grpc_call* call = NULL; + grpc_call* parent_call = NULL; + grpc_completion_queue* cq = NULL; int flags = GRPC_PROPAGATE_DEFAULTS; grpc_slice method_slice; grpc_slice host_slice; - grpc_slice *host_slice_ptr = NULL; - char *tmp_str = NULL; + grpc_slice* host_slice_ptr = NULL; + char* tmp_str = NULL; if (host != Qnil) { host_slice = @@ -466,7 +466,7 @@ static VALUE grpc_rb_channel_create_call(VALUE self, VALUE parent, VALUE mask, /* Note this is an API-level call; a wrapped channel's finalizer doesn't call * this */ static VALUE grpc_rb_channel_destroy(VALUE self) { - grpc_rb_channel *wrapper = NULL; + grpc_rb_channel* wrapper = NULL; TypedData_Get_Struct(self, grpc_rb_channel, &grpc_channel_data_type, wrapper); if (wrapper->bg_wrapped != NULL) { @@ -480,9 +480,9 @@ static VALUE grpc_rb_channel_destroy(VALUE self) { /* Called to obtain the target that this channel accesses. */ static VALUE grpc_rb_channel_get_target(VALUE self) { - grpc_rb_channel *wrapper = NULL; + grpc_rb_channel* wrapper = NULL; VALUE res = Qnil; - char *target = NULL; + char* target = NULL; TypedData_Get_Struct(self, grpc_rb_channel, &grpc_channel_data_type, wrapper); target = grpc_channel_get_target(wrapper->bg_wrapped->channel); @@ -493,8 +493,8 @@ static VALUE grpc_rb_channel_get_target(VALUE self) { } /* Needs to be called under global_connection_polling_mu */ -static int bg_watched_channel_list_lookup(bg_watched_channel *target) { - bg_watched_channel *cur = bg_watched_channel_list_head; +static int bg_watched_channel_list_lookup(bg_watched_channel* target) { + bg_watched_channel* cur = bg_watched_channel_list_head; while (cur != NULL) { if (cur == target) { @@ -507,9 +507,9 @@ static int bg_watched_channel_list_lookup(bg_watched_channel *target) { } /* Needs to be called under global_connection_polling_mu */ -static bg_watched_channel *bg_watched_channel_list_create_and_add( - grpc_channel *channel) { - bg_watched_channel *watched = gpr_zalloc(sizeof(bg_watched_channel)); +static bg_watched_channel* bg_watched_channel_list_create_and_add( + grpc_channel* channel) { + bg_watched_channel* watched = gpr_zalloc(sizeof(bg_watched_channel)); watched->channel = channel; watched->next = bg_watched_channel_list_head; @@ -520,8 +520,8 @@ static bg_watched_channel *bg_watched_channel_list_create_and_add( /* Needs to be called under global_connection_polling_mu */ static void bg_watched_channel_list_free_and_remove( - bg_watched_channel *target) { - bg_watched_channel *bg = NULL; + bg_watched_channel* target) { + bg_watched_channel* bg = NULL; GPR_ASSERT(bg_watched_channel_list_lookup(target)); GPR_ASSERT(target->channel_destroyed && target->refcount == 0); @@ -544,10 +544,10 @@ static void bg_watched_channel_list_free_and_remove( /* Initialize a grpc_rb_channel's "protected grpc_channel" and try to push * it onto the background thread for constant watches. */ -static void *channel_init_try_register_connection_polling_without_gil( - void *arg) { - channel_init_try_register_stack *stack = - (channel_init_try_register_stack *)arg; +static void* channel_init_try_register_connection_polling_without_gil( + void* arg) { + channel_init_try_register_stack* stack = + (channel_init_try_register_stack*)arg; gpr_mu_lock(&global_connection_polling_mu); stack->wrapper->bg_wrapped = @@ -559,9 +559,9 @@ static void *channel_init_try_register_connection_polling_without_gil( // Needs to be called under global_connection_poolling_mu static void grpc_rb_channel_try_register_connection_polling( - bg_watched_channel *bg) { + bg_watched_channel* bg) { grpc_connectivity_state conn_state; - watch_state_op *op = NULL; + watch_state_op* op = NULL; GPR_ASSERT(channel_polling_thread_started || abort_channel_polling); @@ -597,10 +597,10 @@ static void grpc_rb_channel_try_register_connection_polling( // indicates process shutdown. // In the worst case, this stops polling channel connectivity // early and falls back to current behavior. -static void *run_poll_channels_loop_no_gil(void *arg) { +static void* run_poll_channels_loop_no_gil(void* arg) { grpc_event event; - watch_state_op *op = NULL; - bg_watched_channel *bg = NULL; + watch_state_op* op = NULL; + bg_watched_channel* bg = NULL; (void)arg; gpr_log(GPR_DEBUG, "GRPC_RUBY: run_poll_channels_loop_no_gil - begin"); @@ -618,15 +618,15 @@ static void *run_poll_channels_loop_no_gil(void *arg) { } gpr_mu_lock(&global_connection_polling_mu); if (event.type == GRPC_OP_COMPLETE) { - op = (watch_state_op *)event.tag; + op = (watch_state_op*)event.tag; if (op->op_type == CONTINUOUS_WATCH) { - bg = (bg_watched_channel *)op->op.continuous_watch_callback_args.bg; + bg = (bg_watched_channel*)op->op.continuous_watch_callback_args.bg; bg->refcount--; grpc_rb_channel_try_register_connection_polling(bg); gpr_free(op); } else if (op->op_type == WATCH_STATE_API) { grpc_rb_channel_watch_connection_state_op_complete( - (watch_state_op *)event.tag, event.success); + (watch_state_op*)event.tag, event.success); } else { GPR_ASSERT(0); } @@ -641,8 +641,8 @@ static void *run_poll_channels_loop_no_gil(void *arg) { } // Notify the channel polling loop to cleanup and shutdown. -static void run_poll_channels_loop_unblocking_func(void *arg) { - bg_watched_channel *bg = NULL; +static void run_poll_channels_loop_unblocking_func(void* arg) { + bg_watched_channel* bg = NULL; (void)arg; gpr_mu_lock(&global_connection_polling_mu); @@ -686,8 +686,8 @@ static VALUE run_poll_channels_loop(VALUE arg) { return Qnil; } -static void *wait_until_channel_polling_thread_started_no_gil(void *arg) { - int *stop_waiting = (int *)arg; +static void* wait_until_channel_polling_thread_started_no_gil(void* arg) { + int* stop_waiting = (int*)arg; gpr_log(GPR_DEBUG, "GRPC_RUBY: wait for channel polling thread to start"); gpr_mu_lock(&global_connection_polling_mu); while (!channel_polling_thread_started && !abort_channel_polling && @@ -701,8 +701,8 @@ static void *wait_until_channel_polling_thread_started_no_gil(void *arg) { } static void wait_until_channel_polling_thread_started_unblocking_func( - void *arg) { - int *stop_waiting = (int *)arg; + void* arg) { + int* stop_waiting = (int*)arg; gpr_mu_lock(&global_connection_polling_mu); gpr_log(GPR_DEBUG, "GRPC_RUBY: interrupt wait for channel polling thread to start"); @@ -711,7 +711,7 @@ static void wait_until_channel_polling_thread_started_unblocking_func( gpr_mu_unlock(&global_connection_polling_mu); } -static void *set_abort_channel_polling_without_gil(void *arg) { +static void* set_abort_channel_polling_without_gil(void* arg) { (void)arg; gpr_mu_lock(&global_connection_polling_mu); abort_channel_polling = 1; @@ -822,8 +822,8 @@ void Init_grpc_channel() { } /* Gets the wrapped channel from the ruby wrapper */ -grpc_channel *grpc_rb_get_wrapped_channel(VALUE v) { - grpc_rb_channel *wrapper = NULL; +grpc_channel* grpc_rb_get_wrapped_channel(VALUE v) { + grpc_rb_channel* wrapper = NULL; TypedData_Get_Struct(v, grpc_rb_channel, &grpc_channel_data_type, wrapper); return wrapper->bg_wrapped->channel; } diff --git a/src/ruby/ext/grpc/rb_channel_credentials.c b/src/ruby/ext/grpc/rb_channel_credentials.c index 83601ca694f..b23a32caf1c 100644 --- a/src/ruby/ext/grpc/rb_channel_credentials.c +++ b/src/ruby/ext/grpc/rb_channel_credentials.c @@ -35,7 +35,7 @@ grpc_channel_credentials. */ static VALUE grpc_rb_cChannelCredentials = Qnil; -static char *pem_root_certs = NULL; +static char* pem_root_certs = NULL; /* grpc_rb_channel_credentials wraps a grpc_channel_credentials. It provides a * mark object that is used to hold references to any objects used to create @@ -45,16 +45,16 @@ typedef struct grpc_rb_channel_credentials { VALUE mark; /* The actual credentials */ - grpc_channel_credentials *wrapped; + grpc_channel_credentials* wrapped; } grpc_rb_channel_credentials; /* Destroys the credentials instances. */ -static void grpc_rb_channel_credentials_free(void *p) { - grpc_rb_channel_credentials *wrapper = NULL; +static void grpc_rb_channel_credentials_free(void* p) { + grpc_rb_channel_credentials* wrapper = NULL; if (p == NULL) { return; }; - wrapper = (grpc_rb_channel_credentials *)p; + wrapper = (grpc_rb_channel_credentials*)p; grpc_channel_credentials_release(wrapper->wrapped); wrapper->wrapped = NULL; @@ -62,12 +62,12 @@ static void grpc_rb_channel_credentials_free(void *p) { } /* Protects the mark object from GC */ -static void grpc_rb_channel_credentials_mark(void *p) { - grpc_rb_channel_credentials *wrapper = NULL; +static void grpc_rb_channel_credentials_mark(void* p) { + grpc_rb_channel_credentials* wrapper = NULL; if (p == NULL) { return; } - wrapper = (grpc_rb_channel_credentials *)p; + wrapper = (grpc_rb_channel_credentials*)p; if (wrapper->mark != Qnil) { rb_gc_mark(wrapper->mark); @@ -90,7 +90,7 @@ static rb_data_type_t grpc_rb_channel_credentials_data_type = { /* Allocates ChannelCredential instances. Provides safe initial defaults for the instance fields. */ static VALUE grpc_rb_channel_credentials_alloc(VALUE cls) { - grpc_rb_channel_credentials *wrapper = ALLOC(grpc_rb_channel_credentials); + grpc_rb_channel_credentials* wrapper = ALLOC(grpc_rb_channel_credentials); wrapper->wrapped = NULL; wrapper->mark = Qnil; return TypedData_Wrap_Struct(cls, &grpc_rb_channel_credentials_data_type, @@ -100,10 +100,10 @@ static VALUE grpc_rb_channel_credentials_alloc(VALUE cls) { /* Creates a wrapping object for a given channel credentials. This should only * be called with grpc_channel_credentials objects that are not already * associated with any Ruby object. */ -VALUE grpc_rb_wrap_channel_credentials(grpc_channel_credentials *c, +VALUE grpc_rb_wrap_channel_credentials(grpc_channel_credentials* c, VALUE mark) { VALUE rb_wrapper; - grpc_rb_channel_credentials *wrapper; + grpc_rb_channel_credentials* wrapper; if (c == NULL) { return Qnil; } @@ -136,15 +136,15 @@ static ID id_pem_cert_chain; pem_private_key: (optional) PEM encoding of the client's private key pem_cert_chain: (optional) PEM encoding of the client's cert chain Initializes Credential instances. */ -static VALUE grpc_rb_channel_credentials_init(int argc, VALUE *argv, +static VALUE grpc_rb_channel_credentials_init(int argc, VALUE* argv, VALUE self) { VALUE pem_root_certs = Qnil; VALUE pem_private_key = Qnil; VALUE pem_cert_chain = Qnil; - grpc_rb_channel_credentials *wrapper = NULL; - grpc_channel_credentials *creds = NULL; + grpc_rb_channel_credentials* wrapper = NULL; + grpc_channel_credentials* creds = NULL; grpc_ssl_pem_key_cert_pair key_cert_pair; - const char *pem_root_certs_cstr = NULL; + const char* pem_root_certs_cstr = NULL; MEMZERO(&key_cert_pair, grpc_ssl_pem_key_cert_pair, 1); grpc_ruby_once_init(); @@ -180,11 +180,11 @@ static VALUE grpc_rb_channel_credentials_init(int argc, VALUE *argv, return self; } -static VALUE grpc_rb_channel_credentials_compose(int argc, VALUE *argv, +static VALUE grpc_rb_channel_credentials_compose(int argc, VALUE* argv, VALUE self) { - grpc_channel_credentials *creds; - grpc_call_credentials *other; - grpc_channel_credentials *prev = NULL; + grpc_channel_credentials* creds; + grpc_call_credentials* other; + grpc_channel_credentials* prev = NULL; VALUE mark; if (argc == 0) { return self; @@ -210,7 +210,7 @@ static VALUE grpc_rb_channel_credentials_compose(int argc, VALUE *argv, } static grpc_ssl_roots_override_result get_ssl_roots_override( - char **pem_root_certs_ptr) { + char** pem_root_certs_ptr) { *pem_root_certs_ptr = pem_root_certs; if (pem_root_certs == NULL) { return GRPC_SSL_ROOTS_OVERRIDE_FAIL; @@ -220,7 +220,7 @@ static grpc_ssl_roots_override_result get_ssl_roots_override( } static VALUE grpc_rb_set_default_roots_pem(VALUE self, VALUE roots) { - char *roots_ptr = StringValueCStr(roots); + char* roots_ptr = StringValueCStr(roots); size_t length = strlen(roots_ptr); (void)self; pem_root_certs = gpr_malloc((length + 1) * sizeof(char)); @@ -255,8 +255,8 @@ void Init_grpc_channel_credentials() { } /* Gets the wrapped grpc_channel_credentials from the ruby wrapper */ -grpc_channel_credentials *grpc_rb_get_wrapped_channel_credentials(VALUE v) { - grpc_rb_channel_credentials *wrapper = NULL; +grpc_channel_credentials* grpc_rb_get_wrapped_channel_credentials(VALUE v) { + grpc_rb_channel_credentials* wrapper = NULL; TypedData_Get_Struct(v, grpc_rb_channel_credentials, &grpc_rb_channel_credentials_data_type, wrapper); return wrapper->wrapped; diff --git a/src/ruby/ext/grpc/rb_completion_queue.c b/src/ruby/ext/grpc/rb_completion_queue.c index 4283c27429d..64264f5b158 100644 --- a/src/ruby/ext/grpc/rb_completion_queue.c +++ b/src/ruby/ext/grpc/rb_completion_queue.c @@ -30,16 +30,16 @@ /* Used to allow grpc_completion_queue_next call to release the GIL */ typedef struct next_call_stack { - grpc_completion_queue *cq; + grpc_completion_queue* cq; grpc_event event; gpr_timespec timeout; - void *tag; + void* tag; volatile int interrupted; } next_call_stack; /* Calls grpc_completion_queue_pluck without holding the ruby GIL */ -static void *grpc_rb_completion_queue_pluck_no_gil(void *param) { - next_call_stack *const next_call = (next_call_stack *)param; +static void* grpc_rb_completion_queue_pluck_no_gil(void* param) { + next_call_stack* const next_call = (next_call_stack*)param; gpr_timespec increment = gpr_time_from_millis(20, GPR_TIMESPAN); gpr_timespec deadline; do { @@ -55,7 +55,7 @@ static void *grpc_rb_completion_queue_pluck_no_gil(void *param) { } /* Helper function to free a completion queue. */ -void grpc_rb_completion_queue_destroy(grpc_completion_queue *cq) { +void grpc_rb_completion_queue_destroy(grpc_completion_queue* cq) { /* Every function that adds an event to a queue also synchronously plucks that event from the queue, and holds a reference to the Ruby object that holds the queue, so we only get to this point if all of those functions @@ -64,15 +64,15 @@ void grpc_rb_completion_queue_destroy(grpc_completion_queue *cq) { grpc_completion_queue_destroy(cq); } -static void unblock_func(void *param) { - next_call_stack *const next_call = (next_call_stack *)param; +static void unblock_func(void* param) { + next_call_stack* const next_call = (next_call_stack*)param; next_call->interrupted = 1; } /* Does the same thing as grpc_completion_queue_pluck, while properly releasing the GVL and handling interrupts */ -grpc_event rb_completion_queue_pluck(grpc_completion_queue *queue, void *tag, - gpr_timespec deadline, void *reserved) { +grpc_event rb_completion_queue_pluck(grpc_completion_queue* queue, void* tag, + gpr_timespec deadline, void* reserved) { next_call_stack next_call; MEMZERO(&next_call, next_call_stack, 1); next_call.cq = queue; @@ -91,8 +91,8 @@ grpc_event rb_completion_queue_pluck(grpc_completion_queue *queue, void *tag, do { next_call.interrupted = 0; rb_thread_call_without_gvl(grpc_rb_completion_queue_pluck_no_gil, - (void *)&next_call, unblock_func, - (void *)&next_call); + (void*)&next_call, unblock_func, + (void*)&next_call); /* If an interrupt prevented pluck from returning useful information, then any plucks that did complete must have timed out */ } while (next_call.interrupted && next_call.event.type == GRPC_QUEUE_TIMEOUT); diff --git a/src/ruby/ext/grpc/rb_completion_queue.h b/src/ruby/ext/grpc/rb_completion_queue.h index 011b849e3f1..8c29089b9bc 100644 --- a/src/ruby/ext/grpc/rb_completion_queue.h +++ b/src/ruby/ext/grpc/rb_completion_queue.h @@ -23,14 +23,14 @@ #include -void grpc_rb_completion_queue_destroy(grpc_completion_queue *cq); +void grpc_rb_completion_queue_destroy(grpc_completion_queue* cq); /** * Makes the implementation of CompletionQueue#pluck available in other files * * This avoids having code that holds the GIL repeated at multiple sites. */ -grpc_event rb_completion_queue_pluck(grpc_completion_queue *queue, void *tag, - gpr_timespec deadline, void *reserved); +grpc_event rb_completion_queue_pluck(grpc_completion_queue* queue, void* tag, + gpr_timespec deadline, void* reserved); #endif /* GRPC_RB_COMPLETION_QUEUE_H_ */ diff --git a/src/ruby/ext/grpc/rb_compression_options.c b/src/ruby/ext/grpc/rb_compression_options.c index 3365b1784da..e24f20d2f9d 100644 --- a/src/ruby/ext/grpc/rb_compression_options.c +++ b/src/ruby/ext/grpc/rb_compression_options.c @@ -47,17 +47,17 @@ static VALUE id_compress_level_high = Qnil; * Ruby objects and don't have a mark for GC. */ typedef struct grpc_rb_compression_options { /* The actual compression options that's being wrapped */ - grpc_compression_options *wrapped; + grpc_compression_options* wrapped; } grpc_rb_compression_options; /* Destroys the compression options instances and free the * wrapped grpc compression options. */ -static void grpc_rb_compression_options_free(void *p) { - grpc_rb_compression_options *wrapper = NULL; +static void grpc_rb_compression_options_free(void* p) { + grpc_rb_compression_options* wrapper = NULL; if (p == NULL) { return; }; - wrapper = (grpc_rb_compression_options *)p; + wrapper = (grpc_rb_compression_options*)p; if (wrapper->wrapped != NULL) { gpr_free(wrapper->wrapped); @@ -85,7 +85,7 @@ static rb_data_type_t grpc_rb_compression_options_data_type = { Allocate the wrapped grpc compression options and initialize it here too. */ static VALUE grpc_rb_compression_options_alloc(VALUE cls) { - grpc_rb_compression_options *wrapper = NULL; + grpc_rb_compression_options* wrapper = NULL; grpc_ruby_once_init(); @@ -103,7 +103,7 @@ static VALUE grpc_rb_compression_options_alloc(VALUE cls) { VALUE grpc_rb_compression_options_disable_compression_algorithm_internal( VALUE self, VALUE algorithm_to_disable) { grpc_compression_algorithm compression_algorithm = 0; - grpc_rb_compression_options *wrapper = NULL; + grpc_rb_compression_options* wrapper = NULL; TypedData_Get_Struct(self, grpc_rb_compression_options, &grpc_rb_compression_options_data_type, wrapper); @@ -145,7 +145,7 @@ grpc_compression_level grpc_rb_compression_options_level_name_to_value_internal( /* Sets the default compression level, given the name of a compression level. * Throws an error if no algorithm matched. */ void grpc_rb_compression_options_set_default_level( - grpc_compression_options *options, VALUE new_level_name) { + grpc_compression_options* options, VALUE new_level_name) { options->default_level.level = grpc_rb_compression_options_level_name_to_value_internal(new_level_name); options->default_level.is_set = 1; @@ -156,10 +156,10 @@ void grpc_rb_compression_options_set_default_level( * algorithm_value is an out parameter. * Raises an error if the name of the algorithm passed in is invalid. */ void grpc_rb_compression_options_algorithm_name_to_value_internal( - grpc_compression_algorithm *algorithm_value, VALUE algorithm_name) { + grpc_compression_algorithm* algorithm_value, VALUE algorithm_name) { grpc_slice name_slice; VALUE algorithm_name_as_string = Qnil; - char *tmp_str = NULL; + char* tmp_str = NULL; Check_Type(algorithm_name, T_SYMBOL); @@ -186,7 +186,7 @@ void grpc_rb_compression_options_algorithm_name_to_value_internal( * readable algorithm name. */ VALUE grpc_rb_compression_options_is_algorithm_enabled(VALUE self, VALUE algorithm_name) { - grpc_rb_compression_options *wrapper = NULL; + grpc_rb_compression_options* wrapper = NULL; grpc_compression_algorithm internal_algorithm_value; TypedData_Get_Struct(self, grpc_rb_compression_options, @@ -204,7 +204,7 @@ VALUE grpc_rb_compression_options_is_algorithm_enabled(VALUE self, /* Sets the default algorithm to the name of the algorithm passed in. * Raises an error if the name is not a valid compression algorithm name. */ void grpc_rb_compression_options_set_default_algorithm( - grpc_compression_options *options, VALUE algorithm_name) { + grpc_compression_options* options, VALUE algorithm_name) { grpc_rb_compression_options_algorithm_name_to_value_internal( &options->default_algorithm.algorithm, algorithm_name); options->default_algorithm.is_set = 1; @@ -214,7 +214,7 @@ void grpc_rb_compression_options_set_default_algorithm( * algorithm. * Fails if the algorithm name is invalid. */ void grpc_rb_compression_options_disable_algorithm( - grpc_compression_options *compression_options, VALUE algorithm_name) { + grpc_compression_options* compression_options, VALUE algorithm_name) { grpc_compression_algorithm internal_algorithm_value; grpc_rb_compression_options_algorithm_name_to_value_internal( @@ -226,8 +226,8 @@ void grpc_rb_compression_options_disable_algorithm( /* Provides a ruby hash of GRPC core channel argument key-values that * correspond to the compression settings on this instance. */ VALUE grpc_rb_compression_options_to_hash(VALUE self) { - grpc_rb_compression_options *wrapper = NULL; - grpc_compression_options *compression_options = NULL; + grpc_rb_compression_options* wrapper = NULL; + grpc_compression_options* compression_options = NULL; VALUE channel_arg_hash = rb_hash_new(); VALUE key = Qnil; VALUE value = Qnil; @@ -284,7 +284,7 @@ VALUE grpc_rb_compression_options_level_value_to_name_internal( * Fails if the enum value is invalid. */ VALUE grpc_rb_compression_options_algorithm_value_to_name_internal( grpc_compression_algorithm internal_value) { - char *algorithm_name = NULL; + char* algorithm_name = NULL; if (!grpc_compression_algorithm_name(internal_value, &algorithm_name)) { rb_raise(rb_eArgError, "Failed to convert algorithm value to name"); @@ -297,7 +297,7 @@ VALUE grpc_rb_compression_options_algorithm_value_to_name_internal( * Returns nil if no algorithm has been set. */ VALUE grpc_rb_compression_options_get_default_algorithm(VALUE self) { grpc_compression_algorithm internal_value; - grpc_rb_compression_options *wrapper = NULL; + grpc_rb_compression_options* wrapper = NULL; TypedData_Get_Struct(self, grpc_rb_compression_options, &grpc_rb_compression_options_data_type, wrapper); @@ -316,7 +316,7 @@ VALUE grpc_rb_compression_options_get_default_algorithm(VALUE self) { * A nil return value means that it hasn't been set. */ VALUE grpc_rb_compression_options_get_default_level(VALUE self) { grpc_compression_level internal_value; - grpc_rb_compression_options *wrapper = NULL; + grpc_rb_compression_options* wrapper = NULL; TypedData_Get_Struct(self, grpc_rb_compression_options, &grpc_rb_compression_options_data_type, wrapper); @@ -335,7 +335,7 @@ VALUE grpc_rb_compression_options_get_default_level(VALUE self) { VALUE grpc_rb_compression_options_get_disabled_algorithms(VALUE self) { VALUE disabled_algorithms = rb_ary_new(); grpc_compression_algorithm internal_value; - grpc_rb_compression_options *wrapper = NULL; + grpc_rb_compression_options* wrapper = NULL; TypedData_Get_Struct(self, grpc_rb_compression_options, &grpc_rb_compression_options_data_type, wrapper); @@ -363,8 +363,8 @@ VALUE grpc_rb_compression_options_get_disabled_algorithms(VALUE self) { * channel_arg hash = Hash.new[...] * channel_arg_hash_with_compression_options = channel_arg_hash.merge(options) */ -VALUE grpc_rb_compression_options_init(int argc, VALUE *argv, VALUE self) { - grpc_rb_compression_options *wrapper = NULL; +VALUE grpc_rb_compression_options_init(int argc, VALUE* argv, VALUE self) { + grpc_rb_compression_options* wrapper = NULL; VALUE default_algorithm = Qnil; VALUE default_level = Qnil; VALUE disabled_algorithms = Qnil; diff --git a/src/ruby/ext/grpc/rb_event_thread.c b/src/ruby/ext/grpc/rb_event_thread.c index b0bcb6f31e1..281e41c9a88 100644 --- a/src/ruby/ext/grpc/rb_event_thread.c +++ b/src/ruby/ext/grpc/rb_event_thread.c @@ -31,15 +31,15 @@ typedef struct grpc_rb_event { // callback will be called with argument while holding the GVL - void (*callback)(void *); - void *argument; + void (*callback)(void*); + void* argument; - struct grpc_rb_event *next; + struct grpc_rb_event* next; } grpc_rb_event; typedef struct grpc_rb_event_queue { - grpc_rb_event *head; - grpc_rb_event *tail; + grpc_rb_event* head; + grpc_rb_event* tail; gpr_mu mu; gpr_cv cv; @@ -50,8 +50,8 @@ typedef struct grpc_rb_event_queue { static grpc_rb_event_queue event_queue; -void grpc_rb_event_queue_enqueue(void (*callback)(void *), void *argument) { - grpc_rb_event *event = gpr_malloc(sizeof(grpc_rb_event)); +void grpc_rb_event_queue_enqueue(void (*callback)(void*), void* argument) { + grpc_rb_event* event = gpr_malloc(sizeof(grpc_rb_event)); event->callback = callback; event->argument = argument; event->next = NULL; @@ -66,8 +66,8 @@ void grpc_rb_event_queue_enqueue(void (*callback)(void *), void *argument) { gpr_mu_unlock(&event_queue.mu); } -static grpc_rb_event *grpc_rb_event_queue_dequeue() { - grpc_rb_event *event; +static grpc_rb_event* grpc_rb_event_queue_dequeue() { + grpc_rb_event* event; if (event_queue.head == NULL) { event = NULL; } else { @@ -86,8 +86,8 @@ static void grpc_rb_event_queue_destroy() { gpr_cv_destroy(&event_queue.cv); } -static void *grpc_rb_wait_for_event_no_gil(void *param) { - grpc_rb_event *event = NULL; +static void* grpc_rb_wait_for_event_no_gil(void* param) { + grpc_rb_event* event = NULL; (void)param; gpr_mu_lock(&event_queue.mu); while (!event_queue.abort) { @@ -102,7 +102,7 @@ static void *grpc_rb_wait_for_event_no_gil(void *param) { return NULL; } -static void grpc_rb_event_unblocking_func(void *arg) { +static void grpc_rb_event_unblocking_func(void* arg) { (void)arg; gpr_mu_lock(&event_queue.mu); event_queue.abort = true; @@ -113,10 +113,10 @@ static void grpc_rb_event_unblocking_func(void *arg) { /* This is the implementation of the thread that handles auth metadata plugin * events */ static VALUE grpc_rb_event_thread(VALUE arg) { - grpc_rb_event *event; + grpc_rb_event* event; (void)arg; while (true) { - event = (grpc_rb_event *)rb_thread_call_without_gvl( + event = (grpc_rb_event*)rb_thread_call_without_gvl( grpc_rb_wait_for_event_no_gil, NULL, grpc_rb_event_unblocking_func, NULL); if (event == NULL) { diff --git a/src/ruby/ext/grpc/rb_event_thread.h b/src/ruby/ext/grpc/rb_event_thread.h index 5bfecb9a681..fa9c14e1695 100644 --- a/src/ruby/ext/grpc/rb_event_thread.h +++ b/src/ruby/ext/grpc/rb_event_thread.h @@ -18,4 +18,4 @@ void grpc_rb_event_queue_thread_start(); -void grpc_rb_event_queue_enqueue(void (*callback)(void *), void *argument); +void grpc_rb_event_queue_enqueue(void (*callback)(void*), void* argument); diff --git a/src/ruby/ext/grpc/rb_grpc.c b/src/ruby/ext/grpc/rb_grpc.c index b53f09edec4..f065a857db8 100644 --- a/src/ruby/ext/grpc/rb_grpc.c +++ b/src/ruby/ext/grpc/rb_grpc.c @@ -90,9 +90,9 @@ static ID id_tv_nsec; */ gpr_timespec grpc_rb_time_timeval(VALUE time, int interval) { gpr_timespec t; - gpr_timespec *time_const; - const char *tstr = interval ? "time interval" : "time"; - const char *want = " want |