diff --git a/BUILD b/BUILD index 86cbf0c70d0..97ddc56b419 100644 --- a/BUILD +++ b/BUILD @@ -204,6 +204,7 @@ cc_library( "src/core/lib/iomgr/pollset_windows.h", "src/core/lib/iomgr/port.h", "src/core/lib/iomgr/resolve_address.h", + "src/core/lib/iomgr/resource_quota.h", "src/core/lib/iomgr/sockaddr.h", "src/core/lib/iomgr/sockaddr_posix.h", "src/core/lib/iomgr/sockaddr_utils.h", @@ -212,6 +213,7 @@ cc_library( "src/core/lib/iomgr/socket_utils_posix.h", "src/core/lib/iomgr/socket_windows.h", "src/core/lib/iomgr/tcp_client.h", + "src/core/lib/iomgr/tcp_client_posix.h", "src/core/lib/iomgr/tcp_posix.h", "src/core/lib/iomgr/tcp_server.h", "src/core/lib/iomgr/tcp_uv.h", @@ -375,6 +377,7 @@ cc_library( "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_utils_common_posix.c", "src/core/lib/iomgr/socket_utils_linux.c", @@ -625,6 +628,7 @@ cc_library( "src/core/lib/iomgr/pollset_windows.h", "src/core/lib/iomgr/port.h", "src/core/lib/iomgr/resolve_address.h", + "src/core/lib/iomgr/resource_quota.h", "src/core/lib/iomgr/sockaddr.h", "src/core/lib/iomgr/sockaddr_posix.h", "src/core/lib/iomgr/sockaddr_utils.h", @@ -633,6 +637,7 @@ cc_library( "src/core/lib/iomgr/socket_utils_posix.h", "src/core/lib/iomgr/socket_windows.h", "src/core/lib/iomgr/tcp_client.h", + "src/core/lib/iomgr/tcp_client_posix.h", "src/core/lib/iomgr/tcp_posix.h", "src/core/lib/iomgr/tcp_server.h", "src/core/lib/iomgr/tcp_uv.h", @@ -781,6 +786,7 @@ cc_library( "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_utils_common_posix.c", "src/core/lib/iomgr/socket_utils_linux.c", @@ -1001,6 +1007,7 @@ cc_library( "src/core/lib/iomgr/pollset_windows.h", "src/core/lib/iomgr/port.h", "src/core/lib/iomgr/resolve_address.h", + "src/core/lib/iomgr/resource_quota.h", "src/core/lib/iomgr/sockaddr.h", "src/core/lib/iomgr/sockaddr_posix.h", "src/core/lib/iomgr/sockaddr_utils.h", @@ -1009,6 +1016,7 @@ cc_library( "src/core/lib/iomgr/socket_utils_posix.h", "src/core/lib/iomgr/socket_windows.h", "src/core/lib/iomgr/tcp_client.h", + "src/core/lib/iomgr/tcp_client_posix.h", "src/core/lib/iomgr/tcp_posix.h", "src/core/lib/iomgr/tcp_server.h", "src/core/lib/iomgr/tcp_uv.h", @@ -1149,6 +1157,7 @@ cc_library( "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_utils_common_posix.c", "src/core/lib/iomgr/socket_utils_linux.c", @@ -1333,6 +1342,7 @@ cc_library( "src/cpp/common/channel_filter.h", "src/cpp/server/dynamic_thread_pool.h", "src/cpp/server/thread_pool_interface.h", + "src/cpp/thread_manager/thread_manager.h", "src/cpp/client/insecure_credentials.cc", "src/cpp/client/secure_credentials.cc", "src/cpp/common/auth_property_iterator.cc", @@ -1352,6 +1362,7 @@ cc_library( "src/cpp/common/channel_filter.cc", "src/cpp/common/completion_queue_cc.cc", "src/cpp/common/core_codegen.cc", + "src/cpp/common/resource_quota_cc.cc", "src/cpp/common/rpc_method.cc", "src/cpp/server/async_generic_service.cc", "src/cpp/server/create_default_thread_pool.cc", @@ -1361,6 +1372,7 @@ cc_library( "src/cpp/server/server_context.cc", "src/cpp/server/server_credentials.cc", "src/cpp/server/server_posix.cc", + "src/cpp/thread_manager/thread_manager.cc", "src/cpp/util/byte_buffer_cc.cc", "src/cpp/util/slice_cc.cc", "src/cpp/util/status.cc", @@ -1390,12 +1402,7 @@ cc_library( "include/grpc++/impl/server_builder_plugin.h", "include/grpc++/impl/server_initializer.h", "include/grpc++/impl/service_type.h", - "include/grpc++/impl/sync.h", - "include/grpc++/impl/sync_cxx11.h", - "include/grpc++/impl/sync_no_cxx11.h", - "include/grpc++/impl/thd.h", - "include/grpc++/impl/thd_cxx11.h", - "include/grpc++/impl/thd_no_cxx11.h", + "include/grpc++/resource_quota.h", "include/grpc++/security/auth_context.h", "include/grpc++/security/auth_metadata_processor.h", "include/grpc++/security/credentials.h", @@ -1442,9 +1449,6 @@ cc_library( "include/grpc++/impl/codegen/status_helper.h", "include/grpc++/impl/codegen/string_ref.h", "include/grpc++/impl/codegen/stub_options.h", - "include/grpc++/impl/codegen/sync.h", - "include/grpc++/impl/codegen/sync_cxx11.h", - "include/grpc++/impl/codegen/sync_no_cxx11.h", "include/grpc++/impl/codegen/sync_stream.h", "include/grpc++/impl/codegen/time.h", "include/grpc/impl/codegen/byte_buffer_reader.h", @@ -1485,6 +1489,7 @@ cc_library( "src/cpp/common/channel_filter.h", "src/cpp/server/dynamic_thread_pool.h", "src/cpp/server/thread_pool_interface.h", + "src/cpp/thread_manager/thread_manager.h", "src/cpp/client/cronet_credentials.cc", "src/cpp/client/insecure_credentials.cc", "src/cpp/common/insecure_create_auth_context.cc", @@ -1500,6 +1505,7 @@ cc_library( "src/cpp/common/channel_filter.cc", "src/cpp/common/completion_queue_cc.cc", "src/cpp/common/core_codegen.cc", + "src/cpp/common/resource_quota_cc.cc", "src/cpp/common/rpc_method.cc", "src/cpp/server/async_generic_service.cc", "src/cpp/server/create_default_thread_pool.cc", @@ -1509,6 +1515,7 @@ cc_library( "src/cpp/server/server_context.cc", "src/cpp/server/server_credentials.cc", "src/cpp/server/server_posix.cc", + "src/cpp/thread_manager/thread_manager.cc", "src/cpp/util/byte_buffer_cc.cc", "src/cpp/util/slice_cc.cc", "src/cpp/util/status.cc", @@ -1538,12 +1545,7 @@ cc_library( "include/grpc++/impl/server_builder_plugin.h", "include/grpc++/impl/server_initializer.h", "include/grpc++/impl/service_type.h", - "include/grpc++/impl/sync.h", - "include/grpc++/impl/sync_cxx11.h", - "include/grpc++/impl/sync_no_cxx11.h", - "include/grpc++/impl/thd.h", - "include/grpc++/impl/thd_cxx11.h", - "include/grpc++/impl/thd_no_cxx11.h", + "include/grpc++/resource_quota.h", "include/grpc++/security/auth_context.h", "include/grpc++/security/auth_metadata_processor.h", "include/grpc++/security/credentials.h", @@ -1590,9 +1592,6 @@ cc_library( "include/grpc++/impl/codegen/status_helper.h", "include/grpc++/impl/codegen/string_ref.h", "include/grpc++/impl/codegen/stub_options.h", - "include/grpc++/impl/codegen/sync.h", - "include/grpc++/impl/codegen/sync_cxx11.h", - "include/grpc++/impl/codegen/sync_no_cxx11.h", "include/grpc++/impl/codegen/sync_stream.h", "include/grpc++/impl/codegen/time.h", "include/grpc/impl/codegen/byte_buffer_reader.h", @@ -1632,63 +1631,10 @@ cc_library( "src/cpp/ext/proto_server_reflection.h", "src/cpp/ext/proto_server_reflection.cc", "src/cpp/ext/proto_server_reflection_plugin.cc", - "src/cpp/ext/reflection.grpc.pb.cc", - "src/cpp/ext/reflection.pb.cc", + "src/proto/grpc/reflection/v1alpha/reflection.proto", ], hdrs = [ "include/grpc++/ext/proto_server_reflection_plugin.h", - "include/grpc++/ext/reflection.grpc.pb.h", - "include/grpc++/ext/reflection.pb.h", - "include/grpc++/impl/codegen/proto_utils.h", - "include/grpc++/impl/codegen/async_stream.h", - "include/grpc++/impl/codegen/async_unary_call.h", - "include/grpc++/impl/codegen/call.h", - "include/grpc++/impl/codegen/call_hook.h", - "include/grpc++/impl/codegen/channel_interface.h", - "include/grpc++/impl/codegen/client_context.h", - "include/grpc++/impl/codegen/client_unary_call.h", - "include/grpc++/impl/codegen/completion_queue.h", - "include/grpc++/impl/codegen/completion_queue_tag.h", - "include/grpc++/impl/codegen/config.h", - "include/grpc++/impl/codegen/core_codegen_interface.h", - "include/grpc++/impl/codegen/create_auth_context.h", - "include/grpc++/impl/codegen/grpc_library.h", - "include/grpc++/impl/codegen/method_handler_impl.h", - "include/grpc++/impl/codegen/rpc_method.h", - "include/grpc++/impl/codegen/rpc_service_method.h", - "include/grpc++/impl/codegen/security/auth_context.h", - "include/grpc++/impl/codegen/serialization_traits.h", - "include/grpc++/impl/codegen/server_context.h", - "include/grpc++/impl/codegen/server_interface.h", - "include/grpc++/impl/codegen/service_type.h", - "include/grpc++/impl/codegen/status.h", - "include/grpc++/impl/codegen/status_code_enum.h", - "include/grpc++/impl/codegen/status_helper.h", - "include/grpc++/impl/codegen/string_ref.h", - "include/grpc++/impl/codegen/stub_options.h", - "include/grpc++/impl/codegen/sync.h", - "include/grpc++/impl/codegen/sync_cxx11.h", - "include/grpc++/impl/codegen/sync_no_cxx11.h", - "include/grpc++/impl/codegen/sync_stream.h", - "include/grpc++/impl/codegen/time.h", - "include/grpc/impl/codegen/byte_buffer_reader.h", - "include/grpc/impl/codegen/compression_types.h", - "include/grpc/impl/codegen/connectivity_state.h", - "include/grpc/impl/codegen/grpc_types.h", - "include/grpc/impl/codegen/propagation_bits.h", - "include/grpc/impl/codegen/status.h", - "include/grpc/impl/codegen/atm.h", - "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/gpr_types.h", - "include/grpc/impl/codegen/port_platform.h", - "include/grpc/impl/codegen/slice.h", - "include/grpc/impl/codegen/sync.h", - "include/grpc/impl/codegen/sync_generic.h", - "include/grpc/impl/codegen/sync_posix.h", - "include/grpc/impl/codegen/sync_windows.h", - "include/grpc++/impl/codegen/config_protobuf.h", ], includes = [ "include", @@ -1708,6 +1654,7 @@ cc_library( "src/cpp/common/channel_filter.h", "src/cpp/server/dynamic_thread_pool.h", "src/cpp/server/thread_pool_interface.h", + "src/cpp/thread_manager/thread_manager.h", "src/cpp/client/insecure_credentials.cc", "src/cpp/common/insecure_create_auth_context.cc", "src/cpp/server/insecure_server_credentials.cc", @@ -1722,6 +1669,7 @@ cc_library( "src/cpp/common/channel_filter.cc", "src/cpp/common/completion_queue_cc.cc", "src/cpp/common/core_codegen.cc", + "src/cpp/common/resource_quota_cc.cc", "src/cpp/common/rpc_method.cc", "src/cpp/server/async_generic_service.cc", "src/cpp/server/create_default_thread_pool.cc", @@ -1731,6 +1679,7 @@ cc_library( "src/cpp/server/server_context.cc", "src/cpp/server/server_credentials.cc", "src/cpp/server/server_posix.cc", + "src/cpp/thread_manager/thread_manager.cc", "src/cpp/util/byte_buffer_cc.cc", "src/cpp/util/slice_cc.cc", "src/cpp/util/status.cc", @@ -1760,12 +1709,7 @@ cc_library( "include/grpc++/impl/server_builder_plugin.h", "include/grpc++/impl/server_initializer.h", "include/grpc++/impl/service_type.h", - "include/grpc++/impl/sync.h", - "include/grpc++/impl/sync_cxx11.h", - "include/grpc++/impl/sync_no_cxx11.h", - "include/grpc++/impl/thd.h", - "include/grpc++/impl/thd_cxx11.h", - "include/grpc++/impl/thd_no_cxx11.h", + "include/grpc++/resource_quota.h", "include/grpc++/security/auth_context.h", "include/grpc++/security/auth_metadata_processor.h", "include/grpc++/security/credentials.h", @@ -1812,9 +1756,6 @@ cc_library( "include/grpc++/impl/codegen/status_helper.h", "include/grpc++/impl/codegen/string_ref.h", "include/grpc++/impl/codegen/stub_options.h", - "include/grpc++/impl/codegen/sync.h", - "include/grpc++/impl/codegen/sync_cxx11.h", - "include/grpc++/impl/codegen/sync_no_cxx11.h", "include/grpc++/impl/codegen/sync_stream.h", "include/grpc++/impl/codegen/time.h", "include/grpc/impl/codegen/byte_buffer_reader.h", @@ -2073,6 +2014,7 @@ objc_library( "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_utils_common_posix.c", "src/core/lib/iomgr/socket_utils_linux.c", @@ -2302,6 +2244,7 @@ objc_library( "src/core/lib/iomgr/pollset_windows.h", "src/core/lib/iomgr/port.h", "src/core/lib/iomgr/resolve_address.h", + "src/core/lib/iomgr/resource_quota.h", "src/core/lib/iomgr/sockaddr.h", "src/core/lib/iomgr/sockaddr_posix.h", "src/core/lib/iomgr/sockaddr_utils.h", @@ -2310,6 +2253,7 @@ objc_library( "src/core/lib/iomgr/socket_utils_posix.h", "src/core/lib/iomgr/socket_windows.h", "src/core/lib/iomgr/tcp_client.h", + "src/core/lib/iomgr/tcp_client_posix.h", "src/core/lib/iomgr/tcp_posix.h", "src/core/lib/iomgr/tcp_server.h", "src/core/lib/iomgr/tcp_uv.h", diff --git a/CMakeLists.txt b/CMakeLists.txt index af1bb5912a9..4b073b0d684 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -334,6 +334,7 @@ add_library(grpc 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_utils_common_posix.c src/core/lib/iomgr/socket_utils_linux.c @@ -605,6 +606,7 @@ add_library(grpc_cronet 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_utils_common_posix.c src/core/lib/iomgr/socket_utils_linux.c @@ -848,6 +850,7 @@ add_library(grpc_unsecure 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_utils_common_posix.c src/core/lib/iomgr/socket_utils_linux.c @@ -1061,6 +1064,7 @@ add_library(grpc++ src/cpp/common/channel_filter.cc src/cpp/common/completion_queue_cc.cc src/cpp/common/core_codegen.cc + src/cpp/common/resource_quota_cc.cc src/cpp/common/rpc_method.cc src/cpp/server/async_generic_service.cc src/cpp/server/create_default_thread_pool.cc @@ -1070,6 +1074,7 @@ add_library(grpc++ src/cpp/server/server_context.cc src/cpp/server/server_credentials.cc src/cpp/server/server_posix.cc + src/cpp/thread_manager/thread_manager.cc src/cpp/util/byte_buffer_cc.cc src/cpp/util/slice_cc.cc src/cpp/util/status.cc @@ -1116,12 +1121,7 @@ foreach(_hdr include/grpc++/impl/server_builder_plugin.h include/grpc++/impl/server_initializer.h include/grpc++/impl/service_type.h - include/grpc++/impl/sync.h - include/grpc++/impl/sync_cxx11.h - include/grpc++/impl/sync_no_cxx11.h - include/grpc++/impl/thd.h - include/grpc++/impl/thd_cxx11.h - include/grpc++/impl/thd_no_cxx11.h + include/grpc++/resource_quota.h include/grpc++/security/auth_context.h include/grpc++/security/auth_metadata_processor.h include/grpc++/security/credentials.h @@ -1168,9 +1168,6 @@ foreach(_hdr include/grpc++/impl/codegen/status_helper.h include/grpc++/impl/codegen/string_ref.h include/grpc++/impl/codegen/stub_options.h - include/grpc++/impl/codegen/sync.h - include/grpc++/impl/codegen/sync_cxx11.h - include/grpc++/impl/codegen/sync_no_cxx11.h include/grpc++/impl/codegen/sync_stream.h include/grpc++/impl/codegen/time.h include/grpc/impl/codegen/byte_buffer_reader.h @@ -1224,6 +1221,7 @@ add_library(grpc++_cronet src/cpp/common/channel_filter.cc src/cpp/common/completion_queue_cc.cc src/cpp/common/core_codegen.cc + src/cpp/common/resource_quota_cc.cc src/cpp/common/rpc_method.cc src/cpp/server/async_generic_service.cc src/cpp/server/create_default_thread_pool.cc @@ -1233,6 +1231,7 @@ add_library(grpc++_cronet src/cpp/server/server_context.cc src/cpp/server/server_credentials.cc src/cpp/server/server_posix.cc + src/cpp/thread_manager/thread_manager.cc src/cpp/util/byte_buffer_cc.cc src/cpp/util/slice_cc.cc src/cpp/util/status.cc @@ -1279,12 +1278,7 @@ foreach(_hdr include/grpc++/impl/server_builder_plugin.h include/grpc++/impl/server_initializer.h include/grpc++/impl/service_type.h - include/grpc++/impl/sync.h - include/grpc++/impl/sync_cxx11.h - include/grpc++/impl/sync_no_cxx11.h - include/grpc++/impl/thd.h - include/grpc++/impl/thd_cxx11.h - include/grpc++/impl/thd_no_cxx11.h + include/grpc++/resource_quota.h include/grpc++/security/auth_context.h include/grpc++/security/auth_metadata_processor.h include/grpc++/security/credentials.h @@ -1331,9 +1325,6 @@ foreach(_hdr include/grpc++/impl/codegen/status_helper.h include/grpc++/impl/codegen/string_ref.h include/grpc++/impl/codegen/stub_options.h - include/grpc++/impl/codegen/sync.h - include/grpc++/impl/codegen/sync_cxx11.h - include/grpc++/impl/codegen/sync_no_cxx11.h include/grpc++/impl/codegen/sync_stream.h include/grpc++/impl/codegen/time.h include/grpc/impl/codegen/byte_buffer_reader.h @@ -1374,8 +1365,7 @@ endif() add_library(grpc++_reflection src/cpp/ext/proto_server_reflection.cc src/cpp/ext/proto_server_reflection_plugin.cc - src/cpp/ext/reflection.grpc.pb.cc - src/cpp/ext/reflection.pb.cc + src/proto/grpc/reflection/v1alpha/reflection.proto ) target_include_directories(grpc++_reflection @@ -1393,58 +1383,6 @@ target_link_libraries(grpc++_reflection foreach(_hdr include/grpc++/ext/proto_server_reflection_plugin.h - include/grpc++/ext/reflection.grpc.pb.h - include/grpc++/ext/reflection.pb.h - include/grpc++/impl/codegen/proto_utils.h - include/grpc++/impl/codegen/async_stream.h - include/grpc++/impl/codegen/async_unary_call.h - include/grpc++/impl/codegen/call.h - include/grpc++/impl/codegen/call_hook.h - include/grpc++/impl/codegen/channel_interface.h - include/grpc++/impl/codegen/client_context.h - include/grpc++/impl/codegen/client_unary_call.h - include/grpc++/impl/codegen/completion_queue.h - include/grpc++/impl/codegen/completion_queue_tag.h - include/grpc++/impl/codegen/config.h - include/grpc++/impl/codegen/core_codegen_interface.h - include/grpc++/impl/codegen/create_auth_context.h - include/grpc++/impl/codegen/grpc_library.h - include/grpc++/impl/codegen/method_handler_impl.h - include/grpc++/impl/codegen/rpc_method.h - include/grpc++/impl/codegen/rpc_service_method.h - include/grpc++/impl/codegen/security/auth_context.h - include/grpc++/impl/codegen/serialization_traits.h - include/grpc++/impl/codegen/server_context.h - include/grpc++/impl/codegen/server_interface.h - include/grpc++/impl/codegen/service_type.h - include/grpc++/impl/codegen/status.h - include/grpc++/impl/codegen/status_code_enum.h - include/grpc++/impl/codegen/status_helper.h - include/grpc++/impl/codegen/string_ref.h - include/grpc++/impl/codegen/stub_options.h - include/grpc++/impl/codegen/sync.h - include/grpc++/impl/codegen/sync_cxx11.h - include/grpc++/impl/codegen/sync_no_cxx11.h - include/grpc++/impl/codegen/sync_stream.h - include/grpc++/impl/codegen/time.h - include/grpc/impl/codegen/byte_buffer_reader.h - include/grpc/impl/codegen/compression_types.h - include/grpc/impl/codegen/connectivity_state.h - include/grpc/impl/codegen/grpc_types.h - include/grpc/impl/codegen/propagation_bits.h - include/grpc/impl/codegen/status.h - include/grpc/impl/codegen/atm.h - 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/gpr_types.h - include/grpc/impl/codegen/port_platform.h - include/grpc/impl/codegen/slice.h - include/grpc/impl/codegen/sync.h - include/grpc/impl/codegen/sync_generic.h - include/grpc/impl/codegen/sync_posix.h - include/grpc/impl/codegen/sync_windows.h - include/grpc++/impl/codegen/config_protobuf.h ) string(REPLACE "include/" "" _path ${_hdr}) get_filename_component(_path ${_path} PATH) @@ -1478,6 +1416,7 @@ add_library(grpc++_unsecure src/cpp/common/channel_filter.cc src/cpp/common/completion_queue_cc.cc src/cpp/common/core_codegen.cc + src/cpp/common/resource_quota_cc.cc src/cpp/common/rpc_method.cc src/cpp/server/async_generic_service.cc src/cpp/server/create_default_thread_pool.cc @@ -1487,6 +1426,7 @@ add_library(grpc++_unsecure src/cpp/server/server_context.cc src/cpp/server/server_credentials.cc src/cpp/server/server_posix.cc + src/cpp/thread_manager/thread_manager.cc src/cpp/util/byte_buffer_cc.cc src/cpp/util/slice_cc.cc src/cpp/util/status.cc @@ -1533,12 +1473,7 @@ foreach(_hdr include/grpc++/impl/server_builder_plugin.h include/grpc++/impl/server_initializer.h include/grpc++/impl/service_type.h - include/grpc++/impl/sync.h - include/grpc++/impl/sync_cxx11.h - include/grpc++/impl/sync_no_cxx11.h - include/grpc++/impl/thd.h - include/grpc++/impl/thd_cxx11.h - include/grpc++/impl/thd_no_cxx11.h + include/grpc++/resource_quota.h include/grpc++/security/auth_context.h include/grpc++/security/auth_metadata_processor.h include/grpc++/security/credentials.h @@ -1585,9 +1520,6 @@ foreach(_hdr include/grpc++/impl/codegen/status_helper.h include/grpc++/impl/codegen/string_ref.h include/grpc++/impl/codegen/stub_options.h - include/grpc++/impl/codegen/sync.h - include/grpc++/impl/codegen/sync_cxx11.h - include/grpc++/impl/codegen/sync_no_cxx11.h include/grpc++/impl/codegen/sync_stream.h include/grpc++/impl/codegen/time.h include/grpc/impl/codegen/byte_buffer_reader.h diff --git a/Makefile b/Makefile index 89b9f053f87..e312e56b5e6 100644 --- a/Makefile +++ b/Makefile @@ -1008,6 +1008,7 @@ no_server_test: $(BINDIR)/$(CONFIG)/no_server_test percent_decode_fuzzer: $(BINDIR)/$(CONFIG)/percent_decode_fuzzer percent_encode_fuzzer: $(BINDIR)/$(CONFIG)/percent_encode_fuzzer resolve_address_test: $(BINDIR)/$(CONFIG)/resolve_address_test +resource_quota_test: $(BINDIR)/$(CONFIG)/resource_quota_test secure_channel_create_test: $(BINDIR)/$(CONFIG)/secure_channel_create_test secure_endpoint_test: $(BINDIR)/$(CONFIG)/secure_endpoint_test sequential_connectivity_test: $(BINDIR)/$(CONFIG)/sequential_connectivity_test @@ -1075,6 +1076,7 @@ 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 +round_robin_end2end_test: $(BINDIR)/$(CONFIG)/round_robin_end2end_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 @@ -1085,6 +1087,7 @@ shutdown_test: $(BINDIR)/$(CONFIG)/shutdown_test status_test: $(BINDIR)/$(CONFIG)/status_test streaming_throughput_test: $(BINDIR)/$(CONFIG)/streaming_throughput_test stress_test: $(BINDIR)/$(CONFIG)/stress_test +thread_manager_test: $(BINDIR)/$(CONFIG)/thread_manager_test thread_stress_test: $(BINDIR)/$(CONFIG)/thread_stress_test public_headers_must_be_c89: $(BINDIR)/$(CONFIG)/public_headers_must_be_c89 boringssl_aes_test: $(BINDIR)/$(CONFIG)/boringssl_aes_test @@ -1234,9 +1237,9 @@ pc_cxx: $(LIBDIR)/$(CONFIG)/pkgconfig/grpc++.pc pc_cxx_unsecure: $(LIBDIR)/$(CONFIG)/pkgconfig/grpc++_unsecure.pc ifeq ($(EMBED_OPENSSL),true) -privatelibs_cxx: $(LIBDIR)/$(CONFIG)/libgrpc++_reflection_codegen.a $(LIBDIR)/$(CONFIG)/libgrpc++_test.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_config.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libinterop_client_helper.a $(LIBDIR)/$(CONFIG)/libinterop_client_main.a $(LIBDIR)/$(CONFIG)/libinterop_server_helper.a $(LIBDIR)/$(CONFIG)/libinterop_server_lib.a $(LIBDIR)/$(CONFIG)/libinterop_server_main.a $(LIBDIR)/$(CONFIG)/libqps.a $(LIBDIR)/$(CONFIG)/libboringssl_test_util.a $(LIBDIR)/$(CONFIG)/libboringssl_aes_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_asn1_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_base64_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_bio_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_bn_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_bytestring_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_aead_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_cipher_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_cmac_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_ed25519_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_x25519_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_dh_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_digest_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_ec_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_ecdsa_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_err_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_evp_extra_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_evp_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_pbkdf_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_hmac_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_pkcs12_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_pkcs8_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_poly1305_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_rsa_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_x509_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_ssl_test_lib.a +privatelibs_cxx: $(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a $(LIBDIR)/$(CONFIG)/libgrpc++_test.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_config.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libinterop_client_helper.a $(LIBDIR)/$(CONFIG)/libinterop_client_main.a $(LIBDIR)/$(CONFIG)/libinterop_server_helper.a $(LIBDIR)/$(CONFIG)/libinterop_server_lib.a $(LIBDIR)/$(CONFIG)/libinterop_server_main.a $(LIBDIR)/$(CONFIG)/libqps.a $(LIBDIR)/$(CONFIG)/libboringssl_test_util.a $(LIBDIR)/$(CONFIG)/libboringssl_aes_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_asn1_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_base64_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_bio_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_bn_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_bytestring_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_aead_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_cipher_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_cmac_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_ed25519_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_x25519_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_dh_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_digest_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_ec_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_ecdsa_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_err_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_evp_extra_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_evp_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_pbkdf_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_hmac_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_pkcs12_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_pkcs8_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_poly1305_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_rsa_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_x509_test_lib.a $(LIBDIR)/$(CONFIG)/libboringssl_ssl_test_lib.a else -privatelibs_cxx: $(LIBDIR)/$(CONFIG)/libgrpc++_reflection_codegen.a $(LIBDIR)/$(CONFIG)/libgrpc++_test.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_config.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libinterop_client_helper.a $(LIBDIR)/$(CONFIG)/libinterop_client_main.a $(LIBDIR)/$(CONFIG)/libinterop_server_helper.a $(LIBDIR)/$(CONFIG)/libinterop_server_lib.a $(LIBDIR)/$(CONFIG)/libinterop_server_main.a $(LIBDIR)/$(CONFIG)/libqps.a +privatelibs_cxx: $(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a $(LIBDIR)/$(CONFIG)/libgrpc++_test.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_config.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libinterop_client_helper.a $(LIBDIR)/$(CONFIG)/libinterop_client_main.a $(LIBDIR)/$(CONFIG)/libinterop_server_helper.a $(LIBDIR)/$(CONFIG)/libinterop_server_lib.a $(LIBDIR)/$(CONFIG)/libinterop_server_main.a $(LIBDIR)/$(CONFIG)/libqps.a endif @@ -1331,6 +1334,7 @@ buildtests_c: privatelibs_c \ $(BINDIR)/$(CONFIG)/murmur_hash_test \ $(BINDIR)/$(CONFIG)/no_server_test \ $(BINDIR)/$(CONFIG)/resolve_address_test \ + $(BINDIR)/$(CONFIG)/resource_quota_test \ $(BINDIR)/$(CONFIG)/secure_channel_create_test \ $(BINDIR)/$(CONFIG)/secure_endpoint_test \ $(BINDIR)/$(CONFIG)/sequential_connectivity_test \ @@ -1451,6 +1455,7 @@ buildtests_cxx: privatelibs_cxx \ $(BINDIR)/$(CONFIG)/qps_worker \ $(BINDIR)/$(CONFIG)/reconnect_interop_client \ $(BINDIR)/$(CONFIG)/reconnect_interop_server \ + $(BINDIR)/$(CONFIG)/round_robin_end2end_test \ $(BINDIR)/$(CONFIG)/secure_auth_context_test \ $(BINDIR)/$(CONFIG)/secure_sync_unary_ping_pong_test \ $(BINDIR)/$(CONFIG)/server_builder_plugin_test \ @@ -1461,6 +1466,7 @@ buildtests_cxx: privatelibs_cxx \ $(BINDIR)/$(CONFIG)/status_test \ $(BINDIR)/$(CONFIG)/streaming_throughput_test \ $(BINDIR)/$(CONFIG)/stress_test \ + $(BINDIR)/$(CONFIG)/thread_manager_test \ $(BINDIR)/$(CONFIG)/thread_stress_test \ $(BINDIR)/$(CONFIG)/boringssl_aes_test \ $(BINDIR)/$(CONFIG)/boringssl_asn1_test \ @@ -1539,6 +1545,7 @@ buildtests_cxx: privatelibs_cxx \ $(BINDIR)/$(CONFIG)/qps_worker \ $(BINDIR)/$(CONFIG)/reconnect_interop_client \ $(BINDIR)/$(CONFIG)/reconnect_interop_server \ + $(BINDIR)/$(CONFIG)/round_robin_end2end_test \ $(BINDIR)/$(CONFIG)/secure_auth_context_test \ $(BINDIR)/$(CONFIG)/secure_sync_unary_ping_pong_test \ $(BINDIR)/$(CONFIG)/server_builder_plugin_test \ @@ -1549,6 +1556,7 @@ buildtests_cxx: privatelibs_cxx \ $(BINDIR)/$(CONFIG)/status_test \ $(BINDIR)/$(CONFIG)/streaming_throughput_test \ $(BINDIR)/$(CONFIG)/stress_test \ + $(BINDIR)/$(CONFIG)/thread_manager_test \ $(BINDIR)/$(CONFIG)/thread_stress_test \ endif @@ -1717,6 +1725,8 @@ test_c: buildtests_c $(Q) $(BINDIR)/$(CONFIG)/no_server_test || ( echo test no_server_test failed ; exit 1 ) $(E) "[RUN] Testing resolve_address_test" $(Q) $(BINDIR)/$(CONFIG)/resolve_address_test || ( echo test resolve_address_test failed ; exit 1 ) + $(E) "[RUN] Testing resource_quota_test" + $(Q) $(BINDIR)/$(CONFIG)/resource_quota_test || ( echo test resource_quota_test failed ; exit 1 ) $(E) "[RUN] Testing secure_channel_create_test" $(Q) $(BINDIR)/$(CONFIG)/secure_channel_create_test || ( echo test secure_channel_create_test failed ; exit 1 ) $(E) "[RUN] Testing secure_endpoint_test" @@ -1845,6 +1855,8 @@ test_cxx: buildtests_cxx $(Q) $(BINDIR)/$(CONFIG)/proto_server_reflection_test || ( echo test proto_server_reflection_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 round_robin_end2end_test" + $(Q) $(BINDIR)/$(CONFIG)/round_robin_end2end_test || ( echo test round_robin_end2end_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" @@ -1861,6 +1873,8 @@ test_cxx: buildtests_cxx $(Q) $(BINDIR)/$(CONFIG)/status_test || ( echo test status_test failed ; exit 1 ) $(E) "[RUN] Testing streaming_throughput_test" $(Q) $(BINDIR)/$(CONFIG)/streaming_throughput_test || ( echo test streaming_throughput_test failed ; exit 1 ) + $(E) "[RUN] Testing thread_manager_test" + $(Q) $(BINDIR)/$(CONFIG)/thread_manager_test || ( echo test thread_manager_test failed ; exit 1 ) $(E) "[RUN] Testing thread_stress_test" $(Q) $(BINDIR)/$(CONFIG)/thread_stress_test || ( echo test thread_stress_test failed ; exit 1 ) @@ -2619,6 +2633,7 @@ LIBGRPC_SRC = \ 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_utils_common_posix.c \ src/core/lib/iomgr/socket_utils_linux.c \ @@ -2908,6 +2923,7 @@ LIBGRPC_CRONET_SRC = \ 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_utils_common_posix.c \ src/core/lib/iomgr/socket_utils_linux.c \ @@ -3188,6 +3204,7 @@ LIBGRPC_TEST_UTIL_SRC = \ 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_utils_common_posix.c \ src/core/lib/iomgr/socket_utils_linux.c \ @@ -3397,6 +3414,7 @@ LIBGRPC_UNSECURE_SRC = \ 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_utils_common_posix.c \ src/core/lib/iomgr/socket_utils_linux.c \ @@ -3693,6 +3711,7 @@ LIBGRPC++_SRC = \ src/cpp/common/channel_filter.cc \ src/cpp/common/completion_queue_cc.cc \ src/cpp/common/core_codegen.cc \ + src/cpp/common/resource_quota_cc.cc \ src/cpp/common/rpc_method.cc \ src/cpp/server/async_generic_service.cc \ src/cpp/server/create_default_thread_pool.cc \ @@ -3702,6 +3721,7 @@ LIBGRPC++_SRC = \ src/cpp/server/server_context.cc \ src/cpp/server/server_credentials.cc \ src/cpp/server/server_posix.cc \ + src/cpp/thread_manager/thread_manager.cc \ src/cpp/util/byte_buffer_cc.cc \ src/cpp/util/slice_cc.cc \ src/cpp/util/status.cc \ @@ -3731,12 +3751,7 @@ PUBLIC_HEADERS_CXX += \ include/grpc++/impl/server_builder_plugin.h \ include/grpc++/impl/server_initializer.h \ include/grpc++/impl/service_type.h \ - include/grpc++/impl/sync.h \ - include/grpc++/impl/sync_cxx11.h \ - include/grpc++/impl/sync_no_cxx11.h \ - include/grpc++/impl/thd.h \ - include/grpc++/impl/thd_cxx11.h \ - include/grpc++/impl/thd_no_cxx11.h \ + include/grpc++/resource_quota.h \ include/grpc++/security/auth_context.h \ include/grpc++/security/auth_metadata_processor.h \ include/grpc++/security/credentials.h \ @@ -3783,9 +3798,6 @@ PUBLIC_HEADERS_CXX += \ include/grpc++/impl/codegen/status_helper.h \ include/grpc++/impl/codegen/string_ref.h \ include/grpc++/impl/codegen/stub_options.h \ - include/grpc++/impl/codegen/sync.h \ - include/grpc++/impl/codegen/sync_cxx11.h \ - include/grpc++/impl/codegen/sync_no_cxx11.h \ include/grpc++/impl/codegen/sync_stream.h \ include/grpc++/impl/codegen/time.h \ include/grpc/impl/codegen/byte_buffer_reader.h \ @@ -3885,6 +3897,7 @@ LIBGRPC++_CRONET_SRC = \ src/cpp/common/channel_filter.cc \ src/cpp/common/completion_queue_cc.cc \ src/cpp/common/core_codegen.cc \ + src/cpp/common/resource_quota_cc.cc \ src/cpp/common/rpc_method.cc \ src/cpp/server/async_generic_service.cc \ src/cpp/server/create_default_thread_pool.cc \ @@ -3894,6 +3907,7 @@ LIBGRPC++_CRONET_SRC = \ src/cpp/server/server_context.cc \ src/cpp/server/server_credentials.cc \ src/cpp/server/server_posix.cc \ + src/cpp/thread_manager/thread_manager.cc \ src/cpp/util/byte_buffer_cc.cc \ src/cpp/util/slice_cc.cc \ src/cpp/util/status.cc \ @@ -3923,12 +3937,7 @@ PUBLIC_HEADERS_CXX += \ include/grpc++/impl/server_builder_plugin.h \ include/grpc++/impl/server_initializer.h \ include/grpc++/impl/service_type.h \ - include/grpc++/impl/sync.h \ - include/grpc++/impl/sync_cxx11.h \ - include/grpc++/impl/sync_no_cxx11.h \ - include/grpc++/impl/thd.h \ - include/grpc++/impl/thd_cxx11.h \ - include/grpc++/impl/thd_no_cxx11.h \ + include/grpc++/resource_quota.h \ include/grpc++/security/auth_context.h \ include/grpc++/security/auth_metadata_processor.h \ include/grpc++/security/credentials.h \ @@ -3975,9 +3984,6 @@ PUBLIC_HEADERS_CXX += \ include/grpc++/impl/codegen/status_helper.h \ include/grpc++/impl/codegen/string_ref.h \ include/grpc++/impl/codegen/stub_options.h \ - include/grpc++/impl/codegen/sync.h \ - include/grpc++/impl/codegen/sync_cxx11.h \ - include/grpc++/impl/codegen/sync_no_cxx11.h \ include/grpc++/impl/codegen/sync_stream.h \ include/grpc++/impl/codegen/time.h \ include/grpc/impl/codegen/byte_buffer_reader.h \ @@ -4061,77 +4067,22 @@ endif endif -LIBGRPC++_REFLECTION_SRC = \ - src/cpp/ext/proto_server_reflection.cc \ - src/cpp/ext/proto_server_reflection_plugin.cc \ - src/cpp/ext/reflection.grpc.pb.cc \ - src/cpp/ext/reflection.pb.cc \ +LIBGRPC++_PROTO_REFLECTION_DESC_DB_SRC = \ + test/cpp/util/proto_reflection_descriptor_database.cc \ + $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.pb.cc $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.cc \ PUBLIC_HEADERS_CXX += \ - include/grpc++/ext/proto_server_reflection_plugin.h \ - include/grpc++/ext/reflection.grpc.pb.h \ - include/grpc++/ext/reflection.pb.h \ - include/grpc++/impl/codegen/proto_utils.h \ - include/grpc++/impl/codegen/async_stream.h \ - include/grpc++/impl/codegen/async_unary_call.h \ - include/grpc++/impl/codegen/call.h \ - include/grpc++/impl/codegen/call_hook.h \ - include/grpc++/impl/codegen/channel_interface.h \ - include/grpc++/impl/codegen/client_context.h \ - include/grpc++/impl/codegen/client_unary_call.h \ - include/grpc++/impl/codegen/completion_queue.h \ - include/grpc++/impl/codegen/completion_queue_tag.h \ - include/grpc++/impl/codegen/config.h \ - include/grpc++/impl/codegen/core_codegen_interface.h \ - include/grpc++/impl/codegen/create_auth_context.h \ - include/grpc++/impl/codegen/grpc_library.h \ - include/grpc++/impl/codegen/method_handler_impl.h \ - include/grpc++/impl/codegen/rpc_method.h \ - include/grpc++/impl/codegen/rpc_service_method.h \ - include/grpc++/impl/codegen/security/auth_context.h \ - include/grpc++/impl/codegen/serialization_traits.h \ - include/grpc++/impl/codegen/server_context.h \ - include/grpc++/impl/codegen/server_interface.h \ - include/grpc++/impl/codegen/service_type.h \ - include/grpc++/impl/codegen/status.h \ - include/grpc++/impl/codegen/status_code_enum.h \ - include/grpc++/impl/codegen/status_helper.h \ - include/grpc++/impl/codegen/string_ref.h \ - include/grpc++/impl/codegen/stub_options.h \ - include/grpc++/impl/codegen/sync.h \ - include/grpc++/impl/codegen/sync_cxx11.h \ - include/grpc++/impl/codegen/sync_no_cxx11.h \ - include/grpc++/impl/codegen/sync_stream.h \ - include/grpc++/impl/codegen/time.h \ - include/grpc/impl/codegen/byte_buffer_reader.h \ - include/grpc/impl/codegen/compression_types.h \ - include/grpc/impl/codegen/connectivity_state.h \ - include/grpc/impl/codegen/grpc_types.h \ - include/grpc/impl/codegen/propagation_bits.h \ - include/grpc/impl/codegen/status.h \ - include/grpc/impl/codegen/atm.h \ - 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/gpr_types.h \ - include/grpc/impl/codegen/port_platform.h \ - include/grpc/impl/codegen/slice.h \ - include/grpc/impl/codegen/sync.h \ - include/grpc/impl/codegen/sync_generic.h \ - include/grpc/impl/codegen/sync_posix.h \ - include/grpc/impl/codegen/sync_windows.h \ include/grpc++/impl/codegen/config_protobuf.h \ -LIBGRPC++_REFLECTION_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(LIBGRPC++_REFLECTION_SRC)))) +LIBGRPC++_PROTO_REFLECTION_DESC_DB_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(LIBGRPC++_PROTO_REFLECTION_DESC_DB_SRC)))) ifeq ($(NO_SECURE),true) # You can't build secure libraries if you don't have OpenSSL. -$(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a: openssl_dep_error +$(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a: openssl_dep_error -$(LIBDIR)/$(CONFIG)/$(SHARED_PREFIX)grpc++_reflection$(SHARED_VERSION).$(SHARED_EXT): openssl_dep_error else @@ -4139,40 +4090,22 @@ ifeq ($(NO_PROTOBUF),true) # You can't build a C++ library if you don't have protobuf - a bit overreached, but still okay. -$(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a: protobuf_dep_error +$(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a: protobuf_dep_error -$(LIBDIR)/$(CONFIG)/$(SHARED_PREFIX)grpc++_reflection$(SHARED_VERSION).$(SHARED_EXT): protobuf_dep_error else -$(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a: $(ZLIB_DEP) $(OPENSSL_DEP) $(PROTOBUF_DEP) $(LIBGRPC++_REFLECTION_OBJS) +$(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a: $(ZLIB_DEP) $(OPENSSL_DEP) $(PROTOBUF_DEP) $(LIBGRPC++_PROTO_REFLECTION_DESC_DB_OBJS) $(E) "[AR] Creating $@" $(Q) mkdir -p `dirname $@` - $(Q) rm -f $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a - $(Q) $(AR) $(AROPTS) $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(LIBGRPC++_REFLECTION_OBJS) + $(Q) rm -f $(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a + $(Q) $(AR) $(AROPTS) $(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a $(LIBGRPC++_PROTO_REFLECTION_DESC_DB_OBJS) ifeq ($(SYSTEM),Darwin) - $(Q) ranlib -no_warning_for_no_symbols $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a + $(Q) ranlib -no_warning_for_no_symbols $(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a endif -ifeq ($(SYSTEM),MINGW32) -$(LIBDIR)/$(CONFIG)/grpc++_reflection$(SHARED_VERSION).$(SHARED_EXT): $(LIBGRPC++_REFLECTION_OBJS) $(ZLIB_DEP) $(PROTOBUF_DEP) $(LIBDIR)/$(CONFIG)/grpc++.$(SHARED_EXT) $(OPENSSL_DEP) - $(E) "[LD] Linking $@" - $(Q) mkdir -p `dirname $@` - $(Q) $(LDXX) $(LDFLAGS) -L$(LIBDIR)/$(CONFIG) -shared grpc++_reflection.def -Wl,--output-def=$(LIBDIR)/$(CONFIG)/grpc++_reflection$(SHARED_VERSION).def -Wl,--out-implib=$(LIBDIR)/$(CONFIG)/libgrpc++_reflection$(SHARED_VERSION)-dll.a -o $(LIBDIR)/$(CONFIG)/grpc++_reflection$(SHARED_VERSION).$(SHARED_EXT) $(LIBGRPC++_REFLECTION_OBJS) $(LDLIBS) $(ZLIB_MERGE_LIBS) $(LDLIBSXX) $(LDLIBS_PROTOBUF) -lgrpc++-imp -else -$(LIBDIR)/$(CONFIG)/libgrpc++_reflection$(SHARED_VERSION).$(SHARED_EXT): $(LIBGRPC++_REFLECTION_OBJS) $(ZLIB_DEP) $(PROTOBUF_DEP) $(LIBDIR)/$(CONFIG)/libgrpc++.$(SHARED_EXT) $(OPENSSL_DEP) - $(E) "[LD] Linking $@" - $(Q) mkdir -p `dirname $@` -ifeq ($(SYSTEM),Darwin) - $(Q) $(LDXX) $(LDFLAGS) -L$(LIBDIR)/$(CONFIG) -install_name $(SHARED_PREFIX)grpc++_reflection$(SHARED_VERSION).$(SHARED_EXT) -dynamiclib -o $(LIBDIR)/$(CONFIG)/libgrpc++_reflection$(SHARED_VERSION).$(SHARED_EXT) $(LIBGRPC++_REFLECTION_OBJS) $(LDLIBS) $(ZLIB_MERGE_LIBS) $(LDLIBSXX) $(LDLIBS_PROTOBUF) -lgrpc++ -else - $(Q) $(LDXX) $(LDFLAGS) -L$(LIBDIR)/$(CONFIG) -shared -Wl,-soname,libgrpc++_reflection.so.1 -o $(LIBDIR)/$(CONFIG)/libgrpc++_reflection$(SHARED_VERSION).$(SHARED_EXT) $(LIBGRPC++_REFLECTION_OBJS) $(LDLIBS) $(ZLIB_MERGE_LIBS) $(LDLIBSXX) $(LDLIBS_PROTOBUF) -lgrpc++ - $(Q) ln -sf $(SHARED_PREFIX)grpc++_reflection$(SHARED_VERSION).$(SHARED_EXT) $(LIBDIR)/$(CONFIG)/libgrpc++_reflection$(SHARED_VERSION).so.1 - $(Q) ln -sf $(SHARED_PREFIX)grpc++_reflection$(SHARED_VERSION).$(SHARED_EXT) $(LIBDIR)/$(CONFIG)/libgrpc++_reflection$(SHARED_VERSION).so -endif -endif endif @@ -4180,25 +4113,30 @@ endif ifneq ($(NO_SECURE),true) ifneq ($(NO_DEPS),true) --include $(LIBGRPC++_REFLECTION_OBJS:.o=.dep) +-include $(LIBGRPC++_PROTO_REFLECTION_DESC_DB_OBJS:.o=.dep) endif endif +$(OBJDIR)/$(CONFIG)/test/cpp/util/proto_reflection_descriptor_database.o: $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.pb.cc $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.cc -LIBGRPC++_REFLECTION_CODEGEN_SRC = \ +LIBGRPC++_REFLECTION_SRC = \ + src/cpp/ext/proto_server_reflection.cc \ + src/cpp/ext/proto_server_reflection_plugin.cc \ $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.pb.cc $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.cc \ PUBLIC_HEADERS_CXX += \ + include/grpc++/ext/proto_server_reflection_plugin.h \ -LIBGRPC++_REFLECTION_CODEGEN_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(LIBGRPC++_REFLECTION_CODEGEN_SRC)))) +LIBGRPC++_REFLECTION_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(LIBGRPC++_REFLECTION_SRC)))) ifeq ($(NO_SECURE),true) # You can't build secure libraries if you don't have OpenSSL. -$(LIBDIR)/$(CONFIG)/libgrpc++_reflection_codegen.a: openssl_dep_error +$(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a: openssl_dep_error +$(LIBDIR)/$(CONFIG)/$(SHARED_PREFIX)grpc++_reflection$(SHARED_VERSION).$(SHARED_EXT): openssl_dep_error else @@ -4206,22 +4144,40 @@ ifeq ($(NO_PROTOBUF),true) # You can't build a C++ library if you don't have protobuf - a bit overreached, but still okay. -$(LIBDIR)/$(CONFIG)/libgrpc++_reflection_codegen.a: protobuf_dep_error +$(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a: protobuf_dep_error +$(LIBDIR)/$(CONFIG)/$(SHARED_PREFIX)grpc++_reflection$(SHARED_VERSION).$(SHARED_EXT): protobuf_dep_error else -$(LIBDIR)/$(CONFIG)/libgrpc++_reflection_codegen.a: $(ZLIB_DEP) $(OPENSSL_DEP) $(PROTOBUF_DEP) $(LIBGRPC++_REFLECTION_CODEGEN_OBJS) +$(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a: $(ZLIB_DEP) $(OPENSSL_DEP) $(PROTOBUF_DEP) $(LIBGRPC++_REFLECTION_OBJS) $(E) "[AR] Creating $@" $(Q) mkdir -p `dirname $@` - $(Q) rm -f $(LIBDIR)/$(CONFIG)/libgrpc++_reflection_codegen.a - $(Q) $(AR) $(AROPTS) $(LIBDIR)/$(CONFIG)/libgrpc++_reflection_codegen.a $(LIBGRPC++_REFLECTION_CODEGEN_OBJS) + $(Q) rm -f $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a + $(Q) $(AR) $(AROPTS) $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(LIBGRPC++_REFLECTION_OBJS) ifeq ($(SYSTEM),Darwin) - $(Q) ranlib -no_warning_for_no_symbols $(LIBDIR)/$(CONFIG)/libgrpc++_reflection_codegen.a + $(Q) ranlib -no_warning_for_no_symbols $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a endif +ifeq ($(SYSTEM),MINGW32) +$(LIBDIR)/$(CONFIG)/grpc++_reflection$(SHARED_VERSION).$(SHARED_EXT): $(LIBGRPC++_REFLECTION_OBJS) $(ZLIB_DEP) $(PROTOBUF_DEP) $(LIBDIR)/$(CONFIG)/grpc++.$(SHARED_EXT) $(OPENSSL_DEP) + $(E) "[LD] Linking $@" + $(Q) mkdir -p `dirname $@` + $(Q) $(LDXX) $(LDFLAGS) -L$(LIBDIR)/$(CONFIG) -shared grpc++_reflection.def -Wl,--output-def=$(LIBDIR)/$(CONFIG)/grpc++_reflection$(SHARED_VERSION).def -Wl,--out-implib=$(LIBDIR)/$(CONFIG)/libgrpc++_reflection$(SHARED_VERSION)-dll.a -o $(LIBDIR)/$(CONFIG)/grpc++_reflection$(SHARED_VERSION).$(SHARED_EXT) $(LIBGRPC++_REFLECTION_OBJS) $(LDLIBS) $(ZLIB_MERGE_LIBS) $(LDLIBSXX) $(LDLIBS_PROTOBUF) -lgrpc++-imp +else +$(LIBDIR)/$(CONFIG)/libgrpc++_reflection$(SHARED_VERSION).$(SHARED_EXT): $(LIBGRPC++_REFLECTION_OBJS) $(ZLIB_DEP) $(PROTOBUF_DEP) $(LIBDIR)/$(CONFIG)/libgrpc++.$(SHARED_EXT) $(OPENSSL_DEP) + $(E) "[LD] Linking $@" + $(Q) mkdir -p `dirname $@` +ifeq ($(SYSTEM),Darwin) + $(Q) $(LDXX) $(LDFLAGS) -L$(LIBDIR)/$(CONFIG) -install_name $(SHARED_PREFIX)grpc++_reflection$(SHARED_VERSION).$(SHARED_EXT) -dynamiclib -o $(LIBDIR)/$(CONFIG)/libgrpc++_reflection$(SHARED_VERSION).$(SHARED_EXT) $(LIBGRPC++_REFLECTION_OBJS) $(LDLIBS) $(ZLIB_MERGE_LIBS) $(LDLIBSXX) $(LDLIBS_PROTOBUF) -lgrpc++ +else + $(Q) $(LDXX) $(LDFLAGS) -L$(LIBDIR)/$(CONFIG) -shared -Wl,-soname,libgrpc++_reflection.so.1 -o $(LIBDIR)/$(CONFIG)/libgrpc++_reflection$(SHARED_VERSION).$(SHARED_EXT) $(LIBGRPC++_REFLECTION_OBJS) $(LDLIBS) $(ZLIB_MERGE_LIBS) $(LDLIBSXX) $(LDLIBS_PROTOBUF) -lgrpc++ + $(Q) ln -sf $(SHARED_PREFIX)grpc++_reflection$(SHARED_VERSION).$(SHARED_EXT) $(LIBDIR)/$(CONFIG)/libgrpc++_reflection$(SHARED_VERSION).so.1 + $(Q) ln -sf $(SHARED_PREFIX)grpc++_reflection$(SHARED_VERSION).$(SHARED_EXT) $(LIBDIR)/$(CONFIG)/libgrpc++_reflection$(SHARED_VERSION).so +endif +endif endif @@ -4229,9 +4185,11 @@ endif ifneq ($(NO_SECURE),true) ifneq ($(NO_DEPS),true) --include $(LIBGRPC++_REFLECTION_CODEGEN_OBJS:.o=.dep) +-include $(LIBGRPC++_REFLECTION_OBJS:.o=.dep) endif endif +$(OBJDIR)/$(CONFIG)/src/cpp/ext/proto_server_reflection.o: $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.pb.cc $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.cc +$(OBJDIR)/$(CONFIG)/src/cpp/ext/proto_server_reflection_plugin.o: $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.pb.cc $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.cc LIBGRPC++_TEST_SRC = \ @@ -4371,9 +4329,6 @@ PUBLIC_HEADERS_CXX += \ include/grpc++/impl/codegen/status_helper.h \ include/grpc++/impl/codegen/string_ref.h \ include/grpc++/impl/codegen/stub_options.h \ - include/grpc++/impl/codegen/sync.h \ - include/grpc++/impl/codegen/sync_cxx11.h \ - include/grpc++/impl/codegen/sync_no_cxx11.h \ include/grpc++/impl/codegen/sync_stream.h \ include/grpc++/impl/codegen/time.h \ include/grpc/impl/codegen/byte_buffer_reader.h \ @@ -4464,6 +4419,7 @@ LIBGRPC++_UNSECURE_SRC = \ src/cpp/common/channel_filter.cc \ src/cpp/common/completion_queue_cc.cc \ src/cpp/common/core_codegen.cc \ + src/cpp/common/resource_quota_cc.cc \ src/cpp/common/rpc_method.cc \ src/cpp/server/async_generic_service.cc \ src/cpp/server/create_default_thread_pool.cc \ @@ -4473,6 +4429,7 @@ LIBGRPC++_UNSECURE_SRC = \ src/cpp/server/server_context.cc \ src/cpp/server/server_credentials.cc \ src/cpp/server/server_posix.cc \ + src/cpp/thread_manager/thread_manager.cc \ src/cpp/util/byte_buffer_cc.cc \ src/cpp/util/slice_cc.cc \ src/cpp/util/status.cc \ @@ -4502,12 +4459,7 @@ PUBLIC_HEADERS_CXX += \ include/grpc++/impl/server_builder_plugin.h \ include/grpc++/impl/server_initializer.h \ include/grpc++/impl/service_type.h \ - include/grpc++/impl/sync.h \ - include/grpc++/impl/sync_cxx11.h \ - include/grpc++/impl/sync_no_cxx11.h \ - include/grpc++/impl/thd.h \ - include/grpc++/impl/thd_cxx11.h \ - include/grpc++/impl/thd_no_cxx11.h \ + include/grpc++/resource_quota.h \ include/grpc++/security/auth_context.h \ include/grpc++/security/auth_metadata_processor.h \ include/grpc++/security/credentials.h \ @@ -4554,9 +4506,6 @@ PUBLIC_HEADERS_CXX += \ include/grpc++/impl/codegen/status_helper.h \ include/grpc++/impl/codegen/string_ref.h \ include/grpc++/impl/codegen/stub_options.h \ - include/grpc++/impl/codegen/sync.h \ - include/grpc++/impl/codegen/sync_cxx11.h \ - include/grpc++/impl/codegen/sync_no_cxx11.h \ include/grpc++/impl/codegen/sync_stream.h \ include/grpc++/impl/codegen/time.h \ include/grpc/impl/codegen/byte_buffer_reader.h \ @@ -4631,10 +4580,11 @@ LIBGRPC_CLI_LIBS_SRC = \ test/cpp/util/cli_credentials.cc \ test/cpp/util/grpc_tool.cc \ test/cpp/util/proto_file_parser.cc \ - test/cpp/util/proto_reflection_descriptor_database.cc \ test/cpp/util/service_describer.cc \ + $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.pb.cc $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.cc \ PUBLIC_HEADERS_CXX += \ + include/grpc++/impl/codegen/config_protobuf.h \ LIBGRPC_CLI_LIBS_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(LIBGRPC_CLI_LIBS_SRC)))) @@ -4678,6 +4628,11 @@ ifneq ($(NO_DEPS),true) -include $(LIBGRPC_CLI_LIBS_OBJS:.o=.dep) endif endif +$(OBJDIR)/$(CONFIG)/test/cpp/util/cli_call.o: $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.pb.cc $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.cc +$(OBJDIR)/$(CONFIG)/test/cpp/util/cli_credentials.o: $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.pb.cc $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.cc +$(OBJDIR)/$(CONFIG)/test/cpp/util/grpc_tool.o: $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.pb.cc $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.cc +$(OBJDIR)/$(CONFIG)/test/cpp/util/proto_file_parser.o: $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.pb.cc $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.cc +$(OBJDIR)/$(CONFIG)/test/cpp/util/service_describer.o: $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.pb.cc $(GENDIR)/src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.cc LIBGRPC_PLUGIN_SUPPORT_SRC = \ @@ -6942,6 +6897,7 @@ LIBEND2END_TESTS_SRC = \ 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 \ @@ -7024,6 +6980,7 @@ LIBEND2END_NOSEC_TESTS_SRC = \ 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 \ @@ -10420,6 +10377,38 @@ endif endif +RESOURCE_QUOTA_TEST_SRC = \ + test/core/iomgr/resource_quota_test.c \ + +RESOURCE_QUOTA_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(RESOURCE_QUOTA_TEST_SRC)))) +ifeq ($(NO_SECURE),true) + +# You can't build secure targets if you don't have OpenSSL. + +$(BINDIR)/$(CONFIG)/resource_quota_test: openssl_dep_error + +else + + + +$(BINDIR)/$(CONFIG)/resource_quota_test: $(RESOURCE_QUOTA_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) $(LD) $(LDFLAGS) $(RESOURCE_QUOTA_TEST_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)/resource_quota_test + +endif + +$(OBJDIR)/$(CONFIG)/test/core/iomgr/resource_quota_test.o: $(LIBDIR)/$(CONFIG)/libgrpc_test_util.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr_test_util.a $(LIBDIR)/$(CONFIG)/libgpr.a + +deps_resource_quota_test: $(RESOURCE_QUOTA_TEST_OBJS:.o=.dep) + +ifneq ($(NO_SECURE),true) +ifneq ($(NO_DEPS),true) +-include $(RESOURCE_QUOTA_TEST_OBJS:.o=.dep) +endif +endif + + SECURE_CHANNEL_CREATE_TEST_SRC = \ test/core/surface/secure_channel_create_test.c \ @@ -12025,16 +12014,16 @@ $(BINDIR)/$(CONFIG)/grpc_cli: protobuf_dep_error else -$(BINDIR)/$(CONFIG)/grpc_cli: $(PROTOBUF_DEP) $(GRPC_CLI_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_config.a +$(BINDIR)/$(CONFIG)/grpc_cli: $(PROTOBUF_DEP) $(GRPC_CLI_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_config.a $(E) "[LD] Linking $@" $(Q) mkdir -p `dirname $@` - $(Q) $(LDXX) $(LDFLAGS) $(GRPC_CLI_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_config.a $(LDLIBSXX) $(LDLIBS_PROTOBUF) $(LDLIBS) $(LDLIBS_SECURE) $(GTEST_LIB) -o $(BINDIR)/$(CONFIG)/grpc_cli + $(Q) $(LDXX) $(LDFLAGS) $(GRPC_CLI_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_config.a $(LDLIBSXX) $(LDLIBS_PROTOBUF) $(LDLIBS) $(LDLIBS_SECURE) $(GTEST_LIB) -o $(BINDIR)/$(CONFIG)/grpc_cli endif endif -$(OBJDIR)/$(CONFIG)/test/cpp/util/grpc_cli.o: $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_config.a +$(OBJDIR)/$(CONFIG)/test/cpp/util/grpc_cli.o: $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_config.a deps_grpc_cli: $(GRPC_CLI_OBJS:.o=.dep) @@ -12266,7 +12255,6 @@ GRPC_TOOL_TEST_SRC = \ $(GENDIR)/src/proto/grpc/testing/echo.pb.cc $(GENDIR)/src/proto/grpc/testing/echo.grpc.pb.cc \ $(GENDIR)/src/proto/grpc/testing/echo_messages.pb.cc $(GENDIR)/src/proto/grpc/testing/echo_messages.grpc.pb.cc \ test/cpp/util/grpc_tool_test.cc \ - test/cpp/util/string_ref_helper.cc \ GRPC_TOOL_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(GRPC_TOOL_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12288,22 +12276,20 @@ $(BINDIR)/$(CONFIG)/grpc_tool_test: protobuf_dep_error else -$(BINDIR)/$(CONFIG)/grpc_tool_test: $(PROTOBUF_DEP) $(GRPC_TOOL_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.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 +$(BINDIR)/$(CONFIG)/grpc_tool_test: $(PROTOBUF_DEP) $(GRPC_TOOL_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(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) $(GRPC_TOOL_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.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)/grpc_tool_test + $(Q) $(LDXX) $(LDFLAGS) $(GRPC_TOOL_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(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)/grpc_tool_test endif endif -$(OBJDIR)/$(CONFIG)/src/proto/grpc/testing/echo.o: $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.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)/src/proto/grpc/testing/echo_messages.o: $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.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)/src/proto/grpc/testing/echo.o: $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(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/util/grpc_tool_test.o: $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.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)/src/proto/grpc/testing/echo_messages.o: $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(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/util/string_ref_helper.o: $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.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/util/grpc_tool_test.o: $(LIBDIR)/$(CONFIG)/libgrpc_cli_libs.a $(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(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_grpc_tool_test: $(GRPC_TOOL_TEST_OBJS:.o=.dep) @@ -12313,7 +12299,6 @@ ifneq ($(NO_DEPS),true) endif endif $(OBJDIR)/$(CONFIG)/test/cpp/util/grpc_tool_test.o: $(GENDIR)/src/proto/grpc/testing/echo.pb.cc $(GENDIR)/src/proto/grpc/testing/echo.grpc.pb.cc $(GENDIR)/src/proto/grpc/testing/echo_messages.pb.cc $(GENDIR)/src/proto/grpc/testing/echo_messages.grpc.pb.cc -$(OBJDIR)/$(CONFIG)/test/cpp/util/string_ref_helper.o: $(GENDIR)/src/proto/grpc/testing/echo.pb.cc $(GENDIR)/src/proto/grpc/testing/echo.grpc.pb.cc $(GENDIR)/src/proto/grpc/testing/echo_messages.pb.cc $(GENDIR)/src/proto/grpc/testing/echo_messages.grpc.pb.cc GRPCLB_API_TEST_SRC = \ @@ -12693,7 +12678,6 @@ endif PROTO_SERVER_REFLECTION_TEST_SRC = \ test/cpp/end2end/proto_server_reflection_test.cc \ - test/cpp/util/proto_reflection_descriptor_database.cc \ PROTO_SERVER_REFLECTION_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(PROTO_SERVER_REFLECTION_TEST_SRC)))) ifeq ($(NO_SECURE),true) @@ -12715,18 +12699,16 @@ $(BINDIR)/$(CONFIG)/proto_server_reflection_test: protobuf_dep_error else -$(BINDIR)/$(CONFIG)/proto_server_reflection_test: $(PROTOBUF_DEP) $(PROTO_SERVER_REFLECTION_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(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 +$(BINDIR)/$(CONFIG)/proto_server_reflection_test: $(PROTOBUF_DEP) $(PROTO_SERVER_REFLECTION_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(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) $(PROTO_SERVER_REFLECTION_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(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)/proto_server_reflection_test + $(Q) $(LDXX) $(LDFLAGS) $(PROTO_SERVER_REFLECTION_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(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)/proto_server_reflection_test endif endif -$(OBJDIR)/$(CONFIG)/test/cpp/end2end/proto_server_reflection_test.o: $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(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/util/proto_reflection_descriptor_database.o: $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(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/end2end/proto_server_reflection_test.o: $(LIBDIR)/$(CONFIG)/libgrpc++_proto_reflection_desc_db.a $(LIBDIR)/$(CONFIG)/libgrpc++_reflection.a $(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_proto_server_reflection_test: $(PROTO_SERVER_REFLECTION_TEST_OBJS:.o=.dep) @@ -13015,6 +12997,49 @@ 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 +ROUND_ROBIN_END2END_TEST_SRC = \ + test/cpp/end2end/round_robin_end2end_test.cc \ + +ROUND_ROBIN_END2END_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(ROUND_ROBIN_END2END_TEST_SRC)))) +ifeq ($(NO_SECURE),true) + +# You can't build secure targets if you don't have OpenSSL. + +$(BINDIR)/$(CONFIG)/round_robin_end2end_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)/round_robin_end2end_test: protobuf_dep_error + +else + +$(BINDIR)/$(CONFIG)/round_robin_end2end_test: $(PROTOBUF_DEP) $(ROUND_ROBIN_END2END_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) $(ROUND_ROBIN_END2END_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)/round_robin_end2end_test + +endif + +endif + +$(OBJDIR)/$(CONFIG)/test/cpp/end2end/round_robin_end2end_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_round_robin_end2end_test: $(ROUND_ROBIN_END2END_TEST_OBJS:.o=.dep) + +ifneq ($(NO_SECURE),true) +ifneq ($(NO_DEPS),true) +-include $(ROUND_ROBIN_END2END_TEST_OBJS:.o=.dep) +endif +endif + + SECURE_AUTH_CONTEXT_TEST_SRC = \ test/cpp/common/secure_auth_context_test.cc \ @@ -13474,6 +13499,49 @@ $(OBJDIR)/$(CONFIG)/test/cpp/interop/stress_test.o: $(GENDIR)/src/proto/grpc/tes $(OBJDIR)/$(CONFIG)/test/cpp/util/metrics_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/metrics.pb.cc $(GENDIR)/src/proto/grpc/testing/metrics.grpc.pb.cc $(GENDIR)/src/proto/grpc/testing/test.pb.cc $(GENDIR)/src/proto/grpc/testing/test.grpc.pb.cc +THREAD_MANAGER_TEST_SRC = \ + test/cpp/thread_manager/thread_manager_test.cc \ + +THREAD_MANAGER_TEST_OBJS = $(addprefix $(OBJDIR)/$(CONFIG)/, $(addsuffix .o, $(basename $(THREAD_MANAGER_TEST_SRC)))) +ifeq ($(NO_SECURE),true) + +# You can't build secure targets if you don't have OpenSSL. + +$(BINDIR)/$(CONFIG)/thread_manager_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)/thread_manager_test: protobuf_dep_error + +else + +$(BINDIR)/$(CONFIG)/thread_manager_test: $(PROTOBUF_DEP) $(THREAD_MANAGER_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_config.a + $(E) "[LD] Linking $@" + $(Q) mkdir -p `dirname $@` + $(Q) $(LDXX) $(LDFLAGS) $(THREAD_MANAGER_TEST_OBJS) $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_config.a $(LDLIBSXX) $(LDLIBS_PROTOBUF) $(LDLIBS) $(LDLIBS_SECURE) $(GTEST_LIB) -o $(BINDIR)/$(CONFIG)/thread_manager_test + +endif + +endif + +$(OBJDIR)/$(CONFIG)/test/cpp/thread_manager/thread_manager_test.o: $(LIBDIR)/$(CONFIG)/libgrpc++.a $(LIBDIR)/$(CONFIG)/libgrpc.a $(LIBDIR)/$(CONFIG)/libgpr.a $(LIBDIR)/$(CONFIG)/libgrpc++_test_config.a + +deps_thread_manager_test: $(THREAD_MANAGER_TEST_OBJS:.o=.dep) + +ifneq ($(NO_SECURE),true) +ifneq ($(NO_DEPS),true) +-include $(THREAD_MANAGER_TEST_OBJS:.o=.dep) +endif +endif + + THREAD_STRESS_TEST_SRC = \ test/cpp/end2end/thread_stress_test.cc \ @@ -16201,8 +16269,6 @@ src/cpp/common/secure_channel_arguments.cc: $(OPENSSL_DEP) src/cpp/common/secure_create_auth_context.cc: $(OPENSSL_DEP) src/cpp/ext/proto_server_reflection.cc: $(OPENSSL_DEP) src/cpp/ext/proto_server_reflection_plugin.cc: $(OPENSSL_DEP) -src/cpp/ext/reflection.grpc.pb.cc: $(OPENSSL_DEP) -src/cpp/ext/reflection.pb.cc: $(OPENSSL_DEP) src/cpp/server/secure_server_credentials.cc: $(OPENSSL_DEP) src/cpp/test/server_context_test_spouse.cc: $(OPENSSL_DEP) src/csharp/ext/grpc_csharp_ext.c: $(OPENSSL_DEP) diff --git a/binding.gyp b/binding.gyp index 23628f819b3..9f3b75aaf3d 100644 --- a/binding.gyp +++ b/binding.gyp @@ -612,6 +612,7 @@ '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_utils_common_posix.c', 'src/core/lib/iomgr/socket_utils_linux.c', diff --git a/build.yaml b/build.yaml index ed42dcd6a11..56c220d4aba 100644 --- a/build.yaml +++ b/build.yaml @@ -208,6 +208,7 @@ filegroups: - src/core/lib/iomgr/pollset_windows.h - src/core/lib/iomgr/port.h - src/core/lib/iomgr/resolve_address.h + - src/core/lib/iomgr/resource_quota.h - src/core/lib/iomgr/sockaddr.h - src/core/lib/iomgr/sockaddr_posix.h - src/core/lib/iomgr/sockaddr_utils.h @@ -216,6 +217,7 @@ filegroups: - src/core/lib/iomgr/socket_utils_posix.h - src/core/lib/iomgr/socket_windows.h - src/core/lib/iomgr/tcp_client.h + - src/core/lib/iomgr/tcp_client_posix.h - src/core/lib/iomgr/tcp_posix.h - src/core/lib/iomgr/tcp_server.h - src/core/lib/iomgr/tcp_uv.h @@ -303,6 +305,7 @@ filegroups: - 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_utils_common_posix.c - src/core/lib/iomgr/socket_utils_linux.c @@ -707,12 +710,7 @@ filegroups: - include/grpc++/impl/server_builder_plugin.h - include/grpc++/impl/server_initializer.h - include/grpc++/impl/service_type.h - - include/grpc++/impl/sync.h - - include/grpc++/impl/sync_cxx11.h - - include/grpc++/impl/sync_no_cxx11.h - - include/grpc++/impl/thd.h - - include/grpc++/impl/thd_cxx11.h - - include/grpc++/impl/thd_no_cxx11.h + - include/grpc++/resource_quota.h - include/grpc++/security/auth_context.h - include/grpc++/security/auth_metadata_processor.h - include/grpc++/security/credentials.h @@ -738,6 +736,7 @@ filegroups: - src/cpp/common/channel_filter.h - src/cpp/server/dynamic_thread_pool.h - src/cpp/server/thread_pool_interface.h + - src/cpp/thread_manager/thread_manager.h src: - src/cpp/client/channel_cc.cc - src/cpp/client/client_context.cc @@ -750,6 +749,7 @@ filegroups: - src/cpp/common/channel_filter.cc - src/cpp/common/completion_queue_cc.cc - src/cpp/common/core_codegen.cc + - src/cpp/common/resource_quota_cc.cc - src/cpp/common/rpc_method.cc - src/cpp/server/async_generic_service.cc - src/cpp/server/create_default_thread_pool.cc @@ -759,6 +759,7 @@ filegroups: - src/cpp/server/server_context.cc - src/cpp/server/server_credentials.cc - src/cpp/server/server_posix.cc + - src/cpp/thread_manager/thread_manager.cc - src/cpp/util/byte_buffer_cc.cc - src/cpp/util/slice_cc.cc - src/cpp/util/status.cc @@ -795,9 +796,6 @@ filegroups: - include/grpc++/impl/codegen/status_helper.h - include/grpc++/impl/codegen/string_ref.h - include/grpc++/impl/codegen/stub_options.h - - include/grpc++/impl/codegen/sync.h - - include/grpc++/impl/codegen/sync_cxx11.h - - include/grpc++/impl/codegen/sync_no_cxx11.h - include/grpc++/impl/codegen/sync_stream.h - include/grpc++/impl/codegen/time.h uses: @@ -821,14 +819,8 @@ filegroups: - include/grpc++/impl/codegen/config_protobuf.h - name: grpc++_reflection_proto language: c++ - public_headers: - - include/grpc++/ext/reflection.grpc.pb.h - - include/grpc++/ext/reflection.pb.h src: - - src/cpp/ext/reflection.grpc.pb.cc - - src/cpp/ext/reflection.pb.cc - uses: - - grpc++_codegen_proto + - src/proto/grpc/reflection/v1alpha/reflection.proto - name: thrift_util language: c++ public_headers: @@ -1046,6 +1038,18 @@ libs: platforms: - linux secure: true +- name: grpc++_proto_reflection_desc_db + build: private + language: c++ + headers: + - test/cpp/util/proto_reflection_descriptor_database.h + src: + - test/cpp/util/proto_reflection_descriptor_database.cc + deps: + - grpc++ + filegroups: + - grpc++_reflection_proto + - grpc++_config_proto - name: grpc++_reflection build: all language: c++ @@ -1060,11 +1064,6 @@ libs: - grpc++ filegroups: - grpc++_reflection_proto -- name: grpc++_reflection_codegen - build: private - language: c++ - src: - - src/proto/grpc/reflection/v1alpha/reflection.proto - name: grpc++_test build: private language: c++ @@ -1137,18 +1136,19 @@ libs: - test/cpp/util/config_grpc_cli.h - test/cpp/util/grpc_tool.h - test/cpp/util/proto_file_parser.h - - test/cpp/util/proto_reflection_descriptor_database.h - test/cpp/util/service_describer.h src: - test/cpp/util/cli_call.cc - test/cpp/util/cli_credentials.cc - test/cpp/util/grpc_tool.cc - test/cpp/util/proto_file_parser.cc - - test/cpp/util/proto_reflection_descriptor_database.cc - test/cpp/util/service_describer.cc deps: - - grpc++_reflection + - grpc++_proto_reflection_desc_db - grpc++ + filegroups: + - grpc++_reflection_proto + - grpc++_config_proto - name: grpc_plugin_support build: protoc language: c++ @@ -2427,6 +2427,17 @@ targets: - gpr exclude_iomgrs: - uv +- name: resource_quota_test + cpu_cost: 30 + build: test + language: c + src: + - test/core/iomgr/resource_quota_test.c + deps: + - grpc_test_util + - grpc + - gpr_test_util + - gpr - name: secure_channel_create_test build: test language: c @@ -2966,7 +2977,7 @@ targets: - test/cpp/util/grpc_cli.cc deps: - grpc_cli_libs - - grpc++_reflection + - grpc++_proto_reflection_desc_db - grpc++ - grpc - gpr @@ -3043,16 +3054,15 @@ targets: gtest: true build: test language: c++ - headers: - - test/cpp/util/string_ref_helper.h src: - src/proto/grpc/testing/echo.proto - src/proto/grpc/testing/echo_messages.proto - test/cpp/util/grpc_tool_test.cc - - test/cpp/util/string_ref_helper.cc deps: - grpc_cli_libs + - grpc++_proto_reflection_desc_db - grpc++_reflection + - grpc++_test_util - grpc_test_util - grpc++ - grpc @@ -3060,7 +3070,6 @@ targets: - gpr filegroups: - grpc++_codegen_proto - - grpc++_config_proto - name: grpclb_api_test gtest: true build: test @@ -3200,12 +3209,10 @@ targets: gtest: true build: test language: c++ - headers: - - test/cpp/util/proto_reflection_descriptor_database.h src: - test/cpp/end2end/proto_server_reflection_test.cc - - test/cpp/util/proto_reflection_descriptor_database.cc deps: + - grpc++_proto_reflection_desc_db - grpc++_reflection - grpc++_test_util - grpc_test_util @@ -3319,6 +3326,19 @@ targets: - gpr_test_util - gpr - grpc++_test_config +- name: round_robin_end2end_test + gtest: true + build: test + language: c++ + src: + - test/cpp/end2end/round_robin_end2end_test.cc + deps: + - grpc++_test_util + - grpc_test_util + - grpc++ + - grpc + - gpr_test_util + - gpr - name: secure_auth_context_test gtest: true build: test @@ -3474,6 +3494,16 @@ targets: - gpr_test_util - gpr - grpc++_test_config +- name: thread_manager_test + build: test + language: c++ + src: + - test/cpp/thread_manager/thread_manager_test.cc + deps: + - grpc++ + - grpc + - gpr + - grpc++_test_config - name: thread_stress_test gtest: true cpu_cost: 100 diff --git a/config.m4 b/config.m4 index 84af6bd3d0d..8f26e426789 100644 --- a/config.m4 +++ b/config.m4 @@ -128,6 +128,7 @@ if test "$PHP_GRPC" != "no"; then 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_utils_common_posix.c \ src/core/lib/iomgr/socket_utils_linux.c \ diff --git a/doc/cpp-style-guide.md b/doc/cpp-style-guide.md index 0138ceb7371..a1f91353fe9 100644 --- a/doc/cpp-style-guide.md +++ b/doc/cpp-style-guide.md @@ -1,91 +1,9 @@ GRPC C++ STYLE GUIDE ===================== -Background ----------- - -Here we document style rules for C++ usage in the gRPC C++ bindings -and tests. - -General -------- - -- The majority of gRPC's C++ requirements are drawn from the [Google C++ style -guide] (https://google.github.io/styleguide/cppguide.html) - - However, gRPC has some additional requirements to maintain - [portability] (#portability) -- As in C, layout rules are defined by clang-format, and all code +The majority of gRPC's C++ requirements are drawn from the [Google C++ style +guide] (https://google.github.io/styleguide/cppguide.html). Additionally, +as in C, layout rules are defined by clang-format, and all code should be passed through clang-format. A (docker-based) script to do so is included in [tools/distrib/clang\_format\_code.sh] (../tools/distrib/clang_format_code.sh). - - -Portability Restrictions -------------------- - -gRPC supports a large number of compilers, ranging from those that are -missing many key C++11 features to those that have quite detailed -analysis. As a result, gRPC compiles with a high level of warnings and -treat all warnings as errors. gRPC also forbids the use of some common -C++11 constructs. Here are some guidelines, to be extended as needed: -- Do not use range-based for. Expressions of the form - ```c - for (auto& i: vec) { - // code - } - ``` - - are not allowed and should be replaced with code such as - ```c - for (auto it = vec.begin; it != vec.end(); it++) { - auto& i = *it; - // code - } - ``` - -- Do not use lambda of any kind (no capture, explicit capture, or -default capture). Other C++ functional features such as -`std::function` or `std::bind` are allowed -- Do not use brace-list initializers. -- Do not compare a pointer to `nullptr` . This is because gcc 4.4 - does not support `nullptr` directly and gRPC implements a subset of - its features in [include/grpc++/impl/codegen/config.h] - (../include/grpc++/impl/codegen/config.h). Instead, pointers should - be checked for validity using their implicit conversion to `bool`. - In other words, use `if (p)` rather than `if (p != nullptr)` -- Do not initialize global/static pointer variables to `nullptr`. Just let - the compiler implicitly initialize them to `nullptr` (which it will - definitely do). The reason is that `nullptr` is an actual object in - our implementation rather than just a constant pointer value, so - static/global constructors will be called in a potentially - undesirable sequence. -- Do not use `final` or `override` as these are not supported by some - compilers. Instead use `GRPC_FINAL` and `GRPC_OVERRIDE` . These - compile down to the traditional C++ forms for compilers that support - them but are just elided if the compiler does not support those features. -- In the [include] (../../../tree/master/include/grpc++) and [src] - (../../../tree/master/src/cpp) directory trees, you should also not - use certain STL objects like `std::mutex`, `std::lock_guard`, - `std::unique_lock`, `std::nullptr`, `std::thread` . Instead, use - `grpc::mutex`, `grpc::lock_guard`, etc., which are gRPC - implementations of the prominent features of these objects that are - not always available. You can use the `std` versions of those in [test] - (../../../tree/master/test/cpp) -- Similarly, in the same directories, do not use `std::chrono` unless - it is guarded by `#ifndef GRPC_CXX0X_NO_CHRONO` . For platforms that - lack`std::chrono,` there is a C-language timer called gpr_timespec that can - be used instead. -- `std::unique_ptr` must be used with extreme care in any kind of - collection. For example `vector` does not work in - gcc 4.4 if the vector is constructed to its full size at - initialization but does work if elements are added to the vector - using functions like `push_back`. `map` and other pair-based - collections do not work with `unique_ptr` under gcc 4.4. The issue - is that many of these collection implementations assume a copy - constructor - to be available. -- Don't use `std::this_thread` . Use `gpr_sleep_until` for sleeping a thread. -- [Some adjacent character combinations cause problems] - (https://en.wikipedia.org/wiki/Digraphs_and_trigraphs#C). If declaring a - template against some class relative to the global namespace, - `<::name` will be non-portable. Separate the `<` from the `:` and use `< ::name`. diff --git a/gRPC-Core.podspec b/gRPC-Core.podspec index 0e4af8ae6c3..43aedecd06f 100644 --- a/gRPC-Core.podspec +++ b/gRPC-Core.podspec @@ -35,7 +35,7 @@ Pod::Spec.new do |s| s.name = 'gRPC-Core' - version = '1.0.0' + version = '1.0.1' s.version = version s.summary = 'Core cross-platform gRPC library, written in C' s.homepage = 'http://www.grpc.io' @@ -186,7 +186,7 @@ Pod::Spec.new do |s| ss.header_mappings_dir = '.' ss.libraries = 'z' ss.dependency "#{s.name}/Interface", version - ss.dependency 'BoringSSL', '~> 6.0' + ss.dependency 'BoringSSL', '~> 7.0' # To save you from scrolling, this is the last part of the podspec. ss.source_files = 'src/core/lib/profiling/timers.h', @@ -291,6 +291,7 @@ Pod::Spec.new do |s| 'src/core/lib/iomgr/pollset_windows.h', 'src/core/lib/iomgr/port.h', 'src/core/lib/iomgr/resolve_address.h', + 'src/core/lib/iomgr/resource_quota.h', 'src/core/lib/iomgr/sockaddr.h', 'src/core/lib/iomgr/sockaddr_posix.h', 'src/core/lib/iomgr/sockaddr_utils.h', @@ -299,6 +300,7 @@ Pod::Spec.new do |s| 'src/core/lib/iomgr/socket_utils_posix.h', 'src/core/lib/iomgr/socket_windows.h', 'src/core/lib/iomgr/tcp_client.h', + 'src/core/lib/iomgr/tcp_client_posix.h', 'src/core/lib/iomgr/tcp_posix.h', 'src/core/lib/iomgr/tcp_server.h', 'src/core/lib/iomgr/tcp_uv.h', @@ -466,6 +468,7 @@ Pod::Spec.new do |s| '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_utils_common_posix.c', 'src/core/lib/iomgr/socket_utils_linux.c', @@ -684,6 +687,7 @@ Pod::Spec.new do |s| 'src/core/lib/iomgr/pollset_windows.h', 'src/core/lib/iomgr/port.h', 'src/core/lib/iomgr/resolve_address.h', + 'src/core/lib/iomgr/resource_quota.h', 'src/core/lib/iomgr/sockaddr.h', 'src/core/lib/iomgr/sockaddr_posix.h', 'src/core/lib/iomgr/sockaddr_utils.h', @@ -692,6 +696,7 @@ Pod::Spec.new do |s| 'src/core/lib/iomgr/socket_utils_posix.h', 'src/core/lib/iomgr/socket_windows.h', 'src/core/lib/iomgr/tcp_client.h', + 'src/core/lib/iomgr/tcp_client_posix.h', 'src/core/lib/iomgr/tcp_posix.h', 'src/core/lib/iomgr/tcp_server.h', 'src/core/lib/iomgr/tcp_uv.h', diff --git a/gRPC-ProtoRPC.podspec b/gRPC-ProtoRPC.podspec index f6426fb4deb..61d4b62d391 100644 --- a/gRPC-ProtoRPC.podspec +++ b/gRPC-ProtoRPC.podspec @@ -30,7 +30,7 @@ Pod::Spec.new do |s| s.name = 'gRPC-ProtoRPC' - version = '1.0.0' + version = '1.0.1' s.version = version s.summary = 'RPC library for Protocol Buffers, based on gRPC' s.homepage = 'http://www.grpc.io' diff --git a/gRPC-RxLibrary.podspec b/gRPC-RxLibrary.podspec index 316843436ba..d59385c039a 100644 --- a/gRPC-RxLibrary.podspec +++ b/gRPC-RxLibrary.podspec @@ -30,7 +30,7 @@ Pod::Spec.new do |s| s.name = 'gRPC-RxLibrary' - version = '1.0.0' + version = '1.0.1' s.version = version s.summary = 'Reactive Extensions library for iOS/OSX.' s.homepage = 'http://www.grpc.io' diff --git a/gRPC.podspec b/gRPC.podspec index 9a479349531..76410b17d28 100644 --- a/gRPC.podspec +++ b/gRPC.podspec @@ -30,7 +30,7 @@ Pod::Spec.new do |s| s.name = 'gRPC' - version = '1.0.0' + version = '1.0.1' s.version = version s.summary = 'gRPC client library for iOS/OSX' s.homepage = 'http://www.grpc.io' diff --git a/grpc.def b/grpc.def index 6e905a297ed..0b6db801d8d 100644 --- a/grpc.def +++ b/grpc.def @@ -94,6 +94,11 @@ EXPORTS grpc_header_nonbin_value_is_legal grpc_is_binary_header grpc_call_error_to_string + grpc_resource_quota_create + grpc_resource_quota_ref + grpc_resource_quota_unref + grpc_resource_quota_resize + grpc_resource_quota_arg_vtable grpc_insecure_channel_create_from_fd grpc_server_add_insecure_channel_from_fd grpc_use_signal diff --git a/grpc.gemspec b/grpc.gemspec index c5bb926cb50..615a962cdb6 100755 --- a/grpc.gemspec +++ b/grpc.gemspec @@ -211,6 +211,7 @@ Gem::Specification.new do |s| s.files += %w( src/core/lib/iomgr/pollset_windows.h ) s.files += %w( src/core/lib/iomgr/port.h ) s.files += %w( src/core/lib/iomgr/resolve_address.h ) + s.files += %w( src/core/lib/iomgr/resource_quota.h ) s.files += %w( src/core/lib/iomgr/sockaddr.h ) s.files += %w( src/core/lib/iomgr/sockaddr_posix.h ) s.files += %w( src/core/lib/iomgr/sockaddr_utils.h ) @@ -219,6 +220,7 @@ Gem::Specification.new do |s| s.files += %w( src/core/lib/iomgr/socket_utils_posix.h ) s.files += %w( src/core/lib/iomgr/socket_windows.h ) s.files += %w( src/core/lib/iomgr/tcp_client.h ) + s.files += %w( src/core/lib/iomgr/tcp_client_posix.h ) s.files += %w( src/core/lib/iomgr/tcp_posix.h ) s.files += %w( src/core/lib/iomgr/tcp_server.h ) s.files += %w( src/core/lib/iomgr/tcp_uv.h ) @@ -386,6 +388,7 @@ Gem::Specification.new do |s| s.files += %w( src/core/lib/iomgr/resolve_address_posix.c ) s.files += %w( src/core/lib/iomgr/resolve_address_uv.c ) s.files += %w( src/core/lib/iomgr/resolve_address_windows.c ) + s.files += %w( src/core/lib/iomgr/resource_quota.c ) s.files += %w( src/core/lib/iomgr/sockaddr_utils.c ) s.files += %w( src/core/lib/iomgr/socket_utils_common_posix.c ) s.files += %w( src/core/lib/iomgr/socket_utils_linux.c ) diff --git a/include/grpc++/alarm.h b/include/grpc++/alarm.h index 1470fe8d97b..9a15167cc73 100644 --- a/include/grpc++/alarm.h +++ b/include/grpc++/alarm.h @@ -78,7 +78,7 @@ class Alarm : private GrpcLibraryCodegen { class AlarmEntry : public CompletionQueueTag { public: AlarmEntry(void* tag) : tag_(tag) {} - bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { + bool FinalizeResult(void** tag, bool* status) override { *tag = tag_; return true; } diff --git a/include/grpc++/channel.h b/include/grpc++/channel.h index c535d57bffb..c8360282e7b 100644 --- a/include/grpc++/channel.h +++ b/include/grpc++/channel.h @@ -46,16 +46,16 @@ struct grpc_channel; namespace grpc { /// Channels represent a connection to an endpoint. Created by \a CreateChannel. -class Channel GRPC_FINAL : public ChannelInterface, - public CallHook, - public std::enable_shared_from_this, - private GrpcLibraryCodegen { +class Channel final : public ChannelInterface, + public CallHook, + public std::enable_shared_from_this, + private GrpcLibraryCodegen { public: ~Channel(); /// Get the current channel state. If the channel is in IDLE and /// \a try_to_connect is set to true, try to connect. - grpc_connectivity_state GetState(bool try_to_connect) GRPC_OVERRIDE; + grpc_connectivity_state GetState(bool try_to_connect) override; private: template @@ -69,15 +69,15 @@ class Channel GRPC_FINAL : public ChannelInterface, Channel(const grpc::string& host, grpc_channel* c_channel); Call CreateCall(const RpcMethod& method, ClientContext* context, - CompletionQueue* cq) GRPC_OVERRIDE; - void PerformOpsOnCall(CallOpSetInterface* ops, Call* call) GRPC_OVERRIDE; - void* RegisterMethod(const char* method) GRPC_OVERRIDE; + CompletionQueue* cq) override; + void PerformOpsOnCall(CallOpSetInterface* ops, Call* call) override; + void* RegisterMethod(const char* method) override; void NotifyOnStateChangeImpl(grpc_connectivity_state last_observed, gpr_timespec deadline, CompletionQueue* cq, - void* tag) GRPC_OVERRIDE; + void* tag) override; bool WaitForStateChangeImpl(grpc_connectivity_state last_observed, - gpr_timespec deadline) GRPC_OVERRIDE; + gpr_timespec deadline) override; const grpc::string host_; grpc_channel* const c_channel_; // owned diff --git a/include/grpc++/ext/proto_server_reflection_plugin.h b/include/grpc++/ext/proto_server_reflection_plugin.h index 3e54882d41f..66f39eb8760 100644 --- a/include/grpc++/ext/proto_server_reflection_plugin.h +++ b/include/grpc++/ext/proto_server_reflection_plugin.h @@ -48,12 +48,12 @@ namespace reflection { class ProtoServerReflectionPlugin : public ::grpc::ServerBuilderPlugin { public: ProtoServerReflectionPlugin(); - ::grpc::string name() GRPC_OVERRIDE; - void InitServer(::grpc::ServerInitializer* si) GRPC_OVERRIDE; - void Finish(::grpc::ServerInitializer* si) GRPC_OVERRIDE; - void ChangeArguments(const ::grpc::string& name, void* value) GRPC_OVERRIDE; - bool has_async_methods() const GRPC_OVERRIDE; - bool has_sync_methods() const GRPC_OVERRIDE; + ::grpc::string name() override; + void InitServer(::grpc::ServerInitializer* si) override; + void Finish(::grpc::ServerInitializer* si) override; + void ChangeArguments(const ::grpc::string& name, void* value) override; + bool has_async_methods() const override; + bool has_sync_methods() const override; private: std::shared_ptr reflection_service_; diff --git a/include/grpc++/ext/reflection.grpc.pb.h b/include/grpc++/ext/reflection.grpc.pb.h deleted file mode 100644 index 151271c65b8..00000000000 --- a/include/grpc++/ext/reflection.grpc.pb.h +++ /dev/null @@ -1,188 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - - -// Generated by tools/codegen/extensions/gen_reflection_proto.sh -// If you make any local change, they will be lost. -// source: reflection.proto -// Original file comments: -// Copyright 2016, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Service exported by server reflection -// -#ifndef GRPC_reflection_2eproto__INCLUDED -#define GRPC_reflection_2eproto__INCLUDED - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace grpc { -class CompletionQueue; -class Channel; -class RpcService; -class ServerCompletionQueue; -class ServerContext; -} // namespace grpc - -namespace grpc { -namespace reflection { -namespace v1alpha { - -class ServerReflection GRPC_FINAL { - public: - class StubInterface { - public: - virtual ~StubInterface() {} - // The reflection service is structured as a bidirectional stream, ensuring - // all related requests go to a single server. - std::unique_ptr< ::grpc::ClientReaderWriterInterface< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>> ServerReflectionInfo(::grpc::ClientContext* context) { - return std::unique_ptr< ::grpc::ClientReaderWriterInterface< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>>(ServerReflectionInfoRaw(context)); - } - std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>> AsyncServerReflectionInfo(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { - return std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>>(AsyncServerReflectionInfoRaw(context, cq, tag)); - } - private: - virtual ::grpc::ClientReaderWriterInterface< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>* ServerReflectionInfoRaw(::grpc::ClientContext* context) = 0; - virtual ::grpc::ClientAsyncReaderWriterInterface< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>* AsyncServerReflectionInfoRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) = 0; - }; - class Stub GRPC_FINAL : public StubInterface { - public: - Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); - std::unique_ptr< ::grpc::ClientReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>> ServerReflectionInfo(::grpc::ClientContext* context) { - return std::unique_ptr< ::grpc::ClientReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>>(ServerReflectionInfoRaw(context)); - } - std::unique_ptr< ::grpc::ClientAsyncReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>> AsyncServerReflectionInfo(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { - return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>>(AsyncServerReflectionInfoRaw(context, cq, tag)); - } - - private: - std::shared_ptr< ::grpc::ChannelInterface> channel_; - ::grpc::ClientReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>* ServerReflectionInfoRaw(::grpc::ClientContext* context) GRPC_OVERRIDE; - ::grpc::ClientAsyncReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>* AsyncServerReflectionInfoRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) GRPC_OVERRIDE; - const ::grpc::RpcMethod rpcmethod_ServerReflectionInfo_; - }; - static std::unique_ptr NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions()); - - class Service : public ::grpc::Service { - public: - Service(); - virtual ~Service(); - // The reflection service is structured as a bidirectional stream, ensuring - // all related requests go to a single server. - virtual ::grpc::Status ServerReflectionInfo(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionResponse, ::grpc::reflection::v1alpha::ServerReflectionRequest>* stream); - }; - template - class WithAsyncMethod_ServerReflectionInfo : public BaseClass { - private: - void BaseClassMustBeDerivedFromService(const Service *service) {} - public: - WithAsyncMethod_ServerReflectionInfo() { - ::grpc::Service::MarkMethodAsync(0); - } - ~WithAsyncMethod_ServerReflectionInfo() GRPC_OVERRIDE { - BaseClassMustBeDerivedFromService(this); - } - // disable synchronous version of this method - ::grpc::Status ServerReflectionInfo(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionResponse, ::grpc::reflection::v1alpha::ServerReflectionRequest>* stream) GRPC_FINAL GRPC_OVERRIDE { - abort(); - return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); - } - void RequestServerReflectionInfo(::grpc::ServerContext* context, ::grpc::ServerAsyncReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionResponse, ::grpc::reflection::v1alpha::ServerReflectionRequest>* stream, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { - ::grpc::Service::RequestAsyncBidiStreaming(0, context, stream, new_call_cq, notification_cq, tag); - } - }; - typedef WithAsyncMethod_ServerReflectionInfo AsyncService; - template - class WithGenericMethod_ServerReflectionInfo : public BaseClass { - private: - void BaseClassMustBeDerivedFromService(const Service *service) {} - public: - WithGenericMethod_ServerReflectionInfo() { - ::grpc::Service::MarkMethodGeneric(0); - } - ~WithGenericMethod_ServerReflectionInfo() GRPC_OVERRIDE { - BaseClassMustBeDerivedFromService(this); - } - // disable synchronous version of this method - ::grpc::Status ServerReflectionInfo(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionResponse, ::grpc::reflection::v1alpha::ServerReflectionRequest>* stream) GRPC_FINAL GRPC_OVERRIDE { - abort(); - return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); - } - }; - typedef Service StreamedUnaryService; - typedef Service SplitStreamedService; - typedef Service StreamedService; -}; - -} // namespace v1alpha -} // namespace reflection -} // namespace grpc - - -#endif // GRPC_reflection_2eproto__INCLUDED diff --git a/include/grpc++/ext/reflection.pb.h b/include/grpc++/ext/reflection.pb.h deleted file mode 100644 index 6e645af10e5..00000000000 --- a/include/grpc++/ext/reflection.pb.h +++ /dev/null @@ -1,2125 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - - -// Generated by tools/codegen/extensions/gen_reflection_proto.sh -// source: reflection.proto - -#ifndef PROTOBUF_reflection_2eproto__INCLUDED -#define PROTOBUF_reflection_2eproto__INCLUDED - -#include - -#include - -#if GOOGLE_PROTOBUF_VERSION < 3001000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -// @@protoc_insertion_point(includes) - -namespace grpc { -namespace reflection { -namespace v1alpha { - -// Internal implementation detail -- do not call these. -void protobuf_AddDesc_reflection_2eproto(); -void protobuf_InitDefaults_reflection_2eproto(); -void protobuf_AssignDesc_reflection_2eproto(); -void protobuf_ShutdownFile_reflection_2eproto(); - -class ErrorResponse; -class ExtensionNumberResponse; -class ExtensionRequest; -class FileDescriptorResponse; -class ListServiceResponse; -class ServerReflectionRequest; -class ServerReflectionResponse; -class ServiceResponse; - -// =================================================================== - -class ServerReflectionRequest : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:grpc.reflection.v1alpha.ServerReflectionRequest) */ { - public: - ServerReflectionRequest(); - virtual ~ServerReflectionRequest(); - - ServerReflectionRequest(const ServerReflectionRequest& from); - - inline ServerReflectionRequest& operator=(const ServerReflectionRequest& from) { - CopyFrom(from); - return *this; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const ServerReflectionRequest& default_instance(); - - enum MessageRequestCase { - kFileByFilename = 3, - kFileContainingSymbol = 4, - kFileContainingExtension = 5, - kAllExtensionNumbersOfType = 6, - kListServices = 7, - MESSAGE_REQUEST_NOT_SET = 0, - }; - - static const ServerReflectionRequest* internal_default_instance(); - - void Swap(ServerReflectionRequest* other); - - // implements Message ---------------------------------------------- - - inline ServerReflectionRequest* New() const { return New(NULL); } - - ServerReflectionRequest* New(::google::protobuf::Arena* arena) const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const ServerReflectionRequest& from); - void MergeFrom(const ServerReflectionRequest& from); - void Clear(); - bool IsInitialized() const; - - size_t ByteSizeLong() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const { - return InternalSerializeWithCachedSizesToArray(false, output); - } - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - void InternalSwap(ServerReflectionRequest* other); - void UnsafeMergeFrom(const ServerReflectionRequest& from); - private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return _internal_metadata_.arena(); - } - inline void* MaybeArenaPtr() const { - return _internal_metadata_.raw_arena_ptr(); - } - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional string host = 1; - void clear_host(); - static const int kHostFieldNumber = 1; - const ::std::string& host() const; - void set_host(const ::std::string& value); - void set_host(const char* value); - void set_host(const char* value, size_t size); - ::std::string* mutable_host(); - ::std::string* release_host(); - void set_allocated_host(::std::string* host); - - // optional string file_by_filename = 3; - private: - bool has_file_by_filename() const; - public: - void clear_file_by_filename(); - static const int kFileByFilenameFieldNumber = 3; - const ::std::string& file_by_filename() const; - void set_file_by_filename(const ::std::string& value); - void set_file_by_filename(const char* value); - void set_file_by_filename(const char* value, size_t size); - ::std::string* mutable_file_by_filename(); - ::std::string* release_file_by_filename(); - void set_allocated_file_by_filename(::std::string* file_by_filename); - - // optional string file_containing_symbol = 4; - private: - bool has_file_containing_symbol() const; - public: - void clear_file_containing_symbol(); - static const int kFileContainingSymbolFieldNumber = 4; - const ::std::string& file_containing_symbol() const; - void set_file_containing_symbol(const ::std::string& value); - void set_file_containing_symbol(const char* value); - void set_file_containing_symbol(const char* value, size_t size); - ::std::string* mutable_file_containing_symbol(); - ::std::string* release_file_containing_symbol(); - void set_allocated_file_containing_symbol(::std::string* file_containing_symbol); - - // optional .grpc.reflection.v1alpha.ExtensionRequest file_containing_extension = 5; - bool has_file_containing_extension() const; - void clear_file_containing_extension(); - static const int kFileContainingExtensionFieldNumber = 5; - const ::grpc::reflection::v1alpha::ExtensionRequest& file_containing_extension() const; - ::grpc::reflection::v1alpha::ExtensionRequest* mutable_file_containing_extension(); - ::grpc::reflection::v1alpha::ExtensionRequest* release_file_containing_extension(); - void set_allocated_file_containing_extension(::grpc::reflection::v1alpha::ExtensionRequest* file_containing_extension); - - // optional string all_extension_numbers_of_type = 6; - private: - bool has_all_extension_numbers_of_type() const; - public: - void clear_all_extension_numbers_of_type(); - static const int kAllExtensionNumbersOfTypeFieldNumber = 6; - const ::std::string& all_extension_numbers_of_type() const; - void set_all_extension_numbers_of_type(const ::std::string& value); - void set_all_extension_numbers_of_type(const char* value); - void set_all_extension_numbers_of_type(const char* value, size_t size); - ::std::string* mutable_all_extension_numbers_of_type(); - ::std::string* release_all_extension_numbers_of_type(); - void set_allocated_all_extension_numbers_of_type(::std::string* all_extension_numbers_of_type); - - // optional string list_services = 7; - private: - bool has_list_services() const; - public: - void clear_list_services(); - static const int kListServicesFieldNumber = 7; - const ::std::string& list_services() const; - void set_list_services(const ::std::string& value); - void set_list_services(const char* value); - void set_list_services(const char* value, size_t size); - ::std::string* mutable_list_services(); - ::std::string* release_list_services(); - void set_allocated_list_services(::std::string* list_services); - - MessageRequestCase message_request_case() const; - // @@protoc_insertion_point(class_scope:grpc.reflection.v1alpha.ServerReflectionRequest) - private: - inline void set_has_file_by_filename(); - inline void set_has_file_containing_symbol(); - inline void set_has_file_containing_extension(); - inline void set_has_all_extension_numbers_of_type(); - inline void set_has_list_services(); - - inline bool has_message_request() const; - void clear_message_request(); - inline void clear_has_message_request(); - - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::ArenaStringPtr host_; - union MessageRequestUnion { - MessageRequestUnion() {} - ::google::protobuf::internal::ArenaStringPtr file_by_filename_; - ::google::protobuf::internal::ArenaStringPtr file_containing_symbol_; - ::grpc::reflection::v1alpha::ExtensionRequest* file_containing_extension_; - ::google::protobuf::internal::ArenaStringPtr all_extension_numbers_of_type_; - ::google::protobuf::internal::ArenaStringPtr list_services_; - } message_request_; - mutable int _cached_size_; - ::google::protobuf::uint32 _oneof_case_[1]; - - friend void protobuf_InitDefaults_reflection_2eproto_impl(); - friend void protobuf_AddDesc_reflection_2eproto_impl(); - friend void protobuf_AssignDesc_reflection_2eproto(); - friend void protobuf_ShutdownFile_reflection_2eproto(); - - void InitAsDefaultInstance(); -}; -extern ::google::protobuf::internal::ExplicitlyConstructed ServerReflectionRequest_default_instance_; - -// ------------------------------------------------------------------- - -class ExtensionRequest : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:grpc.reflection.v1alpha.ExtensionRequest) */ { - public: - ExtensionRequest(); - virtual ~ExtensionRequest(); - - ExtensionRequest(const ExtensionRequest& from); - - inline ExtensionRequest& operator=(const ExtensionRequest& from) { - CopyFrom(from); - return *this; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const ExtensionRequest& default_instance(); - - static const ExtensionRequest* internal_default_instance(); - - void Swap(ExtensionRequest* other); - - // implements Message ---------------------------------------------- - - inline ExtensionRequest* New() const { return New(NULL); } - - ExtensionRequest* New(::google::protobuf::Arena* arena) const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const ExtensionRequest& from); - void MergeFrom(const ExtensionRequest& from); - void Clear(); - bool IsInitialized() const; - - size_t ByteSizeLong() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const { - return InternalSerializeWithCachedSizesToArray(false, output); - } - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - void InternalSwap(ExtensionRequest* other); - void UnsafeMergeFrom(const ExtensionRequest& from); - private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return _internal_metadata_.arena(); - } - inline void* MaybeArenaPtr() const { - return _internal_metadata_.raw_arena_ptr(); - } - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional string containing_type = 1; - void clear_containing_type(); - static const int kContainingTypeFieldNumber = 1; - const ::std::string& containing_type() const; - void set_containing_type(const ::std::string& value); - void set_containing_type(const char* value); - void set_containing_type(const char* value, size_t size); - ::std::string* mutable_containing_type(); - ::std::string* release_containing_type(); - void set_allocated_containing_type(::std::string* containing_type); - - // optional int32 extension_number = 2; - void clear_extension_number(); - static const int kExtensionNumberFieldNumber = 2; - ::google::protobuf::int32 extension_number() const; - void set_extension_number(::google::protobuf::int32 value); - - // @@protoc_insertion_point(class_scope:grpc.reflection.v1alpha.ExtensionRequest) - private: - - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::ArenaStringPtr containing_type_; - ::google::protobuf::int32 extension_number_; - mutable int _cached_size_; - friend void protobuf_InitDefaults_reflection_2eproto_impl(); - friend void protobuf_AddDesc_reflection_2eproto_impl(); - friend void protobuf_AssignDesc_reflection_2eproto(); - friend void protobuf_ShutdownFile_reflection_2eproto(); - - void InitAsDefaultInstance(); -}; -extern ::google::protobuf::internal::ExplicitlyConstructed ExtensionRequest_default_instance_; - -// ------------------------------------------------------------------- - -class ServerReflectionResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:grpc.reflection.v1alpha.ServerReflectionResponse) */ { - public: - ServerReflectionResponse(); - virtual ~ServerReflectionResponse(); - - ServerReflectionResponse(const ServerReflectionResponse& from); - - inline ServerReflectionResponse& operator=(const ServerReflectionResponse& from) { - CopyFrom(from); - return *this; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const ServerReflectionResponse& default_instance(); - - enum MessageResponseCase { - kFileDescriptorResponse = 4, - kAllExtensionNumbersResponse = 5, - kListServicesResponse = 6, - kErrorResponse = 7, - MESSAGE_RESPONSE_NOT_SET = 0, - }; - - static const ServerReflectionResponse* internal_default_instance(); - - void Swap(ServerReflectionResponse* other); - - // implements Message ---------------------------------------------- - - inline ServerReflectionResponse* New() const { return New(NULL); } - - ServerReflectionResponse* New(::google::protobuf::Arena* arena) const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const ServerReflectionResponse& from); - void MergeFrom(const ServerReflectionResponse& from); - void Clear(); - bool IsInitialized() const; - - size_t ByteSizeLong() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const { - return InternalSerializeWithCachedSizesToArray(false, output); - } - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - void InternalSwap(ServerReflectionResponse* other); - void UnsafeMergeFrom(const ServerReflectionResponse& from); - private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return _internal_metadata_.arena(); - } - inline void* MaybeArenaPtr() const { - return _internal_metadata_.raw_arena_ptr(); - } - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional string valid_host = 1; - void clear_valid_host(); - static const int kValidHostFieldNumber = 1; - const ::std::string& valid_host() const; - void set_valid_host(const ::std::string& value); - void set_valid_host(const char* value); - void set_valid_host(const char* value, size_t size); - ::std::string* mutable_valid_host(); - ::std::string* release_valid_host(); - void set_allocated_valid_host(::std::string* valid_host); - - // optional .grpc.reflection.v1alpha.ServerReflectionRequest original_request = 2; - bool has_original_request() const; - void clear_original_request(); - static const int kOriginalRequestFieldNumber = 2; - const ::grpc::reflection::v1alpha::ServerReflectionRequest& original_request() const; - ::grpc::reflection::v1alpha::ServerReflectionRequest* mutable_original_request(); - ::grpc::reflection::v1alpha::ServerReflectionRequest* release_original_request(); - void set_allocated_original_request(::grpc::reflection::v1alpha::ServerReflectionRequest* original_request); - - // optional .grpc.reflection.v1alpha.FileDescriptorResponse file_descriptor_response = 4; - bool has_file_descriptor_response() const; - void clear_file_descriptor_response(); - static const int kFileDescriptorResponseFieldNumber = 4; - const ::grpc::reflection::v1alpha::FileDescriptorResponse& file_descriptor_response() const; - ::grpc::reflection::v1alpha::FileDescriptorResponse* mutable_file_descriptor_response(); - ::grpc::reflection::v1alpha::FileDescriptorResponse* release_file_descriptor_response(); - void set_allocated_file_descriptor_response(::grpc::reflection::v1alpha::FileDescriptorResponse* file_descriptor_response); - - // optional .grpc.reflection.v1alpha.ExtensionNumberResponse all_extension_numbers_response = 5; - bool has_all_extension_numbers_response() const; - void clear_all_extension_numbers_response(); - static const int kAllExtensionNumbersResponseFieldNumber = 5; - const ::grpc::reflection::v1alpha::ExtensionNumberResponse& all_extension_numbers_response() const; - ::grpc::reflection::v1alpha::ExtensionNumberResponse* mutable_all_extension_numbers_response(); - ::grpc::reflection::v1alpha::ExtensionNumberResponse* release_all_extension_numbers_response(); - void set_allocated_all_extension_numbers_response(::grpc::reflection::v1alpha::ExtensionNumberResponse* all_extension_numbers_response); - - // optional .grpc.reflection.v1alpha.ListServiceResponse list_services_response = 6; - bool has_list_services_response() const; - void clear_list_services_response(); - static const int kListServicesResponseFieldNumber = 6; - const ::grpc::reflection::v1alpha::ListServiceResponse& list_services_response() const; - ::grpc::reflection::v1alpha::ListServiceResponse* mutable_list_services_response(); - ::grpc::reflection::v1alpha::ListServiceResponse* release_list_services_response(); - void set_allocated_list_services_response(::grpc::reflection::v1alpha::ListServiceResponse* list_services_response); - - // optional .grpc.reflection.v1alpha.ErrorResponse error_response = 7; - bool has_error_response() const; - void clear_error_response(); - static const int kErrorResponseFieldNumber = 7; - const ::grpc::reflection::v1alpha::ErrorResponse& error_response() const; - ::grpc::reflection::v1alpha::ErrorResponse* mutable_error_response(); - ::grpc::reflection::v1alpha::ErrorResponse* release_error_response(); - void set_allocated_error_response(::grpc::reflection::v1alpha::ErrorResponse* error_response); - - MessageResponseCase message_response_case() const; - // @@protoc_insertion_point(class_scope:grpc.reflection.v1alpha.ServerReflectionResponse) - private: - inline void set_has_file_descriptor_response(); - inline void set_has_all_extension_numbers_response(); - inline void set_has_list_services_response(); - inline void set_has_error_response(); - - inline bool has_message_response() const; - void clear_message_response(); - inline void clear_has_message_response(); - - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::ArenaStringPtr valid_host_; - ::grpc::reflection::v1alpha::ServerReflectionRequest* original_request_; - union MessageResponseUnion { - MessageResponseUnion() {} - ::grpc::reflection::v1alpha::FileDescriptorResponse* file_descriptor_response_; - ::grpc::reflection::v1alpha::ExtensionNumberResponse* all_extension_numbers_response_; - ::grpc::reflection::v1alpha::ListServiceResponse* list_services_response_; - ::grpc::reflection::v1alpha::ErrorResponse* error_response_; - } message_response_; - mutable int _cached_size_; - ::google::protobuf::uint32 _oneof_case_[1]; - - friend void protobuf_InitDefaults_reflection_2eproto_impl(); - friend void protobuf_AddDesc_reflection_2eproto_impl(); - friend void protobuf_AssignDesc_reflection_2eproto(); - friend void protobuf_ShutdownFile_reflection_2eproto(); - - void InitAsDefaultInstance(); -}; -extern ::google::protobuf::internal::ExplicitlyConstructed ServerReflectionResponse_default_instance_; - -// ------------------------------------------------------------------- - -class FileDescriptorResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:grpc.reflection.v1alpha.FileDescriptorResponse) */ { - public: - FileDescriptorResponse(); - virtual ~FileDescriptorResponse(); - - FileDescriptorResponse(const FileDescriptorResponse& from); - - inline FileDescriptorResponse& operator=(const FileDescriptorResponse& from) { - CopyFrom(from); - return *this; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const FileDescriptorResponse& default_instance(); - - static const FileDescriptorResponse* internal_default_instance(); - - void Swap(FileDescriptorResponse* other); - - // implements Message ---------------------------------------------- - - inline FileDescriptorResponse* New() const { return New(NULL); } - - FileDescriptorResponse* New(::google::protobuf::Arena* arena) const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const FileDescriptorResponse& from); - void MergeFrom(const FileDescriptorResponse& from); - void Clear(); - bool IsInitialized() const; - - size_t ByteSizeLong() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const { - return InternalSerializeWithCachedSizesToArray(false, output); - } - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - void InternalSwap(FileDescriptorResponse* other); - void UnsafeMergeFrom(const FileDescriptorResponse& from); - private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return _internal_metadata_.arena(); - } - inline void* MaybeArenaPtr() const { - return _internal_metadata_.raw_arena_ptr(); - } - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // repeated bytes file_descriptor_proto = 1; - int file_descriptor_proto_size() const; - void clear_file_descriptor_proto(); - static const int kFileDescriptorProtoFieldNumber = 1; - const ::std::string& file_descriptor_proto(int index) const; - ::std::string* mutable_file_descriptor_proto(int index); - void set_file_descriptor_proto(int index, const ::std::string& value); - void set_file_descriptor_proto(int index, const char* value); - void set_file_descriptor_proto(int index, const void* value, size_t size); - ::std::string* add_file_descriptor_proto(); - void add_file_descriptor_proto(const ::std::string& value); - void add_file_descriptor_proto(const char* value); - void add_file_descriptor_proto(const void* value, size_t size); - const ::google::protobuf::RepeatedPtrField< ::std::string>& file_descriptor_proto() const; - ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_file_descriptor_proto(); - - // @@protoc_insertion_point(class_scope:grpc.reflection.v1alpha.FileDescriptorResponse) - private: - - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::RepeatedPtrField< ::std::string> file_descriptor_proto_; - mutable int _cached_size_; - friend void protobuf_InitDefaults_reflection_2eproto_impl(); - friend void protobuf_AddDesc_reflection_2eproto_impl(); - friend void protobuf_AssignDesc_reflection_2eproto(); - friend void protobuf_ShutdownFile_reflection_2eproto(); - - void InitAsDefaultInstance(); -}; -extern ::google::protobuf::internal::ExplicitlyConstructed FileDescriptorResponse_default_instance_; - -// ------------------------------------------------------------------- - -class ExtensionNumberResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:grpc.reflection.v1alpha.ExtensionNumberResponse) */ { - public: - ExtensionNumberResponse(); - virtual ~ExtensionNumberResponse(); - - ExtensionNumberResponse(const ExtensionNumberResponse& from); - - inline ExtensionNumberResponse& operator=(const ExtensionNumberResponse& from) { - CopyFrom(from); - return *this; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const ExtensionNumberResponse& default_instance(); - - static const ExtensionNumberResponse* internal_default_instance(); - - void Swap(ExtensionNumberResponse* other); - - // implements Message ---------------------------------------------- - - inline ExtensionNumberResponse* New() const { return New(NULL); } - - ExtensionNumberResponse* New(::google::protobuf::Arena* arena) const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const ExtensionNumberResponse& from); - void MergeFrom(const ExtensionNumberResponse& from); - void Clear(); - bool IsInitialized() const; - - size_t ByteSizeLong() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const { - return InternalSerializeWithCachedSizesToArray(false, output); - } - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - void InternalSwap(ExtensionNumberResponse* other); - void UnsafeMergeFrom(const ExtensionNumberResponse& from); - private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return _internal_metadata_.arena(); - } - inline void* MaybeArenaPtr() const { - return _internal_metadata_.raw_arena_ptr(); - } - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional string base_type_name = 1; - void clear_base_type_name(); - static const int kBaseTypeNameFieldNumber = 1; - const ::std::string& base_type_name() const; - void set_base_type_name(const ::std::string& value); - void set_base_type_name(const char* value); - void set_base_type_name(const char* value, size_t size); - ::std::string* mutable_base_type_name(); - ::std::string* release_base_type_name(); - void set_allocated_base_type_name(::std::string* base_type_name); - - // repeated int32 extension_number = 2; - int extension_number_size() const; - void clear_extension_number(); - static const int kExtensionNumberFieldNumber = 2; - ::google::protobuf::int32 extension_number(int index) const; - void set_extension_number(int index, ::google::protobuf::int32 value); - void add_extension_number(::google::protobuf::int32 value); - const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& - extension_number() const; - ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* - mutable_extension_number(); - - // @@protoc_insertion_point(class_scope:grpc.reflection.v1alpha.ExtensionNumberResponse) - private: - - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::RepeatedField< ::google::protobuf::int32 > extension_number_; - mutable int _extension_number_cached_byte_size_; - ::google::protobuf::internal::ArenaStringPtr base_type_name_; - mutable int _cached_size_; - friend void protobuf_InitDefaults_reflection_2eproto_impl(); - friend void protobuf_AddDesc_reflection_2eproto_impl(); - friend void protobuf_AssignDesc_reflection_2eproto(); - friend void protobuf_ShutdownFile_reflection_2eproto(); - - void InitAsDefaultInstance(); -}; -extern ::google::protobuf::internal::ExplicitlyConstructed ExtensionNumberResponse_default_instance_; - -// ------------------------------------------------------------------- - -class ListServiceResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:grpc.reflection.v1alpha.ListServiceResponse) */ { - public: - ListServiceResponse(); - virtual ~ListServiceResponse(); - - ListServiceResponse(const ListServiceResponse& from); - - inline ListServiceResponse& operator=(const ListServiceResponse& from) { - CopyFrom(from); - return *this; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const ListServiceResponse& default_instance(); - - static const ListServiceResponse* internal_default_instance(); - - void Swap(ListServiceResponse* other); - - // implements Message ---------------------------------------------- - - inline ListServiceResponse* New() const { return New(NULL); } - - ListServiceResponse* New(::google::protobuf::Arena* arena) const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const ListServiceResponse& from); - void MergeFrom(const ListServiceResponse& from); - void Clear(); - bool IsInitialized() const; - - size_t ByteSizeLong() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const { - return InternalSerializeWithCachedSizesToArray(false, output); - } - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - void InternalSwap(ListServiceResponse* other); - void UnsafeMergeFrom(const ListServiceResponse& from); - private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return _internal_metadata_.arena(); - } - inline void* MaybeArenaPtr() const { - return _internal_metadata_.raw_arena_ptr(); - } - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // repeated .grpc.reflection.v1alpha.ServiceResponse service = 1; - int service_size() const; - void clear_service(); - static const int kServiceFieldNumber = 1; - const ::grpc::reflection::v1alpha::ServiceResponse& service(int index) const; - ::grpc::reflection::v1alpha::ServiceResponse* mutable_service(int index); - ::grpc::reflection::v1alpha::ServiceResponse* add_service(); - ::google::protobuf::RepeatedPtrField< ::grpc::reflection::v1alpha::ServiceResponse >* - mutable_service(); - const ::google::protobuf::RepeatedPtrField< ::grpc::reflection::v1alpha::ServiceResponse >& - service() const; - - // @@protoc_insertion_point(class_scope:grpc.reflection.v1alpha.ListServiceResponse) - private: - - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::RepeatedPtrField< ::grpc::reflection::v1alpha::ServiceResponse > service_; - mutable int _cached_size_; - friend void protobuf_InitDefaults_reflection_2eproto_impl(); - friend void protobuf_AddDesc_reflection_2eproto_impl(); - friend void protobuf_AssignDesc_reflection_2eproto(); - friend void protobuf_ShutdownFile_reflection_2eproto(); - - void InitAsDefaultInstance(); -}; -extern ::google::protobuf::internal::ExplicitlyConstructed ListServiceResponse_default_instance_; - -// ------------------------------------------------------------------- - -class ServiceResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:grpc.reflection.v1alpha.ServiceResponse) */ { - public: - ServiceResponse(); - virtual ~ServiceResponse(); - - ServiceResponse(const ServiceResponse& from); - - inline ServiceResponse& operator=(const ServiceResponse& from) { - CopyFrom(from); - return *this; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const ServiceResponse& default_instance(); - - static const ServiceResponse* internal_default_instance(); - - void Swap(ServiceResponse* other); - - // implements Message ---------------------------------------------- - - inline ServiceResponse* New() const { return New(NULL); } - - ServiceResponse* New(::google::protobuf::Arena* arena) const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const ServiceResponse& from); - void MergeFrom(const ServiceResponse& from); - void Clear(); - bool IsInitialized() const; - - size_t ByteSizeLong() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const { - return InternalSerializeWithCachedSizesToArray(false, output); - } - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - void InternalSwap(ServiceResponse* other); - void UnsafeMergeFrom(const ServiceResponse& from); - private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return _internal_metadata_.arena(); - } - inline void* MaybeArenaPtr() const { - return _internal_metadata_.raw_arena_ptr(); - } - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional string name = 1; - void clear_name(); - static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - void set_name(const char* value); - void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); - - // @@protoc_insertion_point(class_scope:grpc.reflection.v1alpha.ServiceResponse) - private: - - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::ArenaStringPtr name_; - mutable int _cached_size_; - friend void protobuf_InitDefaults_reflection_2eproto_impl(); - friend void protobuf_AddDesc_reflection_2eproto_impl(); - friend void protobuf_AssignDesc_reflection_2eproto(); - friend void protobuf_ShutdownFile_reflection_2eproto(); - - void InitAsDefaultInstance(); -}; -extern ::google::protobuf::internal::ExplicitlyConstructed ServiceResponse_default_instance_; - -// ------------------------------------------------------------------- - -class ErrorResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:grpc.reflection.v1alpha.ErrorResponse) */ { - public: - ErrorResponse(); - virtual ~ErrorResponse(); - - ErrorResponse(const ErrorResponse& from); - - inline ErrorResponse& operator=(const ErrorResponse& from) { - CopyFrom(from); - return *this; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const ErrorResponse& default_instance(); - - static const ErrorResponse* internal_default_instance(); - - void Swap(ErrorResponse* other); - - // implements Message ---------------------------------------------- - - inline ErrorResponse* New() const { return New(NULL); } - - ErrorResponse* New(::google::protobuf::Arena* arena) const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const ErrorResponse& from); - void MergeFrom(const ErrorResponse& from); - void Clear(); - bool IsInitialized() const; - - size_t ByteSizeLong() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const { - return InternalSerializeWithCachedSizesToArray(false, output); - } - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - void InternalSwap(ErrorResponse* other); - void UnsafeMergeFrom(const ErrorResponse& from); - private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return _internal_metadata_.arena(); - } - inline void* MaybeArenaPtr() const { - return _internal_metadata_.raw_arena_ptr(); - } - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional int32 error_code = 1; - void clear_error_code(); - static const int kErrorCodeFieldNumber = 1; - ::google::protobuf::int32 error_code() const; - void set_error_code(::google::protobuf::int32 value); - - // optional string error_message = 2; - void clear_error_message(); - static const int kErrorMessageFieldNumber = 2; - const ::std::string& error_message() const; - void set_error_message(const ::std::string& value); - void set_error_message(const char* value); - void set_error_message(const char* value, size_t size); - ::std::string* mutable_error_message(); - ::std::string* release_error_message(); - void set_allocated_error_message(::std::string* error_message); - - // @@protoc_insertion_point(class_scope:grpc.reflection.v1alpha.ErrorResponse) - private: - - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::ArenaStringPtr error_message_; - ::google::protobuf::int32 error_code_; - mutable int _cached_size_; - friend void protobuf_InitDefaults_reflection_2eproto_impl(); - friend void protobuf_AddDesc_reflection_2eproto_impl(); - friend void protobuf_AssignDesc_reflection_2eproto(); - friend void protobuf_ShutdownFile_reflection_2eproto(); - - void InitAsDefaultInstance(); -}; -extern ::google::protobuf::internal::ExplicitlyConstructed ErrorResponse_default_instance_; - -// =================================================================== - - -// =================================================================== - -#if !PROTOBUF_INLINE_NOT_IN_HEADERS -// ServerReflectionRequest - -// optional string host = 1; -inline void ServerReflectionRequest::clear_host() { - host_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline const ::std::string& ServerReflectionRequest::host() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionRequest.host) - return host_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline void ServerReflectionRequest::set_host(const ::std::string& value) { - - host_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.host) -} -inline void ServerReflectionRequest::set_host(const char* value) { - - host_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ServerReflectionRequest.host) -} -inline void ServerReflectionRequest::set_host(const char* value, size_t size) { - - host_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ServerReflectionRequest.host) -} -inline ::std::string* ServerReflectionRequest::mutable_host() { - - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionRequest.host) - return host_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline ::std::string* ServerReflectionRequest::release_host() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionRequest.host) - - return host_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline void ServerReflectionRequest::set_allocated_host(::std::string* host) { - if (host != NULL) { - - } else { - - } - host_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), host); - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionRequest.host) -} - -// optional string file_by_filename = 3; -inline bool ServerReflectionRequest::has_file_by_filename() const { - return message_request_case() == kFileByFilename; -} -inline void ServerReflectionRequest::set_has_file_by_filename() { - _oneof_case_[0] = kFileByFilename; -} -inline void ServerReflectionRequest::clear_file_by_filename() { - if (has_file_by_filename()) { - message_request_.file_by_filename_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_message_request(); - } -} -inline const ::std::string& ServerReflectionRequest::file_by_filename() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename) - if (has_file_by_filename()) { - return message_request_.file_by_filename_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - return *&::google::protobuf::internal::GetEmptyStringAlreadyInited(); -} -inline void ServerReflectionRequest::set_file_by_filename(const ::std::string& value) { - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename) - if (!has_file_by_filename()) { - clear_message_request(); - set_has_file_by_filename(); - message_request_.file_by_filename_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.file_by_filename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename) -} -inline void ServerReflectionRequest::set_file_by_filename(const char* value) { - if (!has_file_by_filename()) { - clear_message_request(); - set_has_file_by_filename(); - message_request_.file_by_filename_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.file_by_filename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename) -} -inline void ServerReflectionRequest::set_file_by_filename(const char* value, size_t size) { - if (!has_file_by_filename()) { - clear_message_request(); - set_has_file_by_filename(); - message_request_.file_by_filename_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.file_by_filename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( - reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename) -} -inline ::std::string* ServerReflectionRequest::mutable_file_by_filename() { - if (!has_file_by_filename()) { - clear_message_request(); - set_has_file_by_filename(); - message_request_.file_by_filename_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename) - return message_request_.file_by_filename_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline ::std::string* ServerReflectionRequest::release_file_by_filename() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename) - if (has_file_by_filename()) { - clear_has_message_request(); - return message_request_.file_by_filename_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } else { - return NULL; - } -} -inline void ServerReflectionRequest::set_allocated_file_by_filename(::std::string* file_by_filename) { - if (!has_file_by_filename()) { - message_request_.file_by_filename_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - clear_message_request(); - if (file_by_filename != NULL) { - set_has_file_by_filename(); - message_request_.file_by_filename_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - file_by_filename); - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename) -} - -// optional string file_containing_symbol = 4; -inline bool ServerReflectionRequest::has_file_containing_symbol() const { - return message_request_case() == kFileContainingSymbol; -} -inline void ServerReflectionRequest::set_has_file_containing_symbol() { - _oneof_case_[0] = kFileContainingSymbol; -} -inline void ServerReflectionRequest::clear_file_containing_symbol() { - if (has_file_containing_symbol()) { - message_request_.file_containing_symbol_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_message_request(); - } -} -inline const ::std::string& ServerReflectionRequest::file_containing_symbol() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol) - if (has_file_containing_symbol()) { - return message_request_.file_containing_symbol_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - return *&::google::protobuf::internal::GetEmptyStringAlreadyInited(); -} -inline void ServerReflectionRequest::set_file_containing_symbol(const ::std::string& value) { - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol) - if (!has_file_containing_symbol()) { - clear_message_request(); - set_has_file_containing_symbol(); - message_request_.file_containing_symbol_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.file_containing_symbol_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol) -} -inline void ServerReflectionRequest::set_file_containing_symbol(const char* value) { - if (!has_file_containing_symbol()) { - clear_message_request(); - set_has_file_containing_symbol(); - message_request_.file_containing_symbol_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.file_containing_symbol_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol) -} -inline void ServerReflectionRequest::set_file_containing_symbol(const char* value, size_t size) { - if (!has_file_containing_symbol()) { - clear_message_request(); - set_has_file_containing_symbol(); - message_request_.file_containing_symbol_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.file_containing_symbol_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( - reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol) -} -inline ::std::string* ServerReflectionRequest::mutable_file_containing_symbol() { - if (!has_file_containing_symbol()) { - clear_message_request(); - set_has_file_containing_symbol(); - message_request_.file_containing_symbol_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol) - return message_request_.file_containing_symbol_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline ::std::string* ServerReflectionRequest::release_file_containing_symbol() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol) - if (has_file_containing_symbol()) { - clear_has_message_request(); - return message_request_.file_containing_symbol_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } else { - return NULL; - } -} -inline void ServerReflectionRequest::set_allocated_file_containing_symbol(::std::string* file_containing_symbol) { - if (!has_file_containing_symbol()) { - message_request_.file_containing_symbol_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - clear_message_request(); - if (file_containing_symbol != NULL) { - set_has_file_containing_symbol(); - message_request_.file_containing_symbol_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - file_containing_symbol); - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol) -} - -// optional .grpc.reflection.v1alpha.ExtensionRequest file_containing_extension = 5; -inline bool ServerReflectionRequest::has_file_containing_extension() const { - return message_request_case() == kFileContainingExtension; -} -inline void ServerReflectionRequest::set_has_file_containing_extension() { - _oneof_case_[0] = kFileContainingExtension; -} -inline void ServerReflectionRequest::clear_file_containing_extension() { - if (has_file_containing_extension()) { - delete message_request_.file_containing_extension_; - clear_has_message_request(); - } -} -inline const ::grpc::reflection::v1alpha::ExtensionRequest& ServerReflectionRequest::file_containing_extension() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_extension) - return has_file_containing_extension() - ? *message_request_.file_containing_extension_ - : ::grpc::reflection::v1alpha::ExtensionRequest::default_instance(); -} -inline ::grpc::reflection::v1alpha::ExtensionRequest* ServerReflectionRequest::mutable_file_containing_extension() { - if (!has_file_containing_extension()) { - clear_message_request(); - set_has_file_containing_extension(); - message_request_.file_containing_extension_ = new ::grpc::reflection::v1alpha::ExtensionRequest; - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_extension) - return message_request_.file_containing_extension_; -} -inline ::grpc::reflection::v1alpha::ExtensionRequest* ServerReflectionRequest::release_file_containing_extension() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_extension) - if (has_file_containing_extension()) { - clear_has_message_request(); - ::grpc::reflection::v1alpha::ExtensionRequest* temp = message_request_.file_containing_extension_; - message_request_.file_containing_extension_ = NULL; - return temp; - } else { - return NULL; - } -} -inline void ServerReflectionRequest::set_allocated_file_containing_extension(::grpc::reflection::v1alpha::ExtensionRequest* file_containing_extension) { - clear_message_request(); - if (file_containing_extension) { - set_has_file_containing_extension(); - message_request_.file_containing_extension_ = file_containing_extension; - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_extension) -} - -// optional string all_extension_numbers_of_type = 6; -inline bool ServerReflectionRequest::has_all_extension_numbers_of_type() const { - return message_request_case() == kAllExtensionNumbersOfType; -} -inline void ServerReflectionRequest::set_has_all_extension_numbers_of_type() { - _oneof_case_[0] = kAllExtensionNumbersOfType; -} -inline void ServerReflectionRequest::clear_all_extension_numbers_of_type() { - if (has_all_extension_numbers_of_type()) { - message_request_.all_extension_numbers_of_type_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_message_request(); - } -} -inline const ::std::string& ServerReflectionRequest::all_extension_numbers_of_type() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type) - if (has_all_extension_numbers_of_type()) { - return message_request_.all_extension_numbers_of_type_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - return *&::google::protobuf::internal::GetEmptyStringAlreadyInited(); -} -inline void ServerReflectionRequest::set_all_extension_numbers_of_type(const ::std::string& value) { - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type) - if (!has_all_extension_numbers_of_type()) { - clear_message_request(); - set_has_all_extension_numbers_of_type(); - message_request_.all_extension_numbers_of_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.all_extension_numbers_of_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type) -} -inline void ServerReflectionRequest::set_all_extension_numbers_of_type(const char* value) { - if (!has_all_extension_numbers_of_type()) { - clear_message_request(); - set_has_all_extension_numbers_of_type(); - message_request_.all_extension_numbers_of_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.all_extension_numbers_of_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type) -} -inline void ServerReflectionRequest::set_all_extension_numbers_of_type(const char* value, size_t size) { - if (!has_all_extension_numbers_of_type()) { - clear_message_request(); - set_has_all_extension_numbers_of_type(); - message_request_.all_extension_numbers_of_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.all_extension_numbers_of_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( - reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type) -} -inline ::std::string* ServerReflectionRequest::mutable_all_extension_numbers_of_type() { - if (!has_all_extension_numbers_of_type()) { - clear_message_request(); - set_has_all_extension_numbers_of_type(); - message_request_.all_extension_numbers_of_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type) - return message_request_.all_extension_numbers_of_type_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline ::std::string* ServerReflectionRequest::release_all_extension_numbers_of_type() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type) - if (has_all_extension_numbers_of_type()) { - clear_has_message_request(); - return message_request_.all_extension_numbers_of_type_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } else { - return NULL; - } -} -inline void ServerReflectionRequest::set_allocated_all_extension_numbers_of_type(::std::string* all_extension_numbers_of_type) { - if (!has_all_extension_numbers_of_type()) { - message_request_.all_extension_numbers_of_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - clear_message_request(); - if (all_extension_numbers_of_type != NULL) { - set_has_all_extension_numbers_of_type(); - message_request_.all_extension_numbers_of_type_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - all_extension_numbers_of_type); - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type) -} - -// optional string list_services = 7; -inline bool ServerReflectionRequest::has_list_services() const { - return message_request_case() == kListServices; -} -inline void ServerReflectionRequest::set_has_list_services() { - _oneof_case_[0] = kListServices; -} -inline void ServerReflectionRequest::clear_list_services() { - if (has_list_services()) { - message_request_.list_services_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_message_request(); - } -} -inline const ::std::string& ServerReflectionRequest::list_services() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionRequest.list_services) - if (has_list_services()) { - return message_request_.list_services_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - return *&::google::protobuf::internal::GetEmptyStringAlreadyInited(); -} -inline void ServerReflectionRequest::set_list_services(const ::std::string& value) { - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.list_services) - if (!has_list_services()) { - clear_message_request(); - set_has_list_services(); - message_request_.list_services_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.list_services_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.list_services) -} -inline void ServerReflectionRequest::set_list_services(const char* value) { - if (!has_list_services()) { - clear_message_request(); - set_has_list_services(); - message_request_.list_services_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.list_services_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ServerReflectionRequest.list_services) -} -inline void ServerReflectionRequest::set_list_services(const char* value, size_t size) { - if (!has_list_services()) { - clear_message_request(); - set_has_list_services(); - message_request_.list_services_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.list_services_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( - reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ServerReflectionRequest.list_services) -} -inline ::std::string* ServerReflectionRequest::mutable_list_services() { - if (!has_list_services()) { - clear_message_request(); - set_has_list_services(); - message_request_.list_services_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionRequest.list_services) - return message_request_.list_services_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline ::std::string* ServerReflectionRequest::release_list_services() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionRequest.list_services) - if (has_list_services()) { - clear_has_message_request(); - return message_request_.list_services_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } else { - return NULL; - } -} -inline void ServerReflectionRequest::set_allocated_list_services(::std::string* list_services) { - if (!has_list_services()) { - message_request_.list_services_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - clear_message_request(); - if (list_services != NULL) { - set_has_list_services(); - message_request_.list_services_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - list_services); - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionRequest.list_services) -} - -inline bool ServerReflectionRequest::has_message_request() const { - return message_request_case() != MESSAGE_REQUEST_NOT_SET; -} -inline void ServerReflectionRequest::clear_has_message_request() { - _oneof_case_[0] = MESSAGE_REQUEST_NOT_SET; -} -inline ServerReflectionRequest::MessageRequestCase ServerReflectionRequest::message_request_case() const { - return ServerReflectionRequest::MessageRequestCase(_oneof_case_[0]); -} -inline const ServerReflectionRequest* ServerReflectionRequest::internal_default_instance() { - return &ServerReflectionRequest_default_instance_.get(); -} -// ------------------------------------------------------------------- - -// ExtensionRequest - -// optional string containing_type = 1; -inline void ExtensionRequest::clear_containing_type() { - containing_type_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline const ::std::string& ExtensionRequest::containing_type() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ExtensionRequest.containing_type) - return containing_type_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline void ExtensionRequest::set_containing_type(const ::std::string& value) { - - containing_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ExtensionRequest.containing_type) -} -inline void ExtensionRequest::set_containing_type(const char* value) { - - containing_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ExtensionRequest.containing_type) -} -inline void ExtensionRequest::set_containing_type(const char* value, size_t size) { - - containing_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ExtensionRequest.containing_type) -} -inline ::std::string* ExtensionRequest::mutable_containing_type() { - - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ExtensionRequest.containing_type) - return containing_type_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline ::std::string* ExtensionRequest::release_containing_type() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ExtensionRequest.containing_type) - - return containing_type_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline void ExtensionRequest::set_allocated_containing_type(::std::string* containing_type) { - if (containing_type != NULL) { - - } else { - - } - containing_type_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), containing_type); - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ExtensionRequest.containing_type) -} - -// optional int32 extension_number = 2; -inline void ExtensionRequest::clear_extension_number() { - extension_number_ = 0; -} -inline ::google::protobuf::int32 ExtensionRequest::extension_number() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ExtensionRequest.extension_number) - return extension_number_; -} -inline void ExtensionRequest::set_extension_number(::google::protobuf::int32 value) { - - extension_number_ = value; - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ExtensionRequest.extension_number) -} - -inline const ExtensionRequest* ExtensionRequest::internal_default_instance() { - return &ExtensionRequest_default_instance_.get(); -} -// ------------------------------------------------------------------- - -// ServerReflectionResponse - -// optional string valid_host = 1; -inline void ServerReflectionResponse::clear_valid_host() { - valid_host_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline const ::std::string& ServerReflectionResponse::valid_host() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionResponse.valid_host) - return valid_host_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline void ServerReflectionResponse::set_valid_host(const ::std::string& value) { - - valid_host_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionResponse.valid_host) -} -inline void ServerReflectionResponse::set_valid_host(const char* value) { - - valid_host_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ServerReflectionResponse.valid_host) -} -inline void ServerReflectionResponse::set_valid_host(const char* value, size_t size) { - - valid_host_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ServerReflectionResponse.valid_host) -} -inline ::std::string* ServerReflectionResponse::mutable_valid_host() { - - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionResponse.valid_host) - return valid_host_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline ::std::string* ServerReflectionResponse::release_valid_host() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionResponse.valid_host) - - return valid_host_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline void ServerReflectionResponse::set_allocated_valid_host(::std::string* valid_host) { - if (valid_host != NULL) { - - } else { - - } - valid_host_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), valid_host); - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionResponse.valid_host) -} - -// optional .grpc.reflection.v1alpha.ServerReflectionRequest original_request = 2; -inline bool ServerReflectionResponse::has_original_request() const { - return this != internal_default_instance() && original_request_ != NULL; -} -inline void ServerReflectionResponse::clear_original_request() { - if (GetArenaNoVirtual() == NULL && original_request_ != NULL) delete original_request_; - original_request_ = NULL; -} -inline const ::grpc::reflection::v1alpha::ServerReflectionRequest& ServerReflectionResponse::original_request() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionResponse.original_request) - return original_request_ != NULL ? *original_request_ - : *::grpc::reflection::v1alpha::ServerReflectionRequest::internal_default_instance(); -} -inline ::grpc::reflection::v1alpha::ServerReflectionRequest* ServerReflectionResponse::mutable_original_request() { - - if (original_request_ == NULL) { - original_request_ = new ::grpc::reflection::v1alpha::ServerReflectionRequest; - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionResponse.original_request) - return original_request_; -} -inline ::grpc::reflection::v1alpha::ServerReflectionRequest* ServerReflectionResponse::release_original_request() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionResponse.original_request) - - ::grpc::reflection::v1alpha::ServerReflectionRequest* temp = original_request_; - original_request_ = NULL; - return temp; -} -inline void ServerReflectionResponse::set_allocated_original_request(::grpc::reflection::v1alpha::ServerReflectionRequest* original_request) { - delete original_request_; - original_request_ = original_request; - if (original_request) { - - } else { - - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionResponse.original_request) -} - -// optional .grpc.reflection.v1alpha.FileDescriptorResponse file_descriptor_response = 4; -inline bool ServerReflectionResponse::has_file_descriptor_response() const { - return message_response_case() == kFileDescriptorResponse; -} -inline void ServerReflectionResponse::set_has_file_descriptor_response() { - _oneof_case_[0] = kFileDescriptorResponse; -} -inline void ServerReflectionResponse::clear_file_descriptor_response() { - if (has_file_descriptor_response()) { - delete message_response_.file_descriptor_response_; - clear_has_message_response(); - } -} -inline const ::grpc::reflection::v1alpha::FileDescriptorResponse& ServerReflectionResponse::file_descriptor_response() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionResponse.file_descriptor_response) - return has_file_descriptor_response() - ? *message_response_.file_descriptor_response_ - : ::grpc::reflection::v1alpha::FileDescriptorResponse::default_instance(); -} -inline ::grpc::reflection::v1alpha::FileDescriptorResponse* ServerReflectionResponse::mutable_file_descriptor_response() { - if (!has_file_descriptor_response()) { - clear_message_response(); - set_has_file_descriptor_response(); - message_response_.file_descriptor_response_ = new ::grpc::reflection::v1alpha::FileDescriptorResponse; - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionResponse.file_descriptor_response) - return message_response_.file_descriptor_response_; -} -inline ::grpc::reflection::v1alpha::FileDescriptorResponse* ServerReflectionResponse::release_file_descriptor_response() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionResponse.file_descriptor_response) - if (has_file_descriptor_response()) { - clear_has_message_response(); - ::grpc::reflection::v1alpha::FileDescriptorResponse* temp = message_response_.file_descriptor_response_; - message_response_.file_descriptor_response_ = NULL; - return temp; - } else { - return NULL; - } -} -inline void ServerReflectionResponse::set_allocated_file_descriptor_response(::grpc::reflection::v1alpha::FileDescriptorResponse* file_descriptor_response) { - clear_message_response(); - if (file_descriptor_response) { - set_has_file_descriptor_response(); - message_response_.file_descriptor_response_ = file_descriptor_response; - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionResponse.file_descriptor_response) -} - -// optional .grpc.reflection.v1alpha.ExtensionNumberResponse all_extension_numbers_response = 5; -inline bool ServerReflectionResponse::has_all_extension_numbers_response() const { - return message_response_case() == kAllExtensionNumbersResponse; -} -inline void ServerReflectionResponse::set_has_all_extension_numbers_response() { - _oneof_case_[0] = kAllExtensionNumbersResponse; -} -inline void ServerReflectionResponse::clear_all_extension_numbers_response() { - if (has_all_extension_numbers_response()) { - delete message_response_.all_extension_numbers_response_; - clear_has_message_response(); - } -} -inline const ::grpc::reflection::v1alpha::ExtensionNumberResponse& ServerReflectionResponse::all_extension_numbers_response() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionResponse.all_extension_numbers_response) - return has_all_extension_numbers_response() - ? *message_response_.all_extension_numbers_response_ - : ::grpc::reflection::v1alpha::ExtensionNumberResponse::default_instance(); -} -inline ::grpc::reflection::v1alpha::ExtensionNumberResponse* ServerReflectionResponse::mutable_all_extension_numbers_response() { - if (!has_all_extension_numbers_response()) { - clear_message_response(); - set_has_all_extension_numbers_response(); - message_response_.all_extension_numbers_response_ = new ::grpc::reflection::v1alpha::ExtensionNumberResponse; - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionResponse.all_extension_numbers_response) - return message_response_.all_extension_numbers_response_; -} -inline ::grpc::reflection::v1alpha::ExtensionNumberResponse* ServerReflectionResponse::release_all_extension_numbers_response() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionResponse.all_extension_numbers_response) - if (has_all_extension_numbers_response()) { - clear_has_message_response(); - ::grpc::reflection::v1alpha::ExtensionNumberResponse* temp = message_response_.all_extension_numbers_response_; - message_response_.all_extension_numbers_response_ = NULL; - return temp; - } else { - return NULL; - } -} -inline void ServerReflectionResponse::set_allocated_all_extension_numbers_response(::grpc::reflection::v1alpha::ExtensionNumberResponse* all_extension_numbers_response) { - clear_message_response(); - if (all_extension_numbers_response) { - set_has_all_extension_numbers_response(); - message_response_.all_extension_numbers_response_ = all_extension_numbers_response; - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionResponse.all_extension_numbers_response) -} - -// optional .grpc.reflection.v1alpha.ListServiceResponse list_services_response = 6; -inline bool ServerReflectionResponse::has_list_services_response() const { - return message_response_case() == kListServicesResponse; -} -inline void ServerReflectionResponse::set_has_list_services_response() { - _oneof_case_[0] = kListServicesResponse; -} -inline void ServerReflectionResponse::clear_list_services_response() { - if (has_list_services_response()) { - delete message_response_.list_services_response_; - clear_has_message_response(); - } -} -inline const ::grpc::reflection::v1alpha::ListServiceResponse& ServerReflectionResponse::list_services_response() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionResponse.list_services_response) - return has_list_services_response() - ? *message_response_.list_services_response_ - : ::grpc::reflection::v1alpha::ListServiceResponse::default_instance(); -} -inline ::grpc::reflection::v1alpha::ListServiceResponse* ServerReflectionResponse::mutable_list_services_response() { - if (!has_list_services_response()) { - clear_message_response(); - set_has_list_services_response(); - message_response_.list_services_response_ = new ::grpc::reflection::v1alpha::ListServiceResponse; - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionResponse.list_services_response) - return message_response_.list_services_response_; -} -inline ::grpc::reflection::v1alpha::ListServiceResponse* ServerReflectionResponse::release_list_services_response() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionResponse.list_services_response) - if (has_list_services_response()) { - clear_has_message_response(); - ::grpc::reflection::v1alpha::ListServiceResponse* temp = message_response_.list_services_response_; - message_response_.list_services_response_ = NULL; - return temp; - } else { - return NULL; - } -} -inline void ServerReflectionResponse::set_allocated_list_services_response(::grpc::reflection::v1alpha::ListServiceResponse* list_services_response) { - clear_message_response(); - if (list_services_response) { - set_has_list_services_response(); - message_response_.list_services_response_ = list_services_response; - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionResponse.list_services_response) -} - -// optional .grpc.reflection.v1alpha.ErrorResponse error_response = 7; -inline bool ServerReflectionResponse::has_error_response() const { - return message_response_case() == kErrorResponse; -} -inline void ServerReflectionResponse::set_has_error_response() { - _oneof_case_[0] = kErrorResponse; -} -inline void ServerReflectionResponse::clear_error_response() { - if (has_error_response()) { - delete message_response_.error_response_; - clear_has_message_response(); - } -} -inline const ::grpc::reflection::v1alpha::ErrorResponse& ServerReflectionResponse::error_response() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionResponse.error_response) - return has_error_response() - ? *message_response_.error_response_ - : ::grpc::reflection::v1alpha::ErrorResponse::default_instance(); -} -inline ::grpc::reflection::v1alpha::ErrorResponse* ServerReflectionResponse::mutable_error_response() { - if (!has_error_response()) { - clear_message_response(); - set_has_error_response(); - message_response_.error_response_ = new ::grpc::reflection::v1alpha::ErrorResponse; - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionResponse.error_response) - return message_response_.error_response_; -} -inline ::grpc::reflection::v1alpha::ErrorResponse* ServerReflectionResponse::release_error_response() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionResponse.error_response) - if (has_error_response()) { - clear_has_message_response(); - ::grpc::reflection::v1alpha::ErrorResponse* temp = message_response_.error_response_; - message_response_.error_response_ = NULL; - return temp; - } else { - return NULL; - } -} -inline void ServerReflectionResponse::set_allocated_error_response(::grpc::reflection::v1alpha::ErrorResponse* error_response) { - clear_message_response(); - if (error_response) { - set_has_error_response(); - message_response_.error_response_ = error_response; - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionResponse.error_response) -} - -inline bool ServerReflectionResponse::has_message_response() const { - return message_response_case() != MESSAGE_RESPONSE_NOT_SET; -} -inline void ServerReflectionResponse::clear_has_message_response() { - _oneof_case_[0] = MESSAGE_RESPONSE_NOT_SET; -} -inline ServerReflectionResponse::MessageResponseCase ServerReflectionResponse::message_response_case() const { - return ServerReflectionResponse::MessageResponseCase(_oneof_case_[0]); -} -inline const ServerReflectionResponse* ServerReflectionResponse::internal_default_instance() { - return &ServerReflectionResponse_default_instance_.get(); -} -// ------------------------------------------------------------------- - -// FileDescriptorResponse - -// repeated bytes file_descriptor_proto = 1; -inline int FileDescriptorResponse::file_descriptor_proto_size() const { - return file_descriptor_proto_.size(); -} -inline void FileDescriptorResponse::clear_file_descriptor_proto() { - file_descriptor_proto_.Clear(); -} -inline const ::std::string& FileDescriptorResponse::file_descriptor_proto(int index) const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) - return file_descriptor_proto_.Get(index); -} -inline ::std::string* FileDescriptorResponse::mutable_file_descriptor_proto(int index) { - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) - return file_descriptor_proto_.Mutable(index); -} -inline void FileDescriptorResponse::set_file_descriptor_proto(int index, const ::std::string& value) { - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) - file_descriptor_proto_.Mutable(index)->assign(value); -} -inline void FileDescriptorResponse::set_file_descriptor_proto(int index, const char* value) { - file_descriptor_proto_.Mutable(index)->assign(value); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) -} -inline void FileDescriptorResponse::set_file_descriptor_proto(int index, const void* value, size_t size) { - file_descriptor_proto_.Mutable(index)->assign( - reinterpret_cast(value), size); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) -} -inline ::std::string* FileDescriptorResponse::add_file_descriptor_proto() { - // @@protoc_insertion_point(field_add_mutable:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) - return file_descriptor_proto_.Add(); -} -inline void FileDescriptorResponse::add_file_descriptor_proto(const ::std::string& value) { - file_descriptor_proto_.Add()->assign(value); - // @@protoc_insertion_point(field_add:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) -} -inline void FileDescriptorResponse::add_file_descriptor_proto(const char* value) { - file_descriptor_proto_.Add()->assign(value); - // @@protoc_insertion_point(field_add_char:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) -} -inline void FileDescriptorResponse::add_file_descriptor_proto(const void* value, size_t size) { - file_descriptor_proto_.Add()->assign(reinterpret_cast(value), size); - // @@protoc_insertion_point(field_add_pointer:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) -} -inline const ::google::protobuf::RepeatedPtrField< ::std::string>& -FileDescriptorResponse::file_descriptor_proto() const { - // @@protoc_insertion_point(field_list:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) - return file_descriptor_proto_; -} -inline ::google::protobuf::RepeatedPtrField< ::std::string>* -FileDescriptorResponse::mutable_file_descriptor_proto() { - // @@protoc_insertion_point(field_mutable_list:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) - return &file_descriptor_proto_; -} - -inline const FileDescriptorResponse* FileDescriptorResponse::internal_default_instance() { - return &FileDescriptorResponse_default_instance_.get(); -} -// ------------------------------------------------------------------- - -// ExtensionNumberResponse - -// optional string base_type_name = 1; -inline void ExtensionNumberResponse::clear_base_type_name() { - base_type_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline const ::std::string& ExtensionNumberResponse::base_type_name() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name) - return base_type_name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline void ExtensionNumberResponse::set_base_type_name(const ::std::string& value) { - - base_type_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name) -} -inline void ExtensionNumberResponse::set_base_type_name(const char* value) { - - base_type_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name) -} -inline void ExtensionNumberResponse::set_base_type_name(const char* value, size_t size) { - - base_type_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name) -} -inline ::std::string* ExtensionNumberResponse::mutable_base_type_name() { - - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name) - return base_type_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline ::std::string* ExtensionNumberResponse::release_base_type_name() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name) - - return base_type_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline void ExtensionNumberResponse::set_allocated_base_type_name(::std::string* base_type_name) { - if (base_type_name != NULL) { - - } else { - - } - base_type_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), base_type_name); - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name) -} - -// repeated int32 extension_number = 2; -inline int ExtensionNumberResponse::extension_number_size() const { - return extension_number_.size(); -} -inline void ExtensionNumberResponse::clear_extension_number() { - extension_number_.Clear(); -} -inline ::google::protobuf::int32 ExtensionNumberResponse::extension_number(int index) const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ExtensionNumberResponse.extension_number) - return extension_number_.Get(index); -} -inline void ExtensionNumberResponse::set_extension_number(int index, ::google::protobuf::int32 value) { - extension_number_.Set(index, value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ExtensionNumberResponse.extension_number) -} -inline void ExtensionNumberResponse::add_extension_number(::google::protobuf::int32 value) { - extension_number_.Add(value); - // @@protoc_insertion_point(field_add:grpc.reflection.v1alpha.ExtensionNumberResponse.extension_number) -} -inline const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& -ExtensionNumberResponse::extension_number() const { - // @@protoc_insertion_point(field_list:grpc.reflection.v1alpha.ExtensionNumberResponse.extension_number) - return extension_number_; -} -inline ::google::protobuf::RepeatedField< ::google::protobuf::int32 >* -ExtensionNumberResponse::mutable_extension_number() { - // @@protoc_insertion_point(field_mutable_list:grpc.reflection.v1alpha.ExtensionNumberResponse.extension_number) - return &extension_number_; -} - -inline const ExtensionNumberResponse* ExtensionNumberResponse::internal_default_instance() { - return &ExtensionNumberResponse_default_instance_.get(); -} -// ------------------------------------------------------------------- - -// ListServiceResponse - -// repeated .grpc.reflection.v1alpha.ServiceResponse service = 1; -inline int ListServiceResponse::service_size() const { - return service_.size(); -} -inline void ListServiceResponse::clear_service() { - service_.Clear(); -} -inline const ::grpc::reflection::v1alpha::ServiceResponse& ListServiceResponse::service(int index) const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ListServiceResponse.service) - return service_.Get(index); -} -inline ::grpc::reflection::v1alpha::ServiceResponse* ListServiceResponse::mutable_service(int index) { - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ListServiceResponse.service) - return service_.Mutable(index); -} -inline ::grpc::reflection::v1alpha::ServiceResponse* ListServiceResponse::add_service() { - // @@protoc_insertion_point(field_add:grpc.reflection.v1alpha.ListServiceResponse.service) - return service_.Add(); -} -inline ::google::protobuf::RepeatedPtrField< ::grpc::reflection::v1alpha::ServiceResponse >* -ListServiceResponse::mutable_service() { - // @@protoc_insertion_point(field_mutable_list:grpc.reflection.v1alpha.ListServiceResponse.service) - return &service_; -} -inline const ::google::protobuf::RepeatedPtrField< ::grpc::reflection::v1alpha::ServiceResponse >& -ListServiceResponse::service() const { - // @@protoc_insertion_point(field_list:grpc.reflection.v1alpha.ListServiceResponse.service) - return service_; -} - -inline const ListServiceResponse* ListServiceResponse::internal_default_instance() { - return &ListServiceResponse_default_instance_.get(); -} -// ------------------------------------------------------------------- - -// ServiceResponse - -// optional string name = 1; -inline void ServiceResponse::clear_name() { - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline const ::std::string& ServiceResponse::name() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServiceResponse.name) - return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline void ServiceResponse::set_name(const ::std::string& value) { - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServiceResponse.name) -} -inline void ServiceResponse::set_name(const char* value) { - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ServiceResponse.name) -} -inline void ServiceResponse::set_name(const char* value, size_t size) { - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ServiceResponse.name) -} -inline ::std::string* ServiceResponse::mutable_name() { - - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServiceResponse.name) - return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline ::std::string* ServiceResponse::release_name() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServiceResponse.name) - - return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline void ServiceResponse::set_allocated_name(::std::string* name) { - if (name != NULL) { - - } else { - - } - name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServiceResponse.name) -} - -inline const ServiceResponse* ServiceResponse::internal_default_instance() { - return &ServiceResponse_default_instance_.get(); -} -// ------------------------------------------------------------------- - -// ErrorResponse - -// optional int32 error_code = 1; -inline void ErrorResponse::clear_error_code() { - error_code_ = 0; -} -inline ::google::protobuf::int32 ErrorResponse::error_code() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ErrorResponse.error_code) - return error_code_; -} -inline void ErrorResponse::set_error_code(::google::protobuf::int32 value) { - - error_code_ = value; - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ErrorResponse.error_code) -} - -// optional string error_message = 2; -inline void ErrorResponse::clear_error_message() { - error_message_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline const ::std::string& ErrorResponse::error_message() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ErrorResponse.error_message) - return error_message_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline void ErrorResponse::set_error_message(const ::std::string& value) { - - error_message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ErrorResponse.error_message) -} -inline void ErrorResponse::set_error_message(const char* value) { - - error_message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ErrorResponse.error_message) -} -inline void ErrorResponse::set_error_message(const char* value, size_t size) { - - error_message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ErrorResponse.error_message) -} -inline ::std::string* ErrorResponse::mutable_error_message() { - - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ErrorResponse.error_message) - return error_message_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline ::std::string* ErrorResponse::release_error_message() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ErrorResponse.error_message) - - return error_message_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -inline void ErrorResponse::set_allocated_error_message(::std::string* error_message) { - if (error_message != NULL) { - - } else { - - } - error_message_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), error_message); - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ErrorResponse.error_message) -} - -inline const ErrorResponse* ErrorResponse::internal_default_instance() { - return &ErrorResponse_default_instance_.get(); -} -#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - - -// @@protoc_insertion_point(namespace_scope) - -} // namespace v1alpha -} // namespace reflection -} // namespace grpc - -// @@protoc_insertion_point(global_scope) - -#endif // PROTOBUF_reflection_2eproto__INCLUDED diff --git a/include/grpc++/generic/async_generic_service.h b/include/grpc++/generic/async_generic_service.h index 24bae521452..66a5d01d96d 100644 --- a/include/grpc++/generic/async_generic_service.h +++ b/include/grpc++/generic/async_generic_service.h @@ -44,7 +44,7 @@ namespace grpc { typedef ServerAsyncReaderWriter GenericServerAsyncReaderWriter; -class GenericServerContext GRPC_FINAL : public ServerContext { +class GenericServerContext final : public ServerContext { public: const grpc::string& method() const { return method_; } const grpc::string& host() const { return host_; } @@ -57,7 +57,7 @@ class GenericServerContext GRPC_FINAL : public ServerContext { grpc::string host_; }; -class AsyncGenericService GRPC_FINAL { +class AsyncGenericService final { public: AsyncGenericService() : server_(nullptr) {} diff --git a/include/grpc++/generic/generic_stub.h b/include/grpc++/generic/generic_stub.h index d27deae33a5..02c00d0d45c 100644 --- a/include/grpc++/generic/generic_stub.h +++ b/include/grpc++/generic/generic_stub.h @@ -45,7 +45,7 @@ typedef ClientAsyncReaderWriter // Generic stubs provide a type-unsafe interface to call gRPC methods // by name. -class GenericStub GRPC_FINAL { +class GenericStub final { public: explicit GenericStub(std::shared_ptr channel) : channel_(channel) {} diff --git a/include/grpc++/impl/codegen/async_stream.h b/include/grpc++/impl/codegen/async_stream.h index 70533aa4d9f..1a5cbbd45da 100644 --- a/include/grpc++/impl/codegen/async_stream.h +++ b/include/grpc++/impl/codegen/async_stream.h @@ -108,7 +108,7 @@ class ClientAsyncReaderInterface : public ClientAsyncStreamingInterface, public AsyncReaderInterface {}; template -class ClientAsyncReader GRPC_FINAL : public ClientAsyncReaderInterface { +class ClientAsyncReader final : public ClientAsyncReaderInterface { public: /// Create a stream and write the first request out. template @@ -125,7 +125,7 @@ class ClientAsyncReader GRPC_FINAL : public ClientAsyncReaderInterface { call_.PerformOps(&init_ops_); } - void ReadInitialMetadata(void* tag) GRPC_OVERRIDE { + void ReadInitialMetadata(void* tag) override { GPR_CODEGEN_ASSERT(!context_->initial_metadata_received_); meta_ops_.set_output_tag(tag); @@ -133,7 +133,7 @@ class ClientAsyncReader GRPC_FINAL : public ClientAsyncReaderInterface { call_.PerformOps(&meta_ops_); } - void Read(R* msg, void* tag) GRPC_OVERRIDE { + void Read(R* msg, void* tag) override { read_ops_.set_output_tag(tag); if (!context_->initial_metadata_received_) { read_ops_.RecvInitialMetadata(context_); @@ -142,7 +142,7 @@ class ClientAsyncReader GRPC_FINAL : public ClientAsyncReaderInterface { call_.PerformOps(&read_ops_); } - void Finish(Status* status, void* tag) GRPC_OVERRIDE { + void Finish(Status* status, void* tag) override { finish_ops_.set_output_tag(tag); if (!context_->initial_metadata_received_) { finish_ops_.RecvInitialMetadata(context_); @@ -174,7 +174,7 @@ class ClientAsyncWriterInterface : public ClientAsyncStreamingInterface, }; template -class ClientAsyncWriter GRPC_FINAL : public ClientAsyncWriterInterface { +class ClientAsyncWriter final : public ClientAsyncWriterInterface { public: template ClientAsyncWriter(ChannelInterface* channel, CompletionQueue* cq, @@ -190,7 +190,7 @@ class ClientAsyncWriter GRPC_FINAL : public ClientAsyncWriterInterface { call_.PerformOps(&init_ops_); } - void ReadInitialMetadata(void* tag) GRPC_OVERRIDE { + void ReadInitialMetadata(void* tag) override { GPR_CODEGEN_ASSERT(!context_->initial_metadata_received_); meta_ops_.set_output_tag(tag); @@ -198,20 +198,20 @@ class ClientAsyncWriter GRPC_FINAL : public ClientAsyncWriterInterface { call_.PerformOps(&meta_ops_); } - void Write(const W& msg, void* tag) GRPC_OVERRIDE { + void Write(const W& msg, void* tag) override { write_ops_.set_output_tag(tag); // TODO(ctiller): don't assert GPR_CODEGEN_ASSERT(write_ops_.SendMessage(msg).ok()); call_.PerformOps(&write_ops_); } - void WritesDone(void* tag) GRPC_OVERRIDE { + void WritesDone(void* tag) override { writes_done_ops_.set_output_tag(tag); writes_done_ops_.ClientSendClose(); call_.PerformOps(&writes_done_ops_); } - void Finish(Status* status, void* tag) GRPC_OVERRIDE { + void Finish(Status* status, void* tag) override { finish_ops_.set_output_tag(tag); if (!context_->initial_metadata_received_) { finish_ops_.RecvInitialMetadata(context_); @@ -246,7 +246,7 @@ class ClientAsyncReaderWriterInterface : public ClientAsyncStreamingInterface, }; template -class ClientAsyncReaderWriter GRPC_FINAL +class ClientAsyncReaderWriter final : public ClientAsyncReaderWriterInterface { public: ClientAsyncReaderWriter(ChannelInterface* channel, CompletionQueue* cq, @@ -259,7 +259,7 @@ class ClientAsyncReaderWriter GRPC_FINAL call_.PerformOps(&init_ops_); } - void ReadInitialMetadata(void* tag) GRPC_OVERRIDE { + void ReadInitialMetadata(void* tag) override { GPR_CODEGEN_ASSERT(!context_->initial_metadata_received_); meta_ops_.set_output_tag(tag); @@ -267,7 +267,7 @@ class ClientAsyncReaderWriter GRPC_FINAL call_.PerformOps(&meta_ops_); } - void Read(R* msg, void* tag) GRPC_OVERRIDE { + void Read(R* msg, void* tag) override { read_ops_.set_output_tag(tag); if (!context_->initial_metadata_received_) { read_ops_.RecvInitialMetadata(context_); @@ -276,20 +276,20 @@ class ClientAsyncReaderWriter GRPC_FINAL call_.PerformOps(&read_ops_); } - void Write(const W& msg, void* tag) GRPC_OVERRIDE { + void Write(const W& msg, void* tag) override { write_ops_.set_output_tag(tag); // TODO(ctiller): don't assert GPR_CODEGEN_ASSERT(write_ops_.SendMessage(msg).ok()); call_.PerformOps(&write_ops_); } - void WritesDone(void* tag) GRPC_OVERRIDE { + void WritesDone(void* tag) override { writes_done_ops_.set_output_tag(tag); writes_done_ops_.ClientSendClose(); call_.PerformOps(&writes_done_ops_); } - void Finish(Status* status, void* tag) GRPC_OVERRIDE { + void Finish(Status* status, void* tag) override { finish_ops_.set_output_tag(tag); if (!context_->initial_metadata_received_) { finish_ops_.RecvInitialMetadata(context_); @@ -319,12 +319,12 @@ class ServerAsyncReaderInterface : public ServerAsyncStreamingInterface, }; template -class ServerAsyncReader GRPC_FINAL : public ServerAsyncReaderInterface { +class ServerAsyncReader final : public ServerAsyncReaderInterface { public: explicit ServerAsyncReader(ServerContext* ctx) : call_(nullptr, nullptr, nullptr), ctx_(ctx) {} - void SendInitialMetadata(void* tag) GRPC_OVERRIDE { + void SendInitialMetadata(void* tag) override { GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_); meta_ops_.set_output_tag(tag); @@ -337,13 +337,13 @@ class ServerAsyncReader GRPC_FINAL : public ServerAsyncReaderInterface { call_.PerformOps(&meta_ops_); } - void Read(R* msg, void* tag) GRPC_OVERRIDE { + void Read(R* msg, void* tag) override { read_ops_.set_output_tag(tag); read_ops_.RecvMessage(msg); call_.PerformOps(&read_ops_); } - void Finish(const W& msg, const Status& status, void* tag) GRPC_OVERRIDE { + void Finish(const W& msg, const Status& status, void* tag) override { finish_ops_.set_output_tag(tag); if (!ctx_->sent_initial_metadata_) { finish_ops_.SendInitialMetadata(ctx_->initial_metadata_, @@ -363,7 +363,7 @@ class ServerAsyncReader GRPC_FINAL : public ServerAsyncReaderInterface { call_.PerformOps(&finish_ops_); } - void FinishWithError(const Status& status, void* tag) GRPC_OVERRIDE { + void FinishWithError(const Status& status, void* tag) override { GPR_CODEGEN_ASSERT(!status.ok()); finish_ops_.set_output_tag(tag); if (!ctx_->sent_initial_metadata_) { @@ -379,7 +379,7 @@ class ServerAsyncReader GRPC_FINAL : public ServerAsyncReaderInterface { } private: - void BindCall(Call* call) GRPC_OVERRIDE { call_ = *call; } + void BindCall(Call* call) override { call_ = *call; } Call call_; ServerContext* ctx_; @@ -398,12 +398,12 @@ class ServerAsyncWriterInterface : public ServerAsyncStreamingInterface, }; template -class ServerAsyncWriter GRPC_FINAL : public ServerAsyncWriterInterface { +class ServerAsyncWriter final : public ServerAsyncWriterInterface { public: explicit ServerAsyncWriter(ServerContext* ctx) : call_(nullptr, nullptr, nullptr), ctx_(ctx) {} - void SendInitialMetadata(void* tag) GRPC_OVERRIDE { + void SendInitialMetadata(void* tag) override { GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_); meta_ops_.set_output_tag(tag); @@ -416,7 +416,7 @@ class ServerAsyncWriter GRPC_FINAL : public ServerAsyncWriterInterface { call_.PerformOps(&meta_ops_); } - void Write(const W& msg, void* tag) GRPC_OVERRIDE { + void Write(const W& msg, void* tag) override { write_ops_.set_output_tag(tag); if (!ctx_->sent_initial_metadata_) { write_ops_.SendInitialMetadata(ctx_->initial_metadata_, @@ -431,7 +431,7 @@ class ServerAsyncWriter GRPC_FINAL : public ServerAsyncWriterInterface { call_.PerformOps(&write_ops_); } - void Finish(const Status& status, void* tag) GRPC_OVERRIDE { + void Finish(const Status& status, void* tag) override { finish_ops_.set_output_tag(tag); if (!ctx_->sent_initial_metadata_) { finish_ops_.SendInitialMetadata(ctx_->initial_metadata_, @@ -446,7 +446,7 @@ class ServerAsyncWriter GRPC_FINAL : public ServerAsyncWriterInterface { } private: - void BindCall(Call* call) GRPC_OVERRIDE { call_ = *call; } + void BindCall(Call* call) override { call_ = *call; } Call call_; ServerContext* ctx_; @@ -465,13 +465,13 @@ class ServerAsyncReaderWriterInterface : public ServerAsyncStreamingInterface, }; template -class ServerAsyncReaderWriter GRPC_FINAL +class ServerAsyncReaderWriter final : public ServerAsyncReaderWriterInterface { public: explicit ServerAsyncReaderWriter(ServerContext* ctx) : call_(nullptr, nullptr, nullptr), ctx_(ctx) {} - void SendInitialMetadata(void* tag) GRPC_OVERRIDE { + void SendInitialMetadata(void* tag) override { GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_); meta_ops_.set_output_tag(tag); @@ -484,13 +484,13 @@ class ServerAsyncReaderWriter GRPC_FINAL call_.PerformOps(&meta_ops_); } - void Read(R* msg, void* tag) GRPC_OVERRIDE { + void Read(R* msg, void* tag) override { read_ops_.set_output_tag(tag); read_ops_.RecvMessage(msg); call_.PerformOps(&read_ops_); } - void Write(const W& msg, void* tag) GRPC_OVERRIDE { + void Write(const W& msg, void* tag) override { write_ops_.set_output_tag(tag); if (!ctx_->sent_initial_metadata_) { write_ops_.SendInitialMetadata(ctx_->initial_metadata_, @@ -505,7 +505,7 @@ class ServerAsyncReaderWriter GRPC_FINAL call_.PerformOps(&write_ops_); } - void Finish(const Status& status, void* tag) GRPC_OVERRIDE { + void Finish(const Status& status, void* tag) override { finish_ops_.set_output_tag(tag); if (!ctx_->sent_initial_metadata_) { finish_ops_.SendInitialMetadata(ctx_->initial_metadata_, @@ -522,7 +522,7 @@ class ServerAsyncReaderWriter GRPC_FINAL private: friend class ::grpc::Server; - void BindCall(Call* call) GRPC_OVERRIDE { call_ = *call; } + void BindCall(Call* call) override { call_ = *call; } Call call_; ServerContext* ctx_; diff --git a/include/grpc++/impl/codegen/async_unary_call.h b/include/grpc++/impl/codegen/async_unary_call.h index 87c94d6507e..b77a16b699f 100644 --- a/include/grpc++/impl/codegen/async_unary_call.h +++ b/include/grpc++/impl/codegen/async_unary_call.h @@ -55,7 +55,7 @@ class ClientAsyncResponseReaderInterface { }; template -class ClientAsyncResponseReader GRPC_FINAL +class ClientAsyncResponseReader final : public ClientAsyncResponseReaderInterface { public: template @@ -113,13 +113,12 @@ class ClientAsyncResponseReader GRPC_FINAL }; template -class ServerAsyncResponseWriter GRPC_FINAL - : public ServerAsyncStreamingInterface { +class ServerAsyncResponseWriter final : public ServerAsyncStreamingInterface { public: explicit ServerAsyncResponseWriter(ServerContext* ctx) : call_(nullptr, nullptr, nullptr), ctx_(ctx) {} - void SendInitialMetadata(void* tag) GRPC_OVERRIDE { + void SendInitialMetadata(void* tag) override { GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_); meta_buf_.set_output_tag(tag); @@ -168,7 +167,7 @@ class ServerAsyncResponseWriter GRPC_FINAL } private: - void BindCall(Call* call) GRPC_OVERRIDE { call_ = *call; } + void BindCall(Call* call) override { call_ = *call; } Call call_; ServerContext* ctx_; diff --git a/include/grpc++/impl/codegen/call.h b/include/grpc++/impl/codegen/call.h index e211373e7d4..6ab00612f6e 100644 --- a/include/grpc++/impl/codegen/call.h +++ b/include/grpc++/impl/codegen/call.h @@ -337,16 +337,16 @@ class DeserializeFunc { }; template -class DeserializeFuncType GRPC_FINAL : public DeserializeFunc { +class DeserializeFuncType final : public DeserializeFunc { public: DeserializeFuncType(R* message) : message_(message) {} Status Deserialize(grpc_byte_buffer* buf, - int max_receive_message_size) GRPC_OVERRIDE { + int max_receive_message_size) override { return SerializationTraits::Deserialize(buf, message_, max_receive_message_size); } - ~DeserializeFuncType() GRPC_OVERRIDE {} + ~DeserializeFuncType() override {} private: R* message_; // Not a managed pointer because management is external to this @@ -603,7 +603,7 @@ class CallOpSet : public CallOpSetInterface, public Op6 { public: CallOpSet() : return_tag_(this) {} - void FillOps(grpc_op* ops, size_t* nops) GRPC_OVERRIDE { + void FillOps(grpc_op* ops, size_t* nops) override { this->Op1::AddOp(ops, nops); this->Op2::AddOp(ops, nops); this->Op3::AddOp(ops, nops); @@ -612,7 +612,7 @@ class CallOpSet : public CallOpSetInterface, this->Op6::AddOp(ops, nops); } - bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { + bool FinalizeResult(void** tag, bool* status) override { this->Op1::FinishOp(status, max_receive_message_size_); this->Op2::FinishOp(status, max_receive_message_size_); this->Op3::FinishOp(status, max_receive_message_size_); @@ -639,14 +639,14 @@ template , class Op2 = CallNoOp<2>, class Op5 = CallNoOp<5>, class Op6 = CallNoOp<6>> class SneakyCallOpSet : public CallOpSet { public: - bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { + bool FinalizeResult(void** tag, bool* status) override { typedef CallOpSet Base; return Base::FinalizeResult(tag, status) && false; } }; // Straightforward wrapping of the C call object -class Call GRPC_FINAL { +class Call final { public: /* call is owned by the caller */ Call(grpc_call* call, CallHook* call_hook, CompletionQueue* cq) diff --git a/include/grpc++/impl/codegen/client_context.h b/include/grpc++/impl/codegen/client_context.h index a330ed06bbe..777b2f8847f 100644 --- a/include/grpc++/impl/codegen/client_context.h +++ b/include/grpc++/impl/codegen/client_context.h @@ -51,6 +51,7 @@ #include #include +#include #include #include @@ -59,7 +60,6 @@ #include #include #include -#include #include #include #include @@ -235,12 +235,10 @@ class ClientContext { /// DEPRECATED: Use set_wait_for_ready() instead. void set_fail_fast(bool fail_fast) { set_wait_for_ready(!fail_fast); } -#ifndef GRPC_CXX0X_NO_CHRONO /// Return the deadline for the client call. std::chrono::system_clock::time_point deadline() const { return Timespec2Timepoint(deadline_); } -#endif // !GRPC_CXX0X_NO_CHRONO /// Return a \a gpr_timespec representation of the client call's deadline. gpr_timespec raw_deadline() const { return deadline_; } @@ -368,7 +366,7 @@ class ClientContext { bool idempotent_; bool cacheable_; std::shared_ptr channel_; - grpc::mutex mu_; + std::mutex mu_; grpc_call* call_; bool call_canceled_; gpr_timespec deadline_; diff --git a/include/grpc++/impl/codegen/config.h b/include/grpc++/impl/codegen/config.h index 0c754388681..af3ee5a4cf8 100644 --- a/include/grpc++/impl/codegen/config.h +++ b/include/grpc++/impl/codegen/config.h @@ -34,80 +34,6 @@ #ifndef GRPCXX_IMPL_CODEGEN_CONFIG_H #define GRPCXX_IMPL_CODEGEN_CONFIG_H -#if !defined(GRPC_NO_AUTODETECT_PLATFORM) - -#ifdef _MSC_VER -// Visual Studio 2010 is 1600. -#if _MSC_VER < 1600 -#error "gRPC is only supported with Visual Studio starting at 2010" -// Visual Studio 2013 is 1800. -#elif _MSC_VER < 1800 -#define GRPC_CXX0X_NO_FINAL 1 -#define GRPC_CXX0X_NO_OVERRIDE 1 -#define GRPC_CXX0X_NO_CHRONO 1 -#define GRPC_CXX0X_NO_THREAD 1 -#endif -#endif // Visual Studio - -#ifndef __clang__ -#ifdef __GNUC__ -// nullptr was added in gcc 4.6 -#if (__GNUC__ * 100 + __GNUC_MINOR__ < 406) -#define GRPC_CXX0X_NO_NULLPTR 1 -#define GRPC_CXX0X_LIMITED_TOSTRING 1 -#endif -// final and override were added in gcc 4.7 -#if (__GNUC__ * 100 + __GNUC_MINOR__ < 407) -#define GRPC_CXX0X_NO_FINAL 1 -#define GRPC_CXX0X_NO_OVERRIDE 1 -#endif -#endif -#endif - -#endif - -#ifdef GRPC_CXX0X_NO_FINAL -#define GRPC_FINAL -#else -#define GRPC_FINAL final -#endif - -#ifdef GRPC_CXX0X_NO_OVERRIDE -#define GRPC_OVERRIDE -#else -#define GRPC_OVERRIDE override -#endif - -#ifdef GRPC_CXX0X_NO_NULLPTR -#include -#include -namespace grpc { -const class { - public: - template - operator T *() const { - return static_cast(0); - } - template - operator std::unique_ptr() const { - return std::unique_ptr(static_cast(0)); - } - template - operator std::shared_ptr() const { - return std::shared_ptr(static_cast(0)); - } - operator bool() const { return false; } - template - operator std::function() const { - return std::function(); - } - - private: - void operator&() const = delete; -} nullptr = {}; -} -#endif - #ifndef GRPC_CUSTOM_STRING #include #define GRPC_CUSTOM_STRING std::string @@ -117,16 +43,7 @@ namespace grpc { typedef GRPC_CUSTOM_STRING string; -#ifdef GRPC_CXX0X_LIMITED_TOSTRING -inline grpc::string to_string(const int x) { - return std::to_string(static_cast(x)); -} -inline grpc::string to_string(const unsigned int x) { - return std::to_string(static_cast(x)); -} -#else using std::to_string; -#endif } // namespace grpc diff --git a/include/grpc++/impl/codegen/core_codegen.h b/include/grpc++/impl/codegen/core_codegen.h index 0ce009e69d2..aff88ffa074 100644 --- a/include/grpc++/impl/codegen/core_codegen.h +++ b/include/grpc++/impl/codegen/core_codegen.h @@ -45,56 +45,53 @@ namespace grpc { /// Implementation of the core codegen interface. class CoreCodegen : public CoreCodegenInterface { private: - grpc_completion_queue* grpc_completion_queue_create(void* reserved) - GRPC_OVERRIDE; - void grpc_completion_queue_destroy(grpc_completion_queue* cq) GRPC_OVERRIDE; + grpc_completion_queue* grpc_completion_queue_create(void* reserved) override; + void grpc_completion_queue_destroy(grpc_completion_queue* cq) override; grpc_event grpc_completion_queue_pluck(grpc_completion_queue* cq, void* tag, gpr_timespec deadline, - void* reserved) GRPC_OVERRIDE; + void* reserved) override; - void* gpr_malloc(size_t size) GRPC_OVERRIDE; - void gpr_free(void* p) GRPC_OVERRIDE; + void* gpr_malloc(size_t size) override; + void gpr_free(void* p) override; - void gpr_mu_init(gpr_mu* mu) GRPC_OVERRIDE; - void gpr_mu_destroy(gpr_mu* mu) GRPC_OVERRIDE; - void gpr_mu_lock(gpr_mu* mu) GRPC_OVERRIDE; - void gpr_mu_unlock(gpr_mu* mu) GRPC_OVERRIDE; - void gpr_cv_init(gpr_cv* cv) GRPC_OVERRIDE; - void gpr_cv_destroy(gpr_cv* cv) GRPC_OVERRIDE; - int gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, - gpr_timespec abs_deadline) GRPC_OVERRIDE; - void gpr_cv_signal(gpr_cv* cv) GRPC_OVERRIDE; - void gpr_cv_broadcast(gpr_cv* cv) GRPC_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; + void gpr_mu_unlock(gpr_mu* mu) override; + void gpr_cv_init(gpr_cv* cv) override; + void gpr_cv_destroy(gpr_cv* cv) override; + int gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline) override; + void gpr_cv_signal(gpr_cv* cv) override; + void gpr_cv_broadcast(gpr_cv* cv) override; - void grpc_byte_buffer_destroy(grpc_byte_buffer* bb) GRPC_OVERRIDE; + void grpc_byte_buffer_destroy(grpc_byte_buffer* bb) override; int grpc_byte_buffer_reader_init(grpc_byte_buffer_reader* reader, - grpc_byte_buffer* buffer) GRPC_OVERRIDE; - void grpc_byte_buffer_reader_destroy(grpc_byte_buffer_reader* reader) - GRPC_OVERRIDE; + grpc_byte_buffer* buffer) override; + void grpc_byte_buffer_reader_destroy( + grpc_byte_buffer_reader* reader) override; int grpc_byte_buffer_reader_next(grpc_byte_buffer_reader* reader, - gpr_slice* slice) GRPC_OVERRIDE; + gpr_slice* slice) override; grpc_byte_buffer* grpc_raw_byte_buffer_create(gpr_slice* slice, - size_t nslices) GRPC_OVERRIDE; + size_t nslices) override; - gpr_slice gpr_slice_malloc(size_t length) GRPC_OVERRIDE; - void gpr_slice_unref(gpr_slice slice) GRPC_OVERRIDE; - gpr_slice gpr_slice_split_tail(gpr_slice* s, size_t split) GRPC_OVERRIDE; - void gpr_slice_buffer_add(gpr_slice_buffer* sb, - gpr_slice slice) GRPC_OVERRIDE; - void gpr_slice_buffer_pop(gpr_slice_buffer* sb) GRPC_OVERRIDE; + gpr_slice gpr_slice_malloc(size_t length) override; + void gpr_slice_unref(gpr_slice slice) override; + gpr_slice gpr_slice_split_tail(gpr_slice* s, size_t split) override; + void gpr_slice_buffer_add(gpr_slice_buffer* sb, gpr_slice slice) override; + void gpr_slice_buffer_pop(gpr_slice_buffer* sb) override; - void grpc_metadata_array_init(grpc_metadata_array* array) GRPC_OVERRIDE; - void grpc_metadata_array_destroy(grpc_metadata_array* array) GRPC_OVERRIDE; + void grpc_metadata_array_init(grpc_metadata_array* array) override; + void grpc_metadata_array_destroy(grpc_metadata_array* array) override; - gpr_timespec gpr_inf_future(gpr_clock_type type) GRPC_OVERRIDE; - gpr_timespec gpr_time_0(gpr_clock_type type) GRPC_OVERRIDE; + gpr_timespec gpr_inf_future(gpr_clock_type type) override; + gpr_timespec gpr_time_0(gpr_clock_type type) override; - virtual const Status& ok() GRPC_OVERRIDE; - virtual const Status& cancelled() GRPC_OVERRIDE; + virtual const Status& ok() override; + virtual const Status& cancelled() override; - void assert_fail(const char* failed_assertion) GRPC_OVERRIDE; + void assert_fail(const char* failed_assertion) override; }; } // namespace grpc diff --git a/include/grpc++/impl/codegen/method_handler_impl.h b/include/grpc++/impl/codegen/method_handler_impl.h index bb992f0e185..d5d27e15cd6 100644 --- a/include/grpc++/impl/codegen/method_handler_impl.h +++ b/include/grpc++/impl/codegen/method_handler_impl.h @@ -50,7 +50,7 @@ class RpcMethodHandler : public MethodHandler { ServiceType* service) : func_(func), service_(service) {} - void RunHandler(const HandlerParameter& param) GRPC_FINAL { + void RunHandler(const HandlerParameter& param) final { RequestType req; Status status = SerializationTraits::Deserialize( param.request, &req, param.max_receive_message_size); @@ -96,7 +96,7 @@ class ClientStreamingHandler : public MethodHandler { ServiceType* service) : func_(func), service_(service) {} - void RunHandler(const HandlerParameter& param) GRPC_FINAL { + void RunHandler(const HandlerParameter& param) final { ServerReader reader(param.call, param.server_context); ResponseType rsp; Status status = func_(service_, param.server_context, &reader, &rsp); @@ -136,7 +136,7 @@ class ServerStreamingHandler : public MethodHandler { ServiceType* service) : func_(func), service_(service) {} - void RunHandler(const HandlerParameter& param) GRPC_FINAL { + void RunHandler(const HandlerParameter& param) final { RequestType req; Status status = SerializationTraits::Deserialize( param.request, &req, param.max_receive_message_size); @@ -180,7 +180,7 @@ class TemplatedBidiStreamingHandler : public MethodHandler { std::function func) : func_(func), write_needed_(WriteNeeded) {} - void RunHandler(const HandlerParameter& param) GRPC_FINAL { + void RunHandler(const HandlerParameter& param) final { Streamer stream(param.call, param.server_context); Status status = func_(param.server_context, &stream); @@ -266,7 +266,7 @@ class UnknownMethodHandler : public MethodHandler { ops->ServerSendStatus(context->trailing_metadata_, status); } - void RunHandler(const HandlerParameter& param) GRPC_FINAL { + void RunHandler(const HandlerParameter& param) final { CallOpSet ops; FillOps(param.server_context, &ops); param.call->PerformOps(&ops); diff --git a/include/grpc++/impl/codegen/proto_utils.h b/include/grpc++/impl/codegen/proto_utils.h index 6f4786b87be..cbaa3e7bf26 100644 --- a/include/grpc++/impl/codegen/proto_utils.h +++ b/include/grpc++/impl/codegen/proto_utils.h @@ -52,7 +52,7 @@ namespace internal { const int kGrpcBufferWriterMaxBufferLength = 8192; -class GrpcBufferWriter GRPC_FINAL +class GrpcBufferWriter final : public ::grpc::protobuf::io::ZeroCopyOutputStream { public: explicit GrpcBufferWriter(grpc_byte_buffer** bp, int block_size) @@ -61,13 +61,13 @@ class GrpcBufferWriter GRPC_FINAL slice_buffer_ = &(*bp)->data.raw.slice_buffer; } - ~GrpcBufferWriter() GRPC_OVERRIDE { + ~GrpcBufferWriter() override { if (have_backup_) { g_core_codegen_interface->gpr_slice_unref(backup_slice_); } } - bool Next(void** data, int* size) GRPC_OVERRIDE { + bool Next(void** data, int* size) override { if (have_backup_) { slice_ = backup_slice_; have_backup_ = false; @@ -82,7 +82,7 @@ class GrpcBufferWriter GRPC_FINAL return true; } - void BackUp(int count) GRPC_OVERRIDE { + void BackUp(int count) override { g_core_codegen_interface->gpr_slice_buffer_pop(slice_buffer_); if (count == block_size_) { backup_slice_ = slice_; @@ -95,7 +95,7 @@ class GrpcBufferWriter GRPC_FINAL byte_count_ -= count; } - grpc::protobuf::int64 ByteCount() const GRPC_OVERRIDE { return byte_count_; } + grpc::protobuf::int64 ByteCount() const override { return byte_count_; } private: const int block_size_; @@ -106,7 +106,7 @@ class GrpcBufferWriter GRPC_FINAL gpr_slice slice_; }; -class GrpcBufferReader GRPC_FINAL +class GrpcBufferReader final : public ::grpc::protobuf::io::ZeroCopyInputStream { public: explicit GrpcBufferReader(grpc_byte_buffer* buffer) @@ -117,11 +117,11 @@ class GrpcBufferReader GRPC_FINAL "Couldn't initialize byte buffer reader"); } } - ~GrpcBufferReader() GRPC_OVERRIDE { + ~GrpcBufferReader() override { g_core_codegen_interface->grpc_byte_buffer_reader_destroy(&reader_); } - bool Next(const void** data, int* size) GRPC_OVERRIDE { + bool Next(const void** data, int* size) override { if (!status_.ok()) { return false; } @@ -147,9 +147,9 @@ class GrpcBufferReader GRPC_FINAL Status status() const { return status_; } - void BackUp(int count) GRPC_OVERRIDE { backup_count_ = count; } + void BackUp(int count) override { backup_count_ = count; } - bool Skip(int count) GRPC_OVERRIDE { + bool Skip(int count) override { const void* data; int size; while (Next(&data, &size)) { @@ -164,7 +164,7 @@ class GrpcBufferReader GRPC_FINAL return false; } - grpc::protobuf::int64 ByteCount() const GRPC_OVERRIDE { + grpc::protobuf::int64 ByteCount() const override { return byte_count_ - backup_count_; } diff --git a/include/grpc++/impl/codegen/server_context.h b/include/grpc++/impl/codegen/server_context.h index ddf50b019da..dd305763796 100644 --- a/include/grpc++/impl/codegen/server_context.h +++ b/include/grpc++/impl/codegen/server_context.h @@ -94,11 +94,9 @@ class ServerContext { ServerContext(); // for async calls ~ServerContext(); -#ifndef GRPC_CXX0X_NO_CHRONO std::chrono::system_clock::time_point deadline() const { return Timespec2Timepoint(deadline_); } -#endif // !GRPC_CXX0X_NO_CHRONO gpr_timespec raw_deadline() const { return deadline_; } diff --git a/include/grpc++/impl/codegen/server_interface.h b/include/grpc++/impl/codegen/server_interface.h index 4a00d7a3a13..41a64bead03 100644 --- a/include/grpc++/impl/codegen/server_interface.h +++ b/include/grpc++/impl/codegen/server_interface.h @@ -126,12 +126,6 @@ class ServerInterface : public CallHook { /// \return true on a successful shutdown. virtual bool Start(ServerCompletionQueue** cqs, size_t num_cqs) = 0; - /// Process one or more incoming calls. - virtual void RunRpc() = 0; - - /// Schedule \a RunRpc to run in the threadpool. - virtual void ScheduleCallback() = 0; - virtual void ShutdownInternal(gpr_timespec deadline) = 0; virtual int max_receive_message_size() const = 0; @@ -148,7 +142,7 @@ class ServerInterface : public CallHook { bool delete_on_finalize); virtual ~BaseAsyncRequest() {} - bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE; + bool FinalizeResult(void** tag, bool* status) override; protected: ServerInterface* const server_; @@ -174,7 +168,7 @@ class ServerInterface : public CallHook { ServerCompletionQueue* notification_cq); }; - class NoPayloadAsyncRequest GRPC_FINAL : public RegisteredAsyncRequest { + class NoPayloadAsyncRequest final : public RegisteredAsyncRequest { public: NoPayloadAsyncRequest(void* registered_method, ServerInterface* server, ServerContext* context, @@ -189,7 +183,7 @@ class ServerInterface : public CallHook { }; template - class PayloadAsyncRequest GRPC_FINAL : public RegisteredAsyncRequest { + class PayloadAsyncRequest final : public RegisteredAsyncRequest { public: PayloadAsyncRequest(void* registered_method, ServerInterface* server, ServerContext* context, @@ -202,7 +196,7 @@ class ServerInterface : public CallHook { IssueRequest(registered_method, &payload_, notification_cq); } - bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { + bool FinalizeResult(void** tag, bool* status) override { bool serialization_status = *status && payload_ && SerializationTraits::Deserialize( @@ -226,7 +220,7 @@ class ServerInterface : public CallHook { ServerCompletionQueue* notification_cq, void* tag, bool delete_on_finalize); - bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE; + bool FinalizeResult(void** tag, bool* status) override; private: grpc_call_details call_details_; diff --git a/include/grpc++/impl/codegen/sync.h b/include/grpc++/impl/codegen/sync.h deleted file mode 100644 index 62194c77081..00000000000 --- a/include/grpc++/impl/codegen/sync.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#ifndef GRPCXX_IMPL_CODEGEN_SYNC_H -#define GRPCXX_IMPL_CODEGEN_SYNC_H - -#include - -#ifdef GRPC_CXX0X_NO_THREAD -#include -#else -#include -#endif - -#endif // GRPCXX_IMPL_CODEGEN_SYNC_H diff --git a/include/grpc++/impl/codegen/sync_no_cxx11.h b/include/grpc++/impl/codegen/sync_no_cxx11.h deleted file mode 100644 index 87a6594f7df..00000000000 --- a/include/grpc++/impl/codegen/sync_no_cxx11.h +++ /dev/null @@ -1,111 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#ifndef GRPCXX_IMPL_CODEGEN_SYNC_NO_CXX11_H -#define GRPCXX_IMPL_CODEGEN_SYNC_NO_CXX11_H - -#include - -namespace grpc { - -extern CoreCodegenInterface *g_core_codegen_interface; - -template -class lock_guard; -class condition_variable; - -class mutex { - public: - mutex() { g_core_codegen_interface->gpr_mu_init(&mu_); } - ~mutex() { g_core_codegen_interface->gpr_mu_destroy(&mu_); } - - private: - ::gpr_mu mu_; - template - friend class lock_guard; - friend class condition_variable; -}; - -template -class lock_guard { - public: - lock_guard(mutex &mu) : mu_(mu), locked(true) { - g_core_codegen_interface->gpr_mu_lock(&mu.mu_); - } - ~lock_guard() { unlock_internal(); } - - protected: - void lock_internal() { - if (!locked) g_core_codegen_interface->gpr_mu_lock(&mu_.mu_); - locked = true; - } - void unlock_internal() { - if (locked) g_core_codegen_interface->gpr_mu_unlock(&mu_.mu_); - locked = false; - } - - private: - mutex &mu_; - bool locked; - friend class condition_variable; -}; - -template -class unique_lock : public lock_guard { - public: - unique_lock(mutex &mu) : lock_guard(mu) {} - void lock() { this->lock_internal(); } - void unlock() { this->unlock_internal(); } -}; - -class condition_variable { - public: - condition_variable() { g_core_codegen_interface->gpr_cv_init(&cv_); } - ~condition_variable() { g_core_codegen_interface->gpr_cv_destroy(&cv_); } - void wait(lock_guard &mu) { - mu.locked = false; - g_core_codegen_interface->gpr_cv_wait( - &cv_, &mu.mu_.mu_, - g_core_codegen_interface->gpr_inf_future(GPR_CLOCK_REALTIME)); - mu.locked = true; - } - void notify_one() { g_core_codegen_interface->gpr_cv_signal(&cv_); } - void notify_all() { g_core_codegen_interface->gpr_cv_broadcast(&cv_); } - - private: - gpr_cv cv_; -}; - -} // namespace grpc - -#endif // GRPCXX_IMPL_CODEGEN_SYNC_NO_CXX11_H diff --git a/include/grpc++/impl/codegen/sync_stream.h b/include/grpc++/impl/codegen/sync_stream.h index 9a3efb51193..4d9b074e95f 100644 --- a/include/grpc++/impl/codegen/sync_stream.h +++ b/include/grpc++/impl/codegen/sync_stream.h @@ -131,7 +131,7 @@ class ClientReaderInterface : public ClientStreamingInterface, }; template -class ClientReader GRPC_FINAL : public ClientReaderInterface { +class ClientReader final : public ClientReaderInterface { public: /// Blocking create a stream and write the first request out. template @@ -150,7 +150,7 @@ class ClientReader GRPC_FINAL : public ClientReaderInterface { cq_.Pluck(&ops); } - void WaitForInitialMetadata() GRPC_OVERRIDE { + void WaitForInitialMetadata() override { GPR_CODEGEN_ASSERT(!context_->initial_metadata_received_); CallOpSet ops; @@ -159,12 +159,12 @@ class ClientReader GRPC_FINAL : public ClientReaderInterface { cq_.Pluck(&ops); /// status ignored } - bool NextMessageSize(uint32_t* sz) GRPC_OVERRIDE { + bool NextMessageSize(uint32_t* sz) override { *sz = call_.max_receive_message_size(); return true; } - bool Read(R* msg) GRPC_OVERRIDE { + bool Read(R* msg) override { CallOpSet> ops; if (!context_->initial_metadata_received_) { ops.RecvInitialMetadata(context_); @@ -174,7 +174,7 @@ class ClientReader GRPC_FINAL : public ClientReaderInterface { return cq_.Pluck(&ops) && ops.got_message; } - Status Finish() GRPC_OVERRIDE { + Status Finish() override { CallOpSet ops; Status status; ops.ClientRecvStatus(context_, &status); @@ -230,7 +230,7 @@ class ClientWriter : public ClientWriterInterface { } using WriterInterface::Write; - bool Write(const W& msg, const WriteOptions& options) GRPC_OVERRIDE { + bool Write(const W& msg, const WriteOptions& options) override { CallOpSet ops; if (!ops.SendMessage(msg, options).ok()) { return false; @@ -239,7 +239,7 @@ class ClientWriter : public ClientWriterInterface { return cq_.Pluck(&ops); } - bool WritesDone() GRPC_OVERRIDE { + bool WritesDone() override { CallOpSet ops; ops.ClientSendClose(); call_.PerformOps(&ops); @@ -247,7 +247,7 @@ class ClientWriter : public ClientWriterInterface { } /// Read the final response and wait for the final status. - Status Finish() GRPC_OVERRIDE { + Status Finish() override { Status status; if (!context_->initial_metadata_received_) { finish_ops_.RecvInitialMetadata(context_); @@ -287,7 +287,7 @@ class ClientReaderWriterInterface : public ClientStreamingInterface, }; template -class ClientReaderWriter GRPC_FINAL : public ClientReaderWriterInterface { +class ClientReaderWriter final : public ClientReaderWriterInterface { public: /// Blocking create a stream. ClientReaderWriter(ChannelInterface* channel, const RpcMethod& method, @@ -300,7 +300,7 @@ class ClientReaderWriter GRPC_FINAL : public ClientReaderWriterInterface { cq_.Pluck(&ops); } - void WaitForInitialMetadata() GRPC_OVERRIDE { + void WaitForInitialMetadata() override { GPR_CODEGEN_ASSERT(!context_->initial_metadata_received_); CallOpSet ops; @@ -309,12 +309,12 @@ class ClientReaderWriter GRPC_FINAL : public ClientReaderWriterInterface { cq_.Pluck(&ops); // status ignored } - bool NextMessageSize(uint32_t* sz) GRPC_OVERRIDE { + bool NextMessageSize(uint32_t* sz) override { *sz = call_.max_receive_message_size(); return true; } - bool Read(R* msg) GRPC_OVERRIDE { + bool Read(R* msg) override { CallOpSet> ops; if (!context_->initial_metadata_received_) { ops.RecvInitialMetadata(context_); @@ -325,21 +325,21 @@ class ClientReaderWriter GRPC_FINAL : public ClientReaderWriterInterface { } using WriterInterface::Write; - bool Write(const W& msg, const WriteOptions& options) GRPC_OVERRIDE { + bool Write(const W& msg, const WriteOptions& options) override { CallOpSet ops; if (!ops.SendMessage(msg, options).ok()) return false; call_.PerformOps(&ops); return cq_.Pluck(&ops); } - bool WritesDone() GRPC_OVERRIDE { + bool WritesDone() override { CallOpSet ops; ops.ClientSendClose(); call_.PerformOps(&ops); return cq_.Pluck(&ops); } - Status Finish() GRPC_OVERRIDE { + Status Finish() override { CallOpSet ops; if (!context_->initial_metadata_received_) { ops.RecvInitialMetadata(context_); @@ -363,11 +363,11 @@ class ServerReaderInterface : public ServerStreamingInterface, public ReaderInterface {}; template -class ServerReader GRPC_FINAL : public ServerReaderInterface { +class ServerReader final : public ServerReaderInterface { public: ServerReader(Call* call, ServerContext* ctx) : call_(call), ctx_(ctx) {} - void SendInitialMetadata() GRPC_OVERRIDE { + void SendInitialMetadata() override { GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_); CallOpSet ops; @@ -381,12 +381,12 @@ class ServerReader GRPC_FINAL : public ServerReaderInterface { call_->cq()->Pluck(&ops); } - bool NextMessageSize(uint32_t* sz) GRPC_OVERRIDE { + bool NextMessageSize(uint32_t* sz) override { *sz = call_->max_receive_message_size(); return true; } - bool Read(R* msg) GRPC_OVERRIDE { + bool Read(R* msg) override { CallOpSet> ops; ops.RecvMessage(msg); call_->PerformOps(&ops); @@ -404,11 +404,11 @@ class ServerWriterInterface : public ServerStreamingInterface, public WriterInterface {}; template -class ServerWriter GRPC_FINAL : public ServerWriterInterface { +class ServerWriter final : public ServerWriterInterface { public: ServerWriter(Call* call, ServerContext* ctx) : call_(call), ctx_(ctx) {} - void SendInitialMetadata() GRPC_OVERRIDE { + void SendInitialMetadata() override { GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_); CallOpSet ops; @@ -423,7 +423,7 @@ class ServerWriter GRPC_FINAL : public ServerWriterInterface { } using WriterInterface::Write; - bool Write(const W& msg, const WriteOptions& options) GRPC_OVERRIDE { + bool Write(const W& msg, const WriteOptions& options) override { CallOpSet ops; if (!ops.SendMessage(msg, options).ok()) { return false; @@ -454,7 +454,7 @@ class ServerReaderWriterInterface : public ServerStreamingInterface, // Actual implementation of bi-directional streaming namespace internal { template -class ServerReaderWriterBody GRPC_FINAL { +class ServerReaderWriterBody final { public: ServerReaderWriterBody(Call* call, ServerContext* ctx) : call_(call), ctx_(ctx) {} @@ -510,20 +510,20 @@ class ServerReaderWriterBody GRPC_FINAL { // class to represent the user API for a bidirectional streaming call template -class ServerReaderWriter GRPC_FINAL : public ServerReaderWriterInterface { +class ServerReaderWriter final : public ServerReaderWriterInterface { public: ServerReaderWriter(Call* call, ServerContext* ctx) : body_(call, ctx) {} - void SendInitialMetadata() GRPC_OVERRIDE { body_.SendInitialMetadata(); } + void SendInitialMetadata() override { body_.SendInitialMetadata(); } - bool NextMessageSize(uint32_t* sz) GRPC_OVERRIDE { + bool NextMessageSize(uint32_t* sz) override { return body_.NextMessageSize(sz); } - bool Read(R* msg) GRPC_OVERRIDE { return body_.Read(msg); } + bool Read(R* msg) override { return body_.Read(msg); } using WriterInterface::Write; - bool Write(const W& msg, const WriteOptions& options) GRPC_OVERRIDE { + bool Write(const W& msg, const WriteOptions& options) override { return body_.Write(msg, options); } @@ -541,19 +541,19 @@ class ServerReaderWriter GRPC_FINAL : public ServerReaderWriterInterface { /// must have exactly 1 Read and exactly 1 Write, in that order, to function /// correctly. Otherwise, the RPC is in error. template -class ServerUnaryStreamer GRPC_FINAL +class ServerUnaryStreamer final : public ServerReaderWriterInterface { public: ServerUnaryStreamer(Call* call, ServerContext* ctx) : body_(call, ctx), read_done_(false), write_done_(false) {} - void SendInitialMetadata() GRPC_OVERRIDE { body_.SendInitialMetadata(); } + void SendInitialMetadata() override { body_.SendInitialMetadata(); } - bool NextMessageSize(uint32_t* sz) GRPC_OVERRIDE { + bool NextMessageSize(uint32_t* sz) override { return body_.NextMessageSize(sz); } - bool Read(RequestType* request) GRPC_OVERRIDE { + bool Read(RequestType* request) override { if (read_done_) { return false; } @@ -563,7 +563,7 @@ class ServerUnaryStreamer GRPC_FINAL using WriterInterface::Write; bool Write(const ResponseType& response, - const WriteOptions& options) GRPC_OVERRIDE { + const WriteOptions& options) override { if (write_done_ || !read_done_) { return false; } @@ -583,19 +583,19 @@ class ServerUnaryStreamer GRPC_FINAL /// but the server responds to it as though it were a bidi streaming call that /// must first have exactly 1 Read and then any number of Writes. template -class ServerSplitStreamer GRPC_FINAL +class ServerSplitStreamer final : public ServerReaderWriterInterface { public: ServerSplitStreamer(Call* call, ServerContext* ctx) : body_(call, ctx), read_done_(false) {} - void SendInitialMetadata() GRPC_OVERRIDE { body_.SendInitialMetadata(); } + void SendInitialMetadata() override { body_.SendInitialMetadata(); } - bool NextMessageSize(uint32_t* sz) GRPC_OVERRIDE { + bool NextMessageSize(uint32_t* sz) override { return body_.NextMessageSize(sz); } - bool Read(RequestType* request) GRPC_OVERRIDE { + bool Read(RequestType* request) override { if (read_done_) { return false; } @@ -605,7 +605,7 @@ class ServerSplitStreamer GRPC_FINAL using WriterInterface::Write; bool Write(const ResponseType& response, - const WriteOptions& options) GRPC_OVERRIDE { + const WriteOptions& options) override { return read_done_ && body_.Write(response, options); } diff --git a/include/grpc++/impl/codegen/time.h b/include/grpc++/impl/codegen/time.h index 87c5112d0d2..e090ece7567 100644 --- a/include/grpc++/impl/codegen/time.h +++ b/include/grpc++/impl/codegen/time.h @@ -75,8 +75,6 @@ class TimePoint { } // namespace grpc -#ifndef GRPC_CXX0X_NO_CHRONO - #include #include @@ -106,6 +104,4 @@ class TimePoint { } // namespace grpc -#endif // !GRPC_CXX0X_NO_CHRONO - #endif // GRPCXX_IMPL_CODEGEN_TIME_H diff --git a/include/grpc++/impl/grpc_library.h b/include/grpc++/impl/grpc_library.h index 1184d1bf093..ee1d0a97508 100644 --- a/include/grpc++/impl/grpc_library.h +++ b/include/grpc++/impl/grpc_library.h @@ -44,17 +44,17 @@ namespace grpc { namespace internal { -class GrpcLibrary GRPC_FINAL : public GrpcLibraryInterface { +class GrpcLibrary final : public GrpcLibraryInterface { public: - void init() GRPC_OVERRIDE { grpc_init(); } - void shutdown() GRPC_OVERRIDE { grpc_shutdown(); } + void init() override { grpc_init(); } + void shutdown() override { grpc_shutdown(); } }; static GrpcLibrary g_gli; static CoreCodegen g_core_codegen; /// Instantiating this class ensures the proper initialization of gRPC. -class GrpcLibraryInitializer GRPC_FINAL { +class GrpcLibraryInitializer final { public: GrpcLibraryInitializer() { if (grpc::g_glip == nullptr) { diff --git a/include/grpc++/impl/sync.h b/include/grpc++/impl/sync.h deleted file mode 100644 index 3339cddba49..00000000000 --- a/include/grpc++/impl/sync.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#ifndef GRPCXX_IMPL_SYNC_H -#define GRPCXX_IMPL_SYNC_H - -#include - -#endif // GRPCXX_IMPL_SYNC_H diff --git a/include/grpc++/impl/thd.h b/include/grpc++/impl/thd.h deleted file mode 100644 index f8d4258ac61..00000000000 --- a/include/grpc++/impl/thd.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#ifndef GRPCXX_IMPL_THD_H -#define GRPCXX_IMPL_THD_H - -#include - -#ifdef GRPC_CXX0X_NO_THREAD -#include -#else -#include -#endif - -#endif // GRPCXX_IMPL_THD_H diff --git a/include/grpc++/impl/thd_no_cxx11.h b/include/grpc++/impl/thd_no_cxx11.h deleted file mode 100644 index 3f981d3770f..00000000000 --- a/include/grpc++/impl/thd_no_cxx11.h +++ /dev/null @@ -1,117 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#ifndef GRPCXX_IMPL_THD_NO_CXX11_H -#define GRPCXX_IMPL_THD_NO_CXX11_H - -#include - -namespace grpc { - -class thread { - public: - template - thread(void (T::*fptr)(), T *obj) { - func_ = new thread_function(fptr, obj); - joined_ = false; - start(); - } - template - thread(void (T::*fptr)(U arg), T *obj, U arg) { - func_ = new thread_function_arg(fptr, obj, arg); - joined_ = false; - start(); - } - ~thread() { - if (!joined_) std::terminate(); - delete func_; - } - thread(thread &&other) - : func_(other.func_), thd_(other.thd_), joined_(other.joined_) { - other.joined_ = true; - other.func_ = NULL; - } - void join() { - gpr_thd_join(thd_); - joined_ = true; - } - - private: - void start() { - gpr_thd_options options = gpr_thd_options_default(); - gpr_thd_options_set_joinable(&options); - gpr_thd_new(&thd_, thread_func, (void *)func_, &options); - } - static void thread_func(void *arg) { - thread_function_base *func = (thread_function_base *)arg; - func->call(); - } - class thread_function_base { - public: - virtual ~thread_function_base() {} - virtual void call() = 0; - }; - template - class thread_function : public thread_function_base { - public: - thread_function(void (T::*fptr)(), T *obj) : fptr_(fptr), obj_(obj) {} - virtual void call() { (obj_->*fptr_)(); } - - private: - void (T::*fptr_)(); - T *obj_; - }; - template - class thread_function_arg : public thread_function_base { - public: - thread_function_arg(void (T::*fptr)(U arg), T *obj, U arg) - : fptr_(fptr), obj_(obj), arg_(arg) {} - virtual void call() { (obj_->*fptr_)(arg_); } - - private: - void (T::*fptr_)(U arg); - T *obj_; - U arg_; - }; - thread_function_base *func_; - gpr_thd_id thd_; - bool joined_; - - // Disallow copy and assign. - thread(const thread &); - void operator=(const thread &); -}; - -} // namespace grpc - -#endif // GRPCXX_IMPL_THD_NO_CXX11_H diff --git a/include/grpc++/impl/codegen/impl/sync.h b/include/grpc++/resource_quota.h similarity index 58% rename from include/grpc++/impl/codegen/impl/sync.h rename to include/grpc++/resource_quota.h index 88951de6d0d..75e04d4e2ff 100644 --- a/include/grpc++/impl/codegen/impl/sync.h +++ b/include/grpc++/resource_quota.h @@ -1,6 +1,6 @@ /* * - * Copyright 2015, Google Inc. + * Copyright 2016, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -31,15 +31,40 @@ * */ -#ifndef GRPCXX_IMPL_CODEGEN_IMPL_SYNC_H -#define GRPCXX_IMPL_CODEGEN_IMPL_SYNC_H +#ifndef GRPCXX_RESOURCE_QUOTA_H +#define GRPCXX_RESOURCE_QUOTA_H + +struct grpc_resource_quota; #include -#ifdef GRPC_CXX0X_NO_THREAD -#include -#else -#include -#endif +namespace grpc { + +/// ResourceQuota represents a bound on memory usage by the gRPC library. +/// A ResourceQuota can be attached to a server (via ServerBuilder), or a client +/// channel (via ChannelArguments). gRPC will attempt to keep memory used by +/// all attached entities below the ResourceQuota bound. +class ResourceQuota final { + public: + explicit ResourceQuota(const grpc::string& name); + ResourceQuota(); + ~ResourceQuota(); + + /// Resize this ResourceQuota to a new size. If new_size is smaller than the + /// current size of the pool, memory usage will be monotonically decreased + /// until it falls under new_size. No time bound is given for this to occur + /// however. + ResourceQuota& Resize(size_t new_size); + + grpc_resource_quota* c_resource_quota() const { return impl_; } + + private: + ResourceQuota(const ResourceQuota& rhs); + ResourceQuota& operator=(const ResourceQuota& rhs); + + grpc_resource_quota* const impl_; +}; + +} // namespace grpc -#endif // GRPCXX_IMPL_CODEGEN_IMPL_SYNC_H +#endif // GRPCXX_RESOURCE_QUOTA_H diff --git a/include/grpc++/server.h b/include/grpc++/server.h index f51a6c658f0..fba9952e6e7 100644 --- a/include/grpc++/server.h +++ b/include/grpc++/server.h @@ -34,8 +34,10 @@ #ifndef GRPCXX_SERVER_H #define GRPCXX_SERVER_H +#include #include #include +#include #include #include @@ -43,7 +45,6 @@ #include #include #include -#include #include #include #include @@ -64,7 +65,7 @@ class ThreadPoolInterface; /// Models a gRPC server. /// /// Servers are configured and started via \a grpc::ServerBuilder. -class Server GRPC_FINAL : public ServerInterface, private GrpcLibraryCodegen { +class Server final : public ServerInterface, private GrpcLibraryCodegen { public: ~Server(); @@ -72,7 +73,7 @@ class Server GRPC_FINAL : public ServerInterface, private GrpcLibraryCodegen { /// /// \warning The server must be either shutting down or some other thread must /// call \a Shutdown for this function to ever return. - void Wait() GRPC_OVERRIDE; + void Wait() override; /// Global Callbacks /// @@ -105,27 +106,49 @@ class Server GRPC_FINAL : public ServerInterface, private GrpcLibraryCodegen { class AsyncRequest; class ShutdownRequest; + /// SyncRequestThreadManager is an implementation of ThreadManager. This class + /// is responsible for polling for incoming RPCs and calling the RPC handlers. + /// This is only used in case of a Sync server (i.e a server exposing a sync + /// interface) + class SyncRequestThreadManager; + class UnimplementedAsyncRequestContext; class UnimplementedAsyncRequest; class UnimplementedAsyncResponse; /// Server constructors. To be used by \a ServerBuilder only. /// - /// \param thread_pool The threadpool instance to use for call processing. - /// \param thread_pool_owned Does the server own the \a thread_pool instance? - /// \param max_receive_message_size Maximum message length that the channel - /// can receive. - Server(ThreadPoolInterface* thread_pool, bool thread_pool_owned, - int max_receive_message_size, ChannelArguments* args); + /// \param max_message_size Maximum message length that the channel can + /// receive. + /// + /// \param args The channel args + /// + /// \param sync_server_cqs The completion queues to use if the server is a + /// synchronous server (or a hybrid server). The server polls for new RPCs on + /// these queues + /// + /// \param min_pollers The minimum number of polling threads per server + /// completion queue (in param sync_server_cqs) to use for listening to + /// incoming requests (used only in case of sync server) + /// + /// \param max_pollers The maximum number of polling threads per server + /// completion queue (in param sync_server_cqs) to use for listening to + /// incoming requests (used only in case of sync server) + /// + /// \param sync_cq_timeout_msec The timeout to use when calling AsyncNext() on + /// server completion queues passed via sync_server_cqs param. + Server(int max_message_size, ChannelArguments* args, + std::shared_ptr>> + sync_server_cqs, + int min_pollers, int max_pollers, int sync_cq_timeout_msec); /// Register a service. This call does not take ownership of the service. /// The service must exist for the lifetime of the Server instance. - bool RegisterService(const grpc::string* host, - Service* service) GRPC_OVERRIDE; + bool RegisterService(const grpc::string* host, Service* service) override; /// Register a generic service. This call does not take ownership of the /// service. The service must exist for the lifetime of the Server instance. - void RegisterAsyncGenericService(AsyncGenericService* service) GRPC_OVERRIDE; + void RegisterAsyncGenericService(AsyncGenericService* service) override; /// Tries to bind \a server to the given \a addr. /// @@ -139,7 +162,7 @@ class Server GRPC_FINAL : public ServerInterface, private GrpcLibraryCodegen { /// /// \warning It's an error to call this method on an already started server. int AddListeningPort(const grpc::string& addr, - ServerCredentials* creds) GRPC_OVERRIDE; + ServerCredentials* creds) override; /// Start the server. /// @@ -149,56 +172,47 @@ class Server GRPC_FINAL : public ServerInterface, private GrpcLibraryCodegen { /// \param num_cqs How many completion queues does \a cqs hold. /// /// \return true on a successful shutdown. - bool Start(ServerCompletionQueue** cqs, size_t num_cqs) GRPC_OVERRIDE; - - /// Process one or more incoming calls. - void RunRpc() GRPC_OVERRIDE; - - /// Schedule \a RunRpc to run in the threadpool. - void ScheduleCallback() GRPC_OVERRIDE; + bool Start(ServerCompletionQueue** cqs, size_t num_cqs) override; - void PerformOpsOnCall(CallOpSetInterface* ops, Call* call) GRPC_OVERRIDE; + void PerformOpsOnCall(CallOpSetInterface* ops, Call* call) override; - void ShutdownInternal(gpr_timespec deadline) GRPC_OVERRIDE; + void ShutdownInternal(gpr_timespec deadline) override; - int max_receive_message_size() const GRPC_OVERRIDE { + int max_receive_message_size() const override { return max_receive_message_size_; }; - grpc_server* server() GRPC_OVERRIDE { return server_; }; + grpc_server* server() override { return server_; }; ServerInitializer* initializer(); const int max_receive_message_size_; - // Completion queue. - CompletionQueue cq_; + /// The following completion queues are ONLY used in case of Sync API i.e if + /// the server has any services with sync methods. The server uses these + /// completion queues to poll for new RPCs + std::shared_ptr>> + sync_server_cqs_; + + /// List of ThreadManager instances (one for each cq in the sync_server_cqs) + std::vector> sync_req_mgrs_; // Sever status - grpc::mutex mu_; + std::mutex mu_; bool started_; bool shutdown_; - bool shutdown_notified_; - // The number of threads which are running callbacks. - int num_running_cb_; - grpc::condition_variable callback_cv_; + bool shutdown_notified_; // Was notify called on the shutdown_cv_ - grpc::condition_variable shutdown_cv_; + std::condition_variable shutdown_cv_; std::shared_ptr global_callbacks_; - std::list* sync_methods_; std::vector services_; - std::unique_ptr unknown_method_; bool has_generic_service_; - // Pointer to the c grpc server. + // Pointer to the wrapped grpc_server. grpc_server* server_; - ThreadPoolInterface* thread_pool_; - // Whether the thread pool is created and owned by the server. - bool thread_pool_owned_; - std::unique_ptr server_initializer_; }; diff --git a/include/grpc++/server_builder.h b/include/grpc++/server_builder.h index 37f1f8cb803..9252c6a63a8 100644 --- a/include/grpc++/server_builder.h +++ b/include/grpc++/server_builder.h @@ -34,6 +34,7 @@ #ifndef GRPCXX_SERVER_BUILDER_H #define GRPCXX_SERVER_BUILDER_H +#include #include #include #include @@ -42,10 +43,15 @@ #include #include #include +#include +#include + +struct grpc_resource_quota; namespace grpc { class AsyncGenericService; +class ResourceQuota; class CompletionQueue; class RpcService; class Server; @@ -61,6 +67,9 @@ class ServerBuilderPluginTest; class ServerBuilder { public: ServerBuilder(); + ~ServerBuilder(); + + enum SyncServerOption { NUM_CQS, MIN_POLLERS, MAX_POLLERS, CQ_TIMEOUT_MSEC }; /// 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 @@ -113,8 +122,14 @@ class ServerBuilder { ServerBuilder& SetDefaultCompressionAlgorithm( grpc_compression_algorithm algorithm); + /// Set the attached buffer pool for this server + ServerBuilder& SetResourceQuota(const ResourceQuota& resource_quota); + ServerBuilder& SetOption(std::unique_ptr option); + /// Only useful if this is a Synchronous server. + ServerBuilder& SetSyncServerOption(SyncServerOption option, int value); + /// Tries to bind \a server to the given \a addr. /// /// It can be invoked multiple times. @@ -170,6 +185,28 @@ class ServerBuilder { int* selected_port; }; + struct SyncServerSettings { + SyncServerSettings() + : num_cqs(GPR_MAX(gpr_cpu_num_cores(), 4)), + min_pollers(1), + max_pollers(INT_MAX), + cq_timeout_msec(1000) {} + + // Number of server completion queues to create to listen to incoming RPCs. + int num_cqs; + + // Minimum number of threads per completion queue that should be listening + // to incoming RPCs. + int min_pollers; + + // Maximum number of threads per completion queue that can be listening to + // incoming RPCs. + int max_pollers; + + // The timeout for server completion queue's AsyncNext call. + int cq_timeout_msec; + }; + typedef std::unique_ptr HostString; struct NamedService { explicit NamedService(Service* s) : service(s) {} @@ -184,9 +221,15 @@ class ServerBuilder { std::vector> options_; std::vector> services_; std::vector ports_; + + SyncServerSettings sync_server_settings_; + + // List of completion queues added via AddCompletionQueue() method std::vector cqs_; + std::shared_ptr creds_; std::vector> plugins_; + grpc_resource_quota* resource_quota_; AsyncGenericService* generic_service_; struct { bool is_set; diff --git a/include/grpc++/support/byte_buffer.h b/include/grpc++/support/byte_buffer.h index 06f8969b704..1f317df6634 100644 --- a/include/grpc++/support/byte_buffer.h +++ b/include/grpc++/support/byte_buffer.h @@ -47,7 +47,7 @@ namespace grpc { /// A sequence of bytes. -class ByteBuffer GRPC_FINAL { +class ByteBuffer final { public: /// Constuct an empty buffer. ByteBuffer() : buffer_(nullptr) {} diff --git a/include/grpc++/support/channel_arguments.h b/include/grpc++/support/channel_arguments.h index ae243939e9a..49a3e9461cf 100644 --- a/include/grpc++/support/channel_arguments.h +++ b/include/grpc++/support/channel_arguments.h @@ -46,6 +46,8 @@ namespace testing { class ChannelArgumentsTest; } // namespace testing +class ResourceQuota; + /// Options for channel creation. The user can use generic setters to pass /// key value pairs down to c channel creation code. For grpc related options, /// concrete setters are provided. @@ -80,6 +82,14 @@ class ChannelArguments { /// The given string will be sent at the front of the user agent string. void SetUserAgentPrefix(const grpc::string& user_agent_prefix); + /// The given buffer pool will be attached to the constructed channel + void SetResourceQuota(const ResourceQuota& resource_quota); + + /// Set LB policy name. + /// Note that if the name resolver returns only balancer addresses, the + /// grpclb LB policy will be used, regardless of what is specified here. + void SetLoadBalancingPolicyName(const grpc::string& lb_policy_name); + // Generic channel argument setters. Only for advanced use cases. /// Set an integer argument \a value under \a key. void SetInt(const grpc::string& key, int value); @@ -88,6 +98,9 @@ class ChannelArguments { /// Set a pointer argument \a value under \a key. Owership is not transferred. void SetPointer(const grpc::string& key, void* value); + void SetPointerWithVtable(const grpc::string& key, void* value, + const grpc_arg_pointer_vtable* vtable); + /// Set a textual argument \a value under \a key. void SetString(const grpc::string& key, const grpc::string& value); diff --git a/include/grpc++/support/slice.h b/include/grpc++/support/slice.h index 5874b4f5ae3..85561f7f334 100644 --- a/include/grpc++/support/slice.h +++ b/include/grpc++/support/slice.h @@ -44,7 +44,7 @@ namespace grpc { /// A slice represents a contiguous reference counted array of bytes. /// It is cheap to take references to a slice, and it is cheap to create a /// slice pointing to a subset of another slice. -class Slice GRPC_FINAL { +class Slice final { public: /// Construct an empty slice. Slice(); diff --git a/include/grpc/grpc.h b/include/grpc/grpc.h index dbd125e57ad..9dfcca97667 100644 --- a/include/grpc/grpc.h +++ b/include/grpc/grpc.h @@ -405,6 +405,23 @@ GRPCAPI int grpc_is_binary_header(const char *key, size_t length); /** Convert grpc_call_error values to a string */ 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); + +/** Add a reference to a buffer pool */ +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); + +/** Update the size of a buffer pool */ +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); + #ifdef __cplusplus } #endif diff --git a/include/grpc/impl/codegen/grpc_types.h b/include/grpc/impl/codegen/grpc_types.h index 0fc86b57cc1..be766f331fd 100644 --- a/include/grpc/impl/codegen/grpc_types.h +++ b/include/grpc/impl/codegen/grpc_types.h @@ -201,6 +201,9 @@ typedef struct { #define GRPC_ARG_MAX_METADATA_SIZE "grpc.max_metadata_size" /** If non-zero, allow the use of SO_REUSEPORT if it's available (default 1) */ #define GRPC_ARG_ALLOW_REUSEPORT "grpc.so_reuseport" +/** If non-zero, a pointer to a buffer pool (use grpc_resource_quota_arg_vtable + to fetch an appropriate pointer arg vtable */ +#define GRPC_ARG_RESOURCE_QUOTA "grpc.resource_quota" /** Service config data, to be passed to subchannels. Not intended for external use. */ #define GRPC_ARG_SERVICE_CONFIG "grpc.service_config" @@ -474,6 +477,8 @@ typedef struct { char **lb_policy_name; } grpc_channel_info; +typedef struct grpc_resource_quota grpc_resource_quota; + #ifdef __cplusplus } #endif diff --git a/package.json b/package.json index 9afba318162..5506e9bbdf8 100644 --- a/package.json +++ b/package.json @@ -25,24 +25,28 @@ "coverage": "./node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha src/node/test", "install": "./node_modules/.bin/node-pre-gyp install --fallback-to-build" }, - "bundledDependencies": ["node-pre-gyp"], + "bundledDependencies": [ + "node-pre-gyp" + ], "dependencies": { "arguejs": "^0.2.3", - "lodash": "^3.9.3", + "lodash": "^4.15.0", "nan": "^2.0.0", - "protobufjs": "^4.0.0" + "node-pre-gyp": "^0.6.0", + "protobufjs": "^5.0.0" }, "devDependencies": { - "async": "^1.5.0", + "async": "^2.0.1", + "body-parser": "^1.15.2", + "express": "^4.14.0", "google-auth-library": "^0.9.2", "google-protobuf": "^3.0.0", - "istanbul": "^0.3.21", + "istanbul": "^0.4.4", "jsdoc": "^3.3.2", "jshint": "^2.5.0", "minimist": "^1.1.0", - "mocha": "^2.3.4", - "mocha-jenkins-reporter": "^0.1.9", - "mustache": "^2.0.0", + "mocha": "^3.0.2", + "mocha-jenkins-reporter": "^0.2.3", "poisson-process": "^0.2.1" }, "engines": { @@ -50,11 +54,10 @@ }, "binary": { "module_name": "grpc_node", - "module_path": "./build/Release/", + "module_path": "src/node/extension_binary", "host": "https://storage.googleapis.com/", "remote_path": "grpc-precompiled-binaries/node/{name}/v{version}", - "package_name": "{node_abi}-{platform}-{arch}.tar.gz", - "module_path": "src/node/extension_binary" + "package_name": "{node_abi}-{platform}-{arch}.tar.gz" }, "files": [ "LICENSE", @@ -75,7 +78,7 @@ ], "main": "src/node/index.js", "license": "BSD-3-Clause", - "jshintConfig" : { + "jshintConfig": { "bitwise": true, "curly": true, "eqeqeq": true, diff --git a/package.xml b/package.xml index d4a4e3c7b97..a60eac68205 100644 --- a/package.xml +++ b/package.xml @@ -218,6 +218,7 @@ + @@ -226,6 +227,7 @@ + @@ -393,6 +395,7 @@ + diff --git a/setup.py b/setup.py index cdd3bb3f0dd..559a75f6742 100644 --- a/setup.py +++ b/setup.py @@ -52,6 +52,7 @@ PYTHON_STEM = os.path.join('src', 'python', 'grpcio') CORE_INCLUDE = ('include', '.',) BORINGSSL_INCLUDE = (os.path.join('third_party', 'boringssl', 'include'),) ZLIB_INCLUDE = (os.path.join('third_party', 'zlib'),) +README = os.path.join(PYTHON_STEM, 'README.rst') # 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__))) @@ -259,6 +260,7 @@ setuptools.setup( name='grpcio', version=grpc_version.VERSION, license=LICENSE, + long_description=open(README).read(), ext_modules=CYTHON_EXTENSION_MODULES, packages=list(PACKAGES), package_dir=PACKAGE_DIRECTORIES, diff --git a/src/compiler/cpp_generator.cc b/src/compiler/cpp_generator.cc index fa72f9b0d97..a26eeb46b95 100644 --- a/src/compiler/cpp_generator.cc +++ b/src/compiler/cpp_generator.cc @@ -322,7 +322,7 @@ void PrintHeaderClientMethod(Printer *printer, const Method *method, printer->Print( *vars, "::grpc::Status $Method$(::grpc::ClientContext* context, " - "const $Request$& request, $Response$* response) GRPC_OVERRIDE;\n"); + "const $Request$& request, $Response$* response) override;\n"); printer->Print( *vars, "std::unique_ptr< ::grpc::ClientAsyncResponseReader< $Response$>> " @@ -417,37 +417,34 @@ void PrintHeaderClientMethod(Printer *printer, const Method *method, "::grpc::ClientAsyncResponseReader< $Response$>* " "Async$Method$Raw(::grpc::ClientContext* context, " "const $Request$& request, " - "::grpc::CompletionQueue* cq) GRPC_OVERRIDE;\n"); + "::grpc::CompletionQueue* cq) override;\n"); } else if (method->ClientOnlyStreaming()) { printer->Print(*vars, "::grpc::ClientWriter< $Request$>* $Method$Raw(" "::grpc::ClientContext* context, $Response$* response) " - "GRPC_OVERRIDE;\n"); - printer->Print( - *vars, - "::grpc::ClientAsyncWriter< $Request$>* Async$Method$Raw(" - "::grpc::ClientContext* context, $Response$* response, " - "::grpc::CompletionQueue* cq, void* tag) GRPC_OVERRIDE;\n"); + "override;\n"); + printer->Print(*vars, + "::grpc::ClientAsyncWriter< $Request$>* Async$Method$Raw(" + "::grpc::ClientContext* context, $Response$* response, " + "::grpc::CompletionQueue* cq, void* tag) override;\n"); } else if (method->ServerOnlyStreaming()) { printer->Print(*vars, "::grpc::ClientReader< $Response$>* $Method$Raw(" "::grpc::ClientContext* context, const $Request$& request)" - " GRPC_OVERRIDE;\n"); + " override;\n"); printer->Print( *vars, "::grpc::ClientAsyncReader< $Response$>* Async$Method$Raw(" "::grpc::ClientContext* context, const $Request$& request, " - "::grpc::CompletionQueue* cq, void* tag) GRPC_OVERRIDE;\n"); + "::grpc::CompletionQueue* cq, void* tag) override;\n"); } else if (method->BidiStreaming()) { - printer->Print( - *vars, - "::grpc::ClientReaderWriter< $Request$, $Response$>* " - "$Method$Raw(::grpc::ClientContext* context) GRPC_OVERRIDE;\n"); - printer->Print( - *vars, - "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>* " - "Async$Method$Raw(::grpc::ClientContext* context, " - "::grpc::CompletionQueue* cq, void* tag) GRPC_OVERRIDE;\n"); + printer->Print(*vars, + "::grpc::ClientReaderWriter< $Request$, $Response$>* " + "$Method$Raw(::grpc::ClientContext* context) override;\n"); + printer->Print(*vars, + "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>* " + "Async$Method$Raw(::grpc::ClientContext* context, " + "::grpc::CompletionQueue* cq, void* tag) override;\n"); } } } @@ -509,7 +506,7 @@ void PrintHeaderServerMethodAsync(Printer *printer, const Method *method, " ::grpc::Service::MarkMethodAsync($Idx$);\n" "}\n"); printer->Print(*vars, - "~WithAsyncMethod_$Method$() GRPC_OVERRIDE {\n" + "~WithAsyncMethod_$Method$() override {\n" " BaseClassMustBeDerivedFromService(this);\n" "}\n"); if (method->NoStreaming()) { @@ -518,7 +515,7 @@ void PrintHeaderServerMethodAsync(Printer *printer, const Method *method, "// disable synchronous version of this method\n" "::grpc::Status $Method$(" "::grpc::ServerContext* context, const $Request$* request, " - "$Response$* response) GRPC_FINAL GRPC_OVERRIDE {\n" + "$Response$* response) final override {\n" " abort();\n" " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" "}\n"); @@ -540,7 +537,7 @@ void PrintHeaderServerMethodAsync(Printer *printer, const Method *method, "::grpc::Status $Method$(" "::grpc::ServerContext* context, " "::grpc::ServerReader< $Request$>* reader, " - "$Response$* response) GRPC_FINAL GRPC_OVERRIDE {\n" + "$Response$* response) final override {\n" " abort();\n" " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" "}\n"); @@ -561,7 +558,7 @@ void PrintHeaderServerMethodAsync(Printer *printer, const Method *method, "// disable synchronous version of this method\n" "::grpc::Status $Method$(" "::grpc::ServerContext* context, const $Request$* request, " - "::grpc::ServerWriter< $Response$>* writer) GRPC_FINAL GRPC_OVERRIDE " + "::grpc::ServerWriter< $Response$>* writer) final override " "{\n" " abort();\n" " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" @@ -585,7 +582,7 @@ void PrintHeaderServerMethodAsync(Printer *printer, const Method *method, "::grpc::Status $Method$(" "::grpc::ServerContext* context, " "::grpc::ServerReaderWriter< $Response$, $Request$>* stream) " - "GRPC_FINAL GRPC_OVERRIDE {\n" + "final override {\n" " abort();\n" " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" "}\n"); @@ -632,7 +629,7 @@ void PrintHeaderServerMethodStreamedUnary( "std::placeholders::_2)));\n" "}\n"); printer->Print(*vars, - "~WithStreamedUnaryMethod_$Method$() GRPC_OVERRIDE {\n" + "~WithStreamedUnaryMethod_$Method$() override {\n" " BaseClassMustBeDerivedFromService(this);\n" "}\n"); printer->Print( @@ -640,7 +637,7 @@ void PrintHeaderServerMethodStreamedUnary( "// disable regular version of this method\n" "::grpc::Status $Method$(" "::grpc::ServerContext* context, const $Request$* request, " - "$Response$* response) GRPC_FINAL GRPC_OVERRIDE {\n" + "$Response$* response) final override {\n" " abort();\n" " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" "}\n"); @@ -683,7 +680,7 @@ void PrintHeaderServerMethodSplitStreaming( "std::placeholders::_2)));\n" "}\n"); printer->Print(*vars, - "~WithSplitStreamingMethod_$Method$() GRPC_OVERRIDE {\n" + "~WithSplitStreamingMethod_$Method$() override {\n" " BaseClassMustBeDerivedFromService(this);\n" "}\n"); printer->Print( @@ -691,7 +688,7 @@ void PrintHeaderServerMethodSplitStreaming( "// disable regular version of this method\n" "::grpc::Status $Method$(" "::grpc::ServerContext* context, const $Request$* request, " - "::grpc::ServerWriter< $Response$>* writer) GRPC_FINAL GRPC_OVERRIDE " + "::grpc::ServerWriter< $Response$>* writer) final override " "{\n" " abort();\n" " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" @@ -727,7 +724,7 @@ void PrintHeaderServerMethodGeneric( " ::grpc::Service::MarkMethodGeneric($Idx$);\n" "}\n"); printer->Print(*vars, - "~WithGenericMethod_$Method$() GRPC_OVERRIDE {\n" + "~WithGenericMethod_$Method$() override {\n" " BaseClassMustBeDerivedFromService(this);\n" "}\n"); if (method->NoStreaming()) { @@ -736,7 +733,7 @@ void PrintHeaderServerMethodGeneric( "// disable synchronous version of this method\n" "::grpc::Status $Method$(" "::grpc::ServerContext* context, const $Request$* request, " - "$Response$* response) GRPC_FINAL GRPC_OVERRIDE {\n" + "$Response$* response) final override {\n" " abort();\n" " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" "}\n"); @@ -747,7 +744,7 @@ void PrintHeaderServerMethodGeneric( "::grpc::Status $Method$(" "::grpc::ServerContext* context, " "::grpc::ServerReader< $Request$>* reader, " - "$Response$* response) GRPC_FINAL GRPC_OVERRIDE {\n" + "$Response$* response) final override {\n" " abort();\n" " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" "}\n"); @@ -757,7 +754,7 @@ void PrintHeaderServerMethodGeneric( "// disable synchronous version of this method\n" "::grpc::Status $Method$(" "::grpc::ServerContext* context, const $Request$* request, " - "::grpc::ServerWriter< $Response$>* writer) GRPC_FINAL GRPC_OVERRIDE " + "::grpc::ServerWriter< $Response$>* writer) final override " "{\n" " abort();\n" " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" @@ -769,7 +766,7 @@ void PrintHeaderServerMethodGeneric( "::grpc::Status $Method$(" "::grpc::ServerContext* context, " "::grpc::ServerReaderWriter< $Response$, $Request$>* stream) " - "GRPC_FINAL GRPC_OVERRIDE {\n" + "final override {\n" " abort();\n" " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" "}\n"); @@ -784,7 +781,7 @@ void PrintHeaderService(Printer *printer, const Service *service, printer->Print(service->GetLeadingComments().c_str()); printer->Print(*vars, - "class $Service$ GRPC_FINAL {\n" + "class $Service$ final {\n" " public:\n"); printer->Indent(); @@ -810,7 +807,7 @@ void PrintHeaderService(Printer *printer, const Service *service, printer->Outdent(); printer->Print("};\n"); printer->Print( - "class Stub GRPC_FINAL : public StubInterface" + "class Stub final : public StubInterface" " {\n public:\n"); printer->Indent(); printer->Print( diff --git a/src/compiler/python_generator.cc b/src/compiler/python_generator.cc index 6830f49931d..febaf135b6f 100644 --- a/src/compiler/python_generator.cc +++ b/src/compiler/python_generator.cc @@ -35,6 +35,8 @@ #include #include #include +#include +#include #include #include #include @@ -66,66 +68,11 @@ using std::vector; namespace grpc_python_generator { -GeneratorConfiguration::GeneratorConfiguration() - : grpc_package_root("grpc"), beta_package_root("grpc.beta") {} - -PythonGrpcGenerator::PythonGrpcGenerator(const GeneratorConfiguration& config) - : config_(config) {} - -PythonGrpcGenerator::~PythonGrpcGenerator() {} - -bool PythonGrpcGenerator::Generate(const FileDescriptor* file, - const grpc::string& parameter, - GeneratorContext* context, - grpc::string* error) const { - // Get output file name. - grpc::string file_name; - static const int proto_suffix_length = strlen(".proto"); - if (file->name().size() > static_cast(proto_suffix_length) && - file->name().find_last_of(".proto") == file->name().size() - 1) { - file_name = - file->name().substr(0, file->name().size() - proto_suffix_length) + - "_pb2.py"; - } else { - *error = "Invalid proto file name. Proto file must end with .proto"; - return false; - } - - std::unique_ptr output( - context->OpenForInsert(file_name, "module_scope")); - CodedOutputStream coded_out(output.get()); - bool success = false; - grpc::string code = ""; - tie(success, code) = grpc_python_generator::GetServices(file, config_); - if (success) { - coded_out.WriteRaw(code.data(), code.size()); - return true; - } else { - return false; - } -} - namespace { -////////////////////////////////// -// BEGIN FORMATTING BOILERPLATE // -////////////////////////////////// - -// 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. -map ListToDict( - const initializer_list& values) { - assert(values.size() % 2 == 0); - map value_map; - auto value_iter = values.begin(); - for (unsigned i = 0; i < values.size() / 2; ++i) { - grpc::string key = *value_iter; - ++value_iter; - grpc::string value = *value_iter; - value_map[key] = value; - ++value_iter; - } - return value_map; -} + +typedef vector DescriptorVector; +typedef map StringMap; +typedef vector StringVector; // Provides RAII indentation handling. Use as: // { @@ -146,10 +93,6 @@ class IndentScope { Printer* printer_; }; -//////////////////////////////// -// END FORMATTING BOILERPLATE // -//////////////////////////////// - // TODO(https://github.com/google/protobuf/issues/888): // Export `ModuleName` from protobuf's // `src/google/protobuf/compiler/python/python_generator.cc` file. @@ -173,11 +116,61 @@ grpc::string ModuleAlias(const grpc::string& filename) { return module_name; } -bool GetModuleAndMessagePath(const Descriptor* type, - const ServiceDescriptor* service, - grpc::string* out) { +// Tucks all generator state in an anonymous namespace away from +// PythonGrpcGenerator and the header file, mostly to encourage future changes +// to not require updates to the grpcio-tools C++ code part. Assumes that it is +// only ever used from a single thread. +struct PrivateGenerator { + const GeneratorConfiguration& config; + const FileDescriptor* file; + + bool generate_in_pb2_grpc; + + Printer* out; + + PrivateGenerator(const GeneratorConfiguration& config, + const FileDescriptor* file); + + std::pair GetGrpcServices(); + + private: + bool PrintPreamble(); + bool PrintBetaPreamble(); + bool PrintGAServices(); + bool PrintBetaServices(); + + bool PrintAddServicerToServer( + const grpc::string& package_qualified_service_name, + const ServiceDescriptor* service); + bool PrintServicer(const ServiceDescriptor* service); + bool PrintStub(const grpc::string& package_qualified_service_name, + const ServiceDescriptor* service); + + bool PrintBetaServicer(const ServiceDescriptor* service); + bool PrintBetaServerFactory( + const grpc::string& package_qualified_service_name, + const ServiceDescriptor* service); + bool PrintBetaStub(const ServiceDescriptor* service); + bool PrintBetaStubFactory(const grpc::string& package_qualified_service_name, + const ServiceDescriptor* service); + + // Get all comments (leading, leading_detached, trailing) and print them as a + // docstring. Any leading space of a line will be removed, but the line + // wrapping will not be changed. + template + void PrintAllComments(const DescriptorType* descriptor); + + bool GetModuleAndMessagePath(const Descriptor* type, grpc::string* out); +}; + +PrivateGenerator::PrivateGenerator(const GeneratorConfiguration& config, + const FileDescriptor* file) + : config(config), file(file) {} + +bool PrivateGenerator::GetModuleAndMessagePath(const Descriptor* type, + grpc::string* out) { const Descriptor* path_elem_type = type; - vector message_path; + DescriptorVector message_path; do { message_path.push_back(path_elem_type); path_elem_type = path_elem_type->containing_type(); @@ -188,12 +181,16 @@ bool GetModuleAndMessagePath(const Descriptor* type, file_name.find_last_of(".proto") == file_name.size() - 1)) { return false; } - grpc::string service_file_name = service->file()->name(); - grpc::string module = - service_file_name == file_name ? "" : ModuleAlias(file_name) + "."; + grpc::string generator_file_name = file->name(); + grpc::string module; + if (generator_file_name != file_name || generate_in_pb2_grpc) { + module = ModuleAlias(file_name) + "."; + } else { + module = ""; + } grpc::string message_type; - for (auto path_iter = message_path.rbegin(); path_iter != message_path.rend(); - ++path_iter) { + for (DescriptorVector::reverse_iterator path_iter = message_path.rbegin(); + path_iter != message_path.rend(); ++path_iter) { message_type += (*path_iter)->name() + "."; } // no pop_back prior to C++11 @@ -202,33 +199,31 @@ bool GetModuleAndMessagePath(const Descriptor* type, return true; } -// Get all comments (leading, leading_detached, trailing) and print them as a -// docstring. Any leading space of a line will be removed, but the line wrapping -// will not be changed. template -static void PrintAllComments(const DescriptorType* desc, Printer* printer) { - std::vector comments; - grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_LEADING_DETACHED, - &comments); - grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_LEADING, +void PrivateGenerator::PrintAllComments(const DescriptorType* descriptor) { + StringVector comments; + grpc_generator::GetComment( + descriptor, grpc_generator::COMMENTTYPE_LEADING_DETACHED, &comments); + grpc_generator::GetComment(descriptor, grpc_generator::COMMENTTYPE_LEADING, &comments); - grpc_generator::GetComment(desc, grpc_generator::COMMENTTYPE_TRAILING, + grpc_generator::GetComment(descriptor, grpc_generator::COMMENTTYPE_TRAILING, &comments); if (comments.empty()) { return; } - printer->Print("\"\"\""); - for (auto it = comments.begin(); it != comments.end(); ++it) { + out->Print("\"\"\""); + for (StringVector::iterator it = comments.begin(); it != comments.end(); + ++it) { size_t start_pos = it->find_first_not_of(' '); if (start_pos != grpc::string::npos) { - printer->Print(it->c_str() + start_pos); + out->Print(it->c_str() + start_pos); } - printer->Print("\n"); + out->Print("\n"); } - printer->Print("\"\"\"\n"); + out->Print("\"\"\"\n"); } -bool PrintBetaServicer(const ServiceDescriptor* service, Printer* out) { +bool PrivateGenerator::PrintBetaServicer(const ServiceDescriptor* service) { out->Print("\n\n"); out->Print("class Beta$Service$Servicer(object):\n", "Service", service->name()); @@ -241,16 +236,16 @@ bool PrintBetaServicer(const ServiceDescriptor* service, Printer* out) { "generated\n" "only to ease transition from grpcio<0.15.0 to " "grpcio>=0.15.0.\"\"\"\n"); - PrintAllComments(service, out); + PrintAllComments(service); for (int i = 0; i < service->method_count(); ++i) { - auto meth = service->method(i); + const MethodDescriptor* method = service->method(i); grpc::string arg_name = - meth->client_streaming() ? "request_iterator" : "request"; + method->client_streaming() ? "request_iterator" : "request"; out->Print("def $Method$(self, $ArgName$, context):\n", "Method", - meth->name(), "ArgName", arg_name); + method->name(), "ArgName", arg_name); { IndentScope raii_method_indent(out); - PrintAllComments(meth, out); + PrintAllComments(method); out->Print("context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)\n"); } } @@ -258,7 +253,7 @@ bool PrintBetaServicer(const ServiceDescriptor* service, Printer* out) { return true; } -bool PrintBetaStub(const ServiceDescriptor* service, Printer* out) { +bool PrivateGenerator::PrintBetaStub(const ServiceDescriptor* service) { out->Print("\n\n"); out->Print("class Beta$Service$Stub(object):\n", "Service", service->name()); { @@ -270,30 +265,33 @@ bool PrintBetaStub(const ServiceDescriptor* service, Printer* out) { "generated\n" "only to ease transition from grpcio<0.15.0 to " "grpcio>=0.15.0.\"\"\"\n"); - PrintAllComments(service, out); + PrintAllComments(service); for (int i = 0; i < service->method_count(); ++i) { - const MethodDescriptor* meth = service->method(i); + const MethodDescriptor* method = service->method(i); grpc::string arg_name = - meth->client_streaming() ? "request_iterator" : "request"; - auto methdict = ListToDict({"Method", meth->name(), "ArgName", arg_name}); - out->Print(methdict, + method->client_streaming() ? "request_iterator" : "request"; + StringMap method_dict; + method_dict["Method"] = method->name(); + method_dict["ArgName"] = arg_name; + out->Print(method_dict, "def $Method$(self, $ArgName$, timeout, metadata=None, " "with_call=False, protocol_options=None):\n"); { IndentScope raii_method_indent(out); - PrintAllComments(meth, out); + PrintAllComments(method); out->Print("raise NotImplementedError()\n"); } - if (!meth->server_streaming()) { - out->Print(methdict, "$Method$.future = None\n"); + if (!method->server_streaming()) { + out->Print(method_dict, "$Method$.future = None\n"); } } } return true; } -bool PrintBetaServerFactory(const grpc::string& package_qualified_service_name, - const ServiceDescriptor* service, Printer* out) { +bool PrivateGenerator::PrintBetaServerFactory( + const grpc::string& package_qualified_service_name, + const ServiceDescriptor* service) { out->Print("\n\n"); out->Print( "def beta_create_$Service$_server(servicer, pool=None, " @@ -307,9 +305,9 @@ bool PrintBetaServerFactory(const grpc::string& package_qualified_service_name, "file not marked beta) for all further purposes. This function was\n" "generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0" "\"\"\"\n"); - map method_implementation_constructors; - map input_message_modules_and_classes; - map output_message_modules_and_classes; + StringMap method_implementation_constructors; + StringMap input_message_modules_and_classes; + StringMap output_message_modules_and_classes; for (int i = 0; i < service->method_count(); ++i) { const MethodDescriptor* method = service->method(i); const grpc::string method_implementation_constructor = @@ -317,12 +315,12 @@ bool PrintBetaServerFactory(const grpc::string& package_qualified_service_name, grpc::string(method->server_streaming() ? "stream_" : "unary_") + "inline"; grpc::string input_message_module_and_class; - if (!GetModuleAndMessagePath(method->input_type(), service, + if (!GetModuleAndMessagePath(method->input_type(), &input_message_module_and_class)) { return false; } grpc::string output_message_module_and_class; - if (!GetModuleAndMessagePath(method->output_type(), service, + if (!GetModuleAndMessagePath(method->output_type(), &output_message_module_and_class)) { return false; } @@ -334,7 +332,7 @@ bool PrintBetaServerFactory(const grpc::string& package_qualified_service_name, make_pair(method->name(), output_message_module_and_class)); } out->Print("request_deserializers = {\n"); - for (auto name_and_input_module_class_pair = + for (StringMap::iterator name_and_input_module_class_pair = input_message_modules_and_classes.begin(); name_and_input_module_class_pair != input_message_modules_and_classes.end(); @@ -349,7 +347,7 @@ bool PrintBetaServerFactory(const grpc::string& package_qualified_service_name, } out->Print("}\n"); out->Print("response_serializers = {\n"); - for (auto name_and_output_module_class_pair = + for (StringMap::iterator name_and_output_module_class_pair = output_message_modules_and_classes.begin(); name_and_output_module_class_pair != output_message_modules_and_classes.end(); @@ -365,7 +363,7 @@ bool PrintBetaServerFactory(const grpc::string& package_qualified_service_name, } out->Print("}\n"); out->Print("method_implementations = {\n"); - for (auto name_and_implementation_constructor = + for (StringMap::iterator name_and_implementation_constructor = method_implementation_constructors.begin(); name_and_implementation_constructor != method_implementation_constructors.end(); @@ -395,11 +393,11 @@ bool PrintBetaServerFactory(const grpc::string& package_qualified_service_name, return true; } -bool PrintBetaStubFactory(const grpc::string& package_qualified_service_name, - const ServiceDescriptor* service, Printer* out) { - map dict = ListToDict({ - "Service", service->name(), - }); +bool PrivateGenerator::PrintBetaStubFactory( + const grpc::string& package_qualified_service_name, + const ServiceDescriptor* service) { + StringMap dict; + dict["Service"] = service->name(); out->Print("\n\n"); out->Print(dict, "def beta_create_$Service$_stub(channel, host=None," @@ -412,21 +410,21 @@ bool PrintBetaStubFactory(const grpc::string& package_qualified_service_name, "file not marked beta) for all further purposes. This function was\n" "generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0" "\"\"\"\n"); - map method_cardinalities; - map input_message_modules_and_classes; - map output_message_modules_and_classes; + StringMap method_cardinalities; + StringMap input_message_modules_and_classes; + StringMap output_message_modules_and_classes; for (int i = 0; i < service->method_count(); ++i) { const MethodDescriptor* method = service->method(i); const grpc::string method_cardinality = grpc::string(method->client_streaming() ? "STREAM" : "UNARY") + "_" + grpc::string(method->server_streaming() ? "STREAM" : "UNARY"); grpc::string input_message_module_and_class; - if (!GetModuleAndMessagePath(method->input_type(), service, + if (!GetModuleAndMessagePath(method->input_type(), &input_message_module_and_class)) { return false; } grpc::string output_message_module_and_class; - if (!GetModuleAndMessagePath(method->output_type(), service, + if (!GetModuleAndMessagePath(method->output_type(), &output_message_module_and_class)) { return false; } @@ -438,7 +436,7 @@ bool PrintBetaStubFactory(const grpc::string& package_qualified_service_name, make_pair(method->name(), output_message_module_and_class)); } out->Print("request_serializers = {\n"); - for (auto name_and_input_module_class_pair = + for (StringMap::iterator name_and_input_module_class_pair = input_message_modules_and_classes.begin(); name_and_input_module_class_pair != input_message_modules_and_classes.end(); @@ -453,7 +451,7 @@ bool PrintBetaStubFactory(const grpc::string& package_qualified_service_name, } out->Print("}\n"); out->Print("response_deserializers = {\n"); - for (auto name_and_output_module_class_pair = + for (StringMap::iterator name_and_output_module_class_pair = output_message_modules_and_classes.begin(); name_and_output_module_class_pair != output_message_modules_and_classes.end(); @@ -469,7 +467,8 @@ bool PrintBetaStubFactory(const grpc::string& package_qualified_service_name, } out->Print("}\n"); out->Print("cardinalities = {\n"); - for (auto name_and_cardinality = method_cardinalities.begin(); + for (StringMap::iterator name_and_cardinality = + method_cardinalities.begin(); name_and_cardinality != method_cardinalities.end(); name_and_cardinality++) { IndentScope raii_descriptions_indent(out); @@ -493,13 +492,14 @@ bool PrintBetaStubFactory(const grpc::string& package_qualified_service_name, return true; } -bool PrintStub(const grpc::string& package_qualified_service_name, - const ServiceDescriptor* service, Printer* out) { +bool PrivateGenerator::PrintStub( + const grpc::string& package_qualified_service_name, + const ServiceDescriptor* service) { out->Print("\n\n"); out->Print("class $Service$Stub(object):\n", "Service", service->name()); { IndentScope raii_class_indent(out); - PrintAllComments(service, out); + PrintAllComments(service); out->Print("\n"); out->Print("def __init__(self, channel):\n"); { @@ -513,17 +513,17 @@ bool PrintStub(const grpc::string& package_qualified_service_name, } out->Print("\"\"\"\n"); for (int i = 0; i < service->method_count(); ++i) { - auto method = service->method(i); - auto multi_callable_constructor = + const MethodDescriptor* method = service->method(i); + grpc::string multi_callable_constructor = grpc::string(method->client_streaming() ? "stream" : "unary") + "_" + grpc::string(method->server_streaming() ? "stream" : "unary"); grpc::string request_module_and_class; - if (!GetModuleAndMessagePath(method->input_type(), service, + if (!GetModuleAndMessagePath(method->input_type(), &request_module_and_class)) { return false; } grpc::string response_module_and_class; - if (!GetModuleAndMessagePath(method->output_type(), service, + if (!GetModuleAndMessagePath(method->output_type(), &response_module_and_class)) { return false; } @@ -550,14 +550,14 @@ bool PrintStub(const grpc::string& package_qualified_service_name, return true; } -bool PrintServicer(const ServiceDescriptor* service, Printer* out) { +bool PrivateGenerator::PrintServicer(const ServiceDescriptor* service) { out->Print("\n\n"); out->Print("class $Service$Servicer(object):\n", "Service", service->name()); { IndentScope raii_class_indent(out); - PrintAllComments(service, out); + PrintAllComments(service); for (int i = 0; i < service->method_count(); ++i) { - auto method = service->method(i); + const MethodDescriptor* method = service->method(i); grpc::string arg_name = method->client_streaming() ? "request_iterator" : "request"; out->Print("\n"); @@ -565,7 +565,7 @@ bool PrintServicer(const ServiceDescriptor* service, Printer* out) { method->name(), "ArgName", arg_name); { IndentScope raii_method_indent(out); - PrintAllComments(method, out); + PrintAllComments(method); out->Print("context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n"); out->Print("context.set_details('Method not implemented!')\n"); out->Print("raise NotImplementedError('Method not implemented!')\n"); @@ -575,9 +575,9 @@ bool PrintServicer(const ServiceDescriptor* service, Printer* out) { return true; } -bool PrintAddServicerToServer( +bool PrivateGenerator::PrintAddServicerToServer( const grpc::string& package_qualified_service_name, - const ServiceDescriptor* service, Printer* out) { + const ServiceDescriptor* service) { out->Print("\n\n"); out->Print("def add_$Service$Servicer_to_server(servicer, server):\n", "Service", service->name()); @@ -588,19 +588,19 @@ bool PrintAddServicerToServer( IndentScope raii_dict_first_indent(out); IndentScope raii_dict_second_indent(out); for (int i = 0; i < service->method_count(); ++i) { - auto method = service->method(i); - auto method_handler_constructor = + const MethodDescriptor* method = service->method(i); + grpc::string method_handler_constructor = grpc::string(method->client_streaming() ? "stream" : "unary") + "_" + grpc::string(method->server_streaming() ? "stream" : "unary") + "_rpc_method_handler"; grpc::string request_module_and_class; - if (!GetModuleAndMessagePath(method->input_type(), service, + if (!GetModuleAndMessagePath(method->input_type(), &request_module_and_class)) { return false; } grpc::string response_module_and_class; - if (!GetModuleAndMessagePath(method->output_type(), service, + if (!GetModuleAndMessagePath(method->output_type(), &response_module_and_class)) { return false; } @@ -635,53 +635,173 @@ bool PrintAddServicerToServer( return true; } -bool PrintPreamble(const FileDescriptor* file, - const GeneratorConfiguration& config, Printer* out) { - out->Print("import $Package$\n", "Package", config.grpc_package_root); +bool PrivateGenerator::PrintBetaPreamble() { out->Print("from $Package$ import implementations as beta_implementations\n", "Package", config.beta_package_root); out->Print("from $Package$ import interfaces as beta_interfaces\n", "Package", config.beta_package_root); + return true; +} + +bool PrivateGenerator::PrintPreamble() { + out->Print("import $Package$\n", "Package", config.grpc_package_root); out->Print("from grpc.framework.common import cardinality\n"); out->Print( "from grpc.framework.interfaces.face import utilities as " "face_utilities\n"); + if (generate_in_pb2_grpc) { + out->Print("\n"); + for (int i = 0; i < file->service_count(); ++i) { + const ServiceDescriptor* service = file->service(i); + for (int j = 0; j < service->method_count(); ++j) { + const MethodDescriptor* method = service->method(j); + const Descriptor* types[2] = {method->input_type(), + method->output_type()}; + for (int k = 0; k < 2; ++k) { + const Descriptor* type = types[k]; + grpc::string type_file_name = type->file()->name(); + grpc::string module_name = ModuleName(type_file_name); + grpc::string module_alias = ModuleAlias(type_file_name); + out->Print("import $ModuleName$ as $ModuleAlias$\n", "ModuleName", + module_name, "ModuleAlias", module_alias); + } + } + } + } return true; } -} // namespace +bool PrivateGenerator::PrintGAServices() { + grpc::string package = file->package(); + if (!package.empty()) { + package = package.append("."); + } + for (int i = 0; i < file->service_count(); ++i) { + const ServiceDescriptor* service = file->service(i); + grpc::string package_qualified_service_name = package + service->name(); + if (!(PrintStub(package_qualified_service_name, service) && + PrintServicer(service) && + PrintAddServicerToServer(package_qualified_service_name, service))) { + return false; + } + } + return true; +} -pair GetServices(const FileDescriptor* file, - const GeneratorConfiguration& config) { +bool PrivateGenerator::PrintBetaServices() { + grpc::string package = file->package(); + if (!package.empty()) { + package = package.append("."); + } + for (int i = 0; i < file->service_count(); ++i) { + const ServiceDescriptor* service = file->service(i); + grpc::string package_qualified_service_name = package + service->name(); + if (!(PrintBetaServicer(service) && PrintBetaStub(service) && + PrintBetaServerFactory(package_qualified_service_name, service) && + PrintBetaStubFactory(package_qualified_service_name, service))) { + return false; + } + } + return true; +} + +pair PrivateGenerator::GetGrpcServices() { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. StringOutputStream output_stream(&output); - Printer out(&output_stream, '$'); - if (!PrintPreamble(file, config, &out)) { - return make_pair(false, ""); - } - auto package = file->package(); - if (!package.empty()) { - package = package.append("."); - } - for (int i = 0; i < file->service_count(); ++i) { - auto service = file->service(i); - auto package_qualified_service_name = package + service->name(); - if (!(PrintStub(package_qualified_service_name, service, &out) && - PrintServicer(service, &out) && - PrintAddServicerToServer(package_qualified_service_name, service, - &out) && - PrintBetaServicer(service, &out) && PrintBetaStub(service, &out) && - PrintBetaServerFactory(package_qualified_service_name, service, - &out) && - PrintBetaStubFactory(package_qualified_service_name, service, - &out))) { + Printer out_printer(&output_stream, '$'); + out = &out_printer; + + if (generate_in_pb2_grpc) { + if (!PrintPreamble()) { + return make_pair(false, ""); + } + if (!PrintGAServices()) { return make_pair(false, ""); } + } else { + out->Print("try:\n"); + { + IndentScope raii_dict_try_indent(out); + out->Print( + "# THESE ELEMENTS WILL BE DEPRECATED.\n" + "# Please use the generated *_pb2_grpc.py files instead.\n"); + if (!PrintPreamble()) { + return make_pair(false, ""); + } + if (!PrintBetaPreamble()) { + return make_pair(false, ""); + } + if (!PrintGAServices()) { + return make_pair(false, ""); + } + if (!PrintBetaServices()) { + return make_pair(false, ""); + } + } + out->Print("except ImportError:\n"); + { + IndentScope raii_dict_except_indent(out); + out->Print("pass"); + } } } return make_pair(true, std::move(output)); } +} // namespace + +GeneratorConfiguration::GeneratorConfiguration() + : grpc_package_root("grpc"), beta_package_root("grpc.beta") {} + +PythonGrpcGenerator::PythonGrpcGenerator(const GeneratorConfiguration& config) + : config_(config) {} + +PythonGrpcGenerator::~PythonGrpcGenerator() {} + +bool PythonGrpcGenerator::Generate(const FileDescriptor* file, + const grpc::string& parameter, + GeneratorContext* context, + grpc::string* error) const { + // Get output file name. + grpc::string pb2_file_name; + grpc::string pb2_grpc_file_name; + static const int proto_suffix_length = strlen(".proto"); + if (file->name().size() > static_cast(proto_suffix_length) && + file->name().find_last_of(".proto") == file->name().size() - 1) { + grpc::string base = + file->name().substr(0, file->name().size() - proto_suffix_length); + pb2_file_name = base + "_pb2.py"; + pb2_grpc_file_name = base + "_pb2_grpc.py"; + } else { + *error = "Invalid proto file name. Proto file must end with .proto"; + return false; + } + + PrivateGenerator generator(config_, file); + + std::unique_ptr pb2_output( + context->OpenForAppend(pb2_file_name)); + std::unique_ptr grpc_output( + context->Open(pb2_grpc_file_name)); + CodedOutputStream pb2_coded_out(pb2_output.get()); + CodedOutputStream grpc_coded_out(grpc_output.get()); + bool success = false; + grpc::string pb2_code; + grpc::string grpc_code; + generator.generate_in_pb2_grpc = false; + tie(success, pb2_code) = generator.GetGrpcServices(); + if (success) { + generator.generate_in_pb2_grpc = true; + tie(success, grpc_code) = generator.GetGrpcServices(); + if (success) { + pb2_coded_out.WriteRaw(pb2_code.data(), pb2_code.size()); + grpc_coded_out.WriteRaw(grpc_code.data(), grpc_code.size()); + return true; + } + } + return false; +} + } // namespace grpc_python_generator diff --git a/src/compiler/python_generator.h b/src/compiler/python_generator.h index 9bbb83bca6e..6a95255d40e 100644 --- a/src/compiler/python_generator.h +++ b/src/compiler/python_generator.h @@ -62,10 +62,6 @@ class PythonGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator { GeneratorConfiguration config_; }; -std::pair GetServices( - const grpc::protobuf::FileDescriptor* file, - const GeneratorConfiguration& config); - } // namespace grpc_python_generator #endif // GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_H diff --git a/src/compiler/ruby_generator.cc b/src/compiler/ruby_generator.cc index 02202568cb4..c85babf1b86 100644 --- a/src/compiler/ruby_generator.cc +++ b/src/compiler/ruby_generator.cc @@ -119,6 +119,43 @@ void PrintService(const ServiceDescriptor *service, const grpc::string &package, } // namespace +// The following functions are copied directly from the source for the protoc +// ruby generator +// to ensure compatibility (with the exception of int and string type changes). +// See +// https://github.com/google/protobuf/blob/master/src/google/protobuf/compiler/ruby/ruby_generator.cc#L250 +// TODO: keep up to date with protoc code generation, though this behavior isn't +// expected to change +bool IsLower(char ch) { return ch >= 'a' && ch <= 'z'; } + +char ToUpper(char ch) { return IsLower(ch) ? (ch - 'a' + 'A') : ch; } + +// Package names in protobuf are snake_case by convention, but Ruby module +// names must be PascalCased. +// +// foo_bar_baz -> FooBarBaz +grpc::string PackageToModule(const grpc::string &name) { + bool next_upper = true; + grpc::string result; + result.reserve(name.size()); + + for (grpc::string::size_type i = 0; i < name.size(); i++) { + if (name[i] == '_') { + next_upper = true; + } else { + if (next_upper) { + result.push_back(ToUpper(name[i])); + } else { + result.push_back(name[i]); + } + next_upper = false; + } + } + + return result; +} +// end copying of protoc generator for ruby code + grpc::string GetServices(const FileDescriptor *file) { grpc::string output; { @@ -162,7 +199,7 @@ 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", CapitalizeFirst(modules[i]), + "module.name", PackageToModule(modules[i]), }); out.Print(module_vars, "module $module.name$\n"); out.Indent(); diff --git a/src/core/ext/client_channel/client_channel.c b/src/core/ext/client_channel/client_channel.c index d15af0b438c..3b89f938c2e 100644 --- a/src/core/ext/client_channel/client_channel.c +++ b/src/core/ext/client_channel/client_channel.c @@ -1042,6 +1042,10 @@ static void cc_destroy_call_elem(grpc_exec_ctx *exec_ctx, GPR_ASSERT(calld->creation_phase == GRPC_SUBCHANNEL_CALL_HOLDER_NOT_CREATING); gpr_mu_destroy(&calld->mu); GPR_ASSERT(calld->waiting_ops_count == 0); + if (calld->connected_subchannel != NULL) { + GRPC_CONNECTED_SUBCHANNEL_UNREF(exec_ctx, calld->connected_subchannel, + "picked"); + } gpr_free(calld->waiting_ops); gpr_free(and_free_memory); } diff --git a/src/core/ext/client_channel/lb_policy.h b/src/core/ext/client_channel/lb_policy.h index 54ad7797920..120c641edc6 100644 --- a/src/core/ext/client_channel/lb_policy.h +++ b/src/core/ext/client_channel/lb_policy.h @@ -109,10 +109,16 @@ struct grpc_lb_policy_vtable { /*#define GRPC_LB_POLICY_REFCOUNT_DEBUG*/ #ifdef GRPC_LB_POLICY_REFCOUNT_DEBUG + +/* Strong references: the policy will shutdown when they reach zero */ #define GRPC_LB_POLICY_REF(p, r) \ grpc_lb_policy_ref((p), __FILE__, __LINE__, (r)) #define GRPC_LB_POLICY_UNREF(exec_ctx, p, r) \ grpc_lb_policy_unref((exec_ctx), (p), __FILE__, __LINE__, (r)) + +/* Weak references: they don't prevent the shutdown of the LB policy. When no + * strong references are left but there are still weak ones, shutdown is called. + * Once the weak reference also reaches zero, the LB policy is destroyed. */ #define GRPC_LB_POLICY_WEAK_REF(p, r) \ grpc_lb_policy_weak_ref((p), __FILE__, __LINE__, (r)) #define GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, p, r) \ diff --git a/src/core/ext/client_channel/subchannel.c b/src/core/ext/client_channel/subchannel.c index ab6aede23ac..789966cb693 100644 --- a/src/core/ext/client_channel/subchannel.c +++ b/src/core/ext/client_channel/subchannel.c @@ -183,9 +183,10 @@ static void connection_destroy(grpc_exec_ctx *exec_ctx, void *arg, gpr_free(c); } -void grpc_connected_subchannel_ref( +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, diff --git a/src/core/ext/client_channel/subchannel.h b/src/core/ext/client_channel/subchannel.h index 56520740741..93bd72d20d5 100644 --- a/src/core/ext/client_channel/subchannel.h +++ b/src/core/ext/client_channel/subchannel.h @@ -97,7 +97,7 @@ grpc_subchannel *grpc_subchannel_weak_ref( void grpc_subchannel_weak_unref(grpc_exec_ctx *exec_ctx, grpc_subchannel *channel GRPC_SUBCHANNEL_REF_EXTRA_ARGS); -void grpc_connected_subchannel_ref( +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 diff --git a/src/core/ext/lb_policy/grpclb/grpclb.c b/src/core/ext/lb_policy/grpclb/grpclb.c index 6da4febf266..30e412e3580 100644 --- a/src/core/ext/lb_policy/grpclb/grpclb.c +++ b/src/core/ext/lb_policy/grpclb/grpclb.c @@ -43,30 +43,23 @@ * policy to select from this list of LB server backends. * * The first time the policy gets a request for a pick, a ping, or to exit the - * idle state, \a query_for_backends() is called. It creates an instance of \a - * lb_client_data, an internal struct meant to contain the data associated with - * the internal communication with the LB server. This instance is created via - * \a lb_client_data_create(). There, the call over lb_channel to pick-first - * from {a1..an} is created, the \a LoadBalancingRequest message is assembled - * and all necessary callbacks for the progress of the internal call configured. + * idle state, \a query_for_backends_locked() is called. This function sets up + * and initiates the internal communication with the LB server. In particular, + * it's responsible for instantiating the internal *streaming* call to the LB + * server (whichever address from {a1..an} pick-first chose). This call is + * serviced by two callbacks, \a lb_on_server_status_received and \a + * lb_on_response_received. The former will be called when the call to the LB + * server completes. This can happen if the LB server closes the connection or + * if this policy itself cancels the call (for example because it's shutting + * down). If the internal call times out, the usual behavior of pick-first + * applies, continuing to pick from the list {a1..an}. * - * Back in \a query_for_backends(), the internal *streaming* call to the LB - * server (whichever address from {a1..an} pick-first chose) is kicked off. - * It'll progress over the callbacks configured in \a lb_client_data_create() - * (see the field docstrings of \a lb_client_data for more details). - * - * If the call fails with UNIMPLEMENTED, the original call will also fail. - * There's a misconfiguration somewhere: at least one of {a1..an} isn't a LB - * server, which contradicts the LB bit being set. If the internal call times - * out, the usual behavior of pick-first applies, continuing to pick from the - * list {a1..an}. - * - * Upon sucesss, a \a LoadBalancingResponse is expected in \a res_recv_cb. An - * invalid one results in the termination of the streaming call. A new streaming - * call should be created if possible, failing the original call otherwise. - * For a valid \a LoadBalancingResponse, the server list of actual backends is - * extracted. A Round Robin policy will be created from this list. There are two - * possible scenarios: + * Upon sucesss, the incoming \a LoadBalancingResponse is processed by \a + * res_recv. An invalid one results in the termination of the streaming call. A + * new streaming call should be created if possible, failing the original call + * otherwise. For a valid \a LoadBalancingResponse, the server list of actual + * backends is extracted. A Round Robin policy will be created from this list. + * There are two possible scenarios: * * 1. This is the first server list received. There was no previous instance of * the Round Robin policy. \a rr_handover_locked() will instantiate the RR @@ -84,10 +77,10 @@ * Once a RR policy instance is in place (and getting updated as described), * calls to for a pick, a ping or a cancellation will be serviced right away by * forwarding them to the RR instance. Any time there's no RR policy available - * (ie, right after the creation of the gRPCLB policy, if an empty serverlist - * is received, etc), pick/ping requests are added to a list of pending - * picks/pings to be flushed and serviced as part of \a rr_handover_locked() the - * moment the RR policy instance becomes available. + * (ie, right after the creation of the gRPCLB policy, if an empty serverlist is + * received, etc), pick/ping requests are added to a list of pending picks/pings + * to be flushed and serviced as part of \a rr_handover_locked() the moment the + * RR policy instance becomes available. * * \see https://github.com/grpc/grpc/blob/master/doc/load-balancing.md for the * high level design and details. */ @@ -120,12 +113,20 @@ #include "src/core/ext/lb_policy/grpclb/grpclb.h" #include "src/core/ext/lb_policy/grpclb/load_balancer_api.h" #include "src/core/lib/channel/channel_args.h" +#include "src/core/lib/iomgr/sockaddr.h" #include "src/core/lib/iomgr/sockaddr_utils.h" +#include "src/core/lib/iomgr/timer.h" +#include "src/core/lib/support/backoff.h" #include "src/core/lib/support/string.h" #include "src/core/lib/surface/call.h" #include "src/core/lib/surface/channel.h" #include "src/core/lib/transport/static_metadata.h" +#define BACKOFF_MULTIPLIER 1.6 +#define BACKOFF_JITTER 0.2 +#define BACKOFF_MIN_SECONDS 10 +#define BACKOFF_MAX_SECONDS 60 + int grpc_lb_glb_trace = 0; /* add lb_token of selected subchannel (address) to the call's initial @@ -174,13 +175,12 @@ typedef struct wrapped_rr_closure_arg { static void wrapped_rr_closure(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { wrapped_rr_closure_arg *wc_arg = arg; - if (wc_arg->rr_policy != NULL) { - if (grpc_lb_glb_trace) { - gpr_log(GPR_INFO, "Unreffing RR (0x%" PRIxPTR ")", - (intptr_t)wc_arg->rr_policy); - } - GRPC_LB_POLICY_UNREF(exec_ctx, wc_arg->rr_policy, "wrapped_rr_closure"); + GPR_ASSERT(wc_arg->wrapped_closure != NULL); + grpc_exec_ctx_sched(exec_ctx, wc_arg->wrapped_closure, GRPC_ERROR_REF(error), + NULL); + + if (wc_arg->rr_policy != NULL) { /* 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 */ @@ -189,10 +189,12 @@ static void wrapped_rr_closure(grpc_exec_ctx *exec_ctx, void *arg, wc_arg->lb_token_mdelem_storage, GRPC_MDELEM_REF(wc_arg->lb_token)); } + if (grpc_lb_glb_trace) { + gpr_log(GPR_INFO, "Unreffing RR (0x%" PRIxPTR ")", + (intptr_t)wc_arg->rr_policy); + } + GRPC_LB_POLICY_UNREF(exec_ctx, wc_arg->rr_policy, "wrapped_rr_closure"); } - GPR_ASSERT(wc_arg->wrapped_closure != NULL); - grpc_exec_ctx_sched(exec_ctx, wc_arg->wrapped_closure, GRPC_ERROR_REF(error), - NULL); GPR_ASSERT(wc_arg->free_when_done != NULL); gpr_free(wc_arg->free_when_done); } @@ -264,7 +266,6 @@ static void add_pending_ping(pending_ping **root, grpc_closure *notify) { * glb_lb_policy */ typedef struct rr_connectivity_data rr_connectivity_data; -struct lb_client_data; static const grpc_lb_policy_vtable glb_lb_policy_vtable; typedef struct glb_lb_policy { /** base policy: must be first */ @@ -296,20 +297,47 @@ typedef struct glb_lb_policy { * response has arrived. */ grpc_grpclb_serverlist *serverlist; - /** addresses from \a serverlist */ - grpc_lb_addresses *addresses; - /** list of picks that are waiting on RR's policy connectivity */ pending_pick *pending_picks; /** list of pings that are waiting on RR's policy connectivity */ pending_ping *pending_pings; - /** client data associated with the LB server communication */ - struct lb_client_data *lb_client; + bool shutting_down; + + /************************************************************/ + /* client data associated with the LB server communication */ + /************************************************************/ + /* Status from the LB server has been received. This signals the end of the LB + * call. */ + grpc_closure lb_on_server_status_received; + + /* A response from the LB server has been received. Process it */ + grpc_closure lb_on_response_received; + + 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 + lb_trailing_metadata_recv; /* trailing MD from LB server */ + + /* 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; + + /* response the LB server, if any. Processed in lb_on_response_received() */ + grpc_byte_buffer *lb_response_payload; + + /* call status code and details, set in lb_on_server_status_received() */ + grpc_status_code lb_call_status; + char *lb_call_status_details; + size_t lb_call_status_details_capacity; + + /** LB call retry backoff state */ + gpr_backoff lb_call_backoff_state; - /** for tracking of the RR connectivity */ - rr_connectivity_data *rr_connectivity; + /** LB call retry timer */ + grpc_timer lb_call_retry_timer; } glb_lb_policy; /* Keeps track and reacts to changes in connectivity of the RR instance */ @@ -358,6 +386,28 @@ 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) { + 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; + memset(addr, 0, sizeof(*addr)); + if (ip->size == 4) { + addr->len = sizeof(struct sockaddr_in); + 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; + addr6->sin6_family = AF_INET6; + memcpy(&addr6->sin6_addr, ip->bytes, ip->size); + addr6->sin6_port = netorder_port; + } +} + /* Returns addresses extracted from \a serverlist. */ static grpc_lb_addresses *process_serverlist( const grpc_grpclb_serverlist *serverlist) { @@ -384,33 +434,18 @@ static grpc_lb_addresses *process_serverlist( if (!is_server_valid(serverlist->servers[sl_idx], sl_idx, false)) continue; /* address processing */ - 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; grpc_resolved_address addr; - memset(&addr, 0, sizeof(addr)); - if (ip->size == 4) { - addr.len = sizeof(struct sockaddr_in); - 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; - addr6->sin6_family = AF_INET; - memcpy(&addr6->sin6_addr, ip->bytes, ip->size); - addr6->sin6_port = netorder_port; - } + parse_server(server, &addr); /* lb token processing */ void *user_data; if (server->has_load_balance_token) { - const size_t lb_token_size = - GPR_ARRAY_SIZE(server->load_balance_token) - 1; + const size_t lb_token_max_length = + GPR_ARRAY_SIZE(server->load_balance_token); + const size_t lb_token_length = + strnlen(server->load_balance_token, lb_token_max_length); grpc_mdstr *lb_token_mdstr = grpc_mdstr_from_buffer( - (uint8_t *)server->load_balance_token, lb_token_size); + (uint8_t *)server->load_balance_token, lb_token_length); user_data = grpc_mdelem_from_metadata_strings(GRPC_MDSTR_LB_TOKEN, lb_token_mdstr); } else { @@ -427,7 +462,6 @@ static grpc_lb_addresses *process_serverlist( ++addr_idx; } GPR_ASSERT(addr_idx == num_valid); - return lb_addresses; } @@ -448,7 +482,7 @@ static bool pick_from_internal_rr_locked( gpr_log(GPR_INFO, "Unreffing RR (0x%" PRIxPTR ")", (intptr_t)wc_arg->rr_policy); } - GRPC_LB_POLICY_UNREF(exec_ctx, wc_arg->rr_policy, "glb_pick"); + GRPC_LB_POLICY_UNREF(exec_ctx, wc_arg->rr_policy, "glb_pick_sync"); /* add the load reporting initial metadata */ initial_metadata_add_lb_token(pick_args->initial_metadata, @@ -461,7 +495,6 @@ static bool pick_from_internal_rr_locked( * pending pick list inside the RR policy (glb_policy->rr_policy). * Eventually, wrapped_on_complete will be called, which will -among other * things- add the LB token to the call's initial metadata */ - return pick_done; } @@ -470,54 +503,70 @@ static grpc_lb_policy *create_rr_locked( glb_lb_policy *glb_policy) { GPR_ASSERT(serverlist != NULL && serverlist->num_servers > 0); - if (glb_policy->addresses != NULL) { - /* dispose of the previous version */ - grpc_lb_addresses_destroy(glb_policy->addresses); - } - glb_policy->addresses = process_serverlist(serverlist); - grpc_lb_policy_args args; memset(&args, 0, sizeof(args)); args.client_channel_factory = glb_policy->cc_factory; + grpc_lb_addresses *addresses = process_serverlist(serverlist); // 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}; - const grpc_arg arg = - grpc_lb_addresses_create_channel_arg(glb_policy->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, 1); grpc_lb_policy *rr = grpc_lb_policy_create(exec_ctx, "round_robin", &args); + GPR_ASSERT(rr != NULL); + grpc_lb_addresses_destroy(addresses); grpc_channel_args_destroy(args.args); - return rr; } +static void glb_rr_connectivity_changed(grpc_exec_ctx *exec_ctx, void *arg, + grpc_error *error); +/* glb_policy->rr_policy may be NULL (initial handover) */ static void rr_handover_locked(grpc_exec_ctx *exec_ctx, glb_lb_policy *glb_policy, grpc_error *error) { GPR_ASSERT(glb_policy->serverlist != NULL && glb_policy->serverlist->num_servers > 0); + + if (grpc_lb_glb_trace) { + gpr_log(GPR_INFO, "RR handover. Old RR: %p", (void *)glb_policy->rr_policy); + } + if (glb_policy->rr_policy != NULL) { + /* if we are phasing out an existing RR instance, unref it. */ + GRPC_LB_POLICY_UNREF(exec_ctx, glb_policy->rr_policy, "rr_handover"); + } + glb_policy->rr_policy = create_rr_locked(exec_ctx, glb_policy->serverlist, glb_policy); - if (grpc_lb_glb_trace) { - gpr_log(GPR_INFO, "Created RR policy (0x%" PRIxPTR ")", - (intptr_t)glb_policy->rr_policy); + gpr_log(GPR_INFO, "Created RR policy (%p)", (void *)glb_policy->rr_policy); } + GPR_ASSERT(glb_policy->rr_policy != NULL); grpc_pollset_set_add_pollset_set(exec_ctx, glb_policy->rr_policy->interested_parties, glb_policy->base.interested_parties); - glb_policy->rr_connectivity->state = grpc_lb_policy_check_connectivity( + + rr_connectivity_data *rr_connectivity = + gpr_malloc(sizeof(rr_connectivity_data)); + memset(rr_connectivity, 0, sizeof(rr_connectivity_data)); + grpc_closure_init(&rr_connectivity->on_change, glb_rr_connectivity_changed, + rr_connectivity); + rr_connectivity->glb_policy = glb_policy; + rr_connectivity->state = grpc_lb_policy_check_connectivity( exec_ctx, glb_policy->rr_policy, &error); - grpc_lb_policy_notify_on_state_change( - exec_ctx, glb_policy->rr_policy, &glb_policy->rr_connectivity->state, - &glb_policy->rr_connectivity->on_change); + grpc_connectivity_state_set(exec_ctx, &glb_policy->state_tracker, - glb_policy->rr_connectivity->state, - GRPC_ERROR_REF(error), "rr_handover"); + rr_connectivity->state, GRPC_ERROR_REF(error), + "rr_handover"); + /* subscribe */ + GRPC_LB_POLICY_WEAK_REF(&glb_policy->base, "rr_connectivity_cb"); + grpc_lb_policy_notify_on_state_change(exec_ctx, glb_policy->rr_policy, + &rr_connectivity->state, + &rr_connectivity->on_change); grpc_lb_policy_exit_idle(exec_ctx, glb_policy->rr_policy); /* flush pending ops */ @@ -551,35 +600,27 @@ static void rr_handover_locked(grpc_exec_ctx *exec_ctx, static void glb_rr_connectivity_changed(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { + /* If shutdown or error free the arg. Rely on the rest of the code to set the + * right grpclb status. */ rr_connectivity_data *rr_conn_data = arg; glb_lb_policy *glb_policy = rr_conn_data->glb_policy; - if (rr_conn_data->state == GRPC_CHANNEL_SHUTDOWN) { - if (glb_policy->serverlist != NULL) { - /* a RR policy is shutting down but there's a serverlist available -> - * perform a handover */ - gpr_mu_lock(&glb_policy->mu); - rr_handover_locked(exec_ctx, glb_policy, error); - gpr_mu_unlock(&glb_policy->mu); - } else { - /* shutting down and no new serverlist available. Bail out. */ - gpr_free(rr_conn_data); - } + if (rr_conn_data->state != GRPC_CHANNEL_SHUTDOWN && + !glb_policy->shutting_down) { + gpr_mu_lock(&glb_policy->mu); + /* RR not shutting down. Mimic the RR's policy state */ + grpc_connectivity_state_set(exec_ctx, &glb_policy->state_tracker, + rr_conn_data->state, GRPC_ERROR_REF(error), + "rr_connectivity_cb"); + /* resubscribe. Reuse the "rr_connectivity_cb" weak ref. */ + grpc_lb_policy_notify_on_state_change(exec_ctx, glb_policy->rr_policy, + &rr_conn_data->state, + &rr_conn_data->on_change); + gpr_mu_unlock(&glb_policy->mu); } else { - if (error == GRPC_ERROR_NONE) { - gpr_mu_lock(&glb_policy->mu); - /* RR not shutting down. Mimic the RR's policy state */ - grpc_connectivity_state_set(exec_ctx, &glb_policy->state_tracker, - rr_conn_data->state, GRPC_ERROR_REF(error), - "glb_rr_connectivity_changed"); - /* resubscribe */ - grpc_lb_policy_notify_on_state_change(exec_ctx, glb_policy->rr_policy, - &rr_conn_data->state, - &rr_conn_data->on_change); - gpr_mu_unlock(&glb_policy->mu); - } else { /* error */ - gpr_free(rr_conn_data); - } + GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base, + "rr_connectivity_cb"); + gpr_free(rr_conn_data); } } @@ -682,18 +723,11 @@ static grpc_lb_policy *glb_create(grpc_exec_ctx *exec_ctx, return NULL; } - rr_connectivity_data *rr_connectivity = - gpr_malloc(sizeof(rr_connectivity_data)); - memset(rr_connectivity, 0, sizeof(rr_connectivity_data)); - grpc_closure_init(&rr_connectivity->on_change, glb_rr_connectivity_changed, - rr_connectivity); - rr_connectivity->glb_policy = glb_policy; - glb_policy->rr_connectivity = rr_connectivity; - grpc_lb_policy_init(&glb_policy->base, &glb_lb_policy_vtable); gpr_mu_init(&glb_policy->mu); grpc_connectivity_state_init(&glb_policy->state_tracker, GRPC_CHANNEL_IDLE, "grpclb"); + return &glb_policy->base; } @@ -710,14 +744,13 @@ static void glb_destroy(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { grpc_grpclb_destroy_serverlist(glb_policy->serverlist); } gpr_mu_destroy(&glb_policy->mu); - grpc_lb_addresses_destroy(glb_policy->addresses); gpr_free(glb_policy); } -static void lb_client_data_destroy(struct lb_client_data *lb_client); static void glb_shutdown(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { glb_lb_policy *glb_policy = (glb_lb_policy *)pol; gpr_mu_lock(&glb_policy->mu); + glb_policy->shutting_down = true; pending_pick *pp = glb_policy->pending_picks; glb_policy->pending_picks = NULL; @@ -741,15 +774,16 @@ static void glb_shutdown(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { } if (glb_policy->rr_policy) { - /* unsubscribe */ - grpc_lb_policy_notify_on_state_change( - exec_ctx, glb_policy->rr_policy, NULL, - &glb_policy->rr_connectivity->on_change); GRPC_LB_POLICY_UNREF(exec_ctx, glb_policy->rr_policy, "glb_shutdown"); } - lb_client_data_destroy(glb_policy->lb_client); - glb_policy->lb_client = NULL; + if (glb_policy->started_picking) { + if (glb_policy->lb_call != NULL) { + grpc_call_cancel(glb_policy->lb_call, NULL); + /* lb_on_server_status_received will pick up the cancellation and clean up + */ + } + } grpc_connectivity_state_set( exec_ctx, &glb_policy->state_tracker, GRPC_CHANNEL_SHUTDOWN, @@ -780,17 +814,12 @@ static void glb_cancel_pick(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, GRPC_ERROR_UNREF(error); } -static grpc_call *lb_client_data_get_call(struct lb_client_data *lb_client); static void glb_cancel_picks(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; gpr_mu_lock(&glb_policy->mu); - if (glb_policy->lb_client != NULL) { - /* cancel the call to the load balancer service, if any */ - grpc_call_cancel(lb_client_data_get_call(glb_policy->lb_client), NULL); - } pending_pick *pp = glb_policy->pending_picks; glb_policy->pending_picks = NULL; while (pp != NULL) { @@ -810,18 +839,20 @@ static void glb_cancel_picks(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, GRPC_ERROR_UNREF(error); } -static void query_for_backends(grpc_exec_ctx *exec_ctx, - glb_lb_policy *glb_policy); -static void start_picking(grpc_exec_ctx *exec_ctx, glb_lb_policy *glb_policy) { +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) { glb_policy->started_picking = true; - query_for_backends(exec_ctx, glb_policy); + gpr_backoff_reset(&glb_policy->lb_call_backoff_state); + query_for_backends_locked(exec_ctx, glb_policy); } static void glb_exit_idle(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { glb_lb_policy *glb_policy = (glb_lb_policy *)pol; gpr_mu_lock(&glb_policy->mu); if (!glb_policy->started_picking) { - start_picking(exec_ctx, glb_policy); + start_picking_locked(exec_ctx, glb_policy); } gpr_mu_unlock(&glb_policy->mu); } @@ -847,8 +878,8 @@ static int glb_pick(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, if (glb_policy->rr_policy != NULL) { if (grpc_lb_glb_trace) { - gpr_log(GPR_INFO, "about to PICK from 0x%" PRIxPTR "", - (intptr_t)glb_policy->rr_policy); + gpr_log(GPR_INFO, "grpclb %p about to PICK from RR %p", + (void *)glb_policy, (void *)glb_policy->rr_policy); } GRPC_LB_POLICY_REF(glb_policy->rr_policy, "glb_pick"); @@ -865,11 +896,17 @@ static int glb_pick(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, pick_done = pick_from_internal_rr_locked(exec_ctx, glb_policy->rr_policy, pick_args, target, wc_arg); } else { + if (grpc_lb_glb_trace) { + gpr_log(GPR_DEBUG, + "No RR policy in grpclb instance %p. Adding to grpclb's pending " + "picks", + (void *)(glb_policy)); + } add_pending_pick(&glb_policy->pending_picks, pick_args, target, on_complete); if (!glb_policy->started_picking) { - start_picking(exec_ctx, glb_policy); + start_picking_locked(exec_ctx, glb_policy); } pick_done = false; } @@ -898,7 +935,7 @@ static void glb_ping_one(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, } else { add_pending_ping(&glb_policy->pending_pings, closure); if (!glb_policy->started_picking) { - start_picking(exec_ctx, glb_policy); + start_picking_locked(exec_ctx, glb_policy); } } gpr_mu_unlock(&glb_policy->mu); @@ -916,250 +953,182 @@ static void glb_notify_on_state_change(grpc_exec_ctx *exec_ctx, gpr_mu_unlock(&glb_policy->mu); } -/* - * lb_client_data - * - * Used internally for the client call to the LB */ -typedef struct lb_client_data { - gpr_mu mu; - - /* called once initial metadata's been sent */ - grpc_closure md_sent; - - /* called once the LoadBalanceRequest has been sent to the LB server. See - * src/proto/grpc/.../load_balancer.proto */ - grpc_closure req_sent; - - /* A response from the LB server has been received (or error). Process it */ - grpc_closure res_rcvd; - - /* After the client has sent a close to the LB server */ - grpc_closure close_sent; - - /* ... and the status from the LB server has been received */ - grpc_closure srv_status_rcvd; - - grpc_call *lb_call; /* streaming call to the LB server, */ - gpr_timespec deadline; /* for the streaming call to the LB server */ - - grpc_metadata_array initial_metadata_recv; /* initial MD from LB server */ - grpc_metadata_array trailing_metadata_recv; /* trailing MD from LB server */ - - /* what's being sent to the LB server. Note that its value may vary if the LB - * server indicates a redirect. */ - grpc_byte_buffer *request_payload; - - /* response from the LB server, if any. Processed in res_recv_cb() */ - grpc_byte_buffer *response_payload; - - /* the call's status and status detailset in srv_status_rcvd_cb() */ - grpc_status_code status; - char *status_details; - size_t status_details_capacity; - - /* pointer back to the enclosing policy */ - glb_lb_policy *glb_policy; -} lb_client_data; - -static void md_sent_cb(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error); -static void req_sent_cb(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error); -static void res_recv_cb(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error); -static void close_sent_cb(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error); -static void srv_status_rcvd_cb(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error); - -static lb_client_data *lb_client_data_create(glb_lb_policy *glb_policy) { +static void lb_on_server_status_received(grpc_exec_ctx *exec_ctx, void *arg, + grpc_error *error); +static void lb_on_response_received(grpc_exec_ctx *exec_ctx, void *arg, + grpc_error *error); +static void lb_call_init(glb_lb_policy *glb_policy) { GPR_ASSERT(glb_policy->server_name != NULL); GPR_ASSERT(glb_policy->server_name[0] != '\0'); - lb_client_data *lb_client = gpr_malloc(sizeof(lb_client_data)); - memset(lb_client, 0, sizeof(lb_client_data)); - - gpr_mu_init(&lb_client->mu); - grpc_closure_init(&lb_client->md_sent, md_sent_cb, lb_client); - - grpc_closure_init(&lb_client->req_sent, req_sent_cb, lb_client); - grpc_closure_init(&lb_client->res_rcvd, res_recv_cb, lb_client); - grpc_closure_init(&lb_client->close_sent, close_sent_cb, lb_client); - grpc_closure_init(&lb_client->srv_status_rcvd, srv_status_rcvd_cb, lb_client); - - lb_client->deadline = glb_policy->deadline; - /* Note the following LB call progresses every time there's activity in \a * glb_policy->base.interested_parties, which is comprised of the polling * entities from \a client_channel. */ - lb_client->lb_call = grpc_channel_create_pollset_set_call( + glb_policy->lb_call = grpc_channel_create_pollset_set_call( glb_policy->lb_channel, NULL, GRPC_PROPAGATE_DEFAULTS, glb_policy->base.interested_parties, "/grpc.lb.v1.LoadBalancer/BalanceLoad", glb_policy->server_name, - lb_client->deadline, NULL); + glb_policy->deadline, NULL); - grpc_metadata_array_init(&lb_client->initial_metadata_recv); - grpc_metadata_array_init(&lb_client->trailing_metadata_recv); + 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_create(glb_policy->server_name); gpr_slice request_payload_slice = grpc_grpclb_request_encode(request); - lb_client->request_payload = + glb_policy->lb_request_payload = grpc_raw_byte_buffer_create(&request_payload_slice, 1); gpr_slice_unref(request_payload_slice); grpc_grpclb_request_destroy(request); - lb_client->status_details = NULL; - lb_client->status_details_capacity = 0; - lb_client->glb_policy = glb_policy; - return lb_client; + glb_policy->lb_call_status_details = NULL; + glb_policy->lb_call_status_details_capacity = 0; + + grpc_closure_init(&glb_policy->lb_on_server_status_received, + lb_on_server_status_received, glb_policy); + grpc_closure_init(&glb_policy->lb_on_response_received, + lb_on_response_received, glb_policy); + + gpr_backoff_init(&glb_policy->lb_call_backoff_state, BACKOFF_MULTIPLIER, + BACKOFF_JITTER, BACKOFF_MIN_SECONDS * 1000, + BACKOFF_MAX_SECONDS * 1000); } -static void lb_client_data_destroy(lb_client_data *lb_client) { - grpc_call_destroy(lb_client->lb_call); - grpc_metadata_array_destroy(&lb_client->initial_metadata_recv); - grpc_metadata_array_destroy(&lb_client->trailing_metadata_recv); +static void lb_call_destroy(glb_lb_policy *glb_policy) { + GPR_ASSERT(glb_policy->lb_call != NULL); + grpc_call_destroy(glb_policy->lb_call); + glb_policy->lb_call = NULL; - grpc_byte_buffer_destroy(lb_client->request_payload); + grpc_metadata_array_destroy(&glb_policy->lb_initial_metadata_recv); + grpc_metadata_array_destroy(&glb_policy->lb_trailing_metadata_recv); - gpr_free(lb_client->status_details); - gpr_mu_destroy(&lb_client->mu); - gpr_free(lb_client); -} -static grpc_call *lb_client_data_get_call(lb_client_data *lb_client) { - return lb_client->lb_call; + grpc_byte_buffer_destroy(glb_policy->lb_request_payload); + gpr_free(glb_policy->lb_call_status_details); } /* * Auxiliary functions and LB client callbacks. */ -static void query_for_backends(grpc_exec_ctx *exec_ctx, - glb_lb_policy *glb_policy) { +static void query_for_backends_locked(grpc_exec_ctx *exec_ctx, + glb_lb_policy *glb_policy) { GPR_ASSERT(glb_policy->lb_channel != NULL); + lb_call_init(glb_policy); + + if (grpc_lb_glb_trace) { + gpr_log(GPR_INFO, "Query for backends (grpclb: %p, lb_call: %p)", + (void *)glb_policy, (void *)glb_policy->lb_call); + } + GPR_ASSERT(glb_policy->lb_call != NULL); - glb_policy->lb_client = lb_client_data_create(glb_policy); grpc_call_error call_error; - grpc_op ops[1]; + grpc_op ops[4]; memset(ops, 0, sizeof(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++; - call_error = grpc_call_start_batch_and_execute( - exec_ctx, glb_policy->lb_client->lb_call, ops, (size_t)(op - ops), - &glb_policy->lb_client->md_sent); - GPR_ASSERT(GRPC_CALL_OK == call_error); - op = ops; - op->op = GRPC_OP_RECV_STATUS_ON_CLIENT; - op->data.recv_status_on_client.trailing_metadata = - &glb_policy->lb_client->trailing_metadata_recv; - op->data.recv_status_on_client.status = &glb_policy->lb_client->status; - op->data.recv_status_on_client.status_details = - &glb_policy->lb_client->status_details; - op->data.recv_status_on_client.status_details_capacity = - &glb_policy->lb_client->status_details_capacity; + op->op = GRPC_OP_RECV_INITIAL_METADATA; + op->data.recv_initial_metadata = &glb_policy->lb_initial_metadata_recv; op->flags = 0; op->reserved = NULL; op++; - call_error = grpc_call_start_batch_and_execute( - exec_ctx, glb_policy->lb_client->lb_call, ops, (size_t)(op - ops), - &glb_policy->lb_client->srv_status_rcvd); - GPR_ASSERT(GRPC_CALL_OK == call_error); -} - -static void md_sent_cb(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { - lb_client_data *lb_client = arg; - GPR_ASSERT(lb_client->lb_call); - grpc_op ops[1]; - memset(ops, 0, sizeof(ops)); - grpc_op *op = ops; + GPR_ASSERT(glb_policy->lb_request_payload != NULL); op->op = GRPC_OP_SEND_MESSAGE; - op->data.send_message = lb_client->request_payload; + op->data.send_message = glb_policy->lb_request_payload; op->flags = 0; op->reserved = NULL; op++; - grpc_call_error call_error = grpc_call_start_batch_and_execute( - exec_ctx, lb_client->lb_call, ops, (size_t)(op - ops), - &lb_client->req_sent); - GPR_ASSERT(GRPC_CALL_OK == call_error); -} - -static void req_sent_cb(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { - lb_client_data *lb_client = arg; - GPR_ASSERT(lb_client->lb_call); - - grpc_op ops[2]; - memset(ops, 0, sizeof(ops)); - grpc_op *op = ops; - op->op = GRPC_OP_RECV_INITIAL_METADATA; - op->data.recv_initial_metadata = &lb_client->initial_metadata_recv; + op->op = GRPC_OP_RECV_STATUS_ON_CLIENT; + op->data.recv_status_on_client.trailing_metadata = + &glb_policy->lb_trailing_metadata_recv; + op->data.recv_status_on_client.status = &glb_policy->lb_call_status; + op->data.recv_status_on_client.status_details = + &glb_policy->lb_call_status_details; + op->data.recv_status_on_client.status_details_capacity = + &glb_policy->lb_call_status_details_capacity; op->flags = 0; op->reserved = NULL; 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 */ + GRPC_LB_POLICY_WEAK_REF(&glb_policy->base, "lb_on_server_status_received"); + call_error = grpc_call_start_batch_and_execute( + exec_ctx, glb_policy->lb_call, ops, (size_t)(op - ops), + &glb_policy->lb_on_server_status_received); + GPR_ASSERT(GRPC_CALL_OK == call_error); + op = ops; op->op = GRPC_OP_RECV_MESSAGE; - op->data.recv_message = &lb_client->response_payload; + op->data.recv_message = &glb_policy->lb_response_payload; op->flags = 0; op->reserved = NULL; op++; - grpc_call_error call_error = grpc_call_start_batch_and_execute( - exec_ctx, lb_client->lb_call, ops, (size_t)(op - ops), - &lb_client->res_rcvd); + /* take another weak ref to be unref'd in lb_on_response_received */ + GRPC_LB_POLICY_WEAK_REF(&glb_policy->base, "lb_on_response_received"); + call_error = grpc_call_start_batch_and_execute( + exec_ctx, glb_policy->lb_call, ops, (size_t)(op - ops), + &glb_policy->lb_on_response_received); GPR_ASSERT(GRPC_CALL_OK == call_error); } -static void res_recv_cb(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { - lb_client_data *lb_client = arg; +static void lb_on_response_received(grpc_exec_ctx *exec_ctx, void *arg, + grpc_error *error) { + glb_lb_policy *glb_policy = arg; + grpc_op ops[2]; memset(ops, 0, sizeof(ops)); grpc_op *op = ops; - if (lb_client->response_payload != NULL) { + if (glb_policy->lb_response_payload != NULL) { + gpr_backoff_reset(&glb_policy->lb_call_backoff_state); /* Received data from the LB server. Look inside - * lb_client->response_payload, for a serverlist. */ + * glb_policy->lb_response_payload, for a serverlist. */ grpc_byte_buffer_reader bbr; - grpc_byte_buffer_reader_init(&bbr, lb_client->response_payload); + grpc_byte_buffer_reader_init(&bbr, glb_policy->lb_response_payload); gpr_slice response_slice = grpc_byte_buffer_reader_readall(&bbr); - grpc_byte_buffer_destroy(lb_client->response_payload); + grpc_byte_buffer_destroy(glb_policy->lb_response_payload); grpc_grpclb_serverlist *serverlist = grpc_grpclb_response_parse_serverlist(response_slice); if (serverlist != NULL) { + GPR_ASSERT(glb_policy->lb_call != NULL); gpr_slice_unref(response_slice); if (grpc_lb_glb_trace) { gpr_log(GPR_INFO, "Serverlist with %lu servers received", (unsigned long)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; + grpc_sockaddr_to_string(&ipport, &addr, false); + gpr_log(GPR_INFO, "Serverlist[%lu]: %s", (unsigned long)i, ipport); + gpr_free(ipport); + } } /* update serverlist */ if (serverlist->num_servers > 0) { - gpr_mu_lock(&lb_client->glb_policy->mu); - if (grpc_grpclb_serverlist_equals(lb_client->glb_policy->serverlist, - serverlist)) { + gpr_mu_lock(&glb_policy->mu); + if (grpc_grpclb_serverlist_equals(glb_policy->serverlist, serverlist)) { if (grpc_lb_glb_trace) { gpr_log(GPR_INFO, "Incoming server list identical to current, ignoring."); } } else { /* new serverlist */ - if (lb_client->glb_policy->serverlist != NULL) { + if (glb_policy->serverlist != NULL) { /* dispose of the old serverlist */ - grpc_grpclb_destroy_serverlist(lb_client->glb_policy->serverlist); + grpc_grpclb_destroy_serverlist(glb_policy->serverlist); } /* and update the copy in the glb_lb_policy instance */ - lb_client->glb_policy->serverlist = serverlist; - } - if (lb_client->glb_policy->rr_policy == NULL) { - /* initial "handover", in this case from a null RR policy, meaning - * it'll just create the first RR policy instance */ - rr_handover_locked(exec_ctx, lb_client->glb_policy, error); - } else { - /* unref the RR policy, eventually leading to its substitution with a - * new one constructed from the received serverlist (see - * glb_rr_connectivity_changed) */ - GRPC_LB_POLICY_UNREF(exec_ctx, lb_client->glb_policy->rr_policy, - "serverlist_received"); + glb_policy->serverlist = serverlist; + + rr_handover_locked(exec_ctx, glb_policy, error); } - gpr_mu_unlock(&lb_client->glb_policy->mu); + gpr_mu_unlock(&glb_policy->mu); } else { if (grpc_lb_glb_trace) { gpr_log(GPR_INFO, @@ -1167,60 +1136,94 @@ static void res_recv_cb(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { "response with > 0 servers is received"); } } + } else { /* serverlist == NULL */ + gpr_log(GPR_ERROR, "Invalid LB response received: '%s'. Ignoring.", + gpr_dump_slice(response_slice, GPR_DUMP_ASCII | GPR_DUMP_HEX)); + gpr_slice_unref(response_slice); + } + if (!glb_policy->shutting_down) { /* keep listening for serverlist updates */ op->op = GRPC_OP_RECV_MESSAGE; - op->data.recv_message = &lb_client->response_payload; + op->data.recv_message = &glb_policy->lb_response_payload; op->flags = 0; op->reserved = NULL; op++; + /* reuse the "lb_on_response_received" weak ref taken in + * query_for_backends_locked() */ const grpc_call_error call_error = grpc_call_start_batch_and_execute( - exec_ctx, lb_client->lb_call, ops, (size_t)(op - ops), - &lb_client->res_rcvd); /* loop */ + exec_ctx, glb_policy->lb_call, ops, (size_t)(op - ops), + &glb_policy->lb_on_response_received); /* loop */ GPR_ASSERT(GRPC_CALL_OK == call_error); - return; } - - GPR_ASSERT(serverlist == NULL); - gpr_log(GPR_ERROR, "Invalid LB response received: '%s'", - gpr_dump_slice(response_slice, GPR_DUMP_ASCII)); - gpr_slice_unref(response_slice); - - /* Disconnect from server returning invalid response. */ - op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; - op->flags = 0; - op->reserved = NULL; - op++; - grpc_call_error call_error = grpc_call_start_batch_and_execute( - exec_ctx, lb_client->lb_call, ops, (size_t)(op - ops), - &lb_client->close_sent); - GPR_ASSERT(GRPC_CALL_OK == call_error); + } else { /* empty payload: call cancelled. */ + /* dispose of the "lb_on_response_received" weak ref taken in + * query_for_backends_locked() and reused in every reception loop */ + GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base, + "lb_on_response_received_empty_payload"); } - /* empty payload: call cancelled by server. Cleanups happening in - * srv_status_rcvd_cb */ } -static void close_sent_cb(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - if (grpc_lb_glb_trace) { - gpr_log(GPR_INFO, - "Close from LB client sent. Waiting from server status now"); +static void lb_call_on_retry_timer(grpc_exec_ctx *exec_ctx, void *arg, + grpc_error *error) { + glb_lb_policy *glb_policy = arg; + gpr_mu_lock(&glb_policy->mu); + + if (!glb_policy->shutting_down) { + if (grpc_lb_glb_trace) { + gpr_log(GPR_INFO, "Restaring call to LB server (grpclb %p)", + (void *)glb_policy); + } + GPR_ASSERT(glb_policy->lb_call == NULL); + query_for_backends_locked(exec_ctx, glb_policy); } + gpr_mu_unlock(&glb_policy->mu); + + GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base, + "grpclb_on_retry_timer"); } -static void srv_status_rcvd_cb(grpc_exec_ctx *exec_ctx, void *arg, - grpc_error *error) { - lb_client_data *lb_client = arg; +static void lb_on_server_status_received(grpc_exec_ctx *exec_ctx, void *arg, + grpc_error *error) { + glb_lb_policy *glb_policy = arg; + gpr_mu_lock(&glb_policy->mu); + + GPR_ASSERT(glb_policy->lb_call != NULL); + if (grpc_lb_glb_trace) { - gpr_log(GPR_INFO, - "status from lb server received. Status = %d, Details = '%s', " - "Capacity " - "= %lu", - lb_client->status, lb_client->status_details, - (unsigned long)lb_client->status_details_capacity); + gpr_log(GPR_DEBUG, + "Status from LB server received. Status = %d, Details = '%s', " + "(call: %p)", + glb_policy->lb_call_status, glb_policy->lb_call_status_details, + (void *)glb_policy->lb_call); + } + + /* We need to performe cleanups no matter what. */ + lb_call_destroy(glb_policy); + + if (!glb_policy->shutting_down) { + /* if we aren't shutting down, restart the LB client call after some time */ + gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC); + gpr_timespec next_try = + gpr_backoff_step(&glb_policy->lb_call_backoff_state, now); + if (grpc_lb_glb_trace) { + gpr_log(GPR_DEBUG, "Connection to LB server lost (grpclb: %p)...", + (void *)glb_policy); + gpr_timespec timeout = gpr_time_sub(next_try, now); + if (gpr_time_cmp(timeout, gpr_time_0(timeout.clock_type)) > 0) { + gpr_log(GPR_DEBUG, "... retrying in %" PRId64 ".%09d seconds.", + timeout.tv_sec, timeout.tv_nsec); + } else { + gpr_log(GPR_DEBUG, "... retrying immediately."); + } + } + GRPC_LB_POLICY_WEAK_REF(&glb_policy->base, "grpclb_retry_timer"); + grpc_timer_init(exec_ctx, &glb_policy->lb_call_retry_timer, next_try, + lb_call_on_retry_timer, glb_policy, now); } - /* TODO(dgq): deal with stream termination properly (fire up another one? - * fail the original call?) */ + gpr_mu_unlock(&glb_policy->mu); + GRPC_LB_POLICY_WEAK_UNREF(exec_ctx, &glb_policy->base, + "lb_on_server_status_received"); } /* Code wiring the policy with the rest of the core */ diff --git a/src/core/ext/lb_policy/grpclb/proto/grpc/lb/v1/load_balancer.pb.h b/src/core/ext/lb_policy/grpclb/proto/grpc/lb/v1/load_balancer.pb.h index 53fed22bae0..e36d0966f85 100644 --- a/src/core/ext/lb_policy/grpclb/proto/grpc/lb/v1/load_balancer.pb.h +++ b/src/core/ext/lb_policy/grpclb/proto/grpc/lb/v1/load_balancer.pb.h @@ -77,7 +77,7 @@ typedef struct _grpc_lb_v1_Server { bool has_port; int32_t port; bool has_load_balance_token; - char load_balance_token[65]; + char load_balance_token[50]; bool has_drop_request; bool drop_request; /* @@protoc_insertion_point(struct:grpc_lb_v1_Server) */ @@ -172,7 +172,7 @@ extern const pb_field_t grpc_lb_v1_Server_fields[5]; #define grpc_lb_v1_LoadBalanceResponse_size (98 + grpc_lb_v1_ServerList_size) #define grpc_lb_v1_InitialLoadBalanceResponse_size 90 /* grpc_lb_v1_ServerList_size depends on runtime parameters */ -#define grpc_lb_v1_Server_size 98 +#define grpc_lb_v1_Server_size 83 /* Message IDs (where set with "msgid" option) */ #ifdef PB_MSGID diff --git a/src/core/ext/lb_policy/pick_first/pick_first.c b/src/core/ext/lb_policy/pick_first/pick_first.c index 5d3433df74a..ac3c6a305ac 100644 --- a/src/core/ext/lb_policy/pick_first/pick_first.c +++ b/src/core/ext/lb_policy/pick_first/pick_first.c @@ -209,7 +209,7 @@ static int pf_pick(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, /* Check atomically for a selected channel */ grpc_connected_subchannel *selected = GET_SELECTED(p); if (selected != NULL) { - *target = selected; + *target = GRPC_CONNECTED_SUBCHANNEL_REF(selected, "picked"); return 1; } @@ -218,7 +218,7 @@ static int pf_pick(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, selected = GET_SELECTED(p); if (selected) { gpr_mu_unlock(&p->mu); - *target = selected; + *target = GRPC_CONNECTED_SUBCHANNEL_REF(selected, "picked"); return 1; } else { if (!p->started_picking) { @@ -310,7 +310,7 @@ static void pf_connectivity_changed(grpc_exec_ctx *exec_ctx, void *arg, /* update any calls that were waiting for a pick */ while ((pp = p->pending_picks)) { p->pending_picks = pp->next; - *pp->target = selected; + *pp->target = GRPC_CONNECTED_SUBCHANNEL_REF(selected, "picked"); grpc_exec_ctx_sched(exec_ctx, pp->on_complete, GRPC_ERROR_NONE, NULL); gpr_free(pp); } diff --git a/src/core/ext/lb_policy/round_robin/round_robin.c b/src/core/ext/lb_policy/round_robin/round_robin.c index c0743b00e80..427999aa6b8 100644 --- a/src/core/ext/lb_policy/round_robin/round_robin.c +++ b/src/core/ext/lb_policy/round_robin/round_robin.c @@ -120,6 +120,8 @@ typedef struct { grpc_connectivity_state connectivity_state; /** the subchannel's target user data */ void *user_data; + /** vtable to operate over \a user_data */ + const grpc_lb_user_data_vtable *user_data_vtable; } subchannel_data; struct round_robin_lb_policy { @@ -186,9 +188,13 @@ static void advance_last_picked_locked(round_robin_lb_policy *p) { } if (grpc_lb_round_robin_trace) { - gpr_log(GPR_DEBUG, "[READYLIST] ADVANCED LAST PICK. NOW AT NODE %p (SC %p)", - (void *)p->ready_list_last_pick, - (void *)p->ready_list_last_pick->subchannel); + gpr_log(GPR_DEBUG, + "[READYLIST, RR: %p] ADVANCED LAST PICK. NOW AT NODE %p (SC %p, " + "CSC %p)", + (void *)p, (void *)p->ready_list_last_pick, + (void *)p->ready_list_last_pick->subchannel, + (void *)grpc_subchannel_get_connected_subchannel( + p->ready_list_last_pick->subchannel)); } } @@ -255,9 +261,18 @@ static void remove_disconnected_sc_locked(round_robin_lb_policy *p, static void rr_destroy(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { round_robin_lb_policy *p = (round_robin_lb_policy *)pol; ready_list *elem; + + if (grpc_lb_round_robin_trace) { + gpr_log(GPR_DEBUG, "Destroying Round Robin policy at %p", (void *)pol); + } + for (size_t i = 0; i < p->num_subchannels; i++) { subchannel_data *sd = p->subchannels[i]; - GRPC_SUBCHANNEL_UNREF(exec_ctx, sd->subchannel, "round_robin"); + GRPC_SUBCHANNEL_UNREF(exec_ctx, sd->subchannel, "round_robin_destroy"); + if (sd->user_data != NULL) { + GPR_ASSERT(sd->user_data_vtable != NULL); + sd->user_data_vtable->destroy(sd->user_data); + } gpr_free(sd); } @@ -285,6 +300,9 @@ static void rr_shutdown(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { size_t i; gpr_mu_lock(&p->mu); + if (grpc_lb_round_robin_trace) { + gpr_log(GPR_DEBUG, "Shutting down Round Robin policy at %p", (void *)pol); + } p->shutdown = 1; while ((pp = p->pending_picks)) { @@ -296,7 +314,7 @@ static void rr_shutdown(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol) { } grpc_connectivity_state_set( exec_ctx, &p->state_tracker, GRPC_CHANNEL_SHUTDOWN, - GRPC_ERROR_CREATE("Channel Shutdown"), "shutdown"); + GRPC_ERROR_CREATE("Channel Shutdown"), "rr_shutdown"); for (i = 0; i < p->num_subchannels; i++) { subchannel_data *sd = p->subchannels[i]; grpc_subchannel_notify_on_state_change(exec_ctx, sd->subchannel, NULL, NULL, @@ -395,9 +413,16 @@ static int rr_pick(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, pending_pick *pp; ready_list *selected; gpr_mu_lock(&p->mu); + + if (grpc_lb_round_robin_trace) { + gpr_log(GPR_INFO, "Round Robin %p trying to pick", (void *)pol); + } + if ((selected = peek_next_connected_locked(p))) { /* readily available, report right away */ - *target = grpc_subchannel_get_connected_subchannel(selected->subchannel); + *target = GRPC_CONNECTED_SUBCHANNEL_REF( + grpc_subchannel_get_connected_subchannel(selected->subchannel), + "picked"); if (user_data != NULL) { *user_data = selected->user_data; @@ -433,7 +458,6 @@ static void rr_connectivity_changed(grpc_exec_ctx *exec_ctx, void *arg, subchannel_data *sd = arg; round_robin_lb_policy *p = sd->policy; pending_pick *pp; - ready_list *selected; int unref = 0; @@ -454,17 +478,20 @@ static void rr_connectivity_changed(grpc_exec_ctx *exec_ctx, void *arg, /* 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. */ - selected = peek_next_connected_locked(p); + ready_list *selected = peek_next_connected_locked(p); + GPR_ASSERT(selected != NULL); if (p->pending_picks != NULL) { /* if the selected subchannel is going to be used for the pending * picks, update the last picked pointer */ advance_last_picked_locked(p); } + while ((pp = p->pending_picks)) { p->pending_picks = pp->next; - *pp->target = - grpc_subchannel_get_connected_subchannel(selected->subchannel); + *pp->target = GRPC_CONNECTED_SUBCHANNEL_REF( + grpc_subchannel_get_connected_subchannel(selected->subchannel), + "picked"); if (pp->user_data != NULL) { *pp->user_data = selected->user_data; } @@ -578,7 +605,9 @@ static void rr_ping_one(grpc_exec_ctx *exec_ctx, grpc_lb_policy *pol, gpr_mu_lock(&p->mu); if ((selected = peek_next_connected_locked(p))) { gpr_mu_unlock(&p->mu); - target = grpc_subchannel_get_connected_subchannel(selected->subchannel); + target = GRPC_CONNECTED_SUBCHANNEL_REF( + grpc_subchannel_get_connected_subchannel(selected->subchannel), + "picked"); grpc_connected_subchannel_ping(exec_ctx, target, closure); } else { gpr_mu_unlock(&p->mu); @@ -648,7 +677,11 @@ static grpc_lb_policy *round_robin_create(grpc_exec_ctx *exec_ctx, sd->policy = p; sd->index = subchannel_idx; sd->subchannel = subchannel; - sd->user_data = addresses->addresses[i].user_data; + sd->user_data_vtable = addresses->user_data_vtable; + if (sd->user_data_vtable != NULL) { + sd->user_data = + sd->user_data_vtable->copy(addresses->addresses[i].user_data); + } ++subchannel_idx; grpc_closure_init(&sd->connectivity_changed_closure, rr_connectivity_changed, sd); diff --git a/src/core/ext/transport/chttp2/client/insecure/channel_create.c b/src/core/ext/transport/chttp2/client/insecure/channel_create.c index 372fb7bf4ca..71a06e118ba 100644 --- a/src/core/ext/transport/chttp2/client/insecure/channel_create.c +++ b/src/core/ext/transport/chttp2/client/insecure/channel_create.c @@ -154,7 +154,8 @@ static void connector_connect(grpc_exec_ctx *exec_ctx, grpc_connector *con, c->tcp = NULL; grpc_closure_init(&c->connected, connected, c); grpc_tcp_client_connect(exec_ctx, &c->connected, &c->tcp, - args->interested_parties, args->addr, args->deadline); + args->interested_parties, args->channel_args, + args->addr, args->deadline); } static const grpc_connector_vtable connector_vtable = { diff --git a/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.c b/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.c index b2c5e5b088c..1e5b1c22e39 100644 --- a/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.c +++ b/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.c @@ -44,6 +44,7 @@ #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/iomgr/endpoint.h" #include "src/core/lib/iomgr/exec_ctx.h" +#include "src/core/lib/iomgr/tcp_client_posix.h" #include "src/core/lib/iomgr/tcp_posix.h" #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/channel.h" @@ -65,9 +66,8 @@ grpc_channel *grpc_insecure_channel_create_from_fd( int flags = fcntl(fd, F_GETFL, 0); GPR_ASSERT(fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0); - grpc_endpoint *client = - grpc_tcp_create(grpc_fd_create(fd, "client"), - GRPC_TCP_DEFAULT_READ_SLICE_SIZE, "fd-client"); + 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); diff --git a/src/core/ext/transport/chttp2/client/secure/secure_channel_create.c b/src/core/ext/transport/chttp2/client/secure/secure_channel_create.c index 29095af2076..d0ac72a0114 100644 --- a/src/core/ext/transport/chttp2/client/secure/secure_channel_create.c +++ b/src/core/ext/transport/chttp2/client/secure/secure_channel_create.c @@ -212,9 +212,9 @@ static void connector_connect(grpc_exec_ctx *exec_ctx, grpc_connector *con, GPR_ASSERT(c->connecting_endpoint == NULL); gpr_mu_unlock(&c->mu); grpc_closure_init(&c->connected_closure, connected, c); - grpc_tcp_client_connect(exec_ctx, &c->connected_closure, - &c->newly_connecting_endpoint, - args->interested_parties, args->addr, args->deadline); + grpc_tcp_client_connect( + exec_ctx, &c->connected_closure, &c->newly_connecting_endpoint, + args->interested_parties, args->channel_args, args->addr, args->deadline); } static const grpc_connector_vtable connector_vtable = { @@ -347,7 +347,7 @@ grpc_channel *grpc_secure_channel_create(grpc_channel_credentials *creds, &exec_ctx, &f->base, target, GRPC_CLIENT_CHANNEL_TYPE_REGULAR, new_args); // Clean up. GRPC_SECURITY_CONNECTOR_UNREF(&f->security_connector->base, - "client_channel_factory_create_channel"); + "secure_client_channel_factory_create_channel"); grpc_channel_args_destroy(new_args); grpc_client_channel_factory_unref(&exec_ctx, &f->base); grpc_exec_ctx_finish(&exec_ctx); diff --git a/src/core/ext/transport/chttp2/server/insecure/server_chttp2.c b/src/core/ext/transport/chttp2/server/insecure/server_chttp2.c index e4967c2f08b..d42611b8637 100644 --- a/src/core/ext/transport/chttp2/server/insecure/server_chttp2.c +++ b/src/core/ext/transport/chttp2/server/insecure/server_chttp2.c @@ -139,8 +139,8 @@ int grpc_server_add_insecure_http2_port(grpc_server *server, const char *addr) { goto error; } - err = - grpc_tcp_server_create(NULL, grpc_server_get_channel_args(server), &tcp); + err = grpc_tcp_server_create(&exec_ctx, NULL, + grpc_server_get_channel_args(server), &tcp); if (err != GRPC_ERROR_NONE) { goto error; } diff --git a/src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.c b/src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.c index 9af17fb5ae7..aa2ecf5743d 100644 --- a/src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.c +++ b/src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.c @@ -57,8 +57,12 @@ void grpc_server_add_insecure_channel_from_fd(grpc_server *server, char *name; gpr_asprintf(&name, "fd:%d", fd); - grpc_endpoint *server_endpoint = grpc_tcp_create( - grpc_fd_create(fd, name), GRPC_TCP_DEFAULT_READ_SLICE_SIZE, name); + grpc_resource_quota *resource_quota = grpc_resource_quota_from_channel_args( + grpc_server_get_channel_args(server)); + grpc_endpoint *server_endpoint = + grpc_tcp_create(grpc_fd_create(fd, name), resource_quota, + GRPC_TCP_DEFAULT_READ_SLICE_SIZE, name); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); gpr_free(name); diff --git a/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.c b/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.c index 0fab8885418..7ad687042d3 100644 --- a/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.c +++ b/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.c @@ -271,7 +271,8 @@ int grpc_server_add_secure_http2_port(grpc_server *server, const char *addr, memset(server_state, 0, sizeof(*server_state)); grpc_closure_init(&server_state->tcp_server_shutdown_complete, tcp_server_shutdown_complete, server_state); - err = grpc_tcp_server_create(&server_state->tcp_server_shutdown_complete, + err = grpc_tcp_server_create(&exec_ctx, + &server_state->tcp_server_shutdown_complete, grpc_server_get_channel_args(server), &tcp); if (err != GRPC_ERROR_NONE) { goto error; diff --git a/src/core/ext/transport/chttp2/transport/chttp2_transport.c b/src/core/ext/transport/chttp2/transport/chttp2_transport.c index ecf3aea8701..4a9f806354c 100644 --- a/src/core/ext/transport/chttp2/transport/chttp2_transport.c +++ b/src/core/ext/transport/chttp2/transport/chttp2_transport.c @@ -114,6 +114,20 @@ static void fail_pending_writes(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, grpc_chttp2_stream *s, grpc_error *error); +static void benign_reclaimer(grpc_exec_ctx *exec_ctx, void *t, + grpc_error *error); +static void benign_reclaimer_locked(grpc_exec_ctx *exec_ctx, void *t, + grpc_error *error); +static void destructive_reclaimer(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, @@ -241,6 +255,11 @@ static void init_transport(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, grpc_closure_init(&t->write_action_end_locked, write_action_end_locked, t); grpc_closure_init(&t->read_action_begin, read_action_begin, t); grpc_closure_init(&t->read_action_locked, read_action_locked, t); + grpc_closure_init(&t->benign_reclaimer, benign_reclaimer, t); + grpc_closure_init(&t->destructive_reclaimer, destructive_reclaimer, t); + grpc_closure_init(&t->benign_reclaimer_locked, benign_reclaimer_locked, t); + grpc_closure_init(&t->destructive_reclaimer_locked, + destructive_reclaimer_locked, t); grpc_chttp2_goaway_parser_init(&t->goaway_parser); grpc_chttp2_hpack_parser_init(&t->hpack_parser); @@ -362,6 +381,7 @@ static void init_transport(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, } grpc_chttp2_initiate_write(exec_ctx, t, false, "init"); + post_benign_reclaimer(exec_ctx, t); } static void destroy_transport_locked(grpc_exec_ctx *exec_ctx, void *tp, @@ -467,6 +487,7 @@ static int init_stream(grpc_exec_ctx *exec_ctx, grpc_transport *gt, [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE]; *t->accepting_stream = s; grpc_chttp2_stream_map_add(&t->stream_map, s->id, s); + post_destructive_reclaimer(exec_ctx, t); } GPR_TIMER_END("init_stream", 0); @@ -675,6 +696,13 @@ static void write_action_end_locked(grpc_exec_ctx *exec_ctx, void *tp, close_transport_locked(exec_ctx, t, GRPC_ERROR_REF(error)); } + if (t->sent_goaway_state == GRPC_CHTTP2_GOAWAY_SEND_SCHEDULED) { + t->sent_goaway_state = GRPC_CHTTP2_GOAWAY_SENT; + if (grpc_chttp2_stream_map_size(&t->stream_map) == 0) { + close_transport_locked(exec_ctx, t, GRPC_ERROR_CREATE("goaway sent")); + } + } + grpc_chttp2_end_write(exec_ctx, t, GRPC_ERROR_REF(error)); switch (t->write_state) { @@ -780,6 +808,7 @@ static void maybe_start_some_streams(grpc_exec_ctx *exec_ctx, [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE]; s->max_recv_bytes = GPR_MAX(stream_incoming_window, s->max_recv_bytes); grpc_chttp2_stream_map_add(&t->stream_map, s->id, s); + post_destructive_reclaimer(exec_ctx, t); grpc_chttp2_become_writable(exec_ctx, t, s, true, "new_stream"); } /* cancel out streams that will never be started */ @@ -993,9 +1022,14 @@ static void perform_stream_op_locked(grpc_exec_ctx *exec_ctx, void *stream_op, } if (!s->write_closed) { if (t->is_client) { - GPR_ASSERT(s->id == 0); - grpc_chttp2_list_add_waiting_for_concurrency(t, s); - maybe_start_some_streams(exec_ctx, t); + if (!t->closed) { + GPR_ASSERT(s->id == 0); + grpc_chttp2_list_add_waiting_for_concurrency(t, s); + maybe_start_some_streams(exec_ctx, t); + } else { + grpc_chttp2_cancel_stream(exec_ctx, t, s, + GRPC_ERROR_CREATE("Transport closed")); + } } else { GPR_ASSERT(s->id != 0); grpc_chttp2_become_writable(exec_ctx, t, s, true, @@ -1185,6 +1219,14 @@ void grpc_chttp2_ack_ping(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, gpr_free(msg); } +static void send_goaway(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, + grpc_chttp2_error_code error, gpr_slice data) { + t->sent_goaway_state = GRPC_CHTTP2_GOAWAY_SEND_SCHEDULED; + grpc_chttp2_goaway_append(t->last_new_stream_id, (uint32_t)error, data, + &t->qbuf); + grpc_chttp2_initiate_write(exec_ctx, t, false, "goaway_sent"); +} + static void perform_transport_op_locked(grpc_exec_ctx *exec_ctx, void *stream_op, grpc_error *error_ignored) { @@ -1199,15 +1241,9 @@ static void perform_transport_op_locked(grpc_exec_ctx *exec_ctx, } if (op->send_goaway) { - t->sent_goaway = 1; - grpc_chttp2_goaway_append( - t->last_new_stream_id, - (uint32_t)grpc_chttp2_grpc_status_to_http2_error(op->goaway_status), - gpr_slice_ref(*op->goaway_message), &t->qbuf); - close_transport = grpc_chttp2_stream_map_size(&t->stream_map) == 0 - ? GRPC_ERROR_CREATE("GOAWAY sent") - : GRPC_ERROR_NONE; - grpc_chttp2_initiate_write(exec_ctx, t, false, "goaway_sent"); + send_goaway(exec_ctx, t, + grpc_chttp2_grpc_status_to_http2_error(op->goaway_status), + gpr_slice_ref(*op->goaway_message)); } if (op->set_accept_stream) { @@ -1341,10 +1377,14 @@ static void remove_stream(grpc_exec_ctx *exec_ctx, grpc_chttp2_transport *t, s->data_parser.parsing_frame = NULL; } - if (grpc_chttp2_stream_map_size(&t->stream_map) == 0 && t->sent_goaway) { - close_transport_locked( - exec_ctx, t, GRPC_ERROR_CREATE_REFERENCING( - "Last stream closed after sending GOAWAY", &error, 1)); + if (grpc_chttp2_stream_map_size(&t->stream_map) == 0) { + post_benign_reclaimer(exec_ctx, t); + if (t->sent_goaway_state == GRPC_CHTTP2_GOAWAY_SENT) { + close_transport_locked( + exec_ctx, t, + GRPC_ERROR_CREATE_REFERENCING( + "Last stream closed after sending GOAWAY", &error, 1)); + } } if (grpc_chttp2_list_remove_writable_stream(t, s)) { GRPC_CHTTP2_STREAM_UNREF(exec_ctx, s, "chttp2_writing:remove_stream"); @@ -2071,6 +2111,103 @@ grpc_chttp2_incoming_byte_stream *grpc_chttp2_incoming_byte_stream_create( return incoming_byte_stream; } +/******************************************************************************* + * RESOURCE QUOTAS + */ + +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"); + grpc_resource_user_post_reclaimer(exec_ctx, + grpc_endpoint_get_resource_user(t->ep), + false, &t->benign_reclaimer); + } +} + +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"); + grpc_resource_user_post_reclaimer(exec_ctx, + grpc_endpoint_get_resource_user(t->ep), + true, &t->destructive_reclaimer); + } +} + +static void benign_reclaimer(grpc_exec_ctx *exec_ctx, void *arg, + grpc_error *error) { + grpc_chttp2_transport *t = arg; + grpc_combiner_execute(exec_ctx, t->combiner, &t->benign_reclaimer_locked, + GRPC_ERROR_REF(error), false); +} + +static void destructive_reclaimer(grpc_exec_ctx *exec_ctx, void *arg, + grpc_error *error) { + grpc_chttp2_transport *t = arg; + grpc_combiner_execute(exec_ctx, t->combiner, &t->destructive_reclaimer_locked, + GRPC_ERROR_REF(error), false); +} + +static void benign_reclaimer_locked(grpc_exec_ctx *exec_ctx, void *arg, + grpc_error *error) { + grpc_chttp2_transport *t = 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_resource_quota_trace) { + gpr_log(GPR_DEBUG, "HTTP2: %s - send goaway to free memory", + t->peer_string); + } + send_goaway(exec_ctx, t, GRPC_CHTTP2_ENHANCE_YOUR_CALM, + gpr_slice_from_static_string("Buffers full")); + } else if (error == GRPC_ERROR_NONE && grpc_resource_quota_trace) { + gpr_log(GPR_DEBUG, + "HTTP2: %s - skip benign reclamation, there are still %" PRIdPTR + " streams", + t->peer_string, grpc_chttp2_stream_map_size(&t->stream_map)); + } + t->benign_reclaimer_registered = false; + if (error != GRPC_ERROR_CANCELLED) { + grpc_resource_user_finish_reclamation( + exec_ctx, grpc_endpoint_get_resource_user(t->ep)); + } + 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 = 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_map_rand(&t->stream_map); + if (grpc_resource_quota_trace) { + gpr_log(GPR_DEBUG, "HTTP2: %s - abandon stream id %d", t->peer_string, + s->id); + } + grpc_chttp2_cancel_stream( + exec_ctx, t, s, grpc_error_set_int(GRPC_ERROR_CREATE("Buffers full"), + GRPC_ERROR_INT_HTTP2_ERROR, + GRPC_CHTTP2_ENHANCE_YOUR_CALM)); + if (n > 1) { + /* Since we cancel one stream per destructive reclamation, if + there are more streams left, we can immediately post a new + reclaimer in case the resource quota needs to free more + memory */ + post_destructive_reclaimer(exec_ctx, t); + } + } + if (error != GRPC_ERROR_CANCELLED) { + grpc_resource_user_finish_reclamation( + exec_ctx, grpc_endpoint_get_resource_user(t->ep)); + } + GRPC_CHTTP2_UNREF_TRANSPORT(exec_ctx, t, "destructive_reclaimer"); +} + /******************************************************************************* * TRACING */ diff --git a/src/core/ext/transport/chttp2/transport/hpack_parser.c b/src/core/ext/transport/chttp2/transport/hpack_parser.c index 8180f78fc00..9702cb2c814 100644 --- a/src/core/ext/transport/chttp2/transport/hpack_parser.c +++ b/src/core/ext/transport/chttp2/transport/hpack_parser.c @@ -50,6 +50,7 @@ #include #include "src/core/ext/transport/chttp2/transport/bin_encoder.h" +#include "src/core/ext/transport/chttp2/transport/http2_errors.h" #include "src/core/lib/profiling/timers.h" #include "src/core/lib/support/string.h" @@ -1578,6 +1579,20 @@ 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 = sp; + grpc_chttp2_transport *t = s->t; + if (!s->write_closed) { + gpr_slice_buffer_add( + &t->qbuf, grpc_chttp2_rst_stream_create(s->id, GRPC_CHTTP2_NO_ERROR, + &s->stats.outgoing)); + grpc_chttp2_initiate_write(exec_ctx, t, false, "force_rst_stream"); + grpc_chttp2_mark_stream_closed(exec_ctx, t, s, true, true, GRPC_ERROR_NONE); + } + GRPC_CHTTP2_STREAM_UNREF(exec_ctx, s, "final_rst"); +} + grpc_error *grpc_chttp2_header_parser_parse(grpc_exec_ctx *exec_ctx, void *hpack_parser, grpc_chttp2_transport *t, @@ -1613,6 +1628,17 @@ grpc_error *grpc_chttp2_header_parser_parse(grpc_exec_ctx *exec_ctx, s->header_frames_received++; } if (parser->is_eof) { + if (t->is_client && !s->write_closed) { + /* server eof ==> complete closure; we may need to forcefully close + the stream. Wait until the combiner lock is ready to be released + however -- it might be that we receive a RST_STREAM following this + and can avoid the extra write */ + GRPC_CHTTP2_STREAM_REF(s, "final_rst"); + grpc_combiner_execute_finally( + exec_ctx, t->combiner, + grpc_closure_create(force_client_rst_stream, s), GRPC_ERROR_NONE, + false); + } grpc_chttp2_mark_stream_closed(exec_ctx, t, s, true, false, GRPC_ERROR_NONE); } diff --git a/src/core/ext/transport/chttp2/transport/internal.h b/src/core/ext/transport/chttp2/transport/internal.h index 01f521c3604..e0c4a1e925d 100644 --- a/src/core/ext/transport/chttp2/transport/internal.h +++ b/src/core/ext/transport/chttp2/transport/internal.h @@ -138,6 +138,12 @@ typedef enum { GRPC_NUM_SETTING_SETS } grpc_chttp2_setting_set; +typedef enum { + GRPC_CHTTP2_NO_GOAWAY_SEND, + GRPC_CHTTP2_GOAWAY_SEND_SCHEDULED, + GRPC_CHTTP2_GOAWAY_SENT, +} grpc_chttp2_sent_goaway_state; + /* Outstanding ping request data */ typedef struct grpc_chttp2_outstanding_ping { uint8_t id[8]; @@ -249,7 +255,7 @@ struct grpc_chttp2_transport { /** have we seen a goaway */ uint8_t seen_goaway; /** have we sent a goaway */ - uint8_t sent_goaway; + grpc_chttp2_sent_goaway_state sent_goaway_state; /** are the local settings dirty and need to be sent? */ uint8_t dirtied_local_settings; @@ -320,6 +326,18 @@ struct grpc_chttp2_transport { /* if non-NULL, close the transport with this error when writes are finished */ grpc_error *close_transport_on_writes_finished; + + /* buffer pool state */ + /** have we scheduled a benign cleanup? */ + bool benign_reclaimer_registered; + /** have we scheduled a destructive cleanup? */ + bool destructive_reclaimer_registered; + /** benign cleanup closure */ + grpc_closure benign_reclaimer; + grpc_closure benign_reclaimer_locked; + /** destructive cleanup closure */ + grpc_closure destructive_reclaimer; + grpc_closure destructive_reclaimer_locked; }; typedef enum { diff --git a/src/core/ext/transport/chttp2/transport/stream_map.c b/src/core/ext/transport/chttp2/transport/stream_map.c index 59b3a14e0a0..5f5a28446d2 100644 --- a/src/core/ext/transport/chttp2/transport/stream_map.c +++ b/src/core/ext/transport/chttp2/transport/stream_map.c @@ -151,6 +151,17 @@ 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) { + if (map->count == map->free) { + return NULL; + } + if (map->free != 0) { + map->count = compact(map->keys, map->values, map->count); + map->free = 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), diff --git a/src/core/ext/transport/chttp2/transport/stream_map.h b/src/core/ext/transport/chttp2/transport/stream_map.h index e76312dd1a0..203f6406802 100644 --- a/src/core/ext/transport/chttp2/transport/stream_map.h +++ b/src/core/ext/transport/chttp2/transport/stream_map.h @@ -68,6 +68,9 @@ 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); +/* Return a random entry */ +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); diff --git a/src/core/lib/http/httpcli.c b/src/core/lib/http/httpcli.c index 55de1b59905..411e669b531 100644 --- a/src/core/lib/http/httpcli.c +++ b/src/core/lib/http/httpcli.c @@ -70,6 +70,7 @@ typedef struct { grpc_closure done_write; grpc_closure connected; grpc_error *overall_error; + grpc_resource_quota *resource_quota; } internal_request; static grpc_httpcli_get_override g_get_override = NULL; @@ -117,6 +118,7 @@ static void finish(grpc_exec_ctx *exec_ctx, internal_request *req, gpr_slice_buffer_destroy(&req->incoming); gpr_slice_buffer_destroy(&req->outgoing); GRPC_ERROR_UNREF(req->overall_error); + grpc_resource_quota_internal_unref(exec_ctx, req->resource_quota); gpr_free(req); } @@ -223,8 +225,15 @@ static void next_address(grpc_exec_ctx *exec_ctx, internal_request *req, } addr = &req->addresses->addrs[req->next_address++]; grpc_closure_init(&req->connected, on_connected, req); + grpc_arg arg; + arg.key = GRPC_ARG_RESOURCE_QUOTA; + arg.type = GRPC_ARG_POINTER; + arg.value.pointer.p = req->resource_quota; + arg.value.pointer.vtable = grpc_resource_quota_arg_vtable(); + grpc_channel_args args = {1, &arg}; grpc_tcp_client_connect(exec_ctx, &req->connected, &req->ep, - req->context->pollset_set, addr, req->deadline); + req->context->pollset_set, &args, addr, + req->deadline); } static void on_resolved(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { @@ -240,6 +249,7 @@ static void on_resolved(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { 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, gpr_timespec deadline, grpc_closure *on_done, grpc_httpcli_response *response, @@ -255,6 +265,7 @@ static void internal_request_begin(grpc_exec_ctx *exec_ctx, req->context = context; req->pollent = pollent; req->overall_error = GRPC_ERROR_NONE; + req->resource_quota = grpc_resource_quota_internal_ref(resource_quota); grpc_closure_init(&req->on_read, on_read, req); grpc_closure_init(&req->done_write, done_write, req); gpr_slice_buffer_init(&req->incoming); @@ -272,6 +283,7 @@ static void internal_request_begin(grpc_exec_ctx *exec_ctx, 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, gpr_timespec deadline, grpc_closure *on_done, grpc_httpcli_response *response) { @@ -281,14 +293,15 @@ void grpc_httpcli_get(grpc_exec_ctx *exec_ctx, grpc_httpcli_context *context, return; } gpr_asprintf(&name, "HTTP:GET:%s:%s", request->host, request->http.path); - internal_request_begin(exec_ctx, context, pollent, request, deadline, on_done, - response, name, + internal_request_begin(exec_ctx, context, pollent, resource_quota, request, + deadline, on_done, response, name, grpc_httpcli_format_get_request(request)); 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, gpr_timespec deadline, grpc_closure *on_done, @@ -301,7 +314,8 @@ void grpc_httpcli_post(grpc_exec_ctx *exec_ctx, grpc_httpcli_context *context, } gpr_asprintf(&name, "HTTP:POST:%s:%s", request->host, request->http.path); internal_request_begin( - exec_ctx, context, pollent, request, deadline, on_done, response, name, + exec_ctx, context, pollent, resource_quota, request, deadline, on_done, + response, name, grpc_httpcli_format_post_request(request, body_bytes, body_size)); gpr_free(name); } diff --git a/src/core/lib/http/httpcli.h b/src/core/lib/http/httpcli.h index 320c0f86c61..11e03b44dfd 100644 --- a/src/core/lib/http/httpcli.h +++ b/src/core/lib/http/httpcli.h @@ -96,6 +96,7 @@ void grpc_httpcli_context_destroy(grpc_httpcli_context *context); '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, gpr_timespec deadline, grpc_closure *on_complete, grpc_httpcli_response *response); @@ -116,6 +117,7 @@ void grpc_httpcli_get(grpc_exec_ctx *exec_ctx, grpc_httpcli_context *context, 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, gpr_timespec deadline, grpc_closure *on_complete, diff --git a/src/core/lib/iomgr/endpoint.c b/src/core/lib/iomgr/endpoint.c index f901fcf9622..74fa9c45dff 100644 --- a/src/core/lib/iomgr/endpoint.c +++ b/src/core/lib/iomgr/endpoint.c @@ -69,3 +69,7 @@ char* grpc_endpoint_get_peer(grpc_endpoint* ep) { grpc_workqueue* grpc_endpoint_get_workqueue(grpc_endpoint* ep) { return ep->vtable->get_workqueue(ep); } + +grpc_resource_user* grpc_endpoint_get_resource_user(grpc_endpoint* ep) { + return ep->vtable->get_resource_user(ep); +} diff --git a/src/core/lib/iomgr/endpoint.h b/src/core/lib/iomgr/endpoint.h index 910a6f6532a..0ac5486ff57 100644 --- a/src/core/lib/iomgr/endpoint.h +++ b/src/core/lib/iomgr/endpoint.h @@ -39,6 +39,7 @@ #include #include "src/core/lib/iomgr/pollset.h" #include "src/core/lib/iomgr/pollset_set.h" +#include "src/core/lib/iomgr/resource_quota.h" /* An endpoint caps a streaming channel between two communicating processes. Examples may be: a tcp socket, , or some shared memory. */ @@ -58,6 +59,7 @@ struct grpc_endpoint_vtable { grpc_pollset_set *pollset); void (*shutdown)(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep); 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); }; @@ -100,6 +102,8 @@ void grpc_endpoint_add_to_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); + struct grpc_endpoint { const grpc_endpoint_vtable *vtable; }; diff --git a/src/core/lib/iomgr/endpoint_pair.h b/src/core/lib/iomgr/endpoint_pair.h index 5cd78051bdf..f9de0c715ec 100644 --- a/src/core/lib/iomgr/endpoint_pair.h +++ b/src/core/lib/iomgr/endpoint_pair.h @@ -41,7 +41,8 @@ typedef struct { grpc_endpoint *server; } grpc_endpoint_pair; -grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(const char *name, - size_t read_slice_size); +grpc_endpoint_pair grpc_iomgr_create_endpoint_pair( + const char *name, grpc_resource_quota *resource_quota, + size_t read_slice_size); #endif /* GRPC_CORE_LIB_IOMGR_ENDPOINT_PAIR_H */ diff --git a/src/core/lib/iomgr/endpoint_pair_posix.c b/src/core/lib/iomgr/endpoint_pair_posix.c index ec2cd782b14..b9ff969e810 100644 --- a/src/core/lib/iomgr/endpoint_pair_posix.c +++ b/src/core/lib/iomgr/endpoint_pair_posix.c @@ -62,20 +62,21 @@ 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, - size_t read_slice_size) { +grpc_endpoint_pair grpc_iomgr_create_endpoint_pair( + const char *name, grpc_resource_quota *resource_quota, + size_t read_slice_size) { int sv[2]; grpc_endpoint_pair p; char *final_name; create_sockets(sv); gpr_asprintf(&final_name, "%s:client", name); - p.client = grpc_tcp_create(grpc_fd_create(sv[1], final_name), read_slice_size, - "socketpair-server"); + p.client = grpc_tcp_create(grpc_fd_create(sv[1], final_name), resource_quota, + read_slice_size, "socketpair-server"); gpr_free(final_name); gpr_asprintf(&final_name, "%s:server", name); - p.server = grpc_tcp_create(grpc_fd_create(sv[0], final_name), read_slice_size, - "socketpair-client"); + p.server = grpc_tcp_create(grpc_fd_create(sv[0], final_name), resource_quota, + read_slice_size, "socketpair-client"); gpr_free(final_name); return p; } diff --git a/src/core/lib/iomgr/endpoint_pair_uv.c b/src/core/lib/iomgr/endpoint_pair_uv.c index 7941e203886..ff24894c6db 100644 --- a/src/core/lib/iomgr/endpoint_pair_uv.c +++ b/src/core/lib/iomgr/endpoint_pair_uv.c @@ -41,8 +41,9 @@ #include "src/core/lib/iomgr/endpoint_pair.h" -grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(const char *name, - size_t read_slice_size) { +grpc_endpoint_pair grpc_iomgr_create_endpoint_pair( + const char *name, grpc_resource_quota *resource_quota, + size_t read_slice_size) { 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.c b/src/core/lib/iomgr/endpoint_pair_windows.c index 5c78c95492b..93f71b745c6 100644 --- a/src/core/lib/iomgr/endpoint_pair_windows.c +++ b/src/core/lib/iomgr/endpoint_pair_windows.c @@ -82,15 +82,16 @@ static void create_sockets(SOCKET sv[2]) { sv[0] = svr_sock; } -grpc_endpoint_pair grpc_iomgr_create_endpoint_pair(const char *name, - size_t read_slice_size) { +grpc_endpoint_pair grpc_iomgr_create_endpoint_pair( + const char *name, grpc_resource_quota *resource_quota, + size_t read_slice_size) { SOCKET sv[2]; grpc_endpoint_pair p; create_sockets(sv); p.client = grpc_tcp_create(grpc_winsocket_create(sv[1], "endpoint:client"), - "endpoint:server"); + resource_quota, "endpoint:server"); p.server = grpc_tcp_create(grpc_winsocket_create(sv[0], "endpoint:server"), - "endpoint:client"); + resource_quota, "endpoint:client"); return p; } diff --git a/src/core/lib/iomgr/ev_epoll_linux.c b/src/core/lib/iomgr/ev_epoll_linux.c index 8381f4a63a4..db51ec49392 100644 --- a/src/core/lib/iomgr/ev_epoll_linux.c +++ b/src/core/lib/iomgr/ev_epoll_linux.c @@ -1711,6 +1711,12 @@ retry: "pollset_add_fd: Raced creating new polling island. pi_new: %p " "(fd: %d, pollset: %p)", (void *)pi_new, fd->fd, (void *)pollset); + + /* 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); + + /* Ref and unref so that the polling island gets deleted during unref */ PI_ADD_REF(pi_new, "dance_of_destruction"); PI_UNREF(exec_ctx, pi_new, "dance_of_destruction"); goto retry; diff --git a/src/core/lib/iomgr/port.h b/src/core/lib/iomgr/port.h index c0bb3b5a23e..f1897bb91f2 100644 --- a/src/core/lib/iomgr/port.h +++ b/src/core/lib/iomgr/port.h @@ -90,7 +90,6 @@ #define GRPC_POSIX_SOCKETUTILS #endif #elif defined(GPR_APPLE) -#define GRPC_HAVE_IP_PKTINFO 1 #define GRPC_HAVE_SO_NOSIGPIPE 1 #define GRPC_HAVE_UNIX_SOCKET 1 #define GRPC_MSG_IOVLEN_TYPE int @@ -102,7 +101,6 @@ #define GRPC_TIMER_USE_GENERIC 1 #elif defined(GPR_FREEBSD) #define GRPC_HAVE_IPV6_RECVPKTINFO 1 -#define GRPC_HAVE_IP_PKTINFO 1 #define GRPC_HAVE_SO_NOSIGPIPE 1 #define GRPC_HAVE_UNIX_SOCKET 1 #define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1 diff --git a/src/core/lib/iomgr/resource_quota.c b/src/core/lib/iomgr/resource_quota.c new file mode 100644 index 00000000000..8a06443d58f --- /dev/null +++ b/src/core/lib/iomgr/resource_quota.c @@ -0,0 +1,724 @@ +/* + * + * Copyright 2016, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "src/core/lib/iomgr/resource_quota.h" + +#include + +#include +#include +#include +#include + +#include "src/core/lib/iomgr/combiner.h" + +int grpc_resource_quota_trace = 0; + +struct grpc_resource_quota { + /* refcount */ + gpr_refcount refs; + + /* Master combiner lock: all activity on a quota executes under this combiner + * (so no mutex is needed for this data structure) + */ + grpc_combiner *combiner; + /* Size of the resource quota */ + int64_t size; + /* Amount of free memory in the resource quota */ + int64_t free_pool; + + /* Has rq_step been scheduled to occur? */ + bool step_scheduled; + /* Are we currently reclaiming memory */ + bool reclaiming; + /* Closure around rq_step */ + grpc_closure rq_step_closure; + /* Closure around rq_reclamation_done */ + grpc_closure rq_reclamation_done_closure; + + /* Roots of all resource user lists */ + grpc_resource_user *roots[GRPC_RULIST_COUNT]; + + char *name; +}; + +/******************************************************************************* + * list management + */ + +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) { + *root = resource_user; + resource_user->links[list].next = resource_user->links[list].prev = + resource_user; + } else { + resource_user->links[list].next = *root; + resource_user->links[list].prev = (*root)->links[list].prev; + resource_user->links[list].next->links[list].prev = + resource_user->links[list].prev->links[list].next = resource_user; + *root = 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) { + *root = resource_user; + resource_user->links[list].next = resource_user->links[list].prev = + resource_user; + } else { + resource_user->links[list].next = (*root)->links[list].next; + resource_user->links[list].prev = *root; + resource_user->links[list].next->links[list].prev = + resource_user->links[list].prev->links[list].next = resource_user; + } +} + +static bool rulist_empty(grpc_resource_quota *resource_quota, + grpc_rulist list) { + return resource_quota->roots[list] == NULL; +} + +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; + } + if (resource_user->links[list].next == resource_user) { + *root = NULL; + } else { + 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; + *root = resource_user->links[list].next; + } + resource_user->links[list].next = resource_user->links[list].prev = NULL; + 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; + 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_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 quota state machine + */ + +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); + +static void rq_step(grpc_exec_ctx *exec_ctx, void *rq, grpc_error *error) { + grpc_resource_quota *resource_quota = rq; + resource_quota->step_scheduled = false; + do { + if (rq_alloc(exec_ctx, resource_quota)) goto done; + } while (rq_reclaim_from_per_user_free_pool(exec_ctx, resource_quota)); + + if (!rq_reclaim(exec_ctx, resource_quota, false)) { + rq_reclaim(exec_ctx, resource_quota, true); + } + +done: + grpc_resource_quota_internal_unref(exec_ctx, 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_internal_ref(resource_quota); + grpc_combiner_execute_finally(exec_ctx, resource_quota->combiner, + &resource_quota->rq_step_closure, + GRPC_ERROR_NONE, false); +} + +/* 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; + while ((resource_user = rulist_pop_head(resource_quota, + GRPC_RULIST_AWAITING_ALLOCATION))) { + gpr_mu_lock(&resource_user->mu); + if (resource_user->free_pool < 0 && + -resource_user->free_pool <= resource_quota->free_pool) { + int64_t amt = -resource_user->free_pool; + resource_user->free_pool = 0; + resource_quota->free_pool -= amt; + if (grpc_resource_quota_trace) { + 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_resource_quota_trace && resource_user->free_pool >= 0) { + gpr_log(GPR_DEBUG, "RQ %s %s: discard already satisfied alloc request", + resource_quota->name, resource_user->name); + } + if (resource_user->free_pool >= 0) { + resource_user->allocating = false; + grpc_exec_ctx_enqueue_list(exec_ctx, &resource_user->on_allocated, NULL); + gpr_mu_unlock(&resource_user->mu); + } else { + rulist_add_head(resource_user, GRPC_RULIST_AWAITING_ALLOCATION); + gpr_mu_unlock(&resource_user->mu); + return false; + } + } + return true; +} + +/* 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; + while ((resource_user = rulist_pop_head(resource_quota, + GRPC_RULIST_NON_EMPTY_FREE_POOL))) { + gpr_mu_lock(&resource_user->mu); + if (resource_user->free_pool > 0) { + int64_t amt = resource_user->free_pool; + resource_user->free_pool = 0; + resource_quota->free_pool += amt; + if (grpc_resource_quota_trace) { + 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); + } + gpr_mu_unlock(&resource_user->mu); + return true; + } else { + gpr_mu_unlock(&resource_user->mu); + } + } + return false; +} + +/* returns true if reclamation is proceeding */ +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_resource_quota_trace) { + 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_internal_ref(resource_quota); + grpc_closure *c = resource_user->reclaimers[destructive]; + resource_user->reclaimers[destructive] = NULL; + grpc_closure_run(exec_ctx, c, GRPC_ERROR_NONE); + return true; +} + +/******************************************************************************* + * ru_slice: a slice implementation that is backed by a grpc_resource_user + */ + +typedef struct { + gpr_slice_refcount base; + gpr_refcount refs; + grpc_resource_user *resource_user; + size_t size; +} ru_slice_refcount; + +static void ru_slice_ref(void *p) { + ru_slice_refcount *rc = p; + gpr_ref(&rc->refs); +} + +static void ru_slice_unref(void *p) { + ru_slice_refcount *rc = p; + if (gpr_unref(&rc->refs)) { + /* TODO(ctiller): this is dangerous, but I think safe for now: + we have no guarantee here that we're at a safe point for creating an + execution context, but we have no way of writing this code otherwise. + In the future: consider lifting gpr_slice to grpc, and offering an + internal_{ref,unref} pair that is execution context aware. + Alternatively, + make exec_ctx be thread local and 'do the right thing' (whatever that + is) + if NULL */ + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_free(&exec_ctx, rc->resource_user, rc->size); + grpc_exec_ctx_finish(&exec_ctx); + gpr_free(rc); + } +} + +static gpr_slice ru_slice_create(grpc_resource_user *resource_user, + size_t size) { + ru_slice_refcount *rc = gpr_malloc(sizeof(ru_slice_refcount) + size); + rc->base.ref = ru_slice_ref; + rc->base.unref = ru_slice_unref; + gpr_ref_init(&rc->refs, 1); + rc->resource_user = resource_user; + rc->size = size; + gpr_slice slice; + slice.refcount = &rc->base; + slice.data.refcounted.bytes = (uint8_t *)(rc + 1); + slice.data.refcounted.length = size; + return slice; +} + +/******************************************************************************* + * grpc_resource_quota internal implementation: resource user manipulation under + * the combiner + */ + +static void ru_allocate(grpc_exec_ctx *exec_ctx, void *ru, grpc_error *error) { + grpc_resource_user *resource_user = ru; + if (rulist_empty(resource_user->resource_quota, + GRPC_RULIST_AWAITING_ALLOCATION)) { + rq_step_sched(exec_ctx, resource_user->resource_quota); + } + 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 = ru; + if (!rulist_empty(resource_user->resource_quota, + GRPC_RULIST_AWAITING_ALLOCATION) && + rulist_empty(resource_user->resource_quota, + GRPC_RULIST_NON_EMPTY_FREE_POOL)) { + rq_step_sched(exec_ctx, resource_user->resource_quota); + } + rulist_add_tail(resource_user, GRPC_RULIST_NON_EMPTY_FREE_POOL); +} + +static void ru_post_benign_reclaimer(grpc_exec_ctx *exec_ctx, void *ru, + grpc_error *error) { + grpc_resource_user *resource_user = ru; + if (!rulist_empty(resource_user->resource_quota, + GRPC_RULIST_AWAITING_ALLOCATION) && + rulist_empty(resource_user->resource_quota, + GRPC_RULIST_NON_EMPTY_FREE_POOL) && + rulist_empty(resource_user->resource_quota, + GRPC_RULIST_RECLAIMER_BENIGN)) { + rq_step_sched(exec_ctx, resource_user->resource_quota); + } + 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 = ru; + if (!rulist_empty(resource_user->resource_quota, + GRPC_RULIST_AWAITING_ALLOCATION) && + rulist_empty(resource_user->resource_quota, + GRPC_RULIST_NON_EMPTY_FREE_POOL) && + rulist_empty(resource_user->resource_quota, + GRPC_RULIST_RECLAIMER_BENIGN) && + rulist_empty(resource_user->resource_quota, + GRPC_RULIST_RECLAIMER_DESTRUCTIVE)) { + rq_step_sched(exec_ctx, resource_user->resource_quota); + } + rulist_add_tail(resource_user, GRPC_RULIST_RECLAIMER_DESTRUCTIVE); +} + +static void ru_destroy(grpc_exec_ctx *exec_ctx, void *ru, grpc_error *error) { + grpc_resource_user *resource_user = ru; + GPR_ASSERT(resource_user->allocated == 0); + for (int i = 0; i < GRPC_RULIST_COUNT; i++) { + rulist_remove(resource_user, (grpc_rulist)i); + } + grpc_exec_ctx_sched(exec_ctx, resource_user->reclaimers[0], + GRPC_ERROR_CANCELLED, NULL); + grpc_exec_ctx_sched(exec_ctx, resource_user->reclaimers[1], + GRPC_ERROR_CANCELLED, NULL); + grpc_exec_ctx_sched(exec_ctx, (grpc_closure *)gpr_atm_no_barrier_load( + &resource_user->on_done_destroy_closure), + GRPC_ERROR_NONE, NULL); + if (resource_user->free_pool != 0) { + resource_user->resource_quota->free_pool += resource_user->free_pool; + rq_step_sched(exec_ctx, resource_user->resource_quota); + } +} + +static void ru_allocated_slices(grpc_exec_ctx *exec_ctx, void *arg, + grpc_error *error) { + grpc_resource_user_slice_allocator *slice_allocator = arg; + if (error == GRPC_ERROR_NONE) { + for (size_t i = 0; i < slice_allocator->count; i++) { + gpr_slice_buffer_add_indexed( + slice_allocator->dest, ru_slice_create(slice_allocator->resource_user, + slice_allocator->length)); + } + } + grpc_closure_run(exec_ctx, &slice_allocator->on_done, GRPC_ERROR_REF(error)); +} + +/******************************************************************************* + * grpc_resource_quota internal implementation: quota manipulation under the + * combiner + */ + +typedef struct { + int64_t size; + 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 = args; + int64_t delta = a->size - a->resource_quota->size; + a->resource_quota->size += delta; + a->resource_quota->free_pool += delta; + rq_step_sched(exec_ctx, a->resource_quota); + grpc_resource_quota_internal_unref(exec_ctx, a->resource_quota); + gpr_free(a); +} + +static void rq_reclamation_done(grpc_exec_ctx *exec_ctx, void *rq, + grpc_error *error) { + grpc_resource_quota *resource_quota = rq; + resource_quota->reclaiming = false; + rq_step_sched(exec_ctx, resource_quota); + grpc_resource_quota_internal_unref(exec_ctx, resource_quota); +} + +/******************************************************************************* + * grpc_resource_quota api + */ + +/* Public API */ +grpc_resource_quota *grpc_resource_quota_create(const char *name) { + grpc_resource_quota *resource_quota = gpr_malloc(sizeof(*resource_quota)); + gpr_ref_init(&resource_quota->refs, 1); + resource_quota->combiner = grpc_combiner_create(NULL); + resource_quota->free_pool = INT64_MAX; + resource_quota->size = INT64_MAX; + resource_quota->step_scheduled = false; + resource_quota->reclaiming = false; + if (name != NULL) { + resource_quota->name = gpr_strdup(name); + } else { + gpr_asprintf(&resource_quota->name, "anonymous_pool_%" PRIxPTR, + (intptr_t)resource_quota); + } + grpc_closure_init(&resource_quota->rq_step_closure, rq_step, resource_quota); + grpc_closure_init(&resource_quota->rq_reclamation_done_closure, + rq_reclamation_done, resource_quota); + for (int i = 0; i < GRPC_RULIST_COUNT; i++) { + resource_quota->roots[i] = NULL; + } + return resource_quota; +} + +void grpc_resource_quota_internal_unref(grpc_exec_ctx *exec_ctx, + grpc_resource_quota *resource_quota) { + if (gpr_unref(&resource_quota->refs)) { + grpc_combiner_destroy(exec_ctx, resource_quota->combiner); + gpr_free(resource_quota->name); + gpr_free(resource_quota); + } +} + +/* Public API */ +void grpc_resource_quota_unref(grpc_resource_quota *resource_quota) { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); + grpc_exec_ctx_finish(&exec_ctx); +} + +grpc_resource_quota *grpc_resource_quota_internal_ref( + 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) { + grpc_resource_quota_internal_ref(resource_quota); +} + +/* Public API */ +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 = gpr_malloc(sizeof(*a)); + a->resource_quota = grpc_resource_quota_internal_ref(resource_quota); + a->size = (int64_t)size; + grpc_closure_init(&a->closure, rq_resize, a); + grpc_combiner_execute(&exec_ctx, resource_quota->combiner, &a->closure, + GRPC_ERROR_NONE, false); + grpc_exec_ctx_finish(&exec_ctx); +} + +/******************************************************************************* + * grpc_resource_user channel args api + */ + +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_internal_ref( + 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); +} + +static void *rq_copy(void *rq) { + grpc_resource_quota_ref(rq); + return rq; +} + +static void rq_destroy(void *rq) { grpc_resource_quota_unref(rq); } + +static int rq_cmp(void *a, void *b) { return GPR_ICMP(a, b); } + +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; +} + +/******************************************************************************* + * grpc_resource_user api + */ + +void grpc_resource_user_init(grpc_resource_user *resource_user, + grpc_resource_quota *resource_quota, + const char *name) { + resource_user->resource_quota = + grpc_resource_quota_internal_ref(resource_quota); + grpc_closure_init(&resource_user->allocate_closure, &ru_allocate, + resource_user); + grpc_closure_init(&resource_user->add_to_free_pool_closure, + &ru_add_to_free_pool, resource_user); + grpc_closure_init(&resource_user->post_reclaimer_closure[0], + &ru_post_benign_reclaimer, resource_user); + grpc_closure_init(&resource_user->post_reclaimer_closure[1], + &ru_post_destructive_reclaimer, resource_user); + grpc_closure_init(&resource_user->destroy_closure, &ru_destroy, + resource_user); + gpr_mu_init(&resource_user->mu); + resource_user->allocated = 0; + resource_user->free_pool = 0; + grpc_closure_list_init(&resource_user->on_allocated); + resource_user->allocating = false; + resource_user->added_to_free_pool = false; + gpr_atm_no_barrier_store(&resource_user->on_done_destroy_closure, 0); + resource_user->reclaimers[0] = NULL; + resource_user->reclaimers[1] = NULL; + for (int i = 0; i < GRPC_RULIST_COUNT; i++) { + resource_user->links[i].next = resource_user->links[i].prev = NULL; + } + if (name != NULL) { + resource_user->name = gpr_strdup(name); + } else { + gpr_asprintf(&resource_user->name, "anonymous_resource_user_%" PRIxPTR, + (intptr_t)resource_user); + } +} + +void grpc_resource_user_shutdown(grpc_exec_ctx *exec_ctx, + grpc_resource_user *resource_user, + grpc_closure *on_done) { + gpr_mu_lock(&resource_user->mu); + GPR_ASSERT(gpr_atm_no_barrier_load(&resource_user->on_done_destroy_closure) == + 0); + gpr_atm_no_barrier_store(&resource_user->on_done_destroy_closure, + (gpr_atm)on_done); + if (resource_user->allocated == 0) { + grpc_combiner_execute(exec_ctx, resource_user->resource_quota->combiner, + &resource_user->destroy_closure, GRPC_ERROR_NONE, + false); + } + gpr_mu_unlock(&resource_user->mu); +} + +void grpc_resource_user_destroy(grpc_exec_ctx *exec_ctx, + grpc_resource_user *resource_user) { + grpc_resource_quota_internal_unref(exec_ctx, resource_user->resource_quota); + gpr_mu_destroy(&resource_user->mu); + gpr_free(resource_user->name); +} + +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); + grpc_closure *on_done_destroy = (grpc_closure *)gpr_atm_no_barrier_load( + &resource_user->on_done_destroy_closure); + if (on_done_destroy != NULL) { + /* already shutdown */ + if (grpc_resource_quota_trace) { + gpr_log(GPR_DEBUG, "RQ %s %s: alloc %" PRIdPTR " after shutdown", + resource_user->resource_quota->name, resource_user->name, size); + } + grpc_exec_ctx_sched( + exec_ctx, optional_on_done, + GRPC_ERROR_CREATE("Buffer pool user is already shutdown"), NULL); + gpr_mu_unlock(&resource_user->mu); + return; + } + resource_user->allocated += (int64_t)size; + resource_user->free_pool -= (int64_t)size; + if (grpc_resource_quota_trace) { + gpr_log(GPR_DEBUG, "RQ %s %s: alloc %" PRIdPTR "; allocated -> %" PRId64 + ", free_pool -> %" PRId64, + resource_user->resource_quota->name, resource_user->name, size, + resource_user->allocated, resource_user->free_pool); + } + if (resource_user->free_pool < 0) { + grpc_closure_list_append(&resource_user->on_allocated, optional_on_done, + GRPC_ERROR_NONE); + if (!resource_user->allocating) { + resource_user->allocating = true; + grpc_combiner_execute(exec_ctx, resource_user->resource_quota->combiner, + &resource_user->allocate_closure, GRPC_ERROR_NONE, + false); + } + } else { + grpc_exec_ctx_sched(exec_ctx, optional_on_done, GRPC_ERROR_NONE, NULL); + } + gpr_mu_unlock(&resource_user->mu); +} + +void grpc_resource_user_free(grpc_exec_ctx *exec_ctx, + grpc_resource_user *resource_user, size_t size) { + gpr_mu_lock(&resource_user->mu); + GPR_ASSERT(resource_user->allocated >= (int64_t)size); + bool was_zero_or_negative = resource_user->free_pool <= 0; + resource_user->free_pool += (int64_t)size; + resource_user->allocated -= (int64_t)size; + if (grpc_resource_quota_trace) { + gpr_log(GPR_DEBUG, "RQ %s %s: free %" PRIdPTR "; allocated -> %" PRId64 + ", free_pool -> %" PRId64, + resource_user->resource_quota->name, resource_user->name, size, + resource_user->allocated, resource_user->free_pool); + } + bool is_bigger_than_zero = resource_user->free_pool > 0; + if (is_bigger_than_zero && was_zero_or_negative && + !resource_user->added_to_free_pool) { + resource_user->added_to_free_pool = true; + grpc_combiner_execute(exec_ctx, resource_user->resource_quota->combiner, + &resource_user->add_to_free_pool_closure, + GRPC_ERROR_NONE, false); + } + grpc_closure *on_done_destroy = (grpc_closure *)gpr_atm_no_barrier_load( + &resource_user->on_done_destroy_closure); + if (on_done_destroy != NULL && resource_user->allocated == 0) { + grpc_combiner_execute(exec_ctx, resource_user->resource_quota->combiner, + &resource_user->destroy_closure, GRPC_ERROR_NONE, + false); + } + gpr_mu_unlock(&resource_user->mu); +} + +void grpc_resource_user_post_reclaimer(grpc_exec_ctx *exec_ctx, + grpc_resource_user *resource_user, + bool destructive, + grpc_closure *closure) { + if (gpr_atm_acq_load(&resource_user->on_done_destroy_closure) == 0) { + GPR_ASSERT(resource_user->reclaimers[destructive] == NULL); + resource_user->reclaimers[destructive] = closure; + grpc_combiner_execute(exec_ctx, resource_user->resource_quota->combiner, + &resource_user->post_reclaimer_closure[destructive], + GRPC_ERROR_NONE, false); + } else { + grpc_exec_ctx_sched(exec_ctx, closure, GRPC_ERROR_CANCELLED, NULL); + } +} + +void grpc_resource_user_finish_reclamation(grpc_exec_ctx *exec_ctx, + grpc_resource_user *resource_user) { + if (grpc_resource_quota_trace) { + gpr_log(GPR_DEBUG, "RQ %s %s: reclamation complete", + resource_user->resource_quota->name, resource_user->name); + } + grpc_combiner_execute( + exec_ctx, resource_user->resource_quota->combiner, + &resource_user->resource_quota->rq_reclamation_done_closure, + GRPC_ERROR_NONE, false); +} + +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_closure_init(&slice_allocator->on_allocated, ru_allocated_slices, + slice_allocator); + grpc_closure_init(&slice_allocator->on_done, cb, p); + slice_allocator->resource_user = resource_user; +} + +void grpc_resource_user_alloc_slices( + grpc_exec_ctx *exec_ctx, + grpc_resource_user_slice_allocator *slice_allocator, size_t length, + size_t count, gpr_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); +} + +gpr_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 new file mode 100644 index 00000000000..da68f21a2c7 --- /dev/null +++ b/src/core/lib/iomgr/resource_quota.h @@ -0,0 +1,229 @@ +/* + * + * Copyright 2016, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#ifndef GRPC_CORE_LIB_IOMGR_RESOURCE_QUOTA_H +#define GRPC_CORE_LIB_IOMGR_RESOURCE_QUOTA_H + +#include + +#include "src/core/lib/iomgr/exec_ctx.h" + +/** \file Tracks resource usage against a pool. + + The current implementation tracks only memory usage, but in the future + this may be extended to (for example) threads and file descriptors. + + A grpc_resource_quota represents the pooled resources, and + grpc_resource_user instances attach to the quota and consume those + resources. They also offer a vector for reclamation: if we become + resource constrained, grpc_resource_user instances are asked (in turn) to + free up whatever they can so that the system as a whole can make progress. + + There are three kinds of reclamation that take place, in order of increasing + invasiveness: + - an internal reclamation, where cached resource at the resource user level + is returned to the quota + - a benign reclamation phase, whereby resources that are in use but are not + helping anything make progress are reclaimed + - a destructive reclamation, whereby resources that are helping something + make progress may be enacted so that at least one part of the system can + complete. + + Only one reclamation will be outstanding for a given quota at a given time. + On each reclamation attempt, the kinds of reclamation are tried in order of + increasing invasiveness, stopping at the first one that succeeds. Thus, on a + given reclamation attempt, if internal and benign reclamation both fail, it + will wind up doing a destructive reclamation. However, the next reclamation + attempt may then be able to get what it needs via internal or benign + reclamation, due to resources that may have been freed up by the destructive + reclamation in the previous attempt. + + Future work will be to expose the current resource pressure so that back + pressure can be applied to avoid reclamation phases starting. + + Resource users own references to resource quotas, and resource quotas + maintain lists of users (which users arrange to leave before they are + destroyed) */ + +extern int grpc_resource_quota_trace; + +grpc_resource_quota *grpc_resource_quota_internal_ref( + grpc_resource_quota *resource_quota); +void grpc_resource_quota_internal_unref(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); + +/* Resource users are kept in (potentially) several intrusive linked lists + at once. These are the list names. */ +typedef enum { + /* Resource users that are waiting for an allocation */ + GRPC_RULIST_AWAITING_ALLOCATION, + /* Resource users that have free memory available for internal reclamation */ + GRPC_RULIST_NON_EMPTY_FREE_POOL, + /* Resource users that have published a benign reclamation is available */ + GRPC_RULIST_RECLAIMER_BENIGN, + /* Resource users that have published a destructive reclamation is + available */ + GRPC_RULIST_RECLAIMER_DESTRUCTIVE, + /* Number of lists: must be last */ + GRPC_RULIST_COUNT +} grpc_rulist; + +typedef struct grpc_resource_user grpc_resource_user; + +/* Internal linked list pointers for a resource user */ +typedef struct { + grpc_resource_user *next; + grpc_resource_user *prev; +} grpc_resource_user_link; + +struct grpc_resource_user { + /* The quota this resource user consumes from */ + grpc_resource_quota *resource_quota; + + /* Closure to schedule an allocation under the resource quota combiner lock */ + grpc_closure allocate_closure; + /* Closure to publish a non empty free pool under the resource quota combiner + lock */ + grpc_closure add_to_free_pool_closure; + + gpr_mu mu; + /* Total allocated memory outstanding by this resource user in bytes; + always positive */ + int64_t allocated; + /* The amount of memory (in bytes) this user has cached for its own use: to + avoid quota contention, each resource user can keep some memory in + addition to what it is immediately using (e.g., for caching), and the quota + can pull it back under memory pressure. + This value can become negative if more memory has been requested than + existed in the free pool, at which point the quota is consulted to bring + this value non-negative (asynchronously). */ + int64_t free_pool; + /* A list of closures to call once free_pool becomes non-negative - ie when + all outstanding allocations have been granted. */ + grpc_closure_list on_allocated; + /* True if we are currently trying to allocate from the quota, false if not */ + bool allocating; + /* True if we are currently trying to add ourselves to the non-free quota + list, false otherwise */ + bool added_to_free_pool; + + /* Reclaimers: index 0 is the benign reclaimer, 1 is the destructive reclaimer + */ + grpc_closure *reclaimers[2]; + /* Trampoline closures to finish reclamation and re-enter the quota combiner + lock */ + grpc_closure post_reclaimer_closure[2]; + + /* Closure to execute under the quota combiner to de-register and shutdown the + resource user */ + grpc_closure destroy_closure; + /* User supplied closure to call once the user has finished shutting down AND + all outstanding allocations have been freed. Real type is grpc_closure*, + but it's stored as an atomic to avoid a mutex on some fast paths. */ + gpr_atm on_done_destroy_closure; + + /* Links in the various grpc_rulist lists */ + grpc_resource_user_link links[GRPC_RULIST_COUNT]; + + /* The name of this resource user, for debugging/tracing */ + char *name; +}; + +void grpc_resource_user_init(grpc_resource_user *resource_user, + grpc_resource_quota *resource_quota, + const char *name); +void grpc_resource_user_shutdown(grpc_exec_ctx *exec_ctx, + grpc_resource_user *resource_user, + grpc_closure *on_done); +void grpc_resource_user_destroy(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); +/* Release memory back to the quota */ +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); +/* Finish a reclamation step */ +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 { + /* Closure for when a resource user allocation completes */ + grpc_closure on_allocated; + /* Closure to call when slices have been allocated */ + grpc_closure on_done; + /* Length of slices to allocate on the current request */ + size_t length; + /* Number of slices to allocate on the current request */ + size_t count; + /* Destination for slices to allocate on the current request */ + gpr_slice_buffer *dest; + /* Parent 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); + +/* 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, gpr_slice_buffer *dest); + +/* Allocate one slice of length \a size synchronously. */ +gpr_slice grpc_resource_user_slice_malloc(grpc_exec_ctx *exec_ctx, + grpc_resource_user *resource_user, + size_t size); + +#endif /* GRPC_CORE_LIB_IOMGR_RESOURCE_QUOTA_H */ diff --git a/src/core/lib/iomgr/tcp_client.h b/src/core/lib/iomgr/tcp_client.h index fe1e7f4d3ec..18e6e60ebce 100644 --- a/src/core/lib/iomgr/tcp_client.h +++ b/src/core/lib/iomgr/tcp_client.h @@ -39,6 +39,10 @@ #include "src/core/lib/iomgr/pollset_set.h" #include "src/core/lib/iomgr/resolve_address.h" +/* Channel arg (integer) setting how large a slice to try and read from the wire + each time recvmsg (or equivalent) is called */ +#define GRPC_ARG_TCP_READ_CHUNK_SIZE "grpc.experimental.tcp_read_chunk_size" + /* 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). @@ -47,6 +51,7 @@ 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, gpr_timespec deadline); diff --git a/src/core/lib/iomgr/tcp_client_posix.c b/src/core/lib/iomgr/tcp_client_posix.c index e7ae1ef6957..bc08c94ee00 100644 --- a/src/core/lib/iomgr/tcp_client_posix.c +++ b/src/core/lib/iomgr/tcp_client_posix.c @@ -35,7 +35,7 @@ #ifdef GRPC_POSIX_SOCKET -#include "src/core/lib/iomgr/tcp_client.h" +#include "src/core/lib/iomgr/tcp_client_posix.h" #include #include @@ -47,6 +47,7 @@ #include #include +#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/iomgr/ev_posix.h" #include "src/core/lib/iomgr/iomgr_posix.h" #include "src/core/lib/iomgr/sockaddr_utils.h" @@ -69,6 +70,7 @@ typedef struct { 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) { @@ -114,10 +116,39 @@ static void tc_on_alarm(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { if (done) { gpr_mu_destroy(&ac->mu); gpr_free(ac->addr_str); + grpc_channel_args_destroy(ac->channel_args); gpr_free(ac); } } +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) { + size_t tcp_read_chunk_size = GRPC_TCP_DEFAULT_READ_SLICE_SIZE; + 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_TCP_READ_CHUNK_SIZE)) { + grpc_integer_options options = {(int)tcp_read_chunk_size, 1, + 8 * 1024 * 1024}; + tcp_read_chunk_size = (size_t)grpc_channel_arg_get_integer( + &channel_args->args[i], options); + } else if (0 == + strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) { + grpc_resource_quota_internal_unref(exec_ctx, resource_quota); + resource_quota = grpc_resource_quota_internal_ref( + channel_args->args[i].value.pointer.p); + } + } + } + + grpc_endpoint *ep = + grpc_tcp_create(fd, resource_quota, tcp_read_chunk_size, addr_str); + grpc_resource_quota_internal_unref(exec_ctx, resource_quota); + return ep; +} + static void on_writable(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { async_connect *ac = acp; int so_error = 0; @@ -165,7 +196,8 @@ static void on_writable(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { switch (so_error) { case 0: grpc_pollset_set_del_fd(exec_ctx, ac->interested_parties, fd); - *ep = grpc_tcp_create(fd, GRPC_TCP_DEFAULT_READ_SLICE_SIZE, ac->addr_str); + *ep = grpc_tcp_client_create_from_fd(exec_ctx, fd, ac->channel_args, + ac->addr_str); fd = NULL; break; case ENOBUFS: @@ -215,6 +247,7 @@ finish: if (done) { gpr_mu_destroy(&ac->mu); gpr_free(ac->addr_str); + grpc_channel_args_destroy(ac->channel_args); gpr_free(ac); } grpc_exec_ctx_sched(exec_ctx, closure, error, NULL); @@ -223,6 +256,7 @@ finish: 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, gpr_timespec deadline) { int fd; @@ -270,7 +304,8 @@ static void tcp_client_connect_impl(grpc_exec_ctx *exec_ctx, fdobj = grpc_fd_create(fd, name); if (err >= 0) { - *ep = grpc_tcp_create(fdobj, GRPC_TCP_DEFAULT_READ_SLICE_SIZE, addr_str); + *ep = + grpc_tcp_client_create_from_fd(exec_ctx, fdobj, channel_args, addr_str); grpc_exec_ctx_sched(exec_ctx, closure, GRPC_ERROR_NONE, NULL); goto done; } @@ -295,6 +330,7 @@ static void tcp_client_connect_impl(grpc_exec_ctx *exec_ctx, ac->refs = 2; ac->write_closure.cb = on_writable; ac->write_closure.cb_arg = ac; + ac->channel_args = grpc_channel_args_copy(channel_args); if (grpc_tcp_trace) { gpr_log(GPR_DEBUG, "CLIENT_CONNECT: %s: asynchronously connecting", @@ -316,16 +352,18 @@ done: // overridden by api_fuzzer.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_resolved_address *addr, + grpc_pollset_set *interested_parties, const grpc_channel_args *channel_args, + const grpc_resolved_address *addr, gpr_timespec 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, gpr_timespec deadline) { - grpc_tcp_client_connect_impl(exec_ctx, closure, ep, interested_parties, addr, - deadline); + grpc_tcp_client_connect_impl(exec_ctx, closure, ep, interested_parties, + channel_args, addr, deadline); } #endif diff --git a/include/grpc++/impl/codegen/sync_cxx11.h b/src/core/lib/iomgr/tcp_client_posix.h similarity index 78% rename from include/grpc++/impl/codegen/sync_cxx11.h rename to src/core/lib/iomgr/tcp_client_posix.h index 6626ca1f94c..efc5fcd5bba 100644 --- a/include/grpc++/impl/codegen/sync_cxx11.h +++ b/src/core/lib/iomgr/tcp_client_posix.h @@ -31,19 +31,15 @@ * */ -#ifndef GRPCXX_IMPL_CODEGEN_SYNC_CXX11_H -#define GRPCXX_IMPL_CODEGEN_SYNC_CXX11_H +#ifndef GRPC_CORE_LIB_IOMGR_TCP_CLIENT_POSIX_H +#define GRPC_CORE_LIB_IOMGR_TCP_CLIENT_POSIX_H -#include -#include +#include "src/core/lib/iomgr/endpoint.h" +#include "src/core/lib/iomgr/ev_posix.h" +#include "src/core/lib/iomgr/tcp_client.h" -namespace grpc { +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); -using std::condition_variable; -using std::mutex; -using std::lock_guard; -using std::unique_lock; - -} // namespace grpc - -#endif // GRPCXX_IMPL_CODEGEN_SYNC_CXX11_H +#endif /* GRPC_CORE_LIB_IOMGR_TCP_CLIENT_POSIX_H */ diff --git a/src/core/lib/iomgr/tcp_client_uv.c b/src/core/lib/iomgr/tcp_client_uv.c index 62746670420..b07f9ceffa3 100644 --- a/src/core/lib/iomgr/tcp_client_uv.c +++ b/src/core/lib/iomgr/tcp_client_uv.c @@ -54,9 +54,12 @@ typedef struct grpc_uv_tcp_connect { grpc_endpoint **endpoint; int refs; char *addr_name; + grpc_resource_quota *resource_quota; } grpc_uv_tcp_connect; -static void uv_tcp_connect_cleanup(grpc_uv_tcp_connect *connect) { +static void uv_tcp_connect_cleanup(grpc_exec_ctx *exec_ctx, + grpc_uv_tcp_connect *connect) { + grpc_resource_quota_internal_unref(exec_ctx, connect->resource_quota); gpr_free(connect); } @@ -74,7 +77,7 @@ static void uv_tc_on_alarm(grpc_exec_ctx *exec_ctx, void *acp, } done = (--connect->refs == 0); if (done) { - uv_tcp_connect_cleanup(connect); + uv_tcp_connect_cleanup(exec_ctx, connect); } } @@ -86,8 +89,8 @@ static void uv_tc_on_connect(uv_connect_t *req, int status) { grpc_closure *closure = connect->closure; grpc_timer_cancel(&exec_ctx, &connect->alarm); if (status == 0) { - *connect->endpoint = - grpc_tcp_create(connect->tcp_handle, connect->addr_name); + *connect->endpoint = grpc_tcp_create( + connect->tcp_handle, connect->resource_quota, connect->addr_name); } else { error = GRPC_ERROR_CREATE("Failed to connect to remote host"); error = grpc_error_set_int(error, GRPC_ERROR_INT_ERRNO, -status); @@ -105,7 +108,7 @@ static void uv_tc_on_connect(uv_connect_t *req, int status) { } done = (--connect->refs == 0); if (done) { - uv_tcp_connect_cleanup(connect); + uv_tcp_connect_cleanup(&exec_ctx, connect); } grpc_exec_ctx_sched(&exec_ctx, closure, error, NULL); grpc_exec_ctx_finish(&exec_ctx); @@ -114,16 +117,31 @@ static void uv_tc_on_connect(uv_connect_t *req, int status) { 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, gpr_timespec deadline) { grpc_uv_tcp_connect *connect; + grpc_resource_quota *resource_quota = grpc_resource_quota_create(NULL); + (void)channel_args; (void)interested_parties; + + 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_internal_unref(exec_ctx, resource_quota); + resource_quota = grpc_resource_quota_internal_ref( + channel_args->args[i].value.pointer.p); + } + } + } + connect = gpr_malloc(sizeof(grpc_uv_tcp_connect)); memset(connect, 0, sizeof(grpc_uv_tcp_connect)); connect->closure = closure; connect->endpoint = ep; connect->tcp_handle = 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; // TODO(murgatroid99): figure out what the return value here means @@ -138,16 +156,18 @@ static void tcp_client_connect_impl(grpc_exec_ctx *exec_ctx, // overridden by api_fuzzer.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_resolved_address *addr, + grpc_pollset_set *interested_parties, const grpc_channel_args *channel_args, + const grpc_resolved_address *addr, gpr_timespec 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, gpr_timespec deadline) { - grpc_tcp_client_connect_impl(exec_ctx, closure, ep, interested_parties, addr, - deadline); + grpc_tcp_client_connect_impl(exec_ctx, closure, ep, interested_parties, + channel_args, addr, deadline); } #endif /* GRPC_UV */ diff --git a/src/core/lib/iomgr/tcp_client_windows.c b/src/core/lib/iomgr/tcp_client_windows.c index fdd8c1a1f81..30f7c66f159 100644 --- a/src/core/lib/iomgr/tcp_client_windows.c +++ b/src/core/lib/iomgr/tcp_client_windows.c @@ -43,6 +43,7 @@ #include #include +#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/iomgr/iocp_windows.h" #include "src/core/lib/iomgr/sockaddr.h" #include "src/core/lib/iomgr/sockaddr_utils.h" @@ -61,13 +62,16 @@ typedef struct { int refs; grpc_closure on_connect; grpc_endpoint **endpoint; + grpc_resource_quota *resource_quota; } async_connect; -static void async_connect_unlock_and_cleanup(async_connect *ac, +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) { + grpc_resource_quota_internal_unref(exec_ctx, ac->resource_quota); gpr_mu_destroy(&ac->mu); gpr_free(ac->addr_name); gpr_free(ac); @@ -83,7 +87,7 @@ static void on_alarm(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { if (socket != NULL) { grpc_winsocket_shutdown(socket); } - async_connect_unlock_and_cleanup(ac, socket); + async_connect_unlock_and_cleanup(exec_ctx, ac, socket); } static void on_connect(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { @@ -113,12 +117,12 @@ static void on_connect(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { if (!wsa_success) { error = GRPC_WSA_ERROR(WSAGetLastError(), "ConnectEx"); } else { - *ep = grpc_tcp_create(socket, ac->addr_name); + *ep = grpc_tcp_create(socket, ac->resource_quota, ac->addr_name); socket = NULL; } } - async_connect_unlock_and_cleanup(ac, socket); + async_connect_unlock_and_cleanup(exec_ctx, ac, socket); /* If the connection was aborted, the callback was already called when the deadline was met. */ grpc_exec_ctx_sched(exec_ctx, on_done, error, NULL); @@ -129,6 +133,7 @@ static void on_connect(grpc_exec_ctx *exec_ctx, void *acp, grpc_error *error) { void grpc_tcp_client_connect(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, gpr_timespec deadline) { SOCKET sock = INVALID_SOCKET; @@ -144,6 +149,17 @@ void grpc_tcp_client_connect(grpc_exec_ctx *exec_ctx, grpc_closure *on_done, grpc_winsocket_callback_info *info; grpc_error *error = GRPC_ERROR_NONE; + 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_internal_unref(exec_ctx, resource_quota); + resource_quota = grpc_resource_quota_internal_ref( + channel_args->args[i].value.pointer.p); + } + } + } + *endpoint = NULL; /* Use dualstack sockets where available. */ @@ -177,8 +193,8 @@ void grpc_tcp_client_connect(grpc_exec_ctx *exec_ctx, grpc_closure *on_done, grpc_sockaddr_make_wildcard6(0, &local_address); - status = - bind(sock, (struct sockaddr *)&local_address.addr, 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; @@ -206,6 +222,7 @@ void grpc_tcp_client_connect(grpc_exec_ctx *exec_ctx, grpc_closure *on_done, ac->refs = 2; ac->addr_name = grpc_sockaddr_to_uri(addr); ac->endpoint = endpoint; + ac->resource_quota = resource_quota; grpc_closure_init(&ac->on_connect, on_connect, ac); grpc_timer_init(exec_ctx, &ac->alarm, deadline, on_alarm, ac, @@ -225,6 +242,7 @@ failure: } else if (sock != INVALID_SOCKET) { closesocket(sock); } + grpc_resource_quota_internal_unref(exec_ctx, resource_quota); grpc_exec_ctx_sched(exec_ctx, on_done, final_error, NULL); } diff --git a/src/core/lib/iomgr/tcp_posix.c b/src/core/lib/iomgr/tcp_posix.c index 18c63cfbaec..880af93ee1a 100644 --- a/src/core/lib/iomgr/tcp_posix.c +++ b/src/core/lib/iomgr/tcp_posix.c @@ -80,6 +80,7 @@ typedef struct { msg_iovlen_type iov_size; /* Number of slices to allocate per read attempt */ size_t slice_size; gpr_refcount refcount; + gpr_atm shutdown_count; /* garbage after the last read */ gpr_slice_buffer last_read_buffer; @@ -100,15 +101,29 @@ typedef struct { grpc_closure write_closure; char *peer_string; + + grpc_resource_user resource_user; + grpc_resource_user_slice_allocator slice_allocator; } grpc_tcp; 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_unref_closure(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */, + grpc_error *error); + +static void tcp_maybe_shutdown_resource_user(grpc_exec_ctx *exec_ctx, + grpc_tcp *tcp) { + if (gpr_atm_full_fetch_add(&tcp->shutdown_count, 1) == 0) { + grpc_resource_user_shutdown(exec_ctx, &tcp->resource_user, + grpc_closure_create(tcp_unref_closure, tcp)); + } +} static void tcp_shutdown(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) { grpc_tcp *tcp = (grpc_tcp *)ep; + tcp_maybe_shutdown_resource_user(exec_ctx, tcp); grpc_fd_shutdown(exec_ctx, tcp->em_fd); } @@ -116,6 +131,7 @@ 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, "tcp_unref_orphan"); gpr_slice_buffer_destroy(&tcp->last_read_buffer); + grpc_resource_user_destroy(exec_ctx, &tcp->resource_user); gpr_free(tcp->peer_string); gpr_free(tcp); } @@ -152,9 +168,16 @@ static void tcp_unref(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { static void tcp_ref(grpc_tcp *tcp) { gpr_ref(&tcp->refcount); } #endif +static void tcp_unref_closure(grpc_exec_ctx *exec_ctx, void *arg, + grpc_error *error) { + TCP_UNREF(exec_ctx, arg, "resource_user"); +} + static void tcp_destroy(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) { grpc_network_status_unregister_endpoint(ep); grpc_tcp *tcp = (grpc_tcp *)ep; + tcp_maybe_shutdown_resource_user(exec_ctx, tcp); + gpr_slice_buffer_reset_and_unref(&tcp->last_read_buffer); TCP_UNREF(exec_ctx, tcp, "destroy"); } @@ -181,7 +204,7 @@ static void call_read_cb(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp, } #define MAX_READ_IOVEC 4 -static void tcp_continue_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; @@ -192,10 +215,6 @@ static void tcp_continue_read(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { GPR_ASSERT(tcp->incoming_buffer->count <= MAX_READ_IOVEC); GPR_TIMER_BEGIN("tcp_continue_read", 0); - while (tcp->incoming_buffer->count < (size_t)tcp->iov_size) { - gpr_slice_buffer_add_indexed(tcp->incoming_buffer, - gpr_slice_malloc(tcp->slice_size)); - } for (i = 0; i < tcp->incoming_buffer->count; i++) { iov[i].iov_base = GPR_SLICE_START_PTR(tcp->incoming_buffer->slices[i]); iov[i].iov_len = GPR_SLICE_LENGTH(tcp->incoming_buffer->slices[i]); @@ -232,7 +251,7 @@ static void tcp_continue_read(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { } else if (read_bytes == 0) { /* 0 read size ==> end of stream */ gpr_slice_buffer_reset_and_unref(tcp->incoming_buffer); - call_read_cb(exec_ctx, tcp, GRPC_ERROR_CREATE("EOF")); + call_read_cb(exec_ctx, tcp, GRPC_ERROR_CREATE("Socket closed")); TCP_UNREF(exec_ctx, tcp, "read"); } else { GPR_ASSERT((size_t)read_bytes <= tcp->incoming_buffer->length); @@ -252,6 +271,30 @@ static void tcp_continue_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 = tcpp; + if (error != GRPC_ERROR_NONE) { + gpr_slice_buffer_reset_and_unref(tcp->incoming_buffer); + gpr_slice_buffer_reset_and_unref(&tcp->last_read_buffer); + call_read_cb(exec_ctx, tcp, GRPC_ERROR_REF(error)); + TCP_UNREF(exec_ctx, tcp, "read"); + } else { + tcp_do_read(exec_ctx, tcp); + } +} + +static void tcp_continue_read(grpc_exec_ctx *exec_ctx, grpc_tcp *tcp) { + if (tcp->incoming_buffer->count < (size_t)tcp->iov_size) { + grpc_resource_user_alloc_slices( + exec_ctx, &tcp->slice_allocator, tcp->slice_size, + (size_t)tcp->iov_size - tcp->incoming_buffer->count, + tcp->incoming_buffer); + } else { + 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; @@ -259,6 +302,7 @@ static void tcp_handle_read(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */, if (error != GRPC_ERROR_NONE) { gpr_slice_buffer_reset_and_unref(tcp->incoming_buffer); + gpr_slice_buffer_reset_and_unref(&tcp->last_read_buffer); call_read_cb(exec_ctx, tcp, GRPC_ERROR_REF(error)); TCP_UNREF(exec_ctx, tcp, "read"); } else { @@ -469,6 +513,11 @@ static grpc_workqueue *tcp_get_workqueue(grpc_endpoint *ep) { return grpc_fd_get_workqueue(tcp->em_fd); } +static grpc_resource_user *tcp_get_resource_user(grpc_endpoint *ep) { + grpc_tcp *tcp = (grpc_tcp *)ep; + return &tcp->resource_user; +} + static const grpc_endpoint_vtable vtable = {tcp_read, tcp_write, tcp_get_workqueue, @@ -476,10 +525,12 @@ static const grpc_endpoint_vtable vtable = {tcp_read, tcp_add_to_pollset_set, tcp_shutdown, tcp_destroy, + tcp_get_resource_user, tcp_get_peer}; -grpc_endpoint *grpc_tcp_create(grpc_fd *em_fd, size_t slice_size, - const char *peer_string) { +grpc_endpoint *grpc_tcp_create(grpc_fd *em_fd, + grpc_resource_quota *resource_quota, + size_t slice_size, const char *peer_string) { grpc_tcp *tcp = (grpc_tcp *)gpr_malloc(sizeof(grpc_tcp)); tcp->base.vtable = &vtable; tcp->peer_string = gpr_strdup(peer_string); @@ -492,14 +543,20 @@ grpc_endpoint *grpc_tcp_create(grpc_fd *em_fd, size_t slice_size, tcp->slice_size = slice_size; tcp->iov_size = 1; tcp->finished_edge = true; - /* paired with unref in grpc_tcp_destroy */ - gpr_ref_init(&tcp->refcount, 1); + /* paired with unref in grpc_tcp_destroy, and with the shutdown for our + * resource_user */ + gpr_ref_init(&tcp->refcount, 2); + gpr_atm_no_barrier_store(&tcp->shutdown_count, 0); tcp->em_fd = em_fd; tcp->read_closure.cb = tcp_handle_read; tcp->read_closure.cb_arg = tcp; tcp->write_closure.cb = tcp_handle_write; tcp->write_closure.cb_arg = tcp; gpr_slice_buffer_init(&tcp->last_read_buffer); + grpc_resource_user_init(&tcp->resource_user, resource_quota, peer_string); + grpc_resource_user_slice_allocator_init(&tcp->slice_allocator, + &tcp->resource_user, + tcp_read_allocation_done, tcp); /* Tell network status tracker about new endpoint */ grpc_network_status_register_endpoint(&tcp->base); @@ -514,10 +571,13 @@ int grpc_tcp_fd(grpc_endpoint *ep) { 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; GPR_ASSERT(ep->vtable == &vtable); tcp->release_fd = fd; tcp->release_fd_cb = done; + tcp_maybe_shutdown_resource_user(exec_ctx, tcp); + gpr_slice_buffer_reset_and_unref(&tcp->last_read_buffer); TCP_UNREF(exec_ctx, tcp, "destroy"); } diff --git a/src/core/lib/iomgr/tcp_posix.h b/src/core/lib/iomgr/tcp_posix.h index 99125836d69..1c0d13f96e2 100644 --- a/src/core/lib/iomgr/tcp_posix.h +++ b/src/core/lib/iomgr/tcp_posix.h @@ -53,8 +53,8 @@ extern int 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_fd *fd, size_t read_slice_size, - const char *peer_string); +grpc_endpoint *grpc_tcp_create(grpc_fd *fd, grpc_resource_quota *resource_quota, + size_t read_slice_size, const char *peer_string); /* Return the tcp endpoint's fd, or -1 if this is not available. Does not release the fd. diff --git a/src/core/lib/iomgr/tcp_server.h b/src/core/lib/iomgr/tcp_server.h index 0c2a4f41da7..6eba8c40571 100644 --- a/src/core/lib/iomgr/tcp_server.h +++ b/src/core/lib/iomgr/tcp_server.h @@ -61,7 +61,8 @@ typedef void (*grpc_tcp_server_cb)(grpc_exec_ctx *exec_ctx, void *arg, /* 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_closure *shutdown_complete, +grpc_error *grpc_tcp_server_create(grpc_exec_ctx *exec_ctx, + grpc_closure *shutdown_complete, const grpc_channel_args *args, grpc_tcp_server **server); diff --git a/src/core/lib/iomgr/tcp_server_posix.c b/src/core/lib/iomgr/tcp_server_posix.c index 127f8595d1b..b6fc1e4ca29 100644 --- a/src/core/lib/iomgr/tcp_server_posix.c +++ b/src/core/lib/iomgr/tcp_server_posix.c @@ -134,6 +134,8 @@ struct grpc_tcp_server { /* next pollset to assign a channel to */ gpr_atm next_pollset_to_assign; + + grpc_resource_quota *resource_quota; }; static gpr_once check_init = GPR_ONCE_INIT; @@ -150,23 +152,37 @@ static void init(void) { #endif } -grpc_error *grpc_tcp_server_create(grpc_closure *shutdown_complete, +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 = gpr_malloc(sizeof(grpc_tcp_server)); s->so_reuseport = has_so_reuseport; + 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_ALLOW_REUSEPORT, args->args[i].key)) { if (args->args[i].type == GRPC_ARG_INTEGER) { s->so_reuseport = has_so_reuseport && (args->args[i].value.integer != 0); } else { + grpc_resource_quota_internal_unref(exec_ctx, s->resource_quota); gpr_free(s); return GRPC_ERROR_CREATE(GRPC_ARG_ALLOW_REUSEPORT " must be an integer"); } + } else if (0 == strcmp(GRPC_ARG_RESOURCE_QUOTA, args->args[i].key)) { + if (args->args[i].type == GRPC_ARG_POINTER) { + grpc_resource_quota_internal_unref(exec_ctx, s->resource_quota); + s->resource_quota = + grpc_resource_quota_internal_ref(args->args[i].value.pointer.p); + } else { + grpc_resource_quota_internal_unref(exec_ctx, s->resource_quota); + gpr_free(s); + return GRPC_ERROR_CREATE(GRPC_ARG_RESOURCE_QUOTA + " must be a pointer to a buffer pool"); + } } } gpr_ref_init(&s->refs, 1); @@ -203,6 +219,8 @@ static void finish_shutdown(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { gpr_free(sp); } + grpc_resource_quota_internal_unref(exec_ctx, s->resource_quota); + gpr_free(s); } @@ -419,7 +437,8 @@ static void on_read(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *err) { sp->server->on_accept_cb( exec_ctx, sp->server->on_accept_cb_arg, - grpc_tcp_create(fdobj, GRPC_TCP_DEFAULT_READ_SLICE_SIZE, addr_str), + grpc_tcp_create(fdobj, sp->server->resource_quota, + GRPC_TCP_DEFAULT_READ_SLICE_SIZE, addr_str), read_notifier_pollset, &acceptor); gpr_free(name); diff --git a/src/core/lib/iomgr/tcp_server_uv.c b/src/core/lib/iomgr/tcp_server_uv.c index 73e4db3d650..b5b9b92a20a 100644 --- a/src/core/lib/iomgr/tcp_server_uv.c +++ b/src/core/lib/iomgr/tcp_server_uv.c @@ -76,13 +76,30 @@ struct grpc_tcp_server { /* shutdown callback */ grpc_closure *shutdown_complete; + + grpc_resource_quota *resource_quota; }; -grpc_error *grpc_tcp_server_create(grpc_closure *shutdown_complete, +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 = gpr_malloc(sizeof(grpc_tcp_server)); - (void)args; + 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_internal_unref(exec_ctx, s->resource_quota); + s->resource_quota = + grpc_resource_quota_internal_ref(args->args[i].value.pointer.p); + } else { + grpc_resource_quota_internal_unref(exec_ctx, s->resource_quota); + gpr_free(s); + return GRPC_ERROR_CREATE(GRPC_ARG_RESOURCE_QUOTA + " must be a pointer to a buffer pool"); + } + } + } gpr_ref_init(&s->refs, 1); s->on_accept_cb = NULL; s->on_accept_cb_arg = NULL; @@ -119,6 +136,7 @@ static void finish_shutdown(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { gpr_free(sp->handle); gpr_free(sp); } + grpc_resource_quota_internal_unref(exec_ctx, s->resource_quota); gpr_free(s); } @@ -201,7 +219,7 @@ static void on_connect(uv_stream_t *server, int status) { } else { gpr_log(GPR_INFO, "uv_tcp_getpeername error: %s", uv_strerror(status)); } - ep = grpc_tcp_create(client, peer_name_string); + ep = grpc_tcp_create(client, sp->server->resource_quota, peer_name_string); sp->server->on_accept_cb(&exec_ctx, sp->server->on_accept_cb_arg, ep, NULL, &acceptor); grpc_exec_ctx_finish(&exec_ctx); diff --git a/src/core/lib/iomgr/tcp_server_windows.c b/src/core/lib/iomgr/tcp_server_windows.c index ad6769a6ba8..ae54c70d2d0 100644 --- a/src/core/lib/iomgr/tcp_server_windows.c +++ b/src/core/lib/iomgr/tcp_server_windows.c @@ -100,14 +100,32 @@ struct grpc_tcp_server { /* shutdown callback */ grpc_closure *shutdown_complete; + + grpc_resource_quota *resource_quota; }; /* Public function. Allocates the proper data structures to hold a grpc_tcp_server. */ -grpc_error *grpc_tcp_server_create(grpc_closure *shutdown_complete, +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 = 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_internal_unref(exec_ctx, s->resource_quota); + s->resource_quota = + grpc_resource_quota_internal_ref(args->args[i].value.pointer.p); + } else { + grpc_resource_quota_internal_unref(exec_ctx, s->resource_quota); + gpr_free(s); + return GRPC_ERROR_CREATE(GRPC_ARG_RESOURCE_QUOTA + " must be a pointer to a buffer pool"); + } + } + } gpr_ref_init(&s->refs, 1); gpr_mu_init(&s->mu); s->active_ports = 0; @@ -137,6 +155,7 @@ static void finish_shutdown(grpc_exec_ctx *exec_ctx, grpc_tcp_server *s) { grpc_winsocket_destroy(sp->socket); gpr_free(sp); } + grpc_resource_quota_internal_unref(exec_ctx, s->resource_quota); gpr_free(s); } @@ -207,12 +226,13 @@ static grpc_error *prepare_socket(SOCKET sock, goto failure; } - sockname_temp.len = sizeof(struct sockaddr_storage); + int sockname_temp_len = sizeof(struct sockaddr_storage); if (getsockname(sock, (struct sockaddr *)sockname_temp.addr, - &sockname_temp.len) == SOCKET_ERROR) { + &sockname_temp_len) == SOCKET_ERROR) { error = GRPC_WSA_ERROR(WSAGetLastError(), "getsockname"); goto failure; } + sockname_temp.len = sockname_temp_len; *port = grpc_sockaddr_get_port(&sockname_temp); return GRPC_ERROR_NONE; @@ -357,8 +377,10 @@ static void on_accept(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { 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); + getpeername(sock, (struct sockaddr *)peer_name.addr, &peer_name_len); + peer_name.len = peer_name_len; if (!err) { peer_name_string = grpc_sockaddr_to_uri(&peer_name); } else { @@ -368,7 +390,7 @@ static void on_accept(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { } gpr_asprintf(&fd_name, "tcp_server:%s", peer_name_string); ep = grpc_tcp_create(grpc_winsocket_create(sock, fd_name), - peer_name_string); + sp->server->resource_quota, peer_name_string); gpr_free(fd_name); gpr_free(peer_name_string); } else { @@ -466,10 +488,11 @@ grpc_error *grpc_tcp_server_add_port(grpc_tcp_server *s, as some previously created listener. */ if (grpc_sockaddr_get_port(addr) == 0) { for (sp = s->head; sp; sp = sp->next) { - sockname_temp.len = sizeof(struct sockaddr_storage); + int sockname_temp_len = sizeof(struct sockaddr_storage); if (0 == getsockname(sp->socket->socket, (struct sockaddr *)sockname_temp.addr, - &sockname_temp.len)) { + &sockname_temp_len)) { + sockname_temp.len = sockname_temp_len; *port = grpc_sockaddr_get_port(&sockname_temp); if (*port > 0) { allocated_addr = gpr_malloc(sizeof(grpc_resolved_address)); diff --git a/src/core/lib/iomgr/tcp_uv.c b/src/core/lib/iomgr/tcp_uv.c index 05d6eeb2408..8e74c9e8633 100644 --- a/src/core/lib/iomgr/tcp_uv.c +++ b/src/core/lib/iomgr/tcp_uv.c @@ -54,6 +54,9 @@ typedef struct { grpc_endpoint base; gpr_refcount refcount; + uv_write_t write_req; + uv_shutdown_t shutdown_req; + uv_tcp_t *handle; grpc_closure *read_cb; @@ -64,14 +67,23 @@ typedef struct { gpr_slice_buffer *write_slices; uv_buf_t *write_buffers; + grpc_resource_user resource_user; + bool shutting_down; + bool resource_user_shutting_down; + char *peer_string; grpc_pollset *pollset; } grpc_tcp; static void uv_close_callback(uv_handle_t *handle) { gpr_free(handle); } -static void tcp_free(grpc_tcp *tcp) { gpr_free(tcp); } +static void tcp_free(grpc_tcp *tcp) { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_destroy(&exec_ctx, &tcp->resource_user); + gpr_free(tcp); + grpc_exec_ctx_finish(&exec_ctx); +} /*#define GRPC_TCP_REFCOUNT_DEBUG*/ #ifdef GRPC_TCP_REFCOUNT_DEBUG @@ -106,11 +118,14 @@ static void tcp_ref(grpc_tcp *tcp) { gpr_ref(&tcp->refcount); } 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 = handle->data; (void)suggested_size; - tcp->read_slice = gpr_slice_malloc(GRPC_TCP_DEFAULT_READ_SLICE_SIZE); + tcp->read_slice = grpc_resource_user_slice_malloc( + &exec_ctx, &tcp->resource_user, GRPC_TCP_DEFAULT_READ_SLICE_SIZE); buf->base = (char *)GPR_SLICE_START_PTR(tcp->read_slice); buf->len = GPR_SLICE_LENGTH(tcp->read_slice); + grpc_exec_ctx_finish(&exec_ctx); } static void read_callback(uv_stream_t *stream, ssize_t nread, @@ -198,7 +213,8 @@ static void write_callback(uv_write_t *req, int status) { gpr_log(GPR_DEBUG, "write complete on %p: error=%s", tcp, str); } gpr_free(tcp->write_buffers); - gpr_free(req); + grpc_resource_user_free(&exec_ctx, &tcp->resource_user, + sizeof(uv_buf_t) * tcp->write_slices->count); grpc_exec_ctx_sched(&exec_ctx, cb, error, NULL); grpc_exec_ctx_finish(&exec_ctx); } @@ -243,12 +259,15 @@ 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 = gpr_malloc(sizeof(uv_buf_t) * buffer_count); + grpc_resource_user_alloc(exec_ctx, &tcp->resource_user, + sizeof(uv_buf_t) * buffer_count, NULL); for (i = 0; i < buffer_count; i++) { slice = &tcp->write_slices->slices[i]; buffers[i].base = (char *)GPR_SLICE_START_PTR(*slice); buffers[i].len = GPR_SLICE_LENGTH(*slice); } - write_req = gpr_malloc(sizeof(uv_write_t)); + tcp->write_buffers = buffers; + write_req = &tcp->write_req; write_req->data = tcp; TCP_REF(tcp, "write"); // TODO(murgatroid99): figure out what the return value here means @@ -274,13 +293,29 @@ static void uv_add_to_pollset_set(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, (void)pollset; } -static void shutdown_callback(uv_shutdown_t *req, int status) { gpr_free(req); } +static void shutdown_callback(uv_shutdown_t *req, int status) {} + +static void resource_user_shutdown_done(grpc_exec_ctx *exec_ctx, void *arg, + grpc_error *error) { + TCP_UNREF(arg, "resource_user"); +} + +static void uv_resource_user_maybe_shutdown(grpc_exec_ctx *exec_ctx, + grpc_tcp *tcp) { + if (!tcp->resource_user_shutting_down) { + tcp->resource_user_shutting_down = true; + TCP_REF(tcp, "resource_user"); + grpc_resource_user_shutdown( + exec_ctx, &tcp->resource_user, + grpc_closure_create(resource_user_shutdown_done, tcp)); + } +} static void uv_endpoint_shutdown(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) { grpc_tcp *tcp = (grpc_tcp *)ep; if (!tcp->shutting_down) { tcp->shutting_down = true; - uv_shutdown_t *req = gpr_malloc(sizeof(uv_shutdown_t)); + uv_shutdown_t *req = &tcp->shutdown_req; uv_shutdown(req, (uv_stream_t *)tcp->handle, shutdown_callback); } } @@ -289,6 +324,7 @@ 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); + uv_resource_user_maybe_shutdown(exec_ctx, tcp); TCP_UNREF(tcp, "destroy"); } @@ -297,24 +333,30 @@ static char *uv_get_peer(grpc_endpoint *ep) { return gpr_strdup(tcp->peer_string); } +static grpc_resource_user *uv_get_resource_user(grpc_endpoint *ep) { + grpc_tcp *tcp = (grpc_tcp *)ep; + return &tcp->resource_user; +} + static grpc_workqueue *uv_get_workqueue(grpc_endpoint *ep) { return NULL; } -static grpc_endpoint_vtable vtable = {uv_endpoint_read, - uv_endpoint_write, - uv_get_workqueue, - uv_add_to_pollset, - uv_add_to_pollset_set, - uv_endpoint_shutdown, - uv_destroy, - uv_get_peer}; +static grpc_endpoint_vtable vtable = { + uv_endpoint_read, uv_endpoint_write, uv_get_workqueue, + uv_add_to_pollset, uv_add_to_pollset_set, uv_endpoint_shutdown, + uv_destroy, uv_get_resource_user, uv_get_peer}; -grpc_endpoint *grpc_tcp_create(uv_tcp_t *handle, char *peer_string) { +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)); if (grpc_tcp_trace) { gpr_log(GPR_DEBUG, "Creating TCP endpoint %p", tcp); } + /* Disable Nagle's Algorithm */ + uv_tcp_nodelay(handle, 1); + memset(tcp, 0, sizeof(grpc_tcp)); tcp->base.vtable = &vtable; tcp->handle = handle; @@ -322,6 +364,8 @@ grpc_endpoint *grpc_tcp_create(uv_tcp_t *handle, char *peer_string) { gpr_ref_init(&tcp->refcount, 1); tcp->peer_string = gpr_strdup(peer_string); tcp->shutting_down = false; + tcp->resource_user_shutting_down = false; + grpc_resource_user_init(&tcp->resource_user, resource_quota, peer_string); /* Tell network status tracking code about the new endpoint */ grpc_network_status_register_endpoint(&tcp->base); diff --git a/src/core/lib/iomgr/tcp_uv.h b/src/core/lib/iomgr/tcp_uv.h index eed41151ea7..970fcafe4a5 100644 --- a/src/core/lib/iomgr/tcp_uv.h +++ b/src/core/lib/iomgr/tcp_uv.h @@ -52,6 +52,8 @@ extern int grpc_tcp_trace; #define GRPC_TCP_DEFAULT_READ_SLICE_SIZE 8192 -grpc_endpoint *grpc_tcp_create(uv_tcp_t *handle, char *peer_string); +grpc_endpoint *grpc_tcp_create(uv_tcp_t *handle, + grpc_resource_quota *resource_quota, + char *peer_string); #endif /* GRPC_CORE_LIB_IOMGR_TCP_UV_H */ diff --git a/src/core/lib/iomgr/tcp_windows.c b/src/core/lib/iomgr/tcp_windows.c index a5f508a2c35..46f0491d10a 100644 --- a/src/core/lib/iomgr/tcp_windows.c +++ b/src/core/lib/iomgr/tcp_windows.c @@ -109,14 +109,29 @@ typedef struct grpc_tcp { gpr_slice_buffer *write_slices; gpr_slice_buffer *read_slices; + 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; + gpr_atm resource_user_shutdown_count; + char *peer_string; } grpc_tcp; +static void win_unref_closure(grpc_exec_ctx *exec_ctx, void *arg /* grpc_tcp */, + grpc_error *error); + +static void win_maybe_shutdown_resource_user(grpc_exec_ctx *exec_ctx, + grpc_tcp *tcp) { + if (gpr_atm_full_fetch_add(&tcp->resource_user_shutdown_count, 1) == 0) { + grpc_resource_user_shutdown(exec_ctx, &tcp->resource_user, + grpc_closure_create(win_unref_closure, tcp)); + } +} + static void tcp_free(grpc_tcp *tcp) { grpc_winsocket_destroy(tcp->socket); gpr_mu_destroy(&tcp->mu); @@ -155,6 +170,11 @@ static void tcp_unref(grpc_tcp *tcp) { static void tcp_ref(grpc_tcp *tcp) { gpr_ref(&tcp->refcount); } #endif +static void win_unref_closure(grpc_exec_ctx *exec_ctx, void *arg, + grpc_error *error) { + TCP_UNREF(arg, "resource_user"); +} + /* 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 = tcpp; @@ -376,12 +396,14 @@ static void win_shutdown(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) { callback. See the comments in on_read and on_write. */ tcp->shutting_down = 1; grpc_winsocket_shutdown(tcp->socket); + win_maybe_shutdown_resource_user(exec_ctx, tcp); gpr_mu_unlock(&tcp->mu); } static void win_destroy(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) { grpc_network_status_unregister_endpoint(ep); grpc_tcp *tcp = (grpc_tcp *)ep; + win_maybe_shutdown_resource_user(exec_ctx, tcp); TCP_UNREF(tcp, "destroy"); } @@ -392,6 +414,11 @@ static char *win_get_peer(grpc_endpoint *ep) { static grpc_workqueue *win_get_workqueue(grpc_endpoint *ep) { return NULL; } +static grpc_resource_user *win_get_resource_user(grpc_endpoint *ep) { + grpc_tcp *tcp = (grpc_tcp *)ep; + return &tcp->resource_user; +} + static grpc_endpoint_vtable vtable = {win_read, win_write, win_get_workqueue, @@ -399,18 +426,22 @@ static grpc_endpoint_vtable vtable = {win_read, win_add_to_pollset_set, win_shutdown, win_destroy, + win_get_resource_user, win_get_peer}; -grpc_endpoint *grpc_tcp_create(grpc_winsocket *socket, char *peer_string) { +grpc_endpoint *grpc_tcp_create(grpc_winsocket *socket, + grpc_resource_quota *resource_quota, + char *peer_string) { grpc_tcp *tcp = (grpc_tcp *)gpr_malloc(sizeof(grpc_tcp)); memset(tcp, 0, sizeof(grpc_tcp)); tcp->base.vtable = &vtable; tcp->socket = socket; gpr_mu_init(&tcp->mu); - gpr_ref_init(&tcp->refcount, 1); + gpr_ref_init(&tcp->refcount, 2); grpc_closure_init(&tcp->on_read, on_read, tcp); grpc_closure_init(&tcp->on_write, on_write, tcp); tcp->peer_string = gpr_strdup(peer_string); + grpc_resource_user_init(&tcp->resource_user, resource_quota, peer_string); /* Tell network status tracking code about the new endpoint */ grpc_network_status_register_endpoint(&tcp->base); diff --git a/src/core/lib/iomgr/tcp_windows.h b/src/core/lib/iomgr/tcp_windows.h index 86d777235ef..4402de1c385 100644 --- a/src/core/lib/iomgr/tcp_windows.h +++ b/src/core/lib/iomgr/tcp_windows.h @@ -50,7 +50,9 @@ /* Create a tcp endpoint given a winsock handle. * Takes ownership of the handle. */ -grpc_endpoint *grpc_tcp_create(grpc_winsocket *socket, char *peer_string); +grpc_endpoint *grpc_tcp_create(grpc_winsocket *socket, + grpc_resource_quota *resource_quota, + char *peer_string); grpc_error *grpc_tcp_prepare_socket(SOCKET sock); diff --git a/src/core/lib/security/credentials/google_default/google_default_credentials.c b/src/core/lib/security/credentials/google_default/google_default_credentials.c index 312a3d4f90b..cb5ba554b07 100644 --- a/src/core/lib/security/credentials/google_default/google_default_credentials.c +++ b/src/core/lib/security/credentials/google_default/google_default_credentials.c @@ -124,11 +124,14 @@ static int is_stack_running_on_compute_engine(void) { grpc_httpcli_context_init(&context); + grpc_resource_quota *resource_quota = + grpc_resource_quota_create("google_default_credentials"); grpc_httpcli_get( - &exec_ctx, &context, &detector.pollent, &request, + &exec_ctx, &context, &detector.pollent, resource_quota, &request, gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), max_detection_delay), grpc_closure_create(on_compute_engine_detection_http_response, &detector), &detector.response); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); grpc_exec_ctx_flush(&exec_ctx); diff --git a/src/core/lib/security/credentials/jwt/jwt_verifier.c b/src/core/lib/security/credentials/jwt/jwt_verifier.c index 73eb2e32580..43eb6425153 100644 --- a/src/core/lib/security/credentials/jwt/jwt_verifier.c +++ b/src/core/lib/security/credentials/jwt/jwt_verifier.c @@ -657,11 +657,17 @@ static void on_openid_config_retrieved(grpc_exec_ctx *exec_ctx, void *user_data, *(req.host + (req.http.path - jwks_uri)) = '\0'; } + /* 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_create("jwt_verifier"); grpc_httpcli_get( - exec_ctx, &ctx->verifier->http_ctx, &ctx->pollent, &req, + exec_ctx, &ctx->verifier->http_ctx, &ctx->pollent, resource_quota, &req, gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), grpc_jwt_verifier_max_delay), grpc_closure_create(on_keys_retrieved, ctx), &ctx->responses[HTTP_RESPONSE_KEYS]); + grpc_resource_quota_internal_unref(exec_ctx, resource_quota); grpc_json_destroy(json); gpr_free(req.host); return; @@ -764,10 +770,16 @@ static void retrieve_key_and_verify(grpc_exec_ctx *exec_ctx, rsp_idx = HTTP_RESPONSE_OPENID; } + /* 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_create("jwt_verifier"); grpc_httpcli_get( - exec_ctx, &ctx->verifier->http_ctx, &ctx->pollent, &req, + exec_ctx, &ctx->verifier->http_ctx, &ctx->pollent, resource_quota, &req, gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), grpc_jwt_verifier_max_delay), http_cb, &ctx->responses[rsp_idx]); + grpc_resource_quota_internal_unref(exec_ctx, resource_quota); gpr_free(req.host); gpr_free(req.http.path); return; diff --git a/src/core/lib/security/credentials/oauth2/oauth2_credentials.c b/src/core/lib/security/credentials/oauth2/oauth2_credentials.c index c22ea5c468b..d980577c46a 100644 --- a/src/core/lib/security/credentials/oauth2/oauth2_credentials.c +++ b/src/core/lib/security/credentials/oauth2/oauth2_credentials.c @@ -307,9 +307,15 @@ static void compute_engine_fetch_oauth2( request.http.path = GRPC_COMPUTE_ENGINE_METADATA_TOKEN_PATH; request.http.hdr_count = 1; request.http.hdrs = &header; - grpc_httpcli_get(exec_ctx, httpcli_context, pollent, &request, deadline, - grpc_closure_create(response_cb, metadata_req), + /* 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_create("oauth2_credentials"); + grpc_httpcli_get(exec_ctx, httpcli_context, pollent, resource_quota, &request, + deadline, grpc_closure_create(response_cb, metadata_req), &metadata_req->response); + grpc_resource_quota_internal_unref(exec_ctx, resource_quota); } grpc_call_credentials *grpc_google_compute_engine_credentials_create( @@ -357,10 +363,16 @@ static void refresh_token_fetch_oauth2( request.http.hdr_count = 1; request.http.hdrs = &header; request.handshaker = &grpc_httpcli_ssl; - grpc_httpcli_post(exec_ctx, httpcli_context, pollent, &request, body, - strlen(body), deadline, + /* 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_create("oauth2_credentials_refresh"); + grpc_httpcli_post(exec_ctx, httpcli_context, pollent, resource_quota, + &request, body, strlen(body), deadline, grpc_closure_create(response_cb, metadata_req), &metadata_req->response); + grpc_resource_quota_internal_unref(exec_ctx, resource_quota); gpr_free(body); } diff --git a/src/core/lib/security/transport/secure_endpoint.c b/src/core/lib/security/transport/secure_endpoint.c index acb0113ea8c..3924997d31f 100644 --- a/src/core/lib/security/transport/secure_endpoint.c +++ b/src/core/lib/security/transport/secure_endpoint.c @@ -370,6 +370,12 @@ static grpc_workqueue *endpoint_get_workqueue(grpc_endpoint *secure_ep) { return grpc_endpoint_get_workqueue(ep->wrapped_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); +} + static const grpc_endpoint_vtable vtable = {endpoint_read, endpoint_write, endpoint_get_workqueue, @@ -377,6 +383,7 @@ static const grpc_endpoint_vtable vtable = {endpoint_read, endpoint_add_to_pollset_set, endpoint_shutdown, endpoint_destroy, + endpoint_get_resource_user, endpoint_get_peer}; grpc_endpoint *grpc_secure_endpoint_create( diff --git a/src/core/lib/security/transport/security_connector.c b/src/core/lib/security/transport/security_connector.c index 0eca46eb525..ebf72a3abb4 100644 --- a/src/core/lib/security/transport/security_connector.c +++ b/src/core/lib/security/transport/security_connector.c @@ -210,11 +210,11 @@ void grpc_security_connector_unref(grpc_security_connector *sc) { } static void connector_pointer_arg_destroy(void *p) { - GRPC_SECURITY_CONNECTOR_UNREF(p, "connector_pointer_arg"); + GRPC_SECURITY_CONNECTOR_UNREF(p, "connector_pointer_arg_destroy"); } static void *connector_pointer_arg_copy(void *p) { - return GRPC_SECURITY_CONNECTOR_REF(p, "connector_pointer_arg"); + return GRPC_SECURITY_CONNECTOR_REF(p, "connector_pointer_arg_copy"); } static int connector_pointer_cmp(void *a, void *b) { return GPR_ICMP(a, b); } diff --git a/src/core/lib/surface/call.c b/src/core/lib/surface/call.c index 02a5de0857c..6c25952c0a9 100644 --- a/src/core/lib/surface/call.c +++ b/src/core/lib/surface/call.c @@ -1516,8 +1516,10 @@ static grpc_call_error call_start_batch(grpc_exec_ctx *exec_ctx, call, STATUS_FROM_API_OVERRIDE, GRPC_MDSTR_REF(call->send_extra_metadata[1].md->value)); } - set_status_code(call, STATUS_FROM_API_OVERRIDE, - (uint32_t)op->data.send_status_from_server.status); + if (op->data.send_status_from_server.status != GRPC_STATUS_OK) { + set_status_code(call, STATUS_FROM_API_OVERRIDE, + (uint32_t)op->data.send_status_from_server.status); + } if (!prepare_application_metadata( call, (int)op->data.send_status_from_server.trailing_metadata_count, diff --git a/src/core/lib/surface/init.c b/src/core/lib/surface/init.c index 8ca0643ba7e..7903f57a68c 100644 --- a/src/core/lib/surface/init.c +++ b/src/core/lib/surface/init.c @@ -52,6 +52,7 @@ #include "src/core/lib/iomgr/combiner.h" #include "src/core/lib/iomgr/executor.h" #include "src/core/lib/iomgr/iomgr.h" +#include "src/core/lib/iomgr/resource_quota.h" #include "src/core/lib/profiling/timers.h" #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/call.h" @@ -191,6 +192,7 @@ void grpc_init(void) { // Default timeout trace to 1 grpc_cq_event_timeout_trace = 1; grpc_register_tracer("op_failure", &grpc_trace_operation_failures); + grpc_register_tracer("resource_quota", &grpc_resource_quota_trace); #ifndef NDEBUG grpc_register_tracer("pending_tags", &grpc_trace_pending_tags); #endif diff --git a/src/core/lib/tsi/ssl_transport_security.c b/src/core/lib/tsi/ssl_transport_security.c index 749b46e19f4..366dca95077 100644 --- a/src/core/lib/tsi/ssl_transport_security.c +++ b/src/core/lib/tsi/ssl_transport_security.c @@ -31,9 +31,6 @@ * */ -#include "src/core/lib/iomgr/sockaddr.h" - -#include "src/core/lib/iomgr/socket_utils.h" #include "src/core/lib/tsi/ssl_transport_security.h" #include @@ -41,6 +38,15 @@ #include #include +/* TODO(jboeuf): refactor inet_ntop into a portability header. */ +/* Note: for whomever reads this and tries to refactor this, this + can't be in grpc, it has to be in gpr. */ +#ifdef GPR_WINDOWS +#include +#else +#include +#endif + #include #include #include @@ -349,8 +355,8 @@ static tsi_result add_subject_alt_names_properties_to_peer( result = TSI_INTERNAL_ERROR; break; } - const char *name = grpc_inet_ntop(af, subject_alt_name->d.iPAddress->data, - ntop_buf, INET6_ADDRSTRLEN); + const char *name = inet_ntop(af, subject_alt_name->d.iPAddress->data, + ntop_buf, INET6_ADDRSTRLEN); if (name == NULL) { gpr_log(GPR_ERROR, "Could not get IP string from asn1 octet."); result = TSI_INTERNAL_ERROR; diff --git a/src/cpp/client/channel_cc.cc b/src/cpp/client/channel_cc.cc index 43b3875cb3a..847c8c7dc05 100644 --- a/src/cpp/client/channel_cc.cc +++ b/src/cpp/client/channel_cc.cc @@ -106,11 +106,11 @@ grpc_connectivity_state Channel::GetState(bool try_to_connect) { } namespace { -class TagSaver GRPC_FINAL : public CompletionQueueTag { +class TagSaver final : public CompletionQueueTag { public: explicit TagSaver(void* tag) : tag_(tag) {} - ~TagSaver() GRPC_OVERRIDE {} - bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { + ~TagSaver() override {} + bool FinalizeResult(void** tag, bool* status) override { *tag = tag_; delete this; return true; diff --git a/src/cpp/client/client_context.cc b/src/cpp/client/client_context.cc index b6008f47b13..c073741dac0 100644 --- a/src/cpp/client/client_context.cc +++ b/src/cpp/client/client_context.cc @@ -45,12 +45,12 @@ namespace grpc { -class DefaultGlobalClientCallbacks GRPC_FINAL +class DefaultGlobalClientCallbacks final : public ClientContext::GlobalCallbacks { public: - ~DefaultGlobalClientCallbacks() GRPC_OVERRIDE {} - void DefaultConstructor(ClientContext* context) GRPC_OVERRIDE {} - void Destructor(ClientContext* context) GRPC_OVERRIDE {} + ~DefaultGlobalClientCallbacks() override {} + void DefaultConstructor(ClientContext* context) override {} + void Destructor(ClientContext* context) override {} }; static DefaultGlobalClientCallbacks g_default_client_callbacks; @@ -93,7 +93,7 @@ void ClientContext::AddMetadata(const grpc::string& meta_key, void ClientContext::set_call(grpc_call* call, const std::shared_ptr& channel) { - grpc::unique_lock lock(mu_); + std::unique_lock lock(mu_); GPR_ASSERT(call_ == nullptr); call_ = call; channel_ = channel; @@ -119,7 +119,7 @@ void ClientContext::set_compression_algorithm( } void ClientContext::TryCancel() { - grpc::unique_lock lock(mu_); + std::unique_lock lock(mu_); if (call_) { grpc_call_cancel(call_, nullptr); } else { diff --git a/src/cpp/client/cronet_credentials.cc b/src/cpp/client/cronet_credentials.cc index 60cad097db5..8e94cf0ad73 100644 --- a/src/cpp/client/cronet_credentials.cc +++ b/src/cpp/client/cronet_credentials.cc @@ -40,12 +40,12 @@ namespace grpc { -class CronetChannelCredentialsImpl GRPC_FINAL : public ChannelCredentials { +class CronetChannelCredentialsImpl final : public ChannelCredentials { public: CronetChannelCredentialsImpl(void* engine) : engine_(engine) {} std::shared_ptr CreateChannel( - const string& target, const grpc::ChannelArguments& args) GRPC_OVERRIDE { + const string& target, const grpc::ChannelArguments& args) override { grpc_channel_args channel_args; args.SetChannelArgs(&channel_args); return CreateChannelInternal( @@ -53,9 +53,7 @@ class CronetChannelCredentialsImpl GRPC_FINAL : public ChannelCredentials { &channel_args, nullptr)); } - SecureChannelCredentials* AsSecureCredentials() GRPC_OVERRIDE { - return nullptr; - } + SecureChannelCredentials* AsSecureCredentials() override { return nullptr; } private: void* engine_; diff --git a/src/cpp/client/insecure_credentials.cc b/src/cpp/client/insecure_credentials.cc index 13019a71171..116f1dd4ad6 100644 --- a/src/cpp/client/insecure_credentials.cc +++ b/src/cpp/client/insecure_credentials.cc @@ -43,10 +43,10 @@ namespace grpc { namespace { -class InsecureChannelCredentialsImpl GRPC_FINAL : public ChannelCredentials { +class InsecureChannelCredentialsImpl final : public ChannelCredentials { public: std::shared_ptr CreateChannel( - const string& target, const grpc::ChannelArguments& args) GRPC_OVERRIDE { + const string& target, const grpc::ChannelArguments& args) override { grpc_channel_args channel_args; args.SetChannelArgs(&channel_args); return CreateChannelInternal( @@ -54,9 +54,7 @@ class InsecureChannelCredentialsImpl GRPC_FINAL : public ChannelCredentials { grpc_insecure_channel_create(target.c_str(), &channel_args, nullptr)); } - SecureChannelCredentials* AsSecureCredentials() GRPC_OVERRIDE { - return nullptr; - } + SecureChannelCredentials* AsSecureCredentials() override { return nullptr; } }; } // namespace diff --git a/src/cpp/client/secure_credentials.h b/src/cpp/client/secure_credentials.h index ae41ef80078..281db17e983 100644 --- a/src/cpp/client/secure_credentials.h +++ b/src/cpp/client/secure_credentials.h @@ -43,34 +43,34 @@ namespace grpc { -class SecureChannelCredentials GRPC_FINAL : public ChannelCredentials { +class SecureChannelCredentials final : public ChannelCredentials { public: explicit SecureChannelCredentials(grpc_channel_credentials* c_creds); ~SecureChannelCredentials() { grpc_channel_credentials_release(c_creds_); } grpc_channel_credentials* GetRawCreds() { return c_creds_; } std::shared_ptr CreateChannel( - const string& target, const grpc::ChannelArguments& args) GRPC_OVERRIDE; - SecureChannelCredentials* AsSecureCredentials() GRPC_OVERRIDE { return this; } + const string& target, const grpc::ChannelArguments& args) override; + SecureChannelCredentials* AsSecureCredentials() override { return this; } private: grpc_channel_credentials* const c_creds_; }; -class SecureCallCredentials GRPC_FINAL : public CallCredentials { +class SecureCallCredentials final : public CallCredentials { public: explicit SecureCallCredentials(grpc_call_credentials* c_creds); ~SecureCallCredentials() { grpc_call_credentials_release(c_creds_); } grpc_call_credentials* GetRawCreds() { return c_creds_; } - bool ApplyToCall(grpc_call* call) GRPC_OVERRIDE; - SecureCallCredentials* AsSecureCredentials() GRPC_OVERRIDE { return this; } + bool ApplyToCall(grpc_call* call) override; + SecureCallCredentials* AsSecureCredentials() override { return this; } private: grpc_call_credentials* const c_creds_; }; -class MetadataCredentialsPluginWrapper GRPC_FINAL { +class MetadataCredentialsPluginWrapper final { public: static void Destroy(void* wrapper); static void GetMetadata(void* wrapper, grpc_auth_metadata_context context, diff --git a/src/cpp/common/channel_arguments.cc b/src/cpp/common/channel_arguments.cc index f297ae85870..c6cad8eeaee 100644 --- a/src/cpp/common/channel_arguments.cc +++ b/src/cpp/common/channel_arguments.cc @@ -34,6 +34,7 @@ #include +#include #include #include #include "src/core/lib/channel/channel_args.h" @@ -113,6 +114,18 @@ void ChannelArguments::SetUserAgentPrefix( } } +void ChannelArguments::SetResourceQuota( + const grpc::ResourceQuota& resource_quota) { + SetPointerWithVtable(GRPC_ARG_RESOURCE_QUOTA, + resource_quota.c_resource_quota(), + grpc_resource_quota_arg_vtable()); +} + +void ChannelArguments::SetLoadBalancingPolicyName( + const grpc::string& lb_policy_name) { + SetString(GRPC_ARG_LB_POLICY_NAME, lb_policy_name); +} + void ChannelArguments::SetInt(const grpc::string& key, int value) { grpc_arg arg; arg.type = GRPC_ARG_INTEGER; @@ -127,12 +140,18 @@ void ChannelArguments::SetPointer(const grpc::string& key, void* value) { static const grpc_arg_pointer_vtable vtable = { &PointerVtableMembers::Copy, &PointerVtableMembers::Destroy, &PointerVtableMembers::Compare}; + SetPointerWithVtable(key, value, &vtable); +} + +void ChannelArguments::SetPointerWithVtable( + const grpc::string& key, void* value, + const grpc_arg_pointer_vtable* vtable) { grpc_arg arg; arg.type = GRPC_ARG_POINTER; strings_.push_back(key); arg.key = const_cast(strings_.back().c_str()); arg.value.pointer.p = value; - arg.value.pointer.vtable = &vtable; + arg.value.pointer.vtable = vtable; args_.push_back(arg); } diff --git a/src/cpp/common/channel_filter.h b/src/cpp/common/channel_filter.h index ae32e02f699..fc0deff3b39 100644 --- a/src/cpp/common/channel_filter.h +++ b/src/cpp/common/channel_filter.h @@ -268,7 +268,7 @@ namespace internal { // Members of this class correspond to the members of the C // grpc_channel_filter struct. template -class ChannelFilter GRPC_FINAL { +class ChannelFilter final { public: static const size_t channel_data_size = sizeof(ChannelDataType); diff --git a/include/grpc++/impl/thd_cxx11.h b/src/cpp/common/resource_quota_cc.cc similarity index 77% rename from include/grpc++/impl/thd_cxx11.h rename to src/cpp/common/resource_quota_cc.cc index 2055b1d5389..335896ab917 100644 --- a/include/grpc++/impl/thd_cxx11.h +++ b/src/cpp/common/resource_quota_cc.cc @@ -1,6 +1,6 @@ /* * - * Copyright 2015, Google Inc. + * Copyright 2016, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -31,15 +31,21 @@ * */ -#ifndef GRPCXX_IMPL_THD_CXX11_H -#define GRPCXX_IMPL_THD_CXX11_H - -#include +#include +#include namespace grpc { -using std::thread; +ResourceQuota::ResourceQuota() : impl_(grpc_resource_quota_create(nullptr)) {} -} // namespace grpc +ResourceQuota::ResourceQuota(const grpc::string& name) + : impl_(grpc_resource_quota_create(name.c_str())) {} + +ResourceQuota::~ResourceQuota() { grpc_resource_quota_unref(impl_); } -#endif // GRPCXX_IMPL_THD_CXX11_H +ResourceQuota& ResourceQuota::Resize(size_t new_size) { + grpc_resource_quota_resize(impl_, new_size); + return *this; +} + +} // namespace grpc diff --git a/src/cpp/common/secure_auth_context.h b/src/cpp/common/secure_auth_context.h index c9f1dad1319..98f5f09e27c 100644 --- a/src/cpp/common/secure_auth_context.h +++ b/src/cpp/common/secure_auth_context.h @@ -40,30 +40,29 @@ struct grpc_auth_context; namespace grpc { -class SecureAuthContext GRPC_FINAL : public AuthContext { +class SecureAuthContext final : public AuthContext { public: SecureAuthContext(grpc_auth_context* ctx, bool take_ownership); - ~SecureAuthContext() GRPC_OVERRIDE; + ~SecureAuthContext() override; - bool IsPeerAuthenticated() const GRPC_OVERRIDE; + bool IsPeerAuthenticated() const override; - std::vector GetPeerIdentity() const GRPC_OVERRIDE; + std::vector GetPeerIdentity() const override; - grpc::string GetPeerIdentityPropertyName() const GRPC_OVERRIDE; + grpc::string GetPeerIdentityPropertyName() const override; std::vector FindPropertyValues( - const grpc::string& name) const GRPC_OVERRIDE; + const grpc::string& name) const override; - AuthPropertyIterator begin() const GRPC_OVERRIDE; + AuthPropertyIterator begin() const override; - AuthPropertyIterator end() const GRPC_OVERRIDE; + AuthPropertyIterator end() const override; void AddProperty(const grpc::string& key, - const grpc::string_ref& value) GRPC_OVERRIDE; + const grpc::string_ref& value) override; - virtual bool SetPeerIdentityPropertyName(const grpc::string& name) - GRPC_OVERRIDE; + virtual bool SetPeerIdentityPropertyName(const grpc::string& name) override; private: grpc_auth_context* ctx_; diff --git a/src/cpp/ext/proto_server_reflection.h b/src/cpp/ext/proto_server_reflection.h index f66f3c2c9ae..ca0ba97d88f 100644 --- a/src/cpp/ext/proto_server_reflection.h +++ b/src/cpp/ext/proto_server_reflection.h @@ -31,35 +31,18 @@ * */ -/* - - If the generated header `grpc++/ext/reflection.grpc.pb.h` needs to be - installed, target `grpc++_reflection` in `build.yaml` should use the - filegroup `grpc++_reflection_proto`, and GRPC_NO_GENERATED_CODE should not - be defined. - - If the server reflection library needs to generate `reflection.grpc.pb.h` - from `reflection.proto` at compile time, the generated header - `grpc++/ext/reflection.grpc.pb.h` should not be installed. In this case, - target `grpc++_reflection` should depend on `grpc++_reflection_codegen`, and - GRPC_NO_GENERATED_CODE should be defined. -*/ - #ifndef GRPC_INTERNAL_CPP_EXT_PROTO_SERVER_REFLECTION_H #define GRPC_INTERNAL_CPP_EXT_PROTO_SERVER_REFLECTION_H #include #include -// GRPC_NO_GENERATED_CODE indicates generated pb files should not be used -#ifdef GRPC_NO_GENERATED_CODE -#include "src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.h" -#else -#include -#endif // GRPC_NO_GENERATED_CODE #include +#include "src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.h" namespace grpc { -class ProtoServerReflection GRPC_FINAL +class ProtoServerReflection final : public reflection::v1alpha::ServerReflection::Service { public: ProtoServerReflection(); @@ -73,7 +56,7 @@ class ProtoServerReflection GRPC_FINAL ServerContext* context, ServerReaderWriter* stream) - GRPC_OVERRIDE; + override; private: Status ListService(ServerContext* context, diff --git a/src/cpp/ext/reflection.grpc.pb.cc b/src/cpp/ext/reflection.grpc.pb.cc deleted file mode 100644 index 8139c8ea162..00000000000 --- a/src/cpp/ext/reflection.grpc.pb.cc +++ /dev/null @@ -1,97 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - - -// Generated by tools/codegen/extensions/gen_reflection_proto.sh -// If you make any local change, they will be lost. -// source: reflection.proto - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -namespace grpc { -namespace reflection { -namespace v1alpha { - -static const char* ServerReflection_method_names[] = { - "/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo", -}; - -std::unique_ptr< ServerReflection::Stub> ServerReflection::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) { - std::unique_ptr< ServerReflection::Stub> stub(new ServerReflection::Stub(channel)); - return stub; -} - -ServerReflection::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) - : channel_(channel), rpcmethod_ServerReflectionInfo_(ServerReflection_method_names[0], ::grpc::RpcMethod::BIDI_STREAMING, channel) - {} - -::grpc::ClientReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>* ServerReflection::Stub::ServerReflectionInfoRaw(::grpc::ClientContext* context) { - return new ::grpc::ClientReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>(channel_.get(), rpcmethod_ServerReflectionInfo_, context); -} - -::grpc::ClientAsyncReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>* ServerReflection::Stub::AsyncServerReflectionInfoRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { - return new ::grpc::ClientAsyncReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>(channel_.get(), cq, rpcmethod_ServerReflectionInfo_, context, tag); -} - -ServerReflection::Service::Service() { - (void)ServerReflection_method_names; - AddMethod(new ::grpc::RpcServiceMethod( - ServerReflection_method_names[0], - ::grpc::RpcMethod::BIDI_STREAMING, - new ::grpc::BidiStreamingHandler< ServerReflection::Service, ::grpc::reflection::v1alpha::ServerReflectionRequest, ::grpc::reflection::v1alpha::ServerReflectionResponse>( - std::mem_fn(&ServerReflection::Service::ServerReflectionInfo), this))); -} - -ServerReflection::Service::~Service() { -} - -::grpc::Status ServerReflection::Service::ServerReflectionInfo(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< ::grpc::reflection::v1alpha::ServerReflectionResponse, ::grpc::reflection::v1alpha::ServerReflectionRequest>* stream) { - (void) context; - (void) stream; - return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); -} - - -} // namespace grpc -} // namespace reflection -} // namespace v1alpha - diff --git a/src/cpp/ext/reflection.pb.cc b/src/cpp/ext/reflection.pb.cc deleted file mode 100644 index d75503b3ce1..00000000000 --- a/src/cpp/ext/reflection.pb.cc +++ /dev/null @@ -1,4045 +0,0 @@ -/* - * - * Copyright 2015, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - - -// Generated by tools/codegen/extensions/gen_reflection_proto.sh -// source: reflection.proto - -#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -// @@protoc_insertion_point(includes) - -namespace grpc { -namespace reflection { -namespace v1alpha { - -namespace { - -const ::google::protobuf::Descriptor* ServerReflectionRequest_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - ServerReflectionRequest_reflection_ = NULL; -struct ServerReflectionRequestOneofInstance { - ::google::protobuf::internal::ArenaStringPtr file_by_filename_; - ::google::protobuf::internal::ArenaStringPtr file_containing_symbol_; - const ::grpc::reflection::v1alpha::ExtensionRequest* file_containing_extension_; - ::google::protobuf::internal::ArenaStringPtr all_extension_numbers_of_type_; - ::google::protobuf::internal::ArenaStringPtr list_services_; -}* ServerReflectionRequest_default_oneof_instance_ = NULL; -const ::google::protobuf::Descriptor* ExtensionRequest_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - ExtensionRequest_reflection_ = NULL; -const ::google::protobuf::Descriptor* ServerReflectionResponse_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - ServerReflectionResponse_reflection_ = NULL; -struct ServerReflectionResponseOneofInstance { - const ::grpc::reflection::v1alpha::FileDescriptorResponse* file_descriptor_response_; - const ::grpc::reflection::v1alpha::ExtensionNumberResponse* all_extension_numbers_response_; - const ::grpc::reflection::v1alpha::ListServiceResponse* list_services_response_; - const ::grpc::reflection::v1alpha::ErrorResponse* error_response_; -}* ServerReflectionResponse_default_oneof_instance_ = NULL; -const ::google::protobuf::Descriptor* FileDescriptorResponse_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - FileDescriptorResponse_reflection_ = NULL; -const ::google::protobuf::Descriptor* ExtensionNumberResponse_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - ExtensionNumberResponse_reflection_ = NULL; -const ::google::protobuf::Descriptor* ListServiceResponse_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - ListServiceResponse_reflection_ = NULL; -const ::google::protobuf::Descriptor* ServiceResponse_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - ServiceResponse_reflection_ = NULL; -const ::google::protobuf::Descriptor* ErrorResponse_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - ErrorResponse_reflection_ = NULL; - -} // namespace - - -void protobuf_AssignDesc_reflection_2eproto() GOOGLE_ATTRIBUTE_COLD; -void protobuf_AssignDesc_reflection_2eproto() { - protobuf_AddDesc_reflection_2eproto(); - const ::google::protobuf::FileDescriptor* file = - ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( - "reflection.proto"); - GOOGLE_CHECK(file != NULL); - ServerReflectionRequest_descriptor_ = file->message_type(0); - static const int ServerReflectionRequest_offsets_[7] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerReflectionRequest, host_), - PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(ServerReflectionRequest_default_oneof_instance_, file_by_filename_), - PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(ServerReflectionRequest_default_oneof_instance_, file_containing_symbol_), - PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(ServerReflectionRequest_default_oneof_instance_, file_containing_extension_), - PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(ServerReflectionRequest_default_oneof_instance_, all_extension_numbers_of_type_), - PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(ServerReflectionRequest_default_oneof_instance_, list_services_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerReflectionRequest, message_request_), - }; - ServerReflectionRequest_reflection_ = - ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( - ServerReflectionRequest_descriptor_, - ServerReflectionRequest::internal_default_instance(), - ServerReflectionRequest_offsets_, - -1, - -1, - -1, - ServerReflectionRequest_default_oneof_instance_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerReflectionRequest, _oneof_case_[0]), - sizeof(ServerReflectionRequest), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerReflectionRequest, _internal_metadata_)); - ExtensionRequest_descriptor_ = file->message_type(1); - static const int ExtensionRequest_offsets_[2] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ExtensionRequest, containing_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ExtensionRequest, extension_number_), - }; - ExtensionRequest_reflection_ = - ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( - ExtensionRequest_descriptor_, - ExtensionRequest::internal_default_instance(), - ExtensionRequest_offsets_, - -1, - -1, - -1, - sizeof(ExtensionRequest), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ExtensionRequest, _internal_metadata_)); - ServerReflectionResponse_descriptor_ = file->message_type(2); - static const int ServerReflectionResponse_offsets_[7] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerReflectionResponse, valid_host_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerReflectionResponse, original_request_), - PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(ServerReflectionResponse_default_oneof_instance_, file_descriptor_response_), - PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(ServerReflectionResponse_default_oneof_instance_, all_extension_numbers_response_), - PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(ServerReflectionResponse_default_oneof_instance_, list_services_response_), - PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(ServerReflectionResponse_default_oneof_instance_, error_response_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerReflectionResponse, message_response_), - }; - ServerReflectionResponse_reflection_ = - ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( - ServerReflectionResponse_descriptor_, - ServerReflectionResponse::internal_default_instance(), - ServerReflectionResponse_offsets_, - -1, - -1, - -1, - ServerReflectionResponse_default_oneof_instance_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerReflectionResponse, _oneof_case_[0]), - sizeof(ServerReflectionResponse), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerReflectionResponse, _internal_metadata_)); - FileDescriptorResponse_descriptor_ = file->message_type(3); - static const int FileDescriptorResponse_offsets_[1] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorResponse, file_descriptor_proto_), - }; - FileDescriptorResponse_reflection_ = - ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( - FileDescriptorResponse_descriptor_, - FileDescriptorResponse::internal_default_instance(), - FileDescriptorResponse_offsets_, - -1, - -1, - -1, - sizeof(FileDescriptorResponse), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorResponse, _internal_metadata_)); - ExtensionNumberResponse_descriptor_ = file->message_type(4); - static const int ExtensionNumberResponse_offsets_[2] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ExtensionNumberResponse, base_type_name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ExtensionNumberResponse, extension_number_), - }; - ExtensionNumberResponse_reflection_ = - ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( - ExtensionNumberResponse_descriptor_, - ExtensionNumberResponse::internal_default_instance(), - ExtensionNumberResponse_offsets_, - -1, - -1, - -1, - sizeof(ExtensionNumberResponse), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ExtensionNumberResponse, _internal_metadata_)); - ListServiceResponse_descriptor_ = file->message_type(5); - static const int ListServiceResponse_offsets_[1] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ListServiceResponse, service_), - }; - ListServiceResponse_reflection_ = - ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( - ListServiceResponse_descriptor_, - ListServiceResponse::internal_default_instance(), - ListServiceResponse_offsets_, - -1, - -1, - -1, - sizeof(ListServiceResponse), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ListServiceResponse, _internal_metadata_)); - ServiceResponse_descriptor_ = file->message_type(6); - static const int ServiceResponse_offsets_[1] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceResponse, name_), - }; - ServiceResponse_reflection_ = - ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( - ServiceResponse_descriptor_, - ServiceResponse::internal_default_instance(), - ServiceResponse_offsets_, - -1, - -1, - -1, - sizeof(ServiceResponse), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceResponse, _internal_metadata_)); - ErrorResponse_descriptor_ = file->message_type(7); - static const int ErrorResponse_offsets_[2] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ErrorResponse, error_code_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ErrorResponse, error_message_), - }; - ErrorResponse_reflection_ = - ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( - ErrorResponse_descriptor_, - ErrorResponse::internal_default_instance(), - ErrorResponse_offsets_, - -1, - -1, - -1, - sizeof(ErrorResponse), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ErrorResponse, _internal_metadata_)); -} - -namespace { - -GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); -void protobuf_AssignDescriptorsOnce() { - ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, - &protobuf_AssignDesc_reflection_2eproto); -} - -void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD; -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - ServerReflectionRequest_descriptor_, ServerReflectionRequest::internal_default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - ExtensionRequest_descriptor_, ExtensionRequest::internal_default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - ServerReflectionResponse_descriptor_, ServerReflectionResponse::internal_default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - FileDescriptorResponse_descriptor_, FileDescriptorResponse::internal_default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - ExtensionNumberResponse_descriptor_, ExtensionNumberResponse::internal_default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - ListServiceResponse_descriptor_, ListServiceResponse::internal_default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - ServiceResponse_descriptor_, ServiceResponse::internal_default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - ErrorResponse_descriptor_, ErrorResponse::internal_default_instance()); -} - -} // namespace - -void protobuf_ShutdownFile_reflection_2eproto() { - ServerReflectionRequest_default_instance_.Shutdown(); - delete ServerReflectionRequest_default_oneof_instance_; - delete ServerReflectionRequest_reflection_; - ExtensionRequest_default_instance_.Shutdown(); - delete ExtensionRequest_reflection_; - ServerReflectionResponse_default_instance_.Shutdown(); - delete ServerReflectionResponse_default_oneof_instance_; - delete ServerReflectionResponse_reflection_; - FileDescriptorResponse_default_instance_.Shutdown(); - delete FileDescriptorResponse_reflection_; - ExtensionNumberResponse_default_instance_.Shutdown(); - delete ExtensionNumberResponse_reflection_; - ListServiceResponse_default_instance_.Shutdown(); - delete ListServiceResponse_reflection_; - ServiceResponse_default_instance_.Shutdown(); - delete ServiceResponse_reflection_; - ErrorResponse_default_instance_.Shutdown(); - delete ErrorResponse_reflection_; -} - -void protobuf_InitDefaults_reflection_2eproto_impl() { - GOOGLE_PROTOBUF_VERIFY_VERSION; - - ::google::protobuf::internal::GetEmptyString(); - ServerReflectionRequest_default_instance_.DefaultConstruct(); - ServerReflectionRequest_default_oneof_instance_ = new ServerReflectionRequestOneofInstance(); - ::google::protobuf::internal::GetEmptyString(); - ExtensionRequest_default_instance_.DefaultConstruct(); - ::google::protobuf::internal::GetEmptyString(); - ServerReflectionResponse_default_instance_.DefaultConstruct(); - ServerReflectionResponse_default_oneof_instance_ = new ServerReflectionResponseOneofInstance(); - ::google::protobuf::internal::GetEmptyString(); - FileDescriptorResponse_default_instance_.DefaultConstruct(); - ::google::protobuf::internal::GetEmptyString(); - ExtensionNumberResponse_default_instance_.DefaultConstruct(); - ListServiceResponse_default_instance_.DefaultConstruct(); - ::google::protobuf::internal::GetEmptyString(); - ServiceResponse_default_instance_.DefaultConstruct(); - ::google::protobuf::internal::GetEmptyString(); - ErrorResponse_default_instance_.DefaultConstruct(); - ServerReflectionRequest_default_instance_.get_mutable()->InitAsDefaultInstance(); - ExtensionRequest_default_instance_.get_mutable()->InitAsDefaultInstance(); - ServerReflectionResponse_default_instance_.get_mutable()->InitAsDefaultInstance(); - FileDescriptorResponse_default_instance_.get_mutable()->InitAsDefaultInstance(); - ExtensionNumberResponse_default_instance_.get_mutable()->InitAsDefaultInstance(); - ListServiceResponse_default_instance_.get_mutable()->InitAsDefaultInstance(); - ServiceResponse_default_instance_.get_mutable()->InitAsDefaultInstance(); - ErrorResponse_default_instance_.get_mutable()->InitAsDefaultInstance(); -} - -GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_reflection_2eproto_once_); -void protobuf_InitDefaults_reflection_2eproto() { - ::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_reflection_2eproto_once_, - &protobuf_InitDefaults_reflection_2eproto_impl); -} -void protobuf_AddDesc_reflection_2eproto_impl() { - GOOGLE_PROTOBUF_VERIFY_VERSION; - - protobuf_InitDefaults_reflection_2eproto(); - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - "\n\020reflection.proto\022\027grpc.reflection.v1al" - "pha\"\212\002\n\027ServerReflectionRequest\022\014\n\004host\030" - "\001 \001(\t\022\032\n\020file_by_filename\030\003 \001(\tH\000\022 \n\026fil" - "e_containing_symbol\030\004 \001(\tH\000\022N\n\031file_cont" - "aining_extension\030\005 \001(\0132).grpc.reflection" - ".v1alpha.ExtensionRequestH\000\022\'\n\035all_exten" - "sion_numbers_of_type\030\006 \001(\tH\000\022\027\n\rlist_ser" - "vices\030\007 \001(\tH\000B\021\n\017message_request\"E\n\020Exte" - "nsionRequest\022\027\n\017containing_type\030\001 \001(\t\022\030\n" - "\020extension_number\030\002 \001(\005\"\321\003\n\030ServerReflec" - "tionResponse\022\022\n\nvalid_host\030\001 \001(\t\022J\n\020orig" - "inal_request\030\002 \001(\01320.grpc.reflection.v1a" - "lpha.ServerReflectionRequest\022S\n\030file_des" - "criptor_response\030\004 \001(\0132/.grpc.reflection" - ".v1alpha.FileDescriptorResponseH\000\022Z\n\036all" - "_extension_numbers_response\030\005 \001(\01320.grpc" - ".reflection.v1alpha.ExtensionNumberRespo" - "nseH\000\022N\n\026list_services_response\030\006 \001(\0132,." - "grpc.reflection.v1alpha.ListServiceRespo" - "nseH\000\022@\n\016error_response\030\007 \001(\0132&.grpc.ref" - "lection.v1alpha.ErrorResponseH\000B\022\n\020messa" - "ge_response\"7\n\026FileDescriptorResponse\022\035\n" - "\025file_descriptor_proto\030\001 \003(\014\"K\n\027Extensio" - "nNumberResponse\022\026\n\016base_type_name\030\001 \001(\t\022" - "\030\n\020extension_number\030\002 \003(\005\"P\n\023ListService" - "Response\0229\n\007service\030\001 \003(\0132(.grpc.reflect" - "ion.v1alpha.ServiceResponse\"\037\n\017ServiceRe" - "sponse\022\014\n\004name\030\001 \001(\t\":\n\rErrorResponse\022\022\n" - "\nerror_code\030\001 \001(\005\022\025\n\rerror_message\030\002 \001(\t" - "2\223\001\n\020ServerReflection\022\177\n\024ServerReflectio" - "nInfo\0220.grpc.reflection.v1alpha.ServerRe" - "flectionRequest\0321.grpc.reflection.v1alph" - "a.ServerReflectionResponse(\0010\001b\006proto3", 1318); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "reflection.proto", &protobuf_RegisterTypes); - ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_reflection_2eproto); -} - -GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_reflection_2eproto_once_); -void protobuf_AddDesc_reflection_2eproto() { - ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_reflection_2eproto_once_, - &protobuf_AddDesc_reflection_2eproto_impl); -} -// Force AddDescriptors() to be called at static initialization time. -struct StaticDescriptorInitializer_reflection_2eproto { - StaticDescriptorInitializer_reflection_2eproto() { - protobuf_AddDesc_reflection_2eproto(); - } -} static_descriptor_initializer_reflection_2eproto_; - -namespace { - -static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN; -static void MergeFromFail(int line) { - ::google::protobuf::internal::MergeFromFail(__FILE__, line); -} - -} // namespace - - -// =================================================================== - -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int ServerReflectionRequest::kHostFieldNumber; -const int ServerReflectionRequest::kFileByFilenameFieldNumber; -const int ServerReflectionRequest::kFileContainingSymbolFieldNumber; -const int ServerReflectionRequest::kFileContainingExtensionFieldNumber; -const int ServerReflectionRequest::kAllExtensionNumbersOfTypeFieldNumber; -const int ServerReflectionRequest::kListServicesFieldNumber; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 - -ServerReflectionRequest::ServerReflectionRequest() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (this != internal_default_instance()) protobuf_InitDefaults_reflection_2eproto(); - SharedCtor(); - // @@protoc_insertion_point(constructor:grpc.reflection.v1alpha.ServerReflectionRequest) -} - -void ServerReflectionRequest::InitAsDefaultInstance() { - ServerReflectionRequest_default_oneof_instance_->file_by_filename_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ServerReflectionRequest_default_oneof_instance_->file_containing_symbol_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ServerReflectionRequest_default_oneof_instance_->file_containing_extension_ = const_cast< ::grpc::reflection::v1alpha::ExtensionRequest*>( - ::grpc::reflection::v1alpha::ExtensionRequest::internal_default_instance()); - ServerReflectionRequest_default_oneof_instance_->all_extension_numbers_of_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ServerReflectionRequest_default_oneof_instance_->list_services_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -ServerReflectionRequest::ServerReflectionRequest(const ServerReflectionRequest& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { - SharedCtor(); - UnsafeMergeFrom(from); - // @@protoc_insertion_point(copy_constructor:grpc.reflection.v1alpha.ServerReflectionRequest) -} - -void ServerReflectionRequest::SharedCtor() { - host_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_message_request(); - _cached_size_ = 0; -} - -ServerReflectionRequest::~ServerReflectionRequest() { - // @@protoc_insertion_point(destructor:grpc.reflection.v1alpha.ServerReflectionRequest) - SharedDtor(); -} - -void ServerReflectionRequest::SharedDtor() { - host_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (has_message_request()) { - clear_message_request(); - } -} - -void ServerReflectionRequest::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* ServerReflectionRequest::descriptor() { - protobuf_AssignDescriptorsOnce(); - return ServerReflectionRequest_descriptor_; -} - -const ServerReflectionRequest& ServerReflectionRequest::default_instance() { - protobuf_InitDefaults_reflection_2eproto(); - return *internal_default_instance(); -} - -::google::protobuf::internal::ExplicitlyConstructed ServerReflectionRequest_default_instance_; - -ServerReflectionRequest* ServerReflectionRequest::New(::google::protobuf::Arena* arena) const { - ServerReflectionRequest* n = new ServerReflectionRequest; - if (arena != NULL) { - arena->Own(n); - } - return n; -} - -void ServerReflectionRequest::clear_message_request() { -// @@protoc_insertion_point(one_of_clear_start:grpc.reflection.v1alpha.ServerReflectionRequest) - switch (message_request_case()) { - case kFileByFilename: { - message_request_.file_by_filename_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - break; - } - case kFileContainingSymbol: { - message_request_.file_containing_symbol_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - break; - } - case kFileContainingExtension: { - delete message_request_.file_containing_extension_; - break; - } - case kAllExtensionNumbersOfType: { - message_request_.all_extension_numbers_of_type_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - break; - } - case kListServices: { - message_request_.list_services_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - break; - } - case MESSAGE_REQUEST_NOT_SET: { - break; - } - } - _oneof_case_[0] = MESSAGE_REQUEST_NOT_SET; -} - - -void ServerReflectionRequest::Clear() { -// @@protoc_insertion_point(message_clear_start:grpc.reflection.v1alpha.ServerReflectionRequest) - host_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_message_request(); -} - -bool ServerReflectionRequest::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:grpc.reflection.v1alpha.ServerReflectionRequest) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string host = 1; - case 1: { - if (tag == 10) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_host())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->host().data(), this->host().length(), - ::google::protobuf::internal::WireFormatLite::PARSE, - "grpc.reflection.v1alpha.ServerReflectionRequest.host")); - } else { - goto handle_unusual; - } - if (input->ExpectTag(26)) goto parse_file_by_filename; - break; - } - - // optional string file_by_filename = 3; - case 3: { - if (tag == 26) { - parse_file_by_filename: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_file_by_filename())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->file_by_filename().data(), this->file_by_filename().length(), - ::google::protobuf::internal::WireFormatLite::PARSE, - "grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename")); - } else { - goto handle_unusual; - } - goto after_list_services; - break; - } - - // optional string file_containing_symbol = 4; - case 4: { - if (tag == 34) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_file_containing_symbol())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->file_containing_symbol().data(), this->file_containing_symbol().length(), - ::google::protobuf::internal::WireFormatLite::PARSE, - "grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol")); - } else { - goto handle_unusual; - } - goto after_list_services; - break; - } - - // optional .grpc.reflection.v1alpha.ExtensionRequest file_containing_extension = 5; - case 5: { - if (tag == 42) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_file_containing_extension())); - } else { - goto handle_unusual; - } - goto after_list_services; - break; - } - - // optional string all_extension_numbers_of_type = 6; - case 6: { - if (tag == 50) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_all_extension_numbers_of_type())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->all_extension_numbers_of_type().data(), this->all_extension_numbers_of_type().length(), - ::google::protobuf::internal::WireFormatLite::PARSE, - "grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type")); - } else { - goto handle_unusual; - } - if (input->ExpectTag(58)) goto parse_list_services; - break; - } - - // optional string list_services = 7; - case 7: { - if (tag == 58) { - parse_list_services: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_list_services())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->list_services().data(), this->list_services().length(), - ::google::protobuf::internal::WireFormatLite::PARSE, - "grpc.reflection.v1alpha.ServerReflectionRequest.list_services")); - } else { - goto handle_unusual; - } - after_list_services: - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:grpc.reflection.v1alpha.ServerReflectionRequest) - return true; -failure: - // @@protoc_insertion_point(parse_failure:grpc.reflection.v1alpha.ServerReflectionRequest) - return false; -#undef DO_ -} - -void ServerReflectionRequest::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:grpc.reflection.v1alpha.ServerReflectionRequest) - // optional string host = 1; - if (this->host().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->host().data(), this->host().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ServerReflectionRequest.host"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 1, this->host(), output); - } - - // optional string file_by_filename = 3; - if (has_file_by_filename()) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->file_by_filename().data(), this->file_by_filename().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 3, this->file_by_filename(), output); - } - - // optional string file_containing_symbol = 4; - if (has_file_containing_symbol()) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->file_containing_symbol().data(), this->file_containing_symbol().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 4, this->file_containing_symbol(), output); - } - - // optional .grpc.reflection.v1alpha.ExtensionRequest file_containing_extension = 5; - if (has_file_containing_extension()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 5, *message_request_.file_containing_extension_, output); - } - - // optional string all_extension_numbers_of_type = 6; - if (has_all_extension_numbers_of_type()) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->all_extension_numbers_of_type().data(), this->all_extension_numbers_of_type().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 6, this->all_extension_numbers_of_type(), output); - } - - // optional string list_services = 7; - if (has_list_services()) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->list_services().data(), this->list_services().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ServerReflectionRequest.list_services"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 7, this->list_services(), output); - } - - // @@protoc_insertion_point(serialize_end:grpc.reflection.v1alpha.ServerReflectionRequest) -} - -::google::protobuf::uint8* ServerReflectionRequest::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused - // @@protoc_insertion_point(serialize_to_array_start:grpc.reflection.v1alpha.ServerReflectionRequest) - // optional string host = 1; - if (this->host().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->host().data(), this->host().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ServerReflectionRequest.host"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->host(), target); - } - - // optional string file_by_filename = 3; - if (has_file_by_filename()) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->file_by_filename().data(), this->file_by_filename().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 3, this->file_by_filename(), target); - } - - // optional string file_containing_symbol = 4; - if (has_file_containing_symbol()) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->file_containing_symbol().data(), this->file_containing_symbol().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 4, this->file_containing_symbol(), target); - } - - // optional .grpc.reflection.v1alpha.ExtensionRequest file_containing_extension = 5; - if (has_file_containing_extension()) { - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageNoVirtualToArray( - 5, *message_request_.file_containing_extension_, false, target); - } - - // optional string all_extension_numbers_of_type = 6; - if (has_all_extension_numbers_of_type()) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->all_extension_numbers_of_type().data(), this->all_extension_numbers_of_type().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 6, this->all_extension_numbers_of_type(), target); - } - - // optional string list_services = 7; - if (has_list_services()) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->list_services().data(), this->list_services().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ServerReflectionRequest.list_services"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 7, this->list_services(), target); - } - - // @@protoc_insertion_point(serialize_to_array_end:grpc.reflection.v1alpha.ServerReflectionRequest) - return target; -} - -size_t ServerReflectionRequest::ByteSizeLong() const { -// @@protoc_insertion_point(message_byte_size_start:grpc.reflection.v1alpha.ServerReflectionRequest) - size_t total_size = 0; - - // optional string host = 1; - if (this->host().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->host()); - } - - switch (message_request_case()) { - // optional string file_by_filename = 3; - case kFileByFilename: { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->file_by_filename()); - break; - } - // optional string file_containing_symbol = 4; - case kFileContainingSymbol: { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->file_containing_symbol()); - break; - } - // optional .grpc.reflection.v1alpha.ExtensionRequest file_containing_extension = 5; - case kFileContainingExtension: { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - *message_request_.file_containing_extension_); - break; - } - // optional string all_extension_numbers_of_type = 6; - case kAllExtensionNumbersOfType: { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->all_extension_numbers_of_type()); - break; - } - // optional string list_services = 7; - case kListServices: { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->list_services()); - break; - } - case MESSAGE_REQUEST_NOT_SET: { - break; - } - } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void ServerReflectionRequest::MergeFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_merge_from_start:grpc.reflection.v1alpha.ServerReflectionRequest) - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - const ServerReflectionRequest* source = - ::google::protobuf::internal::DynamicCastToGenerated( - &from); - if (source == NULL) { - // @@protoc_insertion_point(generalized_merge_from_cast_fail:grpc.reflection.v1alpha.ServerReflectionRequest) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - // @@protoc_insertion_point(generalized_merge_from_cast_success:grpc.reflection.v1alpha.ServerReflectionRequest) - UnsafeMergeFrom(*source); - } -} - -void ServerReflectionRequest::MergeFrom(const ServerReflectionRequest& from) { -// @@protoc_insertion_point(class_specific_merge_from_start:grpc.reflection.v1alpha.ServerReflectionRequest) - if (GOOGLE_PREDICT_TRUE(&from != this)) { - UnsafeMergeFrom(from); - } else { - MergeFromFail(__LINE__); - } -} - -void ServerReflectionRequest::UnsafeMergeFrom(const ServerReflectionRequest& from) { - GOOGLE_DCHECK(&from != this); - switch (from.message_request_case()) { - case kFileByFilename: { - set_file_by_filename(from.file_by_filename()); - break; - } - case kFileContainingSymbol: { - set_file_containing_symbol(from.file_containing_symbol()); - break; - } - case kFileContainingExtension: { - mutable_file_containing_extension()->::grpc::reflection::v1alpha::ExtensionRequest::MergeFrom(from.file_containing_extension()); - break; - } - case kAllExtensionNumbersOfType: { - set_all_extension_numbers_of_type(from.all_extension_numbers_of_type()); - break; - } - case kListServices: { - set_list_services(from.list_services()); - break; - } - case MESSAGE_REQUEST_NOT_SET: { - break; - } - } - if (from.host().size() > 0) { - - host_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.host_); - } -} - -void ServerReflectionRequest::CopyFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_copy_from_start:grpc.reflection.v1alpha.ServerReflectionRequest) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void ServerReflectionRequest::CopyFrom(const ServerReflectionRequest& from) { -// @@protoc_insertion_point(class_specific_copy_from_start:grpc.reflection.v1alpha.ServerReflectionRequest) - if (&from == this) return; - Clear(); - UnsafeMergeFrom(from); -} - -bool ServerReflectionRequest::IsInitialized() const { - - return true; -} - -void ServerReflectionRequest::Swap(ServerReflectionRequest* other) { - if (other == this) return; - InternalSwap(other); -} -void ServerReflectionRequest::InternalSwap(ServerReflectionRequest* other) { - host_.Swap(&other->host_); - std::swap(message_request_, other->message_request_); - std::swap(_oneof_case_[0], other->_oneof_case_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); - std::swap(_cached_size_, other->_cached_size_); -} - -::google::protobuf::Metadata ServerReflectionRequest::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = ServerReflectionRequest_descriptor_; - metadata.reflection = ServerReflectionRequest_reflection_; - return metadata; -} - -#if PROTOBUF_INLINE_NOT_IN_HEADERS -// ServerReflectionRequest - -// optional string host = 1; -void ServerReflectionRequest::clear_host() { - host_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -const ::std::string& ServerReflectionRequest::host() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionRequest.host) - return host_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -void ServerReflectionRequest::set_host(const ::std::string& value) { - - host_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.host) -} -void ServerReflectionRequest::set_host(const char* value) { - - host_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ServerReflectionRequest.host) -} -void ServerReflectionRequest::set_host(const char* value, size_t size) { - - host_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ServerReflectionRequest.host) -} -::std::string* ServerReflectionRequest::mutable_host() { - - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionRequest.host) - return host_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -::std::string* ServerReflectionRequest::release_host() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionRequest.host) - - return host_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -void ServerReflectionRequest::set_allocated_host(::std::string* host) { - if (host != NULL) { - - } else { - - } - host_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), host); - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionRequest.host) -} - -// optional string file_by_filename = 3; -bool ServerReflectionRequest::has_file_by_filename() const { - return message_request_case() == kFileByFilename; -} -void ServerReflectionRequest::set_has_file_by_filename() { - _oneof_case_[0] = kFileByFilename; -} -void ServerReflectionRequest::clear_file_by_filename() { - if (has_file_by_filename()) { - message_request_.file_by_filename_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_message_request(); - } -} -const ::std::string& ServerReflectionRequest::file_by_filename() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename) - if (has_file_by_filename()) { - return message_request_.file_by_filename_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - return *&::google::protobuf::internal::GetEmptyStringAlreadyInited(); -} -void ServerReflectionRequest::set_file_by_filename(const ::std::string& value) { - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename) - if (!has_file_by_filename()) { - clear_message_request(); - set_has_file_by_filename(); - message_request_.file_by_filename_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.file_by_filename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename) -} -void ServerReflectionRequest::set_file_by_filename(const char* value) { - if (!has_file_by_filename()) { - clear_message_request(); - set_has_file_by_filename(); - message_request_.file_by_filename_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.file_by_filename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename) -} -void ServerReflectionRequest::set_file_by_filename(const char* value, size_t size) { - if (!has_file_by_filename()) { - clear_message_request(); - set_has_file_by_filename(); - message_request_.file_by_filename_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.file_by_filename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( - reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename) -} -::std::string* ServerReflectionRequest::mutable_file_by_filename() { - if (!has_file_by_filename()) { - clear_message_request(); - set_has_file_by_filename(); - message_request_.file_by_filename_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename) - return message_request_.file_by_filename_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -::std::string* ServerReflectionRequest::release_file_by_filename() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename) - if (has_file_by_filename()) { - clear_has_message_request(); - return message_request_.file_by_filename_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } else { - return NULL; - } -} -void ServerReflectionRequest::set_allocated_file_by_filename(::std::string* file_by_filename) { - if (!has_file_by_filename()) { - message_request_.file_by_filename_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - clear_message_request(); - if (file_by_filename != NULL) { - set_has_file_by_filename(); - message_request_.file_by_filename_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - file_by_filename); - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionRequest.file_by_filename) -} - -// optional string file_containing_symbol = 4; -bool ServerReflectionRequest::has_file_containing_symbol() const { - return message_request_case() == kFileContainingSymbol; -} -void ServerReflectionRequest::set_has_file_containing_symbol() { - _oneof_case_[0] = kFileContainingSymbol; -} -void ServerReflectionRequest::clear_file_containing_symbol() { - if (has_file_containing_symbol()) { - message_request_.file_containing_symbol_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_message_request(); - } -} -const ::std::string& ServerReflectionRequest::file_containing_symbol() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol) - if (has_file_containing_symbol()) { - return message_request_.file_containing_symbol_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - return *&::google::protobuf::internal::GetEmptyStringAlreadyInited(); -} -void ServerReflectionRequest::set_file_containing_symbol(const ::std::string& value) { - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol) - if (!has_file_containing_symbol()) { - clear_message_request(); - set_has_file_containing_symbol(); - message_request_.file_containing_symbol_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.file_containing_symbol_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol) -} -void ServerReflectionRequest::set_file_containing_symbol(const char* value) { - if (!has_file_containing_symbol()) { - clear_message_request(); - set_has_file_containing_symbol(); - message_request_.file_containing_symbol_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.file_containing_symbol_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol) -} -void ServerReflectionRequest::set_file_containing_symbol(const char* value, size_t size) { - if (!has_file_containing_symbol()) { - clear_message_request(); - set_has_file_containing_symbol(); - message_request_.file_containing_symbol_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.file_containing_symbol_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( - reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol) -} -::std::string* ServerReflectionRequest::mutable_file_containing_symbol() { - if (!has_file_containing_symbol()) { - clear_message_request(); - set_has_file_containing_symbol(); - message_request_.file_containing_symbol_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol) - return message_request_.file_containing_symbol_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -::std::string* ServerReflectionRequest::release_file_containing_symbol() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol) - if (has_file_containing_symbol()) { - clear_has_message_request(); - return message_request_.file_containing_symbol_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } else { - return NULL; - } -} -void ServerReflectionRequest::set_allocated_file_containing_symbol(::std::string* file_containing_symbol) { - if (!has_file_containing_symbol()) { - message_request_.file_containing_symbol_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - clear_message_request(); - if (file_containing_symbol != NULL) { - set_has_file_containing_symbol(); - message_request_.file_containing_symbol_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - file_containing_symbol); - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_symbol) -} - -// optional .grpc.reflection.v1alpha.ExtensionRequest file_containing_extension = 5; -bool ServerReflectionRequest::has_file_containing_extension() const { - return message_request_case() == kFileContainingExtension; -} -void ServerReflectionRequest::set_has_file_containing_extension() { - _oneof_case_[0] = kFileContainingExtension; -} -void ServerReflectionRequest::clear_file_containing_extension() { - if (has_file_containing_extension()) { - delete message_request_.file_containing_extension_; - clear_has_message_request(); - } -} - const ::grpc::reflection::v1alpha::ExtensionRequest& ServerReflectionRequest::file_containing_extension() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_extension) - return has_file_containing_extension() - ? *message_request_.file_containing_extension_ - : ::grpc::reflection::v1alpha::ExtensionRequest::default_instance(); -} -::grpc::reflection::v1alpha::ExtensionRequest* ServerReflectionRequest::mutable_file_containing_extension() { - if (!has_file_containing_extension()) { - clear_message_request(); - set_has_file_containing_extension(); - message_request_.file_containing_extension_ = new ::grpc::reflection::v1alpha::ExtensionRequest; - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_extension) - return message_request_.file_containing_extension_; -} -::grpc::reflection::v1alpha::ExtensionRequest* ServerReflectionRequest::release_file_containing_extension() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_extension) - if (has_file_containing_extension()) { - clear_has_message_request(); - ::grpc::reflection::v1alpha::ExtensionRequest* temp = message_request_.file_containing_extension_; - message_request_.file_containing_extension_ = NULL; - return temp; - } else { - return NULL; - } -} -void ServerReflectionRequest::set_allocated_file_containing_extension(::grpc::reflection::v1alpha::ExtensionRequest* file_containing_extension) { - clear_message_request(); - if (file_containing_extension) { - set_has_file_containing_extension(); - message_request_.file_containing_extension_ = file_containing_extension; - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_extension) -} - -// optional string all_extension_numbers_of_type = 6; -bool ServerReflectionRequest::has_all_extension_numbers_of_type() const { - return message_request_case() == kAllExtensionNumbersOfType; -} -void ServerReflectionRequest::set_has_all_extension_numbers_of_type() { - _oneof_case_[0] = kAllExtensionNumbersOfType; -} -void ServerReflectionRequest::clear_all_extension_numbers_of_type() { - if (has_all_extension_numbers_of_type()) { - message_request_.all_extension_numbers_of_type_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_message_request(); - } -} -const ::std::string& ServerReflectionRequest::all_extension_numbers_of_type() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type) - if (has_all_extension_numbers_of_type()) { - return message_request_.all_extension_numbers_of_type_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - return *&::google::protobuf::internal::GetEmptyStringAlreadyInited(); -} -void ServerReflectionRequest::set_all_extension_numbers_of_type(const ::std::string& value) { - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type) - if (!has_all_extension_numbers_of_type()) { - clear_message_request(); - set_has_all_extension_numbers_of_type(); - message_request_.all_extension_numbers_of_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.all_extension_numbers_of_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type) -} -void ServerReflectionRequest::set_all_extension_numbers_of_type(const char* value) { - if (!has_all_extension_numbers_of_type()) { - clear_message_request(); - set_has_all_extension_numbers_of_type(); - message_request_.all_extension_numbers_of_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.all_extension_numbers_of_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type) -} -void ServerReflectionRequest::set_all_extension_numbers_of_type(const char* value, size_t size) { - if (!has_all_extension_numbers_of_type()) { - clear_message_request(); - set_has_all_extension_numbers_of_type(); - message_request_.all_extension_numbers_of_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.all_extension_numbers_of_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( - reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type) -} -::std::string* ServerReflectionRequest::mutable_all_extension_numbers_of_type() { - if (!has_all_extension_numbers_of_type()) { - clear_message_request(); - set_has_all_extension_numbers_of_type(); - message_request_.all_extension_numbers_of_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type) - return message_request_.all_extension_numbers_of_type_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -::std::string* ServerReflectionRequest::release_all_extension_numbers_of_type() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type) - if (has_all_extension_numbers_of_type()) { - clear_has_message_request(); - return message_request_.all_extension_numbers_of_type_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } else { - return NULL; - } -} -void ServerReflectionRequest::set_allocated_all_extension_numbers_of_type(::std::string* all_extension_numbers_of_type) { - if (!has_all_extension_numbers_of_type()) { - message_request_.all_extension_numbers_of_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - clear_message_request(); - if (all_extension_numbers_of_type != NULL) { - set_has_all_extension_numbers_of_type(); - message_request_.all_extension_numbers_of_type_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - all_extension_numbers_of_type); - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionRequest.all_extension_numbers_of_type) -} - -// optional string list_services = 7; -bool ServerReflectionRequest::has_list_services() const { - return message_request_case() == kListServices; -} -void ServerReflectionRequest::set_has_list_services() { - _oneof_case_[0] = kListServices; -} -void ServerReflectionRequest::clear_list_services() { - if (has_list_services()) { - message_request_.list_services_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_message_request(); - } -} -const ::std::string& ServerReflectionRequest::list_services() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionRequest.list_services) - if (has_list_services()) { - return message_request_.list_services_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - return *&::google::protobuf::internal::GetEmptyStringAlreadyInited(); -} -void ServerReflectionRequest::set_list_services(const ::std::string& value) { - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.list_services) - if (!has_list_services()) { - clear_message_request(); - set_has_list_services(); - message_request_.list_services_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.list_services_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionRequest.list_services) -} -void ServerReflectionRequest::set_list_services(const char* value) { - if (!has_list_services()) { - clear_message_request(); - set_has_list_services(); - message_request_.list_services_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.list_services_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ServerReflectionRequest.list_services) -} -void ServerReflectionRequest::set_list_services(const char* value, size_t size) { - if (!has_list_services()) { - clear_message_request(); - set_has_list_services(); - message_request_.list_services_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - message_request_.list_services_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( - reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ServerReflectionRequest.list_services) -} -::std::string* ServerReflectionRequest::mutable_list_services() { - if (!has_list_services()) { - clear_message_request(); - set_has_list_services(); - message_request_.list_services_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionRequest.list_services) - return message_request_.list_services_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -::std::string* ServerReflectionRequest::release_list_services() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionRequest.list_services) - if (has_list_services()) { - clear_has_message_request(); - return message_request_.list_services_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } else { - return NULL; - } -} -void ServerReflectionRequest::set_allocated_list_services(::std::string* list_services) { - if (!has_list_services()) { - message_request_.list_services_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - } - clear_message_request(); - if (list_services != NULL) { - set_has_list_services(); - message_request_.list_services_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - list_services); - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionRequest.list_services) -} - -bool ServerReflectionRequest::has_message_request() const { - return message_request_case() != MESSAGE_REQUEST_NOT_SET; -} -void ServerReflectionRequest::clear_has_message_request() { - _oneof_case_[0] = MESSAGE_REQUEST_NOT_SET; -} -ServerReflectionRequest::MessageRequestCase ServerReflectionRequest::message_request_case() const { - return ServerReflectionRequest::MessageRequestCase(_oneof_case_[0]); -} -inline const ServerReflectionRequest* ServerReflectionRequest::internal_default_instance() { - return &ServerReflectionRequest_default_instance_.get(); -} -#endif // PROTOBUF_INLINE_NOT_IN_HEADERS - -// =================================================================== - -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int ExtensionRequest::kContainingTypeFieldNumber; -const int ExtensionRequest::kExtensionNumberFieldNumber; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 - -ExtensionRequest::ExtensionRequest() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (this != internal_default_instance()) protobuf_InitDefaults_reflection_2eproto(); - SharedCtor(); - // @@protoc_insertion_point(constructor:grpc.reflection.v1alpha.ExtensionRequest) -} - -void ExtensionRequest::InitAsDefaultInstance() { -} - -ExtensionRequest::ExtensionRequest(const ExtensionRequest& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { - SharedCtor(); - UnsafeMergeFrom(from); - // @@protoc_insertion_point(copy_constructor:grpc.reflection.v1alpha.ExtensionRequest) -} - -void ExtensionRequest::SharedCtor() { - containing_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - extension_number_ = 0; - _cached_size_ = 0; -} - -ExtensionRequest::~ExtensionRequest() { - // @@protoc_insertion_point(destructor:grpc.reflection.v1alpha.ExtensionRequest) - SharedDtor(); -} - -void ExtensionRequest::SharedDtor() { - containing_type_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -void ExtensionRequest::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* ExtensionRequest::descriptor() { - protobuf_AssignDescriptorsOnce(); - return ExtensionRequest_descriptor_; -} - -const ExtensionRequest& ExtensionRequest::default_instance() { - protobuf_InitDefaults_reflection_2eproto(); - return *internal_default_instance(); -} - -::google::protobuf::internal::ExplicitlyConstructed ExtensionRequest_default_instance_; - -ExtensionRequest* ExtensionRequest::New(::google::protobuf::Arena* arena) const { - ExtensionRequest* n = new ExtensionRequest; - if (arena != NULL) { - arena->Own(n); - } - return n; -} - -void ExtensionRequest::Clear() { -// @@protoc_insertion_point(message_clear_start:grpc.reflection.v1alpha.ExtensionRequest) - containing_type_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - extension_number_ = 0; -} - -bool ExtensionRequest::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:grpc.reflection.v1alpha.ExtensionRequest) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string containing_type = 1; - case 1: { - if (tag == 10) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_containing_type())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->containing_type().data(), this->containing_type().length(), - ::google::protobuf::internal::WireFormatLite::PARSE, - "grpc.reflection.v1alpha.ExtensionRequest.containing_type")); - } else { - goto handle_unusual; - } - if (input->ExpectTag(16)) goto parse_extension_number; - break; - } - - // optional int32 extension_number = 2; - case 2: { - if (tag == 16) { - parse_extension_number: - - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, &extension_number_))); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:grpc.reflection.v1alpha.ExtensionRequest) - return true; -failure: - // @@protoc_insertion_point(parse_failure:grpc.reflection.v1alpha.ExtensionRequest) - return false; -#undef DO_ -} - -void ExtensionRequest::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:grpc.reflection.v1alpha.ExtensionRequest) - // optional string containing_type = 1; - if (this->containing_type().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->containing_type().data(), this->containing_type().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ExtensionRequest.containing_type"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 1, this->containing_type(), output); - } - - // optional int32 extension_number = 2; - if (this->extension_number() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->extension_number(), output); - } - - // @@protoc_insertion_point(serialize_end:grpc.reflection.v1alpha.ExtensionRequest) -} - -::google::protobuf::uint8* ExtensionRequest::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused - // @@protoc_insertion_point(serialize_to_array_start:grpc.reflection.v1alpha.ExtensionRequest) - // optional string containing_type = 1; - if (this->containing_type().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->containing_type().data(), this->containing_type().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ExtensionRequest.containing_type"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->containing_type(), target); - } - - // optional int32 extension_number = 2; - if (this->extension_number() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->extension_number(), target); - } - - // @@protoc_insertion_point(serialize_to_array_end:grpc.reflection.v1alpha.ExtensionRequest) - return target; -} - -size_t ExtensionRequest::ByteSizeLong() const { -// @@protoc_insertion_point(message_byte_size_start:grpc.reflection.v1alpha.ExtensionRequest) - size_t total_size = 0; - - // optional string containing_type = 1; - if (this->containing_type().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->containing_type()); - } - - // optional int32 extension_number = 2; - if (this->extension_number() != 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - this->extension_number()); - } - - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void ExtensionRequest::MergeFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_merge_from_start:grpc.reflection.v1alpha.ExtensionRequest) - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - const ExtensionRequest* source = - ::google::protobuf::internal::DynamicCastToGenerated( - &from); - if (source == NULL) { - // @@protoc_insertion_point(generalized_merge_from_cast_fail:grpc.reflection.v1alpha.ExtensionRequest) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - // @@protoc_insertion_point(generalized_merge_from_cast_success:grpc.reflection.v1alpha.ExtensionRequest) - UnsafeMergeFrom(*source); - } -} - -void ExtensionRequest::MergeFrom(const ExtensionRequest& from) { -// @@protoc_insertion_point(class_specific_merge_from_start:grpc.reflection.v1alpha.ExtensionRequest) - if (GOOGLE_PREDICT_TRUE(&from != this)) { - UnsafeMergeFrom(from); - } else { - MergeFromFail(__LINE__); - } -} - -void ExtensionRequest::UnsafeMergeFrom(const ExtensionRequest& from) { - GOOGLE_DCHECK(&from != this); - if (from.containing_type().size() > 0) { - - containing_type_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.containing_type_); - } - if (from.extension_number() != 0) { - set_extension_number(from.extension_number()); - } -} - -void ExtensionRequest::CopyFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_copy_from_start:grpc.reflection.v1alpha.ExtensionRequest) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void ExtensionRequest::CopyFrom(const ExtensionRequest& from) { -// @@protoc_insertion_point(class_specific_copy_from_start:grpc.reflection.v1alpha.ExtensionRequest) - if (&from == this) return; - Clear(); - UnsafeMergeFrom(from); -} - -bool ExtensionRequest::IsInitialized() const { - - return true; -} - -void ExtensionRequest::Swap(ExtensionRequest* other) { - if (other == this) return; - InternalSwap(other); -} -void ExtensionRequest::InternalSwap(ExtensionRequest* other) { - containing_type_.Swap(&other->containing_type_); - std::swap(extension_number_, other->extension_number_); - _internal_metadata_.Swap(&other->_internal_metadata_); - std::swap(_cached_size_, other->_cached_size_); -} - -::google::protobuf::Metadata ExtensionRequest::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = ExtensionRequest_descriptor_; - metadata.reflection = ExtensionRequest_reflection_; - return metadata; -} - -#if PROTOBUF_INLINE_NOT_IN_HEADERS -// ExtensionRequest - -// optional string containing_type = 1; -void ExtensionRequest::clear_containing_type() { - containing_type_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -const ::std::string& ExtensionRequest::containing_type() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ExtensionRequest.containing_type) - return containing_type_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -void ExtensionRequest::set_containing_type(const ::std::string& value) { - - containing_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ExtensionRequest.containing_type) -} -void ExtensionRequest::set_containing_type(const char* value) { - - containing_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ExtensionRequest.containing_type) -} -void ExtensionRequest::set_containing_type(const char* value, size_t size) { - - containing_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ExtensionRequest.containing_type) -} -::std::string* ExtensionRequest::mutable_containing_type() { - - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ExtensionRequest.containing_type) - return containing_type_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -::std::string* ExtensionRequest::release_containing_type() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ExtensionRequest.containing_type) - - return containing_type_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -void ExtensionRequest::set_allocated_containing_type(::std::string* containing_type) { - if (containing_type != NULL) { - - } else { - - } - containing_type_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), containing_type); - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ExtensionRequest.containing_type) -} - -// optional int32 extension_number = 2; -void ExtensionRequest::clear_extension_number() { - extension_number_ = 0; -} -::google::protobuf::int32 ExtensionRequest::extension_number() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ExtensionRequest.extension_number) - return extension_number_; -} -void ExtensionRequest::set_extension_number(::google::protobuf::int32 value) { - - extension_number_ = value; - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ExtensionRequest.extension_number) -} - -inline const ExtensionRequest* ExtensionRequest::internal_default_instance() { - return &ExtensionRequest_default_instance_.get(); -} -#endif // PROTOBUF_INLINE_NOT_IN_HEADERS - -// =================================================================== - -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int ServerReflectionResponse::kValidHostFieldNumber; -const int ServerReflectionResponse::kOriginalRequestFieldNumber; -const int ServerReflectionResponse::kFileDescriptorResponseFieldNumber; -const int ServerReflectionResponse::kAllExtensionNumbersResponseFieldNumber; -const int ServerReflectionResponse::kListServicesResponseFieldNumber; -const int ServerReflectionResponse::kErrorResponseFieldNumber; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 - -ServerReflectionResponse::ServerReflectionResponse() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (this != internal_default_instance()) protobuf_InitDefaults_reflection_2eproto(); - SharedCtor(); - // @@protoc_insertion_point(constructor:grpc.reflection.v1alpha.ServerReflectionResponse) -} - -void ServerReflectionResponse::InitAsDefaultInstance() { - original_request_ = const_cast< ::grpc::reflection::v1alpha::ServerReflectionRequest*>( - ::grpc::reflection::v1alpha::ServerReflectionRequest::internal_default_instance()); - ServerReflectionResponse_default_oneof_instance_->file_descriptor_response_ = const_cast< ::grpc::reflection::v1alpha::FileDescriptorResponse*>( - ::grpc::reflection::v1alpha::FileDescriptorResponse::internal_default_instance()); - ServerReflectionResponse_default_oneof_instance_->all_extension_numbers_response_ = const_cast< ::grpc::reflection::v1alpha::ExtensionNumberResponse*>( - ::grpc::reflection::v1alpha::ExtensionNumberResponse::internal_default_instance()); - ServerReflectionResponse_default_oneof_instance_->list_services_response_ = const_cast< ::grpc::reflection::v1alpha::ListServiceResponse*>( - ::grpc::reflection::v1alpha::ListServiceResponse::internal_default_instance()); - ServerReflectionResponse_default_oneof_instance_->error_response_ = const_cast< ::grpc::reflection::v1alpha::ErrorResponse*>( - ::grpc::reflection::v1alpha::ErrorResponse::internal_default_instance()); -} - -ServerReflectionResponse::ServerReflectionResponse(const ServerReflectionResponse& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { - SharedCtor(); - UnsafeMergeFrom(from); - // @@protoc_insertion_point(copy_constructor:grpc.reflection.v1alpha.ServerReflectionResponse) -} - -void ServerReflectionResponse::SharedCtor() { - valid_host_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - original_request_ = NULL; - clear_has_message_response(); - _cached_size_ = 0; -} - -ServerReflectionResponse::~ServerReflectionResponse() { - // @@protoc_insertion_point(destructor:grpc.reflection.v1alpha.ServerReflectionResponse) - SharedDtor(); -} - -void ServerReflectionResponse::SharedDtor() { - valid_host_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (has_message_response()) { - clear_message_response(); - } - if (this != &ServerReflectionResponse_default_instance_.get()) { - delete original_request_; - } -} - -void ServerReflectionResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* ServerReflectionResponse::descriptor() { - protobuf_AssignDescriptorsOnce(); - return ServerReflectionResponse_descriptor_; -} - -const ServerReflectionResponse& ServerReflectionResponse::default_instance() { - protobuf_InitDefaults_reflection_2eproto(); - return *internal_default_instance(); -} - -::google::protobuf::internal::ExplicitlyConstructed ServerReflectionResponse_default_instance_; - -ServerReflectionResponse* ServerReflectionResponse::New(::google::protobuf::Arena* arena) const { - ServerReflectionResponse* n = new ServerReflectionResponse; - if (arena != NULL) { - arena->Own(n); - } - return n; -} - -void ServerReflectionResponse::clear_message_response() { -// @@protoc_insertion_point(one_of_clear_start:grpc.reflection.v1alpha.ServerReflectionResponse) - switch (message_response_case()) { - case kFileDescriptorResponse: { - delete message_response_.file_descriptor_response_; - break; - } - case kAllExtensionNumbersResponse: { - delete message_response_.all_extension_numbers_response_; - break; - } - case kListServicesResponse: { - delete message_response_.list_services_response_; - break; - } - case kErrorResponse: { - delete message_response_.error_response_; - break; - } - case MESSAGE_RESPONSE_NOT_SET: { - break; - } - } - _oneof_case_[0] = MESSAGE_RESPONSE_NOT_SET; -} - - -void ServerReflectionResponse::Clear() { -// @@protoc_insertion_point(message_clear_start:grpc.reflection.v1alpha.ServerReflectionResponse) - valid_host_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (GetArenaNoVirtual() == NULL && original_request_ != NULL) delete original_request_; - original_request_ = NULL; - clear_message_response(); -} - -bool ServerReflectionResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:grpc.reflection.v1alpha.ServerReflectionResponse) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string valid_host = 1; - case 1: { - if (tag == 10) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_valid_host())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->valid_host().data(), this->valid_host().length(), - ::google::protobuf::internal::WireFormatLite::PARSE, - "grpc.reflection.v1alpha.ServerReflectionResponse.valid_host")); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_original_request; - break; - } - - // optional .grpc.reflection.v1alpha.ServerReflectionRequest original_request = 2; - case 2: { - if (tag == 18) { - parse_original_request: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_original_request())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(34)) goto parse_file_descriptor_response; - break; - } - - // optional .grpc.reflection.v1alpha.FileDescriptorResponse file_descriptor_response = 4; - case 4: { - if (tag == 34) { - parse_file_descriptor_response: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_file_descriptor_response())); - } else { - goto handle_unusual; - } - goto after_error_response; - break; - } - - // optional .grpc.reflection.v1alpha.ExtensionNumberResponse all_extension_numbers_response = 5; - case 5: { - if (tag == 42) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_all_extension_numbers_response())); - } else { - goto handle_unusual; - } - goto after_error_response; - break; - } - - // optional .grpc.reflection.v1alpha.ListServiceResponse list_services_response = 6; - case 6: { - if (tag == 50) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_list_services_response())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(58)) goto parse_error_response; - break; - } - - // optional .grpc.reflection.v1alpha.ErrorResponse error_response = 7; - case 7: { - if (tag == 58) { - parse_error_response: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_error_response())); - } else { - goto handle_unusual; - } - after_error_response: - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:grpc.reflection.v1alpha.ServerReflectionResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:grpc.reflection.v1alpha.ServerReflectionResponse) - return false; -#undef DO_ -} - -void ServerReflectionResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:grpc.reflection.v1alpha.ServerReflectionResponse) - // optional string valid_host = 1; - if (this->valid_host().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->valid_host().data(), this->valid_host().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ServerReflectionResponse.valid_host"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 1, this->valid_host(), output); - } - - // optional .grpc.reflection.v1alpha.ServerReflectionRequest original_request = 2; - if (this->has_original_request()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 2, *this->original_request_, output); - } - - // optional .grpc.reflection.v1alpha.FileDescriptorResponse file_descriptor_response = 4; - if (has_file_descriptor_response()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 4, *message_response_.file_descriptor_response_, output); - } - - // optional .grpc.reflection.v1alpha.ExtensionNumberResponse all_extension_numbers_response = 5; - if (has_all_extension_numbers_response()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 5, *message_response_.all_extension_numbers_response_, output); - } - - // optional .grpc.reflection.v1alpha.ListServiceResponse list_services_response = 6; - if (has_list_services_response()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 6, *message_response_.list_services_response_, output); - } - - // optional .grpc.reflection.v1alpha.ErrorResponse error_response = 7; - if (has_error_response()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 7, *message_response_.error_response_, output); - } - - // @@protoc_insertion_point(serialize_end:grpc.reflection.v1alpha.ServerReflectionResponse) -} - -::google::protobuf::uint8* ServerReflectionResponse::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused - // @@protoc_insertion_point(serialize_to_array_start:grpc.reflection.v1alpha.ServerReflectionResponse) - // optional string valid_host = 1; - if (this->valid_host().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->valid_host().data(), this->valid_host().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ServerReflectionResponse.valid_host"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->valid_host(), target); - } - - // optional .grpc.reflection.v1alpha.ServerReflectionRequest original_request = 2; - if (this->has_original_request()) { - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageNoVirtualToArray( - 2, *this->original_request_, false, target); - } - - // optional .grpc.reflection.v1alpha.FileDescriptorResponse file_descriptor_response = 4; - if (has_file_descriptor_response()) { - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageNoVirtualToArray( - 4, *message_response_.file_descriptor_response_, false, target); - } - - // optional .grpc.reflection.v1alpha.ExtensionNumberResponse all_extension_numbers_response = 5; - if (has_all_extension_numbers_response()) { - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageNoVirtualToArray( - 5, *message_response_.all_extension_numbers_response_, false, target); - } - - // optional .grpc.reflection.v1alpha.ListServiceResponse list_services_response = 6; - if (has_list_services_response()) { - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageNoVirtualToArray( - 6, *message_response_.list_services_response_, false, target); - } - - // optional .grpc.reflection.v1alpha.ErrorResponse error_response = 7; - if (has_error_response()) { - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageNoVirtualToArray( - 7, *message_response_.error_response_, false, target); - } - - // @@protoc_insertion_point(serialize_to_array_end:grpc.reflection.v1alpha.ServerReflectionResponse) - return target; -} - -size_t ServerReflectionResponse::ByteSizeLong() const { -// @@protoc_insertion_point(message_byte_size_start:grpc.reflection.v1alpha.ServerReflectionResponse) - size_t total_size = 0; - - // optional string valid_host = 1; - if (this->valid_host().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->valid_host()); - } - - // optional .grpc.reflection.v1alpha.ServerReflectionRequest original_request = 2; - if (this->has_original_request()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - *this->original_request_); - } - - switch (message_response_case()) { - // optional .grpc.reflection.v1alpha.FileDescriptorResponse file_descriptor_response = 4; - case kFileDescriptorResponse: { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - *message_response_.file_descriptor_response_); - break; - } - // optional .grpc.reflection.v1alpha.ExtensionNumberResponse all_extension_numbers_response = 5; - case kAllExtensionNumbersResponse: { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - *message_response_.all_extension_numbers_response_); - break; - } - // optional .grpc.reflection.v1alpha.ListServiceResponse list_services_response = 6; - case kListServicesResponse: { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - *message_response_.list_services_response_); - break; - } - // optional .grpc.reflection.v1alpha.ErrorResponse error_response = 7; - case kErrorResponse: { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - *message_response_.error_response_); - break; - } - case MESSAGE_RESPONSE_NOT_SET: { - break; - } - } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void ServerReflectionResponse::MergeFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_merge_from_start:grpc.reflection.v1alpha.ServerReflectionResponse) - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - const ServerReflectionResponse* source = - ::google::protobuf::internal::DynamicCastToGenerated( - &from); - if (source == NULL) { - // @@protoc_insertion_point(generalized_merge_from_cast_fail:grpc.reflection.v1alpha.ServerReflectionResponse) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - // @@protoc_insertion_point(generalized_merge_from_cast_success:grpc.reflection.v1alpha.ServerReflectionResponse) - UnsafeMergeFrom(*source); - } -} - -void ServerReflectionResponse::MergeFrom(const ServerReflectionResponse& from) { -// @@protoc_insertion_point(class_specific_merge_from_start:grpc.reflection.v1alpha.ServerReflectionResponse) - if (GOOGLE_PREDICT_TRUE(&from != this)) { - UnsafeMergeFrom(from); - } else { - MergeFromFail(__LINE__); - } -} - -void ServerReflectionResponse::UnsafeMergeFrom(const ServerReflectionResponse& from) { - GOOGLE_DCHECK(&from != this); - switch (from.message_response_case()) { - case kFileDescriptorResponse: { - mutable_file_descriptor_response()->::grpc::reflection::v1alpha::FileDescriptorResponse::MergeFrom(from.file_descriptor_response()); - break; - } - case kAllExtensionNumbersResponse: { - mutable_all_extension_numbers_response()->::grpc::reflection::v1alpha::ExtensionNumberResponse::MergeFrom(from.all_extension_numbers_response()); - break; - } - case kListServicesResponse: { - mutable_list_services_response()->::grpc::reflection::v1alpha::ListServiceResponse::MergeFrom(from.list_services_response()); - break; - } - case kErrorResponse: { - mutable_error_response()->::grpc::reflection::v1alpha::ErrorResponse::MergeFrom(from.error_response()); - break; - } - case MESSAGE_RESPONSE_NOT_SET: { - break; - } - } - if (from.valid_host().size() > 0) { - - valid_host_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.valid_host_); - } - if (from.has_original_request()) { - mutable_original_request()->::grpc::reflection::v1alpha::ServerReflectionRequest::MergeFrom(from.original_request()); - } -} - -void ServerReflectionResponse::CopyFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_copy_from_start:grpc.reflection.v1alpha.ServerReflectionResponse) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void ServerReflectionResponse::CopyFrom(const ServerReflectionResponse& from) { -// @@protoc_insertion_point(class_specific_copy_from_start:grpc.reflection.v1alpha.ServerReflectionResponse) - if (&from == this) return; - Clear(); - UnsafeMergeFrom(from); -} - -bool ServerReflectionResponse::IsInitialized() const { - - return true; -} - -void ServerReflectionResponse::Swap(ServerReflectionResponse* other) { - if (other == this) return; - InternalSwap(other); -} -void ServerReflectionResponse::InternalSwap(ServerReflectionResponse* other) { - valid_host_.Swap(&other->valid_host_); - std::swap(original_request_, other->original_request_); - std::swap(message_response_, other->message_response_); - std::swap(_oneof_case_[0], other->_oneof_case_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); - std::swap(_cached_size_, other->_cached_size_); -} - -::google::protobuf::Metadata ServerReflectionResponse::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = ServerReflectionResponse_descriptor_; - metadata.reflection = ServerReflectionResponse_reflection_; - return metadata; -} - -#if PROTOBUF_INLINE_NOT_IN_HEADERS -// ServerReflectionResponse - -// optional string valid_host = 1; -void ServerReflectionResponse::clear_valid_host() { - valid_host_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -const ::std::string& ServerReflectionResponse::valid_host() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionResponse.valid_host) - return valid_host_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -void ServerReflectionResponse::set_valid_host(const ::std::string& value) { - - valid_host_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServerReflectionResponse.valid_host) -} -void ServerReflectionResponse::set_valid_host(const char* value) { - - valid_host_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ServerReflectionResponse.valid_host) -} -void ServerReflectionResponse::set_valid_host(const char* value, size_t size) { - - valid_host_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ServerReflectionResponse.valid_host) -} -::std::string* ServerReflectionResponse::mutable_valid_host() { - - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionResponse.valid_host) - return valid_host_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -::std::string* ServerReflectionResponse::release_valid_host() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionResponse.valid_host) - - return valid_host_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -void ServerReflectionResponse::set_allocated_valid_host(::std::string* valid_host) { - if (valid_host != NULL) { - - } else { - - } - valid_host_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), valid_host); - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionResponse.valid_host) -} - -// optional .grpc.reflection.v1alpha.ServerReflectionRequest original_request = 2; -bool ServerReflectionResponse::has_original_request() const { - return this != internal_default_instance() && original_request_ != NULL; -} -void ServerReflectionResponse::clear_original_request() { - if (GetArenaNoVirtual() == NULL && original_request_ != NULL) delete original_request_; - original_request_ = NULL; -} -const ::grpc::reflection::v1alpha::ServerReflectionRequest& ServerReflectionResponse::original_request() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionResponse.original_request) - return original_request_ != NULL ? *original_request_ - : *::grpc::reflection::v1alpha::ServerReflectionRequest::internal_default_instance(); -} -::grpc::reflection::v1alpha::ServerReflectionRequest* ServerReflectionResponse::mutable_original_request() { - - if (original_request_ == NULL) { - original_request_ = new ::grpc::reflection::v1alpha::ServerReflectionRequest; - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionResponse.original_request) - return original_request_; -} -::grpc::reflection::v1alpha::ServerReflectionRequest* ServerReflectionResponse::release_original_request() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionResponse.original_request) - - ::grpc::reflection::v1alpha::ServerReflectionRequest* temp = original_request_; - original_request_ = NULL; - return temp; -} -void ServerReflectionResponse::set_allocated_original_request(::grpc::reflection::v1alpha::ServerReflectionRequest* original_request) { - delete original_request_; - original_request_ = original_request; - if (original_request) { - - } else { - - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionResponse.original_request) -} - -// optional .grpc.reflection.v1alpha.FileDescriptorResponse file_descriptor_response = 4; -bool ServerReflectionResponse::has_file_descriptor_response() const { - return message_response_case() == kFileDescriptorResponse; -} -void ServerReflectionResponse::set_has_file_descriptor_response() { - _oneof_case_[0] = kFileDescriptorResponse; -} -void ServerReflectionResponse::clear_file_descriptor_response() { - if (has_file_descriptor_response()) { - delete message_response_.file_descriptor_response_; - clear_has_message_response(); - } -} - const ::grpc::reflection::v1alpha::FileDescriptorResponse& ServerReflectionResponse::file_descriptor_response() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionResponse.file_descriptor_response) - return has_file_descriptor_response() - ? *message_response_.file_descriptor_response_ - : ::grpc::reflection::v1alpha::FileDescriptorResponse::default_instance(); -} -::grpc::reflection::v1alpha::FileDescriptorResponse* ServerReflectionResponse::mutable_file_descriptor_response() { - if (!has_file_descriptor_response()) { - clear_message_response(); - set_has_file_descriptor_response(); - message_response_.file_descriptor_response_ = new ::grpc::reflection::v1alpha::FileDescriptorResponse; - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionResponse.file_descriptor_response) - return message_response_.file_descriptor_response_; -} -::grpc::reflection::v1alpha::FileDescriptorResponse* ServerReflectionResponse::release_file_descriptor_response() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionResponse.file_descriptor_response) - if (has_file_descriptor_response()) { - clear_has_message_response(); - ::grpc::reflection::v1alpha::FileDescriptorResponse* temp = message_response_.file_descriptor_response_; - message_response_.file_descriptor_response_ = NULL; - return temp; - } else { - return NULL; - } -} -void ServerReflectionResponse::set_allocated_file_descriptor_response(::grpc::reflection::v1alpha::FileDescriptorResponse* file_descriptor_response) { - clear_message_response(); - if (file_descriptor_response) { - set_has_file_descriptor_response(); - message_response_.file_descriptor_response_ = file_descriptor_response; - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionResponse.file_descriptor_response) -} - -// optional .grpc.reflection.v1alpha.ExtensionNumberResponse all_extension_numbers_response = 5; -bool ServerReflectionResponse::has_all_extension_numbers_response() const { - return message_response_case() == kAllExtensionNumbersResponse; -} -void ServerReflectionResponse::set_has_all_extension_numbers_response() { - _oneof_case_[0] = kAllExtensionNumbersResponse; -} -void ServerReflectionResponse::clear_all_extension_numbers_response() { - if (has_all_extension_numbers_response()) { - delete message_response_.all_extension_numbers_response_; - clear_has_message_response(); - } -} - const ::grpc::reflection::v1alpha::ExtensionNumberResponse& ServerReflectionResponse::all_extension_numbers_response() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionResponse.all_extension_numbers_response) - return has_all_extension_numbers_response() - ? *message_response_.all_extension_numbers_response_ - : ::grpc::reflection::v1alpha::ExtensionNumberResponse::default_instance(); -} -::grpc::reflection::v1alpha::ExtensionNumberResponse* ServerReflectionResponse::mutable_all_extension_numbers_response() { - if (!has_all_extension_numbers_response()) { - clear_message_response(); - set_has_all_extension_numbers_response(); - message_response_.all_extension_numbers_response_ = new ::grpc::reflection::v1alpha::ExtensionNumberResponse; - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionResponse.all_extension_numbers_response) - return message_response_.all_extension_numbers_response_; -} -::grpc::reflection::v1alpha::ExtensionNumberResponse* ServerReflectionResponse::release_all_extension_numbers_response() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionResponse.all_extension_numbers_response) - if (has_all_extension_numbers_response()) { - clear_has_message_response(); - ::grpc::reflection::v1alpha::ExtensionNumberResponse* temp = message_response_.all_extension_numbers_response_; - message_response_.all_extension_numbers_response_ = NULL; - return temp; - } else { - return NULL; - } -} -void ServerReflectionResponse::set_allocated_all_extension_numbers_response(::grpc::reflection::v1alpha::ExtensionNumberResponse* all_extension_numbers_response) { - clear_message_response(); - if (all_extension_numbers_response) { - set_has_all_extension_numbers_response(); - message_response_.all_extension_numbers_response_ = all_extension_numbers_response; - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionResponse.all_extension_numbers_response) -} - -// optional .grpc.reflection.v1alpha.ListServiceResponse list_services_response = 6; -bool ServerReflectionResponse::has_list_services_response() const { - return message_response_case() == kListServicesResponse; -} -void ServerReflectionResponse::set_has_list_services_response() { - _oneof_case_[0] = kListServicesResponse; -} -void ServerReflectionResponse::clear_list_services_response() { - if (has_list_services_response()) { - delete message_response_.list_services_response_; - clear_has_message_response(); - } -} - const ::grpc::reflection::v1alpha::ListServiceResponse& ServerReflectionResponse::list_services_response() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionResponse.list_services_response) - return has_list_services_response() - ? *message_response_.list_services_response_ - : ::grpc::reflection::v1alpha::ListServiceResponse::default_instance(); -} -::grpc::reflection::v1alpha::ListServiceResponse* ServerReflectionResponse::mutable_list_services_response() { - if (!has_list_services_response()) { - clear_message_response(); - set_has_list_services_response(); - message_response_.list_services_response_ = new ::grpc::reflection::v1alpha::ListServiceResponse; - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionResponse.list_services_response) - return message_response_.list_services_response_; -} -::grpc::reflection::v1alpha::ListServiceResponse* ServerReflectionResponse::release_list_services_response() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionResponse.list_services_response) - if (has_list_services_response()) { - clear_has_message_response(); - ::grpc::reflection::v1alpha::ListServiceResponse* temp = message_response_.list_services_response_; - message_response_.list_services_response_ = NULL; - return temp; - } else { - return NULL; - } -} -void ServerReflectionResponse::set_allocated_list_services_response(::grpc::reflection::v1alpha::ListServiceResponse* list_services_response) { - clear_message_response(); - if (list_services_response) { - set_has_list_services_response(); - message_response_.list_services_response_ = list_services_response; - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionResponse.list_services_response) -} - -// optional .grpc.reflection.v1alpha.ErrorResponse error_response = 7; -bool ServerReflectionResponse::has_error_response() const { - return message_response_case() == kErrorResponse; -} -void ServerReflectionResponse::set_has_error_response() { - _oneof_case_[0] = kErrorResponse; -} -void ServerReflectionResponse::clear_error_response() { - if (has_error_response()) { - delete message_response_.error_response_; - clear_has_message_response(); - } -} - const ::grpc::reflection::v1alpha::ErrorResponse& ServerReflectionResponse::error_response() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServerReflectionResponse.error_response) - return has_error_response() - ? *message_response_.error_response_ - : ::grpc::reflection::v1alpha::ErrorResponse::default_instance(); -} -::grpc::reflection::v1alpha::ErrorResponse* ServerReflectionResponse::mutable_error_response() { - if (!has_error_response()) { - clear_message_response(); - set_has_error_response(); - message_response_.error_response_ = new ::grpc::reflection::v1alpha::ErrorResponse; - } - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServerReflectionResponse.error_response) - return message_response_.error_response_; -} -::grpc::reflection::v1alpha::ErrorResponse* ServerReflectionResponse::release_error_response() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServerReflectionResponse.error_response) - if (has_error_response()) { - clear_has_message_response(); - ::grpc::reflection::v1alpha::ErrorResponse* temp = message_response_.error_response_; - message_response_.error_response_ = NULL; - return temp; - } else { - return NULL; - } -} -void ServerReflectionResponse::set_allocated_error_response(::grpc::reflection::v1alpha::ErrorResponse* error_response) { - clear_message_response(); - if (error_response) { - set_has_error_response(); - message_response_.error_response_ = error_response; - } - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServerReflectionResponse.error_response) -} - -bool ServerReflectionResponse::has_message_response() const { - return message_response_case() != MESSAGE_RESPONSE_NOT_SET; -} -void ServerReflectionResponse::clear_has_message_response() { - _oneof_case_[0] = MESSAGE_RESPONSE_NOT_SET; -} -ServerReflectionResponse::MessageResponseCase ServerReflectionResponse::message_response_case() const { - return ServerReflectionResponse::MessageResponseCase(_oneof_case_[0]); -} -inline const ServerReflectionResponse* ServerReflectionResponse::internal_default_instance() { - return &ServerReflectionResponse_default_instance_.get(); -} -#endif // PROTOBUF_INLINE_NOT_IN_HEADERS - -// =================================================================== - -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int FileDescriptorResponse::kFileDescriptorProtoFieldNumber; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 - -FileDescriptorResponse::FileDescriptorResponse() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (this != internal_default_instance()) protobuf_InitDefaults_reflection_2eproto(); - SharedCtor(); - // @@protoc_insertion_point(constructor:grpc.reflection.v1alpha.FileDescriptorResponse) -} - -void FileDescriptorResponse::InitAsDefaultInstance() { -} - -FileDescriptorResponse::FileDescriptorResponse(const FileDescriptorResponse& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { - SharedCtor(); - UnsafeMergeFrom(from); - // @@protoc_insertion_point(copy_constructor:grpc.reflection.v1alpha.FileDescriptorResponse) -} - -void FileDescriptorResponse::SharedCtor() { - _cached_size_ = 0; -} - -FileDescriptorResponse::~FileDescriptorResponse() { - // @@protoc_insertion_point(destructor:grpc.reflection.v1alpha.FileDescriptorResponse) - SharedDtor(); -} - -void FileDescriptorResponse::SharedDtor() { -} - -void FileDescriptorResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* FileDescriptorResponse::descriptor() { - protobuf_AssignDescriptorsOnce(); - return FileDescriptorResponse_descriptor_; -} - -const FileDescriptorResponse& FileDescriptorResponse::default_instance() { - protobuf_InitDefaults_reflection_2eproto(); - return *internal_default_instance(); -} - -::google::protobuf::internal::ExplicitlyConstructed FileDescriptorResponse_default_instance_; - -FileDescriptorResponse* FileDescriptorResponse::New(::google::protobuf::Arena* arena) const { - FileDescriptorResponse* n = new FileDescriptorResponse; - if (arena != NULL) { - arena->Own(n); - } - return n; -} - -void FileDescriptorResponse::Clear() { -// @@protoc_insertion_point(message_clear_start:grpc.reflection.v1alpha.FileDescriptorResponse) - file_descriptor_proto_.Clear(); -} - -bool FileDescriptorResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:grpc.reflection.v1alpha.FileDescriptorResponse) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // repeated bytes file_descriptor_proto = 1; - case 1: { - if (tag == 10) { - parse_file_descriptor_proto: - DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( - input, this->add_file_descriptor_proto())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(10)) goto parse_file_descriptor_proto; - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:grpc.reflection.v1alpha.FileDescriptorResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:grpc.reflection.v1alpha.FileDescriptorResponse) - return false; -#undef DO_ -} - -void FileDescriptorResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:grpc.reflection.v1alpha.FileDescriptorResponse) - // repeated bytes file_descriptor_proto = 1; - for (int i = 0; i < this->file_descriptor_proto_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteBytes( - 1, this->file_descriptor_proto(i), output); - } - - // @@protoc_insertion_point(serialize_end:grpc.reflection.v1alpha.FileDescriptorResponse) -} - -::google::protobuf::uint8* FileDescriptorResponse::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused - // @@protoc_insertion_point(serialize_to_array_start:grpc.reflection.v1alpha.FileDescriptorResponse) - // repeated bytes file_descriptor_proto = 1; - for (int i = 0; i < this->file_descriptor_proto_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteBytesToArray(1, this->file_descriptor_proto(i), target); - } - - // @@protoc_insertion_point(serialize_to_array_end:grpc.reflection.v1alpha.FileDescriptorResponse) - return target; -} - -size_t FileDescriptorResponse::ByteSizeLong() const { -// @@protoc_insertion_point(message_byte_size_start:grpc.reflection.v1alpha.FileDescriptorResponse) - size_t total_size = 0; - - // repeated bytes file_descriptor_proto = 1; - total_size += 1 * - ::google::protobuf::internal::FromIntSize(this->file_descriptor_proto_size()); - for (int i = 0; i < this->file_descriptor_proto_size(); i++) { - total_size += ::google::protobuf::internal::WireFormatLite::BytesSize( - this->file_descriptor_proto(i)); - } - - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void FileDescriptorResponse::MergeFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_merge_from_start:grpc.reflection.v1alpha.FileDescriptorResponse) - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - const FileDescriptorResponse* source = - ::google::protobuf::internal::DynamicCastToGenerated( - &from); - if (source == NULL) { - // @@protoc_insertion_point(generalized_merge_from_cast_fail:grpc.reflection.v1alpha.FileDescriptorResponse) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - // @@protoc_insertion_point(generalized_merge_from_cast_success:grpc.reflection.v1alpha.FileDescriptorResponse) - UnsafeMergeFrom(*source); - } -} - -void FileDescriptorResponse::MergeFrom(const FileDescriptorResponse& from) { -// @@protoc_insertion_point(class_specific_merge_from_start:grpc.reflection.v1alpha.FileDescriptorResponse) - if (GOOGLE_PREDICT_TRUE(&from != this)) { - UnsafeMergeFrom(from); - } else { - MergeFromFail(__LINE__); - } -} - -void FileDescriptorResponse::UnsafeMergeFrom(const FileDescriptorResponse& from) { - GOOGLE_DCHECK(&from != this); - file_descriptor_proto_.UnsafeMergeFrom(from.file_descriptor_proto_); -} - -void FileDescriptorResponse::CopyFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_copy_from_start:grpc.reflection.v1alpha.FileDescriptorResponse) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void FileDescriptorResponse::CopyFrom(const FileDescriptorResponse& from) { -// @@protoc_insertion_point(class_specific_copy_from_start:grpc.reflection.v1alpha.FileDescriptorResponse) - if (&from == this) return; - Clear(); - UnsafeMergeFrom(from); -} - -bool FileDescriptorResponse::IsInitialized() const { - - return true; -} - -void FileDescriptorResponse::Swap(FileDescriptorResponse* other) { - if (other == this) return; - InternalSwap(other); -} -void FileDescriptorResponse::InternalSwap(FileDescriptorResponse* other) { - file_descriptor_proto_.UnsafeArenaSwap(&other->file_descriptor_proto_); - _internal_metadata_.Swap(&other->_internal_metadata_); - std::swap(_cached_size_, other->_cached_size_); -} - -::google::protobuf::Metadata FileDescriptorResponse::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = FileDescriptorResponse_descriptor_; - metadata.reflection = FileDescriptorResponse_reflection_; - return metadata; -} - -#if PROTOBUF_INLINE_NOT_IN_HEADERS -// FileDescriptorResponse - -// repeated bytes file_descriptor_proto = 1; -int FileDescriptorResponse::file_descriptor_proto_size() const { - return file_descriptor_proto_.size(); -} -void FileDescriptorResponse::clear_file_descriptor_proto() { - file_descriptor_proto_.Clear(); -} -const ::std::string& FileDescriptorResponse::file_descriptor_proto(int index) const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) - return file_descriptor_proto_.Get(index); -} -::std::string* FileDescriptorResponse::mutable_file_descriptor_proto(int index) { - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) - return file_descriptor_proto_.Mutable(index); -} -void FileDescriptorResponse::set_file_descriptor_proto(int index, const ::std::string& value) { - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) - file_descriptor_proto_.Mutable(index)->assign(value); -} -void FileDescriptorResponse::set_file_descriptor_proto(int index, const char* value) { - file_descriptor_proto_.Mutable(index)->assign(value); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) -} -void FileDescriptorResponse::set_file_descriptor_proto(int index, const void* value, size_t size) { - file_descriptor_proto_.Mutable(index)->assign( - reinterpret_cast(value), size); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) -} -::std::string* FileDescriptorResponse::add_file_descriptor_proto() { - // @@protoc_insertion_point(field_add_mutable:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) - return file_descriptor_proto_.Add(); -} -void FileDescriptorResponse::add_file_descriptor_proto(const ::std::string& value) { - file_descriptor_proto_.Add()->assign(value); - // @@protoc_insertion_point(field_add:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) -} -void FileDescriptorResponse::add_file_descriptor_proto(const char* value) { - file_descriptor_proto_.Add()->assign(value); - // @@protoc_insertion_point(field_add_char:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) -} -void FileDescriptorResponse::add_file_descriptor_proto(const void* value, size_t size) { - file_descriptor_proto_.Add()->assign(reinterpret_cast(value), size); - // @@protoc_insertion_point(field_add_pointer:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) -} -const ::google::protobuf::RepeatedPtrField< ::std::string>& -FileDescriptorResponse::file_descriptor_proto() const { - // @@protoc_insertion_point(field_list:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) - return file_descriptor_proto_; -} -::google::protobuf::RepeatedPtrField< ::std::string>* -FileDescriptorResponse::mutable_file_descriptor_proto() { - // @@protoc_insertion_point(field_mutable_list:grpc.reflection.v1alpha.FileDescriptorResponse.file_descriptor_proto) - return &file_descriptor_proto_; -} - -inline const FileDescriptorResponse* FileDescriptorResponse::internal_default_instance() { - return &FileDescriptorResponse_default_instance_.get(); -} -#endif // PROTOBUF_INLINE_NOT_IN_HEADERS - -// =================================================================== - -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int ExtensionNumberResponse::kBaseTypeNameFieldNumber; -const int ExtensionNumberResponse::kExtensionNumberFieldNumber; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 - -ExtensionNumberResponse::ExtensionNumberResponse() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (this != internal_default_instance()) protobuf_InitDefaults_reflection_2eproto(); - SharedCtor(); - // @@protoc_insertion_point(constructor:grpc.reflection.v1alpha.ExtensionNumberResponse) -} - -void ExtensionNumberResponse::InitAsDefaultInstance() { -} - -ExtensionNumberResponse::ExtensionNumberResponse(const ExtensionNumberResponse& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { - SharedCtor(); - UnsafeMergeFrom(from); - // @@protoc_insertion_point(copy_constructor:grpc.reflection.v1alpha.ExtensionNumberResponse) -} - -void ExtensionNumberResponse::SharedCtor() { - base_type_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - _cached_size_ = 0; -} - -ExtensionNumberResponse::~ExtensionNumberResponse() { - // @@protoc_insertion_point(destructor:grpc.reflection.v1alpha.ExtensionNumberResponse) - SharedDtor(); -} - -void ExtensionNumberResponse::SharedDtor() { - base_type_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -void ExtensionNumberResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* ExtensionNumberResponse::descriptor() { - protobuf_AssignDescriptorsOnce(); - return ExtensionNumberResponse_descriptor_; -} - -const ExtensionNumberResponse& ExtensionNumberResponse::default_instance() { - protobuf_InitDefaults_reflection_2eproto(); - return *internal_default_instance(); -} - -::google::protobuf::internal::ExplicitlyConstructed ExtensionNumberResponse_default_instance_; - -ExtensionNumberResponse* ExtensionNumberResponse::New(::google::protobuf::Arena* arena) const { - ExtensionNumberResponse* n = new ExtensionNumberResponse; - if (arena != NULL) { - arena->Own(n); - } - return n; -} - -void ExtensionNumberResponse::Clear() { -// @@protoc_insertion_point(message_clear_start:grpc.reflection.v1alpha.ExtensionNumberResponse) - base_type_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - extension_number_.Clear(); -} - -bool ExtensionNumberResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:grpc.reflection.v1alpha.ExtensionNumberResponse) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string base_type_name = 1; - case 1: { - if (tag == 10) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_base_type_name())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->base_type_name().data(), this->base_type_name().length(), - ::google::protobuf::internal::WireFormatLite::PARSE, - "grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name")); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_extension_number; - break; - } - - // repeated int32 extension_number = 2; - case 2: { - if (tag == 18) { - parse_extension_number: - DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, this->mutable_extension_number()))); - } else if (tag == 16) { - DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - 1, 18, input, this->mutable_extension_number()))); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:grpc.reflection.v1alpha.ExtensionNumberResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:grpc.reflection.v1alpha.ExtensionNumberResponse) - return false; -#undef DO_ -} - -void ExtensionNumberResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:grpc.reflection.v1alpha.ExtensionNumberResponse) - // optional string base_type_name = 1; - if (this->base_type_name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->base_type_name().data(), this->base_type_name().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 1, this->base_type_name(), output); - } - - // repeated int32 extension_number = 2; - if (this->extension_number_size() > 0) { - ::google::protobuf::internal::WireFormatLite::WriteTag(2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); - output->WriteVarint32(_extension_number_cached_byte_size_); - } - for (int i = 0; i < this->extension_number_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteInt32NoTag( - this->extension_number(i), output); - } - - // @@protoc_insertion_point(serialize_end:grpc.reflection.v1alpha.ExtensionNumberResponse) -} - -::google::protobuf::uint8* ExtensionNumberResponse::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused - // @@protoc_insertion_point(serialize_to_array_start:grpc.reflection.v1alpha.ExtensionNumberResponse) - // optional string base_type_name = 1; - if (this->base_type_name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->base_type_name().data(), this->base_type_name().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->base_type_name(), target); - } - - // repeated int32 extension_number = 2; - if (this->extension_number_size() > 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( - 2, - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, - target); - target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( - _extension_number_cached_byte_size_, target); - } - for (int i = 0; i < this->extension_number_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteInt32NoTagToArray(this->extension_number(i), target); - } - - // @@protoc_insertion_point(serialize_to_array_end:grpc.reflection.v1alpha.ExtensionNumberResponse) - return target; -} - -size_t ExtensionNumberResponse::ByteSizeLong() const { -// @@protoc_insertion_point(message_byte_size_start:grpc.reflection.v1alpha.ExtensionNumberResponse) - size_t total_size = 0; - - // optional string base_type_name = 1; - if (this->base_type_name().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->base_type_name()); - } - - // repeated int32 extension_number = 2; - { - size_t data_size = 0; - unsigned int count = this->extension_number_size(); - for (unsigned int i = 0; i < count; i++) { - data_size += ::google::protobuf::internal::WireFormatLite:: - Int32Size(this->extension_number(i)); - } - if (data_size > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size(data_size); - } - int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _extension_number_cached_byte_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - total_size += data_size; - } - - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void ExtensionNumberResponse::MergeFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_merge_from_start:grpc.reflection.v1alpha.ExtensionNumberResponse) - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - const ExtensionNumberResponse* source = - ::google::protobuf::internal::DynamicCastToGenerated( - &from); - if (source == NULL) { - // @@protoc_insertion_point(generalized_merge_from_cast_fail:grpc.reflection.v1alpha.ExtensionNumberResponse) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - // @@protoc_insertion_point(generalized_merge_from_cast_success:grpc.reflection.v1alpha.ExtensionNumberResponse) - UnsafeMergeFrom(*source); - } -} - -void ExtensionNumberResponse::MergeFrom(const ExtensionNumberResponse& from) { -// @@protoc_insertion_point(class_specific_merge_from_start:grpc.reflection.v1alpha.ExtensionNumberResponse) - if (GOOGLE_PREDICT_TRUE(&from != this)) { - UnsafeMergeFrom(from); - } else { - MergeFromFail(__LINE__); - } -} - -void ExtensionNumberResponse::UnsafeMergeFrom(const ExtensionNumberResponse& from) { - GOOGLE_DCHECK(&from != this); - extension_number_.UnsafeMergeFrom(from.extension_number_); - if (from.base_type_name().size() > 0) { - - base_type_name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.base_type_name_); - } -} - -void ExtensionNumberResponse::CopyFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_copy_from_start:grpc.reflection.v1alpha.ExtensionNumberResponse) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void ExtensionNumberResponse::CopyFrom(const ExtensionNumberResponse& from) { -// @@protoc_insertion_point(class_specific_copy_from_start:grpc.reflection.v1alpha.ExtensionNumberResponse) - if (&from == this) return; - Clear(); - UnsafeMergeFrom(from); -} - -bool ExtensionNumberResponse::IsInitialized() const { - - return true; -} - -void ExtensionNumberResponse::Swap(ExtensionNumberResponse* other) { - if (other == this) return; - InternalSwap(other); -} -void ExtensionNumberResponse::InternalSwap(ExtensionNumberResponse* other) { - base_type_name_.Swap(&other->base_type_name_); - extension_number_.UnsafeArenaSwap(&other->extension_number_); - _internal_metadata_.Swap(&other->_internal_metadata_); - std::swap(_cached_size_, other->_cached_size_); -} - -::google::protobuf::Metadata ExtensionNumberResponse::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = ExtensionNumberResponse_descriptor_; - metadata.reflection = ExtensionNumberResponse_reflection_; - return metadata; -} - -#if PROTOBUF_INLINE_NOT_IN_HEADERS -// ExtensionNumberResponse - -// optional string base_type_name = 1; -void ExtensionNumberResponse::clear_base_type_name() { - base_type_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -const ::std::string& ExtensionNumberResponse::base_type_name() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name) - return base_type_name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -void ExtensionNumberResponse::set_base_type_name(const ::std::string& value) { - - base_type_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name) -} -void ExtensionNumberResponse::set_base_type_name(const char* value) { - - base_type_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name) -} -void ExtensionNumberResponse::set_base_type_name(const char* value, size_t size) { - - base_type_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name) -} -::std::string* ExtensionNumberResponse::mutable_base_type_name() { - - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name) - return base_type_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -::std::string* ExtensionNumberResponse::release_base_type_name() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name) - - return base_type_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -void ExtensionNumberResponse::set_allocated_base_type_name(::std::string* base_type_name) { - if (base_type_name != NULL) { - - } else { - - } - base_type_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), base_type_name); - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ExtensionNumberResponse.base_type_name) -} - -// repeated int32 extension_number = 2; -int ExtensionNumberResponse::extension_number_size() const { - return extension_number_.size(); -} -void ExtensionNumberResponse::clear_extension_number() { - extension_number_.Clear(); -} -::google::protobuf::int32 ExtensionNumberResponse::extension_number(int index) const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ExtensionNumberResponse.extension_number) - return extension_number_.Get(index); -} -void ExtensionNumberResponse::set_extension_number(int index, ::google::protobuf::int32 value) { - extension_number_.Set(index, value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ExtensionNumberResponse.extension_number) -} -void ExtensionNumberResponse::add_extension_number(::google::protobuf::int32 value) { - extension_number_.Add(value); - // @@protoc_insertion_point(field_add:grpc.reflection.v1alpha.ExtensionNumberResponse.extension_number) -} -const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >& -ExtensionNumberResponse::extension_number() const { - // @@protoc_insertion_point(field_list:grpc.reflection.v1alpha.ExtensionNumberResponse.extension_number) - return extension_number_; -} -::google::protobuf::RepeatedField< ::google::protobuf::int32 >* -ExtensionNumberResponse::mutable_extension_number() { - // @@protoc_insertion_point(field_mutable_list:grpc.reflection.v1alpha.ExtensionNumberResponse.extension_number) - return &extension_number_; -} - -inline const ExtensionNumberResponse* ExtensionNumberResponse::internal_default_instance() { - return &ExtensionNumberResponse_default_instance_.get(); -} -#endif // PROTOBUF_INLINE_NOT_IN_HEADERS - -// =================================================================== - -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int ListServiceResponse::kServiceFieldNumber; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 - -ListServiceResponse::ListServiceResponse() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (this != internal_default_instance()) protobuf_InitDefaults_reflection_2eproto(); - SharedCtor(); - // @@protoc_insertion_point(constructor:grpc.reflection.v1alpha.ListServiceResponse) -} - -void ListServiceResponse::InitAsDefaultInstance() { -} - -ListServiceResponse::ListServiceResponse(const ListServiceResponse& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { - SharedCtor(); - UnsafeMergeFrom(from); - // @@protoc_insertion_point(copy_constructor:grpc.reflection.v1alpha.ListServiceResponse) -} - -void ListServiceResponse::SharedCtor() { - _cached_size_ = 0; -} - -ListServiceResponse::~ListServiceResponse() { - // @@protoc_insertion_point(destructor:grpc.reflection.v1alpha.ListServiceResponse) - SharedDtor(); -} - -void ListServiceResponse::SharedDtor() { -} - -void ListServiceResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* ListServiceResponse::descriptor() { - protobuf_AssignDescriptorsOnce(); - return ListServiceResponse_descriptor_; -} - -const ListServiceResponse& ListServiceResponse::default_instance() { - protobuf_InitDefaults_reflection_2eproto(); - return *internal_default_instance(); -} - -::google::protobuf::internal::ExplicitlyConstructed ListServiceResponse_default_instance_; - -ListServiceResponse* ListServiceResponse::New(::google::protobuf::Arena* arena) const { - ListServiceResponse* n = new ListServiceResponse; - if (arena != NULL) { - arena->Own(n); - } - return n; -} - -void ListServiceResponse::Clear() { -// @@protoc_insertion_point(message_clear_start:grpc.reflection.v1alpha.ListServiceResponse) - service_.Clear(); -} - -bool ListServiceResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:grpc.reflection.v1alpha.ListServiceResponse) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // repeated .grpc.reflection.v1alpha.ServiceResponse service = 1; - case 1: { - if (tag == 10) { - DO_(input->IncrementRecursionDepth()); - parse_loop_service: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth( - input, add_service())); - } else { - goto handle_unusual; - } - if (input->ExpectTag(10)) goto parse_loop_service; - input->UnsafeDecrementRecursionDepth(); - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:grpc.reflection.v1alpha.ListServiceResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:grpc.reflection.v1alpha.ListServiceResponse) - return false; -#undef DO_ -} - -void ListServiceResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:grpc.reflection.v1alpha.ListServiceResponse) - // repeated .grpc.reflection.v1alpha.ServiceResponse service = 1; - for (unsigned int i = 0, n = this->service_size(); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 1, this->service(i), output); - } - - // @@protoc_insertion_point(serialize_end:grpc.reflection.v1alpha.ListServiceResponse) -} - -::google::protobuf::uint8* ListServiceResponse::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused - // @@protoc_insertion_point(serialize_to_array_start:grpc.reflection.v1alpha.ListServiceResponse) - // repeated .grpc.reflection.v1alpha.ServiceResponse service = 1; - for (unsigned int i = 0, n = this->service_size(); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageNoVirtualToArray( - 1, this->service(i), false, target); - } - - // @@protoc_insertion_point(serialize_to_array_end:grpc.reflection.v1alpha.ListServiceResponse) - return target; -} - -size_t ListServiceResponse::ByteSizeLong() const { -// @@protoc_insertion_point(message_byte_size_start:grpc.reflection.v1alpha.ListServiceResponse) - size_t total_size = 0; - - // repeated .grpc.reflection.v1alpha.ServiceResponse service = 1; - { - unsigned int count = this->service_size(); - total_size += 1UL * count; - for (unsigned int i = 0; i < count; i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->service(i)); - } - } - - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void ListServiceResponse::MergeFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_merge_from_start:grpc.reflection.v1alpha.ListServiceResponse) - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - const ListServiceResponse* source = - ::google::protobuf::internal::DynamicCastToGenerated( - &from); - if (source == NULL) { - // @@protoc_insertion_point(generalized_merge_from_cast_fail:grpc.reflection.v1alpha.ListServiceResponse) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - // @@protoc_insertion_point(generalized_merge_from_cast_success:grpc.reflection.v1alpha.ListServiceResponse) - UnsafeMergeFrom(*source); - } -} - -void ListServiceResponse::MergeFrom(const ListServiceResponse& from) { -// @@protoc_insertion_point(class_specific_merge_from_start:grpc.reflection.v1alpha.ListServiceResponse) - if (GOOGLE_PREDICT_TRUE(&from != this)) { - UnsafeMergeFrom(from); - } else { - MergeFromFail(__LINE__); - } -} - -void ListServiceResponse::UnsafeMergeFrom(const ListServiceResponse& from) { - GOOGLE_DCHECK(&from != this); - service_.MergeFrom(from.service_); -} - -void ListServiceResponse::CopyFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_copy_from_start:grpc.reflection.v1alpha.ListServiceResponse) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void ListServiceResponse::CopyFrom(const ListServiceResponse& from) { -// @@protoc_insertion_point(class_specific_copy_from_start:grpc.reflection.v1alpha.ListServiceResponse) - if (&from == this) return; - Clear(); - UnsafeMergeFrom(from); -} - -bool ListServiceResponse::IsInitialized() const { - - return true; -} - -void ListServiceResponse::Swap(ListServiceResponse* other) { - if (other == this) return; - InternalSwap(other); -} -void ListServiceResponse::InternalSwap(ListServiceResponse* other) { - service_.UnsafeArenaSwap(&other->service_); - _internal_metadata_.Swap(&other->_internal_metadata_); - std::swap(_cached_size_, other->_cached_size_); -} - -::google::protobuf::Metadata ListServiceResponse::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = ListServiceResponse_descriptor_; - metadata.reflection = ListServiceResponse_reflection_; - return metadata; -} - -#if PROTOBUF_INLINE_NOT_IN_HEADERS -// ListServiceResponse - -// repeated .grpc.reflection.v1alpha.ServiceResponse service = 1; -int ListServiceResponse::service_size() const { - return service_.size(); -} -void ListServiceResponse::clear_service() { - service_.Clear(); -} -const ::grpc::reflection::v1alpha::ServiceResponse& ListServiceResponse::service(int index) const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ListServiceResponse.service) - return service_.Get(index); -} -::grpc::reflection::v1alpha::ServiceResponse* ListServiceResponse::mutable_service(int index) { - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ListServiceResponse.service) - return service_.Mutable(index); -} -::grpc::reflection::v1alpha::ServiceResponse* ListServiceResponse::add_service() { - // @@protoc_insertion_point(field_add:grpc.reflection.v1alpha.ListServiceResponse.service) - return service_.Add(); -} -::google::protobuf::RepeatedPtrField< ::grpc::reflection::v1alpha::ServiceResponse >* -ListServiceResponse::mutable_service() { - // @@protoc_insertion_point(field_mutable_list:grpc.reflection.v1alpha.ListServiceResponse.service) - return &service_; -} -const ::google::protobuf::RepeatedPtrField< ::grpc::reflection::v1alpha::ServiceResponse >& -ListServiceResponse::service() const { - // @@protoc_insertion_point(field_list:grpc.reflection.v1alpha.ListServiceResponse.service) - return service_; -} - -inline const ListServiceResponse* ListServiceResponse::internal_default_instance() { - return &ListServiceResponse_default_instance_.get(); -} -#endif // PROTOBUF_INLINE_NOT_IN_HEADERS - -// =================================================================== - -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int ServiceResponse::kNameFieldNumber; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 - -ServiceResponse::ServiceResponse() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (this != internal_default_instance()) protobuf_InitDefaults_reflection_2eproto(); - SharedCtor(); - // @@protoc_insertion_point(constructor:grpc.reflection.v1alpha.ServiceResponse) -} - -void ServiceResponse::InitAsDefaultInstance() { -} - -ServiceResponse::ServiceResponse(const ServiceResponse& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { - SharedCtor(); - UnsafeMergeFrom(from); - // @@protoc_insertion_point(copy_constructor:grpc.reflection.v1alpha.ServiceResponse) -} - -void ServiceResponse::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - _cached_size_ = 0; -} - -ServiceResponse::~ServiceResponse() { - // @@protoc_insertion_point(destructor:grpc.reflection.v1alpha.ServiceResponse) - SharedDtor(); -} - -void ServiceResponse::SharedDtor() { - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -void ServiceResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* ServiceResponse::descriptor() { - protobuf_AssignDescriptorsOnce(); - return ServiceResponse_descriptor_; -} - -const ServiceResponse& ServiceResponse::default_instance() { - protobuf_InitDefaults_reflection_2eproto(); - return *internal_default_instance(); -} - -::google::protobuf::internal::ExplicitlyConstructed ServiceResponse_default_instance_; - -ServiceResponse* ServiceResponse::New(::google::protobuf::Arena* arena) const { - ServiceResponse* n = new ServiceResponse; - if (arena != NULL) { - arena->Own(n); - } - return n; -} - -void ServiceResponse::Clear() { -// @@protoc_insertion_point(message_clear_start:grpc.reflection.v1alpha.ServiceResponse) - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -bool ServiceResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:grpc.reflection.v1alpha.ServiceResponse) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string name = 1; - case 1: { - if (tag == 10) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_name())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormatLite::PARSE, - "grpc.reflection.v1alpha.ServiceResponse.name")); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:grpc.reflection.v1alpha.ServiceResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:grpc.reflection.v1alpha.ServiceResponse) - return false; -#undef DO_ -} - -void ServiceResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:grpc.reflection.v1alpha.ServiceResponse) - // optional string name = 1; - if (this->name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ServiceResponse.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 1, this->name(), output); - } - - // @@protoc_insertion_point(serialize_end:grpc.reflection.v1alpha.ServiceResponse) -} - -::google::protobuf::uint8* ServiceResponse::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused - // @@protoc_insertion_point(serialize_to_array_start:grpc.reflection.v1alpha.ServiceResponse) - // optional string name = 1; - if (this->name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ServiceResponse.name"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->name(), target); - } - - // @@protoc_insertion_point(serialize_to_array_end:grpc.reflection.v1alpha.ServiceResponse) - return target; -} - -size_t ServiceResponse::ByteSizeLong() const { -// @@protoc_insertion_point(message_byte_size_start:grpc.reflection.v1alpha.ServiceResponse) - size_t total_size = 0; - - // optional string name = 1; - if (this->name().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->name()); - } - - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void ServiceResponse::MergeFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_merge_from_start:grpc.reflection.v1alpha.ServiceResponse) - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - const ServiceResponse* source = - ::google::protobuf::internal::DynamicCastToGenerated( - &from); - if (source == NULL) { - // @@protoc_insertion_point(generalized_merge_from_cast_fail:grpc.reflection.v1alpha.ServiceResponse) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - // @@protoc_insertion_point(generalized_merge_from_cast_success:grpc.reflection.v1alpha.ServiceResponse) - UnsafeMergeFrom(*source); - } -} - -void ServiceResponse::MergeFrom(const ServiceResponse& from) { -// @@protoc_insertion_point(class_specific_merge_from_start:grpc.reflection.v1alpha.ServiceResponse) - if (GOOGLE_PREDICT_TRUE(&from != this)) { - UnsafeMergeFrom(from); - } else { - MergeFromFail(__LINE__); - } -} - -void ServiceResponse::UnsafeMergeFrom(const ServiceResponse& from) { - GOOGLE_DCHECK(&from != this); - if (from.name().size() > 0) { - - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); - } -} - -void ServiceResponse::CopyFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_copy_from_start:grpc.reflection.v1alpha.ServiceResponse) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void ServiceResponse::CopyFrom(const ServiceResponse& from) { -// @@protoc_insertion_point(class_specific_copy_from_start:grpc.reflection.v1alpha.ServiceResponse) - if (&from == this) return; - Clear(); - UnsafeMergeFrom(from); -} - -bool ServiceResponse::IsInitialized() const { - - return true; -} - -void ServiceResponse::Swap(ServiceResponse* other) { - if (other == this) return; - InternalSwap(other); -} -void ServiceResponse::InternalSwap(ServiceResponse* other) { - name_.Swap(&other->name_); - _internal_metadata_.Swap(&other->_internal_metadata_); - std::swap(_cached_size_, other->_cached_size_); -} - -::google::protobuf::Metadata ServiceResponse::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = ServiceResponse_descriptor_; - metadata.reflection = ServiceResponse_reflection_; - return metadata; -} - -#if PROTOBUF_INLINE_NOT_IN_HEADERS -// ServiceResponse - -// optional string name = 1; -void ServiceResponse::clear_name() { - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -const ::std::string& ServiceResponse::name() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ServiceResponse.name) - return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -void ServiceResponse::set_name(const ::std::string& value) { - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ServiceResponse.name) -} -void ServiceResponse::set_name(const char* value) { - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ServiceResponse.name) -} -void ServiceResponse::set_name(const char* value, size_t size) { - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ServiceResponse.name) -} -::std::string* ServiceResponse::mutable_name() { - - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ServiceResponse.name) - return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -::std::string* ServiceResponse::release_name() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ServiceResponse.name) - - return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -void ServiceResponse::set_allocated_name(::std::string* name) { - if (name != NULL) { - - } else { - - } - name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ServiceResponse.name) -} - -inline const ServiceResponse* ServiceResponse::internal_default_instance() { - return &ServiceResponse_default_instance_.get(); -} -#endif // PROTOBUF_INLINE_NOT_IN_HEADERS - -// =================================================================== - -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int ErrorResponse::kErrorCodeFieldNumber; -const int ErrorResponse::kErrorMessageFieldNumber; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 - -ErrorResponse::ErrorResponse() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - if (this != internal_default_instance()) protobuf_InitDefaults_reflection_2eproto(); - SharedCtor(); - // @@protoc_insertion_point(constructor:grpc.reflection.v1alpha.ErrorResponse) -} - -void ErrorResponse::InitAsDefaultInstance() { -} - -ErrorResponse::ErrorResponse(const ErrorResponse& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { - SharedCtor(); - UnsafeMergeFrom(from); - // @@protoc_insertion_point(copy_constructor:grpc.reflection.v1alpha.ErrorResponse) -} - -void ErrorResponse::SharedCtor() { - error_message_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - error_code_ = 0; - _cached_size_ = 0; -} - -ErrorResponse::~ErrorResponse() { - // @@protoc_insertion_point(destructor:grpc.reflection.v1alpha.ErrorResponse) - SharedDtor(); -} - -void ErrorResponse::SharedDtor() { - error_message_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -void ErrorResponse::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* ErrorResponse::descriptor() { - protobuf_AssignDescriptorsOnce(); - return ErrorResponse_descriptor_; -} - -const ErrorResponse& ErrorResponse::default_instance() { - protobuf_InitDefaults_reflection_2eproto(); - return *internal_default_instance(); -} - -::google::protobuf::internal::ExplicitlyConstructed ErrorResponse_default_instance_; - -ErrorResponse* ErrorResponse::New(::google::protobuf::Arena* arena) const { - ErrorResponse* n = new ErrorResponse; - if (arena != NULL) { - arena->Own(n); - } - return n; -} - -void ErrorResponse::Clear() { -// @@protoc_insertion_point(message_clear_start:grpc.reflection.v1alpha.ErrorResponse) - error_code_ = 0; - error_message_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -bool ErrorResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:grpc.reflection.v1alpha.ErrorResponse) - for (;;) { - ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional int32 error_code = 1; - case 1: { - if (tag == 8) { - - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, &error_code_))); - } else { - goto handle_unusual; - } - if (input->ExpectTag(18)) goto parse_error_message; - break; - } - - // optional string error_message = 2; - case 2: { - if (tag == 18) { - parse_error_message: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_error_message())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->error_message().data(), this->error_message().length(), - ::google::protobuf::internal::WireFormatLite::PARSE, - "grpc.reflection.v1alpha.ErrorResponse.error_message")); - } else { - goto handle_unusual; - } - if (input->ExpectAtEnd()) goto success; - break; - } - - default: { - handle_unusual: - if (tag == 0 || - ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - goto success; - } - DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:grpc.reflection.v1alpha.ErrorResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:grpc.reflection.v1alpha.ErrorResponse) - return false; -#undef DO_ -} - -void ErrorResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:grpc.reflection.v1alpha.ErrorResponse) - // optional int32 error_code = 1; - if (this->error_code() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->error_code(), output); - } - - // optional string error_message = 2; - if (this->error_message().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->error_message().data(), this->error_message().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ErrorResponse.error_message"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 2, this->error_message(), output); - } - - // @@protoc_insertion_point(serialize_end:grpc.reflection.v1alpha.ErrorResponse) -} - -::google::protobuf::uint8* ErrorResponse::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused - // @@protoc_insertion_point(serialize_to_array_start:grpc.reflection.v1alpha.ErrorResponse) - // optional int32 error_code = 1; - if (this->error_code() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->error_code(), target); - } - - // optional string error_message = 2; - if (this->error_message().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->error_message().data(), this->error_message().length(), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "grpc.reflection.v1alpha.ErrorResponse.error_message"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 2, this->error_message(), target); - } - - // @@protoc_insertion_point(serialize_to_array_end:grpc.reflection.v1alpha.ErrorResponse) - return target; -} - -size_t ErrorResponse::ByteSizeLong() const { -// @@protoc_insertion_point(message_byte_size_start:grpc.reflection.v1alpha.ErrorResponse) - size_t total_size = 0; - - // optional int32 error_code = 1; - if (this->error_code() != 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - this->error_code()); - } - - // optional string error_message = 2; - if (this->error_message().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->error_message()); - } - - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = cached_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void ErrorResponse::MergeFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_merge_from_start:grpc.reflection.v1alpha.ErrorResponse) - if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); - const ErrorResponse* source = - ::google::protobuf::internal::DynamicCastToGenerated( - &from); - if (source == NULL) { - // @@protoc_insertion_point(generalized_merge_from_cast_fail:grpc.reflection.v1alpha.ErrorResponse) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - // @@protoc_insertion_point(generalized_merge_from_cast_success:grpc.reflection.v1alpha.ErrorResponse) - UnsafeMergeFrom(*source); - } -} - -void ErrorResponse::MergeFrom(const ErrorResponse& from) { -// @@protoc_insertion_point(class_specific_merge_from_start:grpc.reflection.v1alpha.ErrorResponse) - if (GOOGLE_PREDICT_TRUE(&from != this)) { - UnsafeMergeFrom(from); - } else { - MergeFromFail(__LINE__); - } -} - -void ErrorResponse::UnsafeMergeFrom(const ErrorResponse& from) { - GOOGLE_DCHECK(&from != this); - if (from.error_code() != 0) { - set_error_code(from.error_code()); - } - if (from.error_message().size() > 0) { - - error_message_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.error_message_); - } -} - -void ErrorResponse::CopyFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_copy_from_start:grpc.reflection.v1alpha.ErrorResponse) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void ErrorResponse::CopyFrom(const ErrorResponse& from) { -// @@protoc_insertion_point(class_specific_copy_from_start:grpc.reflection.v1alpha.ErrorResponse) - if (&from == this) return; - Clear(); - UnsafeMergeFrom(from); -} - -bool ErrorResponse::IsInitialized() const { - - return true; -} - -void ErrorResponse::Swap(ErrorResponse* other) { - if (other == this) return; - InternalSwap(other); -} -void ErrorResponse::InternalSwap(ErrorResponse* other) { - std::swap(error_code_, other->error_code_); - error_message_.Swap(&other->error_message_); - _internal_metadata_.Swap(&other->_internal_metadata_); - std::swap(_cached_size_, other->_cached_size_); -} - -::google::protobuf::Metadata ErrorResponse::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = ErrorResponse_descriptor_; - metadata.reflection = ErrorResponse_reflection_; - return metadata; -} - -#if PROTOBUF_INLINE_NOT_IN_HEADERS -// ErrorResponse - -// optional int32 error_code = 1; -void ErrorResponse::clear_error_code() { - error_code_ = 0; -} -::google::protobuf::int32 ErrorResponse::error_code() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ErrorResponse.error_code) - return error_code_; -} -void ErrorResponse::set_error_code(::google::protobuf::int32 value) { - - error_code_ = value; - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ErrorResponse.error_code) -} - -// optional string error_message = 2; -void ErrorResponse::clear_error_message() { - error_message_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -const ::std::string& ErrorResponse::error_message() const { - // @@protoc_insertion_point(field_get:grpc.reflection.v1alpha.ErrorResponse.error_message) - return error_message_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -void ErrorResponse::set_error_message(const ::std::string& value) { - - error_message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); - // @@protoc_insertion_point(field_set:grpc.reflection.v1alpha.ErrorResponse.error_message) -} -void ErrorResponse::set_error_message(const char* value) { - - error_message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:grpc.reflection.v1alpha.ErrorResponse.error_message) -} -void ErrorResponse::set_error_message(const char* value, size_t size) { - - error_message_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:grpc.reflection.v1alpha.ErrorResponse.error_message) -} -::std::string* ErrorResponse::mutable_error_message() { - - // @@protoc_insertion_point(field_mutable:grpc.reflection.v1alpha.ErrorResponse.error_message) - return error_message_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -::std::string* ErrorResponse::release_error_message() { - // @@protoc_insertion_point(field_release:grpc.reflection.v1alpha.ErrorResponse.error_message) - - return error_message_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} -void ErrorResponse::set_allocated_error_message(::std::string* error_message) { - if (error_message != NULL) { - - } else { - - } - error_message_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), error_message); - // @@protoc_insertion_point(field_set_allocated:grpc.reflection.v1alpha.ErrorResponse.error_message) -} - -inline const ErrorResponse* ErrorResponse::internal_default_instance() { - return &ErrorResponse_default_instance_.get(); -} -#endif // PROTOBUF_INLINE_NOT_IN_HEADERS - -// @@protoc_insertion_point(namespace_scope) - -} // namespace v1alpha -} // namespace reflection -} // namespace grpc - -// @@protoc_insertion_point(global_scope) diff --git a/src/cpp/server/dynamic_thread_pool.cc b/src/cpp/server/dynamic_thread_pool.cc index 4b226c2992d..1fdc2edb259 100644 --- a/src/cpp/server/dynamic_thread_pool.cc +++ b/src/cpp/server/dynamic_thread_pool.cc @@ -31,16 +31,16 @@ * */ -#include -#include +#include +#include #include "src/cpp/server/dynamic_thread_pool.h" namespace grpc { DynamicThreadPool::DynamicThread::DynamicThread(DynamicThreadPool* pool) : pool_(pool), - thd_(new grpc::thread(&DynamicThreadPool::DynamicThread::ThreadFunc, - this)) {} + thd_(new std::thread(&DynamicThreadPool::DynamicThread::ThreadFunc, + this)) {} DynamicThreadPool::DynamicThread::~DynamicThread() { thd_->join(); thd_.reset(); @@ -49,7 +49,7 @@ DynamicThreadPool::DynamicThread::~DynamicThread() { void DynamicThreadPool::DynamicThread::ThreadFunc() { pool_->ThreadFunc(); // Now that we have killed ourselves, we should reduce the thread count - grpc::unique_lock lock(pool_->mu_); + std::unique_lock lock(pool_->mu_); pool_->nthreads_--; // Move ourselves to dead list pool_->dead_threads_.push_back(this); @@ -62,7 +62,7 @@ void DynamicThreadPool::DynamicThread::ThreadFunc() { void DynamicThreadPool::ThreadFunc() { for (;;) { // Wait until work is available or we are shutting down. - grpc::unique_lock lock(mu_); + std::unique_lock lock(mu_); if (!shutdown_ && callbacks_.empty()) { // If there are too many threads waiting, then quit this thread if (threads_waiting_ >= reserve_threads_) { @@ -91,7 +91,7 @@ DynamicThreadPool::DynamicThreadPool(int reserve_threads) nthreads_(0), threads_waiting_(0) { for (int i = 0; i < reserve_threads_; i++) { - grpc::lock_guard lock(mu_); + std::lock_guard lock(mu_); nthreads_++; new DynamicThread(this); } @@ -104,7 +104,7 @@ void DynamicThreadPool::ReapThreads(std::list* tlist) { } DynamicThreadPool::~DynamicThreadPool() { - grpc::unique_lock lock(mu_); + std::unique_lock lock(mu_); shutdown_ = true; cv_.notify_all(); while (nthreads_ != 0) { @@ -114,7 +114,7 @@ DynamicThreadPool::~DynamicThreadPool() { } void DynamicThreadPool::Add(const std::function& callback) { - grpc::lock_guard lock(mu_); + std::lock_guard lock(mu_); // Add works to the callbacks list callbacks_.push(callback); // Increase pool size or notify as needed diff --git a/src/cpp/server/dynamic_thread_pool.h b/src/cpp/server/dynamic_thread_pool.h index 5ba7533c05f..4f8c4111cc0 100644 --- a/src/cpp/server/dynamic_thread_pool.h +++ b/src/cpp/server/dynamic_thread_pool.h @@ -34,24 +34,25 @@ #ifndef GRPC_INTERNAL_CPP_DYNAMIC_THREAD_POOL_H #define GRPC_INTERNAL_CPP_DYNAMIC_THREAD_POOL_H +#include #include #include +#include #include +#include -#include -#include #include #include "src/cpp/server/thread_pool_interface.h" namespace grpc { -class DynamicThreadPool GRPC_FINAL : public ThreadPoolInterface { +class DynamicThreadPool final : public ThreadPoolInterface { public: explicit DynamicThreadPool(int reserve_threads); ~DynamicThreadPool(); - void Add(const std::function& callback) GRPC_OVERRIDE; + void Add(const std::function& callback) override; private: class DynamicThread { @@ -61,12 +62,12 @@ class DynamicThreadPool GRPC_FINAL : public ThreadPoolInterface { private: DynamicThreadPool* pool_; - std::unique_ptr thd_; + std::unique_ptr thd_; void ThreadFunc(); }; - grpc::mutex mu_; - grpc::condition_variable cv_; - grpc::condition_variable shutdown_cv_; + std::mutex mu_; + std::condition_variable cv_; + std::condition_variable shutdown_cv_; bool shutdown_; std::queue> callbacks_; int reserve_threads_; diff --git a/src/cpp/server/insecure_server_credentials.cc b/src/cpp/server/insecure_server_credentials.cc index ef3cae5fd72..eb5931b7b00 100644 --- a/src/cpp/server/insecure_server_credentials.cc +++ b/src/cpp/server/insecure_server_credentials.cc @@ -38,14 +38,13 @@ namespace grpc { namespace { -class InsecureServerCredentialsImpl GRPC_FINAL : public ServerCredentials { +class InsecureServerCredentialsImpl final : public ServerCredentials { public: - int AddPortToServer(const grpc::string& addr, - grpc_server* server) GRPC_OVERRIDE { + int AddPortToServer(const grpc::string& addr, grpc_server* server) override { return grpc_server_add_insecure_http2_port(server, addr.c_str()); } void SetAuthMetadataProcessor( - const std::shared_ptr& processor) GRPC_OVERRIDE { + const std::shared_ptr& processor) override { (void)processor; GPR_ASSERT(0); // Should not be called on InsecureServerCredentials. } diff --git a/src/cpp/server/secure_server_credentials.h b/src/cpp/server/secure_server_credentials.h index 5460f4a02c3..3a301e60c24 100644 --- a/src/cpp/server/secure_server_credentials.h +++ b/src/cpp/server/secure_server_credentials.h @@ -44,7 +44,7 @@ namespace grpc { -class AuthMetadataProcessorAyncWrapper GRPC_FINAL { +class AuthMetadataProcessorAyncWrapper final { public: static void Destroy(void* wrapper); @@ -64,19 +64,18 @@ class AuthMetadataProcessorAyncWrapper GRPC_FINAL { std::shared_ptr processor_; }; -class SecureServerCredentials GRPC_FINAL : public ServerCredentials { +class SecureServerCredentials final : public ServerCredentials { public: explicit SecureServerCredentials(grpc_server_credentials* creds) : creds_(creds) {} - ~SecureServerCredentials() GRPC_OVERRIDE { + ~SecureServerCredentials() override { grpc_server_credentials_release(creds_); } - int AddPortToServer(const grpc::string& addr, - grpc_server* server) GRPC_OVERRIDE; + int AddPortToServer(const grpc::string& addr, grpc_server* server) override; void SetAuthMetadataProcessor( - const std::shared_ptr& processor) GRPC_OVERRIDE; + const std::shared_ptr& processor) override; private: grpc_server_credentials* creds_; diff --git a/src/cpp/server/server_builder.cc b/src/cpp/server/server_builder.cc index 2980b16c56c..00a90bb184c 100644 --- a/src/cpp/server/server_builder.cc +++ b/src/cpp/server/server_builder.cc @@ -34,7 +34,9 @@ #include #include +#include #include +#include #include #include @@ -54,6 +56,8 @@ static void do_plugin_list_init(void) { ServerBuilder::ServerBuilder() : max_receive_message_size_(-1), max_send_message_size_(-1), + sync_server_settings_(SyncServerSettings()), + resource_quota_(nullptr), generic_service_(nullptr) { gpr_once_init(&once_init_plugin_list, do_plugin_list_init); for (auto it = g_plugin_factory_list->begin(); @@ -61,6 +65,7 @@ ServerBuilder::ServerBuilder() auto& factory = *it; plugins_.emplace_back(factory()); } + // all compression algorithms enabled by default. enabled_compression_algorithms_bitset_ = (1u << GRPC_COMPRESS_ALGORITHMS_COUNT) - 1; @@ -70,6 +75,12 @@ ServerBuilder::ServerBuilder() sizeof(maybe_default_compression_algorithm_)); } +ServerBuilder::~ServerBuilder() { + if (resource_quota_ != nullptr) { + grpc_resource_quota_unref(resource_quota_); + } +} + std::unique_ptr ServerBuilder::AddCompletionQueue( bool is_frequently_polled) { ServerCompletionQueue* cq = new ServerCompletionQueue(is_frequently_polled); @@ -94,7 +105,7 @@ ServerBuilder& ServerBuilder::RegisterAsyncGenericService( gpr_log(GPR_ERROR, "Adding multiple AsyncGenericService is unsupported for now. " "Dropping the service %p", - service); + (void*)service); } else { generic_service_ = service; } @@ -107,6 +118,25 @@ ServerBuilder& ServerBuilder::SetOption( return *this; } +ServerBuilder& ServerBuilder::SetSyncServerOption( + ServerBuilder::SyncServerOption option, int val) { + switch (option) { + case NUM_CQS: + sync_server_settings_.num_cqs = val; + break; + case MIN_POLLERS: + sync_server_settings_.min_pollers = val; + break; + case MAX_POLLERS: + sync_server_settings_.max_pollers = val; + break; + case CQ_TIMEOUT_MSEC: + sync_server_settings_.cq_timeout_msec = val; + break; + } + return *this; +} + ServerBuilder& ServerBuilder::SetCompressionAlgorithmSupportStatus( grpc_compression_algorithm algorithm, bool enabled) { if (enabled) { @@ -130,6 +160,16 @@ ServerBuilder& ServerBuilder::SetDefaultCompressionAlgorithm( return *this; } +ServerBuilder& ServerBuilder::SetResourceQuota( + const grpc::ResourceQuota& resource_quota) { + if (resource_quota_ != nullptr) { + grpc_resource_quota_unref(resource_quota_); + } + resource_quota_ = resource_quota.c_resource_quota(); + grpc_resource_quota_ref(resource_quota_); + return *this; +} + ServerBuilder& ServerBuilder::AddListeningPort( const grpc::string& addr, std::shared_ptr creds, int* selected_port) { @@ -139,35 +179,24 @@ ServerBuilder& ServerBuilder::AddListeningPort( } std::unique_ptr ServerBuilder::BuildAndStart() { - std::unique_ptr thread_pool; - bool has_sync_methods = false; - for (auto it = services_.begin(); it != services_.end(); ++it) { - if ((*it)->service->has_synchronous_methods()) { - if (!thread_pool) { - thread_pool.reset(CreateDefaultThreadPool()); - has_sync_methods = true; - break; - } - } - } ChannelArguments args; for (auto option = options_.begin(); option != options_.end(); ++option) { (*option)->UpdateArguments(&args); (*option)->UpdatePlugins(&plugins_); } + for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { - if (!thread_pool && (*plugin)->has_sync_methods()) { - thread_pool.reset(CreateDefaultThreadPool()); - has_sync_methods = true; - } (*plugin)->UpdateChannelArguments(&args); } + if (max_receive_message_size_ >= 0) { args.SetInt(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH, max_receive_message_size_); } + if (max_send_message_size_ >= 0) { args.SetInt(GRPC_ARG_MAX_SEND_MESSAGE_LENGTH, max_send_message_size_); } + args.SetInt(GRPC_COMPRESSION_CHANNEL_ENABLED_ALGORITHMS_BITSET, enabled_compression_algorithms_bitset_); if (maybe_default_compression_level_.is_set) { @@ -178,27 +207,89 @@ std::unique_ptr ServerBuilder::BuildAndStart() { args.SetInt(GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM, maybe_default_compression_algorithm_.algorithm); } - std::unique_ptr server(new Server(thread_pool.release(), true, - max_receive_message_size_, &args)); + + if (resource_quota_ != nullptr) { + args.SetPointerWithVtable(GRPC_ARG_RESOURCE_QUOTA, resource_quota_, + grpc_resource_quota_arg_vtable()); + } + + // == Determine if the server has any syncrhonous methods == + bool has_sync_methods = false; + for (auto it = services_.begin(); it != services_.end(); ++it) { + if ((*it)->service->has_synchronous_methods()) { + has_sync_methods = true; + break; + } + } + + if (!has_sync_methods) { + for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { + if ((*plugin)->has_sync_methods()) { + has_sync_methods = true; + break; + } + } + } + + // If this is a Sync server, i.e a server expositing sync API, then the server + // needs to create some completion queues to listen for incoming requests. + // 'sync_server_cqs' are those internal completion queues. + // + // This is different from the completion queues added to the server via + // ServerBuilder's AddCompletionQueue() method (those completion queues + // are in 'cqs_' member variable of ServerBuilder object) + std::shared_ptr>> + sync_server_cqs(std::make_shared< + std::vector>>()); + + if (has_sync_methods) { + // This is a Sync server + gpr_log(GPR_INFO, + "Synchronous server. Num CQs: %d, Min pollers: %d, Max Pollers: " + "%d, CQ timeout (msec): %d", + sync_server_settings_.num_cqs, sync_server_settings_.min_pollers, + sync_server_settings_.max_pollers, + sync_server_settings_.cq_timeout_msec); + + // Create completion queues to listen to incoming rpc requests + for (int i = 0; i < sync_server_settings_.num_cqs; i++) { + sync_server_cqs->emplace_back(new ServerCompletionQueue()); + } + } + + std::unique_ptr server(new Server( + max_receive_message_size_, &args, sync_server_cqs, + sync_server_settings_.min_pollers, sync_server_settings_.max_pollers, + sync_server_settings_.cq_timeout_msec)); + ServerInitializer* initializer = server->initializer(); - // If the server has atleast one sync methods, we know that this is a Sync - // server or a Hybrid server and the completion queue (server->cq_) would be - // frequently polled. - int num_frequently_polled_cqs = has_sync_methods ? 1 : 0; - - for (auto cq = cqs_.begin(); cq != cqs_.end(); ++cq) { - // A completion queue that is not polled frequently (by calling Next() or - // AsyncNext()) is not safe to use for listening to incoming channels. - // Register all such completion queues as non-listening completion queues - // with the GRPC core library. - if ((*cq)->IsFrequentlyPolled()) { - grpc_server_register_completion_queue(server->server_, (*cq)->cq(), + // Register all the completion queues with the server. i.e + // 1. sync_server_cqs: internal completion queues created IF this is a sync + // server + // 2. cqs_: Completion queues added via AddCompletionQueue() call + + // All sync cqs (if any) are frequently polled by ThreadManager + int num_frequently_polled_cqs = sync_server_cqs->size(); + + for (auto it = sync_server_cqs->begin(); it != sync_server_cqs->end(); ++it) { + grpc_server_register_completion_queue(server->server_, (*it)->cq(), + nullptr); + } + + // cqs_ contains the completion queue added by calling the ServerBuilder's + // AddCompletionQueue() API. Some of them may not be frequently polled (i.e by + // calling Next() or AsyncNext()) and hence are not safe to be used for + // listening to incoming channels. Such completion queues must be registered + // as non-listening queues + for (auto it = cqs_.begin(); it != cqs_.end(); ++it) { + if ((*it)->IsFrequentlyPolled()) { + grpc_server_register_completion_queue(server->server_, (*it)->cq(), nullptr); num_frequently_polled_cqs++; } else { grpc_server_register_non_listening_completion_queue(server->server_, - (*cq)->cq(), nullptr); + (*it)->cq(), nullptr); } } @@ -214,9 +305,11 @@ std::unique_ptr ServerBuilder::BuildAndStart() { return nullptr; } } + for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { (*plugin)->InitServer(initializer); } + if (generic_service_) { server->RegisterAsyncGenericService(generic_service_); } else { @@ -229,6 +322,7 @@ std::unique_ptr ServerBuilder::BuildAndStart() { } } } + for (auto port = ports_.begin(); port != ports_.end(); port++) { int r = server->AddListeningPort(port->addr, port->creds.get()); if (!r) return nullptr; @@ -236,13 +330,16 @@ std::unique_ptr ServerBuilder::BuildAndStart() { *port->selected_port = r; } } + auto cqs_data = cqs_.empty() ? nullptr : &cqs_[0]; if (!server->Start(cqs_data, cqs_.size())) { return nullptr; } + for (auto plugin = plugins_.begin(); plugin != plugins_.end(); plugin++) { (*plugin)->Finish(initializer); } + return server; } diff --git a/src/cpp/server/server_cc.cc b/src/cpp/server/server_cc.cc index 3f89275370e..b7cfd6dbf11 100644 --- a/src/cpp/server/server_cc.cc +++ b/src/cpp/server/server_cc.cc @@ -1,5 +1,4 @@ /* - * * Copyright 2015, Google Inc. * All rights reserved. * @@ -52,15 +51,15 @@ #include #include "src/core/lib/profiling/timers.h" -#include "src/cpp/server/thread_pool_interface.h" +#include "src/cpp/thread_manager/thread_manager.h" namespace grpc { -class DefaultGlobalCallbacks GRPC_FINAL : public Server::GlobalCallbacks { +class DefaultGlobalCallbacks final : public Server::GlobalCallbacks { public: - ~DefaultGlobalCallbacks() GRPC_OVERRIDE {} - void PreSynchronousRequest(ServerContext* context) GRPC_OVERRIDE {} - void PostSynchronousRequest(ServerContext* context) GRPC_OVERRIDE {} + ~DefaultGlobalCallbacks() override {} + void PreSynchronousRequest(ServerContext* context) override {} + void PostSynchronousRequest(ServerContext* context) override {} }; static std::shared_ptr g_callbacks = nullptr; @@ -80,7 +79,7 @@ class Server::UnimplementedAsyncRequestContext { GenericServerAsyncReaderWriter generic_stream_; }; -class Server::UnimplementedAsyncRequest GRPC_FINAL +class Server::UnimplementedAsyncRequest final : public UnimplementedAsyncRequestContext, public GenericAsyncRequest { public: @@ -90,7 +89,7 @@ class Server::UnimplementedAsyncRequest GRPC_FINAL server_(server), cq_(cq) {} - bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE; + bool FinalizeResult(void** tag, bool* status) override; ServerContext* context() { return &server_context_; } GenericServerAsyncReaderWriter* stream() { return &generic_stream_; } @@ -102,13 +101,13 @@ class Server::UnimplementedAsyncRequest GRPC_FINAL typedef SneakyCallOpSet UnimplementedAsyncResponseOp; -class Server::UnimplementedAsyncResponse GRPC_FINAL +class Server::UnimplementedAsyncResponse final : public UnimplementedAsyncResponseOp { public: UnimplementedAsyncResponse(UnimplementedAsyncRequest* request); ~UnimplementedAsyncResponse() { delete request_; } - bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { + bool FinalizeResult(void** tag, bool* status) override { bool r = UnimplementedAsyncResponseOp::FinalizeResult(tag, status); delete this; return r; @@ -118,15 +117,12 @@ class Server::UnimplementedAsyncResponse GRPC_FINAL UnimplementedAsyncRequest* const request_; }; -class Server::ShutdownRequest GRPC_FINAL : public CompletionQueueTag { +class ShutdownTag : public CompletionQueueTag { public: - bool FinalizeResult(void** tag, bool* status) { - delete this; - return false; - } + bool FinalizeResult(void** tag, bool* status) { return false; } }; -class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag { +class Server::SyncRequest final : public CompletionQueueTag { public: SyncRequest(RpcServiceMethod* method, void* tag) : method_(method), @@ -147,36 +143,6 @@ class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag { grpc_metadata_array_destroy(&request_metadata_); } - static SyncRequest* Wait(CompletionQueue* cq, bool* ok) { - void* tag = nullptr; - *ok = false; - if (!cq->Next(&tag, ok)) { - return nullptr; - } - auto* mrd = static_cast(tag); - GPR_ASSERT(mrd->in_flight_); - return mrd; - } - - static bool AsyncWait(CompletionQueue* cq, SyncRequest** req, bool* ok, - gpr_timespec deadline) { - void* tag = nullptr; - *ok = false; - switch (cq->AsyncNext(&tag, ok, deadline)) { - case CompletionQueue::TIMEOUT: - *req = nullptr; - return true; - case CompletionQueue::SHUTDOWN: - *req = nullptr; - return false; - case CompletionQueue::GOT_EVENT: - *req = static_cast(tag); - GPR_ASSERT((*req)->in_flight_); - return true; - } - GPR_UNREACHABLE_CODE(return false); - } - void SetupRequest() { cq_ = grpc_completion_queue_create(nullptr); } void TeardownRequest() { @@ -204,7 +170,7 @@ class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag { } } - bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { + bool FinalizeResult(void** tag, bool* status) override { if (!*status) { grpc_completion_queue_destroy(cq_); } @@ -216,7 +182,7 @@ class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag { return true; } - class CallData GRPC_FINAL { + class CallData final { public: explicit CallData(Server* server, SyncRequest* mrd) : cq_(mrd->cq_), @@ -266,7 +232,6 @@ class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag { void* const tag_; bool in_flight_; const bool has_request_payload_; - uint32_t incoming_flags_; grpc_call* call_; grpc_call_details* call_details_; gpr_timespec deadline_; @@ -275,53 +240,158 @@ class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag { grpc_completion_queue* cq_; }; +// Implementation of ThreadManager. Each instance of SyncRequestThreadManager +// manages a pool of threads that poll for incoming Sync RPCs and call the +// appropriate RPC handlers +class Server::SyncRequestThreadManager : public ThreadManager { + public: + SyncRequestThreadManager(Server* server, CompletionQueue* server_cq, + std::shared_ptr global_callbacks, + int min_pollers, int max_pollers, + int cq_timeout_msec) + : ThreadManager(min_pollers, max_pollers), + server_(server), + server_cq_(server_cq), + cq_timeout_msec_(cq_timeout_msec), + global_callbacks_(global_callbacks) {} + + WorkStatus PollForWork(void** tag, bool* ok) override { + *tag = nullptr; + gpr_timespec deadline = + gpr_time_from_millis(cq_timeout_msec_, GPR_TIMESPAN); + + switch (server_cq_->AsyncNext(tag, ok, deadline)) { + case CompletionQueue::TIMEOUT: + return TIMEOUT; + case CompletionQueue::SHUTDOWN: + return SHUTDOWN; + case CompletionQueue::GOT_EVENT: + return WORK_FOUND; + } + + GPR_UNREACHABLE_CODE(return TIMEOUT); + } + + void DoWork(void* tag, bool ok) override { + SyncRequest* sync_req = static_cast(tag); + + if (!sync_req) { + // No tag. Nothing to work on. This is an unlikley scenario and possibly a + // bug in RPC Manager implementation. + gpr_log(GPR_ERROR, "Sync server. DoWork() was called with NULL tag"); + return; + } + + if (ok) { + // Calldata takes ownership of the completion queue inside sync_req + SyncRequest::CallData cd(server_, sync_req); + { + // Prepare for the next request + if (!IsShutdown()) { + sync_req->SetupRequest(); // Create new completion queue for sync_req + sync_req->Request(server_->c_server(), server_cq_->cq()); + } + } + + GPR_TIMER_SCOPE("cd.Run()", 0); + cd.Run(global_callbacks_); + } + // TODO (sreek) If ok is false here (which it isn't in case of + // grpc_request_registered_call), we should still re-queue the request + // object + } + + void AddSyncMethod(RpcServiceMethod* method, void* tag) { + sync_requests_.emplace_back(new SyncRequest(method, tag)); + } + + void AddUnknownSyncMethod() { + if (!sync_requests_.empty()) { + unknown_method_.reset(new RpcServiceMethod( + "unknown", RpcMethod::BIDI_STREAMING, new UnknownMethodHandler)); + sync_requests_.emplace_back( + new SyncRequest(unknown_method_.get(), nullptr)); + } + } + + void ShutdownAndDrainCompletionQueue() { + server_cq_->Shutdown(); + + // Drain any pending items from the queue + void* tag; + bool ok; + while (server_cq_->Next(&tag, &ok)) { + // Nothing to be done here + } + } + + void Start() { + if (!sync_requests_.empty()) { + for (auto m = sync_requests_.begin(); m != sync_requests_.end(); m++) { + (*m)->SetupRequest(); + (*m)->Request(server_->c_server(), server_cq_->cq()); + } + + Initialize(); // ThreadManager's Initialize() + } + } + + private: + Server* server_; + CompletionQueue* server_cq_; + int cq_timeout_msec_; + std::vector> sync_requests_; + std::unique_ptr unknown_method_; + std::shared_ptr global_callbacks_; +}; + static internal::GrpcLibraryInitializer g_gli_initializer; -Server::Server(ThreadPoolInterface* thread_pool, bool thread_pool_owned, - int max_receive_message_size, ChannelArguments* args) +Server::Server( + int max_receive_message_size, ChannelArguments* args, + std::shared_ptr>> + sync_server_cqs, + int min_pollers, int max_pollers, int sync_cq_timeout_msec) : max_receive_message_size_(max_receive_message_size), + sync_server_cqs_(sync_server_cqs), started_(false), shutdown_(false), shutdown_notified_(false), - num_running_cb_(0), - sync_methods_(new std::list), has_generic_service_(false), server_(nullptr), - thread_pool_(thread_pool), - thread_pool_owned_(thread_pool_owned), server_initializer_(new ServerInitializer(this)) { g_gli_initializer.summon(); gpr_once_init(&g_once_init_callbacks, InitGlobalCallbacks); global_callbacks_ = g_callbacks; global_callbacks_->UpdateArguments(args); + + for (auto it = sync_server_cqs_->begin(); it != sync_server_cqs_->end(); + it++) { + sync_req_mgrs_.emplace_back(new SyncRequestThreadManager( + this, (*it).get(), global_callbacks_, min_pollers, max_pollers, + sync_cq_timeout_msec)); + } + grpc_channel_args channel_args; args->SetChannelArgs(&channel_args); + server_ = grpc_server_create(&channel_args, nullptr); - if (thread_pool_ == nullptr) { - grpc_server_register_non_listening_completion_queue(server_, cq_.cq(), - nullptr); - } else { - grpc_server_register_completion_queue(server_, cq_.cq(), nullptr); - } } Server::~Server() { { - grpc::unique_lock lock(mu_); + std::unique_lock lock(mu_); if (started_ && !shutdown_) { lock.unlock(); Shutdown(); } else if (!started_) { - cq_.Shutdown(); + // Shutdown the completion queues + for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) { + (*it)->ShutdownAndDrainCompletionQueue(); + } } } - void* got_tag; - bool ok; - GPR_ASSERT(!cq_.Next(&got_tag, &ok)); + grpc_server_destroy(server_); - if (thread_pool_owned_) { - delete thread_pool_; - } - delete sync_methods_; } void Server::SetGlobalCallbacks(GlobalCallbacks* callbacks) { @@ -352,12 +422,14 @@ bool Server::RegisterService(const grpc::string* host, Service* service) { "Can only register an asynchronous service against one server."); service->server_ = this; } + const char* method_name = nullptr; for (auto it = service->methods_.begin(); it != service->methods_.end(); ++it) { if (it->get() == nullptr) { // Handled by generic service if any. continue; } + RpcServiceMethod* method = it->get(); void* tag = grpc_server_register_method( server_, method->name(), host ? host->c_str() : nullptr, @@ -367,11 +439,15 @@ bool Server::RegisterService(const grpc::string* host, Service* service) { method->name()); return false; } - if (method->handler() == nullptr) { + + if (method->handler() == nullptr) { // Async method method->set_server_tag(tag); } else { - sync_methods_->emplace_back(method, tag); + for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) { + (*it)->AddSyncMethod(method, tag); + } } + method_name = method->name(); } @@ -406,60 +482,65 @@ bool Server::Start(ServerCompletionQueue** cqs, size_t num_cqs) { grpc_server_start(server_); if (!has_generic_service_) { - if (!sync_methods_->empty()) { - unknown_method_.reset(new RpcServiceMethod( - "unknown", RpcMethod::BIDI_STREAMING, new UnknownMethodHandler)); - // Use of emplace_back with just constructor arguments is not accepted - // here by gcc-4.4 because it can't match the anonymous nullptr with a - // proper constructor implicitly. Construct the object and use push_back. - sync_methods_->push_back(SyncRequest(unknown_method_.get(), nullptr)); + for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) { + (*it)->AddUnknownSyncMethod(); } + for (size_t i = 0; i < num_cqs; i++) { if (cqs[i]->IsFrequentlyPolled()) { new UnimplementedAsyncRequest(this, cqs[i]); } } } - // Start processing rpcs. - if (!sync_methods_->empty()) { - for (auto m = sync_methods_->begin(); m != sync_methods_->end(); m++) { - m->SetupRequest(); - m->Request(server_, cq_.cq()); - } - ScheduleCallback(); + for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) { + (*it)->Start(); } return true; } void Server::ShutdownInternal(gpr_timespec deadline) { - grpc::unique_lock lock(mu_); + std::unique_lock lock(mu_); if (started_ && !shutdown_) { shutdown_ = true; - grpc_server_shutdown_and_notify(server_, cq_.cq(), new ShutdownRequest()); - cq_.Shutdown(); - lock.unlock(); - // Spin, eating requests until the completion queue is completely shutdown. - // If the deadline expires then cancel anything that's pending and keep - // spinning forever until the work is actually drained. - // Since nothing else needs to touch state guarded by mu_, holding it - // through this loop is fine. - SyncRequest* request; + + /// The completion queue to use for server shutdown completion notification + CompletionQueue shutdown_cq; + ShutdownTag shutdown_tag; // Dummy shutdown tag + grpc_server_shutdown_and_notify(server_, shutdown_cq.cq(), &shutdown_tag); + + // Shutdown all ThreadManagers. This will try to gracefully stop all the + // threads in the ThreadManagers (once they process any inflight requests) + for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) { + (*it)->Shutdown(); // ThreadManager's Shutdown() + } + + shutdown_cq.Shutdown(); + + void* tag; bool ok; - while (SyncRequest::AsyncWait(&cq_, &request, &ok, deadline)) { - if (request == NULL) { // deadline expired - grpc_server_cancel_all_calls(server_); - deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC); - } else if (ok) { - SyncRequest::CallData call_data(this, request); - } + CompletionQueue::NextStatus status = + shutdown_cq.AsyncNext(&tag, &ok, deadline); + + // If this timed out, it means we are done with the grace period for a clean + // shutdown. We should force a shutdown now by cancelling all inflight calls + if (status == CompletionQueue::NextStatus::TIMEOUT) { + grpc_server_cancel_all_calls(server_); + } + // Else in case of SHUTDOWN or GOT_EVENT, it means that the server has + // successfully shutdown + + // Wait for threads in all ThreadManagers to terminate + for (auto it = sync_req_mgrs_.begin(); it != sync_req_mgrs_.end(); it++) { + (*it)->Wait(); + (*it)->ShutdownAndDrainCompletionQueue(); } - lock.lock(); - // Wait for running callbacks to finish. - while (num_running_cb_ != 0) { - callback_cv_.wait(lock); + // Drain the shutdown queue (if the previous call to AsyncNext() timed out + // and we didn't remove the tag from the queue yet) + while (shutdown_cq.Next(&tag, &ok)) { + // Nothing to be done here. Just ignore ok and tag values } shutdown_notified_ = true; @@ -468,7 +549,7 @@ void Server::ShutdownInternal(gpr_timespec deadline) { } void Server::Wait() { - grpc::unique_lock lock(mu_); + std::unique_lock lock(mu_); while (started_ && !shutdown_notified_) { shutdown_cv_.wait(lock); } @@ -585,47 +666,6 @@ Server::UnimplementedAsyncResponse::UnimplementedAsyncResponse( request_->stream()->call_.PerformOps(this); } -void Server::ScheduleCallback() { - { - grpc::unique_lock lock(mu_); - num_running_cb_++; - } - thread_pool_->Add(std::bind(&Server::RunRpc, this)); -} - -void Server::RunRpc() { - // Wait for one more incoming rpc. - bool ok; - GPR_TIMER_SCOPE("Server::RunRpc", 0); - auto* mrd = SyncRequest::Wait(&cq_, &ok); - if (mrd) { - ScheduleCallback(); - if (ok) { - SyncRequest::CallData cd(this, mrd); - { - mrd->SetupRequest(); - grpc::unique_lock lock(mu_); - if (!shutdown_) { - mrd->Request(server_, cq_.cq()); - } else { - // destroy the structure that was created - mrd->TeardownRequest(); - } - } - GPR_TIMER_SCOPE("cd.Run()", 0); - cd.Run(global_callbacks_); - } - } - - { - grpc::unique_lock lock(mu_); - num_running_cb_--; - if (shutdown_) { - callback_cv_.notify_all(); - } - } -} - ServerInitializer* Server::initializer() { return server_initializer_.get(); } } // namespace grpc diff --git a/src/cpp/server/server_context.cc b/src/cpp/server/server_context.cc index 1ca6a2b906e..a66ec4ac841 100644 --- a/src/cpp/server/server_context.cc +++ b/src/cpp/server/server_context.cc @@ -33,9 +33,10 @@ #include +#include + #include #include -#include #include #include #include @@ -48,7 +49,7 @@ namespace grpc { // CompletionOp -class ServerContext::CompletionOp GRPC_FINAL : public CallOpSetInterface { +class ServerContext::CompletionOp final : public CallOpSetInterface { public: // initial refs: one in the server context, one in the cq CompletionOp() @@ -58,8 +59,8 @@ class ServerContext::CompletionOp GRPC_FINAL : public CallOpSetInterface { finalized_(false), cancelled_(0) {} - void FillOps(grpc_op* ops, size_t* nops) GRPC_OVERRIDE; - bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE; + void FillOps(grpc_op* ops, size_t* nops) override; + bool FinalizeResult(void** tag, bool* status) override; bool CheckCancelled(CompletionQueue* cq) { cq->TryPluck(this); @@ -76,20 +77,20 @@ class ServerContext::CompletionOp GRPC_FINAL : public CallOpSetInterface { private: bool CheckCancelledNoPluck() { - grpc::lock_guard g(mu_); + std::lock_guard g(mu_); return finalized_ ? (cancelled_ != 0) : false; } bool has_tag_; void* tag_; - grpc::mutex mu_; + std::mutex mu_; int refs_; bool finalized_; int cancelled_; }; void ServerContext::CompletionOp::Unref() { - grpc::unique_lock lock(mu_); + std::unique_lock lock(mu_); if (--refs_ == 0) { lock.unlock(); delete this; @@ -105,7 +106,7 @@ void ServerContext::CompletionOp::FillOps(grpc_op* ops, size_t* nops) { } bool ServerContext::CompletionOp::FinalizeResult(void** tag, bool* status) { - grpc::unique_lock lock(mu_); + std::unique_lock lock(mu_); finalized_ = true; bool ret = false; if (has_tag_) { diff --git a/src/cpp/thread_manager/thread_manager.cc b/src/cpp/thread_manager/thread_manager.cc new file mode 100644 index 00000000000..1450d009e4f --- /dev/null +++ b/src/cpp/thread_manager/thread_manager.cc @@ -0,0 +1,182 @@ +/* + * + * Copyright 2016, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "src/cpp/thread_manager/thread_manager.h" + +#include +#include +#include + +#include + +namespace grpc { + +ThreadManager::WorkerThread::WorkerThread(ThreadManager* thd_mgr) + : thd_mgr_(thd_mgr), thd_(&ThreadManager::WorkerThread::Run, this) {} + +void ThreadManager::WorkerThread::Run() { + thd_mgr_->MainWorkLoop(); + thd_mgr_->MarkAsCompleted(this); +} + +ThreadManager::WorkerThread::~WorkerThread() { thd_.join(); } + +ThreadManager::ThreadManager(int min_pollers, int max_pollers) + : shutdown_(false), + num_pollers_(0), + min_pollers_(min_pollers), + max_pollers_(max_pollers == -1 ? INT_MAX : max_pollers), + num_threads_(0) {} + +ThreadManager::~ThreadManager() { + { + std::unique_lock lock(mu_); + GPR_ASSERT(num_threads_ == 0); + } + + CleanupCompletedThreads(); +} + +void ThreadManager::Wait() { + std::unique_lock lock(mu_); + while (num_threads_ != 0) { + shutdown_cv_.wait(lock); + } +} + +void ThreadManager::Shutdown() { + std::unique_lock lock(mu_); + shutdown_ = true; +} + +bool ThreadManager::IsShutdown() { + std::unique_lock lock(mu_); + return shutdown_; +} + +void ThreadManager::MarkAsCompleted(WorkerThread* thd) { + { + std::unique_lock list_lock(list_mu_); + completed_threads_.push_back(thd); + } + + std::unique_lock lock(mu_); + num_threads_--; + if (num_threads_ == 0) { + shutdown_cv_.notify_one(); + } +} + +void ThreadManager::CleanupCompletedThreads() { + std::unique_lock lock(list_mu_); + for (auto thd = completed_threads_.begin(); thd != completed_threads_.end(); + thd = completed_threads_.erase(thd)) { + delete *thd; + } +} + +void ThreadManager::Initialize() { + for (int i = 0; i < min_pollers_; i++) { + MaybeCreatePoller(); + } +} + +// If the number of pollers (i.e threads currently blocked in PollForWork()) is +// less than max threshold (i.e max_pollers_) and the total number of threads is +// below the maximum threshold, we can let the current thread continue as poller +bool ThreadManager::MaybeContinueAsPoller() { + std::unique_lock lock(mu_); + if (shutdown_ || num_pollers_ > max_pollers_) { + return false; + } + + num_pollers_++; + return true; +} + +// Create a new poller if the current number of pollers i.e num_pollers_ (i.e +// threads currently blocked in PollForWork()) is below the threshold (i.e +// min_pollers_) and the total number of threads is below the maximum threshold +void ThreadManager::MaybeCreatePoller() { + std::unique_lock lock(mu_); + if (!shutdown_ && num_pollers_ < min_pollers_) { + num_pollers_++; + num_threads_++; + + // Create a new thread (which ends up calling the MainWorkLoop() function + new WorkerThread(this); + } +} + +void ThreadManager::MainWorkLoop() { + void* tag; + bool ok; + + /* + 1. Poll for work (i.e PollForWork()) + 2. After returning from PollForWork, reduce the number of pollers by 1. If + PollForWork() returned a TIMEOUT, then it may indicate that we have more + polling threads than needed. Check if the number of pollers is greater + than min_pollers and if so, terminate the thread. + 3. Since we are short of one poller now, see if a new poller has to be + created (i.e see MaybeCreatePoller() for more details) + 4. Do the actual work (DoWork()) + 5. After doing the work, see it this thread can resume polling work (i.e + see MaybeContinueAsPoller() for more details) */ + do { + WorkStatus work_status = PollForWork(&tag, &ok); + + { + std::unique_lock lock(mu_); + num_pollers_--; + + if (work_status == TIMEOUT && num_pollers_ > min_pollers_) { + break; + } + } + + // Note that MaybeCreatePoller does check for shutdown and creates a new + // thread only if ThreadManager is not shutdown + if (work_status == WORK_FOUND) { + MaybeCreatePoller(); + DoWork(tag, ok); + } + } while (MaybeContinueAsPoller()); + + CleanupCompletedThreads(); + + // If we are here, either ThreadManager is shutting down or it already has + // enough threads. +} + +} // namespace grpc diff --git a/src/cpp/thread_manager/thread_manager.h b/src/cpp/thread_manager/thread_manager.h new file mode 100644 index 00000000000..9c0569c62c1 --- /dev/null +++ b/src/cpp/thread_manager/thread_manager.h @@ -0,0 +1,160 @@ +/* + * + * Copyright 2016, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#ifndef GRPC_INTERNAL_CPP_THREAD_MANAGER_H +#define GRPC_INTERNAL_CPP_THREAD_MANAGER_H + +#include +#include +#include +#include +#include + +#include + +namespace grpc { + +class ThreadManager { + public: + explicit ThreadManager(int min_pollers, int max_pollers); + virtual ~ThreadManager(); + + // Initializes and Starts the Rpc Manager threads + void Initialize(); + + // The return type of PollForWork() function + enum WorkStatus { WORK_FOUND, SHUTDOWN, TIMEOUT }; + + // "Polls" for new work. + // If the return value is WORK_FOUND: + // - The implementaion of PollForWork() MAY set some opaque identifier to + // (identify the work item found) via the '*tag' parameter + // - The implementaion MUST set the value of 'ok' to 'true' or 'false'. A + // value of 'false' indicates some implemenation specific error (that is + // neither SHUTDOWN nor TIMEOUT) + // - ThreadManager does not interpret the values of 'tag' and 'ok' + // - ThreadManager WILL call DoWork() and pass '*tag' and 'ok' as input to + // DoWork() + // + // If the return value is SHUTDOWN:, + // - ThreadManager WILL NOT call DoWork() and terminates the thead + // + // If the return value is TIMEOUT:, + // - ThreadManager WILL NOT call DoWork() + // - ThreadManager MAY terminate the thread depending on the current number + // of active poller threads and mix_pollers/max_pollers settings + // - Also, the value of timeout is specific to the derived class + // implementation + virtual WorkStatus PollForWork(void** tag, bool* ok) = 0; + + // The implementation of DoWork() is supposed to perform the work found by + // PollForWork(). The tag and ok parameters are the same as returned by + // PollForWork() + // + // The implementation of DoWork() should also do any setup needed to ensure + // that the next call to PollForWork() (not necessarily by the current thread) + // actually finds some work + virtual void DoWork(void* tag, bool ok) = 0; + + // Mark the ThreadManager as shutdown and begin draining the work. This is a + // non-blocking call and the caller should call Wait(), a blocking call which + // returns only once the shutdown is complete + void Shutdown(); + + // Has Shutdown() been called + bool IsShutdown(); + + // A blocking call that returns only after the ThreadManager has shutdown and + // all the threads have drained all the outstanding work + void Wait(); + + private: + // Helper wrapper class around std::thread. This takes a ThreadManager object + // and starts a new std::thread to calls the Run() function. + // + // The Run() function calls ThreadManager::MainWorkLoop() function and once + // that completes, it marks the WorkerThread completed by calling + // ThreadManager::MarkAsCompleted() + class WorkerThread { + public: + WorkerThread(ThreadManager* thd_mgr); + ~WorkerThread(); + + private: + // Calls thd_mgr_->MainWorkLoop() and once that completes, calls + // thd_mgr_>MarkAsCompleted(this) to mark the thread as completed + void Run(); + + ThreadManager* thd_mgr_; + std::thread thd_; + }; + + // The main funtion in ThreadManager + void MainWorkLoop(); + + // Create a new poller if the number of current pollers is less than the + // minimum number of pollers needed (i.e min_pollers). + void MaybeCreatePoller(); + + // Returns true if the current thread can resume as a poller. i.e if the + // current number of pollers is less than the max_pollers. + bool MaybeContinueAsPoller(); + + void MarkAsCompleted(WorkerThread* thd); + void CleanupCompletedThreads(); + + // Protects shutdown_, num_pollers_ and num_threads_ + // TODO: sreek - Change num_pollers and num_threads_ to atomics + std::mutex mu_; + + bool shutdown_; + std::condition_variable shutdown_cv_; + + // Number of threads doing polling + int num_pollers_; + + // The minimum and maximum number of threads that should be doing polling + int min_pollers_; + int max_pollers_; + + // The total number of threads (includes threads includes the threads that are + // currently polling i.e num_pollers_) + int num_threads_; + + std::mutex list_mu_; + std::list completed_threads_; +}; + +} // namespace grpc + +#endif // GRPC_INTERNAL_CPP_THREAD_MANAGER_H diff --git a/src/cpp/util/time_cc.cc b/src/cpp/util/time_cc.cc index c43d848cc60..cd59a197032 100644 --- a/src/cpp/util/time_cc.cc +++ b/src/cpp/util/time_cc.cc @@ -32,9 +32,6 @@ */ #include - -#ifndef GRPC_CXX0X_NO_CHRONO - #include #include @@ -91,5 +88,3 @@ system_clock::time_point Timespec2Timepoint(gpr_timespec t) { } } // namespace grpc - -#endif // !GRPC_CXX0X_NO_CHRONO diff --git a/src/csharp/Grpc.Core/Internal/AsyncCall.cs b/src/csharp/Grpc.Core/Internal/AsyncCall.cs index 49d0a111efa..5e61e9ec129 100644 --- a/src/csharp/Grpc.Core/Internal/AsyncCall.cs +++ b/src/csharp/Grpc.Core/Internal/AsyncCall.cs @@ -52,9 +52,8 @@ namespace Grpc.Core.Internal // Completion of a pending unary response if not null. TaskCompletionSource unaryResponseTcs; - // TODO(jtattermusch): this field doesn't need to be initialized for unary response calls. - // Indicates that response streaming call has finished. - TaskCompletionSource streamingCallFinishedTcs = new TaskCompletionSource(); + // Completion of a streaming response call if not null. + TaskCompletionSource streamingResponseCallFinishedTcs; // TODO(jtattermusch): this field could be lazy-initialized (only if someone requests the response headers). // Response headers set here once received. @@ -198,6 +197,7 @@ namespace Grpc.Core.Internal byte[] payload = UnsafeSerialize(msg); + streamingResponseCallFinishedTcs = new TaskCompletionSource(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartServerStreaming(HandleFinished, payload, metadataArray, GetWriteFlagsForCall()); @@ -219,6 +219,7 @@ namespace Grpc.Core.Internal Initialize(details.Channel.CompletionQueue); + streamingResponseCallFinishedTcs = new TaskCompletionSource(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartDuplexStreaming(HandleFinished, metadataArray); @@ -276,13 +277,13 @@ namespace Grpc.Core.Internal } /// - /// Get the task that completes once if streaming call finishes with ok status and throws RpcException with given status otherwise. + /// Get the task that completes once if streaming response call finishes with ok status and throws RpcException with given status otherwise. /// - public Task StreamingCallFinishedTask + public Task StreamingResponseCallFinishedTask { get { - return streamingCallFinishedTcs.Task; + return streamingResponseCallFinishedTcs.Task; } } @@ -529,11 +530,11 @@ namespace Grpc.Core.Internal var status = receivedStatus.Status; if (status.StatusCode != StatusCode.OK) { - streamingCallFinishedTcs.SetException(new RpcException(status)); + streamingResponseCallFinishedTcs.SetException(new RpcException(status)); return; } - streamingCallFinishedTcs.SetResult(null); + streamingResponseCallFinishedTcs.SetResult(null); } } } diff --git a/src/csharp/Grpc.Core/Internal/ClientResponseStream.cs b/src/csharp/Grpc.Core/Internal/ClientResponseStream.cs index ad9423ff58c..65bf60269a5 100644 --- a/src/csharp/Grpc.Core/Internal/ClientResponseStream.cs +++ b/src/csharp/Grpc.Core/Internal/ClientResponseStream.cs @@ -73,7 +73,7 @@ namespace Grpc.Core.Internal if (result == null) { - await call.StreamingCallFinishedTask.ConfigureAwait(false); + await call.StreamingResponseCallFinishedTask.ConfigureAwait(false); return false; } return true; diff --git a/src/node/ext/byte_buffer.cc b/src/node/ext/byte_buffer.cc index a3f678f32c6..ad7d0ec8c89 100644 --- a/src/node/ext/byte_buffer.cc +++ b/src/node/ext/byte_buffer.cc @@ -44,8 +44,8 @@ namespace grpc { namespace node { +using Nan::MaybeLocal; -using v8::Context; using v8::Function; using v8::Local; using v8::Object; @@ -89,15 +89,19 @@ Local ByteBufferToBuffer(grpc_byte_buffer *buffer) { Local MakeFastBuffer(Local slowBuffer) { Nan::EscapableHandleScope scope; Local globalObj = Nan::GetCurrentContext()->Global(); + MaybeLocal constructorValue = Nan::Get( + globalObj, Nan::New("Buffer").ToLocalChecked()); Local bufferConstructor = Local::Cast( - globalObj->Get(Nan::New("Buffer").ToLocalChecked())); - Local consArgs[3] = { + constructorValue.ToLocalChecked()); + const int argc = 3; + Local consArgs[argc] = { slowBuffer, Nan::New(::node::Buffer::Length(slowBuffer)), Nan::New(0) }; - Local fastBuffer = bufferConstructor->NewInstance(3, consArgs); - return scope.Escape(fastBuffer); + MaybeLocal fastBuffer = Nan::NewInstance(bufferConstructor, + argc, consArgs); + return scope.Escape(fastBuffer.ToLocalChecked()); } } // namespace node } // namespace grpc diff --git a/src/node/ext/call.cc b/src/node/ext/call.cc index b48a7bd6987..191e763e0e7 100644 --- a/src/node/ext/call.cc +++ b/src/node/ext/call.cc @@ -669,16 +669,16 @@ NAN_METHOD(Call::New) { return Nan::ThrowTypeError("Call's fourth argument must be a string"); } call = new Call(wrapped_call); - info.This()->SetHiddenValue(Nan::New("channel_").ToLocalChecked(), - channel_object); + 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 = constructor->GetFunction()->NewInstance( - argc, argv); + MaybeLocal maybe_instance = Nan::NewInstance( + constructor->GetFunction(), argc, argv); if (maybe_instance.IsEmpty()) { // There's probably a pending exception return; diff --git a/src/node/ext/channel.cc b/src/node/ext/channel.cc index c4028170e73..5bc58b9b324 100644 --- a/src/node/ext/channel.cc +++ b/src/node/ext/channel.cc @@ -208,8 +208,8 @@ NAN_METHOD(Channel::New) { } else { const int argc = 3; Local argv[argc] = {info[0], info[1], info[2]}; - MaybeLocal maybe_instance = constructor->GetFunction()->NewInstance( - argc, argv); + MaybeLocal maybe_instance = Nan::NewInstance( + constructor->GetFunction(), argc, argv); if (maybe_instance.IsEmpty()) { // There's probably a pending exception return; diff --git a/src/node/ext/server.cc b/src/node/ext/server.cc index 29f31ff15ee..70d5b96f397 100644 --- a/src/node/ext/server.cc +++ b/src/node/ext/server.cc @@ -222,7 +222,7 @@ NAN_METHOD(Server::New) { const int argc = 1; Local argv[argc] = {info[0]}; MaybeLocal maybe_instance = - constructor->GetFunction()->NewInstance(argc, argv); + Nan::NewInstance(constructor->GetFunction(), argc, argv); if (maybe_instance.IsEmpty()) { // There's probably a pending exception return; diff --git a/src/node/performance/benchmark_client_express.js b/src/node/performance/benchmark_client_express.js new file mode 100644 index 00000000000..675eb5f2884 --- /dev/null +++ b/src/node/performance/benchmark_client_express.js @@ -0,0 +1,291 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/** + * 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); + new_options.agent = new protocol.Agent(new_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(); + + 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(); + 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)); + makeCall(client_options); + 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; + }); + } + } + + 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(); + + 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 histogram = this.histogram; + if (reset) { + this.last_wall_time = process.hrtime(); + 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, + // Not sure how to measure these values + time_user: 0, + time_system: 0 + }; +}; + +/** + * 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 index 70cee9979b1..6abde2e17af 100644 --- a/src/node/performance/benchmark_server.js +++ b/src/node/performance/benchmark_server.js @@ -40,6 +40,8 @@ var fs = require('fs'); var path = require('path'); +var EventEmitter = require('events'); +var util = require('util'); var genericService = require('./generic_service'); @@ -138,12 +140,15 @@ function BenchmarkServer(host, port, tls, generic, response_size) { 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.emit('started'); }; /** diff --git a/src/node/performance/benchmark_server_express.js b/src/node/performance/benchmark_server_express.js new file mode 100644 index 00000000000..065bcf660b6 --- /dev/null +++ b/src/node/performance/benchmark_server_express.js @@ -0,0 +1,109 @@ +/* + * + * Copyright 2016, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/** + * 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.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); + if (reset) { + this.last_wall_time = process.hrtime(); + } + return { + time_elapsed: wall_time_diff[0] + wall_time_diff[1] / 1e9, + // Not sure how to measure these values + time_user: 0, + time_system: 0 + }; +}; + +BenchmarkServer.prototype.stop = function(callback) { + this.server.close(callback); +}; + +module.exports = BenchmarkServer; diff --git a/src/node/performance/worker.js b/src/node/performance/worker.js index 7ef9b84fe76..030bf7d7ba0 100644 --- a/src/node/performance/worker.js +++ b/src/node/performance/worker.js @@ -34,18 +34,18 @@ 'use strict'; var console = require('console'); -var worker_service_impl = require('./worker_service_impl'); +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) { +function runServer(port, benchmark_impl) { var server_creds = grpc.ServerCredentials.createInsecure(); var server = new grpc.Server(); server.addProtoService(serviceProto.WorkerService.service, - worker_service_impl); + new WorkerServiceImpl(benchmark_impl, server)); var address = '0.0.0.0:' + port; server.bind(address, server_creds); server.start(); @@ -57,9 +57,9 @@ if (require.main === module) { Error.stackTraceLimit = Infinity; var parseArgs = require('minimist'); var argv = parseArgs(process.argv, { - string: ['driver_port'] + string: ['driver_port', 'benchmark_impl'] }); - runServer(argv.driver_port); + 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 index 4b5cb8f9c21..3f317f64294 100644 --- a/src/node/performance/worker_service_impl.js +++ b/src/node/performance/worker_service_impl.js @@ -38,121 +38,141 @@ var console = require('console'); var BenchmarkClient = require('./benchmark_client'); var BenchmarkServer = require('./benchmark_server'); -exports.quitWorker = function quitWorker(call, callback) { - callback(null, {}); - process.exit(0); -} +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); + } -exports.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; + this.quitWorker = function quitWorker(call, callback) { + server.tryShutdown(function() { + callback(null, {}); + }); + }; + + 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)); + } + 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)); + } + stats = client.mark(); + call.write({ + stats: stats + }); break; - case 'simple_params': - req_size = setup.payload_config.simple_params.req_size; - resp_size = setup.payload_config.simple_params.resp_size; - generic = false; + 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: - call.emit('error', new Error('Unsupported PayloadConfig type' + - setup.payload_config.payload)); + throw new Error('Nonexistent client argtype option: ' + request.argtype); } - switch (setup.load_params.load) { - case 'closed_loop': - client.startClosedLoop(setup.outstanding_rpcs_per_channel, - setup.rpc_type, req_size, resp_size, generic); + }); + 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); + server = new BenchmarkServer('[::]', request.setup.port, + request.setup.security_params); + server.on('started', function() { + stats = server.mark(); + call.write({ + stats: stats, + port: server.getPort() + }); + }); + server.start(); break; - case 'poisson': - client.startPoisson(setup.outstanding_rpcs_per_channel, - setup.rpc_type, req_size, resp_size, - setup.load_params.poisson.offered_load, generic); + 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: - call.emit('error', new Error('Unsupported LoadParams type' + - setup.load_params.load)); + throw new Error('Nonexistent server argtype option'); } - 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(); }); - }); -}; - -exports.runServer = function runServer(call) { - var server; - call.on('data', function(request) { - var stats; - switch (request.argtype) { - case 'setup': - console.log('ServerConfig %j', request.setup); - server = new BenchmarkServer('[::]', request.setup.port, - request.setup.security_params); - server.start(); - stats = server.mark(); - call.write({ - stats: stats, - port: server.getPort() + call.on('end', function() { + server.stop(function() { + call.end(); }); - 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(); }); - }); -}; + }; -exports.coreCount = function coreCount(call, callback) { - callback(null, {cores: os.cpus().length}); + this.coreCount = function coreCount(call, callback) { + callback(null, {cores: os.cpus().length}); + }; }; diff --git a/src/node/src/common.js b/src/node/src/common.js index 22159dd39f7..c6c6d597a88 100644 --- a/src/node/src/common.js +++ b/src/node/src/common.js @@ -141,7 +141,7 @@ exports.getProtobufServiceAttrs = function getProtobufServiceAttrs(service, binaryAsBase64 = options.binaryAsBase64; longsAsStrings = options.longsAsStrings; } - return _.object(_.map(service.children, function(method) { + return _.fromPairs(_.map(service.children, function(method) { return [_.camelCase(method.name), { path: prefix + method.name, requestStream: method.requestStream, diff --git a/src/objective-c/!ProtoCompiler-gRPCPlugin.podspec b/src/objective-c/!ProtoCompiler-gRPCPlugin.podspec index 0c3c3216abe..6e594fd3edc 100644 --- a/src/objective-c/!ProtoCompiler-gRPCPlugin.podspec +++ b/src/objective-c/!ProtoCompiler-gRPCPlugin.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-gRPCPlugin' - v = '1.0.0' + v = '1.0.1' s.version = v s.summary = 'The gRPC ProtoC plugin generates Objective-C files from .proto services.' s.description = <<-DESC @@ -95,7 +95,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.0.0' + s.dependency '!ProtoCompiler', '3.0.2' # For the Protobuf dependency not to complain: s.ios.deployment_target = '7.1' s.osx.deployment_target = '10.9' diff --git a/src/objective-c/!ProtoCompiler.podspec b/src/objective-c/!ProtoCompiler.podspec index 5018dedc066..b55f6c93c62 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.0.0' + v = '3.0.2' 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/BoringSSL.podspec b/src/objective-c/BoringSSL.podspec index e14f39b898c..47b5b1a2e7b 100644 --- a/src/objective-c/BoringSSL.podspec +++ b/src/objective-c/BoringSSL.podspec @@ -31,7 +31,7 @@ Pod::Spec.new do |s| s.name = 'BoringSSL' - version = '6.0' + version = '7.0' s.version = version s.summary = 'BoringSSL is a fork of OpenSSL that is designed to meet Google’s needs.' # Adapted from the homepage: @@ -70,7 +70,7 @@ Pod::Spec.new do |s| s.source = { :git => 'https://boringssl.googlesource.com/boringssl', :tag => "version_for_cocoapods_#{version}", - # :commit => '4ac2dc4c0d48ca45da4f66c40e60d6b425fa94a3', + # :commit => '4fec04b48406111cb88fdd8d196253adc54f7a31', } name = 'openssl' @@ -388,42 +388,42 @@ Pod::Spec.new do |s| 0x28340c19, 0x283480ac, 0x283500ea, - 0x2c322843, - 0x2c32a851, - 0x2c332863, - 0x2c33a875, - 0x2c342889, - 0x2c34a89b, - 0x2c3528b6, - 0x2c35a8c8, - 0x2c3628db, + 0x2c322910, + 0x2c32a91e, + 0x2c332930, + 0x2c33a942, + 0x2c342956, + 0x2c34a968, + 0x2c352983, + 0x2c35a995, + 0x2c3629a8, 0x2c36832d, - 0x2c3728e8, - 0x2c37a8fa, - 0x2c38290d, - 0x2c38a924, - 0x2c392932, - 0x2c39a942, - 0x2c3a2954, - 0x2c3aa968, - 0x2c3b2979, - 0x2c3ba998, - 0x2c3c29ac, - 0x2c3ca9c2, - 0x2c3d29db, - 0x2c3da9f8, - 0x2c3e2a09, - 0x2c3eaa17, - 0x2c3f2a2f, - 0x2c3faa47, - 0x2c402a54, + 0x2c3729b5, + 0x2c37a9c7, + 0x2c3829da, + 0x2c38a9f1, + 0x2c3929ff, + 0x2c39aa0f, + 0x2c3a2a21, + 0x2c3aaa35, + 0x2c3b2a46, + 0x2c3baa65, + 0x2c3c2a79, + 0x2c3caa8f, + 0x2c3d2aa8, + 0x2c3daac5, + 0x2c3e2ad6, + 0x2c3eaae4, + 0x2c3f2afc, + 0x2c3fab14, + 0x2c402b21, 0x2c4090e7, - 0x2c412a65, - 0x2c41aa78, + 0x2c412b32, + 0x2c41ab45, 0x2c4210c0, - 0x2c42aa89, + 0x2c42ab56, 0x2c430720, - 0x2c43a98a, + 0x2c43aa57, 0x30320000, 0x30328015, 0x3033001f, @@ -576,174 +576,183 @@ Pod::Spec.new do |s| 0x403b9861, 0x403c0064, 0x403c8083, - 0x403d1890, - 0x403d98a6, - 0x403e18b5, - 0x403e98c8, - 0x403f18e2, - 0x403f98f0, - 0x40401905, - 0x40409919, - 0x40411936, - 0x40419951, - 0x4042196a, - 0x4042997d, - 0x40431991, - 0x404399a9, - 0x404419c0, + 0x403d18aa, + 0x403d98c0, + 0x403e18cf, + 0x403e98e2, + 0x403f18fc, + 0x403f990a, + 0x4040191f, + 0x40409933, + 0x40411950, + 0x4041996b, + 0x40421984, + 0x40429997, + 0x404319ab, + 0x404399c3, + 0x404419da, 0x404480ac, - 0x404519d5, - 0x404599e7, - 0x40461a0b, - 0x40469a2b, - 0x40471a39, - 0x40479a60, - 0x40481a89, - 0x40489aa2, - 0x40491ab9, - 0x40499ad3, - 0x404a1aea, - 0x404a9b08, - 0x404b1b20, - 0x404b9b37, - 0x404c1b4d, - 0x404c9b5f, - 0x404d1b80, - 0x404d9ba2, - 0x404e1bb6, - 0x404e9bc3, - 0x404f1bf0, - 0x404f9c19, - 0x40501c43, - 0x40509c57, - 0x40511c72, - 0x40519c82, - 0x40521c99, - 0x40529cbd, - 0x40531cd5, - 0x40539ce8, - 0x40541cfd, - 0x40549d20, - 0x40551d2e, - 0x40559d4b, - 0x40561d58, - 0x40569d71, - 0x40571d89, - 0x40579d9c, - 0x40581db1, - 0x40589dc3, - 0x40591df2, - 0x40599e0b, - 0x405a1e1f, - 0x405a9e2f, - 0x405b1e47, - 0x405b9e58, - 0x405c1e6b, - 0x405c9e7c, - 0x405d1e89, - 0x405d9ea0, - 0x405e1ec0, + 0x404519ef, + 0x40459a01, + 0x40461a25, + 0x40469a45, + 0x40471a53, + 0x40479a7a, + 0x40481ab7, + 0x40489ad0, + 0x40491ae7, + 0x40499b01, + 0x404a1b18, + 0x404a9b36, + 0x404b1b4e, + 0x404b9b65, + 0x404c1b7b, + 0x404c9b8d, + 0x404d1bae, + 0x404d9bd0, + 0x404e1be4, + 0x404e9bf1, + 0x404f1c1e, + 0x404f9c47, + 0x40501c71, + 0x40509c85, + 0x40511ca0, + 0x40519cb0, + 0x40521cc7, + 0x40529ceb, + 0x40531d03, + 0x40539d16, + 0x40541d2b, + 0x40549d4e, + 0x40551d5c, + 0x40559d79, + 0x40561d86, + 0x40569d9f, + 0x40571db7, + 0x40579dca, + 0x40581ddf, + 0x40589e06, + 0x40591e35, + 0x40599e62, + 0x405a1e76, + 0x405a9e86, + 0x405b1e9e, + 0x405b9eaf, + 0x405c1ec2, + 0x405c9ee3, + 0x405d1ef0, + 0x405d9f07, + 0x405e1f27, 0x405e8a95, - 0x405f1ee1, - 0x405f9eee, - 0x40601efc, - 0x40609f1e, - 0x40611f46, - 0x40619f5b, - 0x40621f72, - 0x40629f83, - 0x40631f94, - 0x40639fa9, - 0x40641fc0, - 0x40649fd1, - 0x40651fec, - 0x4065a003, - 0x4066201b, - 0x4066a045, - 0x40672070, - 0x4067a091, - 0x406820a4, - 0x4068a0c5, - 0x406920f7, - 0x4069a125, - 0x406a2146, - 0x406aa166, - 0x406b22ee, - 0x406ba311, - 0x406c2327, - 0x406ca553, - 0x406d2582, - 0x406da5aa, - 0x406e25c3, - 0x406ea5db, - 0x406f25fa, - 0x406fa60f, - 0x40702622, - 0x4070a63f, + 0x405f1f48, + 0x405f9f55, + 0x40601f63, + 0x40609f85, + 0x40611fad, + 0x40619fc2, + 0x40621fd9, + 0x40629fea, + 0x40631ffb, + 0x4063a010, + 0x40642027, + 0x4064a053, + 0x4065206e, + 0x4065a085, + 0x4066209d, + 0x4066a0c7, + 0x406720f2, + 0x4067a113, + 0x40682126, + 0x4068a147, + 0x40692179, + 0x4069a1a7, + 0x406a21c8, + 0x406aa1e8, + 0x406b2370, + 0x406ba393, + 0x406c23a9, + 0x406ca60b, + 0x406d263a, + 0x406da662, + 0x406e2690, + 0x406ea6a8, + 0x406f26c7, + 0x406fa6dc, + 0x407026ef, + 0x4070a70c, 0x40710800, - 0x4071a651, - 0x40722664, - 0x4072a67d, - 0x40732695, + 0x4071a71e, + 0x40722731, + 0x4072a74a, + 0x40732762, 0x4073936d, - 0x407426a9, - 0x4074a6c3, - 0x407526d4, - 0x4075a6e8, - 0x407626f6, + 0x40742776, + 0x4074a790, + 0x407527a1, + 0x4075a7b5, + 0x407627c3, 0x407691aa, - 0x4077271b, - 0x4077a73d, - 0x40782758, - 0x4078a791, - 0x407927a8, - 0x4079a7be, - 0x407a27ca, - 0x407aa7dd, - 0x407b27f2, - 0x407ba804, - 0x407c2819, - 0x407ca822, - 0x407d20e0, - 0x407d9c29, - 0x407e276d, - 0x407e9dd3, - 0x407f1a4d, - 0x407f986d, - 0x40801c00, - 0x40809a75, - 0x40811cab, - 0x40819bda, - 0x41f42219, - 0x41f922ab, - 0x41fe219e, - 0x41fea37a, - 0x41ff246b, - 0x42032232, - 0x42082254, - 0x4208a290, - 0x42092182, - 0x4209a2ca, - 0x420a21d9, - 0x420aa1b9, - 0x420b21f9, - 0x420ba272, - 0x420c2487, - 0x420ca347, - 0x420d2361, - 0x420da398, - 0x421223b2, - 0x4217244e, - 0x4217a3f4, - 0x421c2416, - 0x421f23d1, - 0x4221249e, - 0x42262431, - 0x422b2537, - 0x422ba500, - 0x422c251f, - 0x422ca4da, - 0x422d24b9, + 0x407727e8, + 0x4077a80a, + 0x40782825, + 0x4078a85e, + 0x40792875, + 0x4079a88b, + 0x407a2897, + 0x407aa8aa, + 0x407b28bf, + 0x407ba8d1, + 0x407c28e6, + 0x407ca8ef, + 0x407d2162, + 0x407d9c57, + 0x407e283a, + 0x407e9e16, + 0x407f1a67, + 0x407f9887, + 0x40801c2e, + 0x40809a8f, + 0x40811cd9, + 0x40819c08, + 0x4082267b, + 0x4082986d, + 0x40831df1, + 0x4083a038, + 0x40841aa3, + 0x40849e4e, + 0x40851ed3, + 0x41f4229b, + 0x41f9232d, + 0x41fe2220, + 0x41fea3fc, + 0x41ff24ed, + 0x420322b4, + 0x420822d6, + 0x4208a312, + 0x42092204, + 0x4209a34c, + 0x420a225b, + 0x420aa23b, + 0x420b227b, + 0x420ba2f4, + 0x420c2509, + 0x420ca3c9, + 0x420d23e3, + 0x420da41a, + 0x42122434, + 0x421724d0, + 0x4217a476, + 0x421c2498, + 0x421f2453, + 0x42212520, + 0x422624b3, + 0x422b25ef, + 0x422ba59d, + 0x422c25d7, + 0x422ca55c, + 0x422d253b, + 0x422da5bc, + 0x422e2582, 0x4432072b, 0x4432873a, 0x44330746, @@ -786,69 +795,69 @@ Pod::Spec.new do |s| 0x4c3d136d, 0x4c3d937c, 0x4c3e1389, - 0x50322a9b, - 0x5032aaaa, - 0x50332ab5, - 0x5033aac5, - 0x50342ade, - 0x5034aaf8, - 0x50352b06, - 0x5035ab1c, - 0x50362b2e, - 0x5036ab44, - 0x50372b5d, - 0x5037ab70, - 0x50382b88, - 0x5038ab99, - 0x50392bae, - 0x5039abc2, - 0x503a2be2, - 0x503aabf8, - 0x503b2c10, - 0x503bac22, - 0x503c2c3e, - 0x503cac55, - 0x503d2c6e, - 0x503dac84, - 0x503e2c91, - 0x503eaca7, - 0x503f2cb9, + 0x50322b68, + 0x5032ab77, + 0x50332b82, + 0x5033ab92, + 0x50342bab, + 0x5034abc5, + 0x50352bd3, + 0x5035abe9, + 0x50362bfb, + 0x5036ac11, + 0x50372c2a, + 0x5037ac3d, + 0x50382c55, + 0x5038ac66, + 0x50392c7b, + 0x5039ac8f, + 0x503a2caf, + 0x503aacc5, + 0x503b2cdd, + 0x503bacef, + 0x503c2d0b, + 0x503cad22, + 0x503d2d3b, + 0x503dad51, + 0x503e2d5e, + 0x503ead74, + 0x503f2d86, 0x503f8382, - 0x50402ccc, - 0x5040acdc, - 0x50412cf6, - 0x5041ad05, - 0x50422d1f, - 0x5042ad3c, - 0x50432d4c, - 0x5043ad5c, - 0x50442d6b, + 0x50402d99, + 0x5040ada9, + 0x50412dc3, + 0x5041add2, + 0x50422dec, + 0x5042ae09, + 0x50432e19, + 0x5043ae29, + 0x50442e38, 0x5044843f, - 0x50452d7f, - 0x5045ad9d, - 0x50462db0, - 0x5046adc6, - 0x50472dd8, - 0x5047aded, - 0x50482e13, - 0x5048ae21, - 0x50492e34, - 0x5049ae49, - 0x504a2e5f, - 0x504aae6f, - 0x504b2e8f, - 0x504baea2, - 0x504c2ec5, - 0x504caef3, - 0x504d2f05, - 0x504daf22, - 0x504e2f3d, - 0x504eaf59, - 0x504f2f6b, - 0x504faf82, - 0x50502f91, + 0x50452e4c, + 0x5045ae6a, + 0x50462e7d, + 0x5046ae93, + 0x50472ea5, + 0x5047aeba, + 0x50482ee0, + 0x5048aeee, + 0x50492f01, + 0x5049af16, + 0x504a2f2c, + 0x504aaf3c, + 0x504b2f5c, + 0x504baf6f, + 0x504c2f92, + 0x504cafc0, + 0x504d2fd2, + 0x504dafef, + 0x504e300a, + 0x504eb026, + 0x504f3038, + 0x504fb04f, + 0x5050305e, 0x505086ef, - 0x50512fa4, + 0x50513071, 0x58320ec9, 0x68320e8b, 0x68328c25, @@ -1209,6 +1218,7 @@ Pod::Spec.new do |s| "BAD_SSL_FILETYPE\\0" "BAD_WRITE_RETRY\\0" "BIO_NOT_SET\\0" + "BLOCK_CIPHER_PAD_IS_WRONG\\0" "BUFFERED_MESSAGES_ON_CIPHER_CHANGE\\0" "CA_DN_LENGTH_MISMATCH\\0" "CA_DN_TOO_LONG\\0" @@ -1233,6 +1243,7 @@ Pod::Spec.new do |s| "DOWNGRADE_DETECTED\\0" "DTLS_MESSAGE_TOO_BIG\\0" "DUPLICATE_EXTENSION\\0" + "DUPLICATE_KEY_SHARE\\0" "ECC_CERT_NOT_FOR_SIGNING\\0" "EMS_STATE_INCONSISTENT\\0" "ENCRYPTED_LENGTH_TOO_LONG\\0" @@ -1270,15 +1281,18 @@ Pod::Spec.new do |s| "NO_CERTIFICATE_SET\\0" "NO_CIPHERS_AVAILABLE\\0" "NO_CIPHERS_PASSED\\0" + "NO_CIPHERS_SPECIFIED\\0" "NO_CIPHER_MATCH\\0" "NO_COMMON_SIGNATURE_ALGORITHMS\\0" "NO_COMPRESSION_SPECIFIED\\0" + "NO_GROUPS_SPECIFIED\\0" "NO_METHOD_SPECIFIED\\0" "NO_P256_SUPPORT\\0" "NO_PRIVATE_KEY_ASSIGNED\\0" "NO_RENEGOTIATION\\0" "NO_REQUIRED_DIGEST\\0" "NO_SHARED_CIPHER\\0" + "NO_SHARED_GROUP\\0" "NULL_SSL_CTX\\0" "NULL_SSL_METHOD_PASSED\\0" "OLD_SESSION_CIPHER_NOT_RETURNED\\0" @@ -1294,6 +1308,7 @@ Pod::Spec.new do |s| "READ_TIMEOUT_EXPIRED\\0" "RECORD_LENGTH_MISMATCH\\0" "RECORD_TOO_LARGE\\0" + "RENEGOTIATION_EMS_MISMATCH\\0" "RENEGOTIATION_ENCODING_ERR\\0" "RENEGOTIATION_MISMATCH\\0" "REQUIRED_CIPHER_MISSING\\0" @@ -1338,12 +1353,15 @@ Pod::Spec.new do |s| "TLSV1_ALERT_USER_CANCELLED\\0" "TLSV1_BAD_CERTIFICATE_HASH_VALUE\\0" "TLSV1_BAD_CERTIFICATE_STATUS_RESPONSE\\0" + "TLSV1_CERTIFICATE_REQUIRED\\0" "TLSV1_CERTIFICATE_UNOBTAINABLE\\0" + "TLSV1_UNKNOWN_PSK_IDENTITY\\0" "TLSV1_UNRECOGNIZED_NAME\\0" "TLSV1_UNSUPPORTED_EXTENSION\\0" "TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST\\0" "TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG\\0" "TOO_MANY_EMPTY_FRAGMENTS\\0" + "TOO_MANY_KEY_UPDATES\\0" "TOO_MANY_WARNING_ALERTS\\0" "UNABLE_TO_FIND_ECDH_PARAMETERS\\0" "UNEXPECTED_EXTENSION\\0" diff --git a/src/objective-c/CronetFramework.podspec b/src/objective-c/CronetFramework.podspec index 3ebcacf0554..2f47b02c0c0 100644 --- a/src/objective-c/CronetFramework.podspec +++ b/src/objective-c/CronetFramework.podspec @@ -30,14 +30,47 @@ Pod::Spec.new do |s| s.name = "CronetFramework" - s.version = "0.0.2" + s.version = "0.0.3" s.summary = "Cronet, precompiled and used as a framework." s.homepage = "http://chromium.org" - s.license = { :type => 'BSD' } + s.license = { + :type => 'BSD', + :text => <<-LICENSE + Copyright 2015, Google Inc. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following disclaimer + in the documentation and/or other materials provided with the + distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + LICENSE + } s.vendored_framework = "Cronet.framework" s.author = "The Chromium Authors" - s.ios.deployment_target = "7.1" + s.ios.deployment_target = "8.0" s.source = { :http => 'https://storage.googleapis.com/grpc-precompiled-binaries/cronet/Cronet.framework.zip' } s.preserve_paths = "Cronet.framework" s.public_header_files = "Cronet.framework/Headers/**/*{.h}" + s.source_files = "Cronet.framework/Headers/**/*{.h}" end diff --git a/src/objective-c/GRPCClient/GRPCCall+ChannelArg.h b/src/objective-c/GRPCClient/GRPCCall+ChannelArg.h index c1623a00687..4a3f3fa4a1a 100644 --- a/src/objective-c/GRPCClient/GRPCCall+ChannelArg.h +++ b/src/objective-c/GRPCClient/GRPCCall+ChannelArg.h @@ -40,18 +40,15 @@ @interface GRPCCall (ChannelArg) /** - * Use the provided @c userAgentPrefix at the beginning of the HTTP User Agent - * string for all calls to the specified @c host. + * Use the provided @c userAgentPrefix at the beginning of the HTTP User Agent string for all calls + * to the specified @c host. */ -+ (void)setUserAgentPrefix:(nonnull NSString *)userAgentPrefix - forHost:(nonnull NSString *)host; ++ (void)setUserAgentPrefix:(nonnull NSString *)userAgentPrefix forHost:(nonnull NSString *)host; -/** The default response size limit is 4MB. Set this to override that default. - */ +/** The default response size limit is 4MB. Set this to override that default. */ + (void)setResponseSizeLimit:(NSUInteger)limit forHost:(nonnull NSString *)host; -+ (void)closeOpenConnections DEPRECATED_MSG_ATTRIBUTE( - "The API for this feature is experimental, " - "and might be removed or modified at any " - "time."); ++ (void)closeOpenConnections DEPRECATED_MSG_ATTRIBUTE("The API for this feature is experimental, " + "and might be removed or modified at any " + "time."); @end diff --git a/src/objective-c/GRPCClient/GRPCCall+ChannelCredentials.h b/src/objective-c/GRPCClient/GRPCCall+ChannelCredentials.h index beae0d11a23..ac2a37d75f2 100644 --- a/src/objective-c/GRPCClient/GRPCCall+ChannelCredentials.h +++ b/src/objective-c/GRPCClient/GRPCCall+ChannelCredentials.h @@ -33,26 +33,24 @@ #import "GRPCCall.h" -/** Helpers for setting TLS Trusted Roots, Client Certificates, and Private Key - */ +/** Helpers for setting TLS Trusted Roots, Client Certificates, and Private Key */ @interface GRPCCall (ChannelCredentials) /** - * Use the provided @c pemRootCert as the set of trusted root Certificate - * Authorities for @c host. + * Use the provided @c pemRootCert as the set of trusted root Certificate Authorities for @c host. */ + (BOOL)setTLSPEMRootCerts:(nullable NSString *)pemRootCert forHost:(nonnull NSString *)host - error:(NSError *_Nullable *_Nullable)errorPtr; + error:(NSError * _Nullable * _Nullable)errorPtr; /** - * Configures @c host with TLS/SSL Client Credentials and optionally trusted - * root Certificate Authorities. If @c pemRootCerts is nil, the default CA - * Certificates bundled with gRPC will be used. + * Configures @c host with TLS/SSL Client Credentials and optionally trusted root Certificate + * Authorities. If @c pemRootCerts is nil, the default CA Certificates bundled with gRPC will be + * used. */ + (BOOL)setTLSPEMRootCerts:(nullable NSString *)pemRootCerts withPrivateKey:(nullable NSString *)pemPrivateKey withCertChain:(nullable NSString *)pemCertChain forHost:(nonnull NSString *)host - error:(NSError *_Nullable *_Nullable)errorPtr; + error:(NSError * _Nullable * _Nullable)errorPtr; @end diff --git a/src/objective-c/GRPCClient/GRPCCall+OAuth2.h b/src/objective-c/GRPCClient/GRPCCall+OAuth2.h index 467c6332c1e..6b443877e9b 100644 --- a/src/objective-c/GRPCClient/GRPCCall+OAuth2.h +++ b/src/objective-c/GRPCClient/GRPCCall+OAuth2.h @@ -37,17 +37,15 @@ @interface GRPCCall (OAuth2) /** - * Setting this property is equivalent to setting "Bearer " as the - * value of the request header with key "authorization" (the authorization - * header). Setting it to nil removes the authorization header from the request. - * The value obtained by getting the property is the OAuth2 bearer token if the - * authorization header of the request has the form "Bearer ", or nil - * otherwise. + * Setting this property is equivalent to setting "Bearer " as the value of the + * request header with key "authorization" (the authorization header). Setting it to nil removes the + * authorization header from the request. + * The value obtained by getting the property is the OAuth2 bearer token if the authorization header + * of the request has the form "Bearer ", or nil otherwise. */ @property(atomic, copy) NSString *oauth2AccessToken; -/** Returns the value (if any) of the "www-authenticate" response header (the - * challenge header). */ +/** Returns the value (if any) of the "www-authenticate" response header (the challenge header). */ @property(atomic, readonly) NSString *oauth2ChallengeHeader; @end diff --git a/src/objective-c/GRPCClient/GRPCCall+Tests.h b/src/objective-c/GRPCClient/GRPCCall+Tests.h index f517f3aac8a..184ad09c5c8 100644 --- a/src/objective-c/GRPCClient/GRPCCall+Tests.h +++ b/src/objective-c/GRPCClient/GRPCCall+Tests.h @@ -34,36 +34,33 @@ #import "GRPCCall.h" /** - * Methods to let tune down the security of gRPC connections for specific hosts. - * These shouldn't be used in releases, but are sometimes needed for testing. + * Methods to let tune down the security of gRPC connections for specific hosts. These shouldn't be + * used in releases, but are sometimes needed for testing. */ @interface GRPCCall (Tests) /** - * Establish all SSL connections to the provided host using the passed SSL - * target name and the root certificates found in the file at |certsPath|. + * Establish all SSL connections to the provided host using the passed SSL target name and the root + * certificates found in the file at |certsPath|. * - * Must be called before any gRPC call to that host is made. It's illegal to - * pass the same host to more than one invocation of the methods of this - * category. + * Must be called before any gRPC call to that host is made. It's illegal to pass the same host to + * more than one invocation of the methods of this category. */ + (void)useTestCertsPath:(NSString *)certsPath testName:(NSString *)testName forHost:(NSString *)host; /** - * Establish all connections to the provided host using cleartext instead of - * SSL. + * Establish all connections to the provided host using cleartext instead of SSL. * - * Must be called before any gRPC call to that host is made. It's illegal to - * pass the same host to more than one invocation of the methods of this - * category. + * Must be called before any gRPC call to that host is made. It's illegal to pass the same host to + * more than one invocation of the methods of this category. */ + (void)useInsecureConnectionsForHost:(NSString *)host; /** - * Resets all host configurations to their default values, and flushes all - * connections from the cache. + * Resets all host configurations to their default values, and flushes all connections from the + * cache. */ + (void)resetHostSettings; @end diff --git a/src/objective-c/GRPCClient/GRPCCall.h b/src/objective-c/GRPCClient/GRPCCall.h index 5ed160d7a01..7645bb1d34a 100644 --- a/src/objective-c/GRPCClient/GRPCCall.h +++ b/src/objective-c/GRPCClient/GRPCCall.h @@ -34,18 +34,17 @@ /** * The gRPC protocol is an RPC protocol on top of HTTP2. * - * While the most common type of RPC receives only one request message and - * returns only one response message, the protocol also supports RPCs that - * return multiple individual messages in a streaming fashion, RPCs that accept - * a stream of request messages, or RPCs with both streaming requests and + * While the most common type of RPC receives only one request message and returns only one response + * message, the protocol also supports RPCs that return multiple individual messages in a streaming + * fashion, RPCs that accept a stream of request messages, or RPCs with both streaming requests and * responses. * - * Conceptually, each gRPC call consists of a bidirectional stream of binary - * messages, with RPCs of the "non-streaming type" sending only one message in - * the corresponding direction (the protocol doesn't make any distinction). + * Conceptually, each gRPC call consists of a bidirectional stream of binary messages, with RPCs of + * the "non-streaming type" sending only one message in the corresponding direction (the protocol + * doesn't make any distinction). * - * Each RPC uses a different HTTP2 stream, and thus multiple simultaneous RPCs - * can be multiplexed transparently on the same TCP connection. + * Each RPC uses a different HTTP2 stream, and thus multiple simultaneous RPCs can be multiplexed + * transparently on the same TCP connection. */ #import @@ -60,56 +59,51 @@ extern NSString *const kGRPCErrorDomain; /** * gRPC error codes. - * Note that a few of these are never produced by the gRPC libraries, but are of - * general utility for server applications to produce. + * Note that a few of these are never produced by the gRPC libraries, but are of general utility for + * server applications to produce. */ typedef NS_ENUM(NSUInteger, GRPCErrorCode) { /** The operation was cancelled (typically by the caller). */ GRPCErrorCodeCancelled = 1, /** - * Unknown error. Errors raised by APIs that do not return enough error - * information may be + * Unknown error. Errors raised by APIs that do not return enough error information may be * converted to this error. */ GRPCErrorCodeUnknown = 2, /** - * The 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 server (e.g., a malformed file name). + * The 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 + * server (e.g., a malformed file name). */ GRPCErrorCodeInvalidArgument = 3, /** - * Deadline expired before operation could complete. For operations that - * change the state of the server, this error may be returned even if the - * operation has completed successfully. For example, a successful response - * from the server could have been delayed long enough for the deadline to - * expire. + * Deadline expired before operation could complete. For operations that change the state of the + * server, this error may be returned even if the operation has completed successfully. For + * example, a successful response from the server could have been delayed long enough for the + * deadline to expire. */ GRPCErrorCodeDeadlineExceeded = 4, /** Some requested entity (e.g., file or directory) was not found. */ GRPCErrorCodeNotFound = 5, - /** Some entity that we attempted to create (e.g., file or directory) already - exists. */ + /** Some entity that we attempted to create (e.g., file or directory) already exists. */ GRPCErrorCodeAlreadyExists = 6, /** - * The caller does not have permission to execute the specified operation. - * PERMISSION_DENIED isn't used for rejections caused by exhausting some - * resource (RESOURCE_EXHAUSTED is used instead for those errors). - * PERMISSION_DENIED doesn't indicate a failure to identify the caller + * The caller does not have permission to execute the specified operation. PERMISSION_DENIED isn't + * used for rejections caused by exhausting some resource (RESOURCE_EXHAUSTED is used instead for + * those errors). PERMISSION_DENIED doesn't indicate a failure to identify the caller * (UNAUTHENTICATED is used instead for those errors). */ GRPCErrorCodePermissionDenied = 7, /** - * The request does not have valid authentication credentials for the - * operation (e.g. the caller's identity can't be verified). + * The request does not have valid authentication credentials for the operation (e.g. the caller's + * identity can't be verified). */ GRPCErrorCodeUnauthenticated = 16, @@ -117,47 +111,42 @@ typedef NS_ENUM(NSUInteger, GRPCErrorCode) { GRPCErrorCodeResourceExhausted = 8, /** - * The RPC was rejected because the server is not in a state required for the - * procedure's + * The RPC was rejected because the server is not in a state required for the procedure's * execution. For example, a directory to be deleted may be non-empty, etc. - * The client should not retry until the server state has been explicitly - * fixed (e.g. by - * performing another RPC). The details depend on the service being called, - * and should be found in the NSError's userInfo. + * The client should not retry until the server state has been explicitly fixed (e.g. by + * performing another RPC). The details depend on the service being called, and should be found in + * the NSError's userInfo. */ GRPCErrorCodeFailedPrecondition = 9, /** - * The RPC was aborted, typically due to a concurrency issue like sequencer - * check failures, transaction aborts, etc. The client should retry at a - * higher-level (e.g., restarting a read-modify-write sequence). + * The RPC was aborted, typically due to a concurrency issue like sequencer check failures, + * transaction aborts, etc. The client should retry at a higher-level (e.g., restarting a read- + * modify-write sequence). */ GRPCErrorCodeAborted = 10, /** - * The RPC was attempted past the valid range. E.g., enumerating past the end - * of a list. - * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed - * if the system state changes. For example, an RPC to get elements of a list - * will generate INVALID_ARGUMENT if asked to return the element at a negative - * index, but it will generate OUT_OF_RANGE if asked to return the element at - * an index past the current size of the list. + * The RPC was attempted past the valid range. E.g., enumerating past the end of a list. + * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed if the system state + * changes. For example, an RPC to get elements of a list will generate INVALID_ARGUMENT if asked + * to return the element at a negative index, but it will generate OUT_OF_RANGE if asked to return + * the element at an index past the current size of the list. */ GRPCErrorCodeOutOfRange = 11, - /** The procedure is not implemented or not supported/enabled in this server. - */ + /** The procedure is not implemented or not supported/enabled in this server. */ GRPCErrorCodeUnimplemented = 12, /** - * Internal error. Means some invariant expected by the server application or - * the gRPC library has been broken. + * Internal error. Means some invariant expected by the server application or the gRPC library has + * been broken. */ GRPCErrorCodeInternal = 13, /** - * The server is currently unavailable. This is most likely a transient - * condition and may be corrected by retrying with a backoff. + * The server is currently unavailable. This is most likely a transient condition and may be + * corrected by retrying with a backoff. */ GRPCErrorCodeUnavailable = 14, @@ -169,19 +158,17 @@ typedef NS_ENUM(NSUInteger, GRPCErrorCode) { * Safety remark of a gRPC method as defined in RFC 2616 Section 9.1 */ typedef NS_ENUM(NSUInteger, GRPCCallSafety) { - /** Signal that there is no guarantees on how the call affects the server - state. */ + /** Signal that there is no guarantees on how the call affects the server state. */ GRPCCallSafetyDefault = 0, /** Signal that the call is idempotent. gRPC is free to use PUT verb. */ GRPCCallSafetyIdempotentRequest = 1, - /** Signal that the call is cacheable and will not affect server state. gRPC - is free to use GET verb. */ + /** Signal that the call is cacheable and will not affect server state. gRPC is free to use GET verb. */ GRPCCallSafetyCacheableRequest = 2, }; /** - * Keys used in |NSError|'s |userInfo| dictionary to store the response headers - * and trailers sent by the server. + * Keys used in |NSError|'s |userInfo| dictionary to store the response headers and trailers sent by + * the server. */ extern id const kGRPCHeadersKey; extern id const kGRPCTrailersKey; @@ -192,24 +179,20 @@ extern id const kGRPCTrailersKey; @interface GRPCCall : GRXWriter /** - * The container of the request headers of an RPC conforms to this protocol, - * which is a subset of NSMutableDictionary's interface. It will become a - * NSMutableDictionary later on. The keys of this container are the header - * names, which per the HTTP standard are case-insensitive. They are stored in - * lowercase (which is how HTTP/2 mandates them on the wire), and can only - * consist of ASCII characters. - * A header value is a NSString object (with only ASCII characters), unless the - * header name has the suffix "-bin", in which case the value has to be a NSData - * object. + * The container of the request headers of an RPC conforms to this protocol, which is a subset of + * NSMutableDictionary's interface. It will become a NSMutableDictionary later on. + * The keys of this container are the header names, which per the HTTP standard are case- + * insensitive. They are stored in lowercase (which is how HTTP/2 mandates them on the wire), and + * can only consist of ASCII characters. + * A header value is a NSString object (with only ASCII characters), unless the header name has the + * suffix "-bin", in which case the value has to be a NSData object. */ /** - * These HTTP headers will be passed to the server as part of this call. Each - * HTTP header is a name-value pair with string names and either string or - * binary values. + * These HTTP headers will be passed to the server as part of this call. Each HTTP header is a + * name-value pair with string names and either string or binary values. * - * The passed dictionary has to use NSString keys, corresponding to the header - * names. The value associated to each can be a NSString object or a NSData - * object. E.g.: + * The passed dictionary has to use NSString keys, corresponding to the header names. The value + * associated to each can be a NSString object or a NSData object. E.g.: * * call.requestHeaders = @{@"authorization": @"Bearer ..."}; * @@ -222,61 +205,53 @@ extern id const kGRPCTrailersKey; @property(atomic, readonly) NSMutableDictionary *requestHeaders; /** - * This dictionary is populated with the HTTP headers received from the server. - * This happens before any response message is received from the server. It has - * the same structure as the request headers dictionary: Keys are NSString - * header names; names ending with the suffix "-bin" have a NSData value; the - * others have a NSString value. + * This dictionary is populated with the HTTP headers received from the server. This happens before + * any response message is received from the server. It has the same structure as the request + * headers dictionary: Keys are NSString header names; names ending with the suffix "-bin" have a + * NSData value; the others have a NSString value. * - * The value of this property is nil until all response headers are received, - * and will change before any of -writeValue: or -writesFinishedWithError: are - * sent to the writeable. + * The value of this property is nil until all response headers are received, and will change before + * any of -writeValue: or -writesFinishedWithError: are sent to the writeable. */ @property(atomic, readonly) NSDictionary *responseHeaders; /** - * Same as responseHeaders, but populated with the HTTP trailers received from - * the server before the call finishes. + * Same as responseHeaders, but populated with the HTTP trailers received from the server before the + * call finishes. * - * The value of this property is nil until all response trailers are received, - * and will change before -writesFinishedWithError: is sent to the writeable. + * The value of this property is nil until all response trailers are received, and will change + * before -writesFinishedWithError: is sent to the writeable. */ @property(atomic, readonly) NSDictionary *responseTrailers; /** - * The request writer has to write NSData objects into the provided Writeable. - * The server will receive each of those separately and in order as distinct - * messages. - * A gRPC call might not complete until the request writer finishes. On the - * other hand, the request finishing doesn't necessarily make the call to - * finish, as the server might continue sending messages to the response side of - * the call indefinitely (depending on the semantics of the specific remote - * method called). + * The request writer has to write NSData objects into the provided Writeable. The server will + * receive each of those separately and in order as distinct messages. + * A gRPC call might not complete until the request writer finishes. On the other hand, the request + * finishing doesn't necessarily make the call to finish, as the server might continue sending + * messages to the response side of the call indefinitely (depending on the semantics of the + * specific remote method called). * To finish a call right away, invoke cancel. - * host parameter should not contain the scheme (http:// or https://), only the - * name or IP addr and the port number, for example @"localhost:5050". + * host parameter should not contain the scheme (http:// or https://), only the name or IP addr + * and the port number, for example @"localhost:5050". */ - (instancetype)initWithHost:(NSString *)host path:(NSString *)path - requestsWriter:(GRXWriter *)requestsWriter - NS_DESIGNATED_INITIALIZER; + requestsWriter:(GRXWriter *)requestsWriter NS_DESIGNATED_INITIALIZER; /** - * Finishes the request side of this call, notifies the server that the RPC - * should be cancelled, and finishes the response side of the call with an error - * of code CANCELED. + * Finishes the request side of this call, notifies the server that the RPC should be cancelled, and + * finishes the response side of the call with an error of code CANCELED. */ - (void)cancel; /** * Set the call flag for a specific host path. * - * Host parameter should not contain the scheme (http:// or https://), only the - * name or IP addr and the port number, for example @"localhost:5050". + * Host parameter should not contain the scheme (http:// or https://), only the name or IP addr + * and the port number, for example @"localhost:5050". */ -+ (void)setCallSafety:(GRPCCallSafety)callSafety - host:(NSString *)host - path:(NSString *)path; ++ (void)setCallSafety:(GRPCCallSafety)callSafety host:(NSString *)host path:(NSString *)path; // TODO(jcanizales): Let specify a deadline. As a category of GRXWriter? @end @@ -285,7 +260,7 @@ extern id const kGRPCTrailersKey; /** This protocol is kept for backwards compatibility with existing code. */ DEPRECATED_MSG_ATTRIBUTE("Use NSDictionary or NSMutableDictionary instead.") -@protocol GRPCRequestHeaders +@protocol GRPCRequestHeaders @property(nonatomic, readonly) NSUInteger count; - (id)objectForKeyedSubscript:(id)key; @@ -298,6 +273,6 @@ DEPRECATED_MSG_ATTRIBUTE("Use NSDictionary or NSMutableDictionary instead.") #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated" /** This is only needed for backwards-compatibility. */ -@interface NSMutableDictionary (GRPCRequestHeaders) +@interface NSMutableDictionary (GRPCRequestHeaders) @end #pragma clang diagnostic pop diff --git a/src/objective-c/GRPCClient/GRPCCall.m b/src/objective-c/GRPCClient/GRPCCall.m index 85d141aa097..44393f6b999 100644 --- a/src/objective-c/GRPCClient/GRPCCall.m +++ b/src/objective-c/GRPCClient/GRPCCall.m @@ -33,9 +33,9 @@ #import "GRPCCall.h" -#import #include #include +#import #import "private/GRPCConnectivityMonitor.h" #import "private/GRPCHost.h" @@ -45,11 +45,11 @@ #import "private/NSDictionary+GRPC.h" #import "private/NSError+GRPC.h" -NSString *const kGRPCHeadersKey = @"io.grpc.HeadersKey"; -NSString *const kGRPCTrailersKey = @"io.grpc.TrailersKey"; +NSString * const kGRPCHeadersKey = @"io.grpc.HeadersKey"; +NSString * const kGRPCTrailersKey = @"io.grpc.TrailersKey"; static NSMutableDictionary *callFlags; -@interface GRPCCall () +@interface GRPCCall () // Make them read-write. @property(atomic, strong) NSDictionary *responseHeaders; @property(atomic, strong) NSDictionary *responseTrailers; @@ -85,21 +85,17 @@ static NSMutableDictionary *callFlags; // correct ordering. GRXConcurrentWriteable *_responseWriteable; - // The network thread wants the requestWriter to resume (when the server is - // ready for more input), or to stop (on errors), concurrently with user - // threads that want to start it, pause it or stop it. Because a writer isn't - // thread-safe, we'll synchronize those operations on it. - // We don't use a dispatch queue for that purpose, because the writer can call - // writeValue: or writesFinishedWithError: on this GRPCCall as part of those - // operations. We want to be able to pause the writer immediately on - // writeValue:, so we need our locking to be recursive. + // The network thread wants the requestWriter to resume (when the server is ready for more input), + // or to stop (on errors), concurrently with user threads that want to start it, pause it or stop + // it. Because a writer isn't thread-safe, we'll synchronize those operations on it. + // We don't use a dispatch queue for that purpose, because the writer can call writeValue: or + // writesFinishedWithError: on this GRPCCall as part of those operations. We want to be able to + // pause the writer immediately on writeValue:, so we need our locking to be recursive. GRXWriter *_requestWriter; // To create a retain cycle when a call is started, up until it finishes. See - // |startWithWriteable:| and |finishWithError:|. This saves users from having - // to retain a - // reference to the call object if all they're interested in is the handler - // being executed when + // |startWithWriteable:| and |finishWithError:|. This saves users from having to retain a + // reference to the call object if all they're interested in is the handler being executed when // the response arrives. GRPCCall *_retainSelf; @@ -108,16 +104,13 @@ static NSMutableDictionary *callFlags; @synthesize state = _state; -// TODO(jcanizales): If grpc_init is idempotent, this should be changed from -// load to initialize. +// TODO(jcanizales): If grpc_init is idempotent, this should be changed from load to initialize. + (void)load { grpc_init(); callFlags = [NSMutableDictionary dictionary]; } -+ (void)setCallSafety:(GRPCCallSafety)callSafety - host:(NSString *)host - path:(NSString *)path { ++ (void)setCallSafety:(GRPCCallSafety)callSafety host:(NSString *)host path:(NSString *)path { NSString *hostAndPath = [NSString stringWithFormat:@"%@/%@", host, path]; switch (callSafety) { case GRPCCallSafetyDefault: @@ -148,8 +141,7 @@ static NSMutableDictionary *callFlags; path:(NSString *)path requestsWriter:(GRXWriter *)requestWriter { if (!host || !path) { - [NSException raise:NSInvalidArgumentException - format:@"Neither host nor path can be nil."]; + [NSException raise:NSInvalidArgumentException format:@"Neither host nor path can be nil."]; } if (requestWriter.state != GRXWriterStateNotStarted) { [NSException raise:NSInvalidArgumentException @@ -199,10 +191,7 @@ static NSMutableDictionary *callFlags; - (void)cancel { [self finishWithError:[NSError errorWithDomain:kGRPCErrorDomain code:GRPCErrorCodeCancelled - userInfo:@{ - NSLocalizedDescriptionKey : - @"Canceled by app" - }]]; + userInfo:@{NSLocalizedDescriptionKey: @"Canceled by app"}]]; [self cancelCall]; } @@ -217,18 +206,15 @@ static NSMutableDictionary *callFlags; // Only called from the call queue. // The handler will be called from the network queue. -- (void)startReadWithHandler:(void (^)(grpc_byte_buffer *))handler { +- (void)startReadWithHandler:(void(^)(grpc_byte_buffer *))handler { // TODO(jcanizales): Add error handlers for async failures - [_wrappedCall startBatchWithOperations:@[ [[GRPCOpRecvMessage alloc] - initWithHandler:handler] ]]; + [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMessage alloc] initWithHandler:handler]]]; } // Called initially from the network queue once response headers are received, -// then "recursively" from the responseWriteable queue after each response from -// the +// then "recursively" from the responseWriteable queue after each response from the // server has been written. -// If the call is currently paused, this is a noop. Restarting the call will -// invoke this +// If the call is currently paused, this is a noop. Restarting the call will invoke this // method. // TODO(jcanizales): Rename to readResponseIfNotPaused. - (void)startNextRead { @@ -251,23 +237,15 @@ static NSMutableDictionary *callFlags; // don't want to throw, because the app shouldn't crash for a behavior // that's on the hands of any server to have. Instead we finish and ask // the server to cancel. - [weakSelf - finishWithError:[NSError - errorWithDomain:kGRPCErrorDomain - code:GRPCErrorCodeResourceExhausted - userInfo:@{ - NSLocalizedDescriptionKey : - @"Client does not have enough " - @"memory to hold the server " - @"response." - }]]; + [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain + code:GRPCErrorCodeResourceExhausted + userInfo:@{NSLocalizedDescriptionKey: @"Client does not have enough memory to hold the server response."}]]; [weakSelf cancelCall]; return; } - [weakWriteable enqueueValue:data - completionHandler:^{ - [weakSelf startNextRead]; - }]; + [weakWriteable enqueueValue:data completionHandler:^{ + [weakSelf startNextRead]; + }]; }]; }); } @@ -276,22 +254,19 @@ static NSMutableDictionary *callFlags; - (void)sendHeaders:(NSDictionary *)headers { // TODO(jcanizales): Add error handlers for async failures - [_wrappedCall startBatchWithOperations:@[ - [[GRPCOpSendMetadata alloc] - initWithMetadata:headers - flags:[GRPCCall callFlagsForHost:_host path:_path] - handler:nil] - ]]; + [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendMetadata alloc] initWithMetadata:headers + flags:[GRPCCall callFlagsForHost:_host path:_path] + handler:nil]]]; } #pragma mark GRXWriteable implementation // Only called from the call queue. The error handler will be called from the // network queue if the write didn't succeed. -- (void)writeMessage:(NSData *)message - withErrorHandler:(void (^)())errorHandler { +- (void)writeMessage:(NSData *)message withErrorHandler:(void (^)())errorHandler { + __weak GRPCCall *weakSelf = self; - void (^resumingHandler)(void) = ^{ + void(^resumingHandler)(void) = ^{ // Resume the request writer. GRPCCall *strongSelf = weakSelf; if (strongSelf) { @@ -300,9 +275,8 @@ static NSMutableDictionary *callFlags; } } }; - [_wrappedCall startBatchWithOperations:@[ [[GRPCOpSendMessage alloc] - initWithMessage:message - handler:resumingHandler] ] + [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendMessage alloc] initWithMessage:message + handler:resumingHandler]] errorHandler:errorHandler]; } @@ -317,20 +291,18 @@ static NSMutableDictionary *callFlags; __weak GRPCCall *weakSelf = self; dispatch_async(_callQueue, ^{ - [weakSelf writeMessage:value - withErrorHandler:^{ - [weakSelf - finishWithError:[NSError errorWithDomain:kGRPCErrorDomain + [weakSelf writeMessage:value withErrorHandler:^{ + [weakSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain code:GRPCErrorCodeInternal userInfo:nil]]; - }]; + }]; }); } // 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 { - [_wrappedCall startBatchWithOperations:@[ [[GRPCOpSendClose alloc] init] ] + [_wrappedCall startBatchWithOperations:@[[[GRPCOpSendClose alloc] init]] errorHandler:errorHandler]; } @@ -351,19 +323,17 @@ static NSMutableDictionary *callFlags; #pragma mark Invoke -// Both handlers will eventually be called, from the network queue. Writes can -// start immediately after this. +// Both handlers will eventually be called, from the network queue. Writes can start immediately +// after this. // The first one (headersHandler), when the response headers are received. // The second one (completionHandler), whenever the RPC finishes for any reason. -- (void)invokeCallWithHeadersHandler:(void (^)(NSDictionary *))headersHandler - completionHandler: - (void (^)(NSError *, NSDictionary *))completionHandler { +- (void)invokeCallWithHeadersHandler:(void(^)(NSDictionary *))headersHandler + completionHandler:(void(^)(NSError *, NSDictionary *))completionHandler { // TODO(jcanizales): Add error handlers for async failures - [_wrappedCall startBatchWithOperations:@[ [[GRPCOpRecvMetadata alloc] - initWithHandler:headersHandler] ]]; - [_wrappedCall - startBatchWithOperations:@[ [[GRPCOpRecvStatus alloc] - initWithHandler:completionHandler] ]]; + [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvMetadata alloc] + initWithHandler:headersHandler]]]; + [_wrappedCall startBatchWithOperations:@[[[GRPCOpRecvStatus alloc] + initWithHandler:completionHandler]]]; } - (void)invokeCall { @@ -371,31 +341,27 @@ static NSMutableDictionary *callFlags; // Response headers received. self.responseHeaders = headers; [self startNextRead]; - } - completionHandler:^(NSError *error, NSDictionary *trailers) { - self.responseTrailers = trailers; - - if (error) { - NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; - if (error.userInfo) { - [userInfo addEntriesFromDictionary:error.userInfo]; - } - userInfo[kGRPCTrailersKey] = self.responseTrailers; - // TODO(jcanizales): The C gRPC library doesn't guarantee that the - // headers block will be called before this one, so an error might end - // up with trailers but no headers. We shouldn't call finishWithError - // until ater both blocks are called. It is also when this is done - // that we can provide a merged view of response headers and trailers - // in a thread-safe way. - if (self.responseHeaders) { - userInfo[kGRPCHeadersKey] = self.responseHeaders; - } - error = [NSError errorWithDomain:error.domain - code:error.code - userInfo:userInfo]; - } - [self finishWithError:error]; - }]; + } completionHandler:^(NSError *error, NSDictionary *trailers) { + self.responseTrailers = trailers; + + if (error) { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + if (error.userInfo) { + [userInfo addEntriesFromDictionary:error.userInfo]; + } + userInfo[kGRPCTrailersKey] = self.responseTrailers; + // TODO(jcanizales): The C gRPC library doesn't guarantee that the headers block will be + // called before this one, so an error might end up with trailers but no headers. We + // shouldn't call finishWithError until ater both blocks are called. It is also when this is + // done that we can provide a merged view of response headers and trailers in a thread-safe + // way. + if (self.responseHeaders) { + userInfo[kGRPCHeadersKey] = self.responseHeaders; + } + error = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo]; + } + [self finishWithError:error]; + }]; // Now that the RPC has been initiated, request writes can start. @synchronized(_requestWriter) { [_requestWriter startWithWriteable:self]; @@ -409,16 +375,14 @@ static NSMutableDictionary *callFlags; _state = GRXWriterStateStarted; } - // Create a retain cycle so that this instance lives until the RPC finishes - // (or is cancelled). This makes RPCs in which the call isn't externally - // retained possible (as long as it is started before being autoreleased). - // Care is taken not to retain self strongly in any of the blocks used in this - // implementation, so that the life of the instance is determined by this - // retain cycle. + // Create a retain cycle so that this instance lives until the RPC finishes (or is cancelled). + // This makes RPCs in which the call isn't externally retained possible (as long as it is started + // before being autoreleased). + // Care is taken not to retain self strongly in any of the blocks used in this implementation, so + // that the life of the instance is determined by this retain cycle. _retainSelf = self; - _responseWriteable = - [[GRXConcurrentWriteable alloc] initWithWriteable:writeable]; + _responseWriteable = [[GRXConcurrentWriteable alloc] initWithWriteable:writeable]; _wrappedCall = [[GRPCWrappedCall alloc] initWithHost:_host path:_path]; NSAssert(_wrappedCall, @"Error allocating RPC objects. Low memory?"); @@ -427,37 +391,29 @@ static NSMutableDictionary *callFlags; [self invokeCall]; // TODO(jcanizales): Extract this logic somewhere common. - NSString *host = - [NSURL URLWithString:[@"https://" stringByAppendingString:_host]].host; + NSString *host = [NSURL URLWithString:[@"https://" stringByAppendingString:_host]].host; if (!host) { // TODO(jcanizales): Check this on init. - [NSException raise:NSInvalidArgumentException - format:@"host of %@ is nil", _host]; + [NSException raise:NSInvalidArgumentException format:@"host of %@ is nil", _host]; } __weak typeof(self) weakSelf = self; _connectivityMonitor = [GRPCConnectivityMonitor monitorWithHost:host]; void (^handler)() = ^{ typeof(self) strongSelf = weakSelf; if (strongSelf) { - [strongSelf - finishWithError:[NSError errorWithDomain:kGRPCErrorDomain - code:GRPCErrorCodeUnavailable - userInfo:@{ - NSLocalizedDescriptionKey : - @"Connectivity lost." - }]]; + [strongSelf finishWithError:[NSError errorWithDomain:kGRPCErrorDomain + code:GRPCErrorCodeUnavailable + userInfo:@{ NSLocalizedDescriptionKey : @"Connectivity lost." }]]; } }; [_connectivityMonitor handleLossWithHandler:handler - wifiStatusChangeHandler:^{ - }]; + wifiStatusChangeHandler:nil]; } - (void)setState:(GRXWriterState)newState { @synchronized(self) { // Manual transitions are only allowed from the started or paused states. - if (_state == GRXWriterStateNotStarted || - _state == GRXWriterStateFinished) { + if (_state == GRXWriterStateNotStarted || _state == GRXWriterStateFinished) { return; } diff --git a/src/objective-c/GRPCClient/private/GRPCCompletionQueue.h b/src/objective-c/GRPCClient/private/GRPCCompletionQueue.h index c0bbf22c747..fe3b8f39d12 100644 --- a/src/objective-c/GRPCClient/private/GRPCCompletionQueue.h +++ b/src/objective-c/GRPCClient/private/GRPCCompletionQueue.h @@ -34,19 +34,18 @@ #import #include -typedef void (^GRPCQueueCompletionHandler)(bool success); +typedef void(^GRPCQueueCompletionHandler)(bool success); /** - * This class lets one more easily use |grpc_completion_queue|. To use it, pass - * the value of the |unmanagedQueue| property of an instance of this class to - * |grpc_channel_create_call|. Then for every |grpc_call_*| method that accepts - * a tag, you can pass a block of type |GRPCQueueCompletionHandler| (remembering - * to cast it using |__bridge_retained|). The block is guaranteed to eventually - * be called, by a concurrent queue, and then released. Each such block is + * This class lets one more easily use |grpc_completion_queue|. To use it, pass the value of the + * |unmanagedQueue| property of an instance of this class to |grpc_channel_create_call|. Then for + * every |grpc_call_*| method that accepts a tag, you can pass a block of type + * |GRPCQueueCompletionHandler| (remembering to cast it using |__bridge_retained|). The block is + * guaranteed to eventually be called, by a concurrent queue, and then released. Each such block is * passed a |bool| that tells if the operation was successful. * - * Release the GRPCCompletionQueue object only after you are not going to pass - * any more blocks to the |grpc_call| that's using it. + * Release the GRPCCompletionQueue object only after you are not going to pass any more blocks to + * the |grpc_call| that's using it. */ @interface GRPCCompletionQueue : NSObject @property(nonatomic, readonly) grpc_completion_queue *unmanagedQueue; diff --git a/src/objective-c/GRPCClient/private/GRPCConnectivityMonitor.h b/src/objective-c/GRPCClient/private/GRPCConnectivityMonitor.h index 941b596d2c8..e341b6ef6c3 100644 --- a/src/objective-c/GRPCClient/private/GRPCConnectivityMonitor.h +++ b/src/objective-c/GRPCClient/private/GRPCConnectivityMonitor.h @@ -45,7 +45,7 @@ */ #define GRPC_XMACRO_ITEM(methodName, FlagName) \ - @property(nonatomic, readonly) BOOL methodName; +@property(nonatomic, readonly) BOOL methodName; #include "GRPCReachabilityFlagNames.xmacro.h" #undef GRPC_XMACRO_ITEM @@ -60,19 +60,18 @@ - (nonnull instancetype)init NS_UNAVAILABLE; /** - * Queue on which callbacks will be dispatched. Default is the main queue. Set - * it before calling handleLossWithHandler:. + * Queue on which callbacks will be dispatched. Default is the main queue. Set it before calling + * handleLossWithHandler:. */ // TODO(jcanizales): Default to a serial background queue instead. @property(nonatomic, strong, null_resettable) dispatch_queue_t queue; /** - * Calls handler every time the connectivity to this instance's host is lost. If - * this instance is released before that happens, the handler won't be called. - * 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). + * Calls handler every time the connectivity to this instance's host is lost. If this instance is + * released before that happens, the handler won't be called. + * 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:(nonnull void (^)())handler - wifiStatusChangeHandler:(nonnull void (^)())wifiStatusChangeHandler; +- (void)handleLossWithHandler:(nullable void (^)())lossHandler + wifiStatusChangeHandler:(nullable void (^)())wifiStatusChangeHandler; @end diff --git a/src/objective-c/GRPCClient/private/GRPCConnectivityMonitor.m b/src/objective-c/GRPCClient/private/GRPCConnectivityMonitor.m index fec6391d399..40afca2d3d6 100644 --- a/src/objective-c/GRPCClient/private/GRPCConnectivityMonitor.m +++ b/src/objective-c/GRPCClient/private/GRPCConnectivityMonitor.m @@ -58,20 +58,19 @@ } */ -#define GRPC_XMACRO_ITEM(methodName, FlagName) \ - -(BOOL)methodName { \ - return !!(_flags & kSCNetworkReachabilityFlags##FlagName); \ - } +#define GRPC_XMACRO_ITEM(methodName, FlagName) \ +- (BOOL)methodName { \ + return !!(_flags & kSCNetworkReachabilityFlags ## FlagName); \ +} #include "GRPCReachabilityFlagNames.xmacro.h" #undef GRPC_XMACRO_ITEM - (BOOL)isHostReachable { - // Note: connectionOnDemand means it'll be reachable only if using the - // CFSocketStream API or APIs on top of it. - // connectionRequired means we can't tell until a connection is attempted - // (e.g. for VPN on demand). - return self.reachable && !self.interventionRequired && - !self.connectionOnDemand; + // Note: connectionOnDemand means it'll be reachable only if using the CFSocketStream API or APIs + // on top of it. + // connectionRequired means we can't tell until a connection is attempted (e.g. for VPN on + // demand). + return self.reachable && !self.interventionRequired && !self.connectionOnDemand; } - (NSString *)description { @@ -80,9 +79,9 @@ /* * For each flag, add its name to the array if it's ON. Example: - if (self.isCell) { - [activeOptions addObject:@"isCell"]; - } + if (self.isCell) { + [activeOptions addObject:@"isCell"]; + } */ #define GRPC_XMACRO_ITEM(methodName, FlagName) \ @@ -92,14 +91,12 @@ #include "GRPCReachabilityFlagNames.xmacro.h" #undef GRPC_XMACRO_ITEM - return activeOptions.count == 0 - ? @"(none)" - : [activeOptions componentsJoinedByString:@", "]; + return activeOptions.count == 0 ? @"(none)" : [activeOptions componentsJoinedByString:@", "]; } - (BOOL)isEqual:(id)object { return [object isKindOfClass:[GRPCReachabilityFlags class]] && - _flags == ((GRPCReachabilityFlags *)object)->_flags; + _flags == ((GRPCReachabilityFlags *)object)->_flags; } - (NSUInteger)hash { @@ -109,16 +106,15 @@ #pragma mark Connectivity Monitor -// Assumes the third argument is a block that accepts a GRPCReachabilityFlags -// object, and passes the received ones to it. +// Assumes the third argument is a block that accepts a GRPCReachabilityFlags object, and passes the +// received ones to it. static void PassFlagsToContextInfoBlock(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info) { -#pragma unused(target) - // This can be called many times with the same info. The info is retained by - // SCNetworkReachability while this function is being executed. - void (^handler)(GRPCReachabilityFlags *) = - (__bridge void (^)(GRPCReachabilityFlags *))info; + #pragma unused (target) + // This can be called many times with the same info. The info is retained by SCNetworkReachability + // while this function is being executed. + void (^handler)(GRPCReachabilityFlags *) = (__bridge void (^)(GRPCReachabilityFlags *))info; handler([[GRPCReachabilityFlags alloc] initWithFlags:flags]); } @@ -127,8 +123,7 @@ static void PassFlagsToContextInfoBlock(SCNetworkReachabilityRef target, GRPCReachabilityFlags *_previousReachabilityFlags; } -- (nullable instancetype)initWithReachability: - (nullable SCNetworkReachabilityRef)reachability { +- (nullable instancetype)initWithReachability:(nullable SCNetworkReachabilityRef)reachability { if (!reachability) { return nil; } @@ -149,23 +144,23 @@ static void PassFlagsToContextInfoBlock(SCNetworkReachabilityRef target, SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, hostName); - GRPCConnectivityMonitor *returnValue = - [[self alloc] initWithReachability:reachability]; + GRPCConnectivityMonitor *returnValue = [[self alloc] initWithReachability:reachability]; if (reachability) { CFRelease(reachability); } return returnValue; } -- (void)handleLossWithHandler:(void (^)())handler - wifiStatusChangeHandler:(nonnull void (^)())wifiStatusChangeHandler { +- (void)handleLossWithHandler:(nullable void (^)())lossHandler + wifiStatusChangeHandler:(nullable void (^)())wifiStatusChangeHandler { __weak typeof(self) weakSelf = self; [self startListeningWithHandler:^(GRPCReachabilityFlags *flags) { typeof(self) strongSelf = weakSelf; if (strongSelf) { - if (!flags.reachable) { - handler(); - } else if (strongSelf->_previousReachabilityFlags && + if (lossHandler && !flags.reachable) { + lossHandler(); + } else if (wifiStatusChangeHandler && + strongSelf->_previousReachabilityFlags && (flags.isWWAN ^ strongSelf->_previousReachabilityFlags.isWWAN)) { wifiStatusChangeHandler(); @@ -176,19 +171,17 @@ static void PassFlagsToContextInfoBlock(SCNetworkReachabilityRef target, } - (void)startListeningWithHandler:(void (^)(GRPCReachabilityFlags *))handler { - // Copy to ensure the handler block is in the heap (and so can't be - // deallocated when this method returns). + // Copy to ensure the handler block is in the heap (and so can't be deallocated when this method + // returns). void (^copiedHandler)(GRPCReachabilityFlags *) = [handler copy]; SCNetworkReachabilityContext context = { - .version = 0, - .info = (__bridge void *)copiedHandler, - .retain = CFRetain, - .release = CFRelease, + .version = 0, + .info = (__bridge void *)copiedHandler, + .retain = CFRetain, + .release = CFRelease, }; - // The following will retain context.info, and release it when the callback is - // set to NULL. - SCNetworkReachabilitySetCallback(_reachabilityRef, - PassFlagsToContextInfoBlock, &context); + // The following will retain context.info, and release it when the callback is set to NULL. + SCNetworkReachabilitySetCallback(_reachabilityRef, PassFlagsToContextInfoBlock, &context); SCNetworkReachabilitySetDispatchQueue(_reachabilityRef, _queue); } diff --git a/src/objective-c/GRPCClient/private/GRPCHost.m b/src/objective-c/GRPCClient/private/GRPCHost.m index 0524472f530..31065cbf018 100644 --- a/src/objective-c/GRPCClient/private/GRPCHost.m +++ b/src/objective-c/GRPCClient/private/GRPCHost.m @@ -33,9 +33,9 @@ #import "GRPCHost.h" -#import #include #include +#import #ifdef GRPC_COMPILE_WITH_CRONET #import #import @@ -48,10 +48,9 @@ NS_ASSUME_NONNULL_BEGIN -// TODO(jcanizales): Generate the version in a standalone header, from -// templates. Like +// TODO(jcanizales): Generate the version in a standalone header, from templates. Like // templates/src/core/surface/version.c.template . -#define GRPC_OBJC_VERSION_STRING @"1.0.0" +#define GRPC_OBJC_VERSION_STRING @"1.0.1" static NSMutableDictionary *kHostCache; @@ -62,8 +61,7 @@ static NSMutableDictionary *kHostCache; static GRPCConnectivityMonitor *connectivityMonitor = nil; @implementation GRPCHost { - // TODO(mlumish): Investigate whether caching channels with strong links is a - // good idea. + // TODO(mlumish): Investigate whether caching channels with strong links is a good idea. GRPCChannel *_channel; } @@ -83,13 +81,11 @@ static GRPCConnectivityMonitor *connectivityMonitor = nil; return nil; } - // To provide a default port, we try to interpret the address. If it's just a - // host name without scheme and without port, we'll use port 443. If it has a - // scheme, we pass it untouched to the C gRPC library. - // TODO(jcanizales): Add unit tests for the types of addresses we want to let - // pass untouched. - NSURL *hostURL = - [NSURL URLWithString:[@"https://" stringByAppendingString:address]]; + // To provide a default port, we try to interpret the address. If it's just a host name without + // scheme and without port, we'll use port 443. If it has a scheme, we pass it untouched to the C + // gRPC library. + // TODO(jcanizales): Add unit tests for the types of addresses we want to let pass untouched. + NSURL *hostURL = [NSURL URLWithString:[@"https://" stringByAppendingString:address]]; if (hostURL.host && !hostURL.port) { address = [hostURL.host stringByAppendingString:@":443"]; } @@ -99,7 +95,6 @@ static GRPCConnectivityMonitor *connectivityMonitor = nil; dispatch_once(&cacheInitialization, ^{ kHostCache = [NSMutableDictionary dictionary]; }); - @synchronized(kHostCache) { GRPCHost *cachedHost = kHostCache[address]; if (cachedHost) { @@ -137,7 +132,7 @@ static GRPCConnectivityMonitor *connectivityMonitor = nil; } + (void)resetAllHostSettings { - @synchronized(kHostCache) { + @synchronized (kHostCache) { kHostCache = [NSMutableDictionary dictionary]; } } @@ -163,19 +158,16 @@ static GRPCConnectivityMonitor *connectivityMonitor = nil; static NSError *kDefaultRootsError; static dispatch_once_t loading; dispatch_once(&loading, ^{ - NSString *defaultPath = @"gRPCCertificates.bundle/roots"; // .pem - // Do not use NSBundle.mainBundle, as it's nil for tests of library - // projects. + NSString *defaultPath = @"gRPCCertificates.bundle/roots"; // .pem + // Do not use NSBundle.mainBundle, as it's nil for tests of library projects. NSBundle *bundle = [NSBundle bundleForClass:self.class]; NSString *path = [bundle pathForResource:defaultPath ofType:@"pem"]; NSError *error; - // Files in PEM format can have non-ASCII characters in their comments (e.g. - // for the name of the issuer). Load them as UTF8 and produce an ASCII - // equivalent. - NSString *contentInUTF8 = - [NSString stringWithContentsOfFile:path - encoding:NSUTF8StringEncoding - error:&error]; + // Files in PEM format can have non-ASCII characters in their comments (e.g. for the name of the + // issuer). Load them as UTF8 and produce an ASCII equivalent. + NSString *contentInUTF8 = [NSString stringWithContentsOfFile:path + encoding:NSUTF8StringEncoding + error:&error]; if (contentInUTF8 == nil) { kDefaultRootsError = error; return; @@ -193,15 +185,11 @@ static GRPCConnectivityMonitor *connectivityMonitor = nil; if (errorPtr) { *errorPtr = kDefaultRootsError; } - NSAssert(kDefaultRootsASCII, - @"Could not read gRPCCertificates.bundle/roots.pem. This file, " - "with the root certificates, is needed to establish secure " - "(TLS) connections. " - "Because the file is distributed with the gRPC library, this " - "error is usually a sign " - "that the library wasn't configured correctly for your " - "project. Error: %@", - kDefaultRootsError); + NSAssert(kDefaultRootsASCII, @"Could not read gRPCCertificates.bundle/roots.pem. This file, " + "with the root certificates, is needed to establish secure (TLS) connections. " + "Because the file is distributed with the gRPC library, this error is usually a sign " + "that the library wasn't configured correctly for your project. Error: %@", + kDefaultRootsError); return NO; } rootsASCII = kDefaultRootsASCII; @@ -212,12 +200,10 @@ static GRPCConnectivityMonitor *connectivityMonitor = nil; creds = grpc_ssl_credentials_create(rootsASCII.bytes, NULL, NULL); } else { grpc_ssl_pem_key_cert_pair key_cert_pair; - NSData *privateKeyASCII = - [pemPrivateKey dataUsingEncoding:NSASCIIStringEncoding - allowLossyConversion:YES]; - NSData *certChainASCII = - [pemCertChain dataUsingEncoding:NSASCIIStringEncoding - allowLossyConversion:YES]; + NSData *privateKeyASCII = [pemPrivateKey dataUsingEncoding:NSASCIIStringEncoding + allowLossyConversion:YES]; + NSData *certChainASCII = [pemCertChain dataUsingEncoding:NSASCIIStringEncoding + allowLossyConversion:YES]; key_cert_pair.private_key = privateKeyASCII.bytes; key_cert_pair.cert_chain = certChainASCII.bytes; creds = grpc_ssl_credentials_create(rootsASCII.bytes, &key_cert_pair, NULL); @@ -237,8 +223,7 @@ static GRPCConnectivityMonitor *connectivityMonitor = nil; NSMutableDictionary *args = [NSMutableDictionary dictionary]; // TODO(jcanizales): Add OS and device information (see - // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#user-agents - // ). + // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#user-agents ). NSString *userAgent = @"grpc-objc/" GRPC_OBJC_VERSION_STRING; if (_userAgentPrefix) { userAgent = [_userAgentPrefix stringByAppendingFormat:@" %@", userAgent]; @@ -252,7 +237,7 @@ static GRPCConnectivityMonitor *connectivityMonitor = nil; if (_responseSizeLimitOverride) { args[@GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH] = _responseSizeLimitOverride; } - // Use 10000ms initial backoff time for correct behavior on bad/slow networks + // Use 10000ms initial backoff time for correct behavior on bad/slow networks args[@GRPC_ARG_INITIAL_RECONNECT_BACKOFF_MS] = @10000; return args; } @@ -266,15 +251,12 @@ static GRPCConnectivityMonitor *connectivityMonitor = nil; GRPCChannel *channel; @synchronized(self) { if (_channelCreds == nil) { - [self setTLSPEMRootCerts:nil - withPrivateKey:nil - withCertChain:nil - error:nil]; + [self setTLSPEMRootCerts:nil withPrivateKey:nil withCertChain:nil error:nil]; } #ifdef GRPC_COMPILE_WITH_CRONET if (useCronet) { - channel = - [GRPCChannel secureCronetChannelWithHost:_address channelArgs:args]; + channel = [GRPCChannel secureCronetChannelWithHost:_address + channelArgs:args]; } else #endif { @@ -290,8 +272,7 @@ static GRPCConnectivityMonitor *connectivityMonitor = nil; } - (NSString *)hostName { - // TODO(jcanizales): Default to nil instead of _address when Issue #2635 is - // clarified. + // TODO(jcanizales): Default to nil instead of _address when Issue #2635 is clarified. return _hostNameOverride ?: _address; } diff --git a/src/objective-c/GRPCClient/private/GRPCRequestHeaders.m b/src/objective-c/GRPCClient/private/GRPCRequestHeaders.m index 58c6032e804..c6a03c145ea 100644 --- a/src/objective-c/GRPCClient/private/GRPCRequestHeaders.m +++ b/src/objective-c/GRPCClient/private/GRPCRequestHeaders.m @@ -38,10 +38,9 @@ #import "NSDictionary+GRPC.h" // Used by the setter. -static void CheckIsNonNilASCII(NSString *name, NSString *value) { +static void CheckIsNonNilASCII(NSString *name, NSString* value) { if (!value) { - [NSException raise:NSInvalidArgumentException - format:@"%@ cannot be nil", name]; + [NSException raise:NSInvalidArgumentException format:@"%@ cannot be nil", name]; } if (![value canBeConvertedToEncoding:NSASCIIStringEncoding]) { [NSException raise:NSInvalidArgumentException @@ -53,20 +52,15 @@ static void CheckIsNonNilASCII(NSString *name, NSString *value) { static void CheckKeyValuePairIsValid(NSString *key, id value) { if ([key hasSuffix:@"-bin"]) { if (![value isKindOfClass:NSData.class]) { - [NSException - raise:NSInvalidArgumentException - format:@"Expected NSData value for header %@ ending in \"-bin\", " - @"instead got %@", - key, value]; + [NSException raise:NSInvalidArgumentException + format:@"Expected NSData value for header %@ ending in \"-bin\", " + @"instead got %@", key, value]; } } else { if (![value isKindOfClass:NSString.class]) { - [NSException - raise:NSInvalidArgumentException - format: - @"Expected NSString value for header %@ not ending in \"-bin\", " - @"instead got %@", - key, value]; + [NSException raise:NSInvalidArgumentException + format:@"Expected NSString value for header %@ not ending in \"-bin\", " + @"instead got %@", key, value]; } CheckIsNonNilASCII(@"Text header value", (NSString *)value); } @@ -74,10 +68,9 @@ static void CheckKeyValuePairIsValid(NSString *key, id value) { @implementation GRPCRequestHeaders { __weak GRPCCall *_call; - // The NSMutableDictionary superclass doesn't hold any storage (so that people - // can implement their own in subclasses). As that's not the reason we're - // subclassing, we just delegate storage to the default NSMutableDictionary - // subclass returned by the cluster (e.g. __NSDictionaryM on iOS 9). + // The NSMutableDictionary superclass doesn't hold any storage (so that people can implement their + // own in subclasses). As that's not the reason we're subclassing, we just delegate storage to the + // default NSMutableDictionary subclass returned by the cluster (e.g. __NSDictionaryM on iOS 9). NSMutableDictionary *_delegate; } @@ -98,8 +91,7 @@ static void CheckKeyValuePairIsValid(NSString *key, id value) { } // Designated initializer -- (instancetype)initWithCall:(GRPCCall *)call - storage:(NSMutableDictionary *)storage { +- (instancetype)initWithCall:(GRPCCall *)call storage:(NSMutableDictionary *)storage { // TODO(jcanizales): Throw if call or storage are nil. if ((self = [super init])) { _call = call; @@ -108,10 +100,9 @@ static void CheckKeyValuePairIsValid(NSString *key, id value) { return self; } -- (instancetype) -initWithObjects:(const id _Nonnull __unsafe_unretained *)objects - forKeys:(const id _Nonnull __unsafe_unretained *)keys - count:(NSUInteger)cnt { +- (instancetype)initWithObjects:(const id _Nonnull __unsafe_unretained *)objects + forKeys:(const id _Nonnull __unsafe_unretained *)keys + count:(NSUInteger)cnt { return [self init]; } @@ -143,7 +134,7 @@ initWithObjects:(const id _Nonnull __unsafe_unretained *)objects return _delegate.count; } -- (NSEnumerator *_Nonnull)keyEnumerator { +- (NSEnumerator * _Nonnull)keyEnumerator { return [_delegate keyEnumerator]; } diff --git a/src/objective-c/GRPCClient/private/GRPCWrappedCall.m b/src/objective-c/GRPCClient/private/GRPCWrappedCall.m index bbda9f2f647..627b6aa86dd 100644 --- a/src/objective-c/GRPCClient/private/GRPCWrappedCall.m +++ b/src/objective-c/GRPCClient/private/GRPCWrappedCall.m @@ -34,27 +34,27 @@ #import "GRPCWrappedCall.h" #import -#include #include +#include #include #import "GRPCCompletionQueue.h" #import "GRPCHost.h" -#import "NSData+GRPC.h" #import "NSDictionary+GRPC.h" +#import "NSData+GRPC.h" #import "NSError+GRPC.h" @implementation GRPCOperation { - @protected - // Most operation subclasses don't set any flags in the grpc_op, and rely on - // the flag member being initialized to zero. +@protected + // 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)finish { if (_handler) { - void (^handler)() = _handler; + void(^handler)() = _handler; _handler = nil; handler(); } @@ -101,8 +101,7 @@ - (instancetype)initWithMessage:(NSData *)message handler:(void (^)())handler { if (!message) { - [NSException raise:NSInvalidArgumentException - format:@"message cannot be nil"]; + [NSException raise:NSInvalidArgumentException format:@"message cannot be nil"]; } if (self = [super init]) { _op.op = GRPC_OP_SEND_MESSAGE; @@ -138,11 +137,11 @@ grpc_metadata_array _headers; } -- (instancetype)init { +- (instancetype) init { return [self initWithHandler:nil]; } -- (instancetype)initWithHandler:(void (^)(NSDictionary *))handler { +- (instancetype) initWithHandler:(void (^)(NSDictionary *))handler { if (self = [super init]) { _op.op = GRPC_OP_RECV_INITIAL_METADATA; grpc_metadata_array_init(&_headers); @@ -153,7 +152,7 @@ _handler = ^{ __strong typeof(self) strongSelf = weakSelf; NSDictionary *metadata = [NSDictionary - grpc_dictionaryFromMetadataArray:strongSelf->_headers]; + grpc_dictionaryFromMetadataArray:strongSelf->_headers]; handler(metadata); }; } @@ -167,7 +166,7 @@ @end -@implementation GRPCOpRecvMessage { +@implementation GRPCOpRecvMessage{ grpc_byte_buffer *_receivedMessage; } @@ -193,18 +192,18 @@ @end -@implementation GRPCOpRecvStatus { +@implementation GRPCOpRecvStatus{ grpc_status_code _statusCode; char *_details; size_t _detailsCapacity; grpc_metadata_array _trailers; } -- (instancetype)init { +- (instancetype) init { return [self initWithHandler:nil]; } -- (instancetype)initWithHandler:(void (^)(NSError *, NSDictionary *))handler { +- (instancetype) initWithHandler:(void (^)(NSError *, NSDictionary *))handler { if (self = [super init]) { _op.op = GRPC_OP_RECV_STATUS_ON_CLIENT; _op.data.recv_status_on_client.status = &_statusCode; @@ -217,11 +216,10 @@ __weak typeof(self) weakSelf = self; _handler = ^{ __strong typeof(self) strongSelf = weakSelf; - NSError *error = - [NSError grpc_errorFromStatusCode:strongSelf->_statusCode - details:strongSelf->_details]; + NSError *error = [NSError grpc_errorFromStatusCode:strongSelf->_statusCode + details:strongSelf->_details]; NSDictionary *trailers = [NSDictionary - grpc_dictionaryFromMetadataArray:strongSelf->_trailers]; + grpc_dictionaryFromMetadataArray:strongSelf->_trailers]; handler(error, trailers); }; } @@ -247,21 +245,20 @@ return [self initWithHost:nil path:nil]; } -- (instancetype)initWithHost:(NSString *)host path:(NSString *)path { +- (instancetype)initWithHost:(NSString *)host + path:(NSString *)path { if (!path || !host) { [NSException raise:NSInvalidArgumentException format:@"path and host cannot be nil."]; } if (self = [super init]) { - // Each completion queue consumes one thread. There's a trade to be made - // between creating and consuming too many threads and having contention of - // multiple calls in a single completion queue. Currently we use a singleton - // queue. + // Each completion queue consumes one thread. There's a trade to be made between creating and + // consuming too many threads and having contention of multiple calls in a single completion + // queue. Currently we use a singleton queue. _queue = [GRPCCompletionQueue completionQueue]; - _call = [[GRPCHost hostWithAddress:host] unmanagedCallWithPath:path - completionQueue:_queue]; + _call = [[GRPCHost hostWithAddress:host] unmanagedCallWithPath:path completionQueue:_queue]; if (_call == NULL) { return nil; } @@ -273,35 +270,32 @@ [self startBatchWithOperations:operations errorHandler:nil]; } -- (void)startBatchWithOperations:(NSArray *)operations - errorHandler:(void (^)())errorHandler { +- (void)startBatchWithOperations:(NSArray *)operations errorHandler:(void (^)())errorHandler { size_t nops = operations.count; grpc_op *ops_array = gpr_malloc(nops * sizeof(grpc_op)); size_t i = 0; for (GRPCOperation *operation in operations) { ops_array[i++] = operation.op; } - grpc_call_error error = grpc_call_start_batch( - _call, ops_array, nops, (__bridge_retained void *)(^(bool success) { - if (!success) { - if (errorHandler) { - errorHandler(); - } else { - return; - } - } - for (GRPCOperation *operation in operations) { - [operation finish]; - } - }), - NULL); + grpc_call_error error = grpc_call_start_batch(_call, ops_array, nops, + (__bridge_retained void *)(^(bool success){ + if (!success) { + if (errorHandler) { + errorHandler(); + } else { + return; + } + } + for (GRPCOperation *operation in operations) { + [operation finish]; + } + }), NULL); gpr_free(ops_array); if (error != GRPC_CALL_OK) { [NSException raise:NSInternalInconsistencyException - format:@"A precondition for calling grpc_call_start_batch " - @"wasn't met. Error %i", - error]; + format:@"A precondition for calling grpc_call_start_batch wasn't met. Error %i", + error]; } } diff --git a/src/objective-c/GRPCClient/private/NSError+GRPC.h b/src/objective-c/GRPCClient/private/NSError+GRPC.h index a9a321470c3..e0c1efc1f91 100644 --- a/src/objective-c/GRPCClient/private/NSError+GRPC.h +++ b/src/objective-c/GRPCClient/private/NSError+GRPC.h @@ -36,9 +36,8 @@ @interface NSError (GRPC) /** - * Returns nil if the status code is OK. Otherwise, a NSError whose code is one - * of |GRPCErrorCode| and whose domain is |kGRPCErrorDomain|. + * Returns nil if the status code is OK. Otherwise, a NSError whose code is one of |GRPCErrorCode| + * and whose domain is |kGRPCErrorDomain|. */ -+ (instancetype)grpc_errorFromStatusCode:(grpc_status_code)statusCode - details:(char *)details; ++ (instancetype)grpc_errorFromStatusCode:(grpc_status_code)statusCode details:(char *)details; @end diff --git a/src/php/lib/Grpc/BaseStub.php b/src/php/lib/Grpc/BaseStub.php index 8a7f6572a62..36d94cae2c9 100644 --- a/src/php/lib/Grpc/BaseStub.php +++ b/src/php/lib/Grpc/BaseStub.php @@ -116,7 +116,7 @@ class BaseStub } /** - * @param $timeout in microseconds + * @param int $timeout in microseconds * * @return bool true if channel is ready * @throw Exception if channel is in FATAL_ERROR state @@ -189,7 +189,7 @@ class BaseStub /** * validate and normalize the metadata array. * - * @param $metadata The metadata map + * @param array $metadata The metadata map * * @return $metadata Validated and key-normalized metadata map * @throw InvalidArgumentException if key contains invalid characters @@ -216,8 +216,8 @@ class BaseStub * Call a remote method that takes a single argument and has a * single output. * - * @param string $method The name of the method to call - * @param $argument The argument to the method + * @param string $method The name of the method to call + * @param mixed $argument The argument to the method * @param callable $deserialize A function that deserializes the response * @param array $metadata A metadata map to send to the server * @@ -250,8 +250,8 @@ class BaseStub * Call a remote method that takes a stream of arguments and has a single * output. * - * @param string $method The name of the method to call - * @param $arguments An array or Traversable of arguments to stream to the + * @param string $method The name of the method to call + * @param array $arguments An array or Traversable of arguments to stream to the * server * @param callable $deserialize A function that deserializes the response * @param array $metadata A metadata map to send to the server @@ -284,8 +284,8 @@ class BaseStub * Call a remote method that takes a single argument and returns a stream of * responses. * - * @param string $method The name of the method to call - * @param $argument The argument to the method + * @param string $method The name of the method to call + * @param mixed $argument The argument to the method * @param callable $deserialize A function that deserializes the responses * @param array $metadata A metadata map to send to the server * diff --git a/src/proto/grpc/lb/v1/load_balancer.options b/src/proto/grpc/lb/v1/load_balancer.options index a9398d5f474..7fbd44b9ded 100644 --- a/src/proto/grpc/lb/v1/load_balancer.options +++ b/src/proto/grpc/lb/v1/load_balancer.options @@ -1,6 +1,5 @@ grpc.lb.v1.InitialLoadBalanceRequest.name max_size:128 -grpc.lb.v1.InitialLoadBalanceResponse.client_config max_size:64 grpc.lb.v1.InitialLoadBalanceResponse.load_balancer_delegate max_size:64 grpc.lb.v1.Server.ip_address max_size:16 -grpc.lb.v1.Server.load_balance_token max_size:65 +grpc.lb.v1.Server.load_balance_token max_size:50 load_balancer.proto no_unions:true diff --git a/src/proto/grpc/lb/v1/load_balancer.proto b/src/proto/grpc/lb/v1/load_balancer.proto index 210fba1323e..44a5150a7e0 100644 --- a/src/proto/grpc/lb/v1/load_balancer.proto +++ b/src/proto/grpc/lb/v1/load_balancer.proto @@ -63,7 +63,8 @@ message LoadBalanceRequest { } message InitialLoadBalanceRequest { - // Name of load balanced service (IE, service.grpc.gslb.google.com) + // Name of load balanced service (IE, service.grpc.gslb.google.com). Its + // length should be less than 256 bytes. string name = 1; } @@ -95,7 +96,8 @@ message InitialLoadBalanceResponse { // This is an application layer redirect that indicates the client should use // the specified server for load balancing. When this field is non-empty in // the response, the client should open a separate connection to the - // load_balancer_delegate and call the BalanceLoad method. + // load_balancer_delegate and call the BalanceLoad method. Its length should + // be less than 64 bytes. string load_balancer_delegate = 1; // This interval defines how often the client should send the client stats @@ -130,6 +132,8 @@ message Server { // frontend requests for that pick must include the token in its initial // metadata. The token is used by the backend to verify the request and to // allow the backend to report load to the gRPC LB system. + // + // Its length is variable but less than 50 bytes. string load_balance_token = 3; // Indicates whether this particular request should be dropped by the client diff --git a/src/proto/grpc/reflection/v1alpha/reflection.proto b/src/proto/grpc/reflection/v1alpha/reflection.proto index 276ff0e255d..01e582cc8a6 100644 --- a/src/proto/grpc/reflection/v1alpha/reflection.proto +++ b/src/proto/grpc/reflection/v1alpha/reflection.proto @@ -59,8 +59,8 @@ message ServerReflectionRequest { // message type with the given field number. ExtensionRequest file_containing_extension = 5; - // Finds the tag numbers used by all known extensions of extendee_type, and - // appends them to ExtensionNumberResponse in an undefined order. + // Finds the tag numbers used by all known extensions of the given message + // type, and appends them to ExtensionNumberResponse in an undefined order. // Its corresponding method is best-effort: it's not guaranteed that the // reflection service will implement this method, and it's not guaranteed // that this method will provide all extensions. Returns diff --git a/src/proto/grpc/testing/control.proto b/src/proto/grpc/testing/control.proto index ece69108158..918f5fa3e3a 100644 --- a/src/proto/grpc/testing/control.proto +++ b/src/proto/grpc/testing/control.proto @@ -137,6 +137,11 @@ message ServerConfig { // If we use an OTHER_SERVER client_type, this string gives more detail string other_server_api = 11; + + // c++-only options (for now) -------------------------------- + + // Buffer pool size (no buffer pool specified if unset) + int32 resource_quota_size = 1001; } message ServerArgs { @@ -213,6 +218,10 @@ message ScenarioResultSummary double latency_95 = 9; double latency_99 = 10; double latency_999 = 11; + + // Number of requests that succeeded/failed + double successful_requests_per_second = 12; + double failed_requests_per_second = 13; } // Results of a single benchmark scenario. @@ -232,4 +241,6 @@ message ScenarioResult { // Information on success or failure of each worker repeated bool client_success = 7; repeated bool server_success = 8; + // Number of failed requests (one row per status code seen) + repeated RequestResultCount request_results = 9; } diff --git a/src/proto/grpc/testing/proto2/empty2.proto b/src/proto/grpc/testing/proto2/empty2.proto new file mode 100644 index 00000000000..51f0fe28b1a --- /dev/null +++ b/src/proto/grpc/testing/proto2/empty2.proto @@ -0,0 +1,37 @@ + +// Copyright 2016, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; + +package grpc.testing.proto2; + +message EmptyWithExtensions { + extensions 100 to 999; +} diff --git a/src/proto/grpc/testing/proto2/empty2_extensions.proto b/src/proto/grpc/testing/proto2/empty2_extensions.proto new file mode 100644 index 00000000000..0229fe3fbd5 --- /dev/null +++ b/src/proto/grpc/testing/proto2/empty2_extensions.proto @@ -0,0 +1,43 @@ +// Copyright 2016, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto2"; + +import "src/proto/grpc/testing/proto2/empty2.proto"; + +package grpc.testing.proto2; + +// Fill emptiness with music. +extend grpc.testing.proto2.EmptyWithExtensions { + optional int64 Deadmau5 = 124; + optional float Madeon = 125; + optional string AboveAndBeyond = 126; + optional bool Tycho = 127; + optional fixed64 Pendulum = 128; +} diff --git a/src/proto/grpc/testing/stats.proto b/src/proto/grpc/testing/stats.proto index f9d116110b0..d40d7148016 100644 --- a/src/proto/grpc/testing/stats.proto +++ b/src/proto/grpc/testing/stats.proto @@ -59,6 +59,11 @@ message HistogramData { double count = 6; } +message RequestResultCount { + int32 status_code = 1; + int64 count = 2; +} + message ClientStats { // Latency histogram. Data points are in nanoseconds. HistogramData latencies = 1; @@ -67,4 +72,7 @@ message ClientStats { double time_elapsed = 2; double time_user = 3; double time_system = 4; + + // Number of failed requests (one row per status code seen) + repeated RequestResultCount request_results = 5; } diff --git a/src/python/.gitignore b/src/python/.gitignore index f158efa4bf1..7b520579a08 100644 --- a/src/python/.gitignore +++ b/src/python/.gitignore @@ -1 +1,3 @@ gens/ +*_pb2.py +*_pb2_grpc.py diff --git a/src/python/grpcio/grpc_core_dependencies.py b/src/python/grpcio/grpc_core_dependencies.py index 7ffe0f558a6..1ad423909f5 100644 --- a/src/python/grpcio/grpc_core_dependencies.py +++ b/src/python/grpcio/grpc_core_dependencies.py @@ -122,6 +122,7 @@ CORE_SOURCE_FILES = [ '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_utils_common_posix.c', 'src/core/lib/iomgr/socket_utils_linux.c', diff --git a/src/python/grpcio_health_checking/.gitignore b/src/python/grpcio_health_checking/.gitignore index 85af4668866..432c3194f04 100644 --- a/src/python/grpcio_health_checking/.gitignore +++ b/src/python/grpcio_health_checking/.gitignore @@ -1,5 +1,6 @@ *.proto *_pb2.py +*_pb2_grpc.py build/ grpcio_health_checking.egg-info/ dist/ diff --git a/src/python/grpcio_reflection/.gitignore b/src/python/grpcio_reflection/.gitignore new file mode 100644 index 00000000000..c0befdc8ead --- /dev/null +++ b/src/python/grpcio_reflection/.gitignore @@ -0,0 +1,5 @@ +*.proto +*_pb2.py +build/ +grpcio_reflection.egg-info/ +dist/ diff --git a/src/python/grpcio_reflection/grpc/__init__.py b/src/python/grpcio_reflection/grpc/__init__.py new file mode 100644 index 00000000000..70ac5edd483 --- /dev/null +++ b/src/python/grpcio_reflection/grpc/__init__.py @@ -0,0 +1,30 @@ +# Copyright 2016, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +__import__('pkg_resources').declare_namespace(__name__) diff --git a/src/python/grpcio_reflection/grpc/reflection/__init__.py b/src/python/grpcio_reflection/grpc/reflection/__init__.py new file mode 100644 index 00000000000..d5ad73a74ab --- /dev/null +++ b/src/python/grpcio_reflection/grpc/reflection/__init__.py @@ -0,0 +1,29 @@ +# Copyright 2016, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/src/python/grpcio_reflection/grpc/reflection/v1alpha/__init__.py b/src/python/grpcio_reflection/grpc/reflection/v1alpha/__init__.py new file mode 100644 index 00000000000..d5ad73a74ab --- /dev/null +++ b/src/python/grpcio_reflection/grpc/reflection/v1alpha/__init__.py @@ -0,0 +1,29 @@ +# Copyright 2016, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/src/python/grpcio_reflection/grpc/reflection/v1alpha/reflection.py b/src/python/grpcio_reflection/grpc/reflection/v1alpha/reflection.py new file mode 100644 index 00000000000..3c399b0d799 --- /dev/null +++ b/src/python/grpcio_reflection/grpc/reflection/v1alpha/reflection.py @@ -0,0 +1,143 @@ +# Copyright 2016, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Reference implementation for reflection in gRPC Python.""" + +import threading + +import grpc +from google.protobuf import descriptor_pb2 +from google.protobuf import descriptor_pool + +from grpc.reflection.v1alpha import reflection_pb2 + +_POOL = descriptor_pool.Default() + +def _not_found_error(): + return reflection_pb2.ServerReflectionResponse( + error_response=reflection_pb2.ErrorResponse( + error_code=grpc.StatusCode.NOT_FOUND.value[0], + error_message=grpc.StatusCode.NOT_FOUND.value[1].encode(), + ) + ) + +def _file_descriptor_response(descriptor): + proto = descriptor_pb2.FileDescriptorProto() + descriptor.CopyToProto(proto) + serialized_proto = proto.SerializeToString() + return reflection_pb2.ServerReflectionResponse( + file_descriptor_response=reflection_pb2.FileDescriptorResponse( + file_descriptor_proto=(serialized_proto,) + ), + ) + + +class ReflectionServicer(reflection_pb2.ServerReflectionServicer): + """Servicer handling RPCs for service statuses.""" + + def __init__(self, service_names, pool=None): + """Constructor. + + Args: + service_names: Iterable of fully-qualified service names available. + """ + self._service_names = list(service_names) + self._pool = _POOL if pool is None else pool + + def _file_by_filename(self, filename): + try: + descriptor = self._pool.FindFileByName(filename) + except KeyError: + return _not_found_error() + else: + return _file_descriptor_response(descriptor) + + def _file_containing_symbol(self, fully_qualified_name): + try: + descriptor = self._pool.FindFileContainingSymbol(fully_qualified_name) + except KeyError: + return _not_found_error() + else: + return _file_descriptor_response(descriptor) + + def _file_containing_extension(containing_type, extension_number): + # TODO(atash) Python protobuf currently doesn't support querying extensions. + # https://github.com/google/protobuf/issues/2248 + return reflection_pb2.ServerReflectionResponse( + error_response=reflection_pb2.ErrorResponse( + error_code=grpc.StatusCode.UNIMPLEMENTED.value[0], + error_message=grpc.StatusCode.UNIMPLMENTED.value[1].encode(), + ) + ) + + def _extension_numbers_of_type(fully_qualified_name): + # TODO(atash) We're allowed to leave this unsupported according to the + # protocol, but we should still eventually implement it. Hits the same issue + # as `_file_containing_extension`, however. + # https://github.com/google/protobuf/issues/2248 + return reflection_pb2.ServerReflectionResponse( + error_response=reflection_pb2.ErrorResponse( + error_code=grpc.StatusCode.UNIMPLEMENTED.value[0], + error_message=grpc.StatusCode.UNIMPLMENTED.value[1].encode(), + ) + ) + + def _list_services(self): + return reflection_pb2.ServerReflectionResponse( + list_services_response=reflection_pb2.ListServiceResponse( + service=[ + reflection_pb2.ServiceResponse(name=service_name) + for service_name in self._service_names + ] + ) + ) + + def ServerReflectionInfo(self, request_iterator, context): + for request in request_iterator: + if request.HasField('file_by_filename'): + yield self._file_by_filename(request.file_by_filename) + elif request.HasField('file_containing_symbol'): + yield self._file_containing_symbol(request.file_containing_symbol) + elif request.HasField('file_containing_extension'): + yield self._file_containing_extension( + request.file_containing_extension.containing_type, + request.file_containing_extension.extension_number) + elif request.HasField('all_extension_numbers_of_type'): + yield _all_extension_numbers_of_type( + request.all_extension_numbers_of_type) + elif request.HasField('list_services'): + yield self._list_services() + else: + yield reflection_pb2.ServerReflectionResponse( + error_response=reflection_pb2.ErrorResponse( + error_code=grpc.StatusCode.INVALID_ARGUMENT.value[0], + error_message=grpc.StatusCode.INVALID_ARGUMENT.value[1].encode(), + ) + ) + diff --git a/tools/distrib/check_generated_pb_files.sh b/src/python/grpcio_reflection/grpc_version.py old mode 100755 new mode 100644 similarity index 70% rename from tools/distrib/check_generated_pb_files.sh rename to src/python/grpcio_reflection/grpc_version.py index 6b93895484c..9b3c44c0221 --- a/tools/distrib/check_generated_pb_files.sh +++ b/src/python/grpcio_reflection/grpc_version.py @@ -1,4 +1,3 @@ -#!/bin/bash # Copyright 2016, Google Inc. # All rights reserved. # @@ -28,16 +27,6 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -set -ex +# AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_reflection/grpc_version.py.template`!!! -# change to root directory -cd $(dirname $0)/../.. - -# build grpc_check_generated_pb_files docker image -docker build -t grpc_check_generated_pb_files tools/dockerfile/grpc_check_generated_pb_files - -# run check_pb_files against the checked out codebase -docker run -e TEST=$TEST --rm=true -v ${HOST_GIT_ROOT:-`pwd`}:/var/local/jenkins/grpc -t grpc_check_generated_pb_files /var/local/jenkins/grpc/tools/dockerfile/grpc_check_generated_pb_files/check_pb_files.sh - -# If the test fails, please make sure your protobuf submodule is up-to-date and run -# tools/codegen/extensions/gen_reflection_proto.sh to update the generated files. +VERSION='1.1.0.dev0' diff --git a/src/python/grpcio_reflection/reflection_commands.py b/src/python/grpcio_reflection/reflection_commands.py new file mode 100644 index 00000000000..d189aee5774 --- /dev/null +++ b/src/python/grpcio_reflection/reflection_commands.py @@ -0,0 +1,78 @@ +# Copyright 2016, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Provides distutils command classes for the GRPC Python setup process.""" + +import os +import shutil + +import setuptools + +ROOT_DIR = os.path.abspath(os.path.dirname(os.path.abspath(__file__))) +HEALTH_PROTO = os.path.join(ROOT_DIR, '../../proto/grpc/reflection/v1alpha/reflection.proto') + + +class CopyProtoModules(setuptools.Command): + """Command to copy proto modules from grpc/src/proto.""" + + description = '' + user_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + if os.path.isfile(HEALTH_PROTO): + shutil.copyfile( + HEALTH_PROTO, + os.path.join(ROOT_DIR, 'grpc/reflection/v1alpha/reflection.proto')) + + +class BuildPackageProtos(setuptools.Command): + """Command to generate project *_pb2.py modules from proto files.""" + + description = 'build grpc protobuf modules' + user_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + # due to limitations of the proto generator, we require that only *one* + # directory is provided as an 'include' directory. We assume it's the '' key + # to `self.distribution.package_dir` (and get a key error if it's not + # there). + from grpc.tools import command + command.build_package_protos(self.distribution.package_dir['']) diff --git a/src/python/grpcio_reflection/setup.py b/src/python/grpcio_reflection/setup.py new file mode 100644 index 00000000000..df95af4de16 --- /dev/null +++ b/src/python/grpcio_reflection/setup.py @@ -0,0 +1,73 @@ +# Copyright 2016, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Setup module for the GRPC Python package's optional reflection.""" + +import os +import sys + +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 +import grpc_version + +PACKAGE_DIRECTORIES = { + '': '.', +} + +SETUP_REQUIRES = ( + 'grpcio-tools>={version}'.format(version=grpc_version.VERSION), +) + +INSTALL_REQUIRES = ( + 'protobuf>=3.0.0', + '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, +} + +setuptools.setup( + name='grpcio-reflection', + version=grpc_version.VERSION, + license='3-clause BSD', + package_dir=PACKAGE_DIRECTORIES, + packages=setuptools.find_packages('.'), + namespace_packages=['grpc'], + install_requires=INSTALL_REQUIRES, + setup_requires=SETUP_REQUIRES, + cmdclass=COMMAND_CLASS +) diff --git a/src/python/grpcio_tests/.gitignore b/src/python/grpcio_tests/.gitignore index fc620135dc7..dcba283a8ca 100644 --- a/src/python/grpcio_tests/.gitignore +++ b/src/python/grpcio_tests/.gitignore @@ -1,4 +1,5 @@ proto/ src/ *_pb2.py +*_pb2_grpc.py *.egg-info/ diff --git a/src/python/grpcio_tests/setup.py b/src/python/grpcio_tests/setup.py index 73842066020..01d5fa875b9 100644 --- a/src/python/grpcio_tests/setup.py +++ b/src/python/grpcio_tests/setup.py @@ -80,8 +80,14 @@ PACKAGE_DATA = { 'credentials/server1.key', 'credentials/server1.pem', ], - 'tests.protoc_plugin': [ - 'protoc_plugin_test.proto', + 'tests.protoc_plugin.protos.invocation_testing': [ + 'same.proto', + ], + 'tests.protoc_plugin.protos.invocation_testing.split_messages': [ + 'messages.proto', + ], + 'tests.protoc_plugin.protos.invocation_testing.split_services': [ + 'services.proto', ], 'tests.unit': [ 'credentials/ca.pem', diff --git a/src/python/grpcio_tests/tests/_loader.py b/src/python/grpcio_tests/tests/_loader.py index c2f097f6c61..621bedc7bb8 100644 --- a/src/python/grpcio_tests/tests/_loader.py +++ b/src/python/grpcio_tests/tests/_loader.py @@ -84,11 +84,9 @@ class Loader(object): along. """ for importer, module_name, is_package in ( - pkgutil.iter_modules(package_paths)): + pkgutil.walk_packages(package_paths)): module = importer.find_module(module_name).load_module(module_name) self.visit_module(module) - if is_package: - self.walk_packages(module.__path__) def visit_module(self, module): """Visits the module, adding discovered tests to the test suite. diff --git a/src/python/grpcio_tests/tests/protoc_plugin/_split_definitions_test.py b/src/python/grpcio_tests/tests/protoc_plugin/_split_definitions_test.py new file mode 100644 index 00000000000..089366a8c72 --- /dev/null +++ b/src/python/grpcio_tests/tests/protoc_plugin/_split_definitions_test.py @@ -0,0 +1,304 @@ +# Copyright 2016, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import collections +from concurrent import futures +import contextlib +import distutils.spawn +import errno +import importlib +import os +import os.path +import pkgutil +import shutil +import subprocess +import sys +import tempfile +import threading +import unittest + +import grpc +from grpc.tools import protoc +from tests.unit.framework.common import test_constants + +_MESSAGES_IMPORT = b'import "messages.proto";' + +@contextlib.contextmanager +def _system_path(path): + old_system_path = sys.path[:] + sys.path = sys.path[0:1] + path + sys.path[1:] + yield + sys.path = old_system_path + + +class DummySplitServicer(object): + + def __init__(self, request_class, response_class): + self.request_class = request_class + self.response_class = response_class + + def Call(self, request, context): + return self.response_class() + + +class SeparateTestMixin(object): + + def testImportAttributes(self): + with _system_path([self.python_out_directory]): + pb2 = importlib.import_module(self.pb2_import) + pb2.Request + pb2.Response + if self.should_find_services_in_pb2: + pb2.TestServiceServicer + else: + with self.assertRaises(AttributeError): + pb2.TestServiceServicer + + with _system_path([self.grpc_python_out_directory]): + pb2_grpc = importlib.import_module(self.pb2_grpc_import) + pb2_grpc.TestServiceServicer + with self.assertRaises(AttributeError): + pb2_grpc.Request + with self.assertRaises(AttributeError): + pb2_grpc.Response + + def testCall(self): + with _system_path([self.python_out_directory]): + pb2 = importlib.import_module(self.pb2_import) + with _system_path([self.grpc_python_out_directory]): + pb2_grpc = importlib.import_module(self.pb2_grpc_import) + server = grpc.server( + futures.ThreadPoolExecutor(max_workers=test_constants.POOL_SIZE)) + pb2_grpc.add_TestServiceServicer_to_server( + DummySplitServicer( + pb2.Request, pb2.Response), server) + port = server.add_insecure_port('[::]:0') + server.start() + channel = grpc.insecure_channel('localhost:{}'.format(port)) + stub = pb2_grpc.TestServiceStub(channel) + request = pb2.Request() + expected_response = pb2.Response() + response = stub.Call(request) + self.assertEqual(expected_response, response) + + +class CommonTestMixin(object): + + def testImportAttributes(self): + with _system_path([self.python_out_directory]): + pb2 = importlib.import_module(self.pb2_import) + pb2.Request + pb2.Response + if self.should_find_services_in_pb2: + pb2.TestServiceServicer + else: + with self.assertRaises(AttributeError): + pb2.TestServiceServicer + + with _system_path([self.grpc_python_out_directory]): + pb2_grpc = importlib.import_module(self.pb2_grpc_import) + pb2_grpc.TestServiceServicer + with self.assertRaises(AttributeError): + pb2_grpc.Request + with self.assertRaises(AttributeError): + pb2_grpc.Response + + def testCall(self): + with _system_path([self.python_out_directory]): + pb2 = importlib.import_module(self.pb2_import) + with _system_path([self.grpc_python_out_directory]): + pb2_grpc = importlib.import_module(self.pb2_grpc_import) + server = grpc.server( + futures.ThreadPoolExecutor(max_workers=test_constants.POOL_SIZE)) + pb2_grpc.add_TestServiceServicer_to_server( + DummySplitServicer( + pb2.Request, pb2.Response), server) + port = server.add_insecure_port('[::]:0') + server.start() + channel = grpc.insecure_channel('localhost:{}'.format(port)) + stub = pb2_grpc.TestServiceStub(channel) + request = pb2.Request() + expected_response = pb2.Response() + response = stub.Call(request) + self.assertEqual(expected_response, response) + + +class SameSeparateTest(unittest.TestCase, SeparateTestMixin): + + def setUp(self): + same_proto_contents = pkgutil.get_data( + 'tests.protoc_plugin.protos.invocation_testing', 'same.proto') + self.directory = tempfile.mkdtemp(suffix='same_separate', dir='.') + self.proto_directory = os.path.join(self.directory, 'proto_path') + self.python_out_directory = os.path.join(self.directory, 'python_out') + self.grpc_python_out_directory = os.path.join(self.directory, 'grpc_python_out') + os.makedirs(self.proto_directory) + os.makedirs(self.python_out_directory) + os.makedirs(self.grpc_python_out_directory) + same_proto_file = os.path.join(self.proto_directory, 'same_separate.proto') + open(same_proto_file, 'wb').write(same_proto_contents) + protoc_result = protoc.main([ + '', + '--proto_path={}'.format(self.proto_directory), + '--python_out={}'.format(self.python_out_directory), + '--grpc_python_out={}'.format(self.grpc_python_out_directory), + same_proto_file, + ]) + if protoc_result != 0: + raise Exception("unexpected protoc error") + open(os.path.join(self.grpc_python_out_directory, '__init__.py'), 'w').write('') + open(os.path.join(self.python_out_directory, '__init__.py'), 'w').write('') + self.pb2_import = 'same_separate_pb2' + self.pb2_grpc_import = 'same_separate_pb2_grpc' + self.should_find_services_in_pb2 = False + + def tearDown(self): + shutil.rmtree(self.directory) + + +class SameCommonTest(unittest.TestCase, CommonTestMixin): + + def setUp(self): + same_proto_contents = pkgutil.get_data( + 'tests.protoc_plugin.protos.invocation_testing', 'same.proto') + self.directory = tempfile.mkdtemp(suffix='same_common', dir='.') + self.proto_directory = os.path.join(self.directory, 'proto_path') + self.python_out_directory = os.path.join(self.directory, 'python_out') + self.grpc_python_out_directory = self.python_out_directory + os.makedirs(self.proto_directory) + os.makedirs(self.python_out_directory) + same_proto_file = os.path.join(self.proto_directory, 'same_common.proto') + open(same_proto_file, 'wb').write(same_proto_contents) + protoc_result = protoc.main([ + '', + '--proto_path={}'.format(self.proto_directory), + '--python_out={}'.format(self.python_out_directory), + '--grpc_python_out={}'.format(self.grpc_python_out_directory), + same_proto_file, + ]) + if protoc_result != 0: + raise Exception("unexpected protoc error") + open(os.path.join(self.python_out_directory, '__init__.py'), 'w').write('') + self.pb2_import = 'same_common_pb2' + self.pb2_grpc_import = 'same_common_pb2_grpc' + self.should_find_services_in_pb2 = True + + def tearDown(self): + shutil.rmtree(self.directory) + + +class SplitCommonTest(unittest.TestCase, CommonTestMixin): + + def setUp(self): + services_proto_contents = pkgutil.get_data( + 'tests.protoc_plugin.protos.invocation_testing.split_services', + 'services.proto') + messages_proto_contents = pkgutil.get_data( + 'tests.protoc_plugin.protos.invocation_testing.split_messages', + 'messages.proto') + self.directory = tempfile.mkdtemp(suffix='split_common', dir='.') + self.proto_directory = os.path.join(self.directory, 'proto_path') + self.python_out_directory = os.path.join(self.directory, 'python_out') + self.grpc_python_out_directory = self.python_out_directory + os.makedirs(self.proto_directory) + os.makedirs(self.python_out_directory) + services_proto_file = os.path.join(self.proto_directory, + 'split_common_services.proto') + messages_proto_file = os.path.join(self.proto_directory, + 'split_common_messages.proto') + open(services_proto_file, 'wb').write(services_proto_contents.replace( + _MESSAGES_IMPORT, + b'import "split_common_messages.proto";' + )) + open(messages_proto_file, 'wb').write(messages_proto_contents) + protoc_result = protoc.main([ + '', + '--proto_path={}'.format(self.proto_directory), + '--python_out={}'.format(self.python_out_directory), + '--grpc_python_out={}'.format(self.python_out_directory), + services_proto_file, + messages_proto_file, + ]) + if protoc_result != 0: + raise Exception("unexpected protoc error") + open(os.path.join(self.python_out_directory, '__init__.py'), 'w').write('') + self.pb2_import = 'split_common_messages_pb2' + self.pb2_grpc_import = 'split_common_services_pb2_grpc' + self.should_find_services_in_pb2 = False + + def tearDown(self): + shutil.rmtree(self.directory) + + +class SplitSeparateTest(unittest.TestCase, SeparateTestMixin): + + def setUp(self): + services_proto_contents = pkgutil.get_data( + 'tests.protoc_plugin.protos.invocation_testing.split_services', + 'services.proto') + messages_proto_contents = pkgutil.get_data( + 'tests.protoc_plugin.protos.invocation_testing.split_messages', + 'messages.proto') + self.directory = tempfile.mkdtemp(suffix='split_separate', dir='.') + self.proto_directory = os.path.join(self.directory, 'proto_path') + self.python_out_directory = os.path.join(self.directory, 'python_out') + self.grpc_python_out_directory = os.path.join(self.directory, 'grpc_python_out') + os.makedirs(self.proto_directory) + os.makedirs(self.python_out_directory) + os.makedirs(self.grpc_python_out_directory) + services_proto_file = os.path.join(self.proto_directory, + 'split_separate_services.proto') + messages_proto_file = os.path.join(self.proto_directory, + 'split_separate_messages.proto') + open(services_proto_file, 'wb').write(services_proto_contents.replace( + _MESSAGES_IMPORT, + b'import "split_separate_messages.proto";' + )) + open(messages_proto_file, 'wb').write(messages_proto_contents) + protoc_result = protoc.main([ + '', + '--proto_path={}'.format(self.proto_directory), + '--python_out={}'.format(self.python_out_directory), + '--grpc_python_out={}'.format(self.grpc_python_out_directory), + services_proto_file, + messages_proto_file, + ]) + if protoc_result != 0: + raise Exception("unexpected protoc error") + open(os.path.join(self.python_out_directory, '__init__.py'), 'w').write('') + self.pb2_import = 'split_separate_messages_pb2' + self.pb2_grpc_import = 'split_separate_services_pb2_grpc' + self.should_find_services_in_pb2 = False + + def tearDown(self): + shutil.rmtree(self.directory) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/tools/dockerfile/grpc_check_generated_pb_files/Dockerfile b/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/__init__.py similarity index 65% rename from tools/dockerfile/grpc_check_generated_pb_files/Dockerfile rename to src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/__init__.py index d19bc67120f..2f88fa04122 100644 --- a/tools/dockerfile/grpc_check_generated_pb_files/Dockerfile +++ b/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/__init__.py @@ -1,4 +1,4 @@ -# Copyright 2015, Google Inc. +# Copyright 2016, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without @@ -27,47 +27,4 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -FROM debian:jessie -# Install Git and basic packages. -RUN apt-get update && apt-get install -y \ - autoconf \ - autotools-dev \ - build-essential \ - bzip2 \ - ccache \ - curl \ - gcc \ - gcc-multilib \ - git \ - golang \ - gyp \ - lcov \ - libc6 \ - libc6-dbg \ - libc6-dev \ - libgtest-dev \ - libtool \ - make \ - perl \ - strace \ - python-dev \ - python-setuptools \ - python-yaml \ - telnet \ - unzip \ - wget \ - zip && apt-get clean - -#================ -# Build profiling -RUN apt-get update && apt-get install -y time && apt-get clean - -#================= -# C++ dependencies -RUN apt-get update && apt-get -y install libgflags-dev libgtest-dev libc++-dev clang && apt-get clean - -RUN mkdir /var/local/jenkins - -# Define the default command. -CMD ["bash"] diff --git a/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/same.proto b/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/same.proto new file mode 100644 index 00000000000..269e2fd2c7e --- /dev/null +++ b/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/same.proto @@ -0,0 +1,39 @@ +// Copyright 2016, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package grpc_protoc_plugin.invocation_testing; + +message Request {} +message Response {} + +service TestService { + rpc Call(Request) returns (Response); +} diff --git a/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/split_messages/__init__.py b/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/split_messages/__init__.py new file mode 100644 index 00000000000..2f88fa04122 --- /dev/null +++ b/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/split_messages/__init__.py @@ -0,0 +1,30 @@ +# Copyright 2016, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + diff --git a/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/split_messages/messages.proto b/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/split_messages/messages.proto new file mode 100644 index 00000000000..de22dae0492 --- /dev/null +++ b/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/split_messages/messages.proto @@ -0,0 +1,35 @@ +// Copyright 2016, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +package grpc_protoc_plugin.invocation_testing.split; + +message Request {} +message Response {} diff --git a/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/split_services/__init__.py b/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/split_services/__init__.py new file mode 100644 index 00000000000..2f88fa04122 --- /dev/null +++ b/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/split_services/__init__.py @@ -0,0 +1,30 @@ +# Copyright 2016, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + diff --git a/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/split_services/services.proto b/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/split_services/services.proto new file mode 100644 index 00000000000..af999cd48db --- /dev/null +++ b/src/python/grpcio_tests/tests/protoc_plugin/protos/invocation_testing/split_services/services.proto @@ -0,0 +1,38 @@ +// Copyright 2016, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +syntax = "proto3"; + +import "messages.proto"; + +package grpc_protoc_plugin.invocation_testing.split; + +service TestService { + rpc Call(Request) returns (Response); +} diff --git a/src/python/grpcio_tests/tests/reflection/__init__.py b/src/python/grpcio_tests/tests/reflection/__init__.py new file mode 100644 index 00000000000..100a624dc9c --- /dev/null +++ b/src/python/grpcio_tests/tests/reflection/__init__.py @@ -0,0 +1,28 @@ +# Copyright 2016, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/python/grpcio_tests/tests/reflection/_reflection_servicer_test.py b/src/python/grpcio_tests/tests/reflection/_reflection_servicer_test.py new file mode 100644 index 00000000000..87264cf9ba9 --- /dev/null +++ b/src/python/grpcio_tests/tests/reflection/_reflection_servicer_test.py @@ -0,0 +1,185 @@ +# Copyright 2016, Google Inc. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Tests of grpc.reflection.v1alpha.reflection.""" + +import unittest + +import grpc +from grpc.framework.foundation import logging_pool +from grpc.reflection.v1alpha import reflection +from grpc.reflection.v1alpha import reflection_pb2 + +from google.protobuf import descriptor_pool +from google.protobuf import descriptor_pb2 + +from src.proto.grpc.testing.proto2 import empty2_extensions_pb2 +from src.proto.grpc.testing import empty_pb2 +from tests.unit.framework.common import test_constants + +_EMPTY_PROTO_FILE_NAME = 'src/proto/grpc/testing/empty.proto' +_EMPTY_PROTO_SYMBOL_NAME = 'grpc.testing.Empty' +_SERVICE_NAMES = ( + 'Angstrom', 'Bohr', 'Curie', 'Dyson', 'Einstein', 'Feynman', 'Galilei') + +def _file_descriptor_to_proto(descriptor): + proto = descriptor_pb2.FileDescriptorProto() + descriptor.CopyToProto(proto) + return proto.SerializeToString() + +class ReflectionServicerTest(unittest.TestCase): + + def setUp(self): + servicer = reflection.ReflectionServicer(service_names=_SERVICE_NAMES) + server_pool = logging_pool.pool(test_constants.THREAD_CONCURRENCY) + self._server = grpc.server(server_pool) + port = self._server.add_insecure_port('[::]:0') + reflection_pb2.add_ServerReflectionServicer_to_server(servicer, self._server) + self._server.start() + + channel = grpc.insecure_channel('localhost:%d' % port) + self._stub = reflection_pb2.ServerReflectionStub(channel) + + def testFileByName(self): + requests = ( + reflection_pb2.ServerReflectionRequest( + file_by_filename=_EMPTY_PROTO_FILE_NAME + ), + reflection_pb2.ServerReflectionRequest( + file_by_filename='i-donut-exist' + ), + ) + responses = tuple(self._stub.ServerReflectionInfo(requests)) + expected_responses = ( + reflection_pb2.ServerReflectionResponse( + valid_host='', + file_descriptor_response=reflection_pb2.FileDescriptorResponse( + file_descriptor_proto=( + _file_descriptor_to_proto(empty_pb2.DESCRIPTOR), + ) + ) + ), + reflection_pb2.ServerReflectionResponse( + valid_host='', + error_response=reflection_pb2.ErrorResponse( + error_code=grpc.StatusCode.NOT_FOUND.value[0], + error_message=grpc.StatusCode.NOT_FOUND.value[1].encode(), + ) + ), + ) + self.assertEqual(expected_responses, responses) + + def testFileBySymbol(self): + requests = ( + reflection_pb2.ServerReflectionRequest( + file_containing_symbol=_EMPTY_PROTO_SYMBOL_NAME + ), + reflection_pb2.ServerReflectionRequest( + file_containing_symbol='i.donut.exist.co.uk.org.net.me.name.foo' + ), + ) + responses = tuple(self._stub.ServerReflectionInfo(requests)) + expected_responses = ( + reflection_pb2.ServerReflectionResponse( + valid_host='', + file_descriptor_response=reflection_pb2.FileDescriptorResponse( + file_descriptor_proto=( + _file_descriptor_to_proto(empty_pb2.DESCRIPTOR), + ) + ) + ), + reflection_pb2.ServerReflectionResponse( + valid_host='', + error_response=reflection_pb2.ErrorResponse( + error_code=grpc.StatusCode.NOT_FOUND.value[0], + error_message=grpc.StatusCode.NOT_FOUND.value[1].encode(), + ) + ), + ) + self.assertEqual(expected_responses, responses) + + @unittest.skip('TODO(atash): implement file-containing-extension reflection ' + '(see https://github.com/google/protobuf/issues/2248)') + def testFileContainingExtension(self): + requests = ( + reflection_pb2.ServerReflectionRequest( + file_containing_extension=reflection_pb2.ExtensionRequest( + containing_type='grpc.testing.proto2.Empty', + extension_number=125, + ), + ), + reflection_pb2.ServerReflectionRequest( + file_containing_extension=reflection_pb2.ExtensionRequest( + containing_type='i.donut.exist.co.uk.org.net.me.name.foo', + extension_number=55, + ), + ), + ) + responses = tuple(self._stub.ServerReflectionInfo(requests)) + expected_responses = ( + reflection_pb2.ServerReflectionResponse( + valid_host='', + file_descriptor_response=reflection_pb2.FileDescriptorResponse( + file_descriptor_proto=( + _file_descriptor_to_proto(empty_extensions_pb2.DESCRIPTOR), + ) + ) + ), + reflection_pb2.ServerReflectionResponse( + valid_host='', + error_response=reflection_pb2.ErrorResponse( + error_code=grpc.StatusCode.NOT_FOUND.value[0], + error_message=grpc.StatusCode.NOT_FOUND.value[1].encode(), + ) + ), + ) + self.assertEqual(expected_responses, responses) + + def testListServices(self): + requests = ( + reflection_pb2.ServerReflectionRequest( + list_services='', + ), + ) + responses = tuple(self._stub.ServerReflectionInfo(requests)) + expected_responses = ( + reflection_pb2.ServerReflectionResponse( + valid_host='', + list_services_response=reflection_pb2.ListServiceResponse( + service=tuple( + reflection_pb2.ServiceResponse(name=name) + for name in _SERVICE_NAMES + ) + ) + ), + ) + self.assertEqual(expected_responses, responses) + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/src/python/grpcio_tests/tests/tests.json b/src/python/grpcio_tests/tests/tests.json index 2071a33e13a..dd4a0257f54 100644 --- a/src/python/grpcio_tests/tests/tests.json +++ b/src/python/grpcio_tests/tests/tests.json @@ -1,44 +1,49 @@ [ - "_api_test.AllTest", - "_api_test.ChannelConnectivityTest", - "_api_test.ChannelTest", - "_auth_test.AccessTokenCallCredentialsTest", - "_auth_test.GoogleCallCredentialsTest", - "_beta_features_test.BetaFeaturesTest", - "_beta_features_test.ContextManagementAndLifecycleTest", - "_cancel_many_calls_test.CancelManyCallsTest", - "_channel_args_test.ChannelArgsTest", - "_channel_connectivity_test.ChannelConnectivityTest", - "_channel_ready_future_test.ChannelReadyFutureTest", - "_channel_test.ChannelTest", - "_compression_test.CompressionTest", - "_connectivity_channel_test.ConnectivityStatesTest", - "_credentials_test.CredentialsTest", - "_empty_message_test.EmptyMessageTest", - "_exit_test.ExitTest", - "_face_interface_test.DynamicInvokerBlockingInvocationInlineServiceTest", - "_face_interface_test.DynamicInvokerFutureInvocationAsynchronousEventServiceTest", - "_face_interface_test.GenericInvokerBlockingInvocationInlineServiceTest", - "_face_interface_test.GenericInvokerFutureInvocationAsynchronousEventServiceTest", - "_face_interface_test.MultiCallableInvokerBlockingInvocationInlineServiceTest", - "_face_interface_test.MultiCallableInvokerFutureInvocationAsynchronousEventServiceTest", - "_health_servicer_test.HealthServicerTest", - "_implementations_test.CallCredentialsTest", - "_implementations_test.ChannelCredentialsTest", - "_insecure_interop_test.InsecureInteropTest", - "_logging_pool_test.LoggingPoolTest", - "_metadata_code_details_test.MetadataCodeDetailsTest", - "_metadata_test.MetadataTest", - "_not_found_test.NotFoundTest", - "_python_plugin_test.PythonPluginTest", - "_read_some_but_not_all_responses_test.ReadSomeButNotAllResponsesTest", - "_rpc_test.RPCTest", - "_sanity_test.Sanity", - "_secure_interop_test.SecureInteropTest", - "_thread_cleanup_test.CleanupThreadTest", - "_utilities_test.ChannelConnectivityTest", - "beta_python_plugin_test.PythonPluginTest", - "cygrpc_test.InsecureServerInsecureClient", - "cygrpc_test.SecureServerSecureClient", - "cygrpc_test.TypeSmokeTest" + "health_check._health_servicer_test.HealthServicerTest", + "interop._insecure_interop_test.InsecureInteropTest", + "interop._secure_interop_test.SecureInteropTest", + "protoc_plugin._python_plugin_test.PythonPluginTest", + "protoc_plugin._split_definitions_test.SameCommonTest", + "protoc_plugin._split_definitions_test.SameSeparateTest", + "protoc_plugin._split_definitions_test.SplitCommonTest", + "protoc_plugin._split_definitions_test.SplitSeparateTest", + "protoc_plugin.beta_python_plugin_test.PythonPluginTest", + "reflection._reflection_servicer_test.ReflectionServicerTest", + "unit._api_test.AllTest", + "unit._api_test.ChannelConnectivityTest", + "unit._api_test.ChannelTest", + "unit._auth_test.AccessTokenCallCredentialsTest", + "unit._auth_test.GoogleCallCredentialsTest", + "unit._channel_args_test.ChannelArgsTest", + "unit._channel_connectivity_test.ChannelConnectivityTest", + "unit._channel_ready_future_test.ChannelReadyFutureTest", + "unit._compression_test.CompressionTest", + "unit._credentials_test.CredentialsTest", + "unit._cython._cancel_many_calls_test.CancelManyCallsTest", + "unit._cython._channel_test.ChannelTest", + "unit._cython._read_some_but_not_all_responses_test.ReadSomeButNotAllResponsesTest", + "unit._cython.cygrpc_test.InsecureServerInsecureClient", + "unit._cython.cygrpc_test.SecureServerSecureClient", + "unit._cython.cygrpc_test.TypeSmokeTest", + "unit._empty_message_test.EmptyMessageTest", + "unit._exit_test.ExitTest", + "unit._metadata_code_details_test.MetadataCodeDetailsTest", + "unit._metadata_test.MetadataTest", + "unit._rpc_test.RPCTest", + "unit._sanity._sanity_test.Sanity", + "unit._thread_cleanup_test.CleanupThreadTest", + "unit.beta._beta_features_test.BetaFeaturesTest", + "unit.beta._beta_features_test.ContextManagementAndLifecycleTest", + "unit.beta._connectivity_channel_test.ConnectivityStatesTest", + "unit.beta._face_interface_test.DynamicInvokerBlockingInvocationInlineServiceTest", + "unit.beta._face_interface_test.DynamicInvokerFutureInvocationAsynchronousEventServiceTest", + "unit.beta._face_interface_test.GenericInvokerBlockingInvocationInlineServiceTest", + "unit.beta._face_interface_test.GenericInvokerFutureInvocationAsynchronousEventServiceTest", + "unit.beta._face_interface_test.MultiCallableInvokerBlockingInvocationInlineServiceTest", + "unit.beta._face_interface_test.MultiCallableInvokerFutureInvocationAsynchronousEventServiceTest", + "unit.beta._implementations_test.CallCredentialsTest", + "unit.beta._implementations_test.ChannelCredentialsTest", + "unit.beta._not_found_test.NotFoundTest", + "unit.beta._utilities_test.ChannelConnectivityTest", + "unit.framework.foundation._logging_pool_test.LoggingPoolTest" ] diff --git a/src/ruby/ext/grpc/rb_call_credentials.c b/src/ruby/ext/grpc/rb_call_credentials.c index 9b6675da846..280f21c9731 100644 --- a/src/ruby/ext/grpc/rb_call_credentials.c +++ b/src/ruby/ext/grpc/rb_call_credentials.c @@ -86,19 +86,16 @@ static VALUE grpc_rb_call_credentials_callback_rescue(VALUE args, rb_funcall(exception_object, rb_intern("backtrace"), 0), rb_intern("join"), 1, rb_str_new2("\n\tfrom ")); - VALUE rb_exception_info = rb_funcall(exception_object, rb_intern("to_s"), 0); - const char *exception_classname = rb_obj_classname(exception_object); + VALUE rb_exception_info = rb_funcall(exception_object, rb_intern("inspect"), 0); (void)args; - gpr_log(GPR_INFO, "Call credentials callback failed: %s: %s\n%s", - exception_classname, StringValueCStr(rb_exception_info), + gpr_log(GPR_INFO, "Call credentials callback failed: %s\n%s", + StringValueCStr(rb_exception_info), StringValueCStr(backtrace)); rb_hash_aset(result, rb_str_new2("metadata"), Qnil); - /* Currently only gives the exception class name. It should be possible get - more details */ rb_hash_aset(result, rb_str_new2("status"), - INT2NUM(GRPC_STATUS_PERMISSION_DENIED)); + INT2NUM(GRPC_STATUS_UNAUTHENTICATED)); rb_hash_aset(result, rb_str_new2("details"), - rb_str_new2(exception_classname)); + rb_exception_info); return result; } diff --git a/src/ruby/ext/grpc/rb_grpc_imports.generated.c b/src/ruby/ext/grpc/rb_grpc_imports.generated.c index a6cad0db1ac..fd73cc79704 100644 --- a/src/ruby/ext/grpc/rb_grpc_imports.generated.c +++ b/src/ruby/ext/grpc/rb_grpc_imports.generated.c @@ -132,6 +132,11 @@ grpc_header_key_is_legal_type grpc_header_key_is_legal_import; grpc_header_nonbin_value_is_legal_type grpc_header_nonbin_value_is_legal_import; grpc_is_binary_header_type grpc_is_binary_header_import; grpc_call_error_to_string_type grpc_call_error_to_string_import; +grpc_resource_quota_create_type grpc_resource_quota_create_import; +grpc_resource_quota_ref_type grpc_resource_quota_ref_import; +grpc_resource_quota_unref_type grpc_resource_quota_unref_import; +grpc_resource_quota_resize_type grpc_resource_quota_resize_import; +grpc_resource_quota_arg_vtable_type grpc_resource_quota_arg_vtable_import; grpc_insecure_channel_create_from_fd_type grpc_insecure_channel_create_from_fd_import; grpc_server_add_insecure_channel_from_fd_type grpc_server_add_insecure_channel_from_fd_import; grpc_use_signal_type grpc_use_signal_import; @@ -401,6 +406,11 @@ void grpc_rb_load_imports(HMODULE library) { grpc_header_nonbin_value_is_legal_import = (grpc_header_nonbin_value_is_legal_type) GetProcAddress(library, "grpc_header_nonbin_value_is_legal"); grpc_is_binary_header_import = (grpc_is_binary_header_type) GetProcAddress(library, "grpc_is_binary_header"); grpc_call_error_to_string_import = (grpc_call_error_to_string_type) GetProcAddress(library, "grpc_call_error_to_string"); + grpc_resource_quota_create_import = (grpc_resource_quota_create_type) GetProcAddress(library, "grpc_resource_quota_create"); + grpc_resource_quota_ref_import = (grpc_resource_quota_ref_type) GetProcAddress(library, "grpc_resource_quota_ref"); + grpc_resource_quota_unref_import = (grpc_resource_quota_unref_type) GetProcAddress(library, "grpc_resource_quota_unref"); + grpc_resource_quota_resize_import = (grpc_resource_quota_resize_type) GetProcAddress(library, "grpc_resource_quota_resize"); + grpc_resource_quota_arg_vtable_import = (grpc_resource_quota_arg_vtable_type) GetProcAddress(library, "grpc_resource_quota_arg_vtable"); grpc_insecure_channel_create_from_fd_import = (grpc_insecure_channel_create_from_fd_type) GetProcAddress(library, "grpc_insecure_channel_create_from_fd"); grpc_server_add_insecure_channel_from_fd_import = (grpc_server_add_insecure_channel_from_fd_type) GetProcAddress(library, "grpc_server_add_insecure_channel_from_fd"); grpc_use_signal_import = (grpc_use_signal_type) GetProcAddress(library, "grpc_use_signal"); diff --git a/src/ruby/ext/grpc/rb_grpc_imports.generated.h b/src/ruby/ext/grpc/rb_grpc_imports.generated.h index 00a67b0b2cd..c2244150f2c 100644 --- a/src/ruby/ext/grpc/rb_grpc_imports.generated.h +++ b/src/ruby/ext/grpc/rb_grpc_imports.generated.h @@ -347,6 +347,21 @@ extern grpc_is_binary_header_type grpc_is_binary_header_import; typedef const char *(*grpc_call_error_to_string_type)(grpc_call_error error); extern grpc_call_error_to_string_type grpc_call_error_to_string_import; #define grpc_call_error_to_string grpc_call_error_to_string_import +typedef grpc_resource_quota *(*grpc_resource_quota_create_type)(const char *trace_name); +extern grpc_resource_quota_create_type grpc_resource_quota_create_import; +#define grpc_resource_quota_create grpc_resource_quota_create_import +typedef void(*grpc_resource_quota_ref_type)(grpc_resource_quota *resource_quota); +extern grpc_resource_quota_ref_type grpc_resource_quota_ref_import; +#define grpc_resource_quota_ref grpc_resource_quota_ref_import +typedef void(*grpc_resource_quota_unref_type)(grpc_resource_quota *resource_quota); +extern grpc_resource_quota_unref_type grpc_resource_quota_unref_import; +#define grpc_resource_quota_unref grpc_resource_quota_unref_import +typedef void(*grpc_resource_quota_resize_type)(grpc_resource_quota *resource_quota, size_t new_size); +extern grpc_resource_quota_resize_type grpc_resource_quota_resize_import; +#define grpc_resource_quota_resize grpc_resource_quota_resize_import +typedef const grpc_arg_pointer_vtable *(*grpc_resource_quota_arg_vtable_type)(void); +extern grpc_resource_quota_arg_vtable_type grpc_resource_quota_arg_vtable_import; +#define grpc_resource_quota_arg_vtable grpc_resource_quota_arg_vtable_import typedef grpc_channel *(*grpc_insecure_channel_create_from_fd_type)(const char *target, int fd, const grpc_channel_args *args); extern grpc_insecure_channel_create_from_fd_type grpc_insecure_channel_create_from_fd_import; #define grpc_insecure_channel_create_from_fd grpc_insecure_channel_create_from_fd_import diff --git a/src/ruby/lib/grpc/generic/rpc_server.rb b/src/ruby/lib/grpc/generic/rpc_server.rb index 7dbcb7d4796..57f99c8ce69 100644 --- a/src/ruby/lib/grpc/generic/rpc_server.rb +++ b/src/ruby/lib/grpc/generic/rpc_server.rb @@ -54,6 +54,7 @@ module GRPC DEFAULT_MAX_WAITING_REQUESTS = 60 # Default poll period is 1s + # Used for grpc server shutdown and thread pool shutdown timeouts DEFAULT_POLL_PERIOD = 1 # Signal check period is 0.25s @@ -127,7 +128,7 @@ module GRPC deadline = from_relative_time(@poll_period) @server.close(deadline) @pool.shutdown - @pool.wait_for_termination + @pool.wait_for_termination(@poll_period) end def running_state diff --git a/src/ruby/qps/server.rb b/src/ruby/qps/server.rb index d0c2073dd1e..6175855cd94 100644 --- a/src/ruby/qps/server.rb +++ b/src/ruby/qps/server.rb @@ -63,7 +63,9 @@ class BenchmarkServer cred = :this_port_is_insecure end # Make sure server can handle the large number of calls in benchmarks - @server = GRPC::RpcServer.new(pool_size: 100, max_waiting_requests: 100) + # TODO: @apolcyn, if scenario config increases total outstanding + # calls then will need to increase the pool size too + @server = GRPC::RpcServer.new(pool_size: 1024, max_waiting_requests: 1024) @port = @server.add_http2_port("0.0.0.0:" + port.to_s, cred) @server.handle(BenchmarkServiceImpl.new) @start_time = Time.now diff --git a/src/ruby/spec/generic/client_stub_spec.rb b/src/ruby/spec/generic/client_stub_spec.rb index e68b8db7ab7..607a4a3c5da 100644 --- a/src/ruby/spec/generic/client_stub_spec.rb +++ b/src/ruby/spec/generic/client_stub_spec.rb @@ -168,23 +168,61 @@ describe 'ClientStub' do expect(&blk).to raise_error(GRPC::BadStatus) th.join end + + it 'should receive UNAUTHENTICATED if call credentials plugin fails' do + server_port = create_secure_test_server + th = run_request_response(@sent_msg, @resp, @pass) + + certs = load_test_certs + secure_channel_creds = GRPC::Core::ChannelCredentials.new( + certs[0], nil, nil) + secure_stub_opts = { + channel_args: { + GRPC::Core::Channel::SSL_TARGET => 'foo.test.google.fr' + } + } + stub = GRPC::ClientStub.new("localhost:#{server_port}", + secure_channel_creds, **secure_stub_opts) + + error_message = 'Failing call credentials callback' + failing_auth = proc do + fail error_message + end + creds = GRPC::Core::CallCredentials.new(failing_auth) + + error_occured = false + begin + get_response(stub, credentials: creds) + rescue GRPC::BadStatus => e + error_occured = true + expect(e.code).to eq(GRPC::Core::StatusCodes::UNAUTHENTICATED) + expect(e.details.include?(error_message)).to be true + end + expect(error_occured).to eq(true) + + # Kill the server thread so tests can complete + th.kill + end end describe 'without a call operation' do - def get_response(stub) + def get_response(stub, credentials: nil) + puts credentials.inspect stub.request_response(@method, @sent_msg, noop, noop, - metadata: { k1: 'v1', k2: 'v2' }) + metadata: { k1: 'v1', k2: 'v2' }, + credentials: credentials) end it_behaves_like 'request response' end describe 'via a call operation' do - def get_response(stub, run_start_call_first: false) + def get_response(stub, run_start_call_first: false, credentials: nil) op = stub.request_response(@method, @sent_msg, noop, noop, return_op: true, metadata: { k1: 'v1', k2: 'v2' }, - deadline: from_relative_time(2)) + deadline: from_relative_time(2), + credentials: credentials) expect(op).to be_a(GRPC::ActiveCall::Operation) op.start_call if run_start_call_first result = op.execute @@ -492,6 +530,15 @@ describe 'ClientStub' do end end + def create_secure_test_server + certs = load_test_certs + secure_credentials = GRPC::Core::ServerCredentials.new( + nil, [{ private_key: certs[1], cert_chain: certs[2] }], false) + + @server = GRPC::Core::Server.new(nil) + @server.add_http2_port('0.0.0.0:0', secure_credentials) + end + def create_test_server @server = GRPC::Core::Server.new(nil) @server.add_http2_port('0.0.0.0:0', :this_port_is_insecure) diff --git a/templates/gRPC-Core.podspec.template b/templates/gRPC-Core.podspec.template index 1d5a47336c5..d6928a297cb 100644 --- a/templates/gRPC-Core.podspec.template +++ b/templates/gRPC-Core.podspec.template @@ -62,7 +62,7 @@ %> Pod::Spec.new do |s| s.name = 'gRPC-Core' - version = '1.0.0' + version = '1.0.1' s.version = version s.summary = 'Core cross-platform gRPC library, written in C' s.homepage = 'http://www.grpc.io' @@ -149,7 +149,7 @@ ss.header_mappings_dir = '.' ss.libraries = 'z' ss.dependency "#{s.name}/Interface", version - ss.dependency 'BoringSSL', '~> 6.0' + ss.dependency 'BoringSSL', '~> 7.0' # To save you from scrolling, this is the last part of the podspec. ss.source_files = ${ruby_multiline_list(grpc_private_files(libs), 22)} diff --git a/templates/package.json.template b/templates/package.json.template index e9596d4d4cb..81f39d27f51 100644 --- a/templates/package.json.template +++ b/templates/package.json.template @@ -27,24 +27,28 @@ "coverage": "./node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha src/node/test", "install": "./node_modules/.bin/node-pre-gyp install --fallback-to-build" }, - "bundledDependencies": ["node-pre-gyp"], + "bundledDependencies": [ + "node-pre-gyp" + ], "dependencies": { "arguejs": "^0.2.3", - "lodash": "^3.9.3", + "lodash": "^4.15.0", "nan": "^2.0.0", - "protobufjs": "^4.0.0" + "node-pre-gyp": "^0.6.0", + "protobufjs": "^5.0.0" }, "devDependencies": { - "async": "^1.5.0", + "async": "^2.0.1", + "body-parser": "^1.15.2", + "express": "^4.14.0", "google-auth-library": "^0.9.2", "google-protobuf": "^3.0.0", - "istanbul": "^0.3.21", + "istanbul": "^0.4.4", "jsdoc": "^3.3.2", "jshint": "^2.5.0", "minimist": "^1.1.0", - "mocha": "^2.3.4", - "mocha-jenkins-reporter": "^0.1.9", - "mustache": "^2.0.0", + "mocha": "^3.0.2", + "mocha-jenkins-reporter": "^0.2.3", "poisson-process": "^0.2.1" }, "engines": { @@ -52,11 +56,10 @@ }, "binary": { "module_name": "grpc_node", - "module_path": "./build/Release/", + "module_path": "src/node/extension_binary", "host": "https://storage.googleapis.com/", "remote_path": "grpc-precompiled-binaries/node/{name}/v{version}", - "package_name": "{node_abi}-{platform}-{arch}.tar.gz", - "module_path": "src/node/extension_binary" + "package_name": "{node_abi}-{platform}-{arch}.tar.gz" }, "files": [ "LICENSE", @@ -77,7 +80,7 @@ ], "main": "src/node/index.js", "license": "BSD-3-Clause", - "jshintConfig" : { + "jshintConfig": { "bitwise": true, "curly": true, "eqeqeq": true, diff --git a/templates/src/python/grpcio_reflection/grpc_version.py.template b/templates/src/python/grpcio_reflection/grpc_version.py.template new file mode 100644 index 00000000000..3e84201f5bc --- /dev/null +++ b/templates/src/python/grpcio_reflection/grpc_version.py.template @@ -0,0 +1,34 @@ +%YAML 1.2 +--- | + # Copyright 2016, Google Inc. + # All rights reserved. + # + # Redistribution and use in source and binary forms, with or without + # modification, are permitted provided that the following conditions are + # met: + # + # * Redistributions of source code must retain the above copyright + # notice, this list of conditions and the following disclaimer. + # * Redistributions in binary form must reproduce the above + # copyright notice, this list of conditions and the following disclaimer + # in the documentation and/or other materials provided with the + # distribution. + # * Neither the name of Google Inc. nor the names of its + # contributors may be used to endorse or promote products derived from + # this software without specific prior written permission. + # + # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + # AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_reflection/grpc_version.py.template`!!! + + VERSION='${settings.python_version.pep440()}' diff --git a/templates/tools/dockerfile/test/cxx_ubuntu1604_x64/Dockerfile.template b/templates/tools/dockerfile/test/cxx_ubuntu1604_x64/Dockerfile.template index 42ad6c130da..2d780d74f88 100644 --- a/templates/tools/dockerfile/test/cxx_ubuntu1604_x64/Dockerfile.template +++ b/templates/tools/dockerfile/test/cxx_ubuntu1604_x64/Dockerfile.template @@ -39,7 +39,7 @@ # The clang-3.6 symlink for the default clang version was added # to Ubuntu 16.04 recently, so make sure it's installed. # Also install clang3.7. - RUN apt-get update && apt-get -y install clang-3.6 clang-3.7 && apt-get clean + RUN apt-get update && apt-get -y install gcc-4.8 gcc-4.8-multilib g++-4.8 g++-4.8-multilib clang-3.6 clang-3.7 && apt-get clean # Define the default command. CMD ["bash"] diff --git a/test/core/bad_client/bad_client.c b/test/core/bad_client/bad_client.c index be88d4a69a9..a9638500b75 100644 --- a/test/core/bad_client/bad_client.c +++ b/test/core/bad_client/bad_client.c @@ -114,7 +114,10 @@ void grpc_run_bad_client_test( grpc_init(); /* Create endpoints */ - sfd = grpc_iomgr_create_endpoint_pair("fixture", 65536); + grpc_resource_quota *resource_quota = + grpc_resource_quota_create("bad_client_test"); + sfd = grpc_iomgr_create_endpoint_pair("fixture", resource_quota, 65536); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); /* Create server, completion events */ a.server = grpc_server_create(NULL, NULL); diff --git a/test/core/end2end/end2end_nosec_tests.c b/test/core/end2end/end2end_nosec_tests.c index a6302621970..caaa97c215b 100644 --- a/test/core/end2end/end2end_nosec_tests.c +++ b/test/core/end2end/end2end_nosec_tests.c @@ -111,6 +111,8 @@ extern void request_with_flags(grpc_end2end_test_config config); extern void request_with_flags_pre_init(void); extern void request_with_payload(grpc_end2end_test_config config); extern void request_with_payload_pre_init(void); +extern void resource_quota_server(grpc_end2end_test_config config); +extern void resource_quota_server_pre_init(void); extern void server_finishes_request(grpc_end2end_test_config config); extern void server_finishes_request_pre_init(void); extern void shutdown_finishes_calls(grpc_end2end_test_config config); @@ -167,6 +169,7 @@ void grpc_end2end_tests_pre_init(void) { registered_call_pre_init(); request_with_flags_pre_init(); request_with_payload_pre_init(); + resource_quota_server_pre_init(); server_finishes_request_pre_init(); shutdown_finishes_calls_pre_init(); shutdown_finishes_tags_pre_init(); @@ -219,6 +222,7 @@ void grpc_end2end_tests(int argc, char **argv, registered_call(config); request_with_flags(config); request_with_payload(config); + resource_quota_server(config); server_finishes_request(config); shutdown_finishes_calls(config); shutdown_finishes_tags(config); @@ -368,6 +372,10 @@ void grpc_end2end_tests(int argc, char **argv, request_with_payload(config); continue; } + if (0 == strcmp("resource_quota_server", argv[i])) { + resource_quota_server(config); + continue; + } if (0 == strcmp("server_finishes_request", argv[i])) { server_finishes_request(config); continue; diff --git a/test/core/end2end/end2end_tests.c b/test/core/end2end/end2end_tests.c index 925872a71ff..6d17e686e61 100644 --- a/test/core/end2end/end2end_tests.c +++ b/test/core/end2end/end2end_tests.c @@ -113,6 +113,8 @@ extern void request_with_flags(grpc_end2end_test_config config); extern void request_with_flags_pre_init(void); extern void request_with_payload(grpc_end2end_test_config config); extern void request_with_payload_pre_init(void); +extern void resource_quota_server(grpc_end2end_test_config config); +extern void resource_quota_server_pre_init(void); extern void server_finishes_request(grpc_end2end_test_config config); extern void server_finishes_request_pre_init(void); extern void shutdown_finishes_calls(grpc_end2end_test_config config); @@ -170,6 +172,7 @@ void grpc_end2end_tests_pre_init(void) { registered_call_pre_init(); request_with_flags_pre_init(); request_with_payload_pre_init(); + resource_quota_server_pre_init(); server_finishes_request_pre_init(); shutdown_finishes_calls_pre_init(); shutdown_finishes_tags_pre_init(); @@ -223,6 +226,7 @@ void grpc_end2end_tests(int argc, char **argv, registered_call(config); request_with_flags(config); request_with_payload(config); + resource_quota_server(config); server_finishes_request(config); shutdown_finishes_calls(config); shutdown_finishes_tags(config); @@ -376,6 +380,10 @@ void grpc_end2end_tests(int argc, char **argv, request_with_payload(config); continue; } + if (0 == strcmp("resource_quota_server", argv[i])) { + resource_quota_server(config); + continue; + } if (0 == strcmp("server_finishes_request", argv[i])) { server_finishes_request(config); continue; diff --git a/test/core/end2end/fixtures/h2_sockpair+trace.c b/test/core/end2end/fixtures/h2_sockpair+trace.c index 15b045c33c4..a358edf3212 100644 --- a/test/core/end2end/fixtures/h2_sockpair+trace.c +++ b/test/core/end2end/fixtures/h2_sockpair+trace.c @@ -96,7 +96,9 @@ static grpc_end2end_test_fixture chttp2_create_fixture_socketpair( f.fixture_data = sfd; f.cq = grpc_completion_queue_create(NULL); - *sfd = grpc_iomgr_create_endpoint_pair("fixture", 65536); + grpc_resource_quota *resource_quota = grpc_resource_quota_create("fixture"); + *sfd = grpc_iomgr_create_endpoint_pair("fixture", resource_quota, 65536); + grpc_resource_quota_unref(resource_quota); return f; } diff --git a/test/core/end2end/fixtures/h2_sockpair.c b/test/core/end2end/fixtures/h2_sockpair.c index 87091f77a3b..8f7083af59a 100644 --- a/test/core/end2end/fixtures/h2_sockpair.c +++ b/test/core/end2end/fixtures/h2_sockpair.c @@ -90,7 +90,9 @@ static grpc_end2end_test_fixture chttp2_create_fixture_socketpair( f.fixture_data = sfd; f.cq = grpc_completion_queue_create(NULL); - *sfd = grpc_iomgr_create_endpoint_pair("fixture", 65536); + grpc_resource_quota *resource_quota = grpc_resource_quota_create("fixture"); + *sfd = grpc_iomgr_create_endpoint_pair("fixture", resource_quota, 65536); + grpc_resource_quota_unref(resource_quota); return f; } diff --git a/test/core/end2end/fixtures/h2_sockpair_1byte.c b/test/core/end2end/fixtures/h2_sockpair_1byte.c index 7d0a14cd634..b3d9924c122 100644 --- a/test/core/end2end/fixtures/h2_sockpair_1byte.c +++ b/test/core/end2end/fixtures/h2_sockpair_1byte.c @@ -90,7 +90,9 @@ static grpc_end2end_test_fixture chttp2_create_fixture_socketpair( f.fixture_data = sfd; f.cq = grpc_completion_queue_create(NULL); - *sfd = grpc_iomgr_create_endpoint_pair("fixture", 1); + grpc_resource_quota *resource_quota = grpc_resource_quota_create("fixture"); + *sfd = grpc_iomgr_create_endpoint_pair("fixture", resource_quota, 1); + grpc_resource_quota_unref(resource_quota); return f; } diff --git a/test/core/end2end/fixtures/http_proxy.c b/test/core/end2end/fixtures/http_proxy.c index b8f046c7dfc..630f47ef0ec 100644 --- a/test/core/end2end/fixtures/http_proxy.c +++ b/test/core/end2end/fixtures/http_proxy.c @@ -359,7 +359,7 @@ static void on_read_request_done(grpc_exec_ctx* exec_ctx, void* arg, const gpr_timespec deadline = gpr_time_add( gpr_now(GPR_CLOCK_MONOTONIC), gpr_time_from_seconds(10, GPR_TIMESPAN)); grpc_tcp_client_connect(exec_ctx, &conn->on_server_connect_done, - &conn->server_endpoint, conn->pollset_set, + &conn->server_endpoint, conn->pollset_set, NULL, &resolved_addresses->addrs[0], deadline); grpc_resolved_addresses_destroy(resolved_addresses); } @@ -418,7 +418,8 @@ static void thread_main(void* arg) { grpc_exec_ctx_finish(&exec_ctx); } -grpc_end2end_http_proxy* grpc_end2end_http_proxy_create() { +grpc_end2end_http_proxy* grpc_end2end_http_proxy_create(void) { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_end2end_http_proxy* proxy = gpr_malloc(sizeof(*proxy)); memset(proxy, 0, sizeof(*proxy)); // Construct proxy address. @@ -427,8 +428,8 @@ grpc_end2end_http_proxy* grpc_end2end_http_proxy_create() { gpr_log(GPR_INFO, "Proxy address: %s", proxy->proxy_name); // Create TCP server. proxy->channel_args = grpc_channel_args_copy(NULL); - grpc_error* error = - grpc_tcp_server_create(NULL, proxy->channel_args, &proxy->server); + grpc_error* error = grpc_tcp_server_create( + &exec_ctx, NULL, proxy->channel_args, &proxy->server); GPR_ASSERT(error == GRPC_ERROR_NONE); // Bind to port. grpc_resolved_address resolved_addr; @@ -443,7 +444,6 @@ grpc_end2end_http_proxy* grpc_end2end_http_proxy_create() { // Start server. proxy->pollset = gpr_malloc(grpc_pollset_size()); grpc_pollset_init(proxy->pollset, &proxy->mu); - grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_tcp_server_start(&exec_ctx, proxy->server, &proxy->pollset, 1, on_accept, proxy); grpc_exec_ctx_finish(&exec_ctx); diff --git a/test/core/end2end/fuzzers/api_fuzzer.c b/test/core/end2end/fuzzers/api_fuzzer.c index 4e19b760141..659f5cf5cbb 100644 --- a/test/core/end2end/fuzzers/api_fuzzer.c +++ b/test/core/end2end/fuzzers/api_fuzzer.c @@ -173,6 +173,7 @@ static bool is_eof(input_stream *inp) { return inp->cur == inp->end; } static gpr_timespec g_now; static grpc_server *g_server; static grpc_channel *g_channel; +static grpc_resource_quota *g_resource_quota; extern gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type); @@ -231,8 +232,8 @@ void my_resolve_address(grpc_exec_ctx *exec_ctx, const char *addr, // defined in tcp_client_posix.c extern void (*grpc_tcp_client_connect_impl)( grpc_exec_ctx *exec_ctx, grpc_closure *closure, grpc_endpoint **ep, - grpc_pollset_set *interested_parties, const grpc_resolved_address *addr, - gpr_timespec deadline); + grpc_pollset_set *interested_parties, const grpc_channel_args *channel_args, + const grpc_resolved_address *addr, gpr_timespec deadline); static void sched_connect(grpc_exec_ctx *exec_ctx, grpc_closure *closure, grpc_endpoint **ep, gpr_timespec deadline); @@ -252,7 +253,7 @@ static void do_connect(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) { } else if (g_server != NULL) { grpc_endpoint *client; grpc_endpoint *server; - grpc_passthru_endpoint_create(&client, &server); + grpc_passthru_endpoint_create(&client, &server, g_resource_quota); *fc->ep = client; grpc_transport *transport = @@ -289,6 +290,7 @@ static void sched_connect(grpc_exec_ctx *exec_ctx, grpc_closure *closure, static void my_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, gpr_timespec deadline) { sched_connect(exec_ctx, closure, ep, deadline); @@ -520,6 +522,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { int pending_pings = 0; g_active_call = new_call(NULL, ROOT); + g_resource_quota = grpc_resource_quota_create("api_fuzzer"); grpc_completion_queue *cq = grpc_completion_queue_create(NULL); @@ -939,6 +942,11 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { } break; } + // resize the buffer pool + case 21: { + grpc_resource_quota_resize(g_resource_quota, read_uint22(&inp)); + break; + } } } @@ -954,6 +962,8 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { .type == GRPC_QUEUE_SHUTDOWN); grpc_completion_queue_destroy(cq); + grpc_resource_quota_unref(g_resource_quota); + grpc_shutdown(); return 0; } diff --git a/test/core/end2end/fuzzers/client_fuzzer.c b/test/core/end2end/fuzzers/client_fuzzer.c index 00e650a30b9..d104fe55e59 100644 --- a/test/core/end2end/fuzzers/client_fuzzer.c +++ b/test/core/end2end/fuzzers/client_fuzzer.c @@ -58,7 +58,11 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { grpc_init(); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - grpc_endpoint *mock_endpoint = grpc_mock_endpoint_create(discard_write); + grpc_resource_quota *resource_quota = + grpc_resource_quota_create("client_fuzzer"); + grpc_endpoint *mock_endpoint = + grpc_mock_endpoint_create(discard_write, resource_quota); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); grpc_completion_queue *cq = grpc_completion_queue_create(NULL); grpc_transport *transport = diff --git a/test/core/end2end/fuzzers/client_fuzzer_corpus/server_hanging_response_1_header b/test/core/end2end/fuzzers/client_fuzzer_corpus/server_hanging_response_1_header new file mode 100644 index 00000000000..d2abd17464c Binary files /dev/null and b/test/core/end2end/fuzzers/client_fuzzer_corpus/server_hanging_response_1_header differ diff --git a/test/core/end2end/fuzzers/client_fuzzer_corpus/server_hanging_response_2_header2 b/test/core/end2end/fuzzers/client_fuzzer_corpus/server_hanging_response_2_header2 new file mode 100644 index 00000000000..752af468ba6 Binary files /dev/null and b/test/core/end2end/fuzzers/client_fuzzer_corpus/server_hanging_response_2_header2 differ diff --git a/tools/dockerfile/grpc_check_generated_pb_files/check_pb_files.sh b/test/core/end2end/fuzzers/generate_client_examples_of_bad_closing_streams.py similarity index 70% rename from tools/dockerfile/grpc_check_generated_pb_files/check_pb_files.sh rename to test/core/end2end/fuzzers/generate_client_examples_of_bad_closing_streams.py index 9db7aae9eba..d80c1e0442b 100755 --- a/tools/dockerfile/grpc_check_generated_pb_files/check_pb_files.sh +++ b/test/core/end2end/fuzzers/generate_client_examples_of_bad_closing_streams.py @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env python2.7 # Copyright 2015, Google Inc. # All rights reserved. # @@ -28,23 +28,22 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -set -e +import os +import sys -mkdir -p /var/local/git -git clone /var/local/jenkins/grpc /var/local/git/grpc -# clone gRPC submodules, use data from locally cloned submodules where possible -(cd /var/local/jenkins/grpc/ && git submodule foreach 'cd /var/local/git/grpc \ -&& git submodule update --init --reference /var/local/jenkins/grpc/${name} \ -${name}') +os.chdir(os.path.dirname(sys.argv[0])) -cd /var/local/git/grpc +streams = { + 'server_hanging_response_1_header': ( + [0,0,0,4,0,0,0,0,0] + # settings frame + [0,0,0,1,5,0,0,0,1] # trailers + ), + 'server_hanging_response_2_header2': ( + [0,0,0,4,0,0,0,0,0] + # settings frame + [0,0,0,1,4,0,0,0,1] + # headers + [0,0,0,1,5,0,0,0,1] # trailers + ), +} -# build grpc cpp plugin for generating grpc pb files -make grpc_cpp_plugin - -# generate pb files -tools/codegen/extensions/gen_reflection_proto.sh - -# check if the pb files in the checked out codebase are identical with the newly -# generated ones -git diff --exit-code +for name, stream in streams.items(): + open('client_fuzzer_corpus/%s' % name, 'w').write(bytearray(stream)) diff --git a/test/core/end2end/fuzzers/server_fuzzer.c b/test/core/end2end/fuzzers/server_fuzzer.c index 79eaad70c5d..ae4c8e658d0 100644 --- a/test/core/end2end/fuzzers/server_fuzzer.c +++ b/test/core/end2end/fuzzers/server_fuzzer.c @@ -56,7 +56,11 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { grpc_init(); grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - grpc_endpoint *mock_endpoint = grpc_mock_endpoint_create(discard_write); + grpc_resource_quota *resource_quota = + grpc_resource_quota_create("server_fuzzer"); + grpc_endpoint *mock_endpoint = + grpc_mock_endpoint_create(discard_write, resource_quota); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); grpc_mock_endpoint_put_read( &exec_ctx, mock_endpoint, gpr_slice_from_copied_buffer((const char *)data, size)); diff --git a/test/core/end2end/gen_build_yaml.py b/test/core/end2end/gen_build_yaml.py index 0bbf10d475c..bdb3874c210 100755 --- a/test/core/end2end/gen_build_yaml.py +++ b/test/core/end2end/gen_build_yaml.py @@ -39,9 +39,9 @@ import hashlib FixtureOptions = collections.namedtuple( 'FixtureOptions', - 'fullstack includes_proxy dns_resolver secure platforms ci_mac tracing exclude_configs exclude_iomgrs') + 'fullstack includes_proxy dns_resolver secure platforms ci_mac tracing exclude_configs exclude_iomgrs large_writes') default_unsecure_fixture_options = FixtureOptions( - True, False, True, False, ['windows', 'linux', 'mac', 'posix'], True, False, [], []) + True, False, True, False, ['windows', 'linux', 'mac', 'posix'], True, False, [], [], True) socketpair_unsecure_fixture_options = default_unsecure_fixture_options._replace(fullstack=False, dns_resolver=False) default_secure_fixture_options = default_unsecure_fixture_options._replace(secure=True) uds_fixture_options = default_unsecure_fixture_options._replace(dns_resolver=False, platforms=['linux', 'mac', 'posix'], exclude_iomgrs=['uv']) @@ -69,11 +69,12 @@ END2END_FIXTURES = { 'h2_proxy': default_unsecure_fixture_options._replace( includes_proxy=True, ci_mac=False, exclude_iomgrs=['uv']), 'h2_sockpair_1byte': socketpair_unsecure_fixture_options._replace( - ci_mac=False, exclude_configs=['msan'], exclude_iomgrs=['uv']), + ci_mac=False, exclude_configs=['msan'], large_writes=False, + exclude_iomgrs=['uv']), 'h2_sockpair': socketpair_unsecure_fixture_options._replace( ci_mac=False, exclude_iomgrs=['uv']), 'h2_sockpair+trace': socketpair_unsecure_fixture_options._replace( - ci_mac=False, tracing=True, exclude_iomgrs=['uv']), + ci_mac=False, tracing=True, large_writes=False, exclude_iomgrs=['uv']), 'h2_ssl': default_secure_fixture_options, 'h2_ssl_cert': default_secure_fixture_options, 'h2_ssl_proxy': default_secure_fixture_options._replace( @@ -83,8 +84,8 @@ END2END_FIXTURES = { TestOptions = collections.namedtuple( 'TestOptions', - 'needs_fullstack needs_dns proxyable secure traceable cpu_cost exclude_iomgrs') -default_test_options = TestOptions(False, False, True, False, True, 1.0, []) + 'needs_fullstack needs_dns proxyable secure traceable cpu_cost exclude_iomgrs large_writes flaky') +default_test_options = TestOptions(False, False, True, False, True, 1.0, [], False, False) connectivity_test_options = default_test_options._replace(needs_fullstack=True) LOWCPU = 0.1 @@ -93,6 +94,8 @@ LOWCPU = 0.1 END2END_TESTS = { 'bad_hostname': default_test_options, 'binary_metadata': default_test_options, + 'resource_quota_server': default_test_options._replace(large_writes=True, + proxyable=False), 'call_creds': default_test_options._replace(secure=True), 'cancel_after_accept': default_test_options._replace(cpu_cost=LOWCPU), 'cancel_after_client_done': default_test_options, @@ -105,7 +108,7 @@ END2END_TESTS = { proxyable=False, cpu_cost=LOWCPU, exclude_iomgrs=['uv']), 'default_host': default_test_options._replace(needs_fullstack=True, needs_dns=True), - 'disappearing_server': connectivity_test_options, + 'disappearing_server': connectivity_test_options._replace(flaky=True), 'empty_batch': default_test_options, 'filter_causes_close': default_test_options, 'filter_call_init_fails': default_test_options, @@ -155,6 +158,9 @@ def compatible(f, t): if not END2END_TESTS[t].traceable: if END2END_FIXTURES[f].tracing: return False + if END2END_TESTS[t].large_writes: + if not END2END_FIXTURES[f].large_writes: + return False return True @@ -257,7 +263,7 @@ def main(): 'ci_platforms': (END2END_FIXTURES[f].platforms if END2END_FIXTURES[f].ci_mac else without( END2END_FIXTURES[f].platforms, 'mac')), - 'flaky': False, + 'flaky': END2END_TESTS[t].flaky, 'language': 'c', 'cpu_cost': END2END_TESTS[t].cpu_cost, } @@ -274,7 +280,7 @@ def main(): 'ci_platforms': (END2END_FIXTURES[f].platforms if END2END_FIXTURES[f].ci_mac else without( END2END_FIXTURES[f].platforms, 'mac')), - 'flaky': False, + 'flaky': END2END_TESTS[t].flaky, 'language': 'c', 'cpu_cost': END2END_TESTS[t].cpu_cost, } diff --git a/test/core/end2end/tests/max_message_length.c b/test/core/end2end/tests/max_message_length.c index e698987a0a4..449a581d232 100644 --- a/test/core/end2end/tests/max_message_length.c +++ b/test/core/end2end/tests/max_message_length.c @@ -402,7 +402,6 @@ static void test_max_message_length_on_response(grpc_end2end_test_config config, GPR_ASSERT(0 == strcmp(call_details.method, "/service/method")); GPR_ASSERT(0 == strcmp(call_details.host, "foo.test.google.fr:1234")); - GPR_ASSERT(was_cancelled == 0); GPR_ASSERT(status == GRPC_STATUS_INVALID_ARGUMENT); GPR_ASSERT(strcmp(details, diff --git a/test/core/end2end/tests/network_status_change.c b/test/core/end2end/tests/network_status_change.c index 8d6b8f87840..fa711bb0b60 100644 --- a/test/core/end2end/tests/network_status_change.c +++ b/test/core/end2end/tests/network_status_change.c @@ -213,7 +213,6 @@ static void test_invoke_network_status_change(grpc_end2end_test_config config) { GPR_ASSERT(status == GRPC_STATUS_UNAVAILABLE); GPR_ASSERT(0 == strcmp(call_details.method, "/foo")); GPR_ASSERT(0 == strcmp(call_details.host, "foo.test.google.fr")); - GPR_ASSERT(was_cancelled == 0); gpr_free(details); grpc_metadata_array_destroy(&initial_metadata_recv); diff --git a/test/core/end2end/tests/resource_quota_server.c b/test/core/end2end/tests/resource_quota_server.c new file mode 100644 index 00000000000..47c5ed6abb7 --- /dev/null +++ b/test/core/end2end/tests/resource_quota_server.c @@ -0,0 +1,380 @@ +/* + * + * Copyright 2016, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "test/core/end2end/end2end_tests.h" + +#include +#include + +#include +#include +#include +#include +#include +#include "test/core/end2end/cq_verifier.h" + +static void *tag(intptr_t t) { return (void *)t; } + +static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config, + const char *test_name, + grpc_channel_args *client_args, + grpc_channel_args *server_args) { + grpc_end2end_test_fixture f; + gpr_log(GPR_INFO, "%s/%s", test_name, config.name); + f = config.create_fixture(client_args, server_args); + config.init_server(&f, server_args); + config.init_client(&f, client_args, NULL); + return f; +} + +static gpr_timespec n_seconds_time(int n) { + return GRPC_TIMEOUT_SECONDS_TO_DEADLINE(n); +} + +static gpr_timespec five_seconds_time(void) { return n_seconds_time(5); } + +static void drain_cq(grpc_completion_queue *cq) { + grpc_event ev; + do { + ev = grpc_completion_queue_next(cq, five_seconds_time(), NULL); + } while (ev.type != GRPC_QUEUE_SHUTDOWN); +} + +static void shutdown_server(grpc_end2end_test_fixture *f) { + if (!f->server) return; + grpc_server_shutdown_and_notify(f->server, f->cq, tag(1000)); + GPR_ASSERT(grpc_completion_queue_pluck( + f->cq, tag(1000), GRPC_TIMEOUT_SECONDS_TO_DEADLINE(5), NULL) + .type == GRPC_OP_COMPLETE); + grpc_server_destroy(f->server); + f->server = NULL; +} + +static void shutdown_client(grpc_end2end_test_fixture *f) { + if (!f->client) return; + grpc_channel_destroy(f->client); + f->client = NULL; +} + +static void end_test(grpc_end2end_test_fixture *f) { + shutdown_server(f); + shutdown_client(f); + + grpc_completion_queue_shutdown(f->cq); + drain_cq(f->cq); + grpc_completion_queue_destroy(f->cq); +} + +/* Creates and returns a gpr_slice containing random alphanumeric characters. */ +static gpr_slice generate_random_slice() { + size_t i; + static const char chars[] = "abcdefghijklmnopqrstuvwxyz1234567890"; + char *output; + const size_t output_size = 1024 * 1024; + output = gpr_malloc(output_size); + for (i = 0; i < output_size - 1; ++i) { + output[i] = chars[rand() % (int)(sizeof(chars) - 1)]; + } + output[output_size - 1] = '\0'; + gpr_slice out = gpr_slice_from_copied_string(output); + gpr_free(output); + return out; +} + +void resource_quota_server(grpc_end2end_test_config config) { + grpc_resource_quota *resource_quota = + grpc_resource_quota_create("test_server"); + grpc_resource_quota_resize(resource_quota, 5 * 1024 * 1024); + +#define NUM_CALLS 100 +#define CLIENT_BASE_TAG 1000 +#define SERVER_START_BASE_TAG 2000 +#define SERVER_RECV_BASE_TAG 3000 +#define SERVER_END_BASE_TAG 4000 + + grpc_arg arg; + arg.key = GRPC_ARG_RESOURCE_QUOTA; + arg.type = GRPC_ARG_POINTER; + arg.value.pointer.p = resource_quota; + arg.value.pointer.vtable = grpc_resource_quota_arg_vtable(); + grpc_channel_args args = {1, &arg}; + + grpc_end2end_test_fixture f = + begin_test(config, "resource_quota_server", NULL, &args); + + /* Create large request and response bodies. These are big enough to require + * multiple round trips to deliver to the peer, and their exact contents of + * will be verified on completion. */ + gpr_slice request_payload_slice = generate_random_slice(); + + grpc_call **client_calls = malloc(sizeof(grpc_call *) * NUM_CALLS); + grpc_call **server_calls = malloc(sizeof(grpc_call *) * NUM_CALLS); + grpc_metadata_array *initial_metadata_recv = + malloc(sizeof(grpc_metadata_array) * NUM_CALLS); + grpc_metadata_array *trailing_metadata_recv = + malloc(sizeof(grpc_metadata_array) * NUM_CALLS); + grpc_metadata_array *request_metadata_recv = + malloc(sizeof(grpc_metadata_array) * NUM_CALLS); + grpc_call_details *call_details = + malloc(sizeof(grpc_call_details) * NUM_CALLS); + grpc_status_code *status = malloc(sizeof(grpc_status_code) * NUM_CALLS); + char **details = malloc(sizeof(char *) * NUM_CALLS); + size_t *details_capacity = malloc(sizeof(size_t) * NUM_CALLS); + grpc_byte_buffer **request_payload_recv = + malloc(sizeof(grpc_byte_buffer *) * NUM_CALLS); + int *was_cancelled = malloc(sizeof(int) * NUM_CALLS); + grpc_call_error error; + int pending_client_calls = 0; + int pending_server_start_calls = 0; + int pending_server_recv_calls = 0; + int pending_server_end_calls = 0; + int cancelled_calls_on_client = 0; + int cancelled_calls_on_server = 0; + + grpc_byte_buffer *request_payload = + grpc_raw_byte_buffer_create(&request_payload_slice, 1); + + grpc_op ops[6]; + grpc_op *op; + + for (int i = 0; i < NUM_CALLS; i++) { + grpc_metadata_array_init(&initial_metadata_recv[i]); + grpc_metadata_array_init(&trailing_metadata_recv[i]); + grpc_metadata_array_init(&request_metadata_recv[i]); + grpc_call_details_init(&call_details[i]); + details[i] = NULL; + details_capacity[i] = 0; + request_payload_recv[i] = NULL; + was_cancelled[i] = 0; + } + + for (int i = 0; i < NUM_CALLS; i++) { + error = grpc_server_request_call( + f.server, &server_calls[i], &call_details[i], &request_metadata_recv[i], + f.cq, f.cq, tag(SERVER_START_BASE_TAG + i)); + GPR_ASSERT(GRPC_CALL_OK == error); + + pending_server_start_calls++; + } + + for (int i = 0; i < NUM_CALLS; i++) { + client_calls[i] = grpc_channel_create_call( + f.client, NULL, GRPC_PROPAGATE_DEFAULTS, f.cq, "/foo", + "foo.test.google.fr", n_seconds_time(60), NULL); + + memset(ops, 0, sizeof(ops)); + op = ops; + op->op = GRPC_OP_SEND_INITIAL_METADATA; + op->data.send_initial_metadata.count = 0; + op->flags = 0; + op->reserved = NULL; + op++; + op->op = GRPC_OP_SEND_MESSAGE; + op->data.send_message = request_payload; + op->flags = 0; + op->reserved = NULL; + op++; + op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; + op->flags = 0; + op->reserved = NULL; + op++; + op->op = GRPC_OP_RECV_INITIAL_METADATA; + op->data.recv_initial_metadata = &initial_metadata_recv[i]; + op->flags = 0; + op->reserved = NULL; + op++; + op->op = GRPC_OP_RECV_STATUS_ON_CLIENT; + op->data.recv_status_on_client.trailing_metadata = + &trailing_metadata_recv[i]; + op->data.recv_status_on_client.status = &status[i]; + op->data.recv_status_on_client.status_details = &details[i]; + op->data.recv_status_on_client.status_details_capacity = + &details_capacity[i]; + op->flags = 0; + op->reserved = NULL; + op++; + error = grpc_call_start_batch(client_calls[i], ops, (size_t)(op - ops), + tag(CLIENT_BASE_TAG + i), NULL); + GPR_ASSERT(GRPC_CALL_OK == error); + + pending_client_calls++; + } + + while (pending_client_calls + pending_server_recv_calls + + pending_server_end_calls > + 0) { + grpc_event ev = grpc_completion_queue_next(f.cq, n_seconds_time(10), NULL); + GPR_ASSERT(ev.type == GRPC_OP_COMPLETE); + + int ev_tag = (int)(intptr_t)ev.tag; + if (ev_tag < CLIENT_BASE_TAG) { + abort(); /* illegal tag */ + } else if (ev_tag < SERVER_START_BASE_TAG) { + /* client call finished */ + int call_id = ev_tag - CLIENT_BASE_TAG; + GPR_ASSERT(call_id >= 0); + GPR_ASSERT(call_id < NUM_CALLS); + switch (status[call_id]) { + case GRPC_STATUS_RESOURCE_EXHAUSTED: + cancelled_calls_on_client++; + break; + case GRPC_STATUS_OK: + break; + default: + gpr_log(GPR_ERROR, "Unexpected status code: %d", status[call_id]); + abort(); + } + GPR_ASSERT(pending_client_calls > 0); + + grpc_metadata_array_destroy(&initial_metadata_recv[call_id]); + grpc_metadata_array_destroy(&trailing_metadata_recv[call_id]); + grpc_call_destroy(client_calls[call_id]); + gpr_free(details[call_id]); + + pending_client_calls--; + } else if (ev_tag < SERVER_RECV_BASE_TAG) { + /* new incoming call to the server */ + int call_id = ev_tag - SERVER_START_BASE_TAG; + GPR_ASSERT(call_id >= 0); + GPR_ASSERT(call_id < NUM_CALLS); + + memset(ops, 0, sizeof(ops)); + op = ops; + op->op = GRPC_OP_SEND_INITIAL_METADATA; + op->data.send_initial_metadata.count = 0; + op->flags = 0; + op->reserved = NULL; + op++; + op->op = GRPC_OP_RECV_MESSAGE; + op->data.recv_message = &request_payload_recv[call_id]; + op->flags = 0; + op->reserved = NULL; + op++; + error = + grpc_call_start_batch(server_calls[call_id], ops, (size_t)(op - ops), + tag(SERVER_RECV_BASE_TAG + call_id), NULL); + GPR_ASSERT(GRPC_CALL_OK == error); + + GPR_ASSERT(pending_server_start_calls > 0); + pending_server_start_calls--; + pending_server_recv_calls++; + + grpc_call_details_destroy(&call_details[call_id]); + grpc_metadata_array_destroy(&request_metadata_recv[call_id]); + } else if (ev_tag < SERVER_END_BASE_TAG) { + /* finished read on the server */ + int call_id = ev_tag - SERVER_RECV_BASE_TAG; + GPR_ASSERT(call_id >= 0); + GPR_ASSERT(call_id < NUM_CALLS); + + if (ev.success) { + if (request_payload_recv[call_id] != NULL) { + grpc_byte_buffer_destroy(request_payload_recv[call_id]); + request_payload_recv[call_id] = NULL; + } + } else { + GPR_ASSERT(request_payload_recv[call_id] == NULL); + } + + memset(ops, 0, sizeof(ops)); + op = ops; + op->op = GRPC_OP_RECV_CLOSE_ON_SERVER; + op->data.recv_close_on_server.cancelled = &was_cancelled[call_id]; + op->flags = 0; + op->reserved = NULL; + op++; + op->op = GRPC_OP_SEND_STATUS_FROM_SERVER; + op->data.send_status_from_server.trailing_metadata_count = 0; + op->data.send_status_from_server.status = GRPC_STATUS_OK; + op->data.send_status_from_server.status_details = "xyz"; + op->flags = 0; + op->reserved = NULL; + op++; + error = + grpc_call_start_batch(server_calls[call_id], ops, (size_t)(op - ops), + tag(SERVER_END_BASE_TAG + call_id), NULL); + GPR_ASSERT(GRPC_CALL_OK == error); + + GPR_ASSERT(pending_server_recv_calls > 0); + pending_server_recv_calls--; + pending_server_end_calls++; + } else { + int call_id = ev_tag - SERVER_END_BASE_TAG; + GPR_ASSERT(call_id >= 0); + GPR_ASSERT(call_id < NUM_CALLS); + + if (was_cancelled[call_id]) { + cancelled_calls_on_server++; + } + GPR_ASSERT(pending_server_end_calls > 0); + pending_server_end_calls--; + + grpc_call_destroy(server_calls[call_id]); + } + } + + gpr_log( + GPR_INFO, + "Done. %d total calls: %d cancelled at server, %d cancelled at client.", + NUM_CALLS, cancelled_calls_on_server, cancelled_calls_on_client); + + /* The call may be cancelled after the server has sent its status but before + * the client has received it. This means that we should see strictly more + * failures on the client than on the server. */ + GPR_ASSERT(cancelled_calls_on_client >= cancelled_calls_on_server); + /* However, we shouldn't see radically more... 0.9 is a guessed bound on what + * we'd want that ratio to be... to at least trigger some investigation should + * that ratio become much higher. */ + GPR_ASSERT(cancelled_calls_on_server >= 0.9 * cancelled_calls_on_client); + + grpc_byte_buffer_destroy(request_payload); + gpr_slice_unref(request_payload_slice); + grpc_resource_quota_unref(resource_quota); + + free(client_calls); + free(server_calls); + free(initial_metadata_recv); + free(trailing_metadata_recv); + free(request_metadata_recv); + free(call_details); + free(status); + free(details); + free(details_capacity); + free(request_payload_recv); + free(was_cancelled); + + end_test(&f); + config.tear_down_data(&f); +} + +void resource_quota_server_pre_init(void) {} diff --git a/test/core/http/httpcli_test.c b/test/core/http/httpcli_test.c index 38b32a3867f..3e312c1ddee 100644 --- a/test/core/http/httpcli_test.c +++ b/test/core/http/httpcli_test.c @@ -89,8 +89,11 @@ static void test_get(int port) { grpc_http_response response; memset(&response, 0, sizeof(response)); - grpc_httpcli_get(&exec_ctx, &g_context, &g_pops, &req, n_seconds_time(15), + grpc_resource_quota *resource_quota = grpc_resource_quota_create("test_get"); + grpc_httpcli_get(&exec_ctx, &g_context, &g_pops, resource_quota, &req, + n_seconds_time(15), grpc_closure_create(on_finish, &response), &response); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); gpr_mu_lock(g_mu); while (!g_done) { grpc_pollset_worker *worker = NULL; @@ -126,9 +129,11 @@ static void test_post(int port) { grpc_http_response response; memset(&response, 0, sizeof(response)); - grpc_httpcli_post(&exec_ctx, &g_context, &g_pops, &req, "hello", 5, - n_seconds_time(15), + grpc_resource_quota *resource_quota = grpc_resource_quota_create("test_post"); + grpc_httpcli_post(&exec_ctx, &g_context, &g_pops, resource_quota, &req, + "hello", 5, n_seconds_time(15), grpc_closure_create(on_finish, &response), &response); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); gpr_mu_lock(g_mu); while (!g_done) { grpc_pollset_worker *worker = NULL; diff --git a/test/core/http/httpscli_test.c b/test/core/http/httpscli_test.c index 359e5576894..d06035149ef 100644 --- a/test/core/http/httpscli_test.c +++ b/test/core/http/httpscli_test.c @@ -90,8 +90,11 @@ static void test_get(int port) { grpc_http_response response; memset(&response, 0, sizeof(response)); - grpc_httpcli_get(&exec_ctx, &g_context, &g_pops, &req, n_seconds_time(15), + grpc_resource_quota *resource_quota = grpc_resource_quota_create("test_get"); + grpc_httpcli_get(&exec_ctx, &g_context, &g_pops, resource_quota, &req, + n_seconds_time(15), grpc_closure_create(on_finish, &response), &response); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); gpr_mu_lock(g_mu); while (!g_done) { grpc_pollset_worker *worker = NULL; @@ -128,9 +131,11 @@ static void test_post(int port) { grpc_http_response response; memset(&response, 0, sizeof(response)); - grpc_httpcli_post(&exec_ctx, &g_context, &g_pops, &req, "hello", 5, - n_seconds_time(15), + grpc_resource_quota *resource_quota = grpc_resource_quota_create("test_post"); + grpc_httpcli_post(&exec_ctx, &g_context, &g_pops, resource_quota, &req, + "hello", 5, n_seconds_time(15), grpc_closure_create(on_finish, &response), &response); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); gpr_mu_lock(g_mu); while (!g_done) { grpc_pollset_worker *worker = NULL; diff --git a/test/core/internal_api_canaries/iomgr.c b/test/core/internal_api_canaries/iomgr.c index 27d630623ed..f1efa87a696 100644 --- a/test/core/internal_api_canaries/iomgr.c +++ b/test/core/internal_api_canaries/iomgr.c @@ -84,6 +84,7 @@ static void test_code(void) { grpc_endpoint_add_to_pollset_set, grpc_endpoint_shutdown, grpc_endpoint_destroy, + grpc_endpoint_get_resource_user, grpc_endpoint_get_peer}; endpoint.vtable = &vtable; diff --git a/test/core/iomgr/endpoint_pair_test.c b/test/core/iomgr/endpoint_pair_test.c index 99b86b62134..2a257a7ceac 100644 --- a/test/core/iomgr/endpoint_pair_test.c +++ b/test/core/iomgr/endpoint_pair_test.c @@ -49,7 +49,11 @@ static grpc_endpoint_test_fixture create_fixture_endpoint_pair( size_t slice_size) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_endpoint_test_fixture f; - grpc_endpoint_pair p = grpc_iomgr_create_endpoint_pair("test", slice_size); + grpc_resource_quota *resource_quota = + grpc_resource_quota_create("endpoint_pair_test"); + grpc_endpoint_pair p = + grpc_iomgr_create_endpoint_pair("test", resource_quota, slice_size); + grpc_resource_quota_unref(resource_quota); f.client_ep = p.client; f.server_ep = p.server; diff --git a/test/core/iomgr/fd_conservation_posix_test.c b/test/core/iomgr/fd_conservation_posix_test.c index bbb3f46497f..652b37eb6f4 100644 --- a/test/core/iomgr/fd_conservation_posix_test.c +++ b/test/core/iomgr/fd_conservation_posix_test.c @@ -52,15 +52,19 @@ int main(int argc, char **argv) { of descriptors */ rlim.rlim_cur = rlim.rlim_max = 10; GPR_ASSERT(0 == setrlimit(RLIMIT_NOFILE, &rlim)); + grpc_resource_quota *resource_quota = + grpc_resource_quota_create("fd_conservation_posix_test"); for (i = 0; i < 100; i++) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; - p = grpc_iomgr_create_endpoint_pair("test", 1); + p = grpc_iomgr_create_endpoint_pair("test", resource_quota, 1); grpc_endpoint_destroy(&exec_ctx, p.client); grpc_endpoint_destroy(&exec_ctx, p.server); grpc_exec_ctx_finish(&exec_ctx); } + grpc_resource_quota_unref(resource_quota); + grpc_iomgr_shutdown(); return 0; } diff --git a/test/core/iomgr/resource_quota_test.c b/test/core/iomgr/resource_quota_test.c new file mode 100644 index 00000000000..34dee1aee19 --- /dev/null +++ b/test/core/iomgr/resource_quota_test.c @@ -0,0 +1,749 @@ +/* + * + * Copyright 2016, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "src/core/lib/iomgr/resource_quota.h" + +#include +#include + +#include "test/core/util/test_config.h" + +static void inc_int_cb(grpc_exec_ctx *exec_ctx, void *a, grpc_error *error) { + ++*(int *)a; +} + +static void set_bool_cb(grpc_exec_ctx *exec_ctx, void *a, grpc_error *error) { + *(bool *)a = true; +} +grpc_closure *set_bool(bool *p) { return grpc_closure_create(set_bool_cb, p); } + +typedef struct { + size_t size; + grpc_resource_user *resource_user; + grpc_closure *then; +} reclaimer_args; +static void reclaimer_cb(grpc_exec_ctx *exec_ctx, void *args, + grpc_error *error) { + GPR_ASSERT(error == GRPC_ERROR_NONE); + reclaimer_args *a = args; + grpc_resource_user_free(exec_ctx, a->resource_user, a->size); + grpc_resource_user_finish_reclamation(exec_ctx, a->resource_user); + grpc_closure_run(exec_ctx, a->then, GRPC_ERROR_NONE); + gpr_free(a); +} +grpc_closure *make_reclaimer(grpc_resource_user *resource_user, size_t size, + grpc_closure *then) { + reclaimer_args *a = gpr_malloc(sizeof(*a)); + a->size = size; + a->resource_user = resource_user; + a->then = then; + return grpc_closure_create(reclaimer_cb, a); +} + +static void unused_reclaimer_cb(grpc_exec_ctx *exec_ctx, void *arg, + grpc_error *error) { + GPR_ASSERT(error == GRPC_ERROR_CANCELLED); + grpc_closure_run(exec_ctx, arg, GRPC_ERROR_NONE); +} +grpc_closure *make_unused_reclaimer(grpc_closure *then) { + return grpc_closure_create(unused_reclaimer_cb, then); +} + +static void destroy_user(grpc_resource_user *usr) { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + bool done = false; + grpc_resource_user_shutdown(&exec_ctx, usr, set_bool(&done)); + grpc_exec_ctx_flush(&exec_ctx); + GPR_ASSERT(done); + grpc_resource_user_destroy(&exec_ctx, usr); + grpc_exec_ctx_finish(&exec_ctx); +} + +static void test_no_op(void) { + gpr_log(GPR_INFO, "** test_no_op **"); + grpc_resource_quota_unref(grpc_resource_quota_create("test_no_op")); +} + +static void test_resize_then_destroy(void) { + gpr_log(GPR_INFO, "** test_resize_then_destroy **"); + grpc_resource_quota *q = + grpc_resource_quota_create("test_resize_then_destroy"); + grpc_resource_quota_resize(q, 1024 * 1024); + grpc_resource_quota_unref(q); +} + +static void test_resource_user_no_op(void) { + gpr_log(GPR_INFO, "** test_resource_user_no_op **"); + grpc_resource_quota *q = + grpc_resource_quota_create("test_resource_user_no_op"); + grpc_resource_user usr; + grpc_resource_user_init(&usr, q, "usr"); + grpc_resource_quota_unref(q); + destroy_user(&usr); +} + +static void test_instant_alloc_then_free(void) { + gpr_log(GPR_INFO, "** test_instant_alloc_then_free **"); + grpc_resource_quota *q = + grpc_resource_quota_create("test_instant_alloc_then_free"); + grpc_resource_quota_resize(q, 1024 * 1024); + grpc_resource_user usr; + grpc_resource_user_init(&usr, q, "usr"); + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr, 1024, NULL); + grpc_exec_ctx_finish(&exec_ctx); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_free(&exec_ctx, &usr, 1024); + grpc_exec_ctx_finish(&exec_ctx); + } + grpc_resource_quota_unref(q); + destroy_user(&usr); +} + +static void test_instant_alloc_free_pair(void) { + gpr_log(GPR_INFO, "** test_instant_alloc_free_pair **"); + grpc_resource_quota *q = + grpc_resource_quota_create("test_instant_alloc_free_pair"); + grpc_resource_quota_resize(q, 1024 * 1024); + grpc_resource_user usr; + grpc_resource_user_init(&usr, q, "usr"); + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr, 1024, NULL); + grpc_resource_user_free(&exec_ctx, &usr, 1024); + grpc_exec_ctx_finish(&exec_ctx); + } + grpc_resource_quota_unref(q); + destroy_user(&usr); +} + +static void test_simple_async_alloc(void) { + gpr_log(GPR_INFO, "** test_simple_async_alloc **"); + grpc_resource_quota *q = + grpc_resource_quota_create("test_simple_async_alloc"); + grpc_resource_quota_resize(q, 1024 * 1024); + grpc_resource_user usr; + grpc_resource_user_init(&usr, q, "usr"); + { + bool done = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr, 1024, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(done); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_free(&exec_ctx, &usr, 1024); + grpc_exec_ctx_finish(&exec_ctx); + } + grpc_resource_quota_unref(q); + destroy_user(&usr); +} + +static void test_async_alloc_blocked_by_size(void) { + gpr_log(GPR_INFO, "** test_async_alloc_blocked_by_size **"); + grpc_resource_quota *q = + grpc_resource_quota_create("test_async_alloc_blocked_by_size"); + grpc_resource_quota_resize(q, 1); + grpc_resource_user usr; + grpc_resource_user_init(&usr, q, "usr"); + bool done = false; + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr, 1024, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(!done); + } + grpc_resource_quota_resize(q, 1024); + GPR_ASSERT(done); + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_free(&exec_ctx, &usr, 1024); + grpc_exec_ctx_finish(&exec_ctx); + } + grpc_resource_quota_unref(q); + destroy_user(&usr); +} + +static void test_scavenge(void) { + gpr_log(GPR_INFO, "** test_scavenge **"); + grpc_resource_quota *q = grpc_resource_quota_create("test_scavenge"); + grpc_resource_quota_resize(q, 1024); + grpc_resource_user usr1; + grpc_resource_user usr2; + grpc_resource_user_init(&usr1, q, "usr1"); + grpc_resource_user_init(&usr2, q, "usr2"); + { + bool done = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr1, 1024, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(done); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_free(&exec_ctx, &usr1, 1024); + grpc_exec_ctx_finish(&exec_ctx); + } + { + bool done = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr2, 1024, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(done); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_free(&exec_ctx, &usr2, 1024); + grpc_exec_ctx_finish(&exec_ctx); + } + grpc_resource_quota_unref(q); + destroy_user(&usr1); + destroy_user(&usr2); +} + +static void test_scavenge_blocked(void) { + gpr_log(GPR_INFO, "** test_scavenge_blocked **"); + grpc_resource_quota *q = grpc_resource_quota_create("test_scavenge_blocked"); + grpc_resource_quota_resize(q, 1024); + grpc_resource_user usr1; + grpc_resource_user usr2; + grpc_resource_user_init(&usr1, q, "usr1"); + grpc_resource_user_init(&usr2, q, "usr2"); + bool done; + { + done = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr1, 1024, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(done); + } + { + done = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr2, 1024, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(!done); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_free(&exec_ctx, &usr1, 1024); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(done); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_free(&exec_ctx, &usr2, 1024); + grpc_exec_ctx_finish(&exec_ctx); + } + grpc_resource_quota_unref(q); + destroy_user(&usr1); + destroy_user(&usr2); +} + +static void test_blocked_until_scheduled_reclaim(void) { + gpr_log(GPR_INFO, "** test_blocked_until_scheduled_reclaim **"); + grpc_resource_quota *q = + grpc_resource_quota_create("test_blocked_until_scheduled_reclaim"); + grpc_resource_quota_resize(q, 1024); + grpc_resource_user usr; + grpc_resource_user_init(&usr, q, "usr"); + { + bool done = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr, 1024, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(done); + } + bool reclaim_done = false; + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_post_reclaimer( + &exec_ctx, &usr, false, + make_reclaimer(&usr, 1024, set_bool(&reclaim_done))); + grpc_exec_ctx_finish(&exec_ctx); + } + { + bool done = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr, 1024, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(reclaim_done); + GPR_ASSERT(done); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_free(&exec_ctx, &usr, 1024); + grpc_exec_ctx_finish(&exec_ctx); + } + grpc_resource_quota_unref(q); + destroy_user(&usr); +} + +static void test_blocked_until_scheduled_reclaim_and_scavenge(void) { + gpr_log(GPR_INFO, "** test_blocked_until_scheduled_reclaim_and_scavenge **"); + grpc_resource_quota *q = grpc_resource_quota_create( + "test_blocked_until_scheduled_reclaim_and_scavenge"); + grpc_resource_quota_resize(q, 1024); + grpc_resource_user usr1; + grpc_resource_user usr2; + grpc_resource_user_init(&usr1, q, "usr1"); + grpc_resource_user_init(&usr2, q, "usr2"); + { + bool done = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr1, 1024, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(done); + } + bool reclaim_done = false; + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_post_reclaimer( + &exec_ctx, &usr1, false, + make_reclaimer(&usr1, 1024, set_bool(&reclaim_done))); + grpc_exec_ctx_finish(&exec_ctx); + } + { + bool done = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr2, 1024, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(reclaim_done); + GPR_ASSERT(done); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_free(&exec_ctx, &usr2, 1024); + grpc_exec_ctx_finish(&exec_ctx); + } + grpc_resource_quota_unref(q); + destroy_user(&usr1); + destroy_user(&usr2); +} + +static void test_blocked_until_scheduled_destructive_reclaim(void) { + gpr_log(GPR_INFO, "** test_blocked_until_scheduled_destructive_reclaim **"); + grpc_resource_quota *q = grpc_resource_quota_create( + "test_blocked_until_scheduled_destructive_reclaim"); + grpc_resource_quota_resize(q, 1024); + grpc_resource_user usr; + grpc_resource_user_init(&usr, q, "usr"); + { + bool done = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr, 1024, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(done); + } + bool reclaim_done = false; + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_post_reclaimer( + &exec_ctx, &usr, true, + make_reclaimer(&usr, 1024, set_bool(&reclaim_done))); + grpc_exec_ctx_finish(&exec_ctx); + } + { + bool done = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr, 1024, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(reclaim_done); + GPR_ASSERT(done); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_free(&exec_ctx, &usr, 1024); + grpc_exec_ctx_finish(&exec_ctx); + } + grpc_resource_quota_unref(q); + destroy_user(&usr); +} + +static void test_unused_reclaim_is_cancelled(void) { + gpr_log(GPR_INFO, "** test_unused_reclaim_is_cancelled **"); + grpc_resource_quota *q = + grpc_resource_quota_create("test_unused_reclaim_is_cancelled"); + grpc_resource_quota_resize(q, 1024); + grpc_resource_user usr; + grpc_resource_user_init(&usr, q, "usr"); + bool benign_done = false; + bool destructive_done = false; + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_post_reclaimer( + &exec_ctx, &usr, false, make_unused_reclaimer(set_bool(&benign_done))); + grpc_resource_user_post_reclaimer( + &exec_ctx, &usr, true, + make_unused_reclaimer(set_bool(&destructive_done))); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(!benign_done); + GPR_ASSERT(!destructive_done); + } + grpc_resource_quota_unref(q); + destroy_user(&usr); + GPR_ASSERT(benign_done); + GPR_ASSERT(destructive_done); +} + +static void test_benign_reclaim_is_preferred(void) { + gpr_log(GPR_INFO, "** test_benign_reclaim_is_preferred **"); + grpc_resource_quota *q = + grpc_resource_quota_create("test_benign_reclaim_is_preferred"); + grpc_resource_quota_resize(q, 1024); + grpc_resource_user usr; + grpc_resource_user_init(&usr, q, "usr"); + bool benign_done = false; + bool destructive_done = false; + { + bool done = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr, 1024, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(done); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_post_reclaimer( + &exec_ctx, &usr, false, + make_reclaimer(&usr, 1024, set_bool(&benign_done))); + grpc_resource_user_post_reclaimer( + &exec_ctx, &usr, true, + make_unused_reclaimer(set_bool(&destructive_done))); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(!benign_done); + GPR_ASSERT(!destructive_done); + } + { + bool done = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr, 1024, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(benign_done); + GPR_ASSERT(!destructive_done); + GPR_ASSERT(done); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_free(&exec_ctx, &usr, 1024); + grpc_exec_ctx_finish(&exec_ctx); + } + grpc_resource_quota_unref(q); + destroy_user(&usr); + GPR_ASSERT(benign_done); + GPR_ASSERT(destructive_done); +} + +static void test_multiple_reclaims_can_be_triggered(void) { + gpr_log(GPR_INFO, "** test_multiple_reclaims_can_be_triggered **"); + grpc_resource_quota *q = + grpc_resource_quota_create("test_multiple_reclaims_can_be_triggered"); + grpc_resource_quota_resize(q, 1024); + grpc_resource_user usr; + grpc_resource_user_init(&usr, q, "usr"); + bool benign_done = false; + bool destructive_done = false; + { + bool done = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr, 1024, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(done); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_post_reclaimer( + &exec_ctx, &usr, false, + make_reclaimer(&usr, 512, set_bool(&benign_done))); + grpc_resource_user_post_reclaimer( + &exec_ctx, &usr, true, + make_reclaimer(&usr, 512, set_bool(&destructive_done))); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(!benign_done); + GPR_ASSERT(!destructive_done); + } + { + bool done = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr, 1024, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(benign_done); + GPR_ASSERT(destructive_done); + GPR_ASSERT(done); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_free(&exec_ctx, &usr, 1024); + grpc_exec_ctx_finish(&exec_ctx); + } + grpc_resource_quota_unref(q); + destroy_user(&usr); + GPR_ASSERT(benign_done); + GPR_ASSERT(destructive_done); +} + +static void test_resource_user_stays_allocated_until_memory_released(void) { + gpr_log(GPR_INFO, + "** test_resource_user_stays_allocated_until_memory_released **"); + grpc_resource_quota *q = grpc_resource_quota_create( + "test_resource_user_stays_allocated_until_memory_released"); + grpc_resource_quota_resize(q, 1024 * 1024); + grpc_resource_user usr; + grpc_resource_user_init(&usr, q, "usr"); + bool done = false; + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr, 1024, NULL); + grpc_exec_ctx_finish(&exec_ctx); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_quota_unref(q); + grpc_resource_user_shutdown(&exec_ctx, &usr, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(!done); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_free(&exec_ctx, &usr, 1024); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(done); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_destroy(&exec_ctx, &usr); + grpc_exec_ctx_finish(&exec_ctx); + } +} + +static void +test_resource_user_stays_allocated_and_reclaimers_unrun_until_memory_released( + void) { + gpr_log(GPR_INFO, + "** " + "test_resource_user_stays_allocated_and_reclaimers_unrun_until_" + "memory_released **"); + grpc_resource_quota *q = grpc_resource_quota_create( + "test_resource_user_stays_allocated_and_reclaimers_unrun_until_memory_" + "released"); + grpc_resource_quota_resize(q, 1024); + for (int i = 0; i < 10; i++) { + grpc_resource_user usr; + grpc_resource_user_init(&usr, q, "usr"); + bool done = false; + bool reclaimer_cancelled = false; + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_post_reclaimer( + &exec_ctx, &usr, false, + make_unused_reclaimer(set_bool(&reclaimer_cancelled))); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(!reclaimer_cancelled); + } + { + bool allocated = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr, 1024, set_bool(&allocated)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(allocated); + GPR_ASSERT(!reclaimer_cancelled); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_shutdown(&exec_ctx, &usr, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(!done); + GPR_ASSERT(!reclaimer_cancelled); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_free(&exec_ctx, &usr, 1024); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(done); + GPR_ASSERT(reclaimer_cancelled); + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_destroy(&exec_ctx, &usr); + grpc_exec_ctx_finish(&exec_ctx); + } + } + grpc_resource_quota_unref(q); +} + +static void test_reclaimers_can_be_posted_repeatedly(void) { + gpr_log(GPR_INFO, "** test_reclaimers_can_be_posted_repeatedly **"); + grpc_resource_quota *q = + grpc_resource_quota_create("test_reclaimers_can_be_posted_repeatedly"); + grpc_resource_quota_resize(q, 1024); + grpc_resource_user usr; + grpc_resource_user_init(&usr, q, "usr"); + { + bool allocated = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr, 1024, set_bool(&allocated)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(allocated); + } + for (int i = 0; i < 10; i++) { + bool reclaimer_done = false; + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_post_reclaimer( + &exec_ctx, &usr, false, + make_reclaimer(&usr, 1024, set_bool(&reclaimer_done))); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(!reclaimer_done); + } + { + bool allocated = false; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc(&exec_ctx, &usr, 1024, set_bool(&allocated)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(allocated); + GPR_ASSERT(reclaimer_done); + } + } + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_free(&exec_ctx, &usr, 1024); + grpc_exec_ctx_finish(&exec_ctx); + } + destroy_user(&usr); + grpc_resource_quota_unref(q); +} + +static void test_one_slice(void) { + gpr_log(GPR_INFO, "** test_one_slice **"); + + grpc_resource_quota *q = grpc_resource_quota_create("test_one_slice"); + grpc_resource_quota_resize(q, 1024); + + grpc_resource_user usr; + grpc_resource_user_init(&usr, q, "usr"); + + grpc_resource_user_slice_allocator alloc; + int num_allocs = 0; + grpc_resource_user_slice_allocator_init(&alloc, &usr, inc_int_cb, + &num_allocs); + + gpr_slice_buffer buffer; + gpr_slice_buffer_init(&buffer); + + { + const int start_allocs = num_allocs; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc_slices(&exec_ctx, &alloc, 1024, 1, &buffer); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(num_allocs == start_allocs + 1); + } + + gpr_slice_buffer_destroy(&buffer); + destroy_user(&usr); + grpc_resource_quota_unref(q); +} + +static void test_one_slice_deleted_late(void) { + gpr_log(GPR_INFO, "** test_one_slice_deleted_late **"); + + grpc_resource_quota *q = + grpc_resource_quota_create("test_one_slice_deleted_late"); + grpc_resource_quota_resize(q, 1024); + + grpc_resource_user usr; + grpc_resource_user_init(&usr, q, "usr"); + + grpc_resource_user_slice_allocator alloc; + int num_allocs = 0; + grpc_resource_user_slice_allocator_init(&alloc, &usr, inc_int_cb, + &num_allocs); + + gpr_slice_buffer buffer; + gpr_slice_buffer_init(&buffer); + + { + const int start_allocs = num_allocs; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_alloc_slices(&exec_ctx, &alloc, 1024, 1, &buffer); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(num_allocs == start_allocs + 1); + } + + bool done = false; + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_shutdown(&exec_ctx, &usr, set_bool(&done)); + grpc_exec_ctx_finish(&exec_ctx); + GPR_ASSERT(!done); + } + + grpc_resource_quota_unref(q); + gpr_slice_buffer_destroy(&buffer); + GPR_ASSERT(done); + { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resource_user_destroy(&exec_ctx, &usr); + grpc_exec_ctx_finish(&exec_ctx); + } +} + +int main(int argc, char **argv) { + grpc_test_init(argc, argv); + grpc_init(); + test_no_op(); + test_resize_then_destroy(); + test_resource_user_no_op(); + test_instant_alloc_then_free(); + test_instant_alloc_free_pair(); + test_simple_async_alloc(); + test_async_alloc_blocked_by_size(); + test_scavenge(); + test_scavenge_blocked(); + test_blocked_until_scheduled_reclaim(); + test_blocked_until_scheduled_reclaim_and_scavenge(); + test_blocked_until_scheduled_destructive_reclaim(); + test_unused_reclaim_is_cancelled(); + test_benign_reclaim_is_preferred(); + test_multiple_reclaims_can_be_triggered(); + test_resource_user_stays_allocated_until_memory_released(); + test_resource_user_stays_allocated_and_reclaimers_unrun_until_memory_released(); + test_reclaimers_can_be_posted_repeatedly(); + test_one_slice(); + test_one_slice_deleted_late(); + grpc_shutdown(); + return 0; +} diff --git a/test/core/iomgr/tcp_client_posix_test.c b/test/core/iomgr/tcp_client_posix_test.c index 6c6962ed7a2..5fab826fb77 100644 --- a/test/core/iomgr/tcp_client_posix_test.c +++ b/test/core/iomgr/tcp_client_posix_test.c @@ -114,7 +114,7 @@ void test_succeeds(void) { GPR_ASSERT(getsockname(svr_fd, (struct sockaddr *)addr, (socklen_t *)&resolved_addr.len) == 0); grpc_closure_init(&done, must_succeed, NULL); - grpc_tcp_client_connect(&exec_ctx, &done, &g_connecting, g_pollset_set, + grpc_tcp_client_connect(&exec_ctx, &done, &g_connecting, g_pollset_set, NULL, &resolved_addr, gpr_inf_future(GPR_CLOCK_REALTIME)); /* await the connection */ @@ -164,7 +164,7 @@ void test_fails(void) { /* connect to a broken address */ grpc_closure_init(&done, must_fail, NULL); - grpc_tcp_client_connect(&exec_ctx, &done, &g_connecting, g_pollset_set, + grpc_tcp_client_connect(&exec_ctx, &done, &g_connecting, g_pollset_set, NULL, &resolved_addr, gpr_inf_future(GPR_CLOCK_REALTIME)); gpr_mu_lock(g_mu); diff --git a/test/core/iomgr/tcp_posix_test.c b/test/core/iomgr/tcp_posix_test.c index d998958744c..29f12a5afb2 100644 --- a/test/core/iomgr/tcp_posix_test.c +++ b/test/core/iomgr/tcp_posix_test.c @@ -181,7 +181,10 @@ static void read_test(size_t num_bytes, size_t slice_size) { create_sockets(sv); - ep = grpc_tcp_create(grpc_fd_create(sv[1], "read_test"), slice_size, "test"); + grpc_resource_quota *resource_quota = grpc_resource_quota_create("read_test"); + ep = grpc_tcp_create(grpc_fd_create(sv[1], "read_test"), resource_quota, + slice_size, "test"); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); grpc_endpoint_add_to_pollset(&exec_ctx, ep, g_pollset); written_bytes = fill_socket_partial(sv[0], num_bytes); @@ -228,8 +231,11 @@ static void large_read_test(size_t slice_size) { create_sockets(sv); - ep = grpc_tcp_create(grpc_fd_create(sv[1], "large_read_test"), slice_size, - "test"); + grpc_resource_quota *resource_quota = + grpc_resource_quota_create("large_read_test"); + ep = grpc_tcp_create(grpc_fd_create(sv[1], "large_read_test"), resource_quota, + slice_size, "test"); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); grpc_endpoint_add_to_pollset(&exec_ctx, ep, g_pollset); written_bytes = fill_socket(sv[0]); @@ -364,8 +370,11 @@ static void write_test(size_t num_bytes, size_t slice_size) { create_sockets(sv); - ep = grpc_tcp_create(grpc_fd_create(sv[1], "write_test"), + grpc_resource_quota *resource_quota = + grpc_resource_quota_create("write_test"); + ep = grpc_tcp_create(grpc_fd_create(sv[1], "write_test"), resource_quota, GRPC_TCP_DEFAULT_READ_SLICE_SIZE, "test"); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); grpc_endpoint_add_to_pollset(&exec_ctx, ep, g_pollset); state.ep = ep; @@ -428,8 +437,12 @@ static void release_fd_test(size_t num_bytes, size_t slice_size) { create_sockets(sv); - ep = grpc_tcp_create(grpc_fd_create(sv[1], "read_test"), slice_size, "test"); + grpc_resource_quota *resource_quota = + grpc_resource_quota_create("release_fd_test"); + ep = grpc_tcp_create(grpc_fd_create(sv[1], "read_test"), resource_quota, + slice_size, "test"); GPR_ASSERT(grpc_tcp_fd(ep) == sv[1] && sv[1] >= 0); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); grpc_endpoint_add_to_pollset(&exec_ctx, ep, g_pollset); written_bytes = fill_socket_partial(sv[0], num_bytes); @@ -450,8 +463,10 @@ static void release_fd_test(size_t num_bytes, size_t slice_size) { "pollset_work", grpc_pollset_work(&exec_ctx, g_pollset, &worker, gpr_now(GPR_CLOCK_MONOTONIC), deadline))); + gpr_log(GPR_DEBUG, "wakeup: read=%" PRIdPTR " target=%" PRIdPTR, + state.read_bytes, state.target_read_bytes); gpr_mu_unlock(g_mu); - grpc_exec_ctx_finish(&exec_ctx); + grpc_exec_ctx_flush(&exec_ctx); gpr_mu_lock(g_mu); } GPR_ASSERT(state.read_bytes == state.target_read_bytes); @@ -459,6 +474,7 @@ static void release_fd_test(size_t num_bytes, size_t slice_size) { gpr_slice_buffer_destroy(&state.incoming); grpc_tcp_destroy_and_release_fd(&exec_ctx, ep, &fd, &fd_released_cb); + grpc_exec_ctx_flush(&exec_ctx); gpr_mu_lock(g_mu); while (!fd_released_done) { grpc_pollset_worker *worker = NULL; @@ -466,6 +482,7 @@ static void release_fd_test(size_t num_bytes, size_t slice_size) { "pollset_work", grpc_pollset_work(&exec_ctx, g_pollset, &worker, gpr_now(GPR_CLOCK_MONOTONIC), deadline))); + gpr_log(GPR_DEBUG, "wakeup: fd_released_done=%d", fd_released_done); } gpr_mu_unlock(g_mu); GPR_ASSERT(fd_released_done == 1); @@ -511,10 +528,13 @@ static grpc_endpoint_test_fixture create_fixture_tcp_socketpair( grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; create_sockets(sv); + grpc_resource_quota *resource_quota = + grpc_resource_quota_create("tcp_posix_test_socketpair"); f.client_ep = grpc_tcp_create(grpc_fd_create(sv[0], "fixture:client"), - slice_size, "test"); + resource_quota, slice_size, "test"); f.server_ep = grpc_tcp_create(grpc_fd_create(sv[1], "fixture:server"), - slice_size, "test"); + resource_quota, slice_size, "test"); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); grpc_endpoint_add_to_pollset(&exec_ctx, f.client_ep, g_pollset); grpc_endpoint_add_to_pollset(&exec_ctx, f.server_ep, g_pollset); diff --git a/test/core/iomgr/tcp_server_posix_test.c b/test/core/iomgr/tcp_server_posix_test.c index f839911a843..1b8a39c1beb 100644 --- a/test/core/iomgr/tcp_server_posix_test.c +++ b/test/core/iomgr/tcp_server_posix_test.c @@ -138,7 +138,8 @@ static void on_connect(grpc_exec_ctx *exec_ctx, void *arg, grpc_endpoint *tcp, static void test_no_op(void) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_tcp_server *s; - GPR_ASSERT(GRPC_ERROR_NONE == grpc_tcp_server_create(NULL, NULL, &s)); + GPR_ASSERT(GRPC_ERROR_NONE == + grpc_tcp_server_create(&exec_ctx, NULL, NULL, &s)); grpc_tcp_server_unref(&exec_ctx, s); grpc_exec_ctx_finish(&exec_ctx); } @@ -146,7 +147,8 @@ static void test_no_op(void) { static void test_no_op_with_start(void) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; grpc_tcp_server *s; - GPR_ASSERT(GRPC_ERROR_NONE == grpc_tcp_server_create(NULL, NULL, &s)); + GPR_ASSERT(GRPC_ERROR_NONE == + grpc_tcp_server_create(&exec_ctx, NULL, NULL, &s)); LOG_TEST("test_no_op_with_start"); grpc_tcp_server_start(&exec_ctx, s, NULL, 0, on_connect, NULL); grpc_tcp_server_unref(&exec_ctx, s); @@ -158,7 +160,8 @@ static void test_no_op_with_port(void) { grpc_resolved_address resolved_addr; struct sockaddr_in *addr = (struct sockaddr_in *)resolved_addr.addr; grpc_tcp_server *s; - GPR_ASSERT(GRPC_ERROR_NONE == grpc_tcp_server_create(NULL, NULL, &s)); + GPR_ASSERT(GRPC_ERROR_NONE == + grpc_tcp_server_create(&exec_ctx, NULL, NULL, &s)); LOG_TEST("test_no_op_with_port"); memset(&resolved_addr, 0, sizeof(resolved_addr)); @@ -178,7 +181,8 @@ static void test_no_op_with_port_and_start(void) { grpc_resolved_address resolved_addr; struct sockaddr_in *addr = (struct sockaddr_in *)resolved_addr.addr; grpc_tcp_server *s; - GPR_ASSERT(GRPC_ERROR_NONE == grpc_tcp_server_create(NULL, NULL, &s)); + GPR_ASSERT(GRPC_ERROR_NONE == + grpc_tcp_server_create(&exec_ctx, NULL, NULL, &s)); LOG_TEST("test_no_op_with_port_and_start"); int port; @@ -241,7 +245,8 @@ static void test_connect(unsigned n) { unsigned svr1_fd_count; int svr1_port; grpc_tcp_server *s; - GPR_ASSERT(GRPC_ERROR_NONE == grpc_tcp_server_create(NULL, NULL, &s)); + GPR_ASSERT(GRPC_ERROR_NONE == + grpc_tcp_server_create(&exec_ctx, NULL, NULL, &s)); unsigned i; server_weak_ref weak_ref; server_weak_ref_init(&weak_ref); diff --git a/test/core/security/secure_endpoint_test.c b/test/core/security/secure_endpoint_test.c index 1d2bf73bb1d..2262fde98d2 100644 --- a/test/core/security/secure_endpoint_test.c +++ b/test/core/security/secure_endpoint_test.c @@ -56,7 +56,10 @@ static grpc_endpoint_test_fixture secure_endpoint_create_fixture_tcp_socketpair( grpc_endpoint_test_fixture f; grpc_endpoint_pair tcp; - tcp = grpc_iomgr_create_endpoint_pair("fixture", slice_size); + grpc_resource_quota *resource_quota = + grpc_resource_quota_create("secure_endpoint_test"); + tcp = grpc_iomgr_create_endpoint_pair("fixture", resource_quota, slice_size); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); grpc_endpoint_add_to_pollset(&exec_ctx, tcp.client, g_pollset); grpc_endpoint_add_to_pollset(&exec_ctx, tcp.server, g_pollset); diff --git a/test/core/surface/concurrent_connectivity_test.c b/test/core/surface/concurrent_connectivity_test.c index f9f723baaa1..f9f46754546 100644 --- a/test/core/surface/concurrent_connectivity_test.c +++ b/test/core/surface/concurrent_connectivity_test.c @@ -120,7 +120,7 @@ void bad_server_thread(void *vargs) { struct sockaddr_storage *addr = (struct sockaddr_storage *)resolved_addr.addr; int port; grpc_tcp_server *s; - grpc_error *error = grpc_tcp_server_create(NULL, NULL, &s); + grpc_error *error = grpc_tcp_server_create(&exec_ctx, NULL, NULL, &s); GPR_ASSERT(error == GRPC_ERROR_NONE); memset(&resolved_addr, 0, sizeof(resolved_addr)); addr->ss_family = AF_INET; diff --git a/test/core/util/mock_endpoint.c b/test/core/util/mock_endpoint.c index 13e0e918fbe..2b041a44841 100644 --- a/test/core/util/mock_endpoint.c +++ b/test/core/util/mock_endpoint.c @@ -33,16 +33,20 @@ #include "test/core/util/mock_endpoint.h" +#include + #include #include typedef struct grpc_mock_endpoint { grpc_endpoint base; gpr_mu mu; + int refs; void (*on_write)(gpr_slice slice); gpr_slice_buffer read_buffer; gpr_slice_buffer *on_read_out; grpc_closure *on_read; + grpc_resource_user resource_user; } grpc_mock_endpoint; static void me_read(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, @@ -74,6 +78,24 @@ static void me_add_to_pollset(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, static void me_add_to_pollset_set(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep, grpc_pollset_set *pollset) {} +static void unref(grpc_exec_ctx *exec_ctx, grpc_mock_endpoint *m) { + gpr_mu_lock(&m->mu); + if (0 == --m->refs) { + gpr_mu_unlock(&m->mu); + gpr_slice_buffer_destroy(&m->read_buffer); + grpc_resource_user_destroy(exec_ctx, &m->resource_user); + gpr_free(m); + } else { + gpr_mu_unlock(&m->mu); + } +} + +static void me_finish_shutdown(grpc_exec_ctx *exec_ctx, void *me, + grpc_error *error) { + grpc_mock_endpoint *m = me; + unref(exec_ctx, m); +} + static void me_shutdown(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) { grpc_mock_endpoint *m = (grpc_mock_endpoint *)ep; gpr_mu_lock(&m->mu); @@ -82,19 +104,25 @@ static void me_shutdown(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) { GRPC_ERROR_CREATE("Endpoint Shutdown"), NULL); m->on_read = NULL; } + grpc_resource_user_shutdown(exec_ctx, &m->resource_user, + grpc_closure_create(me_finish_shutdown, m)); gpr_mu_unlock(&m->mu); } static void me_destroy(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) { grpc_mock_endpoint *m = (grpc_mock_endpoint *)ep; - gpr_slice_buffer_destroy(&m->read_buffer); - gpr_free(m); + unref(exec_ctx, m); } static char *me_get_peer(grpc_endpoint *ep) { return gpr_strdup("fake:mock_endpoint"); } +static grpc_resource_user *me_get_resource_user(grpc_endpoint *ep) { + grpc_mock_endpoint *m = (grpc_mock_endpoint *)ep; + return &m->resource_user; +} + static grpc_workqueue *me_get_workqueue(grpc_endpoint *ep) { return NULL; } static const grpc_endpoint_vtable vtable = { @@ -105,12 +133,19 @@ static const grpc_endpoint_vtable vtable = { me_add_to_pollset_set, me_shutdown, me_destroy, + me_get_resource_user, me_get_peer, }; -grpc_endpoint *grpc_mock_endpoint_create(void (*on_write)(gpr_slice slice)) { +grpc_endpoint *grpc_mock_endpoint_create(void (*on_write)(gpr_slice slice), + grpc_resource_quota *resource_quota) { grpc_mock_endpoint *m = gpr_malloc(sizeof(*m)); m->base.vtable = &vtable; + m->refs = 2; + char *name; + gpr_asprintf(&name, "mock_endpoint_%" PRIxPTR, (intptr_t)m); + grpc_resource_user_init(&m->resource_user, resource_quota, name); + gpr_free(name); gpr_slice_buffer_init(&m->read_buffer); gpr_mu_init(&m->mu); m->on_write = on_write; diff --git a/test/core/util/mock_endpoint.h b/test/core/util/mock_endpoint.h index 051af9866b6..b3a464ca01c 100644 --- a/test/core/util/mock_endpoint.h +++ b/test/core/util/mock_endpoint.h @@ -36,7 +36,8 @@ #include "src/core/lib/iomgr/endpoint.h" -grpc_endpoint *grpc_mock_endpoint_create(void (*on_write)(gpr_slice slice)); +grpc_endpoint *grpc_mock_endpoint_create(void (*on_write)(gpr_slice slice), + grpc_resource_quota *resource_quota); void grpc_mock_endpoint_put_read(grpc_exec_ctx *exec_ctx, grpc_endpoint *mock_endpoint, gpr_slice slice); diff --git a/test/core/util/passthru_endpoint.c b/test/core/util/passthru_endpoint.c index 7ed9e97bd6a..ee6ef7da601 100644 --- a/test/core/util/passthru_endpoint.c +++ b/test/core/util/passthru_endpoint.c @@ -33,6 +33,8 @@ #include "test/core/util/passthru_endpoint.h" +#include + #include #include @@ -44,6 +46,7 @@ typedef struct { gpr_slice_buffer read_buffer; gpr_slice_buffer *on_read_out; grpc_closure *on_read; + grpc_resource_user resource_user; } half; struct passthru_endpoint { @@ -122,7 +125,8 @@ static void me_shutdown(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) { gpr_mu_unlock(&m->parent->mu); } -static void me_destroy(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) { +static void me_really_destroy(grpc_exec_ctx *exec_ctx, void *ep, + grpc_error *error) { passthru_endpoint *p = ((half *)ep)->parent; gpr_mu_lock(&p->mu); if (0 == --p->halves) { @@ -136,12 +140,23 @@ static void me_destroy(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) { } } +static void me_destroy(grpc_exec_ctx *exec_ctx, grpc_endpoint *ep) { + half *m = (half *)ep; + grpc_resource_user_shutdown(exec_ctx, &m->resource_user, + grpc_closure_create(me_really_destroy, m)); +} + static char *me_get_peer(grpc_endpoint *ep) { return gpr_strdup("fake:mock_endpoint"); } static grpc_workqueue *me_get_workqueue(grpc_endpoint *ep) { return NULL; } +static grpc_resource_user *me_get_resource_user(grpc_endpoint *ep) { + half *m = (half *)ep; + return &m->resource_user; +} + static const grpc_endpoint_vtable vtable = { me_read, me_write, @@ -150,23 +165,32 @@ static const grpc_endpoint_vtable vtable = { me_add_to_pollset_set, me_shutdown, me_destroy, + me_get_resource_user, me_get_peer, }; -static void half_init(half *m, passthru_endpoint *parent) { +static void half_init(half *m, passthru_endpoint *parent, + grpc_resource_quota *resource_quota, + const char *half_name) { m->base.vtable = &vtable; m->parent = parent; gpr_slice_buffer_init(&m->read_buffer); m->on_read = NULL; + char *name; + gpr_asprintf(&name, "passthru_endpoint_%s_%" PRIxPTR, half_name, + (intptr_t)parent); + grpc_resource_user_init(&m->resource_user, resource_quota, name); + gpr_free(name); } void grpc_passthru_endpoint_create(grpc_endpoint **client, - grpc_endpoint **server) { + grpc_endpoint **server, + grpc_resource_quota *resource_quota) { passthru_endpoint *m = gpr_malloc(sizeof(*m)); m->halves = 2; m->shutdown = 0; - half_init(&m->client, m); - half_init(&m->server, m); + half_init(&m->client, m, resource_quota, "client"); + half_init(&m->server, m, resource_quota, "server"); gpr_mu_init(&m->mu); *client = &m->client.base; *server = &m->server.base; diff --git a/test/core/util/passthru_endpoint.h b/test/core/util/passthru_endpoint.h index aa1d3a17637..b81ac5571c2 100644 --- a/test/core/util/passthru_endpoint.h +++ b/test/core/util/passthru_endpoint.h @@ -37,6 +37,7 @@ #include "src/core/lib/iomgr/endpoint.h" void grpc_passthru_endpoint_create(grpc_endpoint **client, - grpc_endpoint **server); + grpc_endpoint **server, + grpc_resource_quota *resource_quota); #endif diff --git a/test/core/util/port_server_client.c b/test/core/util/port_server_client.c index a5c8c496502..b2342feeb40 100644 --- a/test/core/util/port_server_client.c +++ b/test/core/util/port_server_client.c @@ -99,9 +99,12 @@ void grpc_free_port_using_server(char *server, int port) { req.http.path = path; grpc_httpcli_context_init(&context); - grpc_httpcli_get(&exec_ctx, &context, &pr.pops, &req, + grpc_resource_quota *resource_quota = + grpc_resource_quota_create("port_server_client/free"); + grpc_httpcli_get(&exec_ctx, &context, &pr.pops, resource_quota, &req, GRPC_TIMEOUT_SECONDS_TO_DEADLINE(10), grpc_closure_create(freed_port_from_server, &pr), &rsp); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); gpr_mu_lock(pr.mu); while (!pr.done) { grpc_pollset_worker *worker = NULL; @@ -167,10 +170,13 @@ static void got_port_from_server(grpc_exec_ctx *exec_ctx, void *arg, req.http.path = "/get"; grpc_http_response_destroy(&pr->response); memset(&pr->response, 0, sizeof(pr->response)); - grpc_httpcli_get(exec_ctx, pr->ctx, &pr->pops, &req, + grpc_resource_quota *resource_quota = + grpc_resource_quota_create("port_server_client/pick_retry"); + grpc_httpcli_get(exec_ctx, pr->ctx, &pr->pops, resource_quota, &req, GRPC_TIMEOUT_SECONDS_TO_DEADLINE(10), grpc_closure_create(got_port_from_server, pr), &pr->response); + grpc_resource_quota_internal_unref(exec_ctx, resource_quota); return; } GPR_ASSERT(response); @@ -211,9 +217,13 @@ int grpc_pick_port_using_server(char *server) { req.http.path = "/get"; grpc_httpcli_context_init(&context); - grpc_httpcli_get( - &exec_ctx, &context, &pr.pops, &req, GRPC_TIMEOUT_SECONDS_TO_DEADLINE(10), - grpc_closure_create(got_port_from_server, &pr), &pr.response); + grpc_resource_quota *resource_quota = + grpc_resource_quota_create("port_server_client/pick"); + grpc_httpcli_get(&exec_ctx, &context, &pr.pops, resource_quota, &req, + GRPC_TIMEOUT_SECONDS_TO_DEADLINE(10), + grpc_closure_create(got_port_from_server, &pr), + &pr.response); + grpc_resource_quota_internal_unref(&exec_ctx, resource_quota); grpc_exec_ctx_finish(&exec_ctx); gpr_mu_lock(pr.mu); while (pr.port == -1) { diff --git a/test/core/util/test_tcp_server.c b/test/core/util/test_tcp_server.c index 9ac97413d45..16df91d9688 100644 --- a/test/core/util/test_tcp_server.c +++ b/test/core/util/test_tcp_server.c @@ -75,8 +75,8 @@ void test_tcp_server_start(test_tcp_server *server, int port) { addr->sin_port = htons((uint16_t)port); memset(&addr->sin_addr, 0, sizeof(addr->sin_addr)); - grpc_error *error = grpc_tcp_server_create(&server->shutdown_complete, NULL, - &server->tcp_server); + grpc_error *error = grpc_tcp_server_create( + &exec_ctx, &server->shutdown_complete, NULL, &server->tcp_server); GPR_ASSERT(error == GRPC_ERROR_NONE); error = grpc_tcp_server_add_port(server->tcp_server, &resolved_addr, &port_added); diff --git a/test/cpp/codegen/compiler_test_golden b/test/cpp/codegen/compiler_test_golden index 5f0e8246551..0b82f2a59f3 100644 --- a/test/cpp/codegen/compiler_test_golden +++ b/test/cpp/codegen/compiler_test_golden @@ -67,7 +67,7 @@ namespace testing { // ServiceA detached comment 2 // // ServiceA leading comment 1 -class ServiceA GRPC_FINAL { +class ServiceA final { public: class StubInterface { public: @@ -94,10 +94,10 @@ class ServiceA GRPC_FINAL { virtual ::grpc::ClientWriterInterface< ::grpc::testing::Request>* MethodA2Raw(::grpc::ClientContext* context, ::grpc::testing::Response* response) = 0; virtual ::grpc::ClientAsyncWriterInterface< ::grpc::testing::Request>* AsyncMethodA2Raw(::grpc::ClientContext* context, ::grpc::testing::Response* response, ::grpc::CompletionQueue* cq, void* tag) = 0; }; - class Stub GRPC_FINAL : public StubInterface { + class Stub final : public StubInterface { public: Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); - ::grpc::Status MethodA1(::grpc::ClientContext* context, const ::grpc::testing::Request& request, ::grpc::testing::Response* response) GRPC_OVERRIDE; + ::grpc::Status MethodA1(::grpc::ClientContext* context, const ::grpc::testing::Request& request, ::grpc::testing::Response* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::grpc::testing::Response>> AsyncMethodA1(::grpc::ClientContext* context, const ::grpc::testing::Request& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::grpc::testing::Response>>(AsyncMethodA1Raw(context, request, cq)); } @@ -110,9 +110,9 @@ class ServiceA GRPC_FINAL { private: std::shared_ptr< ::grpc::ChannelInterface> channel_; - ::grpc::ClientAsyncResponseReader< ::grpc::testing::Response>* AsyncMethodA1Raw(::grpc::ClientContext* context, const ::grpc::testing::Request& request, ::grpc::CompletionQueue* cq) GRPC_OVERRIDE; - ::grpc::ClientWriter< ::grpc::testing::Request>* MethodA2Raw(::grpc::ClientContext* context, ::grpc::testing::Response* response) GRPC_OVERRIDE; - ::grpc::ClientAsyncWriter< ::grpc::testing::Request>* AsyncMethodA2Raw(::grpc::ClientContext* context, ::grpc::testing::Response* response, ::grpc::CompletionQueue* cq, void* tag) GRPC_OVERRIDE; + ::grpc::ClientAsyncResponseReader< ::grpc::testing::Response>* AsyncMethodA1Raw(::grpc::ClientContext* context, const ::grpc::testing::Request& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientWriter< ::grpc::testing::Request>* MethodA2Raw(::grpc::ClientContext* context, ::grpc::testing::Response* response) override; + ::grpc::ClientAsyncWriter< ::grpc::testing::Request>* AsyncMethodA2Raw(::grpc::ClientContext* context, ::grpc::testing::Response* response, ::grpc::CompletionQueue* cq, void* tag) override; const ::grpc::RpcMethod rpcmethod_MethodA1_; const ::grpc::RpcMethod rpcmethod_MethodA2_; }; @@ -140,11 +140,11 @@ class ServiceA GRPC_FINAL { WithAsyncMethod_MethodA1() { ::grpc::Service::MarkMethodAsync(0); } - ~WithAsyncMethod_MethodA1() GRPC_OVERRIDE { + ~WithAsyncMethod_MethodA1() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method - ::grpc::Status MethodA1(::grpc::ServerContext* context, const ::grpc::testing::Request* request, ::grpc::testing::Response* response) GRPC_FINAL GRPC_OVERRIDE { + ::grpc::Status MethodA1(::grpc::ServerContext* context, const ::grpc::testing::Request* request, ::grpc::testing::Response* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } @@ -160,11 +160,11 @@ class ServiceA GRPC_FINAL { WithAsyncMethod_MethodA2() { ::grpc::Service::MarkMethodAsync(1); } - ~WithAsyncMethod_MethodA2() GRPC_OVERRIDE { + ~WithAsyncMethod_MethodA2() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method - ::grpc::Status MethodA2(::grpc::ServerContext* context, ::grpc::ServerReader< ::grpc::testing::Request>* reader, ::grpc::testing::Response* response) GRPC_FINAL GRPC_OVERRIDE { + ::grpc::Status MethodA2(::grpc::ServerContext* context, ::grpc::ServerReader< ::grpc::testing::Request>* reader, ::grpc::testing::Response* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } @@ -181,11 +181,11 @@ class ServiceA GRPC_FINAL { WithGenericMethod_MethodA1() { ::grpc::Service::MarkMethodGeneric(0); } - ~WithGenericMethod_MethodA1() GRPC_OVERRIDE { + ~WithGenericMethod_MethodA1() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method - ::grpc::Status MethodA1(::grpc::ServerContext* context, const ::grpc::testing::Request* request, ::grpc::testing::Response* response) GRPC_FINAL GRPC_OVERRIDE { + ::grpc::Status MethodA1(::grpc::ServerContext* context, const ::grpc::testing::Request* request, ::grpc::testing::Response* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } @@ -198,11 +198,11 @@ class ServiceA GRPC_FINAL { WithGenericMethod_MethodA2() { ::grpc::Service::MarkMethodGeneric(1); } - ~WithGenericMethod_MethodA2() GRPC_OVERRIDE { + ~WithGenericMethod_MethodA2() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method - ::grpc::Status MethodA2(::grpc::ServerContext* context, ::grpc::ServerReader< ::grpc::testing::Request>* reader, ::grpc::testing::Response* response) GRPC_FINAL GRPC_OVERRIDE { + ::grpc::Status MethodA2(::grpc::ServerContext* context, ::grpc::ServerReader< ::grpc::testing::Request>* reader, ::grpc::testing::Response* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } @@ -216,11 +216,11 @@ class ServiceA GRPC_FINAL { ::grpc::Service::MarkMethodStreamed(0, new ::grpc::StreamedUnaryHandler< ::grpc::testing::Request, ::grpc::testing::Response>(std::bind(&WithStreamedUnaryMethod_MethodA1::StreamedMethodA1, this, std::placeholders::_1, std::placeholders::_2))); } - ~WithStreamedUnaryMethod_MethodA1() GRPC_OVERRIDE { + ~WithStreamedUnaryMethod_MethodA1() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method - ::grpc::Status MethodA1(::grpc::ServerContext* context, const ::grpc::testing::Request* request, ::grpc::testing::Response* response) GRPC_FINAL GRPC_OVERRIDE { + ::grpc::Status MethodA1(::grpc::ServerContext* context, const ::grpc::testing::Request* request, ::grpc::testing::Response* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } @@ -233,7 +233,7 @@ class ServiceA GRPC_FINAL { }; // ServiceB leading comment 1 -class ServiceB GRPC_FINAL { +class ServiceB final { public: class StubInterface { public: @@ -247,17 +247,17 @@ class ServiceB GRPC_FINAL { private: virtual ::grpc::ClientAsyncResponseReaderInterface< ::grpc::testing::Response>* AsyncMethodB1Raw(::grpc::ClientContext* context, const ::grpc::testing::Request& request, ::grpc::CompletionQueue* cq) = 0; }; - class Stub GRPC_FINAL : public StubInterface { + class Stub final : public StubInterface { public: Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); - ::grpc::Status MethodB1(::grpc::ClientContext* context, const ::grpc::testing::Request& request, ::grpc::testing::Response* response) GRPC_OVERRIDE; + ::grpc::Status MethodB1(::grpc::ClientContext* context, const ::grpc::testing::Request& request, ::grpc::testing::Response* response) override; std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::grpc::testing::Response>> AsyncMethodB1(::grpc::ClientContext* context, const ::grpc::testing::Request& request, ::grpc::CompletionQueue* cq) { return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::grpc::testing::Response>>(AsyncMethodB1Raw(context, request, cq)); } private: std::shared_ptr< ::grpc::ChannelInterface> channel_; - ::grpc::ClientAsyncResponseReader< ::grpc::testing::Response>* AsyncMethodB1Raw(::grpc::ClientContext* context, const ::grpc::testing::Request& request, ::grpc::CompletionQueue* cq) GRPC_OVERRIDE; + ::grpc::ClientAsyncResponseReader< ::grpc::testing::Response>* AsyncMethodB1Raw(::grpc::ClientContext* context, const ::grpc::testing::Request& request, ::grpc::CompletionQueue* cq) override; const ::grpc::RpcMethod rpcmethod_MethodB1_; }; static std::unique_ptr NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions()); @@ -278,11 +278,11 @@ class ServiceB GRPC_FINAL { WithAsyncMethod_MethodB1() { ::grpc::Service::MarkMethodAsync(0); } - ~WithAsyncMethod_MethodB1() GRPC_OVERRIDE { + ~WithAsyncMethod_MethodB1() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method - ::grpc::Status MethodB1(::grpc::ServerContext* context, const ::grpc::testing::Request* request, ::grpc::testing::Response* response) GRPC_FINAL GRPC_OVERRIDE { + ::grpc::Status MethodB1(::grpc::ServerContext* context, const ::grpc::testing::Request* request, ::grpc::testing::Response* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } @@ -299,11 +299,11 @@ class ServiceB GRPC_FINAL { WithGenericMethod_MethodB1() { ::grpc::Service::MarkMethodGeneric(0); } - ~WithGenericMethod_MethodB1() GRPC_OVERRIDE { + ~WithGenericMethod_MethodB1() override { BaseClassMustBeDerivedFromService(this); } // disable synchronous version of this method - ::grpc::Status MethodB1(::grpc::ServerContext* context, const ::grpc::testing::Request* request, ::grpc::testing::Response* response) GRPC_FINAL GRPC_OVERRIDE { + ::grpc::Status MethodB1(::grpc::ServerContext* context, const ::grpc::testing::Request* request, ::grpc::testing::Response* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } @@ -317,11 +317,11 @@ class ServiceB GRPC_FINAL { ::grpc::Service::MarkMethodStreamed(0, new ::grpc::StreamedUnaryHandler< ::grpc::testing::Request, ::grpc::testing::Response>(std::bind(&WithStreamedUnaryMethod_MethodB1::StreamedMethodB1, this, std::placeholders::_1, std::placeholders::_2))); } - ~WithStreamedUnaryMethod_MethodB1() GRPC_OVERRIDE { + ~WithStreamedUnaryMethod_MethodB1() override { BaseClassMustBeDerivedFromService(this); } // disable regular version of this method - ::grpc::Status MethodB1(::grpc::ServerContext* context, const ::grpc::testing::Request* request, ::grpc::testing::Response* response) GRPC_FINAL GRPC_OVERRIDE { + ::grpc::Status MethodB1(::grpc::ServerContext* context, const ::grpc::testing::Request* request, ::grpc::testing::Response* response) final override { abort(); return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } diff --git a/test/cpp/common/auth_property_iterator_test.cc b/test/cpp/common/auth_property_iterator_test.cc index 66225ff335c..16bebcab740 100644 --- a/test/cpp/common/auth_property_iterator_test.cc +++ b/test/cpp/common/auth_property_iterator_test.cc @@ -56,7 +56,7 @@ class TestAuthPropertyIterator : public AuthPropertyIterator { class AuthPropertyIteratorTest : public ::testing::Test { protected: - void SetUp() GRPC_OVERRIDE { + void SetUp() override { ctx_ = grpc_auth_context_create(NULL); grpc_auth_context_add_cstring_property(ctx_, "name", "chapi"); grpc_auth_context_add_cstring_property(ctx_, "name", "chapo"); @@ -64,7 +64,7 @@ class AuthPropertyIteratorTest : public ::testing::Test { EXPECT_EQ(1, grpc_auth_context_set_peer_identity_property_name(ctx_, "name")); } - void TearDown() GRPC_OVERRIDE { grpc_auth_context_release(ctx_); } + void TearDown() override { grpc_auth_context_release(ctx_); } grpc_auth_context* ctx_; }; diff --git a/test/cpp/end2end/async_end2end_test.cc b/test/cpp/end2end/async_end2end_test.cc index 823f0bd0358..3845582d5db 100644 --- a/test/cpp/end2end/async_end2end_test.cc +++ b/test/cpp/end2end/async_end2end_test.cc @@ -211,10 +211,10 @@ bool plugin_has_sync_methods(std::unique_ptr& plugin) { // that needs to be tested here. class ServerBuilderSyncPluginDisabler : public ::grpc::ServerBuilderOption { public: - void UpdateArguments(ChannelArguments* arg) GRPC_OVERRIDE {} + void UpdateArguments(ChannelArguments* arg) override {} - void UpdatePlugins(std::vector>* plugins) - GRPC_OVERRIDE { + void UpdatePlugins( + std::vector>* plugins) override { plugins->erase(std::remove_if(plugins->begin(), plugins->end(), plugin_has_sync_methods), plugins->end()); @@ -246,7 +246,7 @@ class AsyncEnd2endTest : public ::testing::TestWithParam { protected: AsyncEnd2endTest() { GetParam().Log(); } - void SetUp() GRPC_OVERRIDE { + void SetUp() override { poll_overrider_.reset(new PollingOverrider(!GetParam().disable_blocking)); port_ = grpc_pick_unused_port_or_die(); @@ -269,7 +269,7 @@ class AsyncEnd2endTest : public ::testing::TestWithParam { gpr_tls_set(&g_is_async_end2end_test, 1); } - void TearDown() GRPC_OVERRIDE { + void TearDown() override { server_->Shutdown(); void* ignored_tag; bool ignored_ok; diff --git a/test/cpp/end2end/client_crash_test_server.cc b/test/cpp/end2end/client_crash_test_server.cc index 6e1457407c1..0e0a1059892 100644 --- a/test/cpp/end2end/client_crash_test_server.cc +++ b/test/cpp/end2end/client_crash_test_server.cc @@ -58,11 +58,10 @@ using namespace gflags; namespace grpc { namespace testing { -class ServiceImpl GRPC_FINAL - : public ::grpc::testing::EchoTestService::Service { - Status BidiStream(ServerContext* context, - ServerReaderWriter* stream) - GRPC_OVERRIDE { +class ServiceImpl final : public ::grpc::testing::EchoTestService::Service { + Status BidiStream( + ServerContext* context, + ServerReaderWriter* stream) override { EchoRequest request; EchoResponse response; while (stream->Read(&request)) { diff --git a/test/cpp/end2end/end2end_test.cc b/test/cpp/end2end/end2end_test.cc index 7af0fb997e2..4b8749884f8 100644 --- a/test/cpp/end2end/end2end_test.cc +++ b/test/cpp/end2end/end2end_test.cc @@ -37,6 +37,7 @@ #include #include #include +#include #include #include #include @@ -91,12 +92,12 @@ class TestMetadataCredentialsPlugin : public MetadataCredentialsPlugin { is_blocking_(is_blocking), is_successful_(is_successful) {} - bool IsBlocking() const GRPC_OVERRIDE { return is_blocking_; } + bool IsBlocking() const override { return is_blocking_; } - Status GetMetadata(grpc::string_ref service_url, grpc::string_ref method_name, - const grpc::AuthContext& channel_auth_context, - std::multimap* metadata) - GRPC_OVERRIDE { + Status GetMetadata( + grpc::string_ref service_url, grpc::string_ref method_name, + const grpc::AuthContext& channel_auth_context, + std::multimap* metadata) override { EXPECT_GT(service_url.length(), 0UL); EXPECT_GT(method_name.length(), 0UL); EXPECT_TRUE(channel_auth_context.IsPeerAuthenticated()); @@ -144,11 +145,11 @@ class TestAuthMetadataProcessor : public AuthMetadataProcessor { } // Interface implementation - bool IsBlocking() const GRPC_OVERRIDE { return is_blocking_; } + bool IsBlocking() const override { return is_blocking_; } Status Process(const InputMetadata& auth_metadata, AuthContext* context, OutputMetadata* consumed_auth_metadata, - OutputMetadata* response_metadata) GRPC_OVERRIDE { + OutputMetadata* response_metadata) override { EXPECT_TRUE(consumed_auth_metadata != nullptr); EXPECT_TRUE(context != nullptr); EXPECT_TRUE(response_metadata != nullptr); @@ -184,7 +185,7 @@ class Proxy : public ::grpc::testing::EchoTestService::Service { : stub_(grpc::testing::EchoTestService::NewStub(channel)) {} Status Echo(ServerContext* server_context, const EchoRequest* request, - EchoResponse* response) GRPC_OVERRIDE { + EchoResponse* response) override { std::unique_ptr client_context = ClientContext::FromServerContext(*server_context); return stub_->Echo(client_context.get(), *request, response); @@ -198,7 +199,7 @@ class TestServiceImplDupPkg : public ::grpc::testing::duplicate::EchoTestService::Service { public: Status Echo(ServerContext* context, const EchoRequest* request, - EchoResponse* response) GRPC_OVERRIDE { + EchoResponse* response) override { response->set_message("no package"); return Status::OK; } @@ -228,7 +229,7 @@ class End2endTest : public ::testing::TestWithParam { GetParam().Log(); } - void TearDown() GRPC_OVERRIDE { + void TearDown() override { if (is_server_started_) { server_->Shutdown(); if (proxy_server_) proxy_server_->Shutdown(); @@ -240,6 +241,7 @@ class End2endTest : public ::testing::TestWithParam { server_address_ << "127.0.0.1:" << port; // Setup server ServerBuilder builder; + ConfigureServerBuilder(&builder); auto server_creds = GetServerCredentials(GetParam().credentials_type); if (GetParam().credentials_type != kInsecureCredentialsType) { server_creds->SetAuthMetadataProcessor(processor); @@ -247,13 +249,21 @@ class End2endTest : public ::testing::TestWithParam { builder.AddListeningPort(server_address_.str(), server_creds); builder.RegisterService(&service_); builder.RegisterService("foo.test.youtube.com", &special_service_); - builder.SetMaxMessageSize( - kMaxMessageSize_); // For testing max message size. builder.RegisterService(&dup_pkg_service_); + + builder.SetSyncServerOption(ServerBuilder::SyncServerOption::NUM_CQS, 4); + builder.SetSyncServerOption( + ServerBuilder::SyncServerOption::CQ_TIMEOUT_MSEC, 10); + server_ = builder.BuildAndStart(); is_server_started_ = true; } + virtual void ConfigureServerBuilder(ServerBuilder* builder) { + builder->SetMaxMessageSize( + kMaxMessageSize_); // For testing max message size. + } + void ResetChannel() { if (!is_server_started_) { StartServer(std::shared_ptr()); @@ -279,6 +289,11 @@ class End2endTest : public ::testing::TestWithParam { ServerBuilder builder; builder.AddListeningPort(proxyaddr.str(), InsecureServerCredentials()); builder.RegisterService(proxy_service_.get()); + + builder.SetSyncServerOption(ServerBuilder::SyncServerOption::NUM_CQS, 4); + builder.SetSyncServerOption( + ServerBuilder::SyncServerOption::CQ_TIMEOUT_MSEC, 10); + proxy_server_ = builder.BuildAndStart(); channel_ = CreateChannel(proxyaddr.str(), InsecureChannelCredentials()); @@ -1476,6 +1491,32 @@ TEST_P(SecureEnd2endTest, ClientAuthContext) { } } +class ResourceQuotaEnd2endTest : public End2endTest { + public: + ResourceQuotaEnd2endTest() + : server_resource_quota_("server_resource_quota") {} + + virtual void ConfigureServerBuilder(ServerBuilder* builder) override { + builder->SetResourceQuota(server_resource_quota_); + } + + private: + ResourceQuota server_resource_quota_; +}; + +TEST_P(ResourceQuotaEnd2endTest, SimpleRequest) { + ResetStub(); + + EchoRequest request; + EchoResponse response; + request.set_message("Hello"); + + ClientContext context; + Status s = stub_->Echo(&context, request, &response); + EXPECT_EQ(response.message(), request.message()); + EXPECT_TRUE(s.ok()); +} + std::vector CreateTestScenarios(bool use_proxy, bool test_insecure, bool test_secure) { @@ -1513,6 +1554,10 @@ INSTANTIATE_TEST_CASE_P(SecureEnd2end, SecureEnd2endTest, ::testing::ValuesIn(CreateTestScenarios(false, false, true))); +INSTANTIATE_TEST_CASE_P(ResourceQuotaEnd2end, ResourceQuotaEnd2endTest, + ::testing::ValuesIn(CreateTestScenarios(false, true, + true))); + } // namespace } // namespace testing } // namespace grpc diff --git a/test/cpp/end2end/filter_end2end_test.cc b/test/cpp/end2end/filter_end2end_test.cc index 853720fd0d0..ab6ed46de56 100644 --- a/test/cpp/end2end/filter_end2end_test.cc +++ b/test/cpp/end2end/filter_end2end_test.cc @@ -78,35 +78,35 @@ namespace { int global_num_connections = 0; int global_num_calls = 0; -mutex global_mu; +std::mutex global_mu; void IncrementConnectionCounter() { - unique_lock lock(global_mu); + std::unique_lock lock(global_mu); ++global_num_connections; } void ResetConnectionCounter() { - unique_lock lock(global_mu); + std::unique_lock lock(global_mu); global_num_connections = 0; } int GetConnectionCounterValue() { - unique_lock lock(global_mu); + std::unique_lock lock(global_mu); return global_num_connections; } void IncrementCallCounter() { - unique_lock lock(global_mu); + std::unique_lock lock(global_mu); ++global_num_calls; } void ResetCallCounter() { - unique_lock lock(global_mu); + std::unique_lock lock(global_mu); global_num_calls = 0; } int GetCallCounterValue() { - unique_lock lock(global_mu); + std::unique_lock lock(global_mu); return global_num_calls; } @@ -126,7 +126,7 @@ class CallDataImpl : public CallData { : CallData(channel_data) {} void StartTransportStreamOp(grpc_exec_ctx* exec_ctx, grpc_call_element* elem, - TransportStreamOp* op) GRPC_OVERRIDE { + TransportStreamOp* op) override { // Incrementing the counter could be done from the ctor, but we want // to test that the individual methods are actually called correctly. if (op->recv_initial_metadata() != nullptr) IncrementCallCounter(); @@ -138,7 +138,7 @@ class FilterEnd2endTest : public ::testing::Test { protected: FilterEnd2endTest() : server_host_("localhost") {} - void SetUp() GRPC_OVERRIDE { + void SetUp() override { int port = grpc_pick_unused_port_or_die(); server_address_ << server_host_ << ":" << port; // Setup server @@ -150,7 +150,7 @@ class FilterEnd2endTest : public ::testing::Test { server_ = builder.BuildAndStart(); } - void TearDown() GRPC_OVERRIDE { + void TearDown() override { server_->Shutdown(); void* ignored_tag; bool ignored_ok; diff --git a/test/cpp/end2end/generic_end2end_test.cc b/test/cpp/end2end/generic_end2end_test.cc index 57efa5fa17f..25c221bb2b0 100644 --- a/test/cpp/end2end/generic_end2end_test.cc +++ b/test/cpp/end2end/generic_end2end_test.cc @@ -75,7 +75,7 @@ class GenericEnd2endTest : public ::testing::Test { protected: GenericEnd2endTest() : server_host_("localhost") {} - void SetUp() GRPC_OVERRIDE { + void SetUp() override { int port = grpc_pick_unused_port_or_die(); server_address_ << server_host_ << ":" << port; // Setup server @@ -91,7 +91,7 @@ class GenericEnd2endTest : public ::testing::Test { server_ = builder.BuildAndStart(); } - void TearDown() GRPC_OVERRIDE { + void TearDown() override { server_->Shutdown(); void* ignored_tag; bool ignored_ok; diff --git a/test/cpp/end2end/hybrid_end2end_test.cc b/test/cpp/end2end/hybrid_end2end_test.cc index 76a5732f338..a4ba76fed14 100644 --- a/test/cpp/end2end/hybrid_end2end_test.cc +++ b/test/cpp/end2end/hybrid_end2end_test.cc @@ -188,7 +188,7 @@ class TestServiceImplDupPkg : public ::grpc::testing::duplicate::EchoTestService::Service { public: Status Echo(ServerContext* context, const EchoRequest* request, - EchoResponse* response) GRPC_OVERRIDE { + EchoResponse* response) override { response->set_message(request->message() + "_dup"); return Status::OK; } @@ -230,7 +230,7 @@ class HybridEnd2endTest : public ::testing::Test { server_ = builder.BuildAndStart(); } - void TearDown() GRPC_OVERRIDE { + void TearDown() override { if (server_) { server_->Shutdown(); } @@ -449,9 +449,9 @@ class StreamedUnaryDupPkg : public duplicate::EchoTestService::WithStreamedUnaryMethod_Echo< TestServiceImplDupPkg> { public: - Status StreamedEcho(ServerContext* context, - ServerUnaryStreamer* stream) - GRPC_OVERRIDE { + Status StreamedEcho( + ServerContext* context, + ServerUnaryStreamer* stream) override { EchoRequest req; EchoResponse resp; uint32_t next_msg_sz; @@ -487,9 +487,9 @@ TEST_F(HybridEnd2endTest, class FullyStreamedUnaryDupPkg : public duplicate::EchoTestService::StreamedUnaryService { public: - Status StreamedEcho(ServerContext* context, - ServerUnaryStreamer* stream) - GRPC_OVERRIDE { + Status StreamedEcho( + ServerContext* context, + ServerUnaryStreamer* stream) override { EchoRequest req; EchoResponse resp; uint32_t next_msg_sz; @@ -528,7 +528,7 @@ class SplitResponseStreamDupPkg public: Status StreamedResponseStream( ServerContext* context, - ServerSplitStreamer* stream) GRPC_OVERRIDE { + ServerSplitStreamer* stream) override { EchoRequest req; EchoResponse resp; uint32_t next_msg_sz; @@ -568,7 +568,7 @@ class FullySplitStreamedDupPkg public: Status StreamedResponseStream( ServerContext* context, - ServerSplitStreamer* stream) GRPC_OVERRIDE { + ServerSplitStreamer* stream) override { EchoRequest req; EchoResponse resp; uint32_t next_msg_sz; @@ -605,9 +605,9 @@ TEST_F(HybridEnd2endTest, // Add a second service that is fully server streamed class FullyStreamedDupPkg : public duplicate::EchoTestService::StreamedService { public: - Status StreamedEcho(ServerContext* context, - ServerUnaryStreamer* stream) - GRPC_OVERRIDE { + Status StreamedEcho( + ServerContext* context, + ServerUnaryStreamer* stream) override { EchoRequest req; EchoResponse resp; uint32_t next_msg_sz; @@ -620,7 +620,7 @@ class FullyStreamedDupPkg : public duplicate::EchoTestService::StreamedService { } Status StreamedResponseStream( ServerContext* context, - ServerSplitStreamer* stream) GRPC_OVERRIDE { + ServerSplitStreamer* stream) override { EchoRequest req; EchoResponse resp; uint32_t next_msg_sz; diff --git a/test/cpp/end2end/mock_test.cc b/test/cpp/end2end/mock_test.cc index 0da5861b67d..d6664da5a0f 100644 --- a/test/cpp/end2end/mock_test.cc +++ b/test/cpp/end2end/mock_test.cc @@ -61,46 +61,44 @@ namespace testing { namespace { template -class MockClientReaderWriter GRPC_FINAL - : public ClientReaderWriterInterface { +class MockClientReaderWriter final : public ClientReaderWriterInterface { public: - void WaitForInitialMetadata() GRPC_OVERRIDE {} - bool NextMessageSize(uint32_t* sz) GRPC_OVERRIDE { + void WaitForInitialMetadata() override {} + bool NextMessageSize(uint32_t* sz) override { *sz = UINT_MAX; return true; } - bool Read(R* msg) GRPC_OVERRIDE { return true; } - bool Write(const W& msg) GRPC_OVERRIDE { return true; } - bool WritesDone() GRPC_OVERRIDE { return true; } - Status Finish() GRPC_OVERRIDE { return Status::OK; } + bool Read(R* msg) override { return true; } + bool Write(const W& msg) override { return true; } + bool WritesDone() override { return true; } + Status Finish() override { return Status::OK; } }; template <> -class MockClientReaderWriter GRPC_FINAL +class MockClientReaderWriter final : public ClientReaderWriterInterface { public: MockClientReaderWriter() : writes_done_(false) {} - void WaitForInitialMetadata() GRPC_OVERRIDE {} - bool NextMessageSize(uint32_t* sz) GRPC_OVERRIDE { + void WaitForInitialMetadata() override {} + bool NextMessageSize(uint32_t* sz) override { *sz = UINT_MAX; return true; } - bool Read(EchoResponse* msg) GRPC_OVERRIDE { + bool Read(EchoResponse* msg) override { if (writes_done_) return false; msg->set_message(last_message_); return true; } - bool Write(const EchoRequest& msg, - const WriteOptions& options) GRPC_OVERRIDE { + bool Write(const EchoRequest& msg, const WriteOptions& options) override { gpr_log(GPR_INFO, "mock recv msg %s", msg.message().c_str()); last_message_ = msg.message(); return true; } - bool WritesDone() GRPC_OVERRIDE { + bool WritesDone() override { writes_done_ = true; return true; } - Status Finish() GRPC_OVERRIDE { return Status::OK; } + Status Finish() override { return Status::OK; } private: bool writes_done_; @@ -113,51 +111,51 @@ class MockStub : public EchoTestService::StubInterface { MockStub() {} ~MockStub() {} Status Echo(ClientContext* context, const EchoRequest& request, - EchoResponse* response) GRPC_OVERRIDE { + EchoResponse* response) override { response->set_message(request.message()); return Status::OK; } Status Unimplemented(ClientContext* context, const EchoRequest& request, - EchoResponse* response) GRPC_OVERRIDE { + EchoResponse* response) override { return Status::OK; } private: ClientAsyncResponseReaderInterface* AsyncEchoRaw( ClientContext* context, const EchoRequest& request, - CompletionQueue* cq) GRPC_OVERRIDE { + CompletionQueue* cq) override { return nullptr; } ClientWriterInterface* RequestStreamRaw( - ClientContext* context, EchoResponse* response) GRPC_OVERRIDE { + ClientContext* context, EchoResponse* response) override { return nullptr; } ClientAsyncWriterInterface* AsyncRequestStreamRaw( ClientContext* context, EchoResponse* response, CompletionQueue* cq, - void* tag) GRPC_OVERRIDE { + void* tag) override { return nullptr; } ClientReaderInterface* ResponseStreamRaw( - ClientContext* context, const EchoRequest& request) GRPC_OVERRIDE { + ClientContext* context, const EchoRequest& request) override { return nullptr; } ClientAsyncReaderInterface* AsyncResponseStreamRaw( ClientContext* context, const EchoRequest& request, CompletionQueue* cq, - void* tag) GRPC_OVERRIDE { + void* tag) override { return nullptr; } ClientReaderWriterInterface* BidiStreamRaw( - ClientContext* context) GRPC_OVERRIDE { + ClientContext* context) override { return new MockClientReaderWriter(); } ClientAsyncReaderWriterInterface* AsyncBidiStreamRaw(ClientContext* context, CompletionQueue* cq, - void* tag) GRPC_OVERRIDE { + void* tag) override { return nullptr; } ClientAsyncResponseReaderInterface* AsyncUnimplementedRaw( ClientContext* context, const EchoRequest& request, - CompletionQueue* cq) GRPC_OVERRIDE { + CompletionQueue* cq) override { return nullptr; } }; @@ -216,14 +214,14 @@ class FakeClient { class TestServiceImpl : public EchoTestService::Service { public: Status Echo(ServerContext* context, const EchoRequest* request, - EchoResponse* response) GRPC_OVERRIDE { + EchoResponse* response) override { response->set_message(request->message()); return Status::OK; } - Status BidiStream(ServerContext* context, - ServerReaderWriter* stream) - GRPC_OVERRIDE { + Status BidiStream( + ServerContext* context, + ServerReaderWriter* stream) override { EchoRequest request; EchoResponse response; while (stream->Read(&request)) { @@ -239,7 +237,7 @@ class MockTest : public ::testing::Test { protected: MockTest() {} - void SetUp() GRPC_OVERRIDE { + void SetUp() override { int port = grpc_pick_unused_port_or_die(); server_address_ << "localhost:" << port; // Setup server @@ -250,7 +248,7 @@ class MockTest : public ::testing::Test { server_ = builder.BuildAndStart(); } - void TearDown() GRPC_OVERRIDE { server_->Shutdown(); } + void TearDown() override { server_->Shutdown(); } void ResetStub() { std::shared_ptr channel = diff --git a/test/cpp/end2end/proto_server_reflection_test.cc b/test/cpp/end2end/proto_server_reflection_test.cc index 75efd01f066..8b9688d2003 100644 --- a/test/cpp/end2end/proto_server_reflection_test.cc +++ b/test/cpp/end2end/proto_server_reflection_test.cc @@ -56,7 +56,7 @@ class ProtoServerReflectionTest : public ::testing::Test { public: ProtoServerReflectionTest() {} - void SetUp() GRPC_OVERRIDE { + void SetUp() override { port_ = grpc_pick_unused_port_or_die(); ref_desc_pool_ = protobuf::DescriptorPool::generated_pool(); diff --git a/test/cpp/end2end/round_robin_end2end_test.cc b/test/cpp/end2end/round_robin_end2end_test.cc new file mode 100644 index 00000000000..76211cbdd3e --- /dev/null +++ b/test/cpp/end2end/round_robin_end2end_test.cc @@ -0,0 +1,211 @@ +/* + * + * Copyright 2016, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "src/proto/grpc/testing/echo.grpc.pb.h" +#include "test/core/util/port.h" +#include "test/core/util/test_config.h" +#include "test/cpp/end2end/test_service_impl.h" + +using grpc::testing::EchoRequest; +using grpc::testing::EchoResponse; +using std::chrono::system_clock; + +namespace grpc { +namespace testing { +namespace { + +// Subclass of TestServiceImpl that increments a request counter for +// every call to the Echo RPC. +class MyTestServiceImpl : public TestServiceImpl { + public: + MyTestServiceImpl() : request_count_(0) {} + + Status Echo(ServerContext* context, const EchoRequest* request, + EchoResponse* response) override { + { + std::unique_lock lock(mu_); + ++request_count_; + } + return TestServiceImpl::Echo(context, request, response); + } + + int request_count() { + std::unique_lock lock(mu_); + return request_count_; + } + + private: + std::mutex mu_; + int request_count_; +}; + +class RoundRobinEnd2endTest : public ::testing::Test { + protected: + RoundRobinEnd2endTest() : server_host_("localhost") {} + + void StartServers(int num_servers) { + for (int i = 0; i < num_servers; ++i) { + servers_.emplace_back(new ServerData(server_host_)); + } + } + + void TearDown() override { + for (size_t i = 0; i < servers_.size(); ++i) { + servers_[i]->Shutdown(); + } + } + + void ResetStub(bool round_robin) { + ChannelArguments args; + if (round_robin) args.SetLoadBalancingPolicyName("round_robin"); + std::ostringstream uri; + uri << "ipv4:///"; + for (size_t i = 0; i < servers_.size() - 1; ++i) { + uri << "127.0.0.1:" << servers_[i]->port_ << ","; + } + uri << "127.0.0.1:" << servers_[servers_.size() - 1]->port_; + std::shared_ptr channel = + CreateCustomChannel(uri.str(), InsecureChannelCredentials(), args); + stub_ = grpc::testing::EchoTestService::NewStub(channel); + } + + void SendRpc(int num_rpcs) { + EchoRequest request; + EchoResponse response; + request.set_message("Live long and prosper."); + for (int i = 0; i < num_rpcs; i++) { + ClientContext context; + Status status = stub_->Echo(&context, request, &response); + EXPECT_TRUE(status.ok()); + EXPECT_EQ(response.message(), request.message()); + } + } + + struct ServerData { + int port_; + std::unique_ptr server_; + MyTestServiceImpl service_; + std::unique_ptr thread_; + + explicit ServerData(const grpc::string& server_host) { + port_ = grpc_pick_unused_port_or_die(); + gpr_log(GPR_INFO, "starting server on port %d", port_); + std::mutex mu; + std::condition_variable cond; + thread_.reset(new std::thread( + std::bind(&ServerData::Start, this, server_host, &mu, &cond))); + std::unique_lock lock(mu); + cond.wait(lock); + gpr_log(GPR_INFO, "server startup complete"); + } + + void Start(const grpc::string& server_host, std::mutex* mu, + std::condition_variable* cond) { + std::ostringstream server_address; + server_address << server_host << ":" << port_; + ServerBuilder builder; + builder.AddListeningPort(server_address.str(), + InsecureServerCredentials()); + builder.RegisterService(&service_); + server_ = builder.BuildAndStart(); + std::lock_guard lock(*mu); + cond->notify_one(); + } + + void Shutdown() { + server_->Shutdown(); + thread_->join(); + } + }; + + const grpc::string server_host_; + CompletionQueue cli_cq_; + std::unique_ptr stub_; + std::vector> servers_; +}; + +TEST_F(RoundRobinEnd2endTest, PickFirst) { + // Start servers and send one RPC per server. + const int kNumServers = 3; + StartServers(kNumServers); + ResetStub(false /* round_robin */); + SendRpc(kNumServers); + // All requests should have gone to a single server. + bool found = false; + for (size_t i = 0; i < servers_.size(); ++i) { + const int request_count = servers_[i]->service_.request_count(); + if (request_count == kNumServers) { + found = true; + } else { + EXPECT_EQ(0, request_count); + } + } + EXPECT_TRUE(found); +} + +TEST_F(RoundRobinEnd2endTest, RoundRobin) { + // Start servers and send one RPC per server. + const int kNumServers = 3; + StartServers(kNumServers); + ResetStub(true /* round_robin */); + SendRpc(kNumServers); + // One request should have gone to each server. + for (size_t i = 0; i < servers_.size(); ++i) { + EXPECT_EQ(1, servers_[i]->service_.request_count()); + } +} + +} // namespace +} // namespace testing +} // namespace grpc + +int main(int argc, char** argv) { + grpc_test_init(argc, argv); + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/test/cpp/end2end/server_builder_plugin_test.cc b/test/cpp/end2end/server_builder_plugin_test.cc index b967a5d1e99..1b6f4ce37d8 100644 --- a/test/cpp/end2end/server_builder_plugin_test.cc +++ b/test/cpp/end2end/server_builder_plugin_test.cc @@ -31,13 +31,14 @@ * */ +#include + #include #include #include #include #include #include -#include #include #include #include @@ -65,29 +66,29 @@ class TestServerBuilderPlugin : public ServerBuilderPlugin { register_service_ = false; } - grpc::string name() GRPC_OVERRIDE { return PLUGIN_NAME; } + grpc::string name() override { return PLUGIN_NAME; } - void InitServer(ServerInitializer* si) GRPC_OVERRIDE { + void InitServer(ServerInitializer* si) override { init_server_is_called_ = true; if (register_service_) { si->RegisterService(service_); } } - void Finish(ServerInitializer* si) GRPC_OVERRIDE { finish_is_called_ = true; } + void Finish(ServerInitializer* si) override { finish_is_called_ = true; } - void ChangeArguments(const grpc::string& name, void* value) GRPC_OVERRIDE { + void ChangeArguments(const grpc::string& name, void* value) override { change_arguments_is_called_ = true; } - bool has_async_methods() const GRPC_OVERRIDE { + bool has_async_methods() const override { if (register_service_) { return service_->has_async_methods(); } return false; } - bool has_sync_methods() const GRPC_OVERRIDE { + bool has_sync_methods() const override { if (register_service_) { return service_->has_synchronous_methods(); } @@ -112,10 +113,10 @@ class InsertPluginServerBuilderOption : public ServerBuilderOption { public: InsertPluginServerBuilderOption() { register_service_ = false; } - void UpdateArguments(ChannelArguments* arg) GRPC_OVERRIDE {} + void UpdateArguments(ChannelArguments* arg) override {} - void UpdatePlugins(std::vector>* plugins) - GRPC_OVERRIDE { + void UpdatePlugins( + std::vector>* plugins) override { plugins->clear(); std::unique_ptr plugin( @@ -154,7 +155,7 @@ class ServerBuilderPluginTest : public ::testing::TestWithParam { public: ServerBuilderPluginTest() {} - void SetUp() GRPC_OVERRIDE { + void SetUp() override { port_ = grpc_pick_unused_port_or_die(); builder_.reset(new ServerBuilder()); } @@ -191,7 +192,7 @@ class ServerBuilderPluginTest : public ::testing::TestWithParam { // we run some tests without a service, and for those we need to supply a // frequently polled completion queue cq_ = builder_->AddCompletionQueue(); - cq_thread_ = new grpc::thread(&ServerBuilderPluginTest::RunCQ, this); + cq_thread_ = new std::thread(&ServerBuilderPluginTest::RunCQ, this); server_ = builder_->BuildAndStart(); EXPECT_TRUE(CheckPresent()); } @@ -202,7 +203,7 @@ class ServerBuilderPluginTest : public ::testing::TestWithParam { stub_ = grpc::testing::EchoTestService::NewStub(channel_); } - void TearDown() GRPC_OVERRIDE { + void TearDown() override { auto plugin = CheckPresent(); EXPECT_TRUE(plugin); EXPECT_TRUE(plugin->init_server_is_called()); @@ -225,7 +226,7 @@ class ServerBuilderPluginTest : public ::testing::TestWithParam { std::unique_ptr stub_; std::unique_ptr cq_; std::unique_ptr server_; - grpc::thread* cq_thread_; + std::thread* cq_thread_; TestServiceImpl service_; int port_; diff --git a/test/cpp/end2end/server_crash_test.cc b/test/cpp/end2end/server_crash_test.cc index 16a5fa23222..8cee1403dcf 100644 --- a/test/cpp/end2end/server_crash_test.cc +++ b/test/cpp/end2end/server_crash_test.cc @@ -60,14 +60,13 @@ namespace testing { namespace { -class ServiceImpl GRPC_FINAL - : public ::grpc::testing::EchoTestService::Service { +class ServiceImpl final : public ::grpc::testing::EchoTestService::Service { public: ServiceImpl() : bidi_stream_count_(0), response_stream_count_(0) {} - Status BidiStream(ServerContext* context, - ServerReaderWriter* stream) - GRPC_OVERRIDE { + Status BidiStream( + ServerContext* context, + ServerReaderWriter* stream) override { bidi_stream_count_++; EchoRequest request; EchoResponse response; @@ -82,7 +81,7 @@ class ServiceImpl GRPC_FINAL } Status ResponseStream(ServerContext* context, const EchoRequest* request, - ServerWriter* writer) GRPC_OVERRIDE { + ServerWriter* writer) override { EchoResponse response; response_stream_count_++; for (int i = 0;; i++) { diff --git a/test/cpp/end2end/shutdown_test.cc b/test/cpp/end2end/shutdown_test.cc index 4cba3b1c814..5b52b1fc1aa 100644 --- a/test/cpp/end2end/shutdown_test.cc +++ b/test/cpp/end2end/shutdown_test.cc @@ -61,7 +61,7 @@ class TestServiceImpl : public ::grpc::testing::EchoTestService::Service { explicit TestServiceImpl(gpr_event* ev) : ev_(ev) {} Status Echo(ServerContext* context, const EchoRequest* request, - EchoResponse* response) GRPC_OVERRIDE { + EchoResponse* response) override { gpr_event_set(ev_, (void*)1); while (!context->IsCancelled()) { } @@ -76,7 +76,7 @@ class ShutdownTest : public ::testing::Test { public: ShutdownTest() : shutdown_(false), service_(&ev_) { gpr_event_init(&ev_); } - void SetUp() GRPC_OVERRIDE { + void SetUp() override { port_ = grpc_pick_unused_port_or_die(); server_ = SetUpServer(port_); } @@ -91,7 +91,7 @@ class ShutdownTest : public ::testing::Test { return server; } - void TearDown() GRPC_OVERRIDE { GPR_ASSERT(shutdown_); } + void TearDown() override { GPR_ASSERT(shutdown_); } void ResetStub() { string target = "dns:localhost:" + to_string(port_); diff --git a/test/cpp/end2end/streaming_throughput_test.cc b/test/cpp/end2end/streaming_throughput_test.cc index fbef761ca9c..302583766b8 100644 --- a/test/cpp/end2end/streaming_throughput_test.cc +++ b/test/cpp/end2end/streaming_throughput_test.cc @@ -121,9 +121,9 @@ class TestServiceImpl : public ::grpc::testing::EchoTestService::Service { } // Only implement the one method we will be calling for brevity. - Status BidiStream(ServerContext* context, - ServerReaderWriter* stream) - GRPC_OVERRIDE { + Status BidiStream( + ServerContext* context, + ServerReaderWriter* stream) override { EchoRequest request; gpr_atm should_exit; gpr_atm_rel_store(&should_exit, static_cast(0)); @@ -147,7 +147,7 @@ class TestServiceImpl : public ::grpc::testing::EchoTestService::Service { class End2endTest : public ::testing::Test { protected: - void SetUp() GRPC_OVERRIDE { + void SetUp() override { int port = grpc_pick_unused_port_or_die(); server_address_ << "localhost:" << port; // Setup server @@ -158,7 +158,7 @@ class End2endTest : public ::testing::Test { server_ = builder.BuildAndStart(); } - void TearDown() GRPC_OVERRIDE { server_->Shutdown(); } + void TearDown() override { server_->Shutdown(); } void ResetStub() { std::shared_ptr channel = diff --git a/test/cpp/end2end/test_service_impl.h b/test/cpp/end2end/test_service_impl.h index c89f88c900e..88e0be7bca7 100644 --- a/test/cpp/end2end/test_service_impl.h +++ b/test/cpp/end2end/test_service_impl.h @@ -63,20 +63,20 @@ class TestServiceImpl : public ::grpc::testing::EchoTestService::Service { : signal_client_(false), host_(new grpc::string(host)) {} Status Echo(ServerContext* context, const EchoRequest* request, - EchoResponse* response) GRPC_OVERRIDE; + EchoResponse* response) override; // Unimplemented is left unimplemented to test the returned error. Status RequestStream(ServerContext* context, ServerReader* reader, - EchoResponse* response) GRPC_OVERRIDE; + EchoResponse* response) override; Status ResponseStream(ServerContext* context, const EchoRequest* request, - ServerWriter* writer) GRPC_OVERRIDE; + ServerWriter* writer) override; - Status BidiStream(ServerContext* context, - ServerReaderWriter* stream) - GRPC_OVERRIDE; + Status BidiStream( + ServerContext* context, + ServerReaderWriter* stream) override; bool signal_client() { std::unique_lock lock(mu_); diff --git a/test/cpp/end2end/thread_stress_test.cc b/test/cpp/end2end/thread_stress_test.cc index 0b9d4cda9f4..fe5a219eed7 100644 --- a/test/cpp/end2end/thread_stress_test.cc +++ b/test/cpp/end2end/thread_stress_test.cc @@ -86,12 +86,12 @@ class TestServiceImpl : public ::grpc::testing::EchoTestService::Service { TestServiceImpl() : signal_client_(false) {} Status Echo(ServerContext* context, const EchoRequest* request, - EchoResponse* response) GRPC_OVERRIDE { + EchoResponse* response) override { response->set_message(request->message()); MaybeEchoDeadline(context, request, response); if (request->has_param() && request->param().client_cancel_after_us()) { { - unique_lock lock(mu_); + std::unique_lock lock(mu_); signal_client_ = true; } while (!context->IsCancelled()) { @@ -118,7 +118,7 @@ class TestServiceImpl : public ::grpc::testing::EchoTestService::Service { Status RequestStream(ServerContext* context, ServerReader* reader, - EchoResponse* response) GRPC_OVERRIDE { + EchoResponse* response) override { EchoRequest request; response->set_message(""); while (reader->Read(&request)) { @@ -130,7 +130,7 @@ class TestServiceImpl : public ::grpc::testing::EchoTestService::Service { // Return 3 messages. // TODO(yangg) make it generic by adding a parameter into EchoRequest Status ResponseStream(ServerContext* context, const EchoRequest* request, - ServerWriter* writer) GRPC_OVERRIDE { + ServerWriter* writer) override { EchoResponse response; response.set_message(request->message() + "0"); writer->Write(response); @@ -142,9 +142,9 @@ class TestServiceImpl : public ::grpc::testing::EchoTestService::Service { return Status::OK; } - Status BidiStream(ServerContext* context, - ServerReaderWriter* stream) - GRPC_OVERRIDE { + Status BidiStream( + ServerContext* context, + ServerReaderWriter* stream) override { EchoRequest request; EchoResponse response; while (stream->Read(&request)) { @@ -156,20 +156,20 @@ class TestServiceImpl : public ::grpc::testing::EchoTestService::Service { } bool signal_client() { - unique_lock lock(mu_); + std::unique_lock lock(mu_); return signal_client_; } private: bool signal_client_; - mutex mu_; + std::mutex mu_; }; class TestServiceImplDupPkg : public ::grpc::testing::duplicate::EchoTestService::Service { public: Status Echo(ServerContext* context, const EchoRequest* request, - EchoResponse* response) GRPC_OVERRIDE { + EchoResponse* response) override { response->set_message("no package"); return Status::OK; } @@ -215,12 +215,12 @@ class CommonStressTest { class CommonStressTestSyncServer : public CommonStressTest { public: - void SetUp() GRPC_OVERRIDE { + void SetUp() override { ServerBuilder builder; SetUpStart(&builder, &service_); SetUpEnd(&builder); } - void TearDown() GRPC_OVERRIDE { + void TearDown() override { TearDownStart(); TearDownEnd(); } @@ -232,7 +232,7 @@ class CommonStressTestSyncServer : public CommonStressTest { class CommonStressTestAsyncServer : public CommonStressTest { public: - void SetUp() GRPC_OVERRIDE { + void SetUp() override { shutting_down_ = false; ServerBuilder builder; SetUpStart(&builder, &service_); @@ -247,9 +247,9 @@ class CommonStressTestAsyncServer new std::thread(&CommonStressTestAsyncServer::ProcessRpcs, this)); } } - void TearDown() GRPC_OVERRIDE { + void TearDown() override { { - unique_lock l(mu_); + std::unique_lock l(mu_); TearDownStart(); shutting_down_ = true; cq_->Shutdown(); @@ -292,7 +292,7 @@ class CommonStressTestAsyncServer } } void RefreshContext(int i) { - unique_lock l(mu_); + std::unique_lock l(mu_); if (!shutting_down_) { contexts_[i].state = Context::READY; contexts_[i].srv_ctx.reset(new ServerContext); @@ -315,7 +315,7 @@ class CommonStressTestAsyncServer ::grpc::testing::EchoTestService::AsyncService service_; std::unique_ptr cq_; bool shutting_down_; - mutex mu_; + std::mutex mu_; std::vector server_threads_; }; @@ -323,8 +323,8 @@ template class End2endTest : public ::testing::Test { protected: End2endTest() {} - void SetUp() GRPC_OVERRIDE { common_.SetUp(); } - void TearDown() GRPC_OVERRIDE { common_.TearDown(); } + void SetUp() override { common_.SetUp(); } + void TearDown() override { common_.TearDown(); } void ResetStub() { common_.ResetStub(); } Common common_; @@ -369,8 +369,8 @@ class AsyncClientEnd2endTest : public ::testing::Test { protected: AsyncClientEnd2endTest() : rpcs_outstanding_(0) {} - void SetUp() GRPC_OVERRIDE { common_.SetUp(); } - void TearDown() GRPC_OVERRIDE { + void SetUp() override { common_.SetUp(); } + void TearDown() override { void* ignored_tag; bool ignored_ok; while (cq_.Next(&ignored_tag, &ignored_ok)) @@ -379,7 +379,7 @@ class AsyncClientEnd2endTest : public ::testing::Test { } void Wait() { - unique_lock l(mu_); + std::unique_lock l(mu_); while (rpcs_outstanding_ != 0) { cv_.wait(l); } @@ -404,7 +404,7 @@ class AsyncClientEnd2endTest : public ::testing::Test { call->response_reader->Finish(&call->response, &call->status, (void*)call); - unique_lock l(mu_); + std::unique_lock l(mu_); rpcs_outstanding_++; } } @@ -422,7 +422,7 @@ class AsyncClientEnd2endTest : public ::testing::Test { bool notify; { - unique_lock l(mu_); + std::unique_lock l(mu_); rpcs_outstanding_--; notify = (rpcs_outstanding_ == 0); } @@ -434,8 +434,8 @@ class AsyncClientEnd2endTest : public ::testing::Test { Common common_; CompletionQueue cq_; - mutex mu_; - condition_variable cv_; + std::mutex mu_; + std::condition_variable cv_; int rpcs_outstanding_; }; diff --git a/test/cpp/grpclb/grpclb_test.cc b/test/cpp/grpclb/grpclb_test.cc index b6056f9ae4c..c796e55e1ae 100644 --- a/test/cpp/grpclb/grpclb_test.cc +++ b/test/cpp/grpclb/grpclb_test.cc @@ -76,10 +76,22 @@ extern "C" { // - Send a serverlist with faulty ip:port addresses (port > 2^16, etc). // - Test reception of invalid serverlist // - Test pinging -// - Test against a non-LB server. That server should return UNIMPLEMENTED and -// the call should fail. +// - Test against a non-LB server. // - Random LB server closing the stream unexpectedly. // - Test using DNS-resolvable names (localhost?) +// +// Findings from end to end testing to be covered here: +// - Handling of LB servers restart, including reconnection after backing-off +// retries. +// - Destruction of load balanced channel (and therefore of grpclb instance) +// while: +// 1) the internal LB call is still active. This should work by virtue +// of the weak reference the LB call holds. The call should be terminated as +// part of the grpclb shutdown process. +// 2) the retry timer is active. Again, the weak reference it holds should +// prevent a premature call to \a glb_destroy. +// - Restart of backend servers with no changes to serverlist. This exercises +// the RR handover mechanism. namespace grpc { namespace { @@ -144,7 +156,6 @@ static gpr_slice build_response_payload_slice( // disfunctional implementation of std::to_string in gcc 4.4, which doesn't // have a version for int but does have one for long long int. string token_data = "token" + std::to_string((long long int)ports[i]); - token_data.resize(64, '-'); server->set_load_balance_token(token_data); } const grpc::string &enc_resp = response.SerializeAsString(); @@ -333,7 +344,6 @@ static void start_backend_server(server_fixture *sf) { // disfunctional implementation of std::to_string in gcc 4.4, which doesn't // have a version for int but does have one for long long int. string expected_token = "token" + std::to_string((long long int)sf->port); - expected_token.resize(64, '-'); GPR_ASSERT(contains_metadata(&request_metadata_recv, "lb-token", expected_token.c_str())); diff --git a/test/cpp/interop/client.cc b/test/cpp/interop/client.cc index 4197ba8bab2..c58910abc3f 100644 --- a/test/cpp/interop/client.cc +++ b/test/cpp/interop/client.cc @@ -54,33 +54,35 @@ DEFINE_int32(server_port, 0, "Server port."); DEFINE_string(server_host, "127.0.0.1", "Server host to connect to"); DEFINE_string(server_host_override, "foo.test.google.fr", "Override the server host which is sent in HTTP header"); -DEFINE_string(test_case, "large_unary", - "Configure different test cases. Valid options are:\n\n" - "all : all test cases;\n" - "cancel_after_begin : cancel stream after starting it;\n" - "cancel_after_first_response: cancel on first response;\n" - "client_compressed_streaming : compressed request streaming with " - "client_compressed_unary : single compressed request;\n" - "client_streaming : request streaming with single response;\n" - "compute_engine_creds: large_unary with compute engine auth;\n" - "custom_metadata: server will echo custom metadata;\n" - "empty_stream : bi-di stream with no request/response;\n" - "empty_unary : empty (zero bytes) request and response;\n" - "half_duplex : half-duplex streaming;\n" - "jwt_token_creds: large_unary with JWT token auth;\n" - "large_unary : single request and (large) response;\n" - "oauth2_auth_token: raw oauth2 access token auth;\n" - "per_rpc_creds: raw oauth2 access token on a single rpc;\n" - "ping_pong : full-duplex streaming;\n" - "response streaming;\n" - "server_compressed_streaming : single request with compressed " - "server_compressed_unary : single compressed response;\n" - "server_streaming : single request with response streaming;\n" - "slow_consumer : single request with response streaming with " - "slow client consumer;\n" - "status_code_and_message: verify status code & message;\n" - "timeout_on_sleeping_server: deadline exceeds on stream;\n" - "unimplemented_method: client calls an unimplemented method;\n"); +DEFINE_string( + test_case, "large_unary", + "Configure different test cases. Valid options are:\n\n" + "all : all test cases;\n" + "cancel_after_begin : cancel stream after starting it;\n" + "cancel_after_first_response: cancel on first response;\n" + "client_compressed_streaming : compressed request streaming with " + "client_compressed_unary : single compressed request;\n" + "client_streaming : request streaming with single response;\n" + "compute_engine_creds: large_unary with compute engine auth;\n" + "custom_metadata: server will echo custom metadata;\n" + "empty_stream : bi-di stream with no request/response;\n" + "empty_unary : empty (zero bytes) request and response;\n" + "half_duplex : half-duplex streaming;\n" + "jwt_token_creds: large_unary with JWT token auth;\n" + "large_unary : single request and (large) response;\n" + "oauth2_auth_token: raw oauth2 access token auth;\n" + "per_rpc_creds: raw oauth2 access token on a single rpc;\n" + "ping_pong : full-duplex streaming;\n" + "response streaming;\n" + "server_compressed_streaming : single request with compressed " + "server_compressed_unary : single compressed response;\n" + "server_streaming : single request with response streaming;\n" + "slow_consumer : single request with response streaming with " + "slow client consumer;\n" + "status_code_and_message: verify status code & message;\n" + "timeout_on_sleeping_server: deadline exceeds on stream;\n" + "unimplemented_method: client calls an unimplemented method;\n" + "unimplemented_service: client calls an unimplemented service;\n"); DEFINE_string(default_service_account, "", "Email of GCE default service account"); DEFINE_string(service_account_key_file, "", @@ -152,6 +154,8 @@ int main(int argc, char** argv) { client.DoCustomMetadata(); } else if (FLAGS_test_case == "unimplemented_method") { client.DoUnimplementedMethod(); + } else if (FLAGS_test_case == "unimplemented_service") { + client.DoUnimplementedService(); } else if (FLAGS_test_case == "cacheable_unary") { client.DoCacheableUnary(); } else if (FLAGS_test_case == "all") { @@ -172,6 +176,7 @@ int main(int argc, char** argv) { client.DoStatusWithMessage(); client.DoCustomMetadata(); client.DoUnimplementedMethod(); + client.DoUnimplementedService(); client.DoCacheableUnary(); // service_account_creds and jwt_token_creds can only run with ssl. if (FLAGS_use_tls) { @@ -207,7 +212,8 @@ int main(int argc, char** argv) { "server_streaming", "status_code_and_message", "timeout_on_sleeping_server", - "unimplemented_method"}; + "unimplemented_method", + "unimplemented_service"}; char* joined_testcases = gpr_strjoin_sep(testcases, GPR_ARRAY_SIZE(testcases), "\n", NULL); diff --git a/test/cpp/interop/interop_client.cc b/test/cpp/interop/interop_client.cc index 1668589cc4a..d1242627ef3 100644 --- a/test/cpp/interop/interop_client.cc +++ b/test/cpp/interop/interop_client.cc @@ -107,6 +107,11 @@ TestService::Stub* InteropClient::ServiceStub::Get() { return stub_.get(); } +UnimplementedService::Stub* +InteropClient::ServiceStub::GetUnimplementedServiceStub() { + return UnimplementedService::NewStub(channel_).get(); +} + void InteropClient::ServiceStub::Reset(std::shared_ptr channel) { channel_ = channel; @@ -162,8 +167,8 @@ bool InteropClient::AssertStatusCode(const Status& s, bool InteropClient::DoEmpty() { gpr_log(GPR_DEBUG, "Sending an empty rpc..."); - Empty request = Empty::default_instance(); - Empty response = Empty::default_instance(); + Empty request; + Empty response; ClientContext context; Status s = serviceStub_.Get()->EmptyCall(&context, request, &response); @@ -1002,11 +1007,30 @@ bool InteropClient::DoCustomMetadata() { return true; } +bool InteropClient::DoUnimplementedService() { + gpr_log(GPR_DEBUG, "Sending a request for an unimplemented service..."); + + Empty request; + Empty response; + ClientContext context; + + UnimplementedService::Stub* stub = serviceStub_.GetUnimplementedServiceStub(); + + Status s = stub->UnimplementedCall(&context, request, &response); + + if (!AssertStatusCode(s, StatusCode::UNIMPLEMENTED)) { + return false; + } + + gpr_log(GPR_DEBUG, "unimplemented service done."); + return true; +} + bool InteropClient::DoUnimplementedMethod() { gpr_log(GPR_DEBUG, "Sending a request for an unimplemented rpc..."); - Empty request = Empty::default_instance(); - Empty response = Empty::default_instance(); + Empty request; + Empty response; ClientContext context; Status s = diff --git a/test/cpp/interop/interop_client.h b/test/cpp/interop/interop_client.h index 0a96e7734d8..7ec7ebee209 100644 --- a/test/cpp/interop/interop_client.h +++ b/test/cpp/interop/interop_client.h @@ -80,6 +80,7 @@ class InteropClient { bool DoStatusWithMessage(); bool DoCustomMetadata(); bool DoUnimplementedMethod(); + bool DoUnimplementedService(); bool DoCacheableUnary(); // Auth tests. // username is a string containing the user email @@ -100,6 +101,7 @@ class InteropClient { ServiceStub(std::shared_ptr channel, bool new_stub_every_call); TestService::Stub* Get(); + UnimplementedService::Stub* GetUnimplementedServiceStub(); void Reset(std::shared_ptr channel); diff --git a/test/cpp/interop/stress_test.cc b/test/cpp/interop/stress_test.cc index 46d09b7f285..fc35db5233a 100644 --- a/test/cpp/interop/stress_test.cc +++ b/test/cpp/interop/stress_test.cc @@ -40,7 +40,6 @@ #include #include #include -#include #include #include @@ -321,7 +320,7 @@ int main(int argc, char** argv) { gpr_log(GPR_INFO, "Starting test(s).."); - std::vector test_threads; + std::vector test_threads; // Create and start the test threads. // Note that: @@ -361,7 +360,7 @@ int main(int argc, char** argv) { "/stress_test/server_%d/channel_%d/stub_%d/qps", server_idx, channel_idx, stub_idx); - test_threads.emplace_back(grpc::thread( + test_threads.emplace_back(std::thread( &StressTestInteropClient::MainLoop, client, metrics_service.CreateQpsGauge(buffer, &is_already_created))); diff --git a/test/cpp/qps/client.h b/test/cpp/qps/client.h index 5fb87b27825..a8d125ad281 100644 --- a/test/cpp/qps/client.h +++ b/test/cpp/qps/client.h @@ -36,6 +36,7 @@ #include #include +#include #include #include @@ -112,21 +113,39 @@ class ClientRequestCreator { } }; -class HistogramEntry GRPC_FINAL { +class HistogramEntry final { public: - HistogramEntry() : used_(false) {} - bool used() const { return used_; } + HistogramEntry() : value_used_(false), status_used_(false) {} + bool value_used() const { return value_used_; } double value() const { return value_; } void set_value(double v) { - used_ = true; + value_used_ = true; value_ = v; } + bool status_used() const { return status_used_; } + int status() const { return status_; } + void set_status(int status) { + status_used_ = true; + status_ = status; + } private: - bool used_; + bool value_used_; double value_; + bool status_used_; + int status_; }; +typedef std::unordered_map StatusHistogram; + +inline void MergeStatusHistogram(const StatusHistogram& from, + StatusHistogram* to) { + for (StatusHistogram::const_iterator it = from.begin(); it != from.end(); + ++it) { + (*to)[it->first] += it->second; + } +} + class Client { public: Client() @@ -139,6 +158,7 @@ class Client { ClientStats Mark(bool reset) { Histogram latencies; + StatusHistogram statuses; UsageTimer::Result timer_result; MaybeStartRequests(); @@ -146,27 +166,36 @@ class Client { // avoid std::vector for old compilers that expect a copy constructor if (reset) { Histogram* to_merge = new Histogram[threads_.size()]; + StatusHistogram* to_merge_status = new StatusHistogram[threads_.size()]; + for (size_t i = 0; i < threads_.size(); i++) { - threads_[i]->BeginSwap(&to_merge[i]); + threads_[i]->BeginSwap(&to_merge[i], &to_merge_status[i]); } std::unique_ptr timer(new UsageTimer); timer_.swap(timer); for (size_t i = 0; i < threads_.size(); i++) { - threads_[i]->EndSwap(); latencies.Merge(to_merge[i]); + MergeStatusHistogram(to_merge_status[i], &statuses); } delete[] to_merge; + delete[] to_merge_status; timer_result = timer->Mark(); } else { // merge snapshots of each thread histogram for (size_t i = 0; i < threads_.size(); i++) { - threads_[i]->MergeStatsInto(&latencies); + threads_[i]->MergeStatsInto(&latencies, &statuses); } timer_result = timer_->Mark(); } ClientStats stats; latencies.FillProto(stats.mutable_latencies()); + for (StatusHistogram::const_iterator it = statuses.begin(); + it != statuses.end(); ++it) { + RequestResultCount* rrc = stats.add_request_results(); + rrc->set_status_code(it->first); + rrc->set_count(it->second); + } stats.set_time_elapsed(timer_result.wall); stats.set_time_system(timer_result.system); stats.set_time_user(timer_result.user); @@ -258,16 +287,16 @@ class Client { ~Thread() { impl_.join(); } - void BeginSwap(Histogram* n) { + void BeginSwap(Histogram* n, StatusHistogram* s) { std::lock_guard g(mu_); n->Swap(&histogram_); + s->swap(statuses_); } - void EndSwap() {} - - void MergeStatsInto(Histogram* hist) { + void MergeStatsInto(Histogram* hist, StatusHistogram* s) { std::unique_lock g(mu_); hist->Merge(histogram_); + MergeStatusHistogram(statuses_, s); } private: @@ -288,9 +317,12 @@ class Client { const bool thread_still_ok = client_->ThreadFunc(&entry, idx_); // lock, update histogram if needed and see if we're done std::lock_guard g(mu_); - if (entry.used()) { + if (entry.value_used()) { histogram_.Add(entry.value()); } + if (entry.status_used()) { + statuses_[entry.status()]++; + } if (!thread_still_ok) { gpr_log(GPR_ERROR, "Finishing client thread due to RPC error"); } @@ -304,6 +336,7 @@ class Client { std::mutex mu_; Histogram histogram_; + StatusHistogram statuses_; Client* client_; const size_t idx_; std::thread impl_; diff --git a/test/cpp/qps/client_async.cc b/test/cpp/qps/client_async.cc index 081114859ce..2ec6a5a23bc 100644 --- a/test/cpp/qps/client_async.cc +++ b/test/cpp/qps/client_async.cc @@ -83,7 +83,7 @@ class ClientRpcContextUnaryImpl : public ClientRpcContext { BenchmarkService::Stub*, grpc::ClientContext*, const RequestType&, CompletionQueue*)> start_req, - std::function on_done) + std::function on_done) : context_(), stub_(stub), cq_(nullptr), @@ -93,8 +93,8 @@ class ClientRpcContextUnaryImpl : public ClientRpcContext { callback_(on_done), next_issue_(next_issue), start_req_(start_req) {} - ~ClientRpcContextUnaryImpl() GRPC_OVERRIDE {} - void Start(CompletionQueue* cq) GRPC_OVERRIDE { + ~ClientRpcContextUnaryImpl() override {} + void Start(CompletionQueue* cq) override { cq_ = cq; if (!next_issue_) { // ready to issue RunNextState(true, nullptr); @@ -102,7 +102,7 @@ class ClientRpcContextUnaryImpl : public ClientRpcContext { alarm_.reset(new Alarm(cq_, next_issue_(), ClientRpcContext::tag(this))); } } - bool RunNextState(bool ok, HistogramEntry* entry) GRPC_OVERRIDE { + bool RunNextState(bool ok, HistogramEntry* entry) override { switch (next_state_) { case State::READY: start_ = UsageTimer::Now(); @@ -113,7 +113,7 @@ class ClientRpcContextUnaryImpl : public ClientRpcContext { return true; case State::RESP_DONE: entry->set_value((UsageTimer::Now() - start_) * 1e9); - callback_(status_, &response_); + callback_(status_, &response_, entry); next_state_ = State::INVALID; return false; default: @@ -121,7 +121,7 @@ class ClientRpcContextUnaryImpl : public ClientRpcContext { return false; } } - ClientRpcContext* StartNewClone() GRPC_OVERRIDE { + ClientRpcContext* StartNewClone() override { return new ClientRpcContextUnaryImpl(stub_, req_, next_issue_, start_req_, callback_); } @@ -135,7 +135,7 @@ class ClientRpcContextUnaryImpl : public ClientRpcContext { ResponseType response_; enum State { INVALID, READY, RESP_DONE }; State next_state_; - std::function callback_; + std::function callback_; std::function next_issue_; std::function>( BenchmarkService::Stub*, grpc::ClientContext*, const RequestType&, @@ -217,7 +217,7 @@ class AsyncClient : public ClientImpl { } return num_threads; } - void DestroyMultithreading() GRPC_OVERRIDE GRPC_FINAL { + void DestroyMultithreading() override final { for (auto ss = shutdown_state_.begin(); ss != shutdown_state_.end(); ++ss) { std::lock_guard lock((*ss)->mutex); (*ss)->shutdown = true; @@ -228,8 +228,7 @@ class AsyncClient : public ClientImpl { this->EndThreads(); // this needed for resolution } - bool ThreadFunc(HistogramEntry* entry, - size_t thread_idx) GRPC_OVERRIDE GRPC_FINAL { + bool ThreadFunc(HistogramEntry* entry, size_t thread_idx) override final { void* got_tag; bool ok; @@ -279,7 +278,7 @@ static std::unique_ptr BenchmarkStubCreator( return BenchmarkService::NewStub(ch); } -class AsyncUnaryClient GRPC_FINAL +class AsyncUnaryClient final : public AsyncClient { public: explicit AsyncUnaryClient(const ClientConfig& config) @@ -287,10 +286,13 @@ class AsyncUnaryClient GRPC_FINAL config, SetupCtx, BenchmarkStubCreator) { StartThreads(num_async_threads_); } - ~AsyncUnaryClient() GRPC_OVERRIDE {} + ~AsyncUnaryClient() override {} private: - static void CheckDone(grpc::Status s, SimpleResponse* response) {} + static void CheckDone(grpc::Status s, SimpleResponse* response, + HistogramEntry* entry) { + entry->set_status(s.error_code()); + } static std::unique_ptr> StartReq(BenchmarkService::Stub* stub, grpc::ClientContext* ctx, const SimpleRequest& request, CompletionQueue* cq) { @@ -326,13 +328,13 @@ class ClientRpcContextStreamingImpl : public ClientRpcContext { callback_(on_done), next_issue_(next_issue), start_req_(start_req) {} - ~ClientRpcContextStreamingImpl() GRPC_OVERRIDE {} - void Start(CompletionQueue* cq) GRPC_OVERRIDE { + ~ClientRpcContextStreamingImpl() override {} + void Start(CompletionQueue* cq) override { cq_ = cq; stream_ = start_req_(stub_, &context_, cq, ClientRpcContext::tag(this)); next_state_ = State::STREAM_IDLE; } - bool RunNextState(bool ok, HistogramEntry* entry) GRPC_OVERRIDE { + bool RunNextState(bool ok, HistogramEntry* entry) override { while (true) { switch (next_state_) { case State::STREAM_IDLE: @@ -374,7 +376,7 @@ class ClientRpcContextStreamingImpl : public ClientRpcContext { } } } - ClientRpcContext* StartNewClone() GRPC_OVERRIDE { + ClientRpcContext* StartNewClone() override { return new ClientRpcContextStreamingImpl(stub_, req_, next_issue_, start_req_, callback_); } @@ -407,7 +409,7 @@ class ClientRpcContextStreamingImpl : public ClientRpcContext { stream_; }; -class AsyncStreamingClient GRPC_FINAL +class AsyncStreamingClient final : public AsyncClient { public: explicit AsyncStreamingClient(const ClientConfig& config) @@ -416,7 +418,7 @@ class AsyncStreamingClient GRPC_FINAL StartThreads(num_async_threads_); } - ~AsyncStreamingClient() GRPC_OVERRIDE {} + ~AsyncStreamingClient() override {} private: static void CheckDone(grpc::Status s, SimpleResponse* response) {} @@ -455,8 +457,8 @@ class ClientRpcContextGenericStreamingImpl : public ClientRpcContext { callback_(on_done), next_issue_(next_issue), start_req_(start_req) {} - ~ClientRpcContextGenericStreamingImpl() GRPC_OVERRIDE {} - void Start(CompletionQueue* cq) GRPC_OVERRIDE { + ~ClientRpcContextGenericStreamingImpl() override {} + void Start(CompletionQueue* cq) override { cq_ = cq; const grpc::string kMethodName( "/grpc.testing.BenchmarkService/StreamingCall"); @@ -464,7 +466,7 @@ class ClientRpcContextGenericStreamingImpl : public ClientRpcContext { ClientRpcContext::tag(this)); next_state_ = State::STREAM_IDLE; } - bool RunNextState(bool ok, HistogramEntry* entry) GRPC_OVERRIDE { + bool RunNextState(bool ok, HistogramEntry* entry) override { while (true) { switch (next_state_) { case State::STREAM_IDLE: @@ -506,7 +508,7 @@ class ClientRpcContextGenericStreamingImpl : public ClientRpcContext { } } } - ClientRpcContext* StartNewClone() GRPC_OVERRIDE { + ClientRpcContext* StartNewClone() override { return new ClientRpcContextGenericStreamingImpl(stub_, req_, next_issue_, start_req_, callback_); } @@ -543,7 +545,7 @@ static std::unique_ptr GenericStubCreator( return std::unique_ptr(new grpc::GenericStub(ch)); } -class GenericAsyncStreamingClient GRPC_FINAL +class GenericAsyncStreamingClient final : public AsyncClient { public: explicit GenericAsyncStreamingClient(const ClientConfig& config) @@ -552,7 +554,7 @@ class GenericAsyncStreamingClient GRPC_FINAL StartThreads(num_async_threads_); } - ~GenericAsyncStreamingClient() GRPC_OVERRIDE {} + ~GenericAsyncStreamingClient() override {} private: static void CheckDone(grpc::Status s, ByteBuffer* response) {} diff --git a/test/cpp/qps/client_sync.cc b/test/cpp/qps/client_sync.cc index 0ccf4e270b6..a88a24d89cc 100644 --- a/test/cpp/qps/client_sync.cc +++ b/test/cpp/qps/client_sync.cc @@ -108,10 +108,10 @@ class SynchronousClient std::vector responses_; private: - void DestroyMultithreading() GRPC_OVERRIDE GRPC_FINAL { EndThreads(); } + void DestroyMultithreading() override final { EndThreads(); } }; -class SynchronousUnaryClient GRPC_FINAL : public SynchronousClient { +class SynchronousUnaryClient final : public SynchronousClient { public: SynchronousUnaryClient(const ClientConfig& config) : SynchronousClient(config) { @@ -119,7 +119,7 @@ class SynchronousUnaryClient GRPC_FINAL : public SynchronousClient { } ~SynchronousUnaryClient() {} - bool ThreadFunc(HistogramEntry* entry, size_t thread_idx) GRPC_OVERRIDE { + bool ThreadFunc(HistogramEntry* entry, size_t thread_idx) override { if (!WaitToIssue(thread_idx)) { return true; } @@ -130,15 +130,12 @@ class SynchronousUnaryClient GRPC_FINAL : public SynchronousClient { grpc::Status s = stub->UnaryCall(&context, request_, &responses_[thread_idx]); entry->set_value((UsageTimer::Now() - start) * 1e9); - if (!s.ok()) { - gpr_log(GPR_ERROR, "RPC error: %d: %s", s.error_code(), - s.error_message().c_str()); - } - return s.ok(); + entry->set_status(s.error_code()); + return true; } }; -class SynchronousStreamingClient GRPC_FINAL : public SynchronousClient { +class SynchronousStreamingClient final : public SynchronousClient { public: SynchronousStreamingClient(const ClientConfig& config) : SynchronousClient(config) { @@ -168,7 +165,7 @@ class SynchronousStreamingClient GRPC_FINAL : public SynchronousClient { delete[] context_; } - bool ThreadFunc(HistogramEntry* entry, size_t thread_idx) GRPC_OVERRIDE { + bool ThreadFunc(HistogramEntry* entry, size_t thread_idx) override { if (!WaitToIssue(thread_idx)) { return true; } diff --git a/test/cpp/qps/driver.cc b/test/cpp/qps/driver.cc index 6c675e34830..a440341ccf4 100644 --- a/test/cpp/qps/driver.cc +++ b/test/cpp/qps/driver.cc @@ -132,7 +132,8 @@ static void postprocess_scenario_result(ScenarioResult* result) { Histogram histogram; histogram.MergeProto(result->latencies()); - auto qps = histogram.Count() / average(result->client_stats(), WallTime); + auto time_estimate = average(result->client_stats(), WallTime); + auto qps = histogram.Count() / time_estimate; auto qps_per_server_core = qps / sum(result->server_cores(), Cores); result->mutable_summary()->set_qps(qps); @@ -157,6 +158,23 @@ static void postprocess_scenario_result(ScenarioResult* result) { result->mutable_summary()->set_server_user_time(server_user_time); result->mutable_summary()->set_client_system_time(client_system_time); result->mutable_summary()->set_client_user_time(client_user_time); + + if (result->request_results_size() > 0) { + int64_t successes = 0; + int64_t failures = 0; + for (int i = 0; i < result->request_results_size(); i++) { + RequestResultCount rrc = result->request_results(i); + if (rrc.status_code() == 0) { + successes += rrc.count(); + } else { + failures += rrc.count(); + } + } + result->mutable_summary()->set_successful_requests_per_second( + successes / time_estimate); + result->mutable_summary()->set_failed_requests_per_second(failures / + time_estimate); + } } // Namespace for classes and functions used only in RunScenario @@ -444,6 +462,7 @@ std::unique_ptr RunScenario( // Finish a run std::unique_ptr result(new ScenarioResult); Histogram merged_latencies; + std::unordered_map merged_statuses; gpr_log(GPR_INFO, "Finishing clients"); for (size_t i = 0; i < num_clients; i++) { @@ -462,6 +481,10 @@ std::unique_ptr RunScenario( gpr_log(GPR_INFO, "Received final status from client %zu", i); const auto& stats = client_status.stats(); merged_latencies.MergeProto(stats.latencies()); + for (int i = 0; i < stats.request_results_size(); i++) { + merged_statuses[stats.request_results(i).status_code()] += + stats.request_results(i).count(); + } result->add_client_stats()->CopyFrom(stats); // That final status should be the last message on the client stream GPR_ASSERT(!client->stream->Read(&client_status)); @@ -481,6 +504,12 @@ std::unique_ptr RunScenario( delete[] clients; merged_latencies.FillProto(result->mutable_latencies()); + for (std::unordered_map::iterator it = merged_statuses.begin(); + it != merged_statuses.end(); ++it) { + RequestResultCount* rrc = result->add_request_results(); + rrc->set_status_code(it->first); + rrc->set_count(it->second); + } gpr_log(GPR_INFO, "Finishing servers"); for (size_t i = 0; i < num_servers; i++) { diff --git a/test/cpp/qps/interarrival.h b/test/cpp/qps/interarrival.h index 0980d5e8baa..4bef06f566e 100644 --- a/test/cpp/qps/interarrival.h +++ b/test/cpp/qps/interarrival.h @@ -69,11 +69,11 @@ inline RandomDistInterface::~RandomDistInterface() {} // independent identical stationary sources. For more information, // see http://en.wikipedia.org/wiki/Exponential_distribution -class ExpDist GRPC_FINAL : public RandomDistInterface { +class ExpDist final : public RandomDistInterface { public: explicit ExpDist(double lambda) : lambda_recip_(1.0 / lambda) {} - ~ExpDist() GRPC_OVERRIDE {} - double transform(double uni) const GRPC_OVERRIDE { + ~ExpDist() override {} + double transform(double uni) const override { // Note: Use 1.0-uni above to avoid NaN if uni is 0 return lambda_recip_ * (-log(1.0 - uni)); } diff --git a/test/cpp/qps/qps_worker.cc b/test/cpp/qps/qps_worker.cc index d3e53fe14a6..d437920e686 100644 --- a/test/cpp/qps/qps_worker.cc +++ b/test/cpp/qps/qps_worker.cc @@ -100,7 +100,7 @@ static std::unique_ptr CreateServer(const ServerConfig& config) { abort(); } -class ScopedProfile GRPC_FINAL { +class ScopedProfile final { public: ScopedProfile(const char* filename, bool enable) : enable_(enable) { if (enable_) grpc_profiler_start(filename); @@ -113,14 +113,14 @@ class ScopedProfile GRPC_FINAL { const bool enable_; }; -class WorkerServiceImpl GRPC_FINAL : public WorkerService::Service { +class WorkerServiceImpl final : public WorkerService::Service { public: WorkerServiceImpl(int server_port, QpsWorker* worker) : acquired_(false), server_port_(server_port), worker_(worker) {} - Status RunClient(ServerContext* ctx, - ServerReaderWriter* stream) - GRPC_OVERRIDE { + Status RunClient( + ServerContext* ctx, + ServerReaderWriter* stream) override { InstanceGuard g(this); if (!g.Acquired()) { return Status(StatusCode::RESOURCE_EXHAUSTED, "Client worker busy"); @@ -132,9 +132,9 @@ class WorkerServiceImpl GRPC_FINAL : public WorkerService::Service { return ret; } - Status RunServer(ServerContext* ctx, - ServerReaderWriter* stream) - GRPC_OVERRIDE { + Status RunServer( + ServerContext* ctx, + ServerReaderWriter* stream) override { InstanceGuard g(this); if (!g.Acquired()) { return Status(StatusCode::RESOURCE_EXHAUSTED, "Server worker busy"); @@ -147,12 +147,12 @@ class WorkerServiceImpl GRPC_FINAL : public WorkerService::Service { } Status CoreCount(ServerContext* ctx, const CoreRequest*, - CoreResponse* resp) GRPC_OVERRIDE { + CoreResponse* resp) override { resp->set_cores(gpr_cpu_num_cores()); return Status::OK; } - Status QuitWorker(ServerContext* ctx, const Void*, Void*) GRPC_OVERRIDE { + Status QuitWorker(ServerContext* ctx, const Void*, Void*) override { InstanceGuard g(this); if (!g.Acquired()) { return Status(StatusCode::RESOURCE_EXHAUSTED, "Quitting worker busy"); diff --git a/test/cpp/qps/report.cc b/test/cpp/qps/report.cc index 2ec7d8676c2..41617e968a5 100644 --- a/test/cpp/qps/report.cc +++ b/test/cpp/qps/report.cc @@ -73,6 +73,12 @@ void CompositeReporter::ReportTimes(const ScenarioResult& result) { void GprLogReporter::ReportQPS(const ScenarioResult& result) { gpr_log(GPR_INFO, "QPS: %.1f", result.summary().qps()); + if (result.summary().failed_requests_per_second() > 0) { + gpr_log(GPR_INFO, "failed requests/second: %.1f", + result.summary().failed_requests_per_second()); + gpr_log(GPR_INFO, "successful requests/second: %.1f", + result.summary().successful_requests_per_second()); + } } void GprLogReporter::ReportQPSPerCore(const ScenarioResult& result) { diff --git a/test/cpp/qps/report.h b/test/cpp/qps/report.h index 39cf498e7b2..9dc259e95a7 100644 --- a/test/cpp/qps/report.h +++ b/test/cpp/qps/report.h @@ -82,10 +82,10 @@ class CompositeReporter : public Reporter { /** Adds a \a reporter to the composite. */ void add(std::unique_ptr reporter); - void ReportQPS(const ScenarioResult& result) GRPC_OVERRIDE; - void ReportQPSPerCore(const ScenarioResult& result) GRPC_OVERRIDE; - void ReportLatency(const ScenarioResult& result) GRPC_OVERRIDE; - void ReportTimes(const ScenarioResult& result) GRPC_OVERRIDE; + void ReportQPS(const ScenarioResult& result) override; + void ReportQPSPerCore(const ScenarioResult& result) override; + void ReportLatency(const ScenarioResult& result) override; + void ReportTimes(const ScenarioResult& result) override; private: std::vector > reporters_; @@ -97,10 +97,10 @@ class GprLogReporter : public Reporter { GprLogReporter(const string& name) : Reporter(name) {} private: - void ReportQPS(const ScenarioResult& result) GRPC_OVERRIDE; - void ReportQPSPerCore(const ScenarioResult& result) GRPC_OVERRIDE; - void ReportLatency(const ScenarioResult& result) GRPC_OVERRIDE; - void ReportTimes(const ScenarioResult& result) GRPC_OVERRIDE; + void ReportQPS(const ScenarioResult& result) override; + void ReportQPSPerCore(const ScenarioResult& result) override; + void ReportLatency(const ScenarioResult& result) override; + void ReportTimes(const ScenarioResult& result) override; }; /** Dumps the report to a JSON file. */ @@ -110,10 +110,10 @@ class JsonReporter : public Reporter { : Reporter(name), report_file_(report_file) {} private: - void ReportQPS(const ScenarioResult& result) GRPC_OVERRIDE; - void ReportQPSPerCore(const ScenarioResult& result) GRPC_OVERRIDE; - void ReportLatency(const ScenarioResult& result) GRPC_OVERRIDE; - void ReportTimes(const ScenarioResult& result) GRPC_OVERRIDE; + void ReportQPS(const ScenarioResult& result) override; + void ReportQPSPerCore(const ScenarioResult& result) override; + void ReportLatency(const ScenarioResult& result) override; + void ReportTimes(const ScenarioResult& result) override; const string report_file_; }; diff --git a/test/cpp/qps/server_async.cc b/test/cpp/qps/server_async.cc index 2fcc64819b3..f556fbdfa1b 100644 --- a/test/cpp/qps/server_async.cc +++ b/test/cpp/qps/server_async.cc @@ -38,6 +38,7 @@ #include #include +#include #include #include #include @@ -57,7 +58,7 @@ namespace testing { template -class AsyncQpsServerTest GRPC_FINAL : public grpc::testing::Server { +class AsyncQpsServerTest final : public grpc::testing::Server { public: AsyncQpsServerTest( const ServerConfig &config, @@ -95,6 +96,11 @@ class AsyncQpsServerTest GRPC_FINAL : public grpc::testing::Server { srv_cqs_.emplace_back(builder.AddCompletionQueue()); } + if (config.resource_quota_size() > 0) { + builder.SetResourceQuota(ResourceQuota("AsyncQpsServerTest") + .Resize(config.resource_quota_size())); + } + server_ = builder.BuildAndStart(); using namespace std::placeholders; @@ -190,7 +196,7 @@ class AsyncQpsServerTest GRPC_FINAL : public grpc::testing::Server { return reinterpret_cast(tag); } - class ServerRpcContextUnaryImpl GRPC_FINAL : public ServerRpcContext { + class ServerRpcContextUnaryImpl final : public ServerRpcContext { public: ServerRpcContextUnaryImpl( std::function*next_state_)(ok); - } - void Reset() GRPC_OVERRIDE { + ~ServerRpcContextUnaryImpl() override {} + bool RunNextState(bool ok) override { return (this->*next_state_)(ok); } + void Reset() override { srv_ctx_.reset(new ServerContextType); req_ = RequestType(); response_writer_ = @@ -251,7 +255,7 @@ class AsyncQpsServerTest GRPC_FINAL : public grpc::testing::Server { grpc::ServerAsyncResponseWriter response_writer_; }; - class ServerRpcContextStreamingImpl GRPC_FINAL : public ServerRpcContext { + class ServerRpcContextStreamingImpl final : public ServerRpcContext { public: ServerRpcContextStreamingImpl( std::function*next_state_)(ok); - } - void Reset() GRPC_OVERRIDE { + ~ServerRpcContextStreamingImpl() override {} + bool RunNextState(bool ok) override { return (this->*next_state_)(ok); } + void Reset() override { srv_ctx_.reset(new ServerContextType); req_ = RequestType(); stream_ = grpc::ServerAsyncReaderWriter( diff --git a/test/cpp/qps/server_sync.cc b/test/cpp/qps/server_sync.cc index 0caed0ab49e..8076a4a6b9a 100644 --- a/test/cpp/qps/server_sync.cc +++ b/test/cpp/qps/server_sync.cc @@ -31,6 +31,7 @@ * */ +#include #include #include #include @@ -47,10 +48,10 @@ namespace grpc { namespace testing { -class BenchmarkServiceImpl GRPC_FINAL : public BenchmarkService::Service { +class BenchmarkServiceImpl final : public BenchmarkService::Service { public: Status UnaryCall(ServerContext* context, const SimpleRequest* request, - SimpleResponse* response) GRPC_OVERRIDE { + SimpleResponse* response) override { if (request->response_size() > 0) { if (!Server::SetPayload(request->response_type(), request->response_size(), @@ -62,7 +63,7 @@ class BenchmarkServiceImpl GRPC_FINAL : public BenchmarkService::Service { } Status StreamingCall( ServerContext* context, - ServerReaderWriter* stream) GRPC_OVERRIDE { + ServerReaderWriter* stream) override { SimpleRequest request; while (stream->Read(&request)) { SimpleResponse response; @@ -79,7 +80,7 @@ class BenchmarkServiceImpl GRPC_FINAL : public BenchmarkService::Service { } }; -class SynchronousServer GRPC_FINAL : public grpc::testing::Server { +class SynchronousServer final : public grpc::testing::Server { public: explicit SynchronousServer(const ServerConfig& config) : Server(config) { ServerBuilder builder; @@ -91,6 +92,11 @@ class SynchronousServer GRPC_FINAL : public grpc::testing::Server { Server::CreateServerCredentials(config)); gpr_free(server_address); + if (config.resource_quota_size() > 0) { + builder.SetResourceQuota(ResourceQuota("AsyncQpsServerTest") + .Resize(config.resource_quota_size())); + } + builder.RegisterService(&service_); impl_ = builder.BuildAndStart(); diff --git a/test/cpp/thread_manager/thread_manager_test.cc b/test/cpp/thread_manager/thread_manager_test.cc new file mode 100644 index 00000000000..284761c53ae --- /dev/null +++ b/test/cpp/thread_manager/thread_manager_test.cc @@ -0,0 +1,135 @@ +/* + * + * Copyright 2016, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *is % allowed in string + */ + +#include +#include + +#include +#include +#include +#include + +#include "src/cpp/thread_manager/thread_manager.h" +#include "test/cpp/util/test_config.h" + +namespace grpc { +class ThreadManagerTest final : public grpc::ThreadManager { + public: + ThreadManagerTest() + : ThreadManager(kMinPollers, kMaxPollers), + num_do_work_(0), + num_poll_for_work_(0), + num_work_found_(0) {} + + grpc::ThreadManager::WorkStatus PollForWork(void **tag, bool *ok) override; + void DoWork(void *tag, bool ok) override; + void PerformTest(); + + private: + void SleepForMs(int sleep_time_ms); + + static const int kMinPollers = 2; + static const int kMaxPollers = 10; + + static const int kPollingTimeoutMsec = 10; + static const int kDoWorkDurationMsec = 1; + + // PollForWork will return SHUTDOWN after these many number of invocations + static const int kMaxNumPollForWork = 50; + + gpr_atm num_do_work_; // Number of calls to DoWork + gpr_atm num_poll_for_work_; // Number of calls to PollForWork + gpr_atm num_work_found_; // Number of times WORK_FOUND was returned +}; + +void ThreadManagerTest::SleepForMs(int duration_ms) { + gpr_timespec sleep_time = + gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), + gpr_time_from_millis(duration_ms, GPR_TIMESPAN)); + gpr_sleep_until(sleep_time); +} + +grpc::ThreadManager::WorkStatus ThreadManagerTest::PollForWork(void **tag, + bool *ok) { + int call_num = gpr_atm_no_barrier_fetch_add(&num_poll_for_work_, 1); + + if (call_num >= kMaxNumPollForWork) { + Shutdown(); + return SHUTDOWN; + } + + // Simulate "polling for work" by sleeping for sometime + SleepForMs(kPollingTimeoutMsec); + + *tag = nullptr; + *ok = true; + + // Return timeout roughly 1 out of every 3 calls + if (call_num % 3 == 0) { + return TIMEOUT; + } else { + gpr_atm_no_barrier_fetch_add(&num_work_found_, 1); + return WORK_FOUND; + } +} + +void ThreadManagerTest::DoWork(void *tag, bool ok) { + gpr_atm_no_barrier_fetch_add(&num_do_work_, 1); + SleepForMs(kDoWorkDurationMsec); // Simulate doing work by sleeping +} + +void ThreadManagerTest::PerformTest() { + // Initialize() starts the ThreadManager + Initialize(); + + // Wait for all the threads to gracefully terminate + Wait(); + + // The number of times DoWork() was called is equal to the number of times + // WORK_FOUND was returned + gpr_log(GPR_DEBUG, "DoWork() called %ld times", + gpr_atm_no_barrier_load(&num_do_work_)); + GPR_ASSERT(gpr_atm_no_barrier_load(&num_do_work_) == + gpr_atm_no_barrier_load(&num_work_found_)); +} +} // namespace grpc + +int main(int argc, char **argv) { + std::srand(std::time(NULL)); + + grpc::testing::InitTest(&argc, &argv, true); + grpc::ThreadManagerTest test_rpc_manager; + test_rpc_manager.PerformTest(); + + return 0; +} diff --git a/test/cpp/util/cli_call.h b/test/cpp/util/cli_call.h index 2fbc9618b64..65da86bd4e7 100644 --- a/test/cpp/util/cli_call.h +++ b/test/cpp/util/cli_call.h @@ -43,7 +43,7 @@ namespace grpc { namespace testing { -class CliCall GRPC_FINAL { +class CliCall final { public: typedef std::multimap OutgoingMetadataContainer; typedef std::multimap diff --git a/test/cpp/util/cli_call_test.cc b/test/cpp/util/cli_call_test.cc index 75e90f824f5..2e8501b2c3a 100644 --- a/test/cpp/util/cli_call_test.cc +++ b/test/cpp/util/cli_call_test.cc @@ -56,7 +56,7 @@ namespace testing { class TestServiceImpl : public ::grpc::testing::EchoTestService::Service { public: Status Echo(ServerContext* context, const EchoRequest* request, - EchoResponse* response) GRPC_OVERRIDE { + EchoResponse* response) override { if (!context->client_metadata().empty()) { for (std::multimap::const_iterator iter = context->client_metadata().begin(); @@ -75,7 +75,7 @@ class CliCallTest : public ::testing::Test { protected: CliCallTest() {} - void SetUp() GRPC_OVERRIDE { + void SetUp() override { int port = grpc_pick_unused_port_or_die(); server_address_ << "localhost:" << port; // Setup server @@ -86,7 +86,7 @@ class CliCallTest : public ::testing::Test { server_ = builder.BuildAndStart(); } - void TearDown() GRPC_OVERRIDE { server_->Shutdown(); } + void TearDown() override { server_->Shutdown(); } void ResetStub() { channel_ = diff --git a/test/cpp/util/grpc_tool_test.cc b/test/cpp/util/grpc_tool_test.cc index bad1579f11e..5ab054d04a1 100644 --- a/test/cpp/util/grpc_tool_test.cc +++ b/test/cpp/util/grpc_tool_test.cc @@ -93,13 +93,12 @@ DECLARE_bool(l); namespace { -class TestCliCredentials GRPC_FINAL : public grpc::testing::CliCredentials { +class TestCliCredentials final : public grpc::testing::CliCredentials { public: - std::shared_ptr GetCredentials() const - GRPC_OVERRIDE { + std::shared_ptr GetCredentials() const override { return InsecureChannelCredentials(); } - const grpc::string GetCredentialUsage() const GRPC_OVERRIDE { return ""; } + const grpc::string GetCredentialUsage() const override { return ""; } }; bool PrintStream(std::stringstream* ss, const grpc::string& output) { @@ -118,7 +117,7 @@ size_t ArraySize(T& a) { class TestServiceImpl : public ::grpc::testing::EchoTestService::Service { public: Status Echo(ServerContext* context, const EchoRequest* request, - EchoResponse* response) GRPC_OVERRIDE { + EchoResponse* response) override { if (!context->client_metadata().empty()) { for (std::multimap::const_iterator iter = context->client_metadata().begin(); diff --git a/test/cpp/util/metrics_server.h b/test/cpp/util/metrics_server.h index aa9bfed23d8..4f1e393a637 100644 --- a/test/cpp/util/metrics_server.h +++ b/test/cpp/util/metrics_server.h @@ -83,13 +83,13 @@ class QpsGauge { std::mutex num_queries_mu_; }; -class MetricsServiceImpl GRPC_FINAL : public MetricsService::Service { +class MetricsServiceImpl final : public MetricsService::Service { public: grpc::Status GetAllGauges(ServerContext* context, const EmptyMessage* request, - ServerWriter* writer) GRPC_OVERRIDE; + ServerWriter* writer) override; grpc::Status GetGauge(ServerContext* context, const GaugeRequest* request, - GaugeResponse* response) GRPC_OVERRIDE; + GaugeResponse* response) override; // Create a QpsGauge with name 'name'. is_present is set to true if the Gauge // is already present in the map. diff --git a/test/cpp/util/proto_file_parser.cc b/test/cpp/util/proto_file_parser.cc index 98dd3f14ad4..3e524227e5c 100644 --- a/test/cpp/util/proto_file_parser.cc +++ b/test/cpp/util/proto_file_parser.cc @@ -61,7 +61,7 @@ class ErrorPrinter : public protobuf::compiler::MultiFileErrorCollector { explicit ErrorPrinter(ProtoFileParser* parser) : parser_(parser) {} void AddError(const grpc::string& filename, int line, int column, - const grpc::string& message) GRPC_OVERRIDE { + const grpc::string& message) override { std::ostringstream oss; oss << "error " << filename << " " << line << " " << column << " " << message << "\n"; @@ -69,7 +69,7 @@ class ErrorPrinter : public protobuf::compiler::MultiFileErrorCollector { } void AddWarning(const grpc::string& filename, int line, int column, - const grpc::string& message) GRPC_OVERRIDE { + const grpc::string& message) override { std::cerr << "warning " << filename << " " << line << " " << column << " " << message << std::endl; } diff --git a/test/cpp/util/proto_reflection_descriptor_database.h b/test/cpp/util/proto_reflection_descriptor_database.h index dfa36044d9e..259277ebbe1 100644 --- a/test/cpp/util/proto_reflection_descriptor_database.h +++ b/test/cpp/util/proto_reflection_descriptor_database.h @@ -38,14 +38,9 @@ #include #include -// GRPC_NO_GENERATED_CODE indicates generated pb files should not be used -#ifdef GRPC_NO_GENERATED_CODE -#include "src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.h" -#else -#include -#endif // GRPC_NO_GENERATED_CODE #include #include +#include "src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.h" namespace grpc { @@ -67,14 +62,13 @@ class ProtoReflectionDescriptorDatabase : public protobuf::DescriptorDatabase { // Find a file by file name. Fills in in *output and returns true if found. // Otherwise, returns false, leaving the contents of *output undefined. bool FindFileByName(const string& filename, - protobuf::FileDescriptorProto* output) GRPC_OVERRIDE; + protobuf::FileDescriptorProto* output) override; // Find the file that declares the given fully-qualified symbol name. // If found, fills in *output and returns true, otherwise returns false // and leaves *output undefined. bool FindFileContainingSymbol(const string& symbol_name, - protobuf::FileDescriptorProto* output) - GRPC_OVERRIDE; + protobuf::FileDescriptorProto* output) override; // Find the file which defines an extension extending the given message type // with the given field number. If found, fills in *output and returns true, @@ -82,7 +76,7 @@ class ProtoReflectionDescriptorDatabase : public protobuf::DescriptorDatabase { // must be a fully-qualified type name. bool FindFileContainingExtension( const string& containing_type, int field_number, - protobuf::FileDescriptorProto* output) GRPC_OVERRIDE; + protobuf::FileDescriptorProto* output) override; // Finds the tag numbers used by all known extensions of // extendee_type, and appends them to output in an undefined @@ -92,7 +86,7 @@ class ProtoReflectionDescriptorDatabase : public protobuf::DescriptorDatabase { // numbers. Returns true if the search was successful, otherwise // returns false and leaves output unchanged. bool FindAllExtensionNumbers(const string& extendee_type, - std::vector* output) GRPC_OVERRIDE; + std::vector* output) override; // Provide a list of full names of registered services bool GetServices(std::vector* output); diff --git a/test/cpp/util/test_credentials_provider.cc b/test/cpp/util/test_credentials_provider.cc index ca15f29795a..0456b966671 100644 --- a/test/cpp/util/test_credentials_provider.cc +++ b/test/cpp/util/test_credentials_provider.cc @@ -34,9 +34,9 @@ #include "test/cpp/util/test_credentials_provider.h" +#include #include -#include #include #include @@ -64,14 +64,14 @@ class CredentialsProvider { class DefaultCredentialsProvider : public CredentialsProvider { public: - ~DefaultCredentialsProvider() GRPC_OVERRIDE {} + ~DefaultCredentialsProvider() override {} - void AddSecureType(const grpc::string& type, - std::unique_ptr type_provider) - GRPC_OVERRIDE { + void AddSecureType( + const grpc::string& type, + std::unique_ptr type_provider) override { // This clobbers any existing entry for type, except the defaults, which // can't be clobbered. - grpc::unique_lock lock(mu_); + std::unique_lock lock(mu_); auto it = std::find(added_secure_type_names_.begin(), added_secure_type_names_.end(), type); if (it == added_secure_type_names_.end()) { @@ -84,7 +84,7 @@ class DefaultCredentialsProvider : public CredentialsProvider { } std::shared_ptr GetChannelCredentials( - const grpc::string& type, ChannelArguments* args) GRPC_OVERRIDE { + const grpc::string& type, ChannelArguments* args) override { if (type == grpc::testing::kInsecureCredentialsType) { return InsecureChannelCredentials(); } else if (type == grpc::testing::kTlsCredentialsType) { @@ -92,7 +92,7 @@ class DefaultCredentialsProvider : public CredentialsProvider { args->SetSslTargetNameOverride("foo.test.google.fr"); return SslCredentials(ssl_opts); } else { - grpc::unique_lock lock(mu_); + std::unique_lock lock(mu_); auto it(std::find(added_secure_type_names_.begin(), added_secure_type_names_.end(), type)); if (it == added_secure_type_names_.end()) { @@ -105,7 +105,7 @@ class DefaultCredentialsProvider : public CredentialsProvider { } std::shared_ptr GetServerCredentials( - const grpc::string& type) GRPC_OVERRIDE { + const grpc::string& type) override { if (type == grpc::testing::kInsecureCredentialsType) { return InsecureServerCredentials(); } else if (type == grpc::testing::kTlsCredentialsType) { @@ -116,7 +116,7 @@ class DefaultCredentialsProvider : public CredentialsProvider { ssl_opts.pem_key_cert_pairs.push_back(pkcp); return SslServerCredentials(ssl_opts); } else { - grpc::unique_lock lock(mu_); + std::unique_lock lock(mu_); auto it(std::find(added_secure_type_names_.begin(), added_secure_type_names_.end(), type)); if (it == added_secure_type_names_.end()) { @@ -127,10 +127,10 @@ class DefaultCredentialsProvider : public CredentialsProvider { ->GetServerCredentials(); } } - std::vector GetSecureCredentialsTypeList() GRPC_OVERRIDE { + std::vector GetSecureCredentialsTypeList() override { std::vector types; types.push_back(grpc::testing::kTlsCredentialsType); - grpc::unique_lock lock(mu_); + std::unique_lock lock(mu_); for (auto it = added_secure_type_names_.begin(); it != added_secure_type_names_.end(); it++) { types.push_back(*it); @@ -139,7 +139,7 @@ class DefaultCredentialsProvider : public CredentialsProvider { } private: - grpc::mutex mu_; + std::mutex mu_; std::vector added_secure_type_names_; std::vector> added_secure_type_providers_; diff --git a/tools/codegen/extensions/gen_reflection_proto.sh b/tools/codegen/extensions/gen_reflection_proto.sh deleted file mode 100755 index ea7689f7e88..00000000000 --- a/tools/codegen/extensions/gen_reflection_proto.sh +++ /dev/null @@ -1,95 +0,0 @@ -#!/bin/bash - -# Copyright 2016, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -set -e -cd $(dirname $0)/../../.. - -PROTO_DIR="src/proto/grpc/reflection/v1alpha" -PROTO_FILE="reflection" -HEADER_DIR="include/grpc++/ext" -SRC_DIR="src/cpp/ext" -INCLUDE_DIR="grpc++/ext" -TMP_DIR="tmp" - -if hash grpc_cpp_plugin 2>/dev/null; then - GRPC_PLUGIN=$(which grpc_cpp_plugin) -else - if [ -f bins/opt/grpc_cpp_plugin ]; then - GRPC_PLUGIN="bins/opt/grpc_cpp_plugin" - else - echo "gRPC protoc plugin not found" - exit 1 - fi -fi - -if hash protoc 2>/dev/null; then - PROTOC=$(which protoc) -else - if [ -f bins/opt/protobuf/protoc ]; then - PROTOC="bins/opt/protobuf/protoc" - else - echo "protoc not found" - exit 1 - fi -fi - -TMP_DIR=${TMP_DIR}_${PROTO_FILE} - -[ ! -d $HEADER_DIR ] && mkdir -p $HEADER_DIR || : -[ ! -d $SRC_DIR ] && mkdir -p $SRC_DIR || : -[ ! -d $TMP_DIR ] && mkdir -p $TMP_DIR || : - -$PROTOC -I$PROTO_DIR --cpp_out=$TMP_DIR ${PROTO_DIR}/${PROTO_FILE}.proto -$PROTOC -I$PROTO_DIR --grpc_out=$TMP_DIR --plugin=protoc-gen-grpc=${GRPC_PLUGIN} ${PROTO_DIR}/${PROTO_FILE}.proto - -sed -i "s/\"${PROTO_FILE}.pb.h\"/<${INCLUDE_DIR/\//\\\/}\/${PROTO_FILE}.pb.h>/g" ${TMP_DIR}/${PROTO_FILE}.pb.cc -sed -i "s/\"${PROTO_FILE}.pb.h\"/<${INCLUDE_DIR/\//\\\/}\/${PROTO_FILE}.pb.h>/g" ${TMP_DIR}/${PROTO_FILE}.grpc.pb.h -sed -i "s/\"${PROTO_FILE}.pb.h\"/<${INCLUDE_DIR/\//\\\/}\/${PROTO_FILE}.pb.h>/g" ${TMP_DIR}/${PROTO_FILE}.grpc.pb.cc -sed -i "s/\"${PROTO_FILE}.grpc.pb.h\"/<${INCLUDE_DIR/\//\\\/}\/${PROTO_FILE}.grpc.pb.h>/g" ${TMP_DIR}/${PROTO_FILE}.grpc.pb.cc - -sed -i "1s/.*/\/\/ Generated by tools\/codegen\/extensions\/gen_reflection_proto.sh/g" ${TMP_DIR}/*.pb.h -sed -i "1s/.*/\/\/ Generated by tools\/codegen\/extensions\/gen_reflection_proto.sh/g" ${TMP_DIR}/*.pb.cc - -/bin/cp LICENSE ${TMP_DIR}/TMP_LICENSE -sed -i -e "s/./ &/" -e "s/.*/ \*&/" ${TMP_DIR}/TMP_LICENSE -sed -i -r "\$a\ *\n *\/\n\n" ${TMP_DIR}/TMP_LICENSE - -sed -i -e "1s/^/ *\n/" -e "1s/^/\/*\n/" ${TMP_DIR}/*.pb.h -sed -i -e "1s/^/ *\n/" -e "1s/^/\/*\n/" ${TMP_DIR}/*.pb.cc - -sed -i "2r ${TMP_DIR}/TMP_LICENSE" ${TMP_DIR}/*.pb.h -sed -i "2r ${TMP_DIR}/TMP_LICENSE" ${TMP_DIR}/*.pb.cc - -/bin/mv ${TMP_DIR}/${PROTO_FILE}.pb.h ${HEADER_DIR} -/bin/mv ${TMP_DIR}/${PROTO_FILE}.grpc.pb.h ${HEADER_DIR} -/bin/mv ${TMP_DIR}/${PROTO_FILE}.pb.cc ${SRC_DIR} -/bin/mv ${TMP_DIR}/${PROTO_FILE}.grpc.pb.cc ${SRC_DIR} -/bin/rm -r $TMP_DIR diff --git a/tools/dockerfile/test/cxx_ubuntu1604_x64/Dockerfile b/tools/dockerfile/test/cxx_ubuntu1604_x64/Dockerfile index 2d282276d31..b4847124cfc 100644 --- a/tools/dockerfile/test/cxx_ubuntu1604_x64/Dockerfile +++ b/tools/dockerfile/test/cxx_ubuntu1604_x64/Dockerfile @@ -97,7 +97,7 @@ RUN mkdir /var/local/jenkins # The clang-3.6 symlink for the default clang version was added # to Ubuntu 16.04 recently, so make sure it's installed. # Also install clang3.7. -RUN apt-get update && apt-get -y install clang-3.6 clang-3.7 && apt-get clean +RUN apt-get update && apt-get -y install gcc-4.8 gcc-4.8-multilib g++-4.8 g++-4.8-multilib clang-3.6 clang-3.7 && apt-get clean # Define the default command. CMD ["bash"] diff --git a/tools/doxygen/Doxyfile.c++ b/tools/doxygen/Doxyfile.c++ index 4b0be37e096..ff3a0e381da 100644 --- a/tools/doxygen/Doxyfile.c++ +++ b/tools/doxygen/Doxyfile.c++ @@ -781,12 +781,7 @@ include/grpc++/impl/server_builder_option.h \ include/grpc++/impl/server_builder_plugin.h \ include/grpc++/impl/server_initializer.h \ include/grpc++/impl/service_type.h \ -include/grpc++/impl/sync.h \ -include/grpc++/impl/sync_cxx11.h \ -include/grpc++/impl/sync_no_cxx11.h \ -include/grpc++/impl/thd.h \ -include/grpc++/impl/thd_cxx11.h \ -include/grpc++/impl/thd_no_cxx11.h \ +include/grpc++/resource_quota.h \ include/grpc++/security/auth_context.h \ include/grpc++/security/auth_metadata_processor.h \ include/grpc++/security/credentials.h \ @@ -833,9 +828,6 @@ include/grpc++/impl/codegen/status_code_enum.h \ include/grpc++/impl/codegen/status_helper.h \ include/grpc++/impl/codegen/string_ref.h \ include/grpc++/impl/codegen/stub_options.h \ -include/grpc++/impl/codegen/sync.h \ -include/grpc++/impl/codegen/sync_cxx11.h \ -include/grpc++/impl/codegen/sync_no_cxx11.h \ include/grpc++/impl/codegen/sync_stream.h \ include/grpc++/impl/codegen/time.h \ include/grpc/impl/codegen/byte_buffer_reader.h \ diff --git a/tools/doxygen/Doxyfile.c++.internal b/tools/doxygen/Doxyfile.c++.internal index e266e154812..a55e9052529 100644 --- a/tools/doxygen/Doxyfile.c++.internal +++ b/tools/doxygen/Doxyfile.c++.internal @@ -781,12 +781,7 @@ include/grpc++/impl/server_builder_option.h \ include/grpc++/impl/server_builder_plugin.h \ include/grpc++/impl/server_initializer.h \ include/grpc++/impl/service_type.h \ -include/grpc++/impl/sync.h \ -include/grpc++/impl/sync_cxx11.h \ -include/grpc++/impl/sync_no_cxx11.h \ -include/grpc++/impl/thd.h \ -include/grpc++/impl/thd_cxx11.h \ -include/grpc++/impl/thd_no_cxx11.h \ +include/grpc++/resource_quota.h \ include/grpc++/security/auth_context.h \ include/grpc++/security/auth_metadata_processor.h \ include/grpc++/security/credentials.h \ @@ -833,9 +828,6 @@ include/grpc++/impl/codegen/status_code_enum.h \ include/grpc++/impl/codegen/status_helper.h \ include/grpc++/impl/codegen/string_ref.h \ include/grpc++/impl/codegen/stub_options.h \ -include/grpc++/impl/codegen/sync.h \ -include/grpc++/impl/codegen/sync_cxx11.h \ -include/grpc++/impl/codegen/sync_no_cxx11.h \ include/grpc++/impl/codegen/sync_stream.h \ include/grpc++/impl/codegen/time.h \ include/grpc/impl/codegen/byte_buffer_reader.h \ @@ -863,6 +855,7 @@ src/cpp/client/create_channel_internal.h \ src/cpp/common/channel_filter.h \ src/cpp/server/dynamic_thread_pool.h \ src/cpp/server/thread_pool_interface.h \ +src/cpp/thread_manager/thread_manager.h \ src/cpp/client/insecure_credentials.cc \ src/cpp/client/secure_credentials.cc \ src/cpp/common/auth_property_iterator.cc \ @@ -882,6 +875,7 @@ src/cpp/common/channel_arguments.cc \ src/cpp/common/channel_filter.cc \ src/cpp/common/completion_queue_cc.cc \ src/cpp/common/core_codegen.cc \ +src/cpp/common/resource_quota_cc.cc \ src/cpp/common/rpc_method.cc \ src/cpp/server/async_generic_service.cc \ src/cpp/server/create_default_thread_pool.cc \ @@ -891,6 +885,7 @@ src/cpp/server/server_cc.cc \ src/cpp/server/server_context.cc \ src/cpp/server/server_credentials.cc \ src/cpp/server/server_posix.cc \ +src/cpp/thread_manager/thread_manager.cc \ src/cpp/util/byte_buffer_cc.cc \ src/cpp/util/slice_cc.cc \ src/cpp/util/status.cc \ diff --git a/tools/doxygen/Doxyfile.core.internal b/tools/doxygen/Doxyfile.core.internal index 8db1a79be07..e83298766fd 100644 --- a/tools/doxygen/Doxyfile.core.internal +++ b/tools/doxygen/Doxyfile.core.internal @@ -828,6 +828,7 @@ src/core/lib/iomgr/pollset_uv.h \ src/core/lib/iomgr/pollset_windows.h \ src/core/lib/iomgr/port.h \ src/core/lib/iomgr/resolve_address.h \ +src/core/lib/iomgr/resource_quota.h \ src/core/lib/iomgr/sockaddr.h \ src/core/lib/iomgr/sockaddr_posix.h \ src/core/lib/iomgr/sockaddr_utils.h \ @@ -836,6 +837,7 @@ src/core/lib/iomgr/socket_utils.h \ src/core/lib/iomgr/socket_utils_posix.h \ src/core/lib/iomgr/socket_windows.h \ src/core/lib/iomgr/tcp_client.h \ +src/core/lib/iomgr/tcp_client_posix.h \ src/core/lib/iomgr/tcp_posix.h \ src/core/lib/iomgr/tcp_server.h \ src/core/lib/iomgr/tcp_uv.h \ @@ -1003,6 +1005,7 @@ 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_utils_common_posix.c \ src/core/lib/iomgr/socket_utils_linux.c \ diff --git a/tools/run_tests/artifact_targets.py b/tools/run_tests/artifact_targets.py index d36f963a7c6..65d34e17e1c 100644 --- a/tools/run_tests/artifact_targets.py +++ b/tools/run_tests/artifact_targets.py @@ -109,8 +109,8 @@ class PythonArtifact: # TODO(atash) get better platform-detection support in core so we don't # need to do this manually... environ['CFLAGS'] = '-DGPR_MANYLINUX1=1' - environ['BUILD_HEALTH_CHECKING'] = 'TRUE' - environ['BUILD_MANYLINUX_WHEEL'] = 'TRUE' + environ['GRPC_BUILD_GRPCIO_TOOLS_DEPENDENTS'] = 'TRUE' + environ['GRPC_BUILD_MANYLINUX_WHEEL'] = 'TRUE' return create_docker_jobspec(self.name, 'tools/dockerfile/grpc_artifact_python_manylinux_%s' % self.arch, 'tools/run_tests/build_artifact_python.sh', diff --git a/tools/run_tests/build_artifact_node.bat b/tools/run_tests/build_artifact_node.bat index c5bd726db7e..57d55ef19ec 100644 --- a/tools/run_tests/build_artifact_node.bat +++ b/tools/run_tests/build_artifact_node.bat @@ -52,4 +52,4 @@ if %errorlevel% neq 0 exit /b %errorlevel% goto :EOF :error -exit /b 1 \ No newline at end of file +exit /b 1 diff --git a/tools/run_tests/build_artifact_python.sh b/tools/run_tests/build_artifact_python.sh index 9fed7c5028a..2a1d41fd686 100755 --- a/tools/run_tests/build_artifact_python.sh +++ b/tools/run_tests/build_artifact_python.sh @@ -66,7 +66,7 @@ ${SETARCH_CMD} ${PYTHON} tools/distrib/python/grpcio_tools/setup.py sdist # Build gRPC tools package binary distribution ${SETARCH_CMD} ${PYTHON} tools/distrib/python/grpcio_tools/setup.py bdist_wheel -if [ "$BUILD_MANYLINUX_WHEEL" != "" ] +if [ "$GRPC_BUILD_MANYLINUX_WHEEL" != "" ] then for wheel in dist/*.whl; do ${AUDITWHEEL} repair $wheel -w "$ARTIFACT_DIR" @@ -82,16 +82,21 @@ fi # Wheels are not supported by setup_requires/dependency_links, so we # manually install the dependency. Note we should only do this if we # are in a docker image or in a virtualenv. -if [ "$BUILD_HEALTH_CHECKING" != "" ] +if [ "$GRPC_BUILD_GRPCIO_TOOLS_DEPENDENTS" != "" ] then ${PIP} install -rrequirements.txt ${PIP} install grpcio --no-index --find-links "file://$ARTIFACT_DIR/" ${PIP} install grpcio-tools --no-index --find-links "file://$ARTIFACT_DIR/" - # Build gRPC health check source distribution + # Build gRPC health-checking source distribution ${SETARCH_CMD} ${PYTHON} src/python/grpcio_health_checking/setup.py \ preprocess build_package_protos sdist cp -r src/python/grpcio_health_checking/dist/* "$ARTIFACT_DIR" + + # Build gRPC reflection source distribution + ${SETARCH_CMD} ${PYTHON} src/python/grpcio_reflection/setup.py \ + preprocess build_package_protos sdist + cp -r src/python/grpcio_reflection/dist/* "$ARTIFACT_DIR" fi cp -r dist/* "$ARTIFACT_DIR" diff --git a/tools/run_tests/build_python.sh b/tools/run_tests/build_python.sh index b786c479f36..fb884ad1668 100755 --- a/tools/run_tests/build_python.sh +++ b/tools/run_tests/build_python.sh @@ -39,6 +39,14 @@ cd $(dirname $0)/../.. PLATFORM=`uname -s` +function is_msys() { + if [ "${PLATFORM/MSYS}" != "$PLATFORM" ]; then + echo true + else + exit 1 + fi +} + function is_mingw() { if [ "${PLATFORM/MINGW}" != "$PLATFORM" ]; then echo true @@ -108,6 +116,12 @@ VENV=${2:-$(venv $PYTHON)} VENV_RELATIVE_PYTHON=${3:-$(venv_relative_python)} TOOLCHAIN=${4:-$(toolchain)} +if [ $(is_msys) ]; then + echo "MSYS doesn't directly provide the right compiler(s);" + echo "switch to a MinGW shell." + exit 1 +fi + ROOT=`pwd` export CFLAGS="-I$ROOT/include -std=gnu99 -fno-wrapv $CFLAGS" export GRPC_PYTHON_BUILD_WITH_CYTHON=1 @@ -166,9 +180,18 @@ pip_install_dir $ROOT/tools/distrib/python/grpcio_tools # TODO(atash) figure out namespace packages and grpcio-tools and auditwheel # etc... pip_install_dir $ROOT + +# Build/install health checking $VENV_PYTHON $ROOT/src/python/grpcio_health_checking/setup.py preprocess $VENV_PYTHON $ROOT/src/python/grpcio_health_checking/setup.py build_package_protos pip_install_dir $ROOT/src/python/grpcio_health_checking + +# Build/install reflection +$VENV_PYTHON $ROOT/src/python/grpcio_reflection/setup.py preprocess +$VENV_PYTHON $ROOT/src/python/grpcio_reflection/setup.py build_package_protos +pip_install_dir $ROOT/src/python/grpcio_reflection + +# Build/install tests $VENV_PYTHON $ROOT/src/python/grpcio_tests/setup.py preprocess $VENV_PYTHON $ROOT/src/python/grpcio_tests/setup.py build_package_protos pip_install_dir $ROOT/src/python/grpcio_tests diff --git a/tools/run_tests/performance/bq_upload_result.py b/tools/run_tests/performance/bq_upload_result.py index 2a99499843a..0ea23d22122 100755 --- a/tools/run_tests/performance/bq_upload_result.py +++ b/tools/run_tests/performance/bq_upload_result.py @@ -117,9 +117,13 @@ def _flatten_result_inplace(scenario_result): scenario_result['latencies'] = json.dumps(scenario_result['latencies']) for stats in scenario_result['clientStats']: stats['latencies'] = json.dumps(stats['latencies']) + stats.pop('requestResults', None) scenario_result['serverCores'] = json.dumps(scenario_result['serverCores']) scenario_result['clientSuccess'] = json.dumps(scenario_result['clientSuccess']) scenario_result['serverSuccess'] = json.dumps(scenario_result['serverSuccess']) + scenario_result['requestResults'] = json.dumps(scenario_result.get('requestResults', [])) + scenario_result['summary'].pop('successfulRequestsPerSecond', None) + scenario_result['summary'].pop('failedRequestsPerSecond', None) def _populate_metadata_inplace(scenario_result): diff --git a/tools/run_tests/performance/scenario_config.py b/tools/run_tests/performance/scenario_config.py index c1a23a93429..4e4c16642ba 100644 --- a/tools/run_tests/performance/scenario_config.py +++ b/tools/run_tests/performance/scenario_config.py @@ -114,7 +114,8 @@ def _ping_pong_scenario(name, rpc_type, warmup_seconds=WARMUP_SECONDS, categories=DEFAULT_CATEGORIES, channels=None, - outstanding=None): + outstanding=None, + resource_quota_size=None): """Creates a basic ping pong scenario.""" scenario = { 'name': name, @@ -141,6 +142,8 @@ def _ping_pong_scenario(name, rpc_type, 'warmup_seconds': warmup_seconds, 'benchmark_seconds': BENCHMARK_SECONDS } + if resource_quota_size: + scenario['server_config']['resource_quota_size'] = resource_quota_size if use_generic_payload: if server_type != 'ASYNC_GENERIC_SERVER': raise Exception('Use ASYNC_GENERIC_SERVER for generic payload.') @@ -229,6 +232,15 @@ class CXXLanguage: secure=secure, categories=smoketest_categories + [SCALABLE]) + yield _ping_pong_scenario( + 'cpp_protobuf_async_client_sync_server_streaming_qps_unconstrained_%s' % secstr, + rpc_type='STREAMING', + client_type='ASYNC_CLIENT', + server_type='SYNC_SERVER', + unconstrained_client='async', + secure=secure, + categories=smoketest_categories+[SCALABLE]) + for rpc_type in ['unary', 'streaming']: for synchronicity in ['sync', 'async']: yield _ping_pong_scenario( @@ -248,6 +260,16 @@ class CXXLanguage: secure=secure, categories=smoketest_categories+[SCALABLE]) + yield _ping_pong_scenario( + 'cpp_protobuf_%s_%s_qps_unconstrained_%s_500kib_resource_quota' % (synchronicity, rpc_type, secstr), + rpc_type=rpc_type.upper(), + client_type='%s_CLIENT' % synchronicity.upper(), + server_type='%s_SERVER' % synchronicity.upper(), + unconstrained_client=synchronicity, + secure=secure, + categories=smoketest_categories+[SCALABLE], + resource_quota_size=500*1024) + for channels in geometric_progression(1, 20000, math.sqrt(10)): for outstanding in geometric_progression(1, 200000, math.sqrt(10)): if synchronicity == 'sync' and outstanding > 1200: continue @@ -348,7 +370,8 @@ class NodeLanguage: self.safename = str(self) def worker_cmdline(self): - return ['tools/run_tests/performance/run_worker_node.sh'] + return ['tools/run_tests/performance/run_worker_node.sh', + '--benchmark_impl=grpc'] def worker_port_offset(self): return 200 @@ -651,11 +674,69 @@ class GoLanguage: def __str__(self): return 'go' +class NodeExpressLanguage: + + def __init__(self): + pass + self.safename = str(self) + + def worker_cmdline(self): + return ['tools/run_tests/performance/run_worker_node.sh', + '--benchmark_impl=express'] + + def worker_port_offset(self): + return 700 + + def scenarios(self): + # TODO(jtattermusch): make this scenario work + #yield _ping_pong_scenario( + # 'node_generic_async_streaming_ping_pong', rpc_type='STREAMING', + # client_type='ASYNC_CLIENT', server_type='ASYNC_GENERIC_SERVER', + # use_generic_payload=True) + + # TODO(jtattermusch): make this scenario work + #yield _ping_pong_scenario( + # 'node_protobuf_async_streaming_ping_pong', rpc_type='STREAMING', + # client_type='ASYNC_CLIENT', server_type='ASYNC_SERVER') + + yield _ping_pong_scenario( + 'node_protobuf_unary_ping_pong', rpc_type='UNARY', + client_type='ASYNC_CLIENT', server_type='ASYNC_SERVER', + categories=[SCALABLE, SMOKETEST]) + + yield _ping_pong_scenario( + 'node_protobuf_async_unary_qps_unconstrained', rpc_type='UNARY', + client_type='ASYNC_CLIENT', server_type='ASYNC_SERVER', + unconstrained_client='async', + categories=[SCALABLE, SMOKETEST]) + + # TODO(jtattermusch): make this scenario work + #yield _ping_pong_scenario( + # 'node_protobuf_async_streaming_qps_unconstrained', rpc_type='STREAMING', + # client_type='ASYNC_CLIENT', server_type='ASYNC_SERVER', + # unconstrained_client='async') + + # TODO(jtattermusch): make this scenario work + #yield _ping_pong_scenario( + # 'node_to_cpp_protobuf_async_unary_ping_pong', rpc_type='UNARY', + # client_type='ASYNC_CLIENT', server_type='ASYNC_SERVER', + # server_language='c++', server_core_limit=1, async_server_threads=1) + + # TODO(jtattermusch): make this scenario work + #yield _ping_pong_scenario( + # 'node_to_cpp_protobuf_async_streaming_ping_pong', rpc_type='STREAMING', + # client_type='ASYNC_CLIENT', server_type='ASYNC_SERVER', + # server_language='c++', server_core_limit=1, async_server_threads=1) + + def __str__(self): + return 'node_express' + LANGUAGES = { 'c++' : CXXLanguage(), 'csharp' : CSharpLanguage(), 'node' : NodeLanguage(), + 'node_express': NodeExpressLanguage(), 'ruby' : RubyLanguage(), 'java' : JavaLanguage(), 'python' : PythonLanguage(), diff --git a/tools/run_tests/performance/scenario_result_schema.json b/tools/run_tests/performance/scenario_result_schema.json index 6bec21df397..3285f212d77 100644 --- a/tools/run_tests/performance/scenario_result_schema.json +++ b/tools/run_tests/performance/scenario_result_schema.json @@ -208,5 +208,10 @@ "name": "serverSuccess", "type": "STRING", "mode": "NULLABLE" + }, + { + "name": "requestResults", + "type": "STRING", + "mode": "NULLABLE" } ] diff --git a/tools/run_tests/pre_build_node.bat b/tools/run_tests/pre_build_node.bat index a29456f9ed9..addb01a2a4d 100644 --- a/tools/run_tests/pre_build_node.bat +++ b/tools/run_tests/pre_build_node.bat @@ -29,6 +29,5 @@ set PATH=%PATH%;C:\Program Files\nodejs\;%APPDATA%\npm -@rem Expire cache after 1 week -call npm update --cache-min 604800 - +@rem Expire cache after 1 day +call npm update --cache-min 86400 diff --git a/tools/run_tests/pre_build_node.sh b/tools/run_tests/pre_build_node.sh index 4879e7ad9bd..e63be9da523 100755 --- a/tools/run_tests/pre_build_node.sh +++ b/tools/run_tests/pre_build_node.sh @@ -37,8 +37,8 @@ set -ex export GRPC_CONFIG=${CONFIG:-opt} -# Expire cache after 1 week -npm update --cache-min 604800 +# Expire cache after 1 day +npm update --cache-min 86400 npm install node-gyp-install ./node_modules/.bin/node-gyp-install diff --git a/tools/run_tests/report_utils.py b/tools/run_tests/report_utils.py index efe5dc999d1..3e18f365102 100644 --- a/tools/run_tests/report_utils.py +++ b/tools/run_tests/report_utils.py @@ -36,7 +36,7 @@ try: from mako.template import Template from mako import exceptions except (ImportError): - pass # Mako not installed but it is ok. + pass # Mako not installed but it is ok. import os import string import xml.etree.cElementTree as ET @@ -63,9 +63,9 @@ def render_junit_xml_report(resultset, xml_report, suite_package='grpc', root = ET.Element('testsuites') testsuite = ET.SubElement(root, 'testsuite', id='1', package=suite_package, name=suite_name) - for shortname, results in resultset.items(): + for shortname, results in resultset.iteritems(): for result in results: - xml_test = ET.SubElement(testsuite, 'testcase', name=shortname) + xml_test = ET.SubElement(testsuite, 'testcase', name=shortname) if result.elapsed_time: xml_test.set('time', str(result.elapsed_time)) ET.SubElement(xml_test, 'system-out').text = _filter_msg(result.message, @@ -79,7 +79,7 @@ def render_junit_xml_report(resultset, xml_report, suite_package='grpc', def render_interop_html_report( - client_langs, server_langs, test_cases, auth_test_cases, http2_cases, + client_langs, server_langs, test_cases, auth_test_cases, http2_cases, resultset, num_failures, cloud_to_prod, prod_servers, http2_interop): """Generate HTML report for interop tests.""" template_file = 'tools/run_tests/interop_html_report.template' @@ -99,7 +99,7 @@ def render_interop_html_report( sorted_server_langs = sorted(server_langs) sorted_prod_servers = sorted(prod_servers) - args = {'client_langs': sorted_client_langs, + args = {'client_langs': sorted_client_langs, 'server_langs': sorted_server_langs, 'test_cases': sorted_test_cases, 'auth_test_cases': sorted_auth_test_cases, @@ -110,9 +110,9 @@ def render_interop_html_report( 'prod_servers': sorted_prod_servers, 'http2_interop': http2_interop} - html_report_out_dir = 'reports' + html_report_out_dir = 'reports' if not os.path.exists(html_report_out_dir): - os.mkdir(html_report_out_dir) + os.mkdir(html_report_out_dir) html_file_path = os.path.join(html_report_out_dir, 'index.html') try: with open(html_file_path, 'w') as output_file: @@ -120,4 +120,3 @@ def render_interop_html_report( except: print(exceptions.text_error_template().render()) raise - diff --git a/tools/run_tests/run_interop_tests.py b/tools/run_tests/run_interop_tests.py index 0c6efda1f47..c73de6b7174 100755 --- a/tools/run_tests/run_interop_tests.py +++ b/tools/run_tests/run_interop_tests.py @@ -64,7 +64,9 @@ _SKIP_SERVER_COMPRESSION = ['server_compressed_unary', _SKIP_COMPRESSION = _SKIP_CLIENT_COMPRESSION + _SKIP_SERVER_COMPRESSION -_SKIP_ADVANCED_GO = ['custom_metadata', 'unimplemented_method'] +_SKIP_ADVANCED_GO = ['custom_metadata', + 'unimplemented_method', + 'unimplemented_service'] _SKIP_ADVANCED = _SKIP_ADVANCED_GO + ['status_code_and_message'] @@ -416,7 +418,8 @@ _TEST_CASES = ['large_unary', 'empty_unary', 'ping_pong', 'timeout_on_sleeping_server', 'custom_metadata', 'status_code_and_message', 'unimplemented_method', 'client_compressed_unary', 'server_compressed_unary', - 'client_compressed_streaming', 'server_compressed_streaming'] + 'client_compressed_streaming', 'server_compressed_streaming', + 'unimplemented_service'] _AUTH_TEST_CASES = ['compute_engine_creds', 'jwt_token_creds', 'oauth2_auth_token', 'per_rpc_creds'] diff --git a/tools/run_tests/run_performance_tests.py b/tools/run_tests/run_performance_tests.py index 099ab89ddff..7cb827ecea9 100755 --- a/tools/run_tests/run_performance_tests.py +++ b/tools/run_tests/run_performance_tests.py @@ -42,6 +42,7 @@ import os import performance.scenario_config as scenario_config import pipes import re +import report_utils import subprocess import sys import tempfile @@ -453,6 +454,7 @@ if not scenarios: total_scenario_failures = 0 qps_workers_killed = 0 +merged_resultset = {} for scenario in scenarios: if args.dry_run: print(scenario.name) @@ -460,14 +462,20 @@ for scenario in scenarios: try: for worker in scenario.workers: worker.start() - scenario_failures, _ = jobset.run([scenario.jobspec, - create_quit_jobspec(scenario.workers, remote_host=args.remote_driver_host)], - newline_on_success=True, maxjobs=1) + scenario_failures, resultset = jobset.run([scenario.jobspec, + create_quit_jobspec(scenario.workers, remote_host=args.remote_driver_host)], + newline_on_success=True, maxjobs=1) total_scenario_failures += scenario_failures + merged_resultset = dict(itertools.chain(merged_resultset.iteritems(), + resultset.iteritems())) finally: # Consider qps workers that need to be killed as failures qps_workers_killed += finish_qps_workers(scenario.workers) + +report_utils.render_junit_xml_report(merged_resultset, 'report.xml', + suite_name='benchmarks') + if total_scenario_failures > 0 or qps_workers_killed > 0: print ("%s scenarios failed and %s qps worker jobs killed" % (total_scenario_failures, qps_workers_killed)) sys.exit(1) diff --git a/tools/run_tests/run_tests.py b/tools/run_tests/run_tests.py index db261d98c29..05f819bd9bb 100755 --- a/tools/run_tests/run_tests.py +++ b/tools/run_tests/run_tests.py @@ -332,6 +332,8 @@ class CLanguage(object): return ('wheezy', self._gcc_make_options(version_suffix='-4.4')) elif compiler == 'gcc4.6': return ('wheezy', self._gcc_make_options(version_suffix='-4.6')) + elif compiler == 'gcc4.8': + return ('ubuntu1604', self._gcc_make_options(version_suffix='-4.8')) elif compiler == 'gcc5.3': return ('ubuntu1604', []) elif compiler == 'clang3.4': @@ -363,7 +365,8 @@ class NodeLanguage(object): self.config = config self.args = args _check_compiler(self.args.compiler, ['default', 'node0.12', - 'node4', 'node5', 'node6']) + 'node4', 'node5', 'node6', + 'node7']) if self.args.compiler == 'default': self.node_version = '4' else: @@ -842,6 +845,53 @@ class Sanity(object): def __str__(self): return 'sanity' +class NodeExpressLanguage(object): + """Dummy Node express test target to enable running express performance + benchmarks""" + + def __init__(self): + self.platform = platform_string() + + def configure(self, config, args): + self.config = config + self.args = args + _check_compiler(self.args.compiler, ['default', 'node0.12', + 'node4', 'node5', 'node6']) + if self.args.compiler == 'default': + self.node_version = '4' + else: + # Take off the word "node" + self.node_version = self.args.compiler[4:] + + def test_specs(self): + return [] + + def pre_build_steps(self): + if self.platform == 'windows': + return [['tools\\run_tests\\pre_build_node.bat']] + else: + return [['tools/run_tests/pre_build_node.sh', self.node_version]] + + def make_targets(self): + return [] + + def make_options(self): + return [] + + def build_steps(self): + return [] + + def post_tests_steps(self): + return [] + + def makefile_name(self): + return 'Makefile' + + def dockerfile_dir(self): + return 'tools/dockerfile/test/node_jessie_%s' % _docker_arch_suffix(self.args.arch) + + def __str__(self): + return 'node_express' # different configurations we can run under with open('tools/run_tests/configs.json') as f: @@ -852,6 +902,7 @@ _LANGUAGES = { 'c++': CLanguage('cxx', 'c++'), 'c': CLanguage('c', 'c'), 'node': NodeLanguage(), + 'node_express': NodeExpressLanguage(), 'php': PhpLanguage(), 'php7': Php7Language(), 'python': PythonLanguage(), @@ -1012,10 +1063,11 @@ argp.add_argument('--arch', help='Selects architecture to target. For some platforms "default" is the only supported choice.') argp.add_argument('--compiler', choices=['default', - 'gcc4.4', 'gcc4.6', 'gcc4.9', 'gcc5.3', + 'gcc4.4', 'gcc4.6', 'gcc4.8', 'gcc4.9', 'gcc5.3', 'clang3.4', 'clang3.5', 'clang3.6', 'clang3.7', 'vs2010', 'vs2013', 'vs2015', 'python2.7', 'python3.4', 'python3.5', 'python3.6', 'pypy', 'pypy3', + 'node0.12', 'node4', 'node5', 'node6', 'node7', 'coreclr'], default='default', help='Selects compiler to use. Allowed values depend on the platform and language.') diff --git a/tools/run_tests/run_tests_in_workspace.sh b/tools/run_tests/run_tests_in_workspace.sh index 98ef3566db1..9c6c5b76e06 100755 --- a/tools/run_tests/run_tests_in_workspace.sh +++ b/tools/run_tests/run_tests_in_workspace.sh @@ -35,11 +35,13 @@ set -ex cd $(dirname $0)/../.. +export repo_root=$(pwd) rm -rf "${WORKSPACE_NAME}" -# TODO(jtattermusch): clone --recursive fetches the submodules from github. -# Try avoiding that to save time and network capacity. -git clone --recursive . "${WORKSPACE_NAME}" +git clone . "${WORKSPACE_NAME}" +# clone gRPC submodules, use data from locally cloned submodules where possible +git submodule foreach 'cd "${repo_root}/${WORKSPACE_NAME}" \ + && git submodule update --init --reference ${repo_root}/${name} ${name}' echo "Running run_tests.py in workspace ${WORKSPACE_NAME}" python "${WORKSPACE_NAME}/tools/run_tests/run_tests.py" $@ diff --git a/tools/run_tests/run_tests_matrix.py b/tools/run_tests/run_tests_matrix.py index b65010ad8b4..41db67cdb58 100755 --- a/tools/run_tests/run_tests_matrix.py +++ b/tools/run_tests/run_tests_matrix.py @@ -46,16 +46,16 @@ os.chdir(_ROOT) _RUNTESTS_TIMEOUT = 4*60*60 # Number of jobs assigned to each run_tests.py instance -_INNER_JOBS = 2 +_DEFAULT_INNER_JOBS = 2 -def _docker_jobspec(name, runtests_args=[]): +def _docker_jobspec(name, runtests_args=[], inner_jobs=_DEFAULT_INNER_JOBS): """Run a single instance of run_tests.py in a docker container""" test_job = jobset.JobSpec( cmdline=['python', 'tools/run_tests/run_tests.py', '--use_docker', '-t', - '-j', str(_INNER_JOBS), + '-j', str(inner_jobs), '-x', 'report_%s.xml' % name, '--report_suite_name', '%s' % name] + runtests_args, shortname='run_tests_%s' % name, @@ -63,7 +63,7 @@ def _docker_jobspec(name, runtests_args=[]): return test_job -def _workspace_jobspec(name, runtests_args=[], workspace_name=None): +def _workspace_jobspec(name, runtests_args=[], workspace_name=None, inner_jobs=_DEFAULT_INNER_JOBS): """Run a single instance of run_tests.py in a separate workspace""" if not workspace_name: workspace_name = 'workspace_%s' % name @@ -71,7 +71,7 @@ def _workspace_jobspec(name, runtests_args=[], workspace_name=None): test_job = jobset.JobSpec( cmdline=['tools/run_tests/run_tests_in_workspace.sh', '-t', - '-j', str(_INNER_JOBS), + '-j', str(inner_jobs), '-x', '../report_%s.xml' % name, '--report_suite_name', '%s' % name] + runtests_args, environ=env, @@ -82,7 +82,8 @@ def _workspace_jobspec(name, runtests_args=[], workspace_name=None): def _generate_jobs(languages, configs, platforms, arch=None, compiler=None, - labels=[], extra_args=[]): + labels=[], extra_args=[], + inner_jobs=_DEFAULT_INNER_JOBS): result = [] for language in languages: for platform in platforms: @@ -97,68 +98,75 @@ def _generate_jobs(languages, configs, platforms, runtests_args += extra_args if platform == 'linux': - job = _docker_jobspec(name=name, runtests_args=runtests_args) + job = _docker_jobspec(name=name, runtests_args=runtests_args, inner_jobs=inner_jobs) else: - job = _workspace_jobspec(name=name, runtests_args=runtests_args) + job = _workspace_jobspec(name=name, runtests_args=runtests_args, inner_jobs=inner_jobs) job.labels = [platform, config, language] + labels result.append(job) return result -def _create_test_jobs(extra_args=[]): +def _create_test_jobs(extra_args=[], inner_jobs=_DEFAULT_INNER_JOBS): test_jobs = [] # supported on linux only test_jobs += _generate_jobs(languages=['sanity', 'php7'], configs=['dbg', 'opt'], platforms=['linux'], labels=['basictests'], - extra_args=extra_args) + extra_args=extra_args, + inner_jobs=inner_jobs) # supported on all platforms. test_jobs += _generate_jobs(languages=['c', 'csharp', 'node', 'python'], configs=['dbg', 'opt'], platforms=['linux', 'macos', 'windows'], labels=['basictests'], - extra_args=extra_args) + extra_args=extra_args, + inner_jobs=inner_jobs) # supported on linux and mac. test_jobs += _generate_jobs(languages=['c++', 'ruby', 'php'], configs=['dbg', 'opt'], platforms=['linux', 'macos'], labels=['basictests'], - extra_args=extra_args) + extra_args=extra_args, + inner_jobs=inner_jobs) # supported on mac only. test_jobs += _generate_jobs(languages=['objc'], configs=['dbg', 'opt'], platforms=['macos'], labels=['basictests'], - extra_args=extra_args) + extra_args=extra_args, + inner_jobs=inner_jobs) # sanitizers test_jobs += _generate_jobs(languages=['c'], configs=['msan', 'asan', 'tsan'], platforms=['linux'], labels=['sanitizers'], - extra_args=extra_args) + extra_args=extra_args, + inner_jobs=inner_jobs) test_jobs += _generate_jobs(languages=['c++'], configs=['asan', 'tsan'], platforms=['linux'], labels=['sanitizers'], - extra_args=extra_args) + extra_args=extra_args, + inner_jobs=inner_jobs) # libuv tests test_jobs += _generate_jobs(languages=['c'], configs=['dbg', 'opt'], platforms=['linux'], labels=['libuv'], - extra_args=extra_args + ['--iomgr_platform=uv']) + extra_args=extra_args + ['--iomgr_platform=uv'], + inner_jobs=inner_jobs) return test_jobs -def _create_portability_test_jobs(extra_args=[]): +def _create_portability_test_jobs(extra_args=[], inner_jobs=_DEFAULT_INNER_JOBS): test_jobs = [] # portability C x86 test_jobs += _generate_jobs(languages=['c'], @@ -167,18 +175,30 @@ def _create_portability_test_jobs(extra_args=[]): arch='x86', compiler='default', labels=['portability'], - extra_args=extra_args) + extra_args=extra_args, + inner_jobs=inner_jobs) # portability C and C++ on x64 for compiler in ['gcc4.4', 'gcc4.6', 'gcc5.3', 'clang3.5', 'clang3.6', 'clang3.7']: - test_jobs += _generate_jobs(languages=['c', 'c++'], + test_jobs += _generate_jobs(languages=['c'], configs=['dbg'], platforms=['linux'], arch='x64', compiler=compiler, labels=['portability'], - extra_args=extra_args) + extra_args=extra_args, + inner_jobs=inner_jobs) + for compiler in ['gcc4.8', 'gcc5.3', + 'clang3.5', 'clang3.6', 'clang3.7']: + test_jobs += _generate_jobs(languages=['c++'], + configs=['dbg'], + platforms=['linux'], + arch='x64', + compiler=compiler, + labels=['portability'], + extra_args=extra_args, + inner_jobs=inner_jobs) # portability C on Windows for arch in ['x86', 'x64']: @@ -189,7 +209,8 @@ def _create_portability_test_jobs(extra_args=[]): arch=arch, compiler=compiler, labels=['portability'], - extra_args=extra_args) + extra_args=extra_args, + inner_jobs=inner_jobs) test_jobs += _generate_jobs(languages=['python'], configs=['dbg'], @@ -197,7 +218,8 @@ def _create_portability_test_jobs(extra_args=[]): arch='default', compiler='python3.4', labels=['portability'], - extra_args=extra_args) + extra_args=extra_args, + inner_jobs=inner_jobs) test_jobs += _generate_jobs(languages=['csharp'], configs=['dbg'], @@ -205,7 +227,8 @@ def _create_portability_test_jobs(extra_args=[]): arch='default', compiler='coreclr', labels=['portability'], - extra_args=extra_args) + extra_args=extra_args, + inner_jobs=inner_jobs) return test_jobs @@ -220,7 +243,7 @@ def _allowed_labels(): argp = argparse.ArgumentParser(description='Run a matrix of run_tests.py tests.') argp.add_argument('-j', '--jobs', - default=multiprocessing.cpu_count()/_INNER_JOBS, + default=multiprocessing.cpu_count()/_DEFAULT_INNER_JOBS, type=int, help='Number of concurrent run_tests.py instances.') argp.add_argument('-f', '--filter', @@ -249,15 +272,21 @@ argp.add_argument('--base_branch', default='origin/master', type=str, help='Branch that pull request is requesting to merge into') +argp.add_argument('--inner_jobs', + default=_DEFAULT_INNER_JOBS, + type=int, + help='Number of jobs in each run_tests.py instance') args = argp.parse_args() + extra_args = [] if args.build_only: extra_args.append('--build_only') if args.force_default_poller: extra_args.append('--force_default_poller') -all_jobs = _create_test_jobs(extra_args=extra_args) + _create_portability_test_jobs(extra_args=extra_args) +all_jobs = _create_test_jobs(extra_args=extra_args, inner_jobs=args.inner_jobs) + \ + _create_portability_test_jobs(extra_args=extra_args, inner_jobs=args.inner_jobs) jobs = [] for job in all_jobs: diff --git a/tools/run_tests/sanity/sanity_tests.yaml b/tools/run_tests/sanity/sanity_tests.yaml index e699c5194df..c5945c602f4 100644 --- a/tools/run_tests/sanity/sanity_tests.yaml +++ b/tools/run_tests/sanity/sanity_tests.yaml @@ -11,4 +11,3 @@ - script: tools/distrib/check_nanopb_output.sh - script: tools/distrib/check_include_guards.py - script: tools/distrib/python/check_grpcio_tools.py -- script: tools/distrib/check_generated_pb_files.sh diff --git a/tools/run_tests/sources_and_headers.json b/tools/run_tests/sources_and_headers.json index d7d6911c0ed..71b8c722261 100644 --- a/tools/run_tests/sources_and_headers.json +++ b/tools/run_tests/sources_and_headers.json @@ -1721,6 +1721,23 @@ "third_party": false, "type": "target" }, + { + "deps": [ + "gpr", + "gpr_test_util", + "grpc", + "grpc_test_util" + ], + "headers": [], + "is_filegroup": false, + "language": "c", + "name": "resource_quota_test", + "src": [ + "test/core/iomgr/resource_quota_test.c" + ], + "third_party": false, + "type": "target" + }, { "deps": [ "gpr", @@ -2480,7 +2497,7 @@ "gpr", "grpc", "grpc++", - "grpc++_reflection", + "grpc++_proto_reflection_desc_db", "grpc++_test_config", "grpc_cli_libs" ], @@ -2599,8 +2616,9 @@ "grpc", "grpc++", "grpc++_codegen_proto", - "grpc++_config_proto", + "grpc++_proto_reflection_desc_db", "grpc++_reflection", + "grpc++_test_util", "grpc_cli_libs", "grpc_test_util" ], @@ -2608,16 +2626,13 @@ "src/proto/grpc/testing/echo.grpc.pb.h", "src/proto/grpc/testing/echo.pb.h", "src/proto/grpc/testing/echo_messages.grpc.pb.h", - "src/proto/grpc/testing/echo_messages.pb.h", - "test/cpp/util/string_ref_helper.h" + "src/proto/grpc/testing/echo_messages.pb.h" ], "is_filegroup": false, "language": "c++", "name": "grpc_tool_test", "src": [ - "test/cpp/util/grpc_tool_test.cc", - "test/cpp/util/string_ref_helper.cc", - "test/cpp/util/string_ref_helper.h" + "test/cpp/util/grpc_tool_test.cc" ], "third_party": false, "type": "target" @@ -2809,20 +2824,17 @@ "gpr_test_util", "grpc", "grpc++", + "grpc++_proto_reflection_desc_db", "grpc++_reflection", "grpc++_test_util", "grpc_test_util" ], - "headers": [ - "test/cpp/util/proto_reflection_descriptor_database.h" - ], + "headers": [], "is_filegroup": false, "language": "c++", "name": "proto_server_reflection_test", "src": [ - "test/cpp/end2end/proto_server_reflection_test.cc", - "test/cpp/util/proto_reflection_descriptor_database.cc", - "test/cpp/util/proto_reflection_descriptor_database.h" + "test/cpp/end2end/proto_server_reflection_test.cc" ], "third_party": false, "type": "target" @@ -2971,6 +2983,25 @@ "third_party": false, "type": "target" }, + { + "deps": [ + "gpr", + "gpr_test_util", + "grpc", + "grpc++", + "grpc++_test_util", + "grpc_test_util" + ], + "headers": [], + "is_filegroup": false, + "language": "c++", + "name": "round_robin_end2end_test", + "src": [ + "test/cpp/end2end/round_robin_end2end_test.cc" + ], + "third_party": false, + "type": "target" + }, { "deps": [ "gpr", @@ -3183,6 +3214,23 @@ "third_party": false, "type": "target" }, + { + "deps": [ + "gpr", + "grpc", + "grpc++", + "grpc++_test_config" + ], + "headers": [], + "is_filegroup": false, + "language": "c++", + "name": "thread_manager_test", + "src": [ + "test/cpp/thread_manager/thread_manager_test.cc" + ], + "third_party": false, + "type": "target" + }, { "deps": [ "gpr", @@ -5026,34 +5074,40 @@ { "deps": [ "grpc++", + "grpc++_config_proto", "grpc++_reflection_proto" ], "headers": [ - "include/grpc++/ext/proto_server_reflection_plugin.h", - "src/cpp/ext/proto_server_reflection.h" + "test/cpp/util/proto_reflection_descriptor_database.h" ], "is_filegroup": false, "language": "c++", - "name": "grpc++_reflection", + "name": "grpc++_proto_reflection_desc_db", "src": [ - "include/grpc++/ext/proto_server_reflection_plugin.h", - "src/cpp/ext/proto_server_reflection.cc", - "src/cpp/ext/proto_server_reflection.h", - "src/cpp/ext/proto_server_reflection_plugin.cc" + "test/cpp/util/proto_reflection_descriptor_database.cc", + "test/cpp/util/proto_reflection_descriptor_database.h" ], "third_party": false, "type": "lib" }, { - "deps": [], + "deps": [ + "grpc++", + "grpc++_reflection_proto" + ], "headers": [ - "src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.h", - "src/proto/grpc/reflection/v1alpha/reflection.pb.h" + "include/grpc++/ext/proto_server_reflection_plugin.h", + "src/cpp/ext/proto_server_reflection.h" ], "is_filegroup": false, "language": "c++", - "name": "grpc++_reflection_codegen", - "src": [], + "name": "grpc++_reflection", + "src": [ + "include/grpc++/ext/proto_server_reflection_plugin.h", + "src/cpp/ext/proto_server_reflection.cc", + "src/cpp/ext/proto_server_reflection.h", + "src/cpp/ext/proto_server_reflection_plugin.cc" + ], "third_party": false, "type": "lib" }, @@ -5156,7 +5210,9 @@ { "deps": [ "grpc++", - "grpc++_reflection" + "grpc++_config_proto", + "grpc++_proto_reflection_desc_db", + "grpc++_reflection_proto" ], "headers": [ "test/cpp/util/cli_call.h", @@ -5164,7 +5220,6 @@ "test/cpp/util/config_grpc_cli.h", "test/cpp/util/grpc_tool.h", "test/cpp/util/proto_file_parser.h", - "test/cpp/util/proto_reflection_descriptor_database.h", "test/cpp/util/service_describer.h" ], "is_filegroup": false, @@ -5180,8 +5235,6 @@ "test/cpp/util/grpc_tool.h", "test/cpp/util/proto_file_parser.cc", "test/cpp/util/proto_file_parser.h", - "test/cpp/util/proto_reflection_descriptor_database.cc", - "test/cpp/util/proto_reflection_descriptor_database.h", "test/cpp/util/service_describer.cc", "test/cpp/util/service_describer.h" ], @@ -6174,6 +6227,7 @@ "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", @@ -6239,6 +6293,7 @@ "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", @@ -6538,6 +6593,7 @@ "src/core/lib/iomgr/pollset_windows.h", "src/core/lib/iomgr/port.h", "src/core/lib/iomgr/resolve_address.h", + "src/core/lib/iomgr/resource_quota.h", "src/core/lib/iomgr/sockaddr.h", "src/core/lib/iomgr/sockaddr_posix.h", "src/core/lib/iomgr/sockaddr_utils.h", @@ -6546,6 +6602,7 @@ "src/core/lib/iomgr/socket_utils_posix.h", "src/core/lib/iomgr/socket_windows.h", "src/core/lib/iomgr/tcp_client.h", + "src/core/lib/iomgr/tcp_client_posix.h", "src/core/lib/iomgr/tcp_posix.h", "src/core/lib/iomgr/tcp_server.h", "src/core/lib/iomgr/tcp_uv.h", @@ -6686,6 +6743,8 @@ "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/resource_quota.h", "src/core/lib/iomgr/sockaddr.h", "src/core/lib/iomgr/sockaddr_posix.h", "src/core/lib/iomgr/sockaddr_utils.c", @@ -6702,6 +6761,7 @@ "src/core/lib/iomgr/socket_windows.h", "src/core/lib/iomgr/tcp_client.h", "src/core/lib/iomgr/tcp_client_posix.c", + "src/core/lib/iomgr/tcp_client_posix.h", "src/core/lib/iomgr/tcp_client_uv.c", "src/core/lib/iomgr/tcp_client_windows.c", "src/core/lib/iomgr/tcp_posix.c", @@ -7397,12 +7457,7 @@ "include/grpc++/impl/server_builder_plugin.h", "include/grpc++/impl/server_initializer.h", "include/grpc++/impl/service_type.h", - "include/grpc++/impl/sync.h", - "include/grpc++/impl/sync_cxx11.h", - "include/grpc++/impl/sync_no_cxx11.h", - "include/grpc++/impl/thd.h", - "include/grpc++/impl/thd_cxx11.h", - "include/grpc++/impl/thd_no_cxx11.h", + "include/grpc++/resource_quota.h", "include/grpc++/security/auth_context.h", "include/grpc++/security/auth_metadata_processor.h", "include/grpc++/security/credentials.h", @@ -7426,7 +7481,8 @@ "src/cpp/client/create_channel_internal.h", "src/cpp/common/channel_filter.h", "src/cpp/server/dynamic_thread_pool.h", - "src/cpp/server/thread_pool_interface.h" + "src/cpp/server/thread_pool_interface.h", + "src/cpp/thread_manager/thread_manager.h" ], "is_filegroup": true, "language": "c++", @@ -7453,12 +7509,7 @@ "include/grpc++/impl/server_builder_plugin.h", "include/grpc++/impl/server_initializer.h", "include/grpc++/impl/service_type.h", - "include/grpc++/impl/sync.h", - "include/grpc++/impl/sync_cxx11.h", - "include/grpc++/impl/sync_no_cxx11.h", - "include/grpc++/impl/thd.h", - "include/grpc++/impl/thd_cxx11.h", - "include/grpc++/impl/thd_no_cxx11.h", + "include/grpc++/resource_quota.h", "include/grpc++/security/auth_context.h", "include/grpc++/security/auth_metadata_processor.h", "include/grpc++/security/credentials.h", @@ -7492,6 +7543,7 @@ "src/cpp/common/channel_filter.h", "src/cpp/common/completion_queue_cc.cc", "src/cpp/common/core_codegen.cc", + "src/cpp/common/resource_quota_cc.cc", "src/cpp/common/rpc_method.cc", "src/cpp/server/async_generic_service.cc", "src/cpp/server/create_default_thread_pool.cc", @@ -7503,6 +7555,8 @@ "src/cpp/server/server_credentials.cc", "src/cpp/server/server_posix.cc", "src/cpp/server/thread_pool_interface.h", + "src/cpp/thread_manager/thread_manager.cc", + "src/cpp/thread_manager/thread_manager.h", "src/cpp/util/byte_buffer_cc.cc", "src/cpp/util/slice_cc.cc", "src/cpp/util/status.cc", @@ -7543,9 +7597,6 @@ "include/grpc++/impl/codegen/status_helper.h", "include/grpc++/impl/codegen/string_ref.h", "include/grpc++/impl/codegen/stub_options.h", - "include/grpc++/impl/codegen/sync.h", - "include/grpc++/impl/codegen/sync_cxx11.h", - "include/grpc++/impl/codegen/sync_no_cxx11.h", "include/grpc++/impl/codegen/sync_stream.h", "include/grpc++/impl/codegen/time.h" ], @@ -7579,9 +7630,6 @@ "include/grpc++/impl/codegen/status_helper.h", "include/grpc++/impl/codegen/string_ref.h", "include/grpc++/impl/codegen/stub_options.h", - "include/grpc++/impl/codegen/sync.h", - "include/grpc++/impl/codegen/sync_cxx11.h", - "include/grpc++/impl/codegen/sync_no_cxx11.h", "include/grpc++/impl/codegen/sync_stream.h", "include/grpc++/impl/codegen/time.h" ], @@ -7634,22 +7682,15 @@ "type": "filegroup" }, { - "deps": [ - "grpc++_codegen_proto" - ], + "deps": [], "headers": [ - "include/grpc++/ext/reflection.grpc.pb.h", - "include/grpc++/ext/reflection.pb.h" + "src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.h", + "src/proto/grpc/reflection/v1alpha/reflection.pb.h" ], "is_filegroup": true, "language": "c++", "name": "grpc++_reflection_proto", - "src": [ - "include/grpc++/ext/reflection.grpc.pb.h", - "include/grpc++/ext/reflection.pb.h", - "src/cpp/ext/reflection.grpc.pb.cc", - "src/cpp/ext/reflection.pb.cc" - ], + "src": [], "third_party": false, "type": "filegroup" }, diff --git a/tools/run_tests/tests.json b/tools/run_tests/tests.json index 5cb50cc999c..94f95e8ab84 100644 --- a/tools/run_tests/tests.json +++ b/tools/run_tests/tests.json @@ -1765,6 +1765,28 @@ "windows" ] }, + { + "args": [], + "ci_platforms": [ + "linux", + "mac", + "posix", + "windows" + ], + "cpu_cost": 30, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "gtest": false, + "language": "c", + "name": "resource_quota_test", + "platforms": [ + "linux", + "mac", + "posix", + "windows" + ] + }, { "args": [], "ci_platforms": [ @@ -2801,6 +2823,28 @@ "posix" ] }, + { + "args": [], + "ci_platforms": [ + "linux", + "mac", + "posix", + "windows" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "gtest": true, + "language": "c++", + "name": "round_robin_end2end_test", + "platforms": [ + "linux", + "mac", + "posix", + "windows" + ] + }, { "args": [], "ci_platforms": [ @@ -2971,6 +3015,28 @@ "posix" ] }, + { + "args": [], + "ci_platforms": [ + "linux", + "mac", + "posix", + "windows" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "gtest": false, + "language": "c++", + "name": "thread_manager_test", + "platforms": [ + "linux", + "mac", + "posix", + "windows" + ] + }, { "args": [], "ci_platforms": [ @@ -5112,7 +5178,7 @@ "cpu_cost": 1.0, "exclude_configs": [], "exclude_iomgrs": [], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_census_test", "platforms": [ @@ -5628,6 +5694,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "language": "c", + "name": "h2_census_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -6126,7 +6215,7 @@ "cpu_cost": 1.0, "exclude_configs": [], "exclude_iomgrs": [], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_compress_test", "platforms": [ @@ -6642,6 +6731,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "language": "c", + "name": "h2_compress_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -7140,7 +7252,7 @@ "cpu_cost": 1.0, "exclude_configs": [], "exclude_iomgrs": [], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_fake_resolver_test", "platforms": [ @@ -7656,6 +7768,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "language": "c", + "name": "h2_fake_resolver_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -8141,7 +8276,7 @@ "cpu_cost": 1.0, "exclude_configs": [], "exclude_iomgrs": [], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_fakesec_test", "platforms": [ @@ -8635,6 +8770,28 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "language": "c", + "name": "h2_fakesec_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -9546,6 +9703,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [ + "uv" + ], + "flaky": false, + "language": "c", + "name": "h2_fd_test", + "platforms": [ + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -10021,7 +10201,7 @@ "cpu_cost": 1.0, "exclude_configs": [], "exclude_iomgrs": [], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_full_test", "platforms": [ @@ -10537,6 +10717,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "language": "c", + "name": "h2_full_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -10984,7 +11187,7 @@ "exclude_iomgrs": [ "uv" ], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_full+pipe_test", "platforms": [ @@ -11409,6 +11612,25 @@ "linux" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "linux" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [ + "uv" + ], + "flaky": false, + "language": "c", + "name": "h2_full+pipe_test", + "platforms": [ + "linux" + ] + }, { "args": [ "server_finishes_request" @@ -11871,7 +12093,7 @@ "cpu_cost": 1.0, "exclude_configs": [], "exclude_iomgrs": [], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_full+trace_test", "platforms": [ @@ -12341,6 +12563,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "language": "c", + "name": "h2_full+trace_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -12850,7 +13095,7 @@ "exclude_iomgrs": [ "uv" ], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_http_proxy_test", "platforms": [ @@ -13390,7 +13635,7 @@ }, { "args": [ - "server_finishes_request" + "resource_quota_server" ], "ci_platforms": [ "windows", @@ -13414,7 +13659,7 @@ }, { "args": [ - "shutdown_finishes_calls" + "server_finishes_request" ], "ci_platforms": [ "windows", @@ -13438,7 +13683,7 @@ }, { "args": [ - "shutdown_finishes_tags" + "shutdown_finishes_calls" ], "ci_platforms": [ "windows", @@ -13462,7 +13707,31 @@ }, { "args": [ - "simple_cacheable_request" + "shutdown_finishes_tags" + ], + "ci_platforms": [ + "windows", + "linux", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [ + "uv" + ], + "flaky": false, + "language": "c", + "name": "h2_http_proxy_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, + { + "args": [ + "simple_cacheable_request" ], "ci_platforms": [ "windows", @@ -13895,7 +14164,7 @@ "cpu_cost": 1.0, "exclude_configs": [], "exclude_iomgrs": [], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_load_reporting_test", "platforms": [ @@ -14411,6 +14680,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "language": "c", + "name": "h2_load_reporting_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -14920,7 +15212,7 @@ "exclude_iomgrs": [ "uv" ], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_oauth2_test", "platforms": [ @@ -15458,6 +15750,30 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [ + "uv" + ], + "flaky": false, + "language": "c", + "name": "h2_oauth2_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -15928,7 +16244,7 @@ "exclude_iomgrs": [ "uv" ], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_proxy_test", "platforms": [ @@ -17330,6 +17646,30 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [ + "uv" + ], + "flaky": false, + "language": "c", + "name": "h2_sockpair_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -19715,7 +20055,7 @@ "cpu_cost": 1.0, "exclude_configs": [], "exclude_iomgrs": [], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_ssl_test", "platforms": [ @@ -20231,6 +20571,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "language": "c", + "name": "h2_ssl_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -20729,7 +21092,7 @@ "cpu_cost": 1.0, "exclude_configs": [], "exclude_iomgrs": [], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_ssl_cert_test", "platforms": [ @@ -21245,6 +21608,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "language": "c", + "name": "h2_ssl_cert_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -21706,7 +22092,7 @@ "exclude_iomgrs": [ "uv" ], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_ssl_proxy_test", "platforms": [ @@ -22631,7 +23017,7 @@ "exclude_iomgrs": [ "uv" ], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_uds_test", "platforms": [ @@ -23146,6 +23532,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [ + "uv" + ], + "flaky": false, + "language": "c", + "name": "h2_uds_test", + "platforms": [ + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -23621,7 +24030,7 @@ "cpu_cost": 1.0, "exclude_configs": [], "exclude_iomgrs": [], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_census_nosec_test", "platforms": [ @@ -24137,6 +24546,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "language": "c", + "name": "h2_census_nosec_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -24612,7 +25044,7 @@ "cpu_cost": 1.0, "exclude_configs": [], "exclude_iomgrs": [], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_compress_nosec_test", "platforms": [ @@ -25128,6 +25560,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "language": "c", + "name": "h2_compress_nosec_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -25603,7 +26058,7 @@ "cpu_cost": 1.0, "exclude_configs": [], "exclude_iomgrs": [], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_fake_resolver_nosec_test", "platforms": [ @@ -26119,6 +26574,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "language": "c", + "name": "h2_fake_resolver_nosec_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -27018,7 +27496,7 @@ }, { "args": [ - "server_finishes_request" + "resource_quota_server" ], "ci_platforms": [ "linux", @@ -27041,7 +27519,7 @@ }, { "args": [ - "shutdown_finishes_calls" + "server_finishes_request" ], "ci_platforms": [ "linux", @@ -27064,7 +27542,7 @@ }, { "args": [ - "shutdown_finishes_tags" + "shutdown_finishes_calls" ], "ci_platforms": [ "linux", @@ -27087,7 +27565,7 @@ }, { "args": [ - "simple_cacheable_request" + "shutdown_finishes_tags" ], "ci_platforms": [ "linux", @@ -27110,7 +27588,7 @@ }, { "args": [ - "simple_metadata" + "simple_cacheable_request" ], "ci_platforms": [ "linux", @@ -27133,7 +27611,7 @@ }, { "args": [ - "simple_request" + "simple_metadata" ], "ci_platforms": [ "linux", @@ -27156,7 +27634,30 @@ }, { "args": [ - "streaming_error_response" + "simple_request" + ], + "ci_platforms": [ + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [ + "uv" + ], + "flaky": false, + "language": "c", + "name": "h2_fd_nosec_test", + "platforms": [ + "linux", + "mac", + "posix" + ] + }, + { + "args": [ + "streaming_error_response" ], "ci_platforms": [ "linux", @@ -27468,7 +27969,7 @@ "cpu_cost": 1.0, "exclude_configs": [], "exclude_iomgrs": [], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_full_nosec_test", "platforms": [ @@ -27984,6 +28485,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "language": "c", + "name": "h2_full_nosec_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -28412,7 +28936,7 @@ "exclude_iomgrs": [ "uv" ], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_full+pipe_nosec_test", "platforms": [ @@ -28837,6 +29361,25 @@ "linux" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "linux" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [ + "uv" + ], + "flaky": false, + "language": "c", + "name": "h2_full+pipe_nosec_test", + "platforms": [ + "linux" + ] + }, { "args": [ "server_finishes_request" @@ -29276,7 +29819,7 @@ "cpu_cost": 1.0, "exclude_configs": [], "exclude_iomgrs": [], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_full+trace_nosec_test", "platforms": [ @@ -29746,6 +30289,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "language": "c", + "name": "h2_full+trace_nosec_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -30231,7 +30797,7 @@ "exclude_iomgrs": [ "uv" ], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_http_proxy_nosec_test", "platforms": [ @@ -30769,6 +31335,30 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [ + "uv" + ], + "flaky": false, + "language": "c", + "name": "h2_http_proxy_nosec_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -31253,7 +31843,7 @@ "cpu_cost": 1.0, "exclude_configs": [], "exclude_iomgrs": [], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_load_reporting_nosec_test", "platforms": [ @@ -31769,6 +32359,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [], + "flaky": false, + "language": "c", + "name": "h2_load_reporting_nosec_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -32206,7 +32819,7 @@ "exclude_iomgrs": [ "uv" ], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_proxy_nosec_test", "platforms": [ @@ -33584,6 +34197,30 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "windows", + "linux", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [ + "uv" + ], + "flaky": false, + "language": "c", + "name": "h2_sockpair_nosec_test", + "platforms": [ + "windows", + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -35872,7 +36509,7 @@ "exclude_iomgrs": [ "uv" ], - "flaky": false, + "flaky": true, "language": "c", "name": "h2_uds_nosec_test", "platforms": [ @@ -36387,6 +37024,29 @@ "posix" ] }, + { + "args": [ + "resource_quota_server" + ], + "ci_platforms": [ + "linux", + "mac", + "posix" + ], + "cpu_cost": 1.0, + "exclude_configs": [], + "exclude_iomgrs": [ + "uv" + ], + "flaky": false, + "language": "c", + "name": "h2_uds_nosec_test", + "platforms": [ + "linux", + "mac", + "posix" + ] + }, { "args": [ "server_finishes_request" @@ -36678,6 +37338,27 @@ "shortname": "json_run_localhost:cpp_protobuf_async_client_sync_server_unary_qps_unconstrained_secure", "timeout_seconds": 180 }, + { + "args": [ + "--scenarios_json", + "{\"scenarios\": [{\"name\": \"cpp_protobuf_async_client_sync_server_streaming_qps_unconstrained_secure\", \"warmup_seconds\": 0, \"benchmark_seconds\": 1, \"num_servers\": 1, \"server_config\": {\"async_server_threads\": 0, \"core_limit\": 0, \"security_params\": {\"use_test_ca\": true, \"server_host_override\": \"foo.test.google.fr\"}, \"server_type\": \"SYNC_SERVER\"}, \"client_config\": {\"client_type\": \"ASYNC_CLIENT\", \"security_params\": {\"use_test_ca\": true, \"server_host_override\": \"foo.test.google.fr\"}, \"payload_config\": {\"simple_params\": {\"resp_size\": 0, \"req_size\": 0}}, \"client_channels\": 64, \"async_client_threads\": 0, \"outstanding_rpcs_per_channel\": 100, \"rpc_type\": \"STREAMING\", \"load_params\": {\"closed_loop\": {}}, \"histogram_params\": {\"max_possible\": 60000000000.0, \"resolution\": 0.01}}, \"num_clients\": 0}]}" + ], + "boringssl": true, + "ci_platforms": [ + "linux" + ], + "cpu_cost": 8, + "defaults": "boringssl", + "exclude_configs": [], + "flaky": false, + "language": "c++", + "name": "json_run_localhost", + "platforms": [ + "linux" + ], + "shortname": "json_run_localhost:cpp_protobuf_async_client_sync_server_streaming_qps_unconstrained_secure", + "timeout_seconds": 180 + }, { "args": [ "--scenarios_json", @@ -36720,6 +37401,27 @@ "shortname": "json_run_localhost:cpp_protobuf_sync_unary_qps_unconstrained_secure", "timeout_seconds": 180 }, + { + "args": [ + "--scenarios_json", + "{\"scenarios\": [{\"name\": \"cpp_protobuf_sync_unary_qps_unconstrained_secure_500kib_resource_quota\", \"warmup_seconds\": 0, \"benchmark_seconds\": 1, \"num_servers\": 1, \"server_config\": {\"resource_quota_size\": 512000, \"async_server_threads\": 0, \"core_limit\": 0, \"security_params\": {\"use_test_ca\": true, \"server_host_override\": \"foo.test.google.fr\"}, \"server_type\": \"SYNC_SERVER\"}, \"client_config\": {\"client_type\": \"SYNC_CLIENT\", \"security_params\": {\"use_test_ca\": true, \"server_host_override\": \"foo.test.google.fr\"}, \"payload_config\": {\"simple_params\": {\"resp_size\": 0, \"req_size\": 0}}, \"client_channels\": 64, \"async_client_threads\": 0, \"outstanding_rpcs_per_channel\": 16, \"rpc_type\": \"UNARY\", \"load_params\": {\"closed_loop\": {}}, \"histogram_params\": {\"max_possible\": 60000000000.0, \"resolution\": 0.01}}, \"num_clients\": 0}]}" + ], + "boringssl": true, + "ci_platforms": [ + "linux" + ], + "cpu_cost": 8, + "defaults": "boringssl", + "exclude_configs": [], + "flaky": false, + "language": "c++", + "name": "json_run_localhost", + "platforms": [ + "linux" + ], + "shortname": "json_run_localhost:cpp_protobuf_sync_unary_qps_unconstrained_secure_500kib_resource_quota", + "timeout_seconds": 180 + }, { "args": [ "--scenarios_json", @@ -36762,6 +37464,27 @@ "shortname": "json_run_localhost:cpp_protobuf_async_unary_qps_unconstrained_secure", "timeout_seconds": 180 }, + { + "args": [ + "--scenarios_json", + "{\"scenarios\": [{\"name\": \"cpp_protobuf_async_unary_qps_unconstrained_secure_500kib_resource_quota\", \"warmup_seconds\": 0, \"benchmark_seconds\": 1, \"num_servers\": 1, \"server_config\": {\"resource_quota_size\": 512000, \"async_server_threads\": 0, \"core_limit\": 0, \"security_params\": {\"use_test_ca\": true, \"server_host_override\": \"foo.test.google.fr\"}, \"server_type\": \"ASYNC_SERVER\"}, \"client_config\": {\"client_type\": \"ASYNC_CLIENT\", \"security_params\": {\"use_test_ca\": true, \"server_host_override\": \"foo.test.google.fr\"}, \"payload_config\": {\"simple_params\": {\"resp_size\": 0, \"req_size\": 0}}, \"client_channels\": 64, \"async_client_threads\": 0, \"outstanding_rpcs_per_channel\": 100, \"rpc_type\": \"UNARY\", \"load_params\": {\"closed_loop\": {}}, \"histogram_params\": {\"max_possible\": 60000000000.0, \"resolution\": 0.01}}, \"num_clients\": 0}]}" + ], + "boringssl": true, + "ci_platforms": [ + "linux" + ], + "cpu_cost": 8, + "defaults": "boringssl", + "exclude_configs": [], + "flaky": false, + "language": "c++", + "name": "json_run_localhost", + "platforms": [ + "linux" + ], + "shortname": "json_run_localhost:cpp_protobuf_async_unary_qps_unconstrained_secure_500kib_resource_quota", + "timeout_seconds": 180 + }, { "args": [ "--scenarios_json", @@ -36804,6 +37527,27 @@ "shortname": "json_run_localhost:cpp_protobuf_sync_streaming_qps_unconstrained_secure", "timeout_seconds": 180 }, + { + "args": [ + "--scenarios_json", + "{\"scenarios\": [{\"name\": \"cpp_protobuf_sync_streaming_qps_unconstrained_secure_500kib_resource_quota\", \"warmup_seconds\": 0, \"benchmark_seconds\": 1, \"num_servers\": 1, \"server_config\": {\"resource_quota_size\": 512000, \"async_server_threads\": 0, \"core_limit\": 0, \"security_params\": {\"use_test_ca\": true, \"server_host_override\": \"foo.test.google.fr\"}, \"server_type\": \"SYNC_SERVER\"}, \"client_config\": {\"client_type\": \"SYNC_CLIENT\", \"security_params\": {\"use_test_ca\": true, \"server_host_override\": \"foo.test.google.fr\"}, \"payload_config\": {\"simple_params\": {\"resp_size\": 0, \"req_size\": 0}}, \"client_channels\": 64, \"async_client_threads\": 0, \"outstanding_rpcs_per_channel\": 16, \"rpc_type\": \"STREAMING\", \"load_params\": {\"closed_loop\": {}}, \"histogram_params\": {\"max_possible\": 60000000000.0, \"resolution\": 0.01}}, \"num_clients\": 0}]}" + ], + "boringssl": true, + "ci_platforms": [ + "linux" + ], + "cpu_cost": 8, + "defaults": "boringssl", + "exclude_configs": [], + "flaky": false, + "language": "c++", + "name": "json_run_localhost", + "platforms": [ + "linux" + ], + "shortname": "json_run_localhost:cpp_protobuf_sync_streaming_qps_unconstrained_secure_500kib_resource_quota", + "timeout_seconds": 180 + }, { "args": [ "--scenarios_json", @@ -36846,6 +37590,27 @@ "shortname": "json_run_localhost:cpp_protobuf_async_streaming_qps_unconstrained_secure", "timeout_seconds": 180 }, + { + "args": [ + "--scenarios_json", + "{\"scenarios\": [{\"name\": \"cpp_protobuf_async_streaming_qps_unconstrained_secure_500kib_resource_quota\", \"warmup_seconds\": 0, \"benchmark_seconds\": 1, \"num_servers\": 1, \"server_config\": {\"resource_quota_size\": 512000, \"async_server_threads\": 0, \"core_limit\": 0, \"security_params\": {\"use_test_ca\": true, \"server_host_override\": \"foo.test.google.fr\"}, \"server_type\": \"ASYNC_SERVER\"}, \"client_config\": {\"client_type\": \"ASYNC_CLIENT\", \"security_params\": {\"use_test_ca\": true, \"server_host_override\": \"foo.test.google.fr\"}, \"payload_config\": {\"simple_params\": {\"resp_size\": 0, \"req_size\": 0}}, \"client_channels\": 64, \"async_client_threads\": 0, \"outstanding_rpcs_per_channel\": 100, \"rpc_type\": \"STREAMING\", \"load_params\": {\"closed_loop\": {}}, \"histogram_params\": {\"max_possible\": 60000000000.0, \"resolution\": 0.01}}, \"num_clients\": 0}]}" + ], + "boringssl": true, + "ci_platforms": [ + "linux" + ], + "cpu_cost": 8, + "defaults": "boringssl", + "exclude_configs": [], + "flaky": false, + "language": "c++", + "name": "json_run_localhost", + "platforms": [ + "linux" + ], + "shortname": "json_run_localhost:cpp_protobuf_async_streaming_qps_unconstrained_secure_500kib_resource_quota", + "timeout_seconds": 180 + }, { "args": [ "--scenarios_json", @@ -36930,6 +37695,27 @@ "shortname": "json_run_localhost:cpp_protobuf_async_client_sync_server_unary_qps_unconstrained_insecure", "timeout_seconds": 180 }, + { + "args": [ + "--scenarios_json", + "{\"scenarios\": [{\"name\": \"cpp_protobuf_async_client_sync_server_streaming_qps_unconstrained_insecure\", \"warmup_seconds\": 0, \"benchmark_seconds\": 1, \"num_servers\": 1, \"server_config\": {\"async_server_threads\": 0, \"core_limit\": 0, \"security_params\": null, \"server_type\": \"SYNC_SERVER\"}, \"client_config\": {\"client_type\": \"ASYNC_CLIENT\", \"security_params\": null, \"payload_config\": {\"simple_params\": {\"resp_size\": 0, \"req_size\": 0}}, \"client_channels\": 64, \"async_client_threads\": 0, \"outstanding_rpcs_per_channel\": 100, \"rpc_type\": \"STREAMING\", \"load_params\": {\"closed_loop\": {}}, \"histogram_params\": {\"max_possible\": 60000000000.0, \"resolution\": 0.01}}, \"num_clients\": 0}]}" + ], + "boringssl": true, + "ci_platforms": [ + "linux" + ], + "cpu_cost": 8, + "defaults": "boringssl", + "exclude_configs": [], + "flaky": false, + "language": "c++", + "name": "json_run_localhost", + "platforms": [ + "linux" + ], + "shortname": "json_run_localhost:cpp_protobuf_async_client_sync_server_streaming_qps_unconstrained_insecure", + "timeout_seconds": 180 + }, { "args": [ "--scenarios_json", @@ -36972,6 +37758,27 @@ "shortname": "json_run_localhost:cpp_protobuf_sync_unary_qps_unconstrained_insecure", "timeout_seconds": 180 }, + { + "args": [ + "--scenarios_json", + "{\"scenarios\": [{\"name\": \"cpp_protobuf_sync_unary_qps_unconstrained_insecure_500kib_resource_quota\", \"warmup_seconds\": 0, \"benchmark_seconds\": 1, \"num_servers\": 1, \"server_config\": {\"resource_quota_size\": 512000, \"async_server_threads\": 0, \"core_limit\": 0, \"security_params\": null, \"server_type\": \"SYNC_SERVER\"}, \"client_config\": {\"client_type\": \"SYNC_CLIENT\", \"security_params\": null, \"payload_config\": {\"simple_params\": {\"resp_size\": 0, \"req_size\": 0}}, \"client_channels\": 64, \"async_client_threads\": 0, \"outstanding_rpcs_per_channel\": 16, \"rpc_type\": \"UNARY\", \"load_params\": {\"closed_loop\": {}}, \"histogram_params\": {\"max_possible\": 60000000000.0, \"resolution\": 0.01}}, \"num_clients\": 0}]}" + ], + "boringssl": true, + "ci_platforms": [ + "linux" + ], + "cpu_cost": 8, + "defaults": "boringssl", + "exclude_configs": [], + "flaky": false, + "language": "c++", + "name": "json_run_localhost", + "platforms": [ + "linux" + ], + "shortname": "json_run_localhost:cpp_protobuf_sync_unary_qps_unconstrained_insecure_500kib_resource_quota", + "timeout_seconds": 180 + }, { "args": [ "--scenarios_json", @@ -37014,6 +37821,27 @@ "shortname": "json_run_localhost:cpp_protobuf_async_unary_qps_unconstrained_insecure", "timeout_seconds": 180 }, + { + "args": [ + "--scenarios_json", + "{\"scenarios\": [{\"name\": \"cpp_protobuf_async_unary_qps_unconstrained_insecure_500kib_resource_quota\", \"warmup_seconds\": 0, \"benchmark_seconds\": 1, \"num_servers\": 1, \"server_config\": {\"resource_quota_size\": 512000, \"async_server_threads\": 0, \"core_limit\": 0, \"security_params\": null, \"server_type\": \"ASYNC_SERVER\"}, \"client_config\": {\"client_type\": \"ASYNC_CLIENT\", \"security_params\": null, \"payload_config\": {\"simple_params\": {\"resp_size\": 0, \"req_size\": 0}}, \"client_channels\": 64, \"async_client_threads\": 0, \"outstanding_rpcs_per_channel\": 100, \"rpc_type\": \"UNARY\", \"load_params\": {\"closed_loop\": {}}, \"histogram_params\": {\"max_possible\": 60000000000.0, \"resolution\": 0.01}}, \"num_clients\": 0}]}" + ], + "boringssl": true, + "ci_platforms": [ + "linux" + ], + "cpu_cost": 8, + "defaults": "boringssl", + "exclude_configs": [], + "flaky": false, + "language": "c++", + "name": "json_run_localhost", + "platforms": [ + "linux" + ], + "shortname": "json_run_localhost:cpp_protobuf_async_unary_qps_unconstrained_insecure_500kib_resource_quota", + "timeout_seconds": 180 + }, { "args": [ "--scenarios_json", @@ -37056,6 +37884,27 @@ "shortname": "json_run_localhost:cpp_protobuf_sync_streaming_qps_unconstrained_insecure", "timeout_seconds": 180 }, + { + "args": [ + "--scenarios_json", + "{\"scenarios\": [{\"name\": \"cpp_protobuf_sync_streaming_qps_unconstrained_insecure_500kib_resource_quota\", \"warmup_seconds\": 0, \"benchmark_seconds\": 1, \"num_servers\": 1, \"server_config\": {\"resource_quota_size\": 512000, \"async_server_threads\": 0, \"core_limit\": 0, \"security_params\": null, \"server_type\": \"SYNC_SERVER\"}, \"client_config\": {\"client_type\": \"SYNC_CLIENT\", \"security_params\": null, \"payload_config\": {\"simple_params\": {\"resp_size\": 0, \"req_size\": 0}}, \"client_channels\": 64, \"async_client_threads\": 0, \"outstanding_rpcs_per_channel\": 16, \"rpc_type\": \"STREAMING\", \"load_params\": {\"closed_loop\": {}}, \"histogram_params\": {\"max_possible\": 60000000000.0, \"resolution\": 0.01}}, \"num_clients\": 0}]}" + ], + "boringssl": true, + "ci_platforms": [ + "linux" + ], + "cpu_cost": 8, + "defaults": "boringssl", + "exclude_configs": [], + "flaky": false, + "language": "c++", + "name": "json_run_localhost", + "platforms": [ + "linux" + ], + "shortname": "json_run_localhost:cpp_protobuf_sync_streaming_qps_unconstrained_insecure_500kib_resource_quota", + "timeout_seconds": 180 + }, { "args": [ "--scenarios_json", @@ -37098,6 +37947,27 @@ "shortname": "json_run_localhost:cpp_protobuf_async_streaming_qps_unconstrained_insecure", "timeout_seconds": 180 }, + { + "args": [ + "--scenarios_json", + "{\"scenarios\": [{\"name\": \"cpp_protobuf_async_streaming_qps_unconstrained_insecure_500kib_resource_quota\", \"warmup_seconds\": 0, \"benchmark_seconds\": 1, \"num_servers\": 1, \"server_config\": {\"resource_quota_size\": 512000, \"async_server_threads\": 0, \"core_limit\": 0, \"security_params\": null, \"server_type\": \"ASYNC_SERVER\"}, \"client_config\": {\"client_type\": \"ASYNC_CLIENT\", \"security_params\": null, \"payload_config\": {\"simple_params\": {\"resp_size\": 0, \"req_size\": 0}}, \"client_channels\": 64, \"async_client_threads\": 0, \"outstanding_rpcs_per_channel\": 100, \"rpc_type\": \"STREAMING\", \"load_params\": {\"closed_loop\": {}}, \"histogram_params\": {\"max_possible\": 60000000000.0, \"resolution\": 0.01}}, \"num_clients\": 0}]}" + ], + "boringssl": true, + "ci_platforms": [ + "linux" + ], + "cpu_cost": 8, + "defaults": "boringssl", + "exclude_configs": [], + "flaky": false, + "language": "c++", + "name": "json_run_localhost", + "platforms": [ + "linux" + ], + "shortname": "json_run_localhost:cpp_protobuf_async_streaming_qps_unconstrained_insecure_500kib_resource_quota", + "timeout_seconds": 180 + }, { "args": [ "test/core/end2end/fuzzers/api_fuzzer_corpus/00.bin" @@ -80350,6 +81220,50 @@ ], "uses_polling": false }, + { + "args": [ + "test/core/end2end/fuzzers/client_fuzzer_corpus/server_hanging_response_1_header" + ], + "ci_platforms": [ + "linux" + ], + "cpu_cost": 0.1, + "exclude_configs": [ + "tsan" + ], + "exclude_iomgrs": [ + "uv" + ], + "flaky": false, + "language": "c", + "name": "client_fuzzer_one_entry", + "platforms": [ + "linux" + ], + "uses_polling": false + }, + { + "args": [ + "test/core/end2end/fuzzers/client_fuzzer_corpus/server_hanging_response_2_header2" + ], + "ci_platforms": [ + "linux" + ], + "cpu_cost": 0.1, + "exclude_configs": [ + "tsan" + ], + "exclude_iomgrs": [ + "uv" + ], + "flaky": false, + "language": "c", + "name": "client_fuzzer_one_entry", + "platforms": [ + "linux" + ], + "uses_polling": false + }, { "args": [ "test/core/end2end/fuzzers/client_fuzzer_corpus/settings_frame_1.bin" diff --git a/vsprojects/buildtests_c.sln b/vsprojects/buildtests_c.sln index 339b42f9d7c..b1918809bf0 100644 --- a/vsprojects/buildtests_c.sln +++ b/vsprojects/buildtests_c.sln @@ -1317,6 +1317,17 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "resolve_address_test", "vcx {B23D3D1A-9438-4EDA-BEB6-9A0A03D17792} = {B23D3D1A-9438-4EDA-BEB6-9A0A03D17792} EndProjectSection EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "resource_quota_test", "vcxproj\test\resource_quota_test\resource_quota_test.vcxproj", "{6084F546-5D66-5CB5-63CF-DC960F14B545}" + ProjectSection(myProperties) = preProject + lib = "False" + EndProjectSection + ProjectSection(ProjectDependencies) = postProject + {17BCAFC0-5FDC-4C94-AEB9-95F3E220614B} = {17BCAFC0-5FDC-4C94-AEB9-95F3E220614B} + {29D16885-7228-4C31-81ED-5F9187C7F2A9} = {29D16885-7228-4C31-81ED-5F9187C7F2A9} + {EAB0A629-17A9-44DB-B5FF-E91A721FE037} = {EAB0A629-17A9-44DB-B5FF-E91A721FE037} + {B23D3D1A-9438-4EDA-BEB6-9A0A03D17792} = {B23D3D1A-9438-4EDA-BEB6-9A0A03D17792} + EndProjectSection +EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "secure_channel_create_test", "vcxproj\test\secure_channel_create_test\secure_channel_create_test.vcxproj", "{62B25398-7173-928E-689E-53860B0ACFC4}" ProjectSection(myProperties) = preProject lib = "False" @@ -3538,6 +3549,22 @@ Global {8279AF6C-9584-67F3-1547-B204864FCCA7}.Release-DLL|Win32.Build.0 = Release|Win32 {8279AF6C-9584-67F3-1547-B204864FCCA7}.Release-DLL|x64.ActiveCfg = Release|x64 {8279AF6C-9584-67F3-1547-B204864FCCA7}.Release-DLL|x64.Build.0 = Release|x64 + {6084F546-5D66-5CB5-63CF-DC960F14B545}.Debug|Win32.ActiveCfg = Debug|Win32 + {6084F546-5D66-5CB5-63CF-DC960F14B545}.Debug|x64.ActiveCfg = Debug|x64 + {6084F546-5D66-5CB5-63CF-DC960F14B545}.Release|Win32.ActiveCfg = Release|Win32 + {6084F546-5D66-5CB5-63CF-DC960F14B545}.Release|x64.ActiveCfg = Release|x64 + {6084F546-5D66-5CB5-63CF-DC960F14B545}.Debug|Win32.Build.0 = Debug|Win32 + {6084F546-5D66-5CB5-63CF-DC960F14B545}.Debug|x64.Build.0 = Debug|x64 + {6084F546-5D66-5CB5-63CF-DC960F14B545}.Release|Win32.Build.0 = Release|Win32 + {6084F546-5D66-5CB5-63CF-DC960F14B545}.Release|x64.Build.0 = Release|x64 + {6084F546-5D66-5CB5-63CF-DC960F14B545}.Debug-DLL|Win32.ActiveCfg = Debug|Win32 + {6084F546-5D66-5CB5-63CF-DC960F14B545}.Debug-DLL|Win32.Build.0 = Debug|Win32 + {6084F546-5D66-5CB5-63CF-DC960F14B545}.Debug-DLL|x64.ActiveCfg = Debug|x64 + {6084F546-5D66-5CB5-63CF-DC960F14B545}.Debug-DLL|x64.Build.0 = Debug|x64 + {6084F546-5D66-5CB5-63CF-DC960F14B545}.Release-DLL|Win32.ActiveCfg = Release|Win32 + {6084F546-5D66-5CB5-63CF-DC960F14B545}.Release-DLL|Win32.Build.0 = Release|Win32 + {6084F546-5D66-5CB5-63CF-DC960F14B545}.Release-DLL|x64.ActiveCfg = Release|x64 + {6084F546-5D66-5CB5-63CF-DC960F14B545}.Release-DLL|x64.Build.0 = Release|x64 {62B25398-7173-928E-689E-53860B0ACFC4}.Debug|Win32.ActiveCfg = Debug|Win32 {62B25398-7173-928E-689E-53860B0ACFC4}.Debug|x64.ActiveCfg = Debug|x64 {62B25398-7173-928E-689E-53860B0ACFC4}.Release|Win32.ActiveCfg = Release|Win32 diff --git a/vsprojects/vcxproj/grpc++/grpc++.vcxproj b/vsprojects/vcxproj/grpc++/grpc++.vcxproj index 6bb9a6169dc..e8946043b64 100644 --- a/vsprojects/vcxproj/grpc++/grpc++.vcxproj +++ b/vsprojects/vcxproj/grpc++/grpc++.vcxproj @@ -279,12 +279,7 @@ - - - - - - + @@ -331,9 +326,6 @@ - - - @@ -363,6 +355,7 @@ + @@ -403,6 +396,8 @@ + + @@ -421,6 +416,8 @@ + + diff --git a/vsprojects/vcxproj/grpc++/grpc++.vcxproj.filters b/vsprojects/vcxproj/grpc++/grpc++.vcxproj.filters index 761424c3fa2..e7d6d557f11 100644 --- a/vsprojects/vcxproj/grpc++/grpc++.vcxproj.filters +++ b/vsprojects/vcxproj/grpc++/grpc++.vcxproj.filters @@ -58,6 +58,9 @@ src\cpp\common + + src\cpp\common + src\cpp\common @@ -85,6 +88,9 @@ src\cpp\server + + src\cpp\thread_manager + src\cpp\util @@ -168,23 +174,8 @@ include\grpc++\impl - - include\grpc++\impl - - - include\grpc++\impl - - - include\grpc++\impl - - - include\grpc++\impl - - - include\grpc++\impl - - - include\grpc++\impl + + include\grpc++ include\grpc++\security @@ -324,15 +315,6 @@ include\grpc++\impl\codegen - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - include\grpc++\impl\codegen @@ -416,6 +398,9 @@ src\cpp\server + + src\cpp\thread_manager + @@ -470,6 +455,9 @@ {321b0980-74ad-e8ca-f23b-deffa5d6bb8f} + + {23f9df56-8604-52a0-e6a2-f01b8e68d0e7} + {f842537a-2bf1-1ec3-b495-7d62c64a1c06} diff --git a/vsprojects/vcxproj/grpc++_reflection_codegen/grpc++_reflection_codegen.vcxproj b/vsprojects/vcxproj/grpc++_proto_reflection_desc_db/grpc++_proto_reflection_desc_db.vcxproj similarity index 91% rename from vsprojects/vcxproj/grpc++_reflection_codegen/grpc++_reflection_codegen.vcxproj rename to vsprojects/vcxproj/grpc++_proto_reflection_desc_db/grpc++_proto_reflection_desc_db.vcxproj index d9e10c2d37e..453b483fdea 100644 --- a/vsprojects/vcxproj/grpc++_reflection_codegen/grpc++_reflection_codegen.vcxproj +++ b/vsprojects/vcxproj/grpc++_proto_reflection_desc_db/grpc++_proto_reflection_desc_db.vcxproj @@ -19,7 +19,7 @@ - {C8A925BF-4373-D85D-60AE-96CDCBBF33F2} + {7B95AF96-915A-7132-AE45-9FA37769FACE} true $(SolutionDir)IntDir\$(MSBuildProjectName)\ @@ -57,10 +57,10 @@ - grpc++_reflection_codegen + grpc++_proto_reflection_desc_db - grpc++_reflection_codegen + grpc++_proto_reflection_desc_db @@ -147,6 +147,14 @@ + + + + + + + + @@ -156,6 +164,11 @@ + + + {C187A093-A0FE-489D-A40A-6E33DE0F9FEB} + + diff --git a/vsprojects/vcxproj/grpc++_proto_reflection_desc_db/grpc++_proto_reflection_desc_db.vcxproj.filters b/vsprojects/vcxproj/grpc++_proto_reflection_desc_db/grpc++_proto_reflection_desc_db.vcxproj.filters new file mode 100644 index 00000000000..7e98918491f --- /dev/null +++ b/vsprojects/vcxproj/grpc++_proto_reflection_desc_db/grpc++_proto_reflection_desc_db.vcxproj.filters @@ -0,0 +1,61 @@ + + + + + test\cpp\util + + + src\proto\grpc\reflection\v1alpha + + + + + include\grpc++\impl\codegen + + + + + test\cpp\util + + + + + + {9b233966-149a-36c4-89fb-11d63d8e00bb} + + + {1abcca00-34c5-513a-f372-4ef9b190910a} + + + {0059fdd3-0e35-5500-b8a5-b2e573d7537c} + + + {3f1b0e9e-802e-0535-bc3a-9685c2cf68d1} + + + {b479720c-6a7e-d0ca-bad6-db7cc12c9b0c} + + + {d9aa2326-a033-5a44-a24b-25cdb4a58297} + + + {cdabe038-cb18-dc0f-8afa-0787627ebd55} + + + {3947956e-b4fb-30ce-fc28-da34aec087e7} + + + {79b4cc2b-5f94-0c9f-4754-1197647dd040} + + + {96bd243c-be93-569d-6a83-4a67ab8c1fa3} + + + {1041430f-3c5a-c462-ccc6-adc845814dbe} + + + {c84ddb0b-56a0-0d29-a5c0-6cb1a7a49119} + + + + diff --git a/vsprojects/vcxproj/grpc++_reflection/grpc++_reflection.vcxproj b/vsprojects/vcxproj/grpc++_reflection/grpc++_reflection.vcxproj index 230128180a3..da4c6857764 100644 --- a/vsprojects/vcxproj/grpc++_reflection/grpc++_reflection.vcxproj +++ b/vsprojects/vcxproj/grpc++_reflection/grpc++_reflection.vcxproj @@ -148,58 +148,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -209,10 +157,14 @@ - + - + + + + + diff --git a/vsprojects/vcxproj/grpc++_reflection/grpc++_reflection.vcxproj.filters b/vsprojects/vcxproj/grpc++_reflection/grpc++_reflection.vcxproj.filters index 540e1c6e364..b292e06fd7c 100644 --- a/vsprojects/vcxproj/grpc++_reflection/grpc++_reflection.vcxproj.filters +++ b/vsprojects/vcxproj/grpc++_reflection/grpc++_reflection.vcxproj.filters @@ -7,173 +7,14 @@ src\cpp\ext - - src\cpp\ext - - - src\cpp\ext + + src\proto\grpc\reflection\v1alpha include\grpc++\ext - - include\grpc++\ext - - - include\grpc++\ext - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen\security - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc\impl\codegen - - - include\grpc++\impl\codegen - @@ -185,30 +26,12 @@ {e9441021-f78a-ec84-7efd-1883975feddb} - - {3b19b259-3bf4-c0fa-8e20-ed79acd63ac3} - {c66e66b4-a64e-79bf-40e8-1a1bac124a3d} {8d96203b-d3ce-2164-74a6-06e0ff2b09af} - - {4e57d72c-762f-20b1-bdb9-bc7088ca6fda} - - - {0f0f3943-7a9d-2b03-7eb1-2fbad4199428} - - - {e1b8bc6d-2cd2-1283-868a-dfd64c3dbab8} - - - {7bccc379-84fb-c1aa-19aa-a0cc09ac59ac} - - - {a1f1904b-e820-dd3c-b4b0-14a6e0ff9d19} - {5ec5476e-3d72-e3f9-4f05-3f7c31c13651} @@ -218,6 +41,18 @@ {d0204618-0f6a-dbc6-cf41-ffc04e76075a} + + {728e13e3-db36-9633-3cb9-a74c0f11470d} + + + {b49296ac-bc15-94ec-012b-5f8fe2ce2c1f} + + + {d980f473-6242-4a95-556a-7d4c6d6a2a00} + + + {8c7d8658-ade7-6086-0e04-7e00380ddccf} + diff --git a/vsprojects/vcxproj/grpc++_reflection_codegen/grpc++_reflection_codegen.vcxproj.filters b/vsprojects/vcxproj/grpc++_reflection_codegen/grpc++_reflection_codegen.vcxproj.filters deleted file mode 100644 index 577dcc77d8f..00000000000 --- a/vsprojects/vcxproj/grpc++_reflection_codegen/grpc++_reflection_codegen.vcxproj.filters +++ /dev/null @@ -1,27 +0,0 @@ - - - - - src\proto\grpc\reflection\v1alpha - - - - - - {d6f45d49-92db-00f7-3dd4-e53f5768d80c} - - - {32b951f4-cef1-24a3-ffb9-bb229f0cdd6a} - - - {8fdcb9f3-4d86-2f49-5c15-c92e0e0f4fba} - - - {098a074c-f3de-2840-8009-1a3840af1efc} - - - {219ff371-7d3a-130c-5792-be36514a4e98} - - - - diff --git a/vsprojects/vcxproj/grpc++_test_util/grpc++_test_util.vcxproj b/vsprojects/vcxproj/grpc++_test_util/grpc++_test_util.vcxproj index 17e91995543..d2305b2e255 100644 --- a/vsprojects/vcxproj/grpc++_test_util/grpc++_test_util.vcxproj +++ b/vsprojects/vcxproj/grpc++_test_util/grpc++_test_util.vcxproj @@ -173,9 +173,6 @@ - - - diff --git a/vsprojects/vcxproj/grpc++_test_util/grpc++_test_util.vcxproj.filters b/vsprojects/vcxproj/grpc++_test_util/grpc++_test_util.vcxproj.filters index 25a1752479c..d1aaba70926 100644 --- a/vsprojects/vcxproj/grpc++_test_util/grpc++_test_util.vcxproj.filters +++ b/vsprojects/vcxproj/grpc++_test_util/grpc++_test_util.vcxproj.filters @@ -111,15 +111,6 @@ include\grpc++\impl\codegen - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - include\grpc++\impl\codegen diff --git a/vsprojects/vcxproj/grpc++_unsecure/grpc++_unsecure.vcxproj b/vsprojects/vcxproj/grpc++_unsecure/grpc++_unsecure.vcxproj index 02e65926fe6..17285752422 100644 --- a/vsprojects/vcxproj/grpc++_unsecure/grpc++_unsecure.vcxproj +++ b/vsprojects/vcxproj/grpc++_unsecure/grpc++_unsecure.vcxproj @@ -279,12 +279,7 @@ - - - - - - + @@ -331,9 +326,6 @@ - - - @@ -359,6 +351,7 @@ + @@ -389,6 +382,8 @@ + + @@ -407,6 +402,8 @@ + + diff --git a/vsprojects/vcxproj/grpc++_unsecure/grpc++_unsecure.vcxproj.filters b/vsprojects/vcxproj/grpc++_unsecure/grpc++_unsecure.vcxproj.filters index ff1a0e96446..7fc8ed33fcd 100644 --- a/vsprojects/vcxproj/grpc++_unsecure/grpc++_unsecure.vcxproj.filters +++ b/vsprojects/vcxproj/grpc++_unsecure/grpc++_unsecure.vcxproj.filters @@ -43,6 +43,9 @@ src\cpp\common + + src\cpp\common + src\cpp\common @@ -70,6 +73,9 @@ src\cpp\server + + src\cpp\thread_manager + src\cpp\util @@ -153,23 +159,8 @@ include\grpc++\impl - - include\grpc++\impl - - - include\grpc++\impl - - - include\grpc++\impl - - - include\grpc++\impl - - - include\grpc++\impl - - - include\grpc++\impl + + include\grpc++ include\grpc++\security @@ -309,15 +300,6 @@ include\grpc++\impl\codegen - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - include\grpc++\impl\codegen @@ -389,6 +371,9 @@ src\cpp\server + + src\cpp\thread_manager + @@ -443,6 +428,9 @@ {8a54a279-d14b-4237-0df3-1ffe1ef5a7af} + + {e5b55f25-d99f-b8e5-9981-7da7fa7ba628} + {fb5d9a64-20ca-5119-ed38-04a3cf94923d} diff --git a/vsprojects/vcxproj/grpc/grpc.vcxproj b/vsprojects/vcxproj/grpc/grpc.vcxproj index b9d97fec6c1..d9d0d42d677 100644 --- a/vsprojects/vcxproj/grpc/grpc.vcxproj +++ b/vsprojects/vcxproj/grpc/grpc.vcxproj @@ -337,6 +337,7 @@ + @@ -345,6 +346,7 @@ + @@ -559,6 +561,8 @@ + + diff --git a/vsprojects/vcxproj/grpc/grpc.vcxproj.filters b/vsprojects/vcxproj/grpc/grpc.vcxproj.filters index 86f7edae29f..ab9b76073cf 100644 --- a/vsprojects/vcxproj/grpc/grpc.vcxproj.filters +++ b/vsprojects/vcxproj/grpc/grpc.vcxproj.filters @@ -136,6 +136,9 @@ src\core\lib\iomgr + + src\core\lib\iomgr + src\core\lib\iomgr @@ -830,6 +833,9 @@ src\core\lib\iomgr + + src\core\lib\iomgr + src\core\lib\iomgr @@ -854,6 +860,9 @@ src\core\lib\iomgr + + src\core\lib\iomgr + src\core\lib\iomgr diff --git a/vsprojects/vcxproj/grpc_cli_libs/grpc_cli_libs.vcxproj b/vsprojects/vcxproj/grpc_cli_libs/grpc_cli_libs.vcxproj index 4c61baa506d..c97c7dcb3db 100644 --- a/vsprojects/vcxproj/grpc_cli_libs/grpc_cli_libs.vcxproj +++ b/vsprojects/vcxproj/grpc_cli_libs/grpc_cli_libs.vcxproj @@ -146,13 +146,15 @@ + + + - @@ -164,14 +166,20 @@ - - + + + + + + + + - - {5F575402-3F89-5D1A-6910-9DB8BF5D2BAB} + + {7B95AF96-915A-7132-AE45-9FA37769FACE} {C187A093-A0FE-489D-A40A-6E33DE0F9FEB} diff --git a/vsprojects/vcxproj/grpc_cli_libs/grpc_cli_libs.vcxproj.filters b/vsprojects/vcxproj/grpc_cli_libs/grpc_cli_libs.vcxproj.filters index d4d692766d6..84a401a7bd1 100644 --- a/vsprojects/vcxproj/grpc_cli_libs/grpc_cli_libs.vcxproj.filters +++ b/vsprojects/vcxproj/grpc_cli_libs/grpc_cli_libs.vcxproj.filters @@ -13,12 +13,17 @@ test\cpp\util - - test\cpp\util - test\cpp\util + + src\proto\grpc\reflection\v1alpha + + + + + include\grpc++\impl\codegen + @@ -36,15 +41,39 @@ test\cpp\util - - test\cpp\util - test\cpp\util + + {09004fab-571d-4499-ea07-ab14a367b0e6} + + + {17074550-63b5-b955-9a30-33f983c6933a} + + + {9d5cca3a-e3da-b197-ba07-8ef7649de092} + + + {12d6b95a-4072-e05e-8de7-79b0c2f7329f} + + + {5cc1b6f3-ef01-62ac-9b0e-1fd776f42182} + + + {86bd3e99-8380-85fd-f297-1ac2f018ed51} + + + {10c2568e-5695-1c21-6c51-172889d406f8} + + + {5213881a-59f9-2d2e-43aa-1433dc6f70af} + + + {8a66b2e3-477b-66e2-fba8-6987c6381367} + {16a32a9f-93aa-5812-5a5e-be659aaa76aa} diff --git a/vsprojects/vcxproj/grpc_test_util/grpc_test_util.vcxproj b/vsprojects/vcxproj/grpc_test_util/grpc_test_util.vcxproj index 35ace6eabbd..39c144d992f 100644 --- a/vsprojects/vcxproj/grpc_test_util/grpc_test_util.vcxproj +++ b/vsprojects/vcxproj/grpc_test_util/grpc_test_util.vcxproj @@ -230,6 +230,7 @@ + @@ -238,6 +239,7 @@ + @@ -410,6 +412,8 @@ + + diff --git a/vsprojects/vcxproj/grpc_test_util/grpc_test_util.vcxproj.filters b/vsprojects/vcxproj/grpc_test_util/grpc_test_util.vcxproj.filters index 4b104aeb9bf..0fbfc3acd37 100644 --- a/vsprojects/vcxproj/grpc_test_util/grpc_test_util.vcxproj.filters +++ b/vsprojects/vcxproj/grpc_test_util/grpc_test_util.vcxproj.filters @@ -193,6 +193,9 @@ src\core\lib\iomgr + + src\core\lib\iomgr + src\core\lib\iomgr @@ -626,6 +629,9 @@ src\core\lib\iomgr + + src\core\lib\iomgr + src\core\lib\iomgr @@ -650,6 +656,9 @@ src\core\lib\iomgr + + src\core\lib\iomgr + src\core\lib\iomgr diff --git a/vsprojects/vcxproj/grpc_unsecure/grpc_unsecure.vcxproj b/vsprojects/vcxproj/grpc_unsecure/grpc_unsecure.vcxproj index 377bbf9bbd5..87e3921ff96 100644 --- a/vsprojects/vcxproj/grpc_unsecure/grpc_unsecure.vcxproj +++ b/vsprojects/vcxproj/grpc_unsecure/grpc_unsecure.vcxproj @@ -327,6 +327,7 @@ + @@ -335,6 +336,7 @@ + @@ -527,6 +529,8 @@ + + diff --git a/vsprojects/vcxproj/grpc_unsecure/grpc_unsecure.vcxproj.filters b/vsprojects/vcxproj/grpc_unsecure/grpc_unsecure.vcxproj.filters index 9171f823775..1e719226faf 100644 --- a/vsprojects/vcxproj/grpc_unsecure/grpc_unsecure.vcxproj.filters +++ b/vsprojects/vcxproj/grpc_unsecure/grpc_unsecure.vcxproj.filters @@ -139,6 +139,9 @@ src\core\lib\iomgr + + src\core\lib\iomgr + src\core\lib\iomgr @@ -743,6 +746,9 @@ src\core\lib\iomgr + + src\core\lib\iomgr + src\core\lib\iomgr @@ -767,6 +773,9 @@ src\core\lib\iomgr + + src\core\lib\iomgr + src\core\lib\iomgr diff --git a/vsprojects/vcxproj/test/codegen_test_full/codegen_test_full.vcxproj b/vsprojects/vcxproj/test/codegen_test_full/codegen_test_full.vcxproj index 2d75735728b..a2b2a1dfa0f 100644 --- a/vsprojects/vcxproj/test/codegen_test_full/codegen_test_full.vcxproj +++ b/vsprojects/vcxproj/test/codegen_test_full/codegen_test_full.vcxproj @@ -186,9 +186,6 @@ - - - diff --git a/vsprojects/vcxproj/test/codegen_test_full/codegen_test_full.vcxproj.filters b/vsprojects/vcxproj/test/codegen_test_full/codegen_test_full.vcxproj.filters index dda79675fbd..94b6c2530ef 100644 --- a/vsprojects/vcxproj/test/codegen_test_full/codegen_test_full.vcxproj.filters +++ b/vsprojects/vcxproj/test/codegen_test_full/codegen_test_full.vcxproj.filters @@ -99,15 +99,6 @@ include\grpc++\impl\codegen - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - include\grpc++\impl\codegen diff --git a/vsprojects/vcxproj/test/codegen_test_minimal/codegen_test_minimal.vcxproj b/vsprojects/vcxproj/test/codegen_test_minimal/codegen_test_minimal.vcxproj index 270c2a3a062..1a3c1579837 100644 --- a/vsprojects/vcxproj/test/codegen_test_minimal/codegen_test_minimal.vcxproj +++ b/vsprojects/vcxproj/test/codegen_test_minimal/codegen_test_minimal.vcxproj @@ -186,9 +186,6 @@ - - - diff --git a/vsprojects/vcxproj/test/codegen_test_minimal/codegen_test_minimal.vcxproj.filters b/vsprojects/vcxproj/test/codegen_test_minimal/codegen_test_minimal.vcxproj.filters index dc5e321649b..1f4b60ca4d9 100644 --- a/vsprojects/vcxproj/test/codegen_test_minimal/codegen_test_minimal.vcxproj.filters +++ b/vsprojects/vcxproj/test/codegen_test_minimal/codegen_test_minimal.vcxproj.filters @@ -102,15 +102,6 @@ include\grpc++\impl\codegen - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - include\grpc++\impl\codegen diff --git a/vsprojects/vcxproj/test/end2end/tests/end2end_nosec_tests/end2end_nosec_tests.vcxproj b/vsprojects/vcxproj/test/end2end/tests/end2end_nosec_tests/end2end_nosec_tests.vcxproj index d6ec36962fc..a47c40f0f73 100644 --- a/vsprojects/vcxproj/test/end2end/tests/end2end_nosec_tests/end2end_nosec_tests.vcxproj +++ b/vsprojects/vcxproj/test/end2end/tests/end2end_nosec_tests/end2end_nosec_tests.vcxproj @@ -221,6 +221,8 @@ + + diff --git a/vsprojects/vcxproj/test/end2end/tests/end2end_nosec_tests/end2end_nosec_tests.vcxproj.filters b/vsprojects/vcxproj/test/end2end/tests/end2end_nosec_tests/end2end_nosec_tests.vcxproj.filters index a6c24a895a4..71cf6838fe2 100644 --- a/vsprojects/vcxproj/test/end2end/tests/end2end_nosec_tests/end2end_nosec_tests.vcxproj.filters +++ b/vsprojects/vcxproj/test/end2end/tests/end2end_nosec_tests/end2end_nosec_tests.vcxproj.filters @@ -106,6 +106,9 @@ test\core\end2end\tests + + test\core\end2end\tests + test\core\end2end\tests diff --git a/vsprojects/vcxproj/test/end2end/tests/end2end_tests/end2end_tests.vcxproj b/vsprojects/vcxproj/test/end2end/tests/end2end_tests/end2end_tests.vcxproj index 085b14700c0..68ff5f1ebd8 100644 --- a/vsprojects/vcxproj/test/end2end/tests/end2end_tests/end2end_tests.vcxproj +++ b/vsprojects/vcxproj/test/end2end/tests/end2end_tests/end2end_tests.vcxproj @@ -223,6 +223,8 @@ + + diff --git a/vsprojects/vcxproj/test/end2end/tests/end2end_tests/end2end_tests.vcxproj.filters b/vsprojects/vcxproj/test/end2end/tests/end2end_tests/end2end_tests.vcxproj.filters index d224a9ced96..7a620f61a54 100644 --- a/vsprojects/vcxproj/test/end2end/tests/end2end_tests/end2end_tests.vcxproj.filters +++ b/vsprojects/vcxproj/test/end2end/tests/end2end_tests/end2end_tests.vcxproj.filters @@ -109,6 +109,9 @@ test\core\end2end\tests + + test\core\end2end\tests + test\core\end2end\tests diff --git a/vsprojects/vcxproj/test/grpc_cli/grpc_cli.vcxproj b/vsprojects/vcxproj/test/grpc_cli/grpc_cli.vcxproj index 78a0a63b5d7..fbb1bc8ab22 100644 --- a/vsprojects/vcxproj/test/grpc_cli/grpc_cli.vcxproj +++ b/vsprojects/vcxproj/test/grpc_cli/grpc_cli.vcxproj @@ -167,8 +167,8 @@ {86E35862-43E8-F59E-F906-AFE0348AD3D2} - - {5F575402-3F89-5D1A-6910-9DB8BF5D2BAB} + + {7B95AF96-915A-7132-AE45-9FA37769FACE} {C187A093-A0FE-489D-A40A-6E33DE0F9FEB} diff --git a/vsprojects/vcxproj/test/grpc_tool_test/grpc_tool_test.vcxproj b/vsprojects/vcxproj/test/grpc_tool_test/grpc_tool_test.vcxproj index bdf310db1bd..1e3cc3ca043 100644 --- a/vsprojects/vcxproj/test/grpc_tool_test/grpc_tool_test.vcxproj +++ b/vsprojects/vcxproj/test/grpc_tool_test/grpc_tool_test.vcxproj @@ -187,9 +187,6 @@ - - - @@ -211,9 +208,6 @@ - - - @@ -233,16 +227,20 @@ - - {86E35862-43E8-F59E-F906-AFE0348AD3D2} + + {7B95AF96-915A-7132-AE45-9FA37769FACE} + {5F575402-3F89-5D1A-6910-9DB8BF5D2BAB} + + {0BE77741-552A-929B-A497-4EF7ECE17A64} + {17BCAFC0-5FDC-4C94-AEB9-95F3E220614B} diff --git a/vsprojects/vcxproj/test/grpc_tool_test/grpc_tool_test.vcxproj.filters b/vsprojects/vcxproj/test/grpc_tool_test/grpc_tool_test.vcxproj.filters index cd341e9eb1f..1c308c58817 100644 --- a/vsprojects/vcxproj/test/grpc_tool_test/grpc_tool_test.vcxproj.filters +++ b/vsprojects/vcxproj/test/grpc_tool_test/grpc_tool_test.vcxproj.filters @@ -10,9 +10,6 @@ test\cpp\util - - test\cpp\util - @@ -96,15 +93,6 @@ include\grpc++\impl\codegen - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - - - include\grpc++\impl\codegen - include\grpc++\impl\codegen @@ -166,11 +154,6 @@ include\grpc++\impl\codegen - - - test\cpp\util - - diff --git a/vsprojects/vcxproj/test/proto_server_reflection_test/proto_server_reflection_test.vcxproj b/vsprojects/vcxproj/test/proto_server_reflection_test/proto_server_reflection_test.vcxproj index 27fc168946b..d3cd3f1e042 100644 --- a/vsprojects/vcxproj/test/proto_server_reflection_test/proto_server_reflection_test.vcxproj +++ b/vsprojects/vcxproj/test/proto_server_reflection_test/proto_server_reflection_test.vcxproj @@ -159,16 +159,14 @@ - - - - - + + {7B95AF96-915A-7132-AE45-9FA37769FACE} + {5F575402-3F89-5D1A-6910-9DB8BF5D2BAB} diff --git a/vsprojects/vcxproj/test/proto_server_reflection_test/proto_server_reflection_test.vcxproj.filters b/vsprojects/vcxproj/test/proto_server_reflection_test/proto_server_reflection_test.vcxproj.filters index 6d6e5c1f32c..ae0b05aa730 100644 --- a/vsprojects/vcxproj/test/proto_server_reflection_test/proto_server_reflection_test.vcxproj.filters +++ b/vsprojects/vcxproj/test/proto_server_reflection_test/proto_server_reflection_test.vcxproj.filters @@ -4,14 +4,6 @@ test\cpp\end2end - - test\cpp\util - - - - - test\cpp\util - @@ -24,9 +16,6 @@ {130f224c-89a5-54ea-7045-b54b4188c52b} - - {aae81aad-5563-fceb-1461-10fdec84c5b0} - diff --git a/vsprojects/vcxproj/test/resource_quota_test/resource_quota_test.vcxproj b/vsprojects/vcxproj/test/resource_quota_test/resource_quota_test.vcxproj new file mode 100644 index 00000000000..389340e9a03 --- /dev/null +++ b/vsprojects/vcxproj/test/resource_quota_test/resource_quota_test.vcxproj @@ -0,0 +1,199 @@ + + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {6084F546-5D66-5CB5-63CF-DC960F14B545} + true + $(SolutionDir)IntDir\$(MSBuildProjectName)\ + + + + v100 + + + v110 + + + v120 + + + v140 + + + Application + true + Unicode + + + Application + false + true + Unicode + + + + + + + + + + + + + + resource_quota_test + static + Debug + static + Debug + + + resource_quota_test + static + Release + static + Release + + + + NotUsing + Level3 + Disabled + WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebug + true + None + false + + + Console + true + false + + + + + + NotUsing + Level3 + Disabled + WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebug + true + None + false + + + Console + true + false + + + + + + NotUsing + Level3 + MaxSpeed + WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) + true + true + true + MultiThreaded + true + None + false + + + Console + true + false + true + true + + + + + + NotUsing + Level3 + MaxSpeed + WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) + true + true + true + MultiThreaded + true + None + false + + + Console + true + false + true + true + + + + + + + + + + {17BCAFC0-5FDC-4C94-AEB9-95F3E220614B} + + + {29D16885-7228-4C31-81ED-5F9187C7F2A9} + + + {EAB0A629-17A9-44DB-B5FF-E91A721FE037} + + + {B23D3D1A-9438-4EDA-BEB6-9A0A03D17792} + + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + + + + diff --git a/vsprojects/vcxproj/test/resource_quota_test/resource_quota_test.vcxproj.filters b/vsprojects/vcxproj/test/resource_quota_test/resource_quota_test.vcxproj.filters new file mode 100644 index 00000000000..d76c8aed5d5 --- /dev/null +++ b/vsprojects/vcxproj/test/resource_quota_test/resource_quota_test.vcxproj.filters @@ -0,0 +1,21 @@ + + + + + test\core\iomgr + + + + + + {06783e32-dbf0-7e7c-7b50-12b278f9cc12} + + + {c4f432b6-577b-e3ed-fec9-a915af5ebbd5} + + + {fcc82d68-ffb2-0843-83aa-175006c43aeb} + + + + diff --git a/vsprojects/vcxproj/test/round_robin_end2end_test/round_robin_end2end_test.vcxproj b/vsprojects/vcxproj/test/round_robin_end2end_test/round_robin_end2end_test.vcxproj new file mode 100644 index 00000000000..55e16f188dc --- /dev/null +++ b/vsprojects/vcxproj/test/round_robin_end2end_test/round_robin_end2end_test.vcxproj @@ -0,0 +1,207 @@ + + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {54B15DF6-42BA-5347-C9B8-2D7F1F2921C6} + true + $(SolutionDir)IntDir\$(MSBuildProjectName)\ + + + + v100 + + + v110 + + + v120 + + + v140 + + + Application + true + Unicode + + + Application + false + true + Unicode + + + + + + + + + + + + + + + + round_robin_end2end_test + static + Debug + static + Debug + + + round_robin_end2end_test + static + Release + static + Release + + + + NotUsing + Level3 + Disabled + WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebug + true + None + false + + + Console + true + false + + + + + + NotUsing + Level3 + Disabled + WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebug + true + None + false + + + Console + true + false + + + + + + NotUsing + Level3 + MaxSpeed + WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) + true + true + true + MultiThreaded + true + None + false + + + Console + true + false + true + true + + + + + + NotUsing + Level3 + MaxSpeed + WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) + true + true + true + MultiThreaded + true + None + false + + + Console + true + false + true + true + + + + + + + + + + {0BE77741-552A-929B-A497-4EF7ECE17A64} + + + {17BCAFC0-5FDC-4C94-AEB9-95F3E220614B} + + + {C187A093-A0FE-489D-A40A-6E33DE0F9FEB} + + + {29D16885-7228-4C31-81ED-5F9187C7F2A9} + + + {EAB0A629-17A9-44DB-B5FF-E91A721FE037} + + + {B23D3D1A-9438-4EDA-BEB6-9A0A03D17792} + + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + + + + diff --git a/vsprojects/vcxproj/test/round_robin_end2end_test/round_robin_end2end_test.vcxproj.filters b/vsprojects/vcxproj/test/round_robin_end2end_test/round_robin_end2end_test.vcxproj.filters new file mode 100644 index 00000000000..95a149953fc --- /dev/null +++ b/vsprojects/vcxproj/test/round_robin_end2end_test/round_robin_end2end_test.vcxproj.filters @@ -0,0 +1,21 @@ + + + + + test\cpp\end2end + + + + + + {e151f47d-6563-5ef9-fae6-70708f9f8ee6} + + + {07958594-fd93-28f7-9388-c67c952701b8} + + + {7596a0dd-caa4-b365-a59f-f7ffef38b10d} + + + + diff --git a/vsprojects/vcxproj/test/thread_manager_test/thread_manager_test.vcxproj b/vsprojects/vcxproj/test/thread_manager_test/thread_manager_test.vcxproj new file mode 100644 index 00000000000..2c35a03a021 --- /dev/null +++ b/vsprojects/vcxproj/test/thread_manager_test/thread_manager_test.vcxproj @@ -0,0 +1,201 @@ + + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {08C611E4-7F87-73BE-76CE-C158A4CC05A3} + true + $(SolutionDir)IntDir\$(MSBuildProjectName)\ + + + + v100 + + + v110 + + + v120 + + + v140 + + + Application + true + Unicode + + + Application + false + true + Unicode + + + + + + + + + + + + + + + + thread_manager_test + static + Debug + static + Debug + + + thread_manager_test + static + Release + static + Release + + + + NotUsing + Level3 + Disabled + WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebug + true + None + false + + + Console + true + false + + + + + + NotUsing + Level3 + Disabled + WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) + true + MultiThreadedDebug + true + None + false + + + Console + true + false + + + + + + NotUsing + Level3 + MaxSpeed + WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) + true + true + true + MultiThreaded + true + None + false + + + Console + true + false + true + true + + + + + + NotUsing + Level3 + MaxSpeed + WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) + true + true + true + MultiThreaded + true + None + false + + + Console + true + false + true + true + + + + + + + + + + {C187A093-A0FE-489D-A40A-6E33DE0F9FEB} + + + {29D16885-7228-4C31-81ED-5F9187C7F2A9} + + + {B23D3D1A-9438-4EDA-BEB6-9A0A03D17792} + + + {3F7D093D-11F9-C4BC-BEB7-18EB28E3F290} + + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + + + + diff --git a/vsprojects/vcxproj/test/thread_manager_test/thread_manager_test.vcxproj.filters b/vsprojects/vcxproj/test/thread_manager_test/thread_manager_test.vcxproj.filters new file mode 100644 index 00000000000..e1741f8316c --- /dev/null +++ b/vsprojects/vcxproj/test/thread_manager_test/thread_manager_test.vcxproj.filters @@ -0,0 +1,21 @@ + + + + + test\cpp\thread_manager + + + + + + {e9e471cd-7f7e-9abc-af13-ec58851849ac} + + + {b350f72c-af76-7272-4342-1b0fc7a458ee} + + + {6b09ea8d-fbc6-e6fe-f884-b3d3dfcbfc12} + + + +